Code

frontend: Clear current command on authentication error.
[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 "frontend/parser.h"
33 #include "utils/error.h"
34 #include "utils/strbuf.h"
35 #include "utils/proto.h"
37 #include <assert.h>
38 #include <errno.h>
40 #include <arpa/inet.h>
41 #include <fcntl.h>
43 #include <stdlib.h>
44 #include <string.h>
46 #include <pthread.h>
48 /*
49  * private variables
50  */
52 static pthread_key_t conn_ctx_key;
53 static _Bool         conn_ctx_key_initialized = 0;
55 /*
56  * private types
57  */
59 /* name of connection objects */
60 #define CONN_FD_PREFIX "conn#"
61 #define CONN_FD_PLACEHOLDER "XXXXXXX"
63 static int
64 connection_init(sdb_object_t *obj, va_list ap)
65 {
66         sdb_conn_t *conn;
67         int sock_fd;
68         int sock_fl;
70         assert(obj);
71         conn = CONN(obj);
73         sock_fd = va_arg(ap, int);
75         conn->buf = sdb_strbuf_create(/* size = */ 128);
76         if (! conn->buf) {
77                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
78                                 "for a new connection");
79                 return -1;
80         }
81         conn->errbuf = sdb_strbuf_create(0);
82         if (! conn->errbuf) {
83                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
84                                 "for a new connection");
85                 return -1;
86         }
88         conn->client_addr_len = sizeof(conn->client_addr);
89         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
90                         &conn->client_addr_len);
92         if (conn->fd < 0) {
93                 char buf[1024];
94                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
95                                 "connection: %s", sdb_strerror(errno,
96                                         buf, sizeof(buf)));
97                 return -1;
98         }
100         if (conn->client_addr.ss_family != AF_UNIX) {
101                 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
102                                 "unexpected family type %d", conn->client_addr.ss_family);
103                 return -1;
104         }
106         sock_fl = fcntl(conn->fd, F_GETFL);
107         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
108                 char buf[1024];
109                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
110                                 "to non-blocking mode: %s", conn->fd,
111                                 sdb_strerror(errno, buf, sizeof(buf)));
112                 return -1;
113         }
115         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
116                         conn->fd);
118         conn->cmd = CONNECTION_IDLE;
119         conn->cmd_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)
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)
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)
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)
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)
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)
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)
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)
259         int status = -1;
261         assert(conn && (conn->cmd != CONNECTION_IDLE));
263         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
264                         conn->cmd, conn->cmd_len);
266         if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP)) {
267                 const char *errmsg = "Authentication required";
268                 sdb_connection_send(conn, CONNECTION_ERROR,
269                                 (uint32_t)strlen(errmsg), errmsg);
271                 /* remove the command from the buffer */
272                 if (conn->cmd_len)
273                         sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
274                 return -1;
275         }
277         /* reset */
278         sdb_strbuf_sprintf(conn->errbuf, "");
280         switch (conn->cmd) {
281                 case CONNECTION_PING:
282                         status = sdb_connection_ping(conn);
283                         break;
284                 case CONNECTION_STARTUP:
285                         status = sdb_fe_session_start(conn);
286                         break;
288                 case CONNECTION_QUERY:
289                 {
290                         sdb_llist_t *parsetree;
291                         sdb_conn_node_t *node = NULL;
293                         parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
294                                         (int)conn->cmd_len);
295                         if (! parsetree) {
296                                 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
297                                                 sdb_strbuf_string(conn->buf));
298                                 status = -1;
299                                 break;
300                         }
302                         switch (sdb_llist_len(parsetree)) {
303                                 case 0:
304                                         /* skipping empty command */
305                                         break;
306                                 case 1:
307                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
308                                         break;
310                                 default:
311                                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
312                                                         "in multi-statement query '%s'",
313                                                         sdb_llist_len(parsetree) - 1,
314                                                         sdb_llist_len(parsetree) == 2 ? "" : "s",
315                                                         sdb_strbuf_string(conn->buf));
316                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
317                         }
319                         if (node) {
320                                 status = sdb_fe_exec(conn, node);
321                                 sdb_object_deref(SDB_OBJ(node));
322                         }
324                         sdb_llist_destroy(parsetree);
325                         break;
326                 }
328                 case CONNECTION_FETCH:
329                         status = sdb_fe_fetch(conn, sdb_strbuf_string(conn->buf));
330                         break;
331                 case CONNECTION_LIST:
332                         status = sdb_fe_list(conn);
333                         break;
334                 case CONNECTION_LOOKUP:
335                 {
336                         sdb_store_matcher_t *m;
338                         m = sdb_fe_parse_matcher(sdb_strbuf_string(conn->buf),
339                                         (int)conn->cmd_len);
340                         if (! m) {
341                                 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse expression '%s'",
342                                                 sdb_strbuf_string(conn->buf));
343                                 status = -1;
344                                 break;
345                         }
347                         status = sdb_fe_lookup(conn, m);
348                         sdb_object_deref(SDB_OBJ(m));
349                         break;
350                 }
352                 default:
353                 {
354                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
355                                         conn->cmd);
356                         sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
357                         status = -1;
358                         break;
359                 }
360         }
362         if (status)
363                 sdb_connection_send(conn, CONNECTION_ERROR,
364                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
365                                 sdb_strbuf_string(conn->errbuf));
367         /* remove the command from the buffer */
368         if (conn->cmd_len)
369                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
370         conn->cmd = CONNECTION_IDLE;
371         conn->cmd_len = 0;
372         return status;
373 } /* command_handle */
375 /* initialize the connection state information */
376 static int
377 command_init(sdb_conn_t *conn)
379         size_t len;
381         assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
383         conn->cmd = connection_get_int32(conn, 0);
384         conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
386         len = 2 * sizeof(uint32_t);
387         if (conn->cmd == CONNECTION_IDLE)
388                 len += conn->cmd_len;
389         sdb_strbuf_skip(conn->buf, 0, len);
390         return 0;
391 } /* command_init */
393 /* returns negative value on error, 0 on EOF, number of octets else */
394 static ssize_t
395 connection_read(sdb_conn_t *conn)
397         ssize_t n = 0;
399         if ((! conn) || (conn->fd < 0))
400                 return -1;
402         while (42) {
403                 ssize_t status;
405                 errno = 0;
406                 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
407                 if (status < 0) {
408                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
409                                 break;
411                         close(conn->fd);
412                         conn->fd = -1;
413                         return (int)status;
414                 }
415                 else if (! status) /* EOF */
416                         break;
418                 n += status;
419         }
421         return n;
422 } /* connection_read */
424 /*
425  * public API
426  */
428 int
429 sdb_connection_enable_logging(void)
431         return sdb_plugin_register_log("connection-logger", connection_log,
432                         /* user_data = */ NULL);
433 } /* sdb_connection_enable_logging */
435 sdb_conn_t *
436 sdb_connection_accept(int fd)
438         if (fd < 0)
439                 return NULL;
441         /* the placeholder will be replaced with the accepted file
442          * descriptor when initializing the object */
443         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
444                                 connection_type, fd));
445 } /* sdb_connection_create */
447 void
448 sdb_connection_close(sdb_conn_t *conn)
450         if (! conn)
451                 return;
453         /* close the connection even if someone else still references it */
454         if (conn->fd >= 0)
455                 close(conn->fd);
456         conn->fd = -1;
458         sdb_object_deref(SDB_OBJ(conn));
459 } /* sdb_connection_close */
461 ssize_t
462 sdb_connection_read(sdb_conn_t *conn)
464         ssize_t n = 0;
466         sdb_conn_set_ctx(conn);
468         while (42) {
469                 ssize_t status = connection_read(conn);
471                 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
472                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
473                         command_init(conn);
474                 if ((conn->cmd != CONNECTION_IDLE)
475                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
476                         command_handle(conn);
478                 if (status <= 0)
479                         break;
481                 n += status;
482         }
484         sdb_conn_set_ctx(NULL);
485         return n;
486 } /* sdb_connection_read */
488 ssize_t
489 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
490                 uint32_t msg_len, const char *msg)
492         ssize_t status;
494         if ((! conn) || (conn->fd < 0))
495                 return -1;
497         status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
498         if (status < 0) {
499                 char errbuf[1024];
501                 /* tell other code that there was a problem and, more importantly,
502                  * make sure we don't try to send further logs to the connection */
503                 close(conn->fd);
504                 conn->fd = -1;
506                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
507                                 "(code: %u, len: %u) to client: %s", code, msg_len,
508                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
509         }
510         return status;
511 } /* sdb_connection_send */
513 int
514 sdb_connection_ping(sdb_conn_t *conn)
516         if ((! conn) || (conn->cmd != CONNECTION_PING))
517                 return -1;
519         /* we're alive */
520         sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
521         return 0;
522 } /* sdb_connection_ping */
524 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */