2fdc5e9222d33449cb10709d090106f66c866e08
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;
120 conn->skip_len = 0;
122 /* update the object name */
123 snprintf(obj->name + strlen(CONN_FD_PREFIX),
124 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
125 return 0;
126 } /* connection_init */
128 static void
129 connection_destroy(sdb_object_t *obj)
130 {
131 sdb_conn_t *conn;
132 size_t len;
134 assert(obj);
135 conn = CONN(obj);
137 if (conn->buf) {
138 len = sdb_strbuf_len(conn->buf);
139 if (len)
140 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
141 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
142 }
144 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
145 if (conn->fd >= 0)
146 close(conn->fd);
147 conn->fd = -1;
149 if (conn->username)
150 free(conn->username);
151 conn->username = NULL;
153 sdb_strbuf_destroy(conn->buf);
154 conn->buf = NULL;
155 sdb_strbuf_destroy(conn->errbuf);
156 conn->errbuf = NULL;
157 } /* connection_destroy */
159 static sdb_type_t connection_type = {
160 /* size = */ sizeof(sdb_conn_t),
161 /* init = */ connection_init,
162 /* destroy = */ connection_destroy,
163 };
165 /*
166 * private helper functions
167 */
169 static void
170 sdb_conn_ctx_destructor(void *c)
171 {
172 sdb_object_t *conn = c;
174 if (! conn)
175 return;
176 sdb_object_deref(conn);
177 } /* sdb_conn_ctx_destructor */
179 static void
180 sdb_conn_ctx_init(void)
181 {
182 if (conn_ctx_key_initialized)
183 return;
185 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
186 conn_ctx_key_initialized = 1;
187 } /* sdb_conn_ctx_init */
189 static void
190 sdb_conn_set_ctx(sdb_conn_t *conn)
191 {
192 sdb_conn_t *old;
194 sdb_conn_ctx_init();
196 old = pthread_getspecific(conn_ctx_key);
197 if (old)
198 sdb_object_deref(SDB_OBJ(old));
199 if (conn)
200 sdb_object_ref(SDB_OBJ(conn));
201 pthread_setspecific(conn_ctx_key, conn);
202 } /* sdb_conn_set_ctx */
204 static sdb_conn_t *
205 sdb_conn_get_ctx(void)
206 {
207 if (! conn_ctx_key_initialized)
208 return NULL;
209 return pthread_getspecific(conn_ctx_key);
210 } /* sdb_conn_get_ctx */
212 /*
213 * connection handler functions
214 */
216 /*
217 * connection_log:
218 * Send a log message originating from the current thread to the client.
219 */
220 static int
221 connection_log(int prio, const char *msg,
222 sdb_object_t __attribute__((unused)) *user_data)
223 {
224 sdb_conn_t *conn;
226 conn = sdb_conn_get_ctx();
227 /* no connection associated to this thread
228 * or user not authenticated yet => don't leak any information */
229 if ((! conn) || (! conn->username))
230 return 0;
232 /* XXX: make the log-level configurable by the client at runtime */
233 if (prio >= SDB_LOG_DEBUG)
234 return 0;
236 /* TODO: Use CONNECTION_LOG_<prio>? */
237 if (sdb_connection_send(conn, CONNECTION_LOG,
238 (uint32_t)strlen(msg), msg) < 0)
239 return -1;
240 return 0;
241 } /* connection_log */
243 static uint32_t
244 connection_get_int32(sdb_conn_t *conn, size_t offset)
245 {
246 const char *data;
247 uint32_t n;
249 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
251 data = sdb_strbuf_string(conn->buf);
252 memcpy(&n, data + offset, sizeof(n));
253 n = ntohl(n);
254 return n;
255 } /* connection_get_int32 */
257 static int
258 command_handle(sdb_conn_t *conn)
259 {
260 int status = -1;
262 assert(conn && (conn->cmd != CONNECTION_IDLE));
263 assert(! conn->skip_len);
265 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
266 conn->cmd, conn->cmd_len);
268 switch (conn->cmd) {
269 case CONNECTION_PING:
270 status = sdb_connection_ping(conn);
271 break;
272 case CONNECTION_STARTUP:
273 status = sdb_fe_session_start(conn);
274 break;
276 case CONNECTION_QUERY:
277 {
278 sdb_llist_t *parsetree;
279 sdb_conn_node_t *node = NULL;
281 parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
282 (int)conn->cmd_len);
283 if (! parsetree) {
284 char query[conn->cmd_len + 1];
285 strncpy(query, sdb_strbuf_string(conn->buf), conn->cmd_len);
286 query[sizeof(query) - 1] = '\0';
287 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
288 query);
289 status = -1;
290 break;
291 }
293 switch (sdb_llist_len(parsetree)) {
294 case 0:
295 /* skipping empty command */
296 break;
297 case 1:
298 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
299 break;
301 default:
302 {
303 char query[conn->cmd_len + 1];
304 strncpy(query, sdb_strbuf_string(conn->buf), conn->cmd_len);
305 query[sizeof(query) - 1] = '\0';
306 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
307 "in multi-statement query '%s'",
308 sdb_llist_len(parsetree) - 1,
309 sdb_llist_len(parsetree) == 2 ? "" : "s",
310 query);
311 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
312 }
313 }
315 if (node) {
316 status = sdb_fe_exec(conn, node);
317 sdb_object_deref(SDB_OBJ(node));
318 }
320 sdb_llist_destroy(parsetree);
321 break;
322 }
324 case CONNECTION_FETCH:
325 {
326 char hostname[conn->cmd_len + 1];
327 strncpy(hostname, sdb_strbuf_string(conn->buf), conn->cmd_len);
328 hostname[sizeof(hostname) - 1] = '\0';
329 status = sdb_fe_exec_fetch(conn, hostname, /* filter = */ NULL);
330 break;
331 }
332 case CONNECTION_LIST:
333 status = sdb_fe_exec_list(conn, /* filter = */ NULL);
334 break;
335 case CONNECTION_LOOKUP:
336 {
337 sdb_store_matcher_t *m;
339 m = sdb_fe_parse_matcher(sdb_strbuf_string(conn->buf),
340 (int)conn->cmd_len);
341 if (! m) {
342 char expr[conn->cmd_len + 1];
343 strncpy(expr, sdb_strbuf_string(conn->buf), conn->cmd_len);
344 expr[sizeof(expr) - 1] = '\0';
345 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse "
346 "lookup condition '%s'", expr);
347 status = -1;
348 break;
349 }
351 status = sdb_fe_exec_lookup(conn, m, /* filter = */ NULL);
352 sdb_object_deref(SDB_OBJ(m));
353 break;
354 }
356 default:
357 {
358 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
359 conn->cmd);
360 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
361 status = -1;
362 break;
363 }
364 }
366 if (status)
367 sdb_connection_send(conn, CONNECTION_ERROR,
368 (uint32_t)sdb_strbuf_len(conn->errbuf),
369 sdb_strbuf_string(conn->errbuf));
370 return status;
371 } /* command_handle */
373 /* initialize the connection state information */
374 static int
375 command_init(sdb_conn_t *conn)
376 {
377 const char *errmsg = NULL;
379 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
381 if (conn->skip_len)
382 return -1;
384 /* reset */
385 sdb_strbuf_sprintf(conn->errbuf, "");
387 conn->cmd = connection_get_int32(conn, 0);
388 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
390 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
392 if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP))
393 errmsg = "Authentication required";
394 else if (conn->cmd == CONNECTION_IDLE)
395 errmsg = "Invalid command 0";
397 if (errmsg) {
398 size_t len = sdb_strbuf_len(conn->buf);
400 sdb_strbuf_sprintf(conn->errbuf, errmsg);
401 sdb_connection_send(conn, CONNECTION_ERROR,
402 (uint32_t)strlen(errmsg), errmsg);
403 conn->skip_len += conn->cmd_len;
404 conn->cmd = CONNECTION_IDLE;
405 conn->cmd_len = 0;
407 if (len > conn->skip_len)
408 len = conn->skip_len;
409 sdb_strbuf_skip(conn->buf, 0, len);
410 conn->skip_len -= len;
411 /* connection_read will handle anything else */
412 }
413 return 0;
414 } /* command_init */
416 /* returns negative value on error, 0 on EOF, number of octets else */
417 static ssize_t
418 connection_read(sdb_conn_t *conn)
419 {
420 ssize_t n = 0;
422 if ((! conn) || (conn->fd < 0))
423 return -1;
425 while (42) {
426 ssize_t status;
428 errno = 0;
429 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
430 if (status < 0) {
431 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
432 break;
434 close(conn->fd);
435 conn->fd = -1;
436 return (int)status;
437 }
438 else if (! status) /* EOF */
439 break;
441 if (conn->skip_len) {
442 size_t len = (size_t)status < conn->skip_len
443 ? (size_t)status : conn->skip_len;
444 sdb_strbuf_skip(conn->buf, 0, len);
445 conn->skip_len -= len;
446 }
448 n += status;
450 /* give the main loop a chance to execute commands (and free up buffer
451 * space) on large amounts of incoming traffic */
452 if (n > 1024 * 1024)
453 break;
454 }
456 return n;
457 } /* connection_read */
459 /*
460 * public API
461 */
463 int
464 sdb_connection_enable_logging(void)
465 {
466 return sdb_plugin_register_log("connection-logger", connection_log,
467 /* user_data = */ NULL);
468 } /* sdb_connection_enable_logging */
470 sdb_conn_t *
471 sdb_connection_accept(int fd)
472 {
473 if (fd < 0)
474 return NULL;
476 /* the placeholder will be replaced with the accepted file
477 * descriptor when initializing the object */
478 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
479 connection_type, fd));
480 } /* sdb_connection_create */
482 void
483 sdb_connection_close(sdb_conn_t *conn)
484 {
485 if (! conn)
486 return;
488 /* close the connection even if someone else still references it */
489 if (conn->fd >= 0)
490 close(conn->fd);
491 conn->fd = -1;
493 sdb_object_deref(SDB_OBJ(conn));
494 } /* sdb_connection_close */
496 ssize_t
497 sdb_connection_read(sdb_conn_t *conn)
498 {
499 ssize_t n = 0;
501 sdb_conn_set_ctx(conn);
503 while (42) {
504 ssize_t status = connection_read(conn);
506 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
507 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
508 command_init(conn);
509 if ((conn->cmd != CONNECTION_IDLE)
510 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
511 command_handle(conn);
513 /* remove the command from the buffer */
514 if (conn->cmd_len)
515 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
516 conn->cmd = CONNECTION_IDLE;
517 conn->cmd_len = 0;
518 }
520 if (status <= 0)
521 break;
523 n += status;
524 }
526 sdb_conn_set_ctx(NULL);
527 return n;
528 } /* sdb_connection_read */
530 ssize_t
531 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
532 uint32_t msg_len, const char *msg)
533 {
534 ssize_t status;
536 if ((! conn) || (conn->fd < 0))
537 return -1;
539 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
540 if (status < 0) {
541 char errbuf[1024];
543 /* tell other code that there was a problem and, more importantly,
544 * make sure we don't try to send further logs to the connection */
545 close(conn->fd);
546 conn->fd = -1;
548 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
549 "(code: %u, len: %u) to client: %s", code, msg_len,
550 sdb_strerror(errno, errbuf, sizeof(errbuf)));
551 }
552 return status;
553 } /* sdb_connection_send */
555 int
556 sdb_connection_ping(sdb_conn_t *conn)
557 {
558 if ((! conn) || (conn->cmd != CONNECTION_PING))
559 return -1;
561 /* we're alive */
562 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
563 return 0;
564 } /* sdb_connection_ping */
566 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */