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)
112 {
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)
187 {
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)
228 {
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)
238 {
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)
248 {
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)
263 {
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)
280 {
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)
307 {
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)
348 {
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(conn->buf, &conn->cmd, &conn->cmd_len))
360 return -1;
361 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
363 if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
364 errmsg = "Authentication required";
365 else if (conn->cmd == SDB_CONNECTION_IDLE)
366 errmsg = "Invalid command 0";
368 if (errmsg) {
369 size_t len = sdb_strbuf_len(conn->buf);
371 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
372 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
373 (uint32_t)strlen(errmsg), errmsg);
374 conn->skip_len += conn->cmd_len;
375 conn->cmd = SDB_CONNECTION_IDLE;
376 conn->cmd_len = 0;
378 if (len > conn->skip_len)
379 len = conn->skip_len;
380 sdb_strbuf_skip(conn->buf, 0, len);
381 conn->skip_len -= len;
382 /* connection_read will handle anything else */
383 }
384 return 0;
385 } /* command_init */
387 /* returns negative value on error, 0 on EOF, number of octets else */
388 static ssize_t
389 connection_read(sdb_conn_t *conn)
390 {
391 ssize_t n = 0;
393 if ((! conn) || (conn->fd < 0))
394 return -1;
396 while (42) {
397 ssize_t status;
399 errno = 0;
400 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
401 if (status < 0) {
402 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
403 break;
405 sdb_connection_close(conn);
406 return (int)status;
407 }
408 else if (! status) /* EOF */
409 break;
411 if (conn->skip_len) {
412 size_t len = (size_t)status < conn->skip_len
413 ? (size_t)status : conn->skip_len;
414 sdb_strbuf_skip(conn->buf, 0, len);
415 conn->skip_len -= len;
416 }
418 n += status;
420 /* give the main loop a chance to execute commands (and free up buffer
421 * space) on large amounts of incoming traffic */
422 if (n > 1024 * 1024)
423 break;
424 }
426 return n;
427 } /* connection_read */
429 /*
430 * public API
431 */
433 int
434 sdb_connection_enable_logging(void)
435 {
436 return sdb_plugin_register_log("connection-logger", connection_log,
437 /* user_data = */ NULL);
438 } /* sdb_connection_enable_logging */
440 sdb_conn_t *
441 sdb_connection_accept(int fd)
442 {
443 if (fd < 0)
444 return NULL;
446 /* the placeholder will be replaced with the accepted file
447 * descriptor when initializing the object */
448 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
449 connection_type, fd));
450 } /* sdb_connection_create */
452 void
453 sdb_connection_close(sdb_conn_t *conn)
454 {
455 if (! conn)
456 return;
458 /* close the connection even if someone else still references it */
459 if (conn->fd >= 0)
460 close(conn->fd);
461 conn->fd = -1;
462 } /* sdb_connection_close */
464 ssize_t
465 sdb_connection_handle(sdb_conn_t *conn)
466 {
467 ssize_t n = 0;
469 sdb_conn_set_ctx(conn);
471 while (42) {
472 ssize_t status = connection_read(conn);
474 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
475 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
476 command_init(conn);
477 if ((conn->cmd != SDB_CONNECTION_IDLE)
478 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
479 command_handle(conn);
481 /* remove the command from the buffer */
482 if (conn->cmd_len)
483 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
484 conn->cmd = SDB_CONNECTION_IDLE;
485 conn->cmd_len = 0;
486 }
488 if (status <= 0)
489 break;
491 n += status;
492 }
494 sdb_conn_set_ctx(NULL);
495 return n;
496 } /* sdb_connection_handle */
498 ssize_t
499 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
500 uint32_t msg_len, const char *msg)
501 {
502 char buf[2 * sizeof(uint32_t) + msg_len];
503 ssize_t status;
505 if ((! conn) || (conn->fd < 0))
506 return -1;
507 if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
508 return -1;
510 status = sdb_write(conn->fd, sizeof(buf), buf);
511 if (status < 0) {
512 char errbuf[1024];
514 /* tell other code that there was a problem and, more importantly,
515 * make sure we don't try to send further logs to the connection */
516 sdb_connection_close(conn);
517 conn->ready = 0;
519 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
520 "(code: %u, len: %u) to client: %s", code, msg_len,
521 sdb_strerror(errno, errbuf, sizeof(errbuf)));
522 }
523 return status;
524 } /* sdb_connection_send */
526 int
527 sdb_connection_ping(sdb_conn_t *conn)
528 {
529 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
530 return -1;
532 /* we're alive */
533 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
534 return 0;
535 } /* sdb_connection_ping */
537 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */