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 on fd=%i",
144 conn->fd);
145 if (conn->fd >= 0)
146 close(conn->fd);
147 conn->fd = -1;
149 sdb_strbuf_destroy(conn->buf);
150 conn->buf = NULL;
151 sdb_strbuf_destroy(conn->errbuf);
152 conn->errbuf = NULL;
153 } /* connection_destroy */
155 static sdb_type_t connection_type = {
156 /* size = */ sizeof(sdb_conn_t),
157 /* init = */ connection_init,
158 /* destroy = */ connection_destroy,
159 };
161 /*
162 * private helper functions
163 */
165 static void
166 sdb_conn_ctx_destructor(void *c)
167 {
168 sdb_object_t *conn = c;
170 if (! conn)
171 return;
172 sdb_object_deref(conn);
173 } /* sdb_conn_ctx_destructor */
175 static void
176 sdb_conn_ctx_init(void)
177 {
178 if (conn_ctx_key_initialized)
179 return;
181 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
182 conn_ctx_key_initialized = 1;
183 } /* sdb_conn_ctx_init */
185 static void
186 sdb_conn_set_ctx(sdb_conn_t *conn)
187 {
188 sdb_conn_ctx_init();
189 if (conn)
190 sdb_object_ref(SDB_OBJ(conn));
191 pthread_setspecific(conn_ctx_key, conn);
192 } /* sdb_conn_set_ctx */
194 static sdb_conn_t *
195 sdb_conn_get_ctx(void)
196 {
197 if (! conn_ctx_key_initialized)
198 return NULL;
199 return pthread_getspecific(conn_ctx_key);
200 } /* sdb_conn_get_ctx */
202 /*
203 * connection handler functions
204 */
206 /*
207 * connection_log:
208 * Send a log message originating from the current thread to the client.
209 */
210 static int
211 connection_log(int prio, const char *msg,
212 sdb_object_t __attribute__((unused)) *user_data)
213 {
214 sdb_conn_t *conn;
216 conn = sdb_conn_get_ctx();
217 /* no connection associated to this thread
218 * or user not authenticated yet => don't leak any information */
219 if ((! conn) || (! conn->username))
220 return 0;
222 /* XXX: make the log-level configurable by the client at runtime */
223 if (prio >= SDB_LOG_DEBUG)
224 return 0;
226 /* TODO: Use CONNECTION_LOG_<prio>? */
227 if (sdb_connection_send(conn, CONNECTION_LOG,
228 (uint32_t)strlen(msg), msg) < 0)
229 return -1;
230 return 0;
231 } /* connection_log */
233 static uint32_t
234 connection_get_int32(sdb_conn_t *conn, size_t offset)
235 {
236 const char *data;
237 uint32_t n;
239 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
241 data = sdb_strbuf_string(conn->buf);
242 memcpy(&n, data + offset, sizeof(n));
243 n = ntohl(n);
244 return n;
245 } /* connection_get_int32 */
247 static int
248 command_handle(sdb_conn_t *conn)
249 {
250 int status = -1;
252 assert(conn && (conn->cmd != CONNECTION_IDLE));
254 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
255 conn->cmd, conn->cmd_len);
257 if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP)) {
258 const char *errmsg = "Authentication required";
259 sdb_connection_send(conn, CONNECTION_ERROR,
260 (uint32_t)strlen(errmsg), errmsg);
261 return -1;
262 }
264 /* reset */
265 sdb_strbuf_sprintf(conn->errbuf, "");
267 switch (conn->cmd) {
268 case CONNECTION_PING:
269 status = sdb_connection_ping(conn);
270 break;
271 case CONNECTION_STARTUP:
272 status = sdb_fe_session_start(conn);
273 break;
275 case CONNECTION_QUERY:
276 {
277 sdb_llist_t *parsetree;
278 sdb_conn_node_t *node = NULL;
280 parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
281 (int)conn->cmd_len);
282 if (! parsetree) {
283 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
284 sdb_strbuf_string(conn->buf));
285 status = -1;
286 break;
287 }
289 switch (sdb_llist_len(parsetree)) {
290 case 0:
291 /* skipping empty command */
292 break;
293 case 1:
294 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
295 break;
297 default:
298 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
299 "in multi-statement query '%s'",
300 sdb_llist_len(parsetree) - 1,
301 sdb_llist_len(parsetree) == 2 ? "" : "s",
302 sdb_strbuf_string(conn->buf));
303 node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
304 }
306 if (node) {
307 status = sdb_fe_exec(conn, node);
308 sdb_object_deref(SDB_OBJ(node));
309 }
311 sdb_llist_destroy(parsetree);
312 break;
313 }
315 case CONNECTION_FETCH:
316 status = sdb_fe_fetch(conn, sdb_strbuf_string(conn->buf));
317 break;
318 case CONNECTION_LIST:
319 status = sdb_fe_list(conn);
320 break;
321 case CONNECTION_LOOKUP:
322 {
323 sdb_store_matcher_t *m;
325 m = sdb_fe_parse_matcher(sdb_strbuf_string(conn->buf),
326 (int)conn->cmd_len);
327 if (! m) {
328 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse expression '%s'",
329 sdb_strbuf_string(conn->buf));
330 status = -1;
331 break;
332 }
334 status = sdb_fe_lookup(conn, m);
335 sdb_object_deref(SDB_OBJ(m));
336 break;
337 }
339 default:
340 {
341 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
342 conn->cmd);
343 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
344 status = -1;
345 break;
346 }
347 }
349 if (status)
350 sdb_connection_send(conn, CONNECTION_ERROR,
351 (uint32_t)sdb_strbuf_len(conn->errbuf),
352 sdb_strbuf_string(conn->errbuf));
354 /* remove the command from the buffer */
355 if (conn->cmd_len)
356 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
357 conn->cmd = CONNECTION_IDLE;
358 conn->cmd_len = 0;
359 return status;
360 } /* command_handle */
362 /* initialize the connection state information */
363 static int
364 command_init(sdb_conn_t *conn)
365 {
366 size_t len;
368 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
370 conn->cmd = connection_get_int32(conn, 0);
371 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
373 len = 2 * sizeof(uint32_t);
374 if (conn->cmd == CONNECTION_IDLE)
375 len += conn->cmd_len;
376 sdb_strbuf_skip(conn->buf, 0, len);
377 return 0;
378 } /* command_init */
380 /* returns negative value on error, 0 on EOF, number of octets else */
381 static ssize_t
382 connection_read(sdb_conn_t *conn)
383 {
384 ssize_t n = 0;
386 if ((! conn) || (conn->fd < 0))
387 return -1;
389 while (42) {
390 ssize_t status;
392 errno = 0;
393 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
394 if (status < 0) {
395 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
396 break;
398 close(conn->fd);
399 conn->fd = -1;
400 return (int)status;
401 }
402 else if (! status) /* EOF */
403 break;
405 n += status;
406 }
408 return n;
409 } /* connection_read */
411 /*
412 * public API
413 */
415 int
416 sdb_connection_enable_logging(void)
417 {
418 return sdb_plugin_register_log("connection-logger", connection_log,
419 /* user_data = */ NULL);
420 } /* sdb_connection_enable_logging */
422 sdb_conn_t *
423 sdb_connection_accept(int fd)
424 {
425 if (fd < 0)
426 return NULL;
428 /* the placeholder will be replaced with the accepted file
429 * descriptor when initializing the object */
430 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
431 connection_type, fd));
432 } /* sdb_connection_create */
434 void
435 sdb_connection_close(sdb_conn_t *conn)
436 {
437 sdb_object_deref(SDB_OBJ(conn));
438 } /* sdb_connection_close */
440 ssize_t
441 sdb_connection_read(sdb_conn_t *conn)
442 {
443 ssize_t n = 0;
445 sdb_conn_set_ctx(conn);
447 while (42) {
448 ssize_t status = connection_read(conn);
450 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
451 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
452 command_init(conn);
453 if ((conn->cmd != CONNECTION_IDLE)
454 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
455 command_handle(conn);
457 if (status <= 0)
458 break;
460 n += status;
461 }
463 sdb_conn_set_ctx(NULL);
464 return n;
465 } /* sdb_connection_read */
467 ssize_t
468 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
469 uint32_t msg_len, const char *msg)
470 {
471 ssize_t status;
473 if ((! conn) || (conn->fd < 0))
474 return -1;
476 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
477 if (status < 0) {
478 char errbuf[1024];
480 /* tell other code that there was a problem and, more importantly,
481 * make sure we don't try to send further logs to the connection */
482 close(conn->fd);
483 conn->fd = -1;
485 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
486 "(code: %u, len: %u) to client: %s", code, msg_len,
487 sdb_strerror(errno, errbuf, sizeof(errbuf)));
488 }
489 return status;
490 } /* sdb_connection_send */
492 int
493 sdb_connection_ping(sdb_conn_t *conn)
494 {
495 if ((! conn) || (conn->cmd != CONNECTION_PING))
496 return -1;
498 /* we're alive */
499 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
500 return 0;
501 } /* sdb_connection_ping */
503 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */