Code

frontend: Send connection-related log messages to the client.
[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 #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;
120         /* update the object name */
121         snprintf(obj->name + strlen(CONN_FD_PREFIX),
122                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
123         return 0;
124 } /* connection_init */
126 static void
127 connection_destroy(sdb_object_t *obj)
129         sdb_conn_t *conn;
130         size_t len;
132         assert(obj);
133         conn = CONN(obj);
135         if (conn->buf) {
136                 len = sdb_strbuf_len(conn->buf);
137                 if (len)
138                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
139                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
140         }
142         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i",
143                         conn->fd);
144         close(conn->fd);
145         conn->fd = -1;
147         sdb_strbuf_destroy(conn->buf);
148         conn->buf = NULL;
149         sdb_strbuf_destroy(conn->errbuf);
150         conn->errbuf = NULL;
151 } /* connection_destroy */
153 static sdb_type_t connection_type = {
154         /* size = */ sizeof(sdb_conn_t),
155         /* init = */ connection_init,
156         /* destroy = */ connection_destroy,
157 };
159 /*
160  * private helper functions
161  */
163 static void
164 sdb_conn_ctx_destructor(void *c)
166         sdb_object_t *conn = c;
168         if (! conn)
169                 return;
170         sdb_object_deref(conn);
171 } /* sdb_conn_ctx_destructor */
173 static void
174 sdb_conn_ctx_init(void)
176         if (conn_ctx_key_initialized)
177                 return;
179         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
180         conn_ctx_key_initialized = 1;
181 } /* sdb_conn_ctx_init */
183 static void
184 sdb_conn_set_ctx(sdb_conn_t *conn)
186         sdb_conn_ctx_init();
187         if (conn)
188                 sdb_object_ref(SDB_OBJ(conn));
189         pthread_setspecific(conn_ctx_key, conn);
190 } /* sdb_conn_set_ctx */
192 static sdb_conn_t *
193 sdb_conn_get_ctx(void)
195         if (! conn_ctx_key_initialized)
196                 return NULL;
197         return pthread_getspecific(conn_ctx_key);
198 } /* sdb_conn_get_ctx */
200 /*
201  * connection handler functions
202  */
204 /*
205  * connection_log:
206  * Send a log message originating from the current thread to the client.
207  */
208 static int
209 connection_log(int __attribute__((unused)) prio, const char *msg,
210                 sdb_object_t __attribute__((unused)) *user_data)
212         sdb_conn_t *conn;
214         conn = sdb_conn_get_ctx();
215         /* no connection associated to this thread
216          * or user not authenticated yet => don't leak any information */
217         if ((! conn) || (! conn->username))
218                 return 0;
220         /* TODO: Use CONNECTION_LOG_<prio>? */
221         if (sdb_connection_send(conn, CONNECTION_LOG,
222                                 (uint32_t)strlen(msg), msg) < 0)
223                 return -1;
224         return 0;
225 } /* connection_log */
227 static uint32_t
228 connection_get_int32(sdb_conn_t *conn, size_t offset)
230         const char *data;
231         uint32_t n;
233         assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
235         data = sdb_strbuf_string(conn->buf);
236         memcpy(&n, data + offset, sizeof(n));
237         n = ntohl(n);
238         return n;
239 } /* connection_get_int32 */
241 static int
242 command_handle(sdb_conn_t *conn)
244         int status = -1;
246         assert(conn && (conn->cmd != CONNECTION_IDLE));
248         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
249                         conn->cmd, conn->cmd_len);
251         if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP)) {
252                 const char *errmsg = "Authentication required";
253                 sdb_connection_send(conn, CONNECTION_ERROR,
254                                 (uint32_t)strlen(errmsg), errmsg);
255                 return -1;
256         }
258         /* reset */
259         sdb_strbuf_sprintf(conn->errbuf, "");
261         switch (conn->cmd) {
262                 case CONNECTION_PING:
263                         status = sdb_connection_ping(conn);
264                         break;
265                 case CONNECTION_STARTUP:
266                         status = sdb_fe_session_start(conn);
267                         break;
269                 case CONNECTION_QUERY:
270                 {
271                         sdb_llist_t *parsetree;
272                         sdb_conn_node_t *node = NULL;
274                         parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
275                                         (int)conn->cmd_len);
276                         if (! parsetree) {
277                                 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
278                                                 sdb_strbuf_string(conn->buf));
279                                 status = -1;
280                                 break;
281                         }
283                         switch (sdb_llist_len(parsetree)) {
284                                 case 0:
285                                         /* skipping empty command */
286                                         break;
287                                 case 1:
288                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
289                                         break;
291                                 default:
292                                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
293                                                         "in multi-statement query '%s'",
294                                                         sdb_llist_len(parsetree) - 1,
295                                                         sdb_llist_len(parsetree) == 2 ? "" : "s",
296                                                         sdb_strbuf_string(conn->buf));
297                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
298                         }
300                         if (node)
301                                 status = sdb_fe_exec(conn, node);
303                         sdb_llist_destroy(parsetree);
304                         break;
305                 }
307                 case CONNECTION_LIST:
308                         status = sdb_fe_list(conn);
309                         break;
311                 default:
312                 {
313                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
314                                         conn->cmd);
315                         sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
316                         status = -1;
317                         break;
318                 }
319         }
321         if (status)
322                 sdb_connection_send(conn, CONNECTION_ERROR,
323                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
324                                 sdb_strbuf_string(conn->errbuf));
326         /* remove the command from the buffer */
327         if (conn->cmd_len)
328                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
329         conn->cmd = CONNECTION_IDLE;
330         conn->cmd_len = 0;
331         return status;
332 } /* command_handle */
334 /* initialize the connection state information */
335 static int
336 command_init(sdb_conn_t *conn)
338         size_t len;
340         assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
342         conn->cmd = connection_get_int32(conn, 0);
343         conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
345         len = 2 * sizeof(uint32_t);
346         if (conn->cmd == CONNECTION_IDLE)
347                 len += conn->cmd_len;
348         sdb_strbuf_skip(conn->buf, 0, len);
349         return 0;
350 } /* command_init */
352 /* returns negative value on error, 0 on EOF, number of octets else */
353 static ssize_t
354 connection_read(sdb_conn_t *conn)
356         ssize_t n = 0;
358         while (42) {
359                 ssize_t status;
361                 errno = 0;
362                 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
363                 if (status < 0) {
364                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
365                                 break;
366                         return (int)status;
367                 }
368                 else if (! status) /* EOF */
369                         break;
371                 n += status;
372         }
374         return n;
375 } /* connection_read */
377 /*
378  * public API
379  */
381 int
382 sdb_connection_enable_logging(void)
384         return sdb_plugin_register_log("connection-logger", connection_log,
385                         /* user_data = */ NULL);
386 } /* sdb_connection_enable_logging */
388 sdb_conn_t *
389 sdb_connection_accept(int fd)
391         if (fd < 0)
392                 return NULL;
394         /* the placeholder will be replaced with the accepted file
395          * descriptor when initializing the object */
396         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
397                                 connection_type, fd));
398 } /* sdb_connection_create */
400 void
401 sdb_connection_close(sdb_conn_t *conn)
403         sdb_object_deref(SDB_OBJ(conn));
404 } /* sdb_connection_close */
406 ssize_t
407 sdb_connection_read(sdb_conn_t *conn)
409         ssize_t n = 0;
411         sdb_conn_set_ctx(conn);
413         while (42) {
414                 ssize_t status = connection_read(conn);
416                 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
417                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
418                         command_init(conn);
419                 if ((conn->cmd != CONNECTION_IDLE)
420                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
421                         command_handle(conn);
423                 if (status <= 0)
424                         break;
426                 n += status;
427         }
429         sdb_conn_set_ctx(NULL);
430         return n;
431 } /* sdb_connection_read */
433 ssize_t
434 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
435                 uint32_t msg_len, const char *msg)
437         ssize_t status;
439         if ((! conn) || (conn->fd < 0))
440                 return -1;
442         status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
443         if (status < 0) {
444                 char errbuf[1024];
446                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
447                                 "(code: %u, len: %u) to client: %s", code, msg_len,
448                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
449         }
450         return status;
451 } /* sdb_connection_send */
453 int
454 sdb_connection_ping(sdb_conn_t *conn)
456         if ((! conn) || (conn->cmd != CONNECTION_PING))
457                 return -1;
459         /* we're alive */
460         sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
461         return 0;
462 } /* sdb_connection_ping */
464 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */