6cad74788cbef796e42ef01a3fd6f334430fdabd
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 if (! sdb_strbuf_len(conn->errbuf))
295 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
296 sdb_connection_send(conn, CONNECTION_ERROR,
297 (uint32_t)sdb_strbuf_len(conn->errbuf),
298 sdb_strbuf_string(conn->errbuf));
299 }
300 return status;
301 } /* command_handle */
303 /* initialize the connection state information */
304 static int
305 command_init(sdb_conn_t *conn)
306 {
307 const char *errmsg = NULL;
309 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
311 if (conn->skip_len)
312 return -1;
314 /* reset */
315 sdb_strbuf_clear(conn->errbuf);
317 conn->cmd = connection_get_int32(conn, 0);
318 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
320 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
322 if ((! conn->ready) && (conn->cmd != CONNECTION_STARTUP))
323 errmsg = "Authentication required";
324 else if (conn->cmd == CONNECTION_IDLE)
325 errmsg = "Invalid command 0";
327 if (errmsg) {
328 size_t len = sdb_strbuf_len(conn->buf);
330 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
331 sdb_connection_send(conn, CONNECTION_ERROR,
332 (uint32_t)strlen(errmsg), errmsg);
333 conn->skip_len += conn->cmd_len;
334 conn->cmd = CONNECTION_IDLE;
335 conn->cmd_len = 0;
337 if (len > conn->skip_len)
338 len = conn->skip_len;
339 sdb_strbuf_skip(conn->buf, 0, len);
340 conn->skip_len -= len;
341 /* connection_read will handle anything else */
342 }
343 return 0;
344 } /* command_init */
346 /* returns negative value on error, 0 on EOF, number of octets else */
347 static ssize_t
348 connection_read(sdb_conn_t *conn)
349 {
350 ssize_t n = 0;
352 if ((! conn) || (conn->fd < 0))
353 return -1;
355 while (42) {
356 ssize_t status;
358 errno = 0;
359 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
360 if (status < 0) {
361 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
362 break;
364 close(conn->fd);
365 conn->fd = -1;
366 return (int)status;
367 }
368 else if (! status) /* EOF */
369 break;
371 if (conn->skip_len) {
372 size_t len = (size_t)status < conn->skip_len
373 ? (size_t)status : conn->skip_len;
374 sdb_strbuf_skip(conn->buf, 0, len);
375 conn->skip_len -= len;
376 }
378 n += status;
380 /* give the main loop a chance to execute commands (and free up buffer
381 * space) on large amounts of incoming traffic */
382 if (n > 1024 * 1024)
383 break;
384 }
386 return n;
387 } /* connection_read */
389 /*
390 * public API
391 */
393 int
394 sdb_connection_enable_logging(void)
395 {
396 return sdb_plugin_register_log("connection-logger", connection_log,
397 /* user_data = */ NULL);
398 } /* sdb_connection_enable_logging */
400 sdb_conn_t *
401 sdb_connection_accept(int fd)
402 {
403 if (fd < 0)
404 return NULL;
406 /* the placeholder will be replaced with the accepted file
407 * descriptor when initializing the object */
408 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
409 connection_type, fd));
410 } /* sdb_connection_create */
412 void
413 sdb_connection_close(sdb_conn_t *conn)
414 {
415 if (! conn)
416 return;
418 /* close the connection even if someone else still references it */
419 if (conn->fd >= 0)
420 close(conn->fd);
421 conn->fd = -1;
423 sdb_object_deref(SDB_OBJ(conn));
424 } /* sdb_connection_close */
426 ssize_t
427 sdb_connection_read(sdb_conn_t *conn)
428 {
429 ssize_t n = 0;
431 sdb_conn_set_ctx(conn);
433 while (42) {
434 ssize_t status = connection_read(conn);
436 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
437 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
438 command_init(conn);
439 if ((conn->cmd != CONNECTION_IDLE)
440 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
441 command_handle(conn);
443 /* remove the command from the buffer */
444 if (conn->cmd_len)
445 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
446 conn->cmd = CONNECTION_IDLE;
447 conn->cmd_len = 0;
448 }
450 if (status <= 0)
451 break;
453 n += status;
454 }
456 sdb_conn_set_ctx(NULL);
457 return n;
458 } /* sdb_connection_read */
460 ssize_t
461 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
462 uint32_t msg_len, const char *msg)
463 {
464 ssize_t status;
466 if ((! conn) || (conn->fd < 0))
467 return -1;
469 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
470 if (status < 0) {
471 char errbuf[1024];
473 /* tell other code that there was a problem and, more importantly,
474 * make sure we don't try to send further logs to the connection */
475 close(conn->fd);
476 conn->fd = -1;
477 conn->ready = 0;
479 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
480 "(code: %u, len: %u) to client: %s", code, msg_len,
481 sdb_strerror(errno, errbuf, sizeof(errbuf)));
482 }
483 return status;
484 } /* sdb_connection_send */
486 int
487 sdb_connection_ping(sdb_conn_t *conn)
488 {
489 if ((! conn) || (conn->cmd != CONNECTION_PING))
490 return -1;
492 /* we're alive */
493 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
494 return 0;
495 } /* sdb_connection_ping */
497 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */