Code

frontend: Add support for TCP connections.
[sysdb.git] / src / frontend / connection.c
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 #ifdef HAVE_CONFIG_H
29 #       include "config.h"
30 #endif
32 #include "sysdb.h"
33 #include "core/object.h"
34 #include "core/plugin.h"
35 #include "frontend/connection-private.h"
36 #include "utils/error.h"
37 #include "utils/strbuf.h"
38 #include "utils/proto.h"
39 #include "utils/os.h"
41 #include <assert.h>
42 #include <errno.h>
44 #include <arpa/inet.h>
45 #include <fcntl.h>
47 #include <stdlib.h>
48 #include <string.h>
50 #include <pthread.h>
52 /*
53  * private variables
54  */
56 static pthread_key_t conn_ctx_key;
57 static bool          conn_ctx_key_initialized = 0;
59 /*
60  * private types
61  */
63 /* name of connection objects */
64 #define CONN_FD_PREFIX "conn#"
65 #define CONN_FD_PLACEHOLDER "XXXXXXX"
67 static ssize_t
68 conn_read(sdb_conn_t *conn, size_t len)
69 {
70         return sdb_strbuf_read(conn->buf, conn->fd, len);
71 } /* conn_read */
73 static ssize_t
74 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
75 {
76         return sdb_write(conn->fd, len, buf);
77 } /* conn_write */
79 static int
80 connection_init(sdb_object_t *obj, va_list ap)
81 {
82         sdb_conn_t *conn;
83         int sock_fd;
84         int sock_fl;
86         assert(obj);
87         conn = CONN(obj);
89         sock_fd = va_arg(ap, int);
91         conn->buf = sdb_strbuf_create(/* size = */ 128);
92         if (! conn->buf) {
93                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
94                                 "for a new connection");
95                 return -1;
96         }
97         conn->errbuf = sdb_strbuf_create(0);
98         if (! conn->errbuf) {
99                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
100                                 "for a new connection");
101                 return -1;
102         }
104         conn->client_addr_len = sizeof(conn->client_addr);
105         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
106                         &conn->client_addr_len);
108         if (conn->fd < 0) {
109                 char buf[1024];
110                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
111                                 "connection: %s", sdb_strerror(errno,
112                                         buf, sizeof(buf)));
113                 return -1;
114         }
116         /* update the object name */
117         snprintf(obj->name + strlen(CONN_FD_PREFIX),
118                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
120         /* defaults */
121         conn->read = conn_read;
122         conn->write = conn_write;
123         conn->finish = NULL;
124         conn->session = NULL;
126         sock_fl = fcntl(conn->fd, F_GETFL);
127         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
128                 char buf[1024];
129                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
130                                 "to non-blocking mode: %s", conn->fd,
131                                 sdb_strerror(errno, buf, sizeof(buf)));
132                 return -1;
133         }
135         conn->username = NULL;
136         conn->ready = 0;
138         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
139                         conn->fd);
141         conn->cmd = SDB_CONNECTION_IDLE;
142         conn->cmd_len = 0;
143         conn->skip_len = 0;
144         return 0;
145 } /* connection_init */
147 static void
148 connection_destroy(sdb_object_t *obj)
150         sdb_conn_t *conn;
151         size_t len;
153         assert(obj);
154         conn = CONN(obj);
156         conn->ready = 0;
158         if (conn->finish)
159                 conn->finish(conn);
160         conn->finish = NULL;
162         if (conn->buf) {
163                 len = sdb_strbuf_len(conn->buf);
164                 if (len)
165                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
166                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
167         }
169         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
170         sdb_connection_close(conn);
172         if (conn->username)
173                 free(conn->username);
174         conn->username = NULL;
176         sdb_strbuf_destroy(conn->buf);
177         conn->buf = NULL;
178         sdb_strbuf_destroy(conn->errbuf);
179         conn->errbuf = NULL;
180 } /* connection_destroy */
182 static sdb_type_t connection_type = {
183         /* size = */ sizeof(sdb_conn_t),
184         /* init = */ connection_init,
185         /* destroy = */ connection_destroy,
186 };
188 /*
189  * private helper functions
190  */
192 static void
193 sdb_conn_ctx_destructor(void *c)
195         sdb_object_t *conn = c;
197         if (! conn)
198                 return;
199         sdb_object_deref(conn);
200 } /* sdb_conn_ctx_destructor */
202 static void
203 sdb_conn_ctx_init(void)
205         if (conn_ctx_key_initialized)
206                 return;
208         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
209         conn_ctx_key_initialized = 1;
210 } /* sdb_conn_ctx_init */
212 static void
213 sdb_conn_set_ctx(sdb_conn_t *conn)
215         sdb_conn_t *old;
217         sdb_conn_ctx_init();
219         old = pthread_getspecific(conn_ctx_key);
220         if (old)
221                 sdb_object_deref(SDB_OBJ(old));
222         if (conn)
223                 sdb_object_ref(SDB_OBJ(conn));
224         pthread_setspecific(conn_ctx_key, conn);
225 } /* sdb_conn_set_ctx */
227 static sdb_conn_t *
228 sdb_conn_get_ctx(void)
230         if (! conn_ctx_key_initialized)
231                 return NULL;
232         return pthread_getspecific(conn_ctx_key);
233 } /* sdb_conn_get_ctx */
235 /*
236  * connection handler functions
237  */
239 /*
240  * connection_log:
241  * Send a log message originating from the current thread to the client.
242  */
243 static int
244 connection_log(int prio, const char *msg,
245                 sdb_object_t __attribute__((unused)) *user_data)
247         uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
248         uint32_t p = htonl((uint32_t)prio);
249         char tmp[len + 1];
251         sdb_conn_t *conn;
253         conn = sdb_conn_get_ctx();
254         /* no connection associated to this thread
255          * or startup not done yet => don't leak any information */
256         if ((! conn) || (! conn->ready))
257                 return 0;
259         /* XXX: make the log-level configurable by the client at runtime */
260         if (prio >= SDB_LOG_DEBUG)
261                 return 0;
263         memcpy(tmp, &p, sizeof(p));
264         strcpy(tmp + sizeof(p), msg);
266         if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
267                 return -1;
268         return 0;
269 } /* connection_log */
271 static int
272 command_handle(sdb_conn_t *conn)
274         int status = -1;
276         assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
277         assert(! conn->skip_len);
279         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
280                         conn->cmd, conn->cmd_len);
282         if (conn->cmd == SDB_CONNECTION_PING)
283                 status = sdb_connection_ping(conn);
284         else if (conn->cmd == SDB_CONNECTION_STARTUP)
285                 status = sdb_fe_session_start(conn);
286         else if (conn->cmd == SDB_CONNECTION_QUERY)
287                 status = sdb_fe_query(conn);
288         else if (conn->cmd == SDB_CONNECTION_FETCH)
289                 status = sdb_fe_fetch(conn);
290         else if (conn->cmd == SDB_CONNECTION_LIST)
291                 status = sdb_fe_list(conn);
292         else if (conn->cmd == SDB_CONNECTION_LOOKUP)
293                 status = sdb_fe_lookup(conn);
294         else if (conn->cmd == SDB_CONNECTION_STORE)
295                 status = sdb_fe_store(conn);
296         else {
297                 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
298                                 conn->cmd);
299                 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
300                 status = -1;
301         }
303         if (status) {
304                 if (! sdb_strbuf_len(conn->errbuf))
305                         sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
306                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
307                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
308                                 sdb_strbuf_string(conn->errbuf));
309         }
310         return status;
311 } /* command_handle */
313 /* initialize the connection state information */
314 static int
315 command_init(sdb_conn_t *conn)
317         const char *errmsg = NULL;
319         assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
321         if (conn->skip_len)
322                 return -1;
324         /* reset */
325         sdb_strbuf_clear(conn->errbuf);
327         if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
328                                 &conn->cmd, &conn->cmd_len) < 0)
329                 return -1;
330         sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
332         if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
333                 errmsg = "Authentication required";
334         else if (conn->cmd == SDB_CONNECTION_IDLE)
335                 errmsg = "Invalid command 0";
337         if (errmsg) {
338                 size_t len = sdb_strbuf_len(conn->buf);
340                 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
341                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
342                                 (uint32_t)strlen(errmsg), errmsg);
343                 conn->skip_len += conn->cmd_len;
344                 conn->cmd = SDB_CONNECTION_IDLE;
345                 conn->cmd_len = 0;
347                 if (len > conn->skip_len)
348                         len = conn->skip_len;
349                 sdb_strbuf_skip(conn->buf, 0, len);
350                 conn->skip_len -= len;
351                 /* connection_read will handle anything else */
352         }
353         return 0;
354 } /* command_init */
356 /* returns negative value on error, 0 on EOF, number of octets else */
357 static ssize_t
358 connection_read(sdb_conn_t *conn)
360         ssize_t n = 0;
362         if ((! conn) || (conn->fd < 0))
363                 return -1;
365         while (42) {
366                 ssize_t status;
368                 errno = 0;
369                 status = conn->read(conn, 1024);
370                 if (status < 0) {
371                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
372                                 break;
374                         sdb_connection_close(conn);
375                         return (int)status;
376                 }
377                 else if (! status) /* EOF */
378                         break;
380                 if (conn->skip_len) {
381                         size_t len = (size_t)status < conn->skip_len
382                                 ? (size_t)status : conn->skip_len;
383                         sdb_strbuf_skip(conn->buf, 0, len);
384                         conn->skip_len -= len;
385                 }
387                 n += status;
389                 /* give the main loop a chance to execute commands (and free up buffer
390                  * space) on large amounts of incoming traffic */
391                 if (n > 1024 * 1024)
392                         break;
393         }
395         return n;
396 } /* connection_read */
398 /*
399  * public API
400  */
402 int
403 sdb_connection_enable_logging(void)
405         return sdb_plugin_register_log("connection-logger", connection_log,
406                         /* user_data = */ NULL);
407 } /* sdb_connection_enable_logging */
409 sdb_conn_t *
410 sdb_connection_accept(int fd)
412         if (fd < 0)
413                 return NULL;
415         /* the placeholder will be replaced with the accepted file
416          * descriptor when initializing the object */
417         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
418                                 connection_type, fd));
419 } /* sdb_connection_create */
421 void
422 sdb_connection_close(sdb_conn_t *conn)
424         if (! conn)
425                 return;
427         if (conn->finish)
428                 conn->finish(conn);
429         conn->finish = NULL;
431         /* close the connection even if someone else still references it */
432         if (conn->fd >= 0)
433                 close(conn->fd);
434         conn->fd = -1;
435 } /* sdb_connection_close */
437 ssize_t
438 sdb_connection_handle(sdb_conn_t *conn)
440         ssize_t n = 0;
442         sdb_conn_set_ctx(conn);
444         while (42) {
445                 ssize_t status = connection_read(conn);
447                 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
448                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
449                         command_init(conn);
450                 if ((conn->cmd != SDB_CONNECTION_IDLE)
451                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
452                         command_handle(conn);
454                         /* remove the command from the buffer */
455                         if (conn->cmd_len)
456                                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
457                         conn->cmd = SDB_CONNECTION_IDLE;
458                         conn->cmd_len = 0;
459                 }
461                 if (status <= 0)
462                         break;
464                 n += status;
465         }
467         sdb_conn_set_ctx(NULL);
468         return n;
469 } /* sdb_connection_handle */
471 ssize_t
472 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
473                 uint32_t msg_len, const char *msg)
475         char buf[2 * sizeof(uint32_t) + msg_len];
476         ssize_t status;
478         if ((! conn) || (conn->fd < 0))
479                 return -1;
480         if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
481                 return -1;
483         status = conn->write(conn, buf, sizeof(buf));
484         if (status < 0) {
485                 char errbuf[1024];
487                 /* tell other code that there was a problem and, more importantly,
488                  * make sure we don't try to send further logs to the connection */
489                 sdb_connection_close(conn);
490                 conn->ready = 0;
492                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
493                                 "(code: %u, len: %u) to client: %s", code, msg_len,
494                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
495         }
496         return status;
497 } /* sdb_connection_send */
499 int
500 sdb_connection_ping(sdb_conn_t *conn)
502         if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
503                 return -1;
505         /* we're alive */
506         sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
507         return 0;
508 } /* sdb_connection_ping */
510 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */