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 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 %s", obj->name);
144 if (conn->fd >= 0)
145 close(conn->fd);
146 conn->fd = -1;
148 if (conn->username)
149 free(conn->username);
150 conn->username = NULL;
152 sdb_strbuf_destroy(conn->buf);
153 conn->buf = NULL;
154 sdb_strbuf_destroy(conn->errbuf);
155 conn->errbuf = NULL;
156 } /* connection_destroy */
158 static sdb_type_t connection_type = {
159 /* size = */ sizeof(sdb_conn_t),
160 /* init = */ connection_init,
161 /* destroy = */ connection_destroy,
162 };
164 /*
165 * private helper functions
166 */
168 static void
169 sdb_conn_ctx_destructor(void *c)
170 {
171 sdb_object_t *conn = c;
173 if (! conn)
174 return;
175 sdb_object_deref(conn);
176 } /* sdb_conn_ctx_destructor */
178 static void
179 sdb_conn_ctx_init(void)
180 {
181 if (conn_ctx_key_initialized)
182 return;
184 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
185 conn_ctx_key_initialized = 1;
186 } /* sdb_conn_ctx_init */
188 static void
189 sdb_conn_set_ctx(sdb_conn_t *conn)
190 {
191 sdb_conn_t *old;
193 sdb_conn_ctx_init();
195 old = pthread_getspecific(conn_ctx_key);
196 if (old)
197 sdb_object_deref(SDB_OBJ(old));
198 if (conn)
199 sdb_object_ref(SDB_OBJ(conn));
200 pthread_setspecific(conn_ctx_key, conn);
201 } /* sdb_conn_set_ctx */
203 static sdb_conn_t *
204 sdb_conn_get_ctx(void)
205 {
206 if (! conn_ctx_key_initialized)
207 return NULL;
208 return pthread_getspecific(conn_ctx_key);
209 } /* sdb_conn_get_ctx */
211 /*
212 * connection handler functions
213 */
215 /*
216 * connection_log:
217 * Send a log message originating from the current thread to the client.
218 */
219 static int
220 connection_log(int prio, const char *msg,
221 sdb_object_t __attribute__((unused)) *user_data)
222 {
223 sdb_conn_t *conn;
225 conn = sdb_conn_get_ctx();
226 /* no connection associated to this thread
227 * or user not authenticated yet => don't leak any information */
228 if ((! conn) || (! conn->username))
229 return 0;
231 /* XXX: make the log-level configurable by the client at runtime */
232 if (prio >= SDB_LOG_DEBUG)
233 return 0;
235 /* TODO: Use CONNECTION_LOG_<prio>? */
236 if (sdb_connection_send(conn, CONNECTION_LOG,
237 (uint32_t)strlen(msg), msg) < 0)
238 return -1;
239 return 0;
240 } /* connection_log */
242 static uint32_t
243 connection_get_int32(sdb_conn_t *conn, size_t offset)
244 {
245 const char *data;
246 uint32_t n;
248 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
250 data = sdb_strbuf_string(conn->buf);
251 memcpy(&n, data + offset, sizeof(n));
252 n = ntohl(n);
253 return n;
254 } /* connection_get_int32 */
256 static int
257 command_handle(sdb_conn_t *conn)
258 {
259 int status = -1;
261 assert(conn && (conn->cmd != CONNECTION_IDLE));
262 assert(! conn->skip_len);
264 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
265 conn->cmd, conn->cmd_len);
267 if (conn->cmd == CONNECTION_PING)
268 status = sdb_connection_ping(conn);
269 else if (conn->cmd == CONNECTION_STARTUP)
270 status = sdb_fe_session_start(conn);
271 else if (conn->cmd == CONNECTION_QUERY)
272 status = sdb_fe_query(conn);
273 else if (conn->cmd == CONNECTION_FETCH)
274 status = sdb_fe_fetch(conn);
275 else if (conn->cmd == CONNECTION_LIST)
276 status = sdb_fe_list(conn);
277 else if (conn->cmd == CONNECTION_LOOKUP)
278 status = sdb_fe_lookup(conn);
279 else {
280 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
281 conn->cmd);
282 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
283 status = -1;
284 }
286 if (status)
287 sdb_connection_send(conn, CONNECTION_ERROR,
288 (uint32_t)sdb_strbuf_len(conn->errbuf),
289 sdb_strbuf_string(conn->errbuf));
290 return status;
291 } /* command_handle */
293 /* initialize the connection state information */
294 static int
295 command_init(sdb_conn_t *conn)
296 {
297 const char *errmsg = NULL;
299 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
301 if (conn->skip_len)
302 return -1;
304 /* reset */
305 sdb_strbuf_clear(conn->errbuf);
307 conn->cmd = connection_get_int32(conn, 0);
308 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
310 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
312 if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP))
313 errmsg = "Authentication required";
314 else if (conn->cmd == CONNECTION_IDLE)
315 errmsg = "Invalid command 0";
317 if (errmsg) {
318 size_t len = sdb_strbuf_len(conn->buf);
320 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
321 sdb_connection_send(conn, CONNECTION_ERROR,
322 (uint32_t)strlen(errmsg), errmsg);
323 conn->skip_len += conn->cmd_len;
324 conn->cmd = CONNECTION_IDLE;
325 conn->cmd_len = 0;
327 if (len > conn->skip_len)
328 len = conn->skip_len;
329 sdb_strbuf_skip(conn->buf, 0, len);
330 conn->skip_len -= len;
331 /* connection_read will handle anything else */
332 }
333 return 0;
334 } /* command_init */
336 /* returns negative value on error, 0 on EOF, number of octets else */
337 static ssize_t
338 connection_read(sdb_conn_t *conn)
339 {
340 ssize_t n = 0;
342 if ((! conn) || (conn->fd < 0))
343 return -1;
345 while (42) {
346 ssize_t status;
348 errno = 0;
349 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
350 if (status < 0) {
351 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
352 break;
354 close(conn->fd);
355 conn->fd = -1;
356 return (int)status;
357 }
358 else if (! status) /* EOF */
359 break;
361 if (conn->skip_len) {
362 size_t len = (size_t)status < conn->skip_len
363 ? (size_t)status : conn->skip_len;
364 sdb_strbuf_skip(conn->buf, 0, len);
365 conn->skip_len -= len;
366 }
368 n += status;
370 /* give the main loop a chance to execute commands (and free up buffer
371 * space) on large amounts of incoming traffic */
372 if (n > 1024 * 1024)
373 break;
374 }
376 return n;
377 } /* connection_read */
379 /*
380 * public API
381 */
383 int
384 sdb_connection_enable_logging(void)
385 {
386 return sdb_plugin_register_log("connection-logger", connection_log,
387 /* user_data = */ NULL);
388 } /* sdb_connection_enable_logging */
390 sdb_conn_t *
391 sdb_connection_accept(int fd)
392 {
393 if (fd < 0)
394 return NULL;
396 /* the placeholder will be replaced with the accepted file
397 * descriptor when initializing the object */
398 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
399 connection_type, fd));
400 } /* sdb_connection_create */
402 void
403 sdb_connection_close(sdb_conn_t *conn)
404 {
405 if (! conn)
406 return;
408 /* close the connection even if someone else still references it */
409 if (conn->fd >= 0)
410 close(conn->fd);
411 conn->fd = -1;
413 sdb_object_deref(SDB_OBJ(conn));
414 } /* sdb_connection_close */
416 ssize_t
417 sdb_connection_read(sdb_conn_t *conn)
418 {
419 ssize_t n = 0;
421 sdb_conn_set_ctx(conn);
423 while (42) {
424 ssize_t status = connection_read(conn);
426 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
427 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
428 command_init(conn);
429 if ((conn->cmd != CONNECTION_IDLE)
430 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
431 command_handle(conn);
433 /* remove the command from the buffer */
434 if (conn->cmd_len)
435 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
436 conn->cmd = CONNECTION_IDLE;
437 conn->cmd_len = 0;
438 }
440 if (status <= 0)
441 break;
443 n += status;
444 }
446 sdb_conn_set_ctx(NULL);
447 return n;
448 } /* sdb_connection_read */
450 ssize_t
451 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
452 uint32_t msg_len, const char *msg)
453 {
454 ssize_t status;
456 if ((! conn) || (conn->fd < 0))
457 return -1;
459 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
460 if (status < 0) {
461 char errbuf[1024];
463 /* tell other code that there was a problem and, more importantly,
464 * make sure we don't try to send further logs to the connection */
465 close(conn->fd);
466 conn->fd = -1;
468 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
469 "(code: %u, len: %u) to client: %s", code, msg_len,
470 sdb_strerror(errno, errbuf, sizeof(errbuf)));
471 }
472 return status;
473 } /* sdb_connection_send */
475 int
476 sdb_connection_ping(sdb_conn_t *conn)
477 {
478 if ((! conn) || (conn->cmd != CONNECTION_PING))
479 return -1;
481 /* we're alive */
482 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
483 return 0;
484 } /* sdb_connection_ping */
486 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */