Code

frontend: Added the SERVER_VERSION command.
[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 <sys/socket.h>
48 #include <sys/un.h>
50 #include <stdlib.h>
51 #include <string.h>
53 #include <pthread.h>
54 #include <netdb.h>
56 /*
57  * private variables
58  */
60 static pthread_key_t conn_ctx_key;
61 static bool          conn_ctx_key_initialized = 0;
63 /*
64  * private types
65  */
67 /* name of connection objects */
68 #define CONN_FD_PREFIX "conn#"
69 #define CONN_FD_PLACEHOLDER "XXXXXXX"
71 static ssize_t
72 conn_read(sdb_conn_t *conn, size_t len)
73 {
74         return sdb_strbuf_read(conn->buf, conn->fd, len);
75 } /* conn_read */
77 static ssize_t
78 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
79 {
80         return sdb_write(conn->fd, len, buf);
81 } /* conn_write */
83 static int
84 connection_init(sdb_object_t *obj, va_list ap)
85 {
86         sdb_conn_t *conn;
87         int sock_fd;
88         int sock_fl;
90         assert(obj);
91         conn = CONN(obj);
93         sock_fd = va_arg(ap, int);
95         conn->buf = sdb_strbuf_create(/* size = */ 128);
96         if (! conn->buf) {
97                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
98                                 "for a new connection");
99                 return -1;
100         }
101         conn->errbuf = sdb_strbuf_create(0);
102         if (! conn->errbuf) {
103                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
104                                 "for a new connection");
105                 return -1;
106         }
108         conn->client_addr_len = sizeof(conn->client_addr);
109         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
110                         &conn->client_addr_len);
112         if (conn->fd < 0) {
113                 char buf[1024];
114                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
115                                 "connection: %s", sdb_strerror(errno,
116                                         buf, sizeof(buf)));
117                 return -1;
118         }
120         /* update the object name */
121         snprintf(obj->name + strlen(CONN_FD_PREFIX),
122                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
124         /* defaults */
125         conn->read = conn_read;
126         conn->write = conn_write;
127         conn->finish = NULL;
128         conn->ssl_session = NULL;
130         sock_fl = fcntl(conn->fd, F_GETFL);
131         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
132                 char buf[1024];
133                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
134                                 "to non-blocking mode: %s", conn->fd,
135                                 sdb_strerror(errno, buf, sizeof(buf)));
136                 return -1;
137         }
139         conn->username = NULL;
140         conn->ready = 0;
142         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
143                         conn->fd);
145         conn->cmd = SDB_CONNECTION_IDLE;
146         conn->cmd_len = 0;
147         conn->skip_len = 0;
148         return 0;
149 } /* connection_init */
151 static void
152 connection_destroy(sdb_object_t *obj)
154         sdb_conn_t *conn;
155         size_t len;
157         assert(obj);
158         conn = CONN(obj);
160         conn->ready = 0;
162         if (conn->finish)
163                 conn->finish(conn);
164         conn->finish = NULL;
166         if (conn->buf) {
167                 len = sdb_strbuf_len(conn->buf);
168                 if (len)
169                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
170                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
171         }
173         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
174         sdb_connection_close(conn);
176         if (conn->username)
177                 free(conn->username);
178         conn->username = NULL;
180         sdb_strbuf_destroy(conn->buf);
181         conn->buf = NULL;
182         sdb_strbuf_destroy(conn->errbuf);
183         conn->errbuf = NULL;
184 } /* connection_destroy */
186 static sdb_type_t connection_type = {
187         /* size = */ sizeof(sdb_conn_t),
188         /* init = */ connection_init,
189         /* destroy = */ connection_destroy,
190 };
192 /*
193  * private helper functions
194  */
196 static void
197 sdb_conn_ctx_destructor(void *c)
199         sdb_object_t *conn = c;
201         if (! conn)
202                 return;
203         sdb_object_deref(conn);
204 } /* sdb_conn_ctx_destructor */
206 static void
207 sdb_conn_ctx_init(void)
209         if (conn_ctx_key_initialized)
210                 return;
212         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
213         conn_ctx_key_initialized = 1;
214 } /* sdb_conn_ctx_init */
216 static void
217 sdb_conn_set_ctx(sdb_conn_t *conn)
219         sdb_conn_t *old;
221         sdb_conn_ctx_init();
223         old = pthread_getspecific(conn_ctx_key);
224         if (old)
225                 sdb_object_deref(SDB_OBJ(old));
226         if (conn)
227                 sdb_object_ref(SDB_OBJ(conn));
228         pthread_setspecific(conn_ctx_key, conn);
229 } /* sdb_conn_set_ctx */
231 static sdb_conn_t *
232 sdb_conn_get_ctx(void)
234         if (! conn_ctx_key_initialized)
235                 return NULL;
236         return pthread_getspecific(conn_ctx_key);
237 } /* sdb_conn_get_ctx */
239 /*
240  * connection handler functions
241  */
243 /*
244  * connection_log:
245  * Send a log message originating from the current thread to the client.
246  */
247 static int
248 connection_log(int prio, const char *msg,
249                 sdb_object_t __attribute__((unused)) *user_data)
251         uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
252         uint32_t p = htonl((uint32_t)prio);
253         char tmp[len + 1];
255         sdb_conn_t *conn;
257         conn = sdb_conn_get_ctx();
258         /* no connection associated to this thread
259          * or startup not done yet => don't leak any information */
260         if ((! conn) || (! conn->ready))
261                 return 0;
263         /* XXX: make the log-level configurable by the client at runtime */
264         if (prio >= SDB_LOG_DEBUG)
265                 return 0;
267         memcpy(tmp, &p, sizeof(p));
268         strcpy(tmp + sizeof(p), msg);
270         if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
271                 return -1;
272         return 0;
273 } /* connection_log */
275 static int
276 command_handle(sdb_conn_t *conn)
278         int status = -1;
280         assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
281         assert(! conn->skip_len);
283         if (conn->cmd == SDB_CONNECTION_PING)
284                 status = sdb_connection_ping(conn);
285         else if (conn->cmd == SDB_CONNECTION_STARTUP)
286                 status = sdb_fe_session_start(conn);
288         else if (conn->cmd == SDB_CONNECTION_QUERY)
289                 status = sdb_fe_query(conn);
290         else if (conn->cmd == SDB_CONNECTION_FETCH)
291                 status = sdb_fe_fetch(conn);
292         else if (conn->cmd == SDB_CONNECTION_LIST)
293                 status = sdb_fe_list(conn);
294         else if (conn->cmd == SDB_CONNECTION_LOOKUP)
295                 status = sdb_fe_lookup(conn);
296         else if (conn->cmd == SDB_CONNECTION_STORE)
297                 status = sdb_fe_store(conn);
299         else if (conn->cmd == SDB_CONNECTION_SERVER_VERSION)
300                 status = sdb_connection_server_version(conn);
302         else {
303                 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
304                                 conn->cmd);
305                 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
306                 status = -1;
307         }
309         if (status) {
310                 if (! sdb_strbuf_len(conn->errbuf))
311                         sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
312                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
313                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
314                                 sdb_strbuf_string(conn->errbuf));
315         }
316         return status;
317 } /* command_handle */
319 /* initialize the connection state information */
320 static int
321 command_init(sdb_conn_t *conn)
323         const char *errmsg = NULL;
325         assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
327         if (conn->skip_len)
328                 return -1;
330         /* reset */
331         sdb_strbuf_clear(conn->errbuf);
333         if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
334                                 &conn->cmd, &conn->cmd_len) < 0)
335                 return -1;
336         sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
338         if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
339                 errmsg = "Authentication required";
340         else if (conn->cmd == SDB_CONNECTION_IDLE)
341                 errmsg = "Invalid command 0";
343         if (errmsg) {
344                 size_t len = sdb_strbuf_len(conn->buf);
346                 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
347                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
348                                 (uint32_t)strlen(errmsg), errmsg);
349                 conn->skip_len += conn->cmd_len;
350                 conn->cmd = SDB_CONNECTION_IDLE;
351                 conn->cmd_len = 0;
353                 if (len > conn->skip_len)
354                         len = conn->skip_len;
355                 sdb_strbuf_skip(conn->buf, 0, len);
356                 conn->skip_len -= len;
357                 /* connection_read will handle anything else */
358         }
359         return 0;
360 } /* command_init */
362 /* returns negative value on error, 0 on EOF, number of octets else */
363 static ssize_t
364 connection_read(sdb_conn_t *conn)
366         ssize_t n = 0;
368         if ((! conn) || (conn->fd < 0))
369                 return -1;
371         while (42) {
372                 ssize_t status;
374                 errno = 0;
375                 status = conn->read(conn, 1024);
376                 if (status < 0) {
377                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
378                                 break;
380                         sdb_connection_close(conn);
381                         return (int)status;
382                 }
383                 else if (! status) /* EOF */
384                         break;
386                 if (conn->skip_len) {
387                         size_t len = (size_t)status < conn->skip_len
388                                 ? (size_t)status : conn->skip_len;
389                         sdb_strbuf_skip(conn->buf, 0, len);
390                         conn->skip_len -= len;
391                 }
393                 n += status;
395                 /* give the main loop a chance to execute commands (and free up buffer
396                  * space) on large amounts of incoming traffic */
397                 if (n > 1024 * 1024)
398                         break;
399         }
401         return n;
402 } /* connection_read */
404 /*
405  * public API
406  */
408 int
409 sdb_connection_enable_logging(void)
411         return sdb_plugin_register_log("connection-logger", connection_log,
412                         /* user_data = */ NULL);
413 } /* sdb_connection_enable_logging */
415 sdb_conn_t *
416 sdb_connection_accept(int fd, sdb_conn_setup_cb setup, void *user_data)
418         sdb_conn_t *conn;
419         const char *peer = "unknown";
421         if (fd < 0)
422                 return NULL;
424         /* the placeholder will be replaced with the accepted file
425          * descriptor when initializing the object */
426         conn = CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
427                                 connection_type, fd));
428         if (setup && (setup(conn, user_data) < 0)) {
429                 sdb_object_deref(SDB_OBJ(conn));
430                 return NULL;
431         }
433         if (conn->username)
434                 peer = conn->username;
436         if (conn->client_addr.ss_family == AF_UNIX) {
437                 sdb_log(SDB_LOG_INFO,
438                                 "frontend: Accepted connection from peer %s", peer);
439         }
440         else {
441                 char host[1024] = "<unknown>", port[32] = "";
442                 getnameinfo((struct sockaddr *)&conn->client_addr,
443                                 conn->client_addr_len, host, sizeof(host), port, sizeof(port),
444                                 NI_NUMERICHOST | NI_NUMERICSERV);
445                 sdb_log(SDB_LOG_INFO, "frontend: Accepted connection from "
446                                 "peer %s at %s:%s", peer, host, port);
447         }
448         return conn;
449 } /* sdb_connection_create */
451 void
452 sdb_connection_close(sdb_conn_t *conn)
454         if (! conn)
455                 return;
457         if (conn->finish)
458                 conn->finish(conn);
459         conn->finish = NULL;
461         /* close the connection even if someone else still references it */
462         if (conn->fd >= 0)
463                 close(conn->fd);
464         conn->fd = -1;
465 } /* sdb_connection_close */
467 ssize_t
468 sdb_connection_handle(sdb_conn_t *conn)
470         ssize_t n = 0;
472         sdb_conn_set_ctx(conn);
474         while (42) {
475                 ssize_t status = connection_read(conn);
477                 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
478                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
479                         command_init(conn);
480                 if ((conn->cmd != SDB_CONNECTION_IDLE)
481                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
482                         command_handle(conn);
484                         /* remove the command from the buffer */
485                         if (conn->cmd_len)
486                                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
487                         conn->cmd = SDB_CONNECTION_IDLE;
488                         conn->cmd_len = 0;
489                 }
491                 if (status <= 0)
492                         break;
494                 n += status;
495         }
497         sdb_conn_set_ctx(NULL);
498         return n;
499 } /* sdb_connection_handle */
501 ssize_t
502 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
503                 uint32_t msg_len, const char *msg)
505         char buf[2 * sizeof(uint32_t) + msg_len];
506         ssize_t status;
508         if ((! conn) || (conn->fd < 0))
509                 return -1;
510         if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
511                 return -1;
513         status = conn->write(conn, buf, sizeof(buf));
514         if (status < 0) {
515                 char errbuf[1024];
517                 /* tell other code that there was a problem and, more importantly,
518                  * make sure we don't try to send further logs to the connection */
519                 sdb_connection_close(conn);
520                 conn->ready = 0;
522                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
523                                 "(code: %u, len: %u) to client: %s", code, msg_len,
524                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
525         }
526         return status;
527 } /* sdb_connection_send */
529 int
530 sdb_connection_ping(sdb_conn_t *conn)
532         if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
533                 return -1;
535         /* we're alive */
536         sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
537         return 0;
538 } /* sdb_connection_ping */
540 int
541 sdb_connection_server_version(sdb_conn_t *conn)
543         char msg[sizeof(uint32_t) + strlen(SDB_VERSION_EXTRA) + 1];
545         if ((! conn) || (conn->cmd != SDB_CONNECTION_SERVER_VERSION))
546                 return -1;
548         sdb_proto_marshal_int32(msg, sizeof(msg), (uint32_t)SDB_VERSION);
549         strncpy(msg + sizeof(uint32_t), SDB_VERSION_EXTRA,
550                         sizeof(msg) - sizeof(uint32_t));
551         sdb_connection_send(conn, SDB_CONNECTION_OK, (uint32_t)sizeof(msg), msg);
552         return 0;
553 } /* sdb_connection_server_version */
555 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */