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 #include "sysdb.h"
29 #include "core/object.h"
30 #include "core/plugin.h"
31 #include "frontend/connection-private.h"
32 #include "frontend/parser.h"
33 #include "utils/error.h"
34 #include "utils/strbuf.h"
35 #include "utils/proto.h"
37 #include <assert.h>
38 #include <errno.h>
40 #include <arpa/inet.h>
41 #include <fcntl.h>
43 #include <stdlib.h>
44 #include <string.h>
46 #include <pthread.h>
48 /*
49 * private variables
50 */
52 static pthread_key_t conn_ctx_key;
53 static _Bool conn_ctx_key_initialized = 0;
55 /*
56 * private types
57 */
59 /* name of connection objects */
60 #define CONN_FD_PREFIX "conn#"
61 #define CONN_FD_PLACEHOLDER "XXXXXXX"
63 static int
64 connection_init(sdb_object_t *obj, va_list ap)
65 {
66 sdb_conn_t *conn;
67 int sock_fd;
68 int sock_fl;
70 assert(obj);
71 conn = CONN(obj);
73 sock_fd = va_arg(ap, int);
75 conn->buf = sdb_strbuf_create(/* size = */ 128);
76 if (! conn->buf) {
77 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
78 "for a new connection");
79 return -1;
80 }
81 conn->errbuf = sdb_strbuf_create(0);
82 if (! conn->errbuf) {
83 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
84 "for a new connection");
85 return -1;
86 }
88 conn->client_addr_len = sizeof(conn->client_addr);
89 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
90 &conn->client_addr_len);
92 if (conn->fd < 0) {
93 char buf[1024];
94 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
95 "connection: %s", sdb_strerror(errno,
96 buf, sizeof(buf)));
97 return -1;
98 }
100 if (conn->client_addr.ss_family != AF_UNIX) {
101 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
102 "unexpected family type %d", conn->client_addr.ss_family);
103 return -1;
104 }
106 sock_fl = fcntl(conn->fd, F_GETFL);
107 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
108 char buf[1024];
109 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
110 "to non-blocking mode: %s", conn->fd,
111 sdb_strerror(errno, buf, sizeof(buf)));
112 return -1;
113 }
115 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
116 conn->fd);
118 conn->cmd = CONNECTION_IDLE;
119 conn->cmd_len = 0;
121 /* update the object name */
122 snprintf(obj->name + strlen(CONN_FD_PREFIX),
123 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
124 return 0;
125 } /* connection_init */
127 static void
128 connection_destroy(sdb_object_t *obj)
129 {
130 sdb_conn_t *conn;
131 size_t len;
133 assert(obj);
134 conn = CONN(obj);
136 if (conn->buf) {
137 len = sdb_strbuf_len(conn->buf);
138 if (len)
139 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
140 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
141 }
143 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
144 if (conn->fd >= 0)
145 close(conn->fd);
146 conn->fd = -1;
148 sdb_strbuf_destroy(conn->buf);
149 conn->buf = NULL;
150 sdb_strbuf_destroy(conn->errbuf);
151 conn->errbuf = NULL;
152 } /* connection_destroy */
154 static sdb_type_t connection_type = {
155 /* size = */ sizeof(sdb_conn_t),
156 /* init = */ connection_init,
157 /* destroy = */ connection_destroy,
158 };
160 /*
161 * private helper functions
162 */
164 static void
165 sdb_conn_ctx_destructor(void *c)
166 {
167 sdb_object_t *conn = c;
169 if (! conn)
170 return;
171 sdb_object_deref(conn);
172 } /* sdb_conn_ctx_destructor */
174 static void
175 sdb_conn_ctx_init(void)
176 {
177 if (conn_ctx_key_initialized)
178 return;
180 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
181 conn_ctx_key_initialized = 1;
182 } /* sdb_conn_ctx_init */
184 static void
185 sdb_conn_set_ctx(sdb_conn_t *conn)
186 {
187 sdb_conn_t *old;
189 sdb_conn_ctx_init();
191 old = pthread_getspecific(conn_ctx_key);
192 if (old)
193 sdb_object_deref(SDB_OBJ(old));
194 if (conn)
195 sdb_object_ref(SDB_OBJ(conn));
196 pthread_setspecific(conn_ctx_key, conn);
197 } /* sdb_conn_set_ctx */
199 static sdb_conn_t *
200 sdb_conn_get_ctx(void)
201 {
202 if (! conn_ctx_key_initialized)
203 return NULL;
204 return pthread_getspecific(conn_ctx_key);
205 } /* sdb_conn_get_ctx */
207 /*
208 * connection handler functions
209 */
211 /*
212 * connection_log:
213 * Send a log message originating from the current thread to the client.
214 */
215 static int
216 connection_log(int prio, const char *msg,
217 sdb_object_t __attribute__((unused)) *user_data)
218 {
219 sdb_conn_t *conn;
221 conn = sdb_conn_get_ctx();
222 /* no connection associated to this thread
223 * or user not authenticated yet => don't leak any information */
224 if ((! conn) || (! conn->username))
225 return 0;
227 /* XXX: make the log-level configurable by the client at runtime */
228 if (prio >= SDB_LOG_DEBUG)
229 return 0;
231 /* TODO: Use CONNECTION_LOG_<prio>? */
232 if (sdb_connection_send(conn, CONNECTION_LOG,
233 (uint32_t)strlen(msg), msg) < 0)
234 return -1;
235 return 0;
236 } /* connection_log */
238 static uint32_t
239 connection_get_int32(sdb_conn_t *conn, size_t offset)
240 {
241 const char *data;
242 uint32_t n;
244 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
246 data = sdb_strbuf_string(conn->buf);
247 memcpy(&n, data + offset, sizeof(n));
248 n = ntohl(n);
249 return n;
250 } /* connection_get_int32 */
252 static int
253 command_handle(sdb_conn_t *conn)
254 {
255 int status = -1;
257 assert(conn && (conn->cmd != CONNECTION_IDLE));
259 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
260 conn->cmd, conn->cmd_len);
262 if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP)) {
263 const char *errmsg = "Authentication required";
264 sdb_connection_send(conn, CONNECTION_ERROR,
265 (uint32_t)strlen(errmsg), errmsg);
266 return -1;
267 }
269 /* reset */
270 sdb_strbuf_sprintf(conn->errbuf, "");
272 switch (conn->cmd) {
273 case CONNECTION_PING:
274 status = sdb_connection_ping(conn);
275 break;
276 case CONNECTION_STARTUP:
277 status = sdb_fe_session_start(conn);
278 break;
280 case CONNECTION_QUERY:
281 {
282 sdb_llist_t *parsetree;
283 sdb_conn_node_t *node = NULL;
285 parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
286 (int)conn->cmd_len);
287 if (! parsetree) {
288 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
289 sdb_strbuf_string(conn->buf));
290 status = -1;
291 break;
292 }
294 switch (sdb_llist_len(parsetree)) {
295 case 0:
296 /* skipping empty command */
297 break;
298 case 1:
299 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
300 break;
302 default:
303 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
304 "in multi-statement query '%s'",
305 sdb_llist_len(parsetree) - 1,
306 sdb_llist_len(parsetree) == 2 ? "" : "s",
307 sdb_strbuf_string(conn->buf));
308 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
309 }
311 if (node) {
312 status = sdb_fe_exec(conn, node);
313 sdb_object_deref(SDB_OBJ(node));
314 }
316 sdb_llist_destroy(parsetree);
317 break;
318 }
320 case CONNECTION_FETCH:
321 status = sdb_fe_fetch(conn, sdb_strbuf_string(conn->buf));
322 break;
323 case CONNECTION_LIST:
324 status = sdb_fe_list(conn);
325 break;
326 case CONNECTION_LOOKUP:
327 {
328 sdb_store_matcher_t *m;
330 m = sdb_fe_parse_matcher(sdb_strbuf_string(conn->buf),
331 (int)conn->cmd_len);
332 if (! m) {
333 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse expression '%s'",
334 sdb_strbuf_string(conn->buf));
335 status = -1;
336 break;
337 }
339 status = sdb_fe_lookup(conn, m);
340 sdb_object_deref(SDB_OBJ(m));
341 break;
342 }
344 default:
345 {
346 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
347 conn->cmd);
348 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
349 status = -1;
350 break;
351 }
352 }
354 if (status)
355 sdb_connection_send(conn, CONNECTION_ERROR,
356 (uint32_t)sdb_strbuf_len(conn->errbuf),
357 sdb_strbuf_string(conn->errbuf));
359 /* remove the command from the buffer */
360 if (conn->cmd_len)
361 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
362 conn->cmd = CONNECTION_IDLE;
363 conn->cmd_len = 0;
364 return status;
365 } /* command_handle */
367 /* initialize the connection state information */
368 static int
369 command_init(sdb_conn_t *conn)
370 {
371 size_t len;
373 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
375 conn->cmd = connection_get_int32(conn, 0);
376 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
378 len = 2 * sizeof(uint32_t);
379 if (conn->cmd == CONNECTION_IDLE)
380 len += conn->cmd_len;
381 sdb_strbuf_skip(conn->buf, 0, len);
382 return 0;
383 } /* command_init */
385 /* returns negative value on error, 0 on EOF, number of octets else */
386 static ssize_t
387 connection_read(sdb_conn_t *conn)
388 {
389 ssize_t n = 0;
391 if ((! conn) || (conn->fd < 0))
392 return -1;
394 while (42) {
395 ssize_t status;
397 errno = 0;
398 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
399 if (status < 0) {
400 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
401 break;
403 close(conn->fd);
404 conn->fd = -1;
405 return (int)status;
406 }
407 else if (! status) /* EOF */
408 break;
410 n += status;
411 }
413 return n;
414 } /* connection_read */
416 /*
417 * public API
418 */
420 int
421 sdb_connection_enable_logging(void)
422 {
423 return sdb_plugin_register_log("connection-logger", connection_log,
424 /* user_data = */ NULL);
425 } /* sdb_connection_enable_logging */
427 sdb_conn_t *
428 sdb_connection_accept(int fd)
429 {
430 if (fd < 0)
431 return NULL;
433 /* the placeholder will be replaced with the accepted file
434 * descriptor when initializing the object */
435 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
436 connection_type, fd));
437 } /* sdb_connection_create */
439 void
440 sdb_connection_close(sdb_conn_t *conn)
441 {
442 sdb_object_deref(SDB_OBJ(conn));
443 } /* sdb_connection_close */
445 ssize_t
446 sdb_connection_read(sdb_conn_t *conn)
447 {
448 ssize_t n = 0;
450 sdb_conn_set_ctx(conn);
452 while (42) {
453 ssize_t status = connection_read(conn);
455 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
456 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
457 command_init(conn);
458 if ((conn->cmd != CONNECTION_IDLE)
459 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
460 command_handle(conn);
462 if (status <= 0)
463 break;
465 n += status;
466 }
468 sdb_conn_set_ctx(NULL);
469 return n;
470 } /* sdb_connection_read */
472 ssize_t
473 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
474 uint32_t msg_len, const char *msg)
475 {
476 ssize_t status;
478 if ((! conn) || (conn->fd < 0))
479 return -1;
481 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
482 if (status < 0) {
483 char errbuf[1024];
485 /* tell other code that there was a problem and, more importantly,
486 * make sure we don't try to send further logs to the connection */
487 close(conn->fd);
488 conn->fd = -1;
490 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
491 "(code: %u, len: %u) to client: %s", code, msg_len,
492 sdb_strerror(errno, errbuf, sizeof(errbuf)));
493 }
494 return status;
495 } /* sdb_connection_send */
497 int
498 sdb_connection_ping(sdb_conn_t *conn)
499 {
500 if ((! conn) || (conn->cmd != CONNECTION_PING))
501 return -1;
503 /* we're alive */
504 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
505 return 0;
506 } /* sdb_connection_ping */
508 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */