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 <stdlib.h>
48 #include <string.h>
50 #include <pthread.h>
52 /*
53 * private variables
54 */
56 static pthread_key_t conn_ctx_key;
57 static bool conn_ctx_key_initialized = 0;
59 /*
60 * private types
61 */
63 /* name of connection objects */
64 #define CONN_FD_PREFIX "conn#"
65 #define CONN_FD_PLACEHOLDER "XXXXXXX"
67 static ssize_t
68 conn_read(sdb_conn_t *conn, size_t len)
69 {
70 return sdb_strbuf_read(conn->buf, conn->fd, len);
71 } /* conn_read */
73 static ssize_t
74 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
75 {
76 return sdb_write(conn->fd, len, buf);
77 } /* conn_write */
79 static int
80 connection_init(sdb_object_t *obj, va_list ap)
81 {
82 sdb_conn_t *conn;
83 int sock_fd;
84 int sock_fl;
86 assert(obj);
87 conn = CONN(obj);
89 sock_fd = va_arg(ap, int);
91 conn->buf = sdb_strbuf_create(/* size = */ 128);
92 if (! conn->buf) {
93 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
94 "for a new connection");
95 return -1;
96 }
97 conn->errbuf = sdb_strbuf_create(0);
98 if (! conn->errbuf) {
99 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
100 "for a new connection");
101 return -1;
102 }
104 conn->client_addr_len = sizeof(conn->client_addr);
105 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
106 &conn->client_addr_len);
108 if (conn->fd < 0) {
109 char buf[1024];
110 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
111 "connection: %s", sdb_strerror(errno,
112 buf, sizeof(buf)));
113 return -1;
114 }
116 /* update the object name */
117 snprintf(obj->name + strlen(CONN_FD_PREFIX),
118 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
120 /* defaults */
121 conn->read = conn_read;
122 conn->write = conn_write;
123 conn->finish = NULL;
124 conn->session = NULL;
126 if (conn->client_addr.ss_family != AF_UNIX) {
127 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
128 "unexpected family type %d", conn->client_addr.ss_family);
129 return -1;
130 }
132 sock_fl = fcntl(conn->fd, F_GETFL);
133 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
134 char buf[1024];
135 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
136 "to non-blocking mode: %s", conn->fd,
137 sdb_strerror(errno, buf, sizeof(buf)));
138 return -1;
139 }
141 conn->username = NULL;
142 conn->ready = 0;
144 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
145 conn->fd);
147 conn->cmd = SDB_CONNECTION_IDLE;
148 conn->cmd_len = 0;
149 conn->skip_len = 0;
150 return 0;
151 } /* connection_init */
153 static void
154 connection_destroy(sdb_object_t *obj)
155 {
156 sdb_conn_t *conn;
157 size_t len;
159 assert(obj);
160 conn = CONN(obj);
162 conn->ready = 0;
164 if (conn->finish)
165 conn->finish(conn);
166 conn->finish = NULL;
168 if (conn->buf) {
169 len = sdb_strbuf_len(conn->buf);
170 if (len)
171 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
172 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
173 }
175 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
176 sdb_connection_close(conn);
178 if (conn->username)
179 free(conn->username);
180 conn->username = NULL;
182 sdb_strbuf_destroy(conn->buf);
183 conn->buf = NULL;
184 sdb_strbuf_destroy(conn->errbuf);
185 conn->errbuf = NULL;
186 } /* connection_destroy */
188 static sdb_type_t connection_type = {
189 /* size = */ sizeof(sdb_conn_t),
190 /* init = */ connection_init,
191 /* destroy = */ connection_destroy,
192 };
194 /*
195 * private helper functions
196 */
198 static void
199 sdb_conn_ctx_destructor(void *c)
200 {
201 sdb_object_t *conn = c;
203 if (! conn)
204 return;
205 sdb_object_deref(conn);
206 } /* sdb_conn_ctx_destructor */
208 static void
209 sdb_conn_ctx_init(void)
210 {
211 if (conn_ctx_key_initialized)
212 return;
214 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
215 conn_ctx_key_initialized = 1;
216 } /* sdb_conn_ctx_init */
218 static void
219 sdb_conn_set_ctx(sdb_conn_t *conn)
220 {
221 sdb_conn_t *old;
223 sdb_conn_ctx_init();
225 old = pthread_getspecific(conn_ctx_key);
226 if (old)
227 sdb_object_deref(SDB_OBJ(old));
228 if (conn)
229 sdb_object_ref(SDB_OBJ(conn));
230 pthread_setspecific(conn_ctx_key, conn);
231 } /* sdb_conn_set_ctx */
233 static sdb_conn_t *
234 sdb_conn_get_ctx(void)
235 {
236 if (! conn_ctx_key_initialized)
237 return NULL;
238 return pthread_getspecific(conn_ctx_key);
239 } /* sdb_conn_get_ctx */
241 /*
242 * connection handler functions
243 */
245 /*
246 * connection_log:
247 * Send a log message originating from the current thread to the client.
248 */
249 static int
250 connection_log(int prio, const char *msg,
251 sdb_object_t __attribute__((unused)) *user_data)
252 {
253 uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
254 uint32_t p = htonl((uint32_t)prio);
255 char tmp[len + 1];
257 sdb_conn_t *conn;
259 conn = sdb_conn_get_ctx();
260 /* no connection associated to this thread
261 * or startup not done yet => don't leak any information */
262 if ((! conn) || (! conn->ready))
263 return 0;
265 /* XXX: make the log-level configurable by the client at runtime */
266 if (prio >= SDB_LOG_DEBUG)
267 return 0;
269 memcpy(tmp, &p, sizeof(p));
270 strcpy(tmp + sizeof(p), msg);
272 if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
273 return -1;
274 return 0;
275 } /* connection_log */
277 static int
278 command_handle(sdb_conn_t *conn)
279 {
280 int status = -1;
282 assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
283 assert(! conn->skip_len);
285 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
286 conn->cmd, conn->cmd_len);
288 if (conn->cmd == SDB_CONNECTION_PING)
289 status = sdb_connection_ping(conn);
290 else if (conn->cmd == SDB_CONNECTION_STARTUP)
291 status = sdb_fe_session_start(conn);
292 else if (conn->cmd == SDB_CONNECTION_QUERY)
293 status = sdb_fe_query(conn);
294 else if (conn->cmd == SDB_CONNECTION_FETCH)
295 status = sdb_fe_fetch(conn);
296 else if (conn->cmd == SDB_CONNECTION_LIST)
297 status = sdb_fe_list(conn);
298 else if (conn->cmd == SDB_CONNECTION_LOOKUP)
299 status = sdb_fe_lookup(conn);
300 else if (conn->cmd == SDB_CONNECTION_STORE)
301 status = sdb_fe_store(conn);
302 else {
303 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
304 conn->cmd);
305 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
306 status = -1;
307 }
309 if (status) {
310 if (! sdb_strbuf_len(conn->errbuf))
311 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
312 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
313 (uint32_t)sdb_strbuf_len(conn->errbuf),
314 sdb_strbuf_string(conn->errbuf));
315 }
316 return status;
317 } /* command_handle */
319 /* initialize the connection state information */
320 static int
321 command_init(sdb_conn_t *conn)
322 {
323 const char *errmsg = NULL;
325 assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
327 if (conn->skip_len)
328 return -1;
330 /* reset */
331 sdb_strbuf_clear(conn->errbuf);
333 if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
334 &conn->cmd, &conn->cmd_len) < 0)
335 return -1;
336 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
338 if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
339 errmsg = "Authentication required";
340 else if (conn->cmd == SDB_CONNECTION_IDLE)
341 errmsg = "Invalid command 0";
343 if (errmsg) {
344 size_t len = sdb_strbuf_len(conn->buf);
346 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
347 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
348 (uint32_t)strlen(errmsg), errmsg);
349 conn->skip_len += conn->cmd_len;
350 conn->cmd = SDB_CONNECTION_IDLE;
351 conn->cmd_len = 0;
353 if (len > conn->skip_len)
354 len = conn->skip_len;
355 sdb_strbuf_skip(conn->buf, 0, len);
356 conn->skip_len -= len;
357 /* connection_read will handle anything else */
358 }
359 return 0;
360 } /* command_init */
362 /* returns negative value on error, 0 on EOF, number of octets else */
363 static ssize_t
364 connection_read(sdb_conn_t *conn)
365 {
366 ssize_t n = 0;
368 if ((! conn) || (conn->fd < 0))
369 return -1;
371 while (42) {
372 ssize_t status;
374 errno = 0;
375 status = conn->read(conn, 1024);
376 if (status < 0) {
377 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
378 break;
380 sdb_connection_close(conn);
381 return (int)status;
382 }
383 else if (! status) /* EOF */
384 break;
386 if (conn->skip_len) {
387 size_t len = (size_t)status < conn->skip_len
388 ? (size_t)status : conn->skip_len;
389 sdb_strbuf_skip(conn->buf, 0, len);
390 conn->skip_len -= len;
391 }
393 n += status;
395 /* give the main loop a chance to execute commands (and free up buffer
396 * space) on large amounts of incoming traffic */
397 if (n > 1024 * 1024)
398 break;
399 }
401 return n;
402 } /* connection_read */
404 /*
405 * public API
406 */
408 int
409 sdb_connection_enable_logging(void)
410 {
411 return sdb_plugin_register_log("connection-logger", connection_log,
412 /* user_data = */ NULL);
413 } /* sdb_connection_enable_logging */
415 sdb_conn_t *
416 sdb_connection_accept(int fd)
417 {
418 if (fd < 0)
419 return NULL;
421 /* the placeholder will be replaced with the accepted file
422 * descriptor when initializing the object */
423 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
424 connection_type, fd));
425 } /* sdb_connection_create */
427 void
428 sdb_connection_close(sdb_conn_t *conn)
429 {
430 if (! conn)
431 return;
433 if (conn->finish)
434 conn->finish(conn);
435 conn->finish = NULL;
437 /* close the connection even if someone else still references it */
438 if (conn->fd >= 0)
439 close(conn->fd);
440 conn->fd = -1;
441 } /* sdb_connection_close */
443 ssize_t
444 sdb_connection_handle(sdb_conn_t *conn)
445 {
446 ssize_t n = 0;
448 sdb_conn_set_ctx(conn);
450 while (42) {
451 ssize_t status = connection_read(conn);
453 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
454 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
455 command_init(conn);
456 if ((conn->cmd != SDB_CONNECTION_IDLE)
457 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
458 command_handle(conn);
460 /* remove the command from the buffer */
461 if (conn->cmd_len)
462 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
463 conn->cmd = SDB_CONNECTION_IDLE;
464 conn->cmd_len = 0;
465 }
467 if (status <= 0)
468 break;
470 n += status;
471 }
473 sdb_conn_set_ctx(NULL);
474 return n;
475 } /* sdb_connection_handle */
477 ssize_t
478 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
479 uint32_t msg_len, const char *msg)
480 {
481 char buf[2 * sizeof(uint32_t) + msg_len];
482 ssize_t status;
484 if ((! conn) || (conn->fd < 0))
485 return -1;
486 if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
487 return -1;
489 status = conn->write(conn, buf, sizeof(buf));
490 if (status < 0) {
491 char errbuf[1024];
493 /* tell other code that there was a problem and, more importantly,
494 * make sure we don't try to send further logs to the connection */
495 sdb_connection_close(conn);
496 conn->ready = 0;
498 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
499 "(code: %u, len: %u) to client: %s", code, msg_len,
500 sdb_strerror(errno, errbuf, sizeof(errbuf)));
501 }
502 return status;
503 } /* sdb_connection_send */
505 int
506 sdb_connection_ping(sdb_conn_t *conn)
507 {
508 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
509 return -1;
511 /* we're alive */
512 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
513 return 0;
514 } /* sdb_connection_ping */
516 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */