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 "utils/error.h"
33 #include "utils/strbuf.h"
34 #include "utils/proto.h"
36 #include <assert.h>
37 #include <errno.h>
39 #include <arpa/inet.h>
40 #include <fcntl.h>
42 #include <stdlib.h>
43 #include <string.h>
45 #include <pthread.h>
47 /*
48 * private variables
49 */
51 static pthread_key_t conn_ctx_key;
52 static _Bool conn_ctx_key_initialized = 0;
54 /*
55 * private types
56 */
58 /* name of connection objects */
59 #define CONN_FD_PREFIX "conn#"
60 #define CONN_FD_PLACEHOLDER "XXXXXXX"
62 static int
63 connection_init(sdb_object_t *obj, va_list ap)
64 {
65 sdb_conn_t *conn;
66 int sock_fd;
67 int sock_fl;
69 assert(obj);
70 conn = CONN(obj);
72 sock_fd = va_arg(ap, int);
74 conn->buf = sdb_strbuf_create(/* size = */ 128);
75 if (! conn->buf) {
76 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
77 "for a new connection");
78 return -1;
79 }
80 conn->errbuf = sdb_strbuf_create(0);
81 if (! conn->errbuf) {
82 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
83 "for a new connection");
84 return -1;
85 }
87 conn->client_addr_len = sizeof(conn->client_addr);
88 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
89 &conn->client_addr_len);
91 if (conn->fd < 0) {
92 char buf[1024];
93 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
94 "connection: %s", sdb_strerror(errno,
95 buf, sizeof(buf)));
96 return -1;
97 }
99 if (conn->client_addr.ss_family != AF_UNIX) {
100 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
101 "unexpected family type %d", conn->client_addr.ss_family);
102 return -1;
103 }
105 sock_fl = fcntl(conn->fd, F_GETFL);
106 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
107 char buf[1024];
108 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
109 "to non-blocking mode: %s", conn->fd,
110 sdb_strerror(errno, buf, sizeof(buf)));
111 return -1;
112 }
114 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
115 conn->fd);
117 conn->cmd = CONNECTION_IDLE;
118 conn->cmd_len = 0;
119 conn->skip_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 conn->ready = 0;
138 if (conn->buf) {
139 len = sdb_strbuf_len(conn->buf);
140 if (len)
141 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
142 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
143 }
145 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
146 if (conn->fd >= 0)
147 close(conn->fd);
148 conn->fd = -1;
150 if (conn->username)
151 free(conn->username);
152 conn->username = NULL;
154 sdb_strbuf_destroy(conn->buf);
155 conn->buf = NULL;
156 sdb_strbuf_destroy(conn->errbuf);
157 conn->errbuf = NULL;
158 } /* connection_destroy */
160 static sdb_type_t connection_type = {
161 /* size = */ sizeof(sdb_conn_t),
162 /* init = */ connection_init,
163 /* destroy = */ connection_destroy,
164 };
166 /*
167 * private helper functions
168 */
170 static void
171 sdb_conn_ctx_destructor(void *c)
172 {
173 sdb_object_t *conn = c;
175 if (! conn)
176 return;
177 sdb_object_deref(conn);
178 } /* sdb_conn_ctx_destructor */
180 static void
181 sdb_conn_ctx_init(void)
182 {
183 if (conn_ctx_key_initialized)
184 return;
186 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
187 conn_ctx_key_initialized = 1;
188 } /* sdb_conn_ctx_init */
190 static void
191 sdb_conn_set_ctx(sdb_conn_t *conn)
192 {
193 sdb_conn_t *old;
195 sdb_conn_ctx_init();
197 old = pthread_getspecific(conn_ctx_key);
198 if (old)
199 sdb_object_deref(SDB_OBJ(old));
200 if (conn)
201 sdb_object_ref(SDB_OBJ(conn));
202 pthread_setspecific(conn_ctx_key, conn);
203 } /* sdb_conn_set_ctx */
205 static sdb_conn_t *
206 sdb_conn_get_ctx(void)
207 {
208 if (! conn_ctx_key_initialized)
209 return NULL;
210 return pthread_getspecific(conn_ctx_key);
211 } /* sdb_conn_get_ctx */
213 /*
214 * connection handler functions
215 */
217 /*
218 * connection_log:
219 * Send a log message originating from the current thread to the client.
220 */
221 static int
222 connection_log(int prio, const char *msg,
223 sdb_object_t __attribute__((unused)) *user_data)
224 {
225 uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
226 uint32_t p = htonl((uint32_t)prio);
227 char tmp[len + 1];
229 sdb_conn_t *conn;
231 conn = sdb_conn_get_ctx();
232 /* no connection associated to this thread
233 * or startup not done yet => don't leak any information */
234 if ((! conn) || (! conn->ready))
235 return 0;
237 /* XXX: make the log-level configurable by the client at runtime */
238 if (prio >= SDB_LOG_DEBUG)
239 return 0;
241 memcpy(tmp, &p, sizeof(p));
242 strcpy(tmp + sizeof(p), msg);
244 if (sdb_connection_send(conn, CONNECTION_LOG, len, tmp) < 0)
245 return -1;
246 return 0;
247 } /* connection_log */
249 static uint32_t
250 connection_get_int32(sdb_conn_t *conn, size_t offset)
251 {
252 const char *data;
253 uint32_t n;
255 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
257 data = sdb_strbuf_string(conn->buf);
258 memcpy(&n, data + offset, sizeof(n));
259 n = ntohl(n);
260 return n;
261 } /* connection_get_int32 */
263 static int
264 command_handle(sdb_conn_t *conn)
265 {
266 int status = -1;
268 assert(conn && (conn->cmd != CONNECTION_IDLE));
269 assert(! conn->skip_len);
271 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
272 conn->cmd, conn->cmd_len);
274 if (conn->cmd == CONNECTION_PING)
275 status = sdb_connection_ping(conn);
276 else if (conn->cmd == CONNECTION_STARTUP)
277 status = sdb_fe_session_start(conn);
278 else if (conn->cmd == CONNECTION_QUERY)
279 status = sdb_fe_query(conn);
280 else if (conn->cmd == CONNECTION_FETCH)
281 status = sdb_fe_fetch(conn);
282 else if (conn->cmd == CONNECTION_LIST)
283 status = sdb_fe_list(conn);
284 else if (conn->cmd == CONNECTION_LOOKUP)
285 status = sdb_fe_lookup(conn);
286 else {
287 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
288 conn->cmd);
289 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
290 status = -1;
291 }
293 if (status)
294 sdb_connection_send(conn, CONNECTION_ERROR,
295 (uint32_t)sdb_strbuf_len(conn->errbuf),
296 sdb_strbuf_string(conn->errbuf));
297 return status;
298 } /* command_handle */
300 /* initialize the connection state information */
301 static int
302 command_init(sdb_conn_t *conn)
303 {
304 const char *errmsg = NULL;
306 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
308 if (conn->skip_len)
309 return -1;
311 /* reset */
312 sdb_strbuf_clear(conn->errbuf);
314 conn->cmd = connection_get_int32(conn, 0);
315 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
317 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
319 if ((! conn->ready) && (conn->cmd != CONNECTION_STARTUP))
320 errmsg = "Authentication required";
321 else if (conn->cmd == CONNECTION_IDLE)
322 errmsg = "Invalid command 0";
324 if (errmsg) {
325 size_t len = sdb_strbuf_len(conn->buf);
327 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
328 sdb_connection_send(conn, CONNECTION_ERROR,
329 (uint32_t)strlen(errmsg), errmsg);
330 conn->skip_len += conn->cmd_len;
331 conn->cmd = CONNECTION_IDLE;
332 conn->cmd_len = 0;
334 if (len > conn->skip_len)
335 len = conn->skip_len;
336 sdb_strbuf_skip(conn->buf, 0, len);
337 conn->skip_len -= len;
338 /* connection_read will handle anything else */
339 }
340 return 0;
341 } /* command_init */
343 /* returns negative value on error, 0 on EOF, number of octets else */
344 static ssize_t
345 connection_read(sdb_conn_t *conn)
346 {
347 ssize_t n = 0;
349 if ((! conn) || (conn->fd < 0))
350 return -1;
352 while (42) {
353 ssize_t status;
355 errno = 0;
356 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
357 if (status < 0) {
358 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
359 break;
361 close(conn->fd);
362 conn->fd = -1;
363 return (int)status;
364 }
365 else if (! status) /* EOF */
366 break;
368 if (conn->skip_len) {
369 size_t len = (size_t)status < conn->skip_len
370 ? (size_t)status : conn->skip_len;
371 sdb_strbuf_skip(conn->buf, 0, len);
372 conn->skip_len -= len;
373 }
375 n += status;
377 /* give the main loop a chance to execute commands (and free up buffer
378 * space) on large amounts of incoming traffic */
379 if (n > 1024 * 1024)
380 break;
381 }
383 return n;
384 } /* connection_read */
386 /*
387 * public API
388 */
390 int
391 sdb_connection_enable_logging(void)
392 {
393 return sdb_plugin_register_log("connection-logger", connection_log,
394 /* user_data = */ NULL);
395 } /* sdb_connection_enable_logging */
397 sdb_conn_t *
398 sdb_connection_accept(int fd)
399 {
400 if (fd < 0)
401 return NULL;
403 /* the placeholder will be replaced with the accepted file
404 * descriptor when initializing the object */
405 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
406 connection_type, fd));
407 } /* sdb_connection_create */
409 void
410 sdb_connection_close(sdb_conn_t *conn)
411 {
412 if (! conn)
413 return;
415 /* close the connection even if someone else still references it */
416 if (conn->fd >= 0)
417 close(conn->fd);
418 conn->fd = -1;
420 sdb_object_deref(SDB_OBJ(conn));
421 } /* sdb_connection_close */
423 ssize_t
424 sdb_connection_read(sdb_conn_t *conn)
425 {
426 ssize_t n = 0;
428 sdb_conn_set_ctx(conn);
430 while (42) {
431 ssize_t status = connection_read(conn);
433 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
434 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
435 command_init(conn);
436 if ((conn->cmd != CONNECTION_IDLE)
437 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
438 command_handle(conn);
440 /* remove the command from the buffer */
441 if (conn->cmd_len)
442 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
443 conn->cmd = CONNECTION_IDLE;
444 conn->cmd_len = 0;
445 }
447 if (status <= 0)
448 break;
450 n += status;
451 }
453 sdb_conn_set_ctx(NULL);
454 return n;
455 } /* sdb_connection_read */
457 ssize_t
458 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
459 uint32_t msg_len, const char *msg)
460 {
461 ssize_t status;
463 if ((! conn) || (conn->fd < 0))
464 return -1;
466 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
467 if (status < 0) {
468 char errbuf[1024];
470 /* tell other code that there was a problem and, more importantly,
471 * make sure we don't try to send further logs to the connection */
472 close(conn->fd);
473 conn->fd = -1;
474 conn->ready = 0;
476 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
477 "(code: %u, len: %u) to client: %s", code, msg_len,
478 sdb_strerror(errno, errbuf, sizeof(errbuf)));
479 }
480 return status;
481 } /* sdb_connection_send */
483 int
484 sdb_connection_ping(sdb_conn_t *conn)
485 {
486 if ((! conn) || (conn->cmd != CONNECTION_PING))
487 return -1;
489 /* we're alive */
490 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
491 return 0;
492 } /* sdb_connection_ping */
494 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */