Code

frontend: Added FETCH support to the connection handler.
[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 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         /* XXX: make the log-level configurable by the client at runtime */
221         if (prio >= SDB_LOG_DEBUG)
222                 return 0;
224         /* TODO: Use CONNECTION_LOG_<prio>? */
225         if (sdb_connection_send(conn, CONNECTION_LOG,
226                                 (uint32_t)strlen(msg), msg) < 0)
227                 return -1;
228         return 0;
229 } /* connection_log */
231 static uint32_t
232 connection_get_int32(sdb_conn_t *conn, size_t offset)
234         const char *data;
235         uint32_t n;
237         assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
239         data = sdb_strbuf_string(conn->buf);
240         memcpy(&n, data + offset, sizeof(n));
241         n = ntohl(n);
242         return n;
243 } /* connection_get_int32 */
245 static int
246 command_handle(sdb_conn_t *conn)
248         int status = -1;
250         assert(conn && (conn->cmd != CONNECTION_IDLE));
252         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
253                         conn->cmd, conn->cmd_len);
255         if ((! conn->username) && (conn->cmd != CONNECTION_STARTUP)) {
256                 const char *errmsg = "Authentication required";
257                 sdb_connection_send(conn, CONNECTION_ERROR,
258                                 (uint32_t)strlen(errmsg), errmsg);
259                 return -1;
260         }
262         /* reset */
263         sdb_strbuf_sprintf(conn->errbuf, "");
265         switch (conn->cmd) {
266                 case CONNECTION_PING:
267                         status = sdb_connection_ping(conn);
268                         break;
269                 case CONNECTION_STARTUP:
270                         status = sdb_fe_session_start(conn);
271                         break;
273                 case CONNECTION_QUERY:
274                 {
275                         sdb_llist_t *parsetree;
276                         sdb_conn_node_t *node = NULL;
278                         parsetree = sdb_fe_parse(sdb_strbuf_string(conn->buf),
279                                         (int)conn->cmd_len);
280                         if (! parsetree) {
281                                 sdb_log(SDB_LOG_ERR, "frontend: Failed to parse query '%s'",
282                                                 sdb_strbuf_string(conn->buf));
283                                 status = -1;
284                                 break;
285                         }
287                         switch (sdb_llist_len(parsetree)) {
288                                 case 0:
289                                         /* skipping empty command */
290                                         break;
291                                 case 1:
292                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
293                                         break;
295                                 default:
296                                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring %d command%s "
297                                                         "in multi-statement query '%s'",
298                                                         sdb_llist_len(parsetree) - 1,
299                                                         sdb_llist_len(parsetree) == 2 ? "" : "s",
300                                                         sdb_strbuf_string(conn->buf));
301                                         node = SDB_CONN_NODE(sdb_llist_get(parsetree, 0));
302                         }
304                         if (node) {
305                                 status = sdb_fe_exec(conn, node);
306                                 sdb_object_deref(SDB_OBJ(node));
307                         }
309                         sdb_llist_destroy(parsetree);
310                         break;
311                 }
313                 case CONNECTION_FETCH:
314                         status = sdb_fe_fetch(conn, sdb_strbuf_string(conn->buf));
315                         break;
316                 case CONNECTION_LIST:
317                         status = sdb_fe_list(conn);
318                         break;
320                 default:
321                 {
322                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
323                                         conn->cmd);
324                         sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
325                         status = -1;
326                         break;
327                 }
328         }
330         if (status)
331                 sdb_connection_send(conn, CONNECTION_ERROR,
332                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
333                                 sdb_strbuf_string(conn->errbuf));
335         /* remove the command from the buffer */
336         if (conn->cmd_len)
337                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
338         conn->cmd = CONNECTION_IDLE;
339         conn->cmd_len = 0;
340         return status;
341 } /* command_handle */
343 /* initialize the connection state information */
344 static int
345 command_init(sdb_conn_t *conn)
347         size_t len;
349         assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
351         conn->cmd = connection_get_int32(conn, 0);
352         conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
354         len = 2 * sizeof(uint32_t);
355         if (conn->cmd == CONNECTION_IDLE)
356                 len += conn->cmd_len;
357         sdb_strbuf_skip(conn->buf, 0, len);
358         return 0;
359 } /* command_init */
361 /* returns negative value on error, 0 on EOF, number of octets else */
362 static ssize_t
363 connection_read(sdb_conn_t *conn)
365         ssize_t n = 0;
367         while (42) {
368                 ssize_t status;
370                 errno = 0;
371                 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
372                 if (status < 0) {
373                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
374                                 break;
375                         return (int)status;
376                 }
377                 else if (! status) /* EOF */
378                         break;
380                 n += status;
381         }
383         return n;
384 } /* connection_read */
386 /*
387  * public API
388  */
390 int
391 sdb_connection_enable_logging(void)
393         return sdb_plugin_register_log("connection-logger", connection_log,
394                         /* user_data = */ NULL);
395 } /* sdb_connection_enable_logging */
397 sdb_conn_t *
398 sdb_connection_accept(int fd)
400         if (fd < 0)
401                 return NULL;
403         /* the placeholder will be replaced with the accepted file
404          * descriptor when initializing the object */
405         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
406                                 connection_type, fd));
407 } /* sdb_connection_create */
409 void
410 sdb_connection_close(sdb_conn_t *conn)
412         sdb_object_deref(SDB_OBJ(conn));
413 } /* sdb_connection_close */
415 ssize_t
416 sdb_connection_read(sdb_conn_t *conn)
418         ssize_t n = 0;
420         sdb_conn_set_ctx(conn);
422         while (42) {
423                 ssize_t status = connection_read(conn);
425                 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
426                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
427                         command_init(conn);
428                 if ((conn->cmd != CONNECTION_IDLE)
429                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
430                         command_handle(conn);
432                 if (status <= 0)
433                         break;
435                 n += status;
436         }
438         sdb_conn_set_ctx(NULL);
439         return n;
440 } /* sdb_connection_read */
442 ssize_t
443 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
444                 uint32_t msg_len, const char *msg)
446         ssize_t status;
448         if ((! conn) || (conn->fd < 0))
449                 return -1;
451         status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
452         if (status < 0) {
453                 char errbuf[1024];
455                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
456                                 "(code: %u, len: %u) to client: %s", code, msg_len,
457                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
458         }
459         return status;
460 } /* sdb_connection_send */
462 int
463 sdb_connection_ping(sdb_conn_t *conn)
465         if ((! conn) || (conn->cmd != CONNECTION_PING))
466                 return -1;
468         /* we're alive */
469         sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
470         return 0;
471 } /* sdb_connection_ping */
473 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */