Code

frontend: Make connection I/O handling more flexible.
[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 <stdlib.h>
48 #include <string.h>
50 #include <sys/socket.h>
51 #include <sys/types.h>
52 #include <sys/param.h>
54 #ifdef HAVE_UCRED_H
55 #       include <ucred.h>
56 #endif
57 #ifdef HAVE_SYS_UCRED_H
58 #       include <sys/ucred.h>
59 #endif
61 #include <pwd.h>
63 #include <pthread.h>
65 /*
66  * private variables
67  */
69 static pthread_key_t conn_ctx_key;
70 static bool          conn_ctx_key_initialized = 0;
72 /*
73  * private types
74  */
76 /* name of connection objects */
77 #define CONN_FD_PREFIX "conn#"
78 #define CONN_FD_PLACEHOLDER "XXXXXXX"
80 /* XXX: only supports UNIX sockets so far */
81 static char *
82 peer(int sockfd)
83 {
84         uid_t uid;
86         struct passwd pw_entry;
87         struct passwd *result = NULL;
88         char buf[1024];
90 #ifdef SO_PEERCRED
91         struct ucred cred;
92         socklen_t len = sizeof(cred);
94         if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cred, &len)
95                         || (len != sizeof(cred)))
96                 return NULL;
97         uid = cred.uid;
98 #else /* SO_PEERCRED */
99         errno = ENOSYS;
100         return NULL;
101 #endif
103         memset(&pw_entry, 0, sizeof(pw_entry));
104         if (getpwuid_r(uid, &pw_entry, buf, sizeof(buf), &result)
105                         || (! result))
106                 return NULL;
107         return strdup(result->pw_name);
108 } /* peer */
110 static ssize_t
111 conn_read(sdb_conn_t *conn, size_t len)
113         return sdb_strbuf_read(conn->buf, conn->fd, len);
114 } /* conn_read */
116 static ssize_t
117 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
119         return sdb_write(conn->fd, len, buf);
120 } /* conn_write */
122 static int
123 connection_init(sdb_object_t *obj, va_list ap)
125         sdb_conn_t *conn;
126         int sock_fd;
127         int sock_fl;
129         assert(obj);
130         conn = CONN(obj);
132         sock_fd = va_arg(ap, int);
134         conn->buf = sdb_strbuf_create(/* size = */ 128);
135         if (! conn->buf) {
136                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
137                                 "for a new connection");
138                 return -1;
139         }
140         conn->errbuf = sdb_strbuf_create(0);
141         if (! conn->errbuf) {
142                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
143                                 "for a new connection");
144                 return -1;
145         }
147         conn->client_addr_len = sizeof(conn->client_addr);
148         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
149                         &conn->client_addr_len);
151         if (conn->fd < 0) {
152                 char buf[1024];
153                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
154                                 "connection: %s", sdb_strerror(errno,
155                                         buf, sizeof(buf)));
156                 return -1;
157         }
159         /* defaults */
160         conn->read = conn_read;
161         conn->write = conn_write;
162         conn->finish = NULL;
163         conn->session = NULL;
165         if (conn->client_addr.ss_family != AF_UNIX) {
166                 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
167                                 "unexpected family type %d", conn->client_addr.ss_family);
168                 return -1;
169         }
171         sock_fl = fcntl(conn->fd, F_GETFL);
172         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
173                 char buf[1024];
174                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
175                                 "to non-blocking mode: %s", conn->fd,
176                                 sdb_strerror(errno, buf, sizeof(buf)));
177                 return -1;
178         }
180         conn->username = peer(conn->fd);
181         if (! conn->username) {
182                 char buf[1024];
183                 sdb_log(SDB_LOG_ERR, "frontend: Failed to retrieve peer for "
184                                 "connection conn#%i: %s", conn->fd,
185                                 sdb_strerror(errno, buf, sizeof(buf)));
186                 return -1;
187         }
188         conn->ready = 0;
190         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
191                         conn->fd);
193         conn->cmd = SDB_CONNECTION_IDLE;
194         conn->cmd_len = 0;
195         conn->skip_len = 0;
197         /* update the object name */
198         snprintf(obj->name + strlen(CONN_FD_PREFIX),
199                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
200         return 0;
201 } /* connection_init */
203 static void
204 connection_destroy(sdb_object_t *obj)
206         sdb_conn_t *conn;
207         size_t len;
209         assert(obj);
210         conn = CONN(obj);
212         conn->ready = 0;
214         if (conn->finish)
215                 conn->finish(conn);
216         conn->finish = NULL;
218         if (conn->buf) {
219                 len = sdb_strbuf_len(conn->buf);
220                 if (len)
221                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
222                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
223         }
225         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
226         sdb_connection_close(conn);
228         if (conn->username)
229                 free(conn->username);
230         conn->username = NULL;
232         sdb_strbuf_destroy(conn->buf);
233         conn->buf = NULL;
234         sdb_strbuf_destroy(conn->errbuf);
235         conn->errbuf = NULL;
236 } /* connection_destroy */
238 static sdb_type_t connection_type = {
239         /* size = */ sizeof(sdb_conn_t),
240         /* init = */ connection_init,
241         /* destroy = */ connection_destroy,
242 };
244 /*
245  * private helper functions
246  */
248 static void
249 sdb_conn_ctx_destructor(void *c)
251         sdb_object_t *conn = c;
253         if (! conn)
254                 return;
255         sdb_object_deref(conn);
256 } /* sdb_conn_ctx_destructor */
258 static void
259 sdb_conn_ctx_init(void)
261         if (conn_ctx_key_initialized)
262                 return;
264         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
265         conn_ctx_key_initialized = 1;
266 } /* sdb_conn_ctx_init */
268 static void
269 sdb_conn_set_ctx(sdb_conn_t *conn)
271         sdb_conn_t *old;
273         sdb_conn_ctx_init();
275         old = pthread_getspecific(conn_ctx_key);
276         if (old)
277                 sdb_object_deref(SDB_OBJ(old));
278         if (conn)
279                 sdb_object_ref(SDB_OBJ(conn));
280         pthread_setspecific(conn_ctx_key, conn);
281 } /* sdb_conn_set_ctx */
283 static sdb_conn_t *
284 sdb_conn_get_ctx(void)
286         if (! conn_ctx_key_initialized)
287                 return NULL;
288         return pthread_getspecific(conn_ctx_key);
289 } /* sdb_conn_get_ctx */
291 /*
292  * connection handler functions
293  */
295 /*
296  * connection_log:
297  * Send a log message originating from the current thread to the client.
298  */
299 static int
300 connection_log(int prio, const char *msg,
301                 sdb_object_t __attribute__((unused)) *user_data)
303         uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
304         uint32_t p = htonl((uint32_t)prio);
305         char tmp[len + 1];
307         sdb_conn_t *conn;
309         conn = sdb_conn_get_ctx();
310         /* no connection associated to this thread
311          * or startup not done yet => don't leak any information */
312         if ((! conn) || (! conn->ready))
313                 return 0;
315         /* XXX: make the log-level configurable by the client at runtime */
316         if (prio >= SDB_LOG_DEBUG)
317                 return 0;
319         memcpy(tmp, &p, sizeof(p));
320         strcpy(tmp + sizeof(p), msg);
322         if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
323                 return -1;
324         return 0;
325 } /* connection_log */
327 static int
328 command_handle(sdb_conn_t *conn)
330         int status = -1;
332         assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
333         assert(! conn->skip_len);
335         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
336                         conn->cmd, conn->cmd_len);
338         if (conn->cmd == SDB_CONNECTION_PING)
339                 status = sdb_connection_ping(conn);
340         else if (conn->cmd == SDB_CONNECTION_STARTUP)
341                 status = sdb_fe_session_start(conn);
342         else if (conn->cmd == SDB_CONNECTION_QUERY)
343                 status = sdb_fe_query(conn);
344         else if (conn->cmd == SDB_CONNECTION_FETCH)
345                 status = sdb_fe_fetch(conn);
346         else if (conn->cmd == SDB_CONNECTION_LIST)
347                 status = sdb_fe_list(conn);
348         else if (conn->cmd == SDB_CONNECTION_LOOKUP)
349                 status = sdb_fe_lookup(conn);
350         else if (conn->cmd == SDB_CONNECTION_STORE)
351                 status = sdb_fe_store(conn);
352         else {
353                 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
354                                 conn->cmd);
355                 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
356                 status = -1;
357         }
359         if (status) {
360                 if (! sdb_strbuf_len(conn->errbuf))
361                         sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
362                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
363                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
364                                 sdb_strbuf_string(conn->errbuf));
365         }
366         return status;
367 } /* command_handle */
369 /* initialize the connection state information */
370 static int
371 command_init(sdb_conn_t *conn)
373         const char *errmsg = NULL;
375         assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
377         if (conn->skip_len)
378                 return -1;
380         /* reset */
381         sdb_strbuf_clear(conn->errbuf);
383         if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
384                                 &conn->cmd, &conn->cmd_len) < 0)
385                 return -1;
386         sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
388         if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
389                 errmsg = "Authentication required";
390         else if (conn->cmd == SDB_CONNECTION_IDLE)
391                 errmsg = "Invalid command 0";
393         if (errmsg) {
394                 size_t len = sdb_strbuf_len(conn->buf);
396                 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
397                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
398                                 (uint32_t)strlen(errmsg), errmsg);
399                 conn->skip_len += conn->cmd_len;
400                 conn->cmd = SDB_CONNECTION_IDLE;
401                 conn->cmd_len = 0;
403                 if (len > conn->skip_len)
404                         len = conn->skip_len;
405                 sdb_strbuf_skip(conn->buf, 0, len);
406                 conn->skip_len -= len;
407                 /* connection_read will handle anything else */
408         }
409         return 0;
410 } /* command_init */
412 /* returns negative value on error, 0 on EOF, number of octets else */
413 static ssize_t
414 connection_read(sdb_conn_t *conn)
416         ssize_t n = 0;
418         if ((! conn) || (conn->fd < 0))
419                 return -1;
421         while (42) {
422                 ssize_t status;
424                 errno = 0;
425                 status = conn->read(conn, 1024);
426                 if (status < 0) {
427                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
428                                 break;
430                         sdb_connection_close(conn);
431                         return (int)status;
432                 }
433                 else if (! status) /* EOF */
434                         break;
436                 if (conn->skip_len) {
437                         size_t len = (size_t)status < conn->skip_len
438                                 ? (size_t)status : conn->skip_len;
439                         sdb_strbuf_skip(conn->buf, 0, len);
440                         conn->skip_len -= len;
441                 }
443                 n += status;
445                 /* give the main loop a chance to execute commands (and free up buffer
446                  * space) on large amounts of incoming traffic */
447                 if (n > 1024 * 1024)
448                         break;
449         }
451         return n;
452 } /* connection_read */
454 /*
455  * public API
456  */
458 int
459 sdb_connection_enable_logging(void)
461         return sdb_plugin_register_log("connection-logger", connection_log,
462                         /* user_data = */ NULL);
463 } /* sdb_connection_enable_logging */
465 sdb_conn_t *
466 sdb_connection_accept(int fd)
468         if (fd < 0)
469                 return NULL;
471         /* the placeholder will be replaced with the accepted file
472          * descriptor when initializing the object */
473         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
474                                 connection_type, fd));
475 } /* sdb_connection_create */
477 void
478 sdb_connection_close(sdb_conn_t *conn)
480         if (! conn)
481                 return;
483         if (conn->finish)
484                 conn->finish(conn);
485         conn->finish = NULL;
487         /* close the connection even if someone else still references it */
488         if (conn->fd >= 0)
489                 close(conn->fd);
490         conn->fd = -1;
491 } /* sdb_connection_close */
493 ssize_t
494 sdb_connection_handle(sdb_conn_t *conn)
496         ssize_t n = 0;
498         sdb_conn_set_ctx(conn);
500         while (42) {
501                 ssize_t status = connection_read(conn);
503                 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
504                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
505                         command_init(conn);
506                 if ((conn->cmd != SDB_CONNECTION_IDLE)
507                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
508                         command_handle(conn);
510                         /* remove the command from the buffer */
511                         if (conn->cmd_len)
512                                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
513                         conn->cmd = SDB_CONNECTION_IDLE;
514                         conn->cmd_len = 0;
515                 }
517                 if (status <= 0)
518                         break;
520                 n += status;
521         }
523         sdb_conn_set_ctx(NULL);
524         return n;
525 } /* sdb_connection_handle */
527 ssize_t
528 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
529                 uint32_t msg_len, const char *msg)
531         char buf[2 * sizeof(uint32_t) + msg_len];
532         ssize_t status;
534         if ((! conn) || (conn->fd < 0))
535                 return -1;
536         if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
537                 return -1;
539         status = conn->write(conn, buf, sizeof(buf));
540         if (status < 0) {
541                 char errbuf[1024];
543                 /* tell other code that there was a problem and, more importantly,
544                  * make sure we don't try to send further logs to the connection */
545                 sdb_connection_close(conn);
546                 conn->ready = 0;
548                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
549                                 "(code: %u, len: %u) to client: %s", code, msg_len,
550                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
551         }
552         return status;
553 } /* sdb_connection_send */
555 int
556 sdb_connection_ping(sdb_conn_t *conn)
558         if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
559                 return -1;
561         /* we're alive */
562         sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
563         return 0;
564 } /* sdb_connection_ping */
566 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */