Code

14e53363b7589dd2d19ccbc8a566a740138ba0da
[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 int
111 connection_init(sdb_object_t *obj, va_list ap)
113         sdb_conn_t *conn;
114         int sock_fd;
115         int sock_fl;
117         assert(obj);
118         conn = CONN(obj);
120         sock_fd = va_arg(ap, int);
122         conn->buf = sdb_strbuf_create(/* size = */ 128);
123         if (! conn->buf) {
124                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
125                                 "for a new connection");
126                 return -1;
127         }
128         conn->errbuf = sdb_strbuf_create(0);
129         if (! conn->errbuf) {
130                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
131                                 "for a new connection");
132                 return -1;
133         }
135         conn->client_addr_len = sizeof(conn->client_addr);
136         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
137                         &conn->client_addr_len);
139         if (conn->fd < 0) {
140                 char buf[1024];
141                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
142                                 "connection: %s", sdb_strerror(errno,
143                                         buf, sizeof(buf)));
144                 return -1;
145         }
147         if (conn->client_addr.ss_family != AF_UNIX) {
148                 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
149                                 "unexpected family type %d", conn->client_addr.ss_family);
150                 return -1;
151         }
153         sock_fl = fcntl(conn->fd, F_GETFL);
154         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
155                 char buf[1024];
156                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
157                                 "to non-blocking mode: %s", conn->fd,
158                                 sdb_strerror(errno, buf, sizeof(buf)));
159                 return -1;
160         }
162         conn->username = peer(conn->fd);
163         if (! conn->username) {
164                 char buf[1024];
165                 sdb_log(SDB_LOG_ERR, "frontend: Failed to retrieve peer for "
166                                 "connection conn#%i: %s", conn->fd,
167                                 sdb_strerror(errno, buf, sizeof(buf)));
168                 return -1;
169         }
170         conn->ready = 0;
172         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
173                         conn->fd);
175         conn->cmd = SDB_CONNECTION_IDLE;
176         conn->cmd_len = 0;
177         conn->skip_len = 0;
179         /* update the object name */
180         snprintf(obj->name + strlen(CONN_FD_PREFIX),
181                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
182         return 0;
183 } /* connection_init */
185 static void
186 connection_destroy(sdb_object_t *obj)
188         sdb_conn_t *conn;
189         size_t len;
191         assert(obj);
192         conn = CONN(obj);
194         conn->ready = 0;
196         if (conn->buf) {
197                 len = sdb_strbuf_len(conn->buf);
198                 if (len)
199                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
200                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
201         }
203         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
204         sdb_connection_close(conn);
206         if (conn->username)
207                 free(conn->username);
208         conn->username = NULL;
210         sdb_strbuf_destroy(conn->buf);
211         conn->buf = NULL;
212         sdb_strbuf_destroy(conn->errbuf);
213         conn->errbuf = NULL;
214 } /* connection_destroy */
216 static sdb_type_t connection_type = {
217         /* size = */ sizeof(sdb_conn_t),
218         /* init = */ connection_init,
219         /* destroy = */ connection_destroy,
220 };
222 /*
223  * private helper functions
224  */
226 static void
227 sdb_conn_ctx_destructor(void *c)
229         sdb_object_t *conn = c;
231         if (! conn)
232                 return;
233         sdb_object_deref(conn);
234 } /* sdb_conn_ctx_destructor */
236 static void
237 sdb_conn_ctx_init(void)
239         if (conn_ctx_key_initialized)
240                 return;
242         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
243         conn_ctx_key_initialized = 1;
244 } /* sdb_conn_ctx_init */
246 static void
247 sdb_conn_set_ctx(sdb_conn_t *conn)
249         sdb_conn_t *old;
251         sdb_conn_ctx_init();
253         old = pthread_getspecific(conn_ctx_key);
254         if (old)
255                 sdb_object_deref(SDB_OBJ(old));
256         if (conn)
257                 sdb_object_ref(SDB_OBJ(conn));
258         pthread_setspecific(conn_ctx_key, conn);
259 } /* sdb_conn_set_ctx */
261 static sdb_conn_t *
262 sdb_conn_get_ctx(void)
264         if (! conn_ctx_key_initialized)
265                 return NULL;
266         return pthread_getspecific(conn_ctx_key);
267 } /* sdb_conn_get_ctx */
269 /*
270  * connection handler functions
271  */
273 /*
274  * connection_log:
275  * Send a log message originating from the current thread to the client.
276  */
277 static int
278 connection_log(int prio, const char *msg,
279                 sdb_object_t __attribute__((unused)) *user_data)
281         uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
282         uint32_t p = htonl((uint32_t)prio);
283         char tmp[len + 1];
285         sdb_conn_t *conn;
287         conn = sdb_conn_get_ctx();
288         /* no connection associated to this thread
289          * or startup not done yet => don't leak any information */
290         if ((! conn) || (! conn->ready))
291                 return 0;
293         /* XXX: make the log-level configurable by the client at runtime */
294         if (prio >= SDB_LOG_DEBUG)
295                 return 0;
297         memcpy(tmp, &p, sizeof(p));
298         strcpy(tmp + sizeof(p), msg);
300         if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
301                 return -1;
302         return 0;
303 } /* connection_log */
305 static int
306 command_handle(sdb_conn_t *conn)
308         int status = -1;
310         assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
311         assert(! conn->skip_len);
313         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
314                         conn->cmd, conn->cmd_len);
316         if (conn->cmd == SDB_CONNECTION_PING)
317                 status = sdb_connection_ping(conn);
318         else if (conn->cmd == SDB_CONNECTION_STARTUP)
319                 status = sdb_fe_session_start(conn);
320         else if (conn->cmd == SDB_CONNECTION_QUERY)
321                 status = sdb_fe_query(conn);
322         else if (conn->cmd == SDB_CONNECTION_FETCH)
323                 status = sdb_fe_fetch(conn);
324         else if (conn->cmd == SDB_CONNECTION_LIST)
325                 status = sdb_fe_list(conn);
326         else if (conn->cmd == SDB_CONNECTION_LOOKUP)
327                 status = sdb_fe_lookup(conn);
328         else {
329                 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
330                                 conn->cmd);
331                 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
332                 status = -1;
333         }
335         if (status) {
336                 if (! sdb_strbuf_len(conn->errbuf))
337                         sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
338                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
339                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
340                                 sdb_strbuf_string(conn->errbuf));
341         }
342         return status;
343 } /* command_handle */
345 /* initialize the connection state information */
346 static int
347 command_init(sdb_conn_t *conn)
349         const char *errmsg = NULL;
351         assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
353         if (conn->skip_len)
354                 return -1;
356         /* reset */
357         sdb_strbuf_clear(conn->errbuf);
359         if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
360                                 &conn->cmd, &conn->cmd_len))
361                 return -1;
362         sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
364         if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
365                 errmsg = "Authentication required";
366         else if (conn->cmd == SDB_CONNECTION_IDLE)
367                 errmsg = "Invalid command 0";
369         if (errmsg) {
370                 size_t len = sdb_strbuf_len(conn->buf);
372                 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
373                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
374                                 (uint32_t)strlen(errmsg), errmsg);
375                 conn->skip_len += conn->cmd_len;
376                 conn->cmd = SDB_CONNECTION_IDLE;
377                 conn->cmd_len = 0;
379                 if (len > conn->skip_len)
380                         len = conn->skip_len;
381                 sdb_strbuf_skip(conn->buf, 0, len);
382                 conn->skip_len -= len;
383                 /* connection_read will handle anything else */
384         }
385         return 0;
386 } /* command_init */
388 /* returns negative value on error, 0 on EOF, number of octets else */
389 static ssize_t
390 connection_read(sdb_conn_t *conn)
392         ssize_t n = 0;
394         if ((! conn) || (conn->fd < 0))
395                 return -1;
397         while (42) {
398                 ssize_t status;
400                 errno = 0;
401                 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
402                 if (status < 0) {
403                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
404                                 break;
406                         sdb_connection_close(conn);
407                         return (int)status;
408                 }
409                 else if (! status) /* EOF */
410                         break;
412                 if (conn->skip_len) {
413                         size_t len = (size_t)status < conn->skip_len
414                                 ? (size_t)status : conn->skip_len;
415                         sdb_strbuf_skip(conn->buf, 0, len);
416                         conn->skip_len -= len;
417                 }
419                 n += status;
421                 /* give the main loop a chance to execute commands (and free up buffer
422                  * space) on large amounts of incoming traffic */
423                 if (n > 1024 * 1024)
424                         break;
425         }
427         return n;
428 } /* connection_read */
430 /*
431  * public API
432  */
434 int
435 sdb_connection_enable_logging(void)
437         return sdb_plugin_register_log("connection-logger", connection_log,
438                         /* user_data = */ NULL);
439 } /* sdb_connection_enable_logging */
441 sdb_conn_t *
442 sdb_connection_accept(int fd)
444         if (fd < 0)
445                 return NULL;
447         /* the placeholder will be replaced with the accepted file
448          * descriptor when initializing the object */
449         return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
450                                 connection_type, fd));
451 } /* sdb_connection_create */
453 void
454 sdb_connection_close(sdb_conn_t *conn)
456         if (! conn)
457                 return;
459         /* close the connection even if someone else still references it */
460         if (conn->fd >= 0)
461                 close(conn->fd);
462         conn->fd = -1;
463 } /* sdb_connection_close */
465 ssize_t
466 sdb_connection_handle(sdb_conn_t *conn)
468         ssize_t n = 0;
470         sdb_conn_set_ctx(conn);
472         while (42) {
473                 ssize_t status = connection_read(conn);
475                 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
476                                 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
477                         command_init(conn);
478                 if ((conn->cmd != SDB_CONNECTION_IDLE)
479                                 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
480                         command_handle(conn);
482                         /* remove the command from the buffer */
483                         if (conn->cmd_len)
484                                 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
485                         conn->cmd = SDB_CONNECTION_IDLE;
486                         conn->cmd_len = 0;
487                 }
489                 if (status <= 0)
490                         break;
492                 n += status;
493         }
495         sdb_conn_set_ctx(NULL);
496         return n;
497 } /* sdb_connection_handle */
499 ssize_t
500 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
501                 uint32_t msg_len, const char *msg)
503         char buf[2 * sizeof(uint32_t) + msg_len];
504         ssize_t status;
506         if ((! conn) || (conn->fd < 0))
507                 return -1;
508         if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
509                 return -1;
511         status = sdb_write(conn->fd, sizeof(buf), buf);
512         if (status < 0) {
513                 char errbuf[1024];
515                 /* tell other code that there was a problem and, more importantly,
516                  * make sure we don't try to send further logs to the connection */
517                 sdb_connection_close(conn);
518                 conn->ready = 0;
520                 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
521                                 "(code: %u, len: %u) to client: %s", code, msg_len,
522                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
523         }
524         return status;
525 } /* sdb_connection_send */
527 int
528 sdb_connection_ping(sdb_conn_t *conn)
530         if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
531                 return -1;
533         /* we're alive */
534         sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
535         return 0;
536 } /* sdb_connection_ping */
538 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */