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 int
250 command_handle(sdb_conn_t *conn)
251 {
252 int status = -1;
254 assert(conn && (conn->cmd != CONNECTION_IDLE));
255 assert(! conn->skip_len);
257 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
258 conn->cmd, conn->cmd_len);
260 if (conn->cmd == CONNECTION_PING)
261 status = sdb_connection_ping(conn);
262 else if (conn->cmd == CONNECTION_STARTUP)
263 status = sdb_fe_session_start(conn);
264 else if (conn->cmd == CONNECTION_QUERY)
265 status = sdb_fe_query(conn);
266 else if (conn->cmd == CONNECTION_FETCH)
267 status = sdb_fe_fetch(conn);
268 else if (conn->cmd == CONNECTION_LIST)
269 status = sdb_fe_list(conn);
270 else if (conn->cmd == CONNECTION_LOOKUP)
271 status = sdb_fe_lookup(conn);
272 else {
273 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
274 conn->cmd);
275 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
276 status = -1;
277 }
279 if (status) {
280 if (! sdb_strbuf_len(conn->errbuf))
281 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
282 sdb_connection_send(conn, CONNECTION_ERROR,
283 (uint32_t)sdb_strbuf_len(conn->errbuf),
284 sdb_strbuf_string(conn->errbuf));
285 }
286 return status;
287 } /* command_handle */
289 /* initialize the connection state information */
290 static int
291 command_init(sdb_conn_t *conn)
292 {
293 const char *errmsg = NULL;
295 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
297 if (conn->skip_len)
298 return -1;
300 /* reset */
301 sdb_strbuf_clear(conn->errbuf);
303 conn->cmd = sdb_proto_get_int(conn->buf, 0);
304 conn->cmd_len = sdb_proto_get_int(conn->buf, sizeof(uint32_t));
306 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
308 if ((! conn->ready) && (conn->cmd != CONNECTION_STARTUP))
309 errmsg = "Authentication required";
310 else if (conn->cmd == CONNECTION_IDLE)
311 errmsg = "Invalid command 0";
313 if (errmsg) {
314 size_t len = sdb_strbuf_len(conn->buf);
316 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
317 sdb_connection_send(conn, CONNECTION_ERROR,
318 (uint32_t)strlen(errmsg), errmsg);
319 conn->skip_len += conn->cmd_len;
320 conn->cmd = CONNECTION_IDLE;
321 conn->cmd_len = 0;
323 if (len > conn->skip_len)
324 len = conn->skip_len;
325 sdb_strbuf_skip(conn->buf, 0, len);
326 conn->skip_len -= len;
327 /* connection_read will handle anything else */
328 }
329 return 0;
330 } /* command_init */
332 /* returns negative value on error, 0 on EOF, number of octets else */
333 static ssize_t
334 connection_read(sdb_conn_t *conn)
335 {
336 ssize_t n = 0;
338 if ((! conn) || (conn->fd < 0))
339 return -1;
341 while (42) {
342 ssize_t status;
344 errno = 0;
345 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
346 if (status < 0) {
347 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
348 break;
350 close(conn->fd);
351 conn->fd = -1;
352 return (int)status;
353 }
354 else if (! status) /* EOF */
355 break;
357 if (conn->skip_len) {
358 size_t len = (size_t)status < conn->skip_len
359 ? (size_t)status : conn->skip_len;
360 sdb_strbuf_skip(conn->buf, 0, len);
361 conn->skip_len -= len;
362 }
364 n += status;
366 /* give the main loop a chance to execute commands (and free up buffer
367 * space) on large amounts of incoming traffic */
368 if (n > 1024 * 1024)
369 break;
370 }
372 return n;
373 } /* connection_read */
375 /*
376 * public API
377 */
379 int
380 sdb_connection_enable_logging(void)
381 {
382 return sdb_plugin_register_log("connection-logger", connection_log,
383 /* user_data = */ NULL);
384 } /* sdb_connection_enable_logging */
386 sdb_conn_t *
387 sdb_connection_accept(int fd)
388 {
389 if (fd < 0)
390 return NULL;
392 /* the placeholder will be replaced with the accepted file
393 * descriptor when initializing the object */
394 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
395 connection_type, fd));
396 } /* sdb_connection_create */
398 void
399 sdb_connection_close(sdb_conn_t *conn)
400 {
401 if (! conn)
402 return;
404 /* close the connection even if someone else still references it */
405 if (conn->fd >= 0)
406 close(conn->fd);
407 conn->fd = -1;
409 sdb_object_deref(SDB_OBJ(conn));
410 } /* sdb_connection_close */
412 ssize_t
413 sdb_connection_read(sdb_conn_t *conn)
414 {
415 ssize_t n = 0;
417 sdb_conn_set_ctx(conn);
419 while (42) {
420 ssize_t status = connection_read(conn);
422 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
423 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
424 command_init(conn);
425 if ((conn->cmd != CONNECTION_IDLE)
426 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
427 command_handle(conn);
429 /* remove the command from the buffer */
430 if (conn->cmd_len)
431 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
432 conn->cmd = CONNECTION_IDLE;
433 conn->cmd_len = 0;
434 }
436 if (status <= 0)
437 break;
439 n += status;
440 }
442 sdb_conn_set_ctx(NULL);
443 return n;
444 } /* sdb_connection_read */
446 ssize_t
447 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
448 uint32_t msg_len, const char *msg)
449 {
450 ssize_t status;
452 if ((! conn) || (conn->fd < 0))
453 return -1;
455 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
456 if (status < 0) {
457 char errbuf[1024];
459 /* tell other code that there was a problem and, more importantly,
460 * make sure we don't try to send further logs to the connection */
461 close(conn->fd);
462 conn->fd = -1;
463 conn->ready = 0;
465 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
466 "(code: %u, len: %u) to client: %s", code, msg_len,
467 sdb_strerror(errno, errbuf, sizeof(errbuf)));
468 }
469 return status;
470 } /* sdb_connection_send */
472 int
473 sdb_connection_ping(sdb_conn_t *conn)
474 {
475 if ((! conn) || (conn->cmd != CONNECTION_PING))
476 return -1;
478 /* we're alive */
479 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
480 return 0;
481 } /* sdb_connection_ping */
483 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */