Code

frontend: Fixed two typing issues.
[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);
307                         sdb_llist_destroy(parsetree);
308                         break;
309                 }
311                 case CONNECTION_LIST:
312                         status = sdb_fe_list(conn);
313                         break;
315                 default:
316                 {
317                         sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
318                                         conn->cmd);
319                         sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
320                         status = -1;
321                         break;
322                 }
323         }
325         if (status)
326                 sdb_connection_send(conn, CONNECTION_ERROR,
327                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
328                                 sdb_strbuf_string(conn->errbuf));
330         /* remove the command from the buffer */
331         if (conn->cmd_len)
332                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
333         conn->cmd = CONNECTION_IDLE;
334         conn->cmd_len = 0;
335         return status;
336 } /* command_handle */
338 /* initialize the connection state information */
339 static int
340 command_init(sdb_conn_t *conn)
342         size_t len;
344         assert(conn && (conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len));
346         conn->cmd = connection_get_int32(conn, 0);
347         conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
349         len = 2 * sizeof(uint32_t);
350         if (conn->cmd == CONNECTION_IDLE)
351                 len += conn->cmd_len;
352         sdb_strbuf_skip(conn->buf, 0, len);
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         while (42) {
363                 ssize_t status;
365                 errno = 0;
366                 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
367                 if (status < 0) {
368                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
369                                 break;
370                         return (int)status;
371                 }
372                 else if (! status) /* EOF */
373                         break;
375                 n += status;
376         }
378         return n;
379 } /* connection_read */
381 /*
382  * public API
383  */
385 int
386 sdb_connection_enable_logging(void)
388         return sdb_plugin_register_log("connection-logger", connection_log,
389                         /* user_data = */ NULL);
390 } /* sdb_connection_enable_logging */
392 sdb_conn_t *
393 sdb_connection_accept(int fd)
395         if (fd < 0)
396                 return NULL;
398         /* the placeholder will be replaced with the accepted file
399          * descriptor when initializing the object */
400         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
401                                 connection_type, fd));
402 } /* sdb_connection_create */
404 void
405 sdb_connection_close(sdb_conn_t *conn)
407         sdb_object_deref(SDB_OBJ(conn));
408 } /* sdb_connection_close */
410 ssize_t
411 sdb_connection_read(sdb_conn_t *conn)
413         ssize_t n = 0;
415         sdb_conn_set_ctx(conn);
417         while (42) {
418                 ssize_t status = connection_read(conn);
420                 if ((conn->cmd == CONNECTION_IDLE) && (! conn->cmd_len)
421                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
422                         command_init(conn);
423                 if ((conn->cmd != CONNECTION_IDLE)
424                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
425                         command_handle(conn);
427                 if (status <= 0)
428                         break;
430                 n += status;
431         }
433         sdb_conn_set_ctx(NULL);
434         return n;
435 } /* sdb_connection_read */
437 ssize_t
438 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
439                 uint32_t msg_len, const char *msg)
441         ssize_t status;
443         if ((! conn) || (conn->fd < 0))
444                 return -1;
446         status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
447         if (status < 0) {
448                 char errbuf[1024];
450                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
451                                 "(code: %u, len: %u) to client: %s", code, msg_len,
452                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
453         }
454         return status;
455 } /* sdb_connection_send */
457 int
458 sdb_connection_ping(sdb_conn_t *conn)
460         if ((! conn) || (conn->cmd != CONNECTION_PING))
461                 return -1;
463         /* we're alive */
464         sdb_connection_send(conn, CONNECTION_OK, 0, NULL);
465         return 0;
466 } /* sdb_connection_ping */
468 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */