a7414017284a558cfc0000dfdd8ab5d80d3d1c5c
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 sdb_conn_t *conn;
227 conn = sdb_conn_get_ctx();
228 /* no connection associated to this thread
229 * or startup not done yet => don't leak any information */
230 if ((! conn) || (! conn->ready))
231 return 0;
233 /* XXX: make the log-level configurable by the client at runtime */
234 if (prio >= SDB_LOG_DEBUG)
235 return 0;
237 /* TODO: Use CONNECTION_LOG_<prio>? */
238 if (sdb_connection_send(conn, CONNECTION_LOG,
239 (uint32_t)strlen(msg), msg) < 0)
240 return -1;
241 return 0;
242 } /* connection_log */
244 static uint32_t
245 connection_get_int32(sdb_conn_t *conn, size_t offset)
246 {
247 const char *data;
248 uint32_t n;
250 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
252 data = sdb_strbuf_string(conn->buf);
253 memcpy(&n, data + offset, sizeof(n));
254 n = ntohl(n);
255 return n;
256 } /* connection_get_int32 */
258 static int
259 command_handle(sdb_conn_t *conn)
260 {
261 int status = -1;
263 assert(conn && (conn->cmd != CONNECTION_IDLE));
264 assert(! conn->skip_len);
266 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
267 conn->cmd, conn->cmd_len);
269 if (conn->cmd == CONNECTION_PING)
270 status = sdb_connection_ping(conn);
271 else if (conn->cmd == CONNECTION_STARTUP)
272 status = sdb_fe_session_start(conn);
273 else if (conn->cmd == CONNECTION_QUERY)
274 status = sdb_fe_query(conn);
275 else if (conn->cmd == CONNECTION_FETCH)
276 status = sdb_fe_fetch(conn);
277 else if (conn->cmd == CONNECTION_LIST)
278 status = sdb_fe_list(conn);
279 else if (conn->cmd == CONNECTION_LOOKUP)
280 status = sdb_fe_lookup(conn);
281 else {
282 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
283 conn->cmd);
284 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
285 status = -1;
286 }
288 if (status)
289 sdb_connection_send(conn, CONNECTION_ERROR,
290 (uint32_t)sdb_strbuf_len(conn->errbuf),
291 sdb_strbuf_string(conn->errbuf));
292 return status;
293 } /* command_handle */
295 /* initialize the connection state information */
296 static int
297 command_init(sdb_conn_t *conn)
298 {
299 const char *errmsg = NULL;
301 assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
303 if (conn->skip_len)
304 return -1;
306 /* reset */
307 sdb_strbuf_clear(conn->errbuf);
309 conn->cmd = connection_get_int32(conn, 0);
310 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
312 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
314 if ((! conn->ready) && (conn->cmd != CONNECTION_STARTUP))
315 errmsg = "Authentication required";
316 else if (conn->cmd == CONNECTION_IDLE)
317 errmsg = "Invalid command 0";
319 if (errmsg) {
320 size_t len = sdb_strbuf_len(conn->buf);
322 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
323 sdb_connection_send(conn, CONNECTION_ERROR,
324 (uint32_t)strlen(errmsg), errmsg);
325 conn->skip_len += conn->cmd_len;
326 conn->cmd = CONNECTION_IDLE;
327 conn->cmd_len = 0;
329 if (len > conn->skip_len)
330 len = conn->skip_len;
331 sdb_strbuf_skip(conn->buf, 0, len);
332 conn->skip_len -= len;
333 /* connection_read will handle anything else */
334 }
335 return 0;
336 } /* command_init */
338 /* returns negative value on error, 0 on EOF, number of octets else */
339 static ssize_t
340 connection_read(sdb_conn_t *conn)
341 {
342 ssize_t n = 0;
344 if ((! conn) || (conn->fd < 0))
345 return -1;
347 while (42) {
348 ssize_t status;
350 errno = 0;
351 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
352 if (status < 0) {
353 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
354 break;
356 close(conn->fd);
357 conn->fd = -1;
358 return (int)status;
359 }
360 else if (! status) /* EOF */
361 break;
363 if (conn->skip_len) {
364 size_t len = (size_t)status < conn->skip_len
365 ? (size_t)status : conn->skip_len;
366 sdb_strbuf_skip(conn->buf, 0, len);
367 conn->skip_len -= len;
368 }
370 n += status;
372 /* give the main loop a chance to execute commands (and free up buffer
373 * space) on large amounts of incoming traffic */
374 if (n > 1024 * 1024)
375 break;
376 }
378 return n;
379 } /* connection_read */
381 /*
382 * public API
383 */
385 int
386 sdb_connection_enable_logging(void)
387 {
388 return sdb_plugin_register_log("connection-logger", connection_log,
389 /* user_data = */ NULL);
390 } /* sdb_connection_enable_logging */
392 sdb_conn_t *
393 sdb_connection_accept(int fd)
394 {
395 if (fd < 0)
396 return NULL;
398 /* the placeholder will be replaced with the accepted file
399 * descriptor when initializing the object */
400 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
401 connection_type, fd));
402 } /* sdb_connection_create */
404 void
405 sdb_connection_close(sdb_conn_t *conn)
406 {
407 if (! conn)
408 return;
410 /* close the connection even if someone else still references it */
411 if (conn->fd >= 0)
412 close(conn->fd);
413 conn->fd = -1;
415 sdb_object_deref(SDB_OBJ(conn));
416 } /* sdb_connection_close */
418 ssize_t
419 sdb_connection_read(sdb_conn_t *conn)
420 {
421 ssize_t n = 0;
423 sdb_conn_set_ctx(conn);
425 while (42) {
426 ssize_t status = connection_read(conn);
428 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
429 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
430 command_init(conn);
431 if ((conn->cmd != CONNECTION_IDLE)
432 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
433 command_handle(conn);
435 /* remove the command from the buffer */
436 if (conn->cmd_len)
437 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
438 conn->cmd = CONNECTION_IDLE;
439 conn->cmd_len = 0;
440 }
442 if (status <= 0)
443 break;
445 n += status;
446 }
448 sdb_conn_set_ctx(NULL);
449 return n;
450 } /* sdb_connection_read */
452 ssize_t
453 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
454 uint32_t msg_len, const char *msg)
455 {
456 ssize_t status;
458 if ((! conn) || (conn->fd < 0))
459 return -1;
461 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
462 if (status < 0) {
463 char errbuf[1024];
465 /* tell other code that there was a problem and, more importantly,
466 * make sure we don't try to send further logs to the connection */
467 close(conn->fd);
468 conn->fd = -1;
469 conn->ready = 0;
471 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
472 "(code: %u, len: %u) to client: %s", code, msg_len,
473 sdb_strerror(errno, errbuf, sizeof(errbuf)));
474 }
475 return status;
476 } /* sdb_connection_send */
478 int
479 sdb_connection_ping(sdb_conn_t *conn)
480 {
481 if ((! conn) || (conn->cmd != CONNECTION_PING))
482 return -1;
484 /* we're alive */
485 sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
486 return 0;
487 } /* sdb_connection_ping */
489 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */