58a2cb4d3e3d06d510927b57b414f37bc3af425c
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 if (conn->fd >= 0)
205 close(conn->fd);
206 conn->fd = -1;
208 if (conn->username)
209 free(conn->username);
210 conn->username = NULL;
212 sdb_strbuf_destroy(conn->buf);
213 conn->buf = NULL;
214 sdb_strbuf_destroy(conn->errbuf);
215 conn->errbuf = NULL;
216 } /* connection_destroy */
218 static sdb_type_t connection_type = {
219 /* size = */ sizeof(sdb_conn_t),
220 /* init = */ connection_init,
221 /* destroy = */ connection_destroy,
222 };
224 /*
225 * private helper functions
226 */
228 static void
229 sdb_conn_ctx_destructor(void *c)
230 {
231 sdb_object_t *conn = c;
233 if (! conn)
234 return;
235 sdb_object_deref(conn);
236 } /* sdb_conn_ctx_destructor */
238 static void
239 sdb_conn_ctx_init(void)
240 {
241 if (conn_ctx_key_initialized)
242 return;
244 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
245 conn_ctx_key_initialized = 1;
246 } /* sdb_conn_ctx_init */
248 static void
249 sdb_conn_set_ctx(sdb_conn_t *conn)
250 {
251 sdb_conn_t *old;
253 sdb_conn_ctx_init();
255 old = pthread_getspecific(conn_ctx_key);
256 if (old)
257 sdb_object_deref(SDB_OBJ(old));
258 if (conn)
259 sdb_object_ref(SDB_OBJ(conn));
260 pthread_setspecific(conn_ctx_key, conn);
261 } /* sdb_conn_set_ctx */
263 static sdb_conn_t *
264 sdb_conn_get_ctx(void)
265 {
266 if (! conn_ctx_key_initialized)
267 return NULL;
268 return pthread_getspecific(conn_ctx_key);
269 } /* sdb_conn_get_ctx */
271 /*
272 * connection handler functions
273 */
275 /*
276 * connection_log:
277 * Send a log message originating from the current thread to the client.
278 */
279 static int
280 connection_log(int prio, const char *msg,
281 sdb_object_t __attribute__((unused)) *user_data)
282 {
283 uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
284 uint32_t p = htonl((uint32_t)prio);
285 char tmp[len + 1];
287 sdb_conn_t *conn;
289 conn = sdb_conn_get_ctx();
290 /* no connection associated to this thread
291 * or startup not done yet => don't leak any information */
292 if ((! conn) || (! conn->ready))
293 return 0;
295 /* XXX: make the log-level configurable by the client at runtime */
296 if (prio >= SDB_LOG_DEBUG)
297 return 0;
299 memcpy(tmp, &p, sizeof(p));
300 strcpy(tmp + sizeof(p), msg);
302 if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
303 return -1;
304 return 0;
305 } /* connection_log */
307 static int
308 command_handle(sdb_conn_t *conn)
309 {
310 int status = -1;
312 assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
313 assert(! conn->skip_len);
315 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
316 conn->cmd, conn->cmd_len);
318 if (conn->cmd == SDB_CONNECTION_PING)
319 status = sdb_connection_ping(conn);
320 else if (conn->cmd == SDB_CONNECTION_STARTUP)
321 status = sdb_fe_session_start(conn);
322 else if (conn->cmd == SDB_CONNECTION_QUERY)
323 status = sdb_fe_query(conn);
324 else if (conn->cmd == SDB_CONNECTION_FETCH)
325 status = sdb_fe_fetch(conn);
326 else if (conn->cmd == SDB_CONNECTION_LIST)
327 status = sdb_fe_list(conn);
328 else if (conn->cmd == SDB_CONNECTION_LOOKUP)
329 status = sdb_fe_lookup(conn);
330 else {
331 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
332 conn->cmd);
333 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
334 status = -1;
335 }
337 if (status) {
338 if (! sdb_strbuf_len(conn->errbuf))
339 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
340 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
341 (uint32_t)sdb_strbuf_len(conn->errbuf),
342 sdb_strbuf_string(conn->errbuf));
343 }
344 return status;
345 } /* command_handle */
347 /* initialize the connection state information */
348 static int
349 command_init(sdb_conn_t *conn)
350 {
351 const char *errmsg = NULL;
353 assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
355 if (conn->skip_len)
356 return -1;
358 /* reset */
359 sdb_strbuf_clear(conn->errbuf);
361 conn->cmd = sdb_proto_get_int(conn->buf, 0);
362 conn->cmd_len = sdb_proto_get_int(conn->buf, sizeof(uint32_t));
364 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
366 if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
367 errmsg = "Authentication required";
368 else if (conn->cmd == SDB_CONNECTION_IDLE)
369 errmsg = "Invalid command 0";
371 if (errmsg) {
372 size_t len = sdb_strbuf_len(conn->buf);
374 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
375 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
376 (uint32_t)strlen(errmsg), errmsg);
377 conn->skip_len += conn->cmd_len;
378 conn->cmd = SDB_CONNECTION_IDLE;
379 conn->cmd_len = 0;
381 if (len > conn->skip_len)
382 len = conn->skip_len;
383 sdb_strbuf_skip(conn->buf, 0, len);
384 conn->skip_len -= len;
385 /* connection_read will handle anything else */
386 }
387 return 0;
388 } /* command_init */
390 /* returns negative value on error, 0 on EOF, number of octets else */
391 static ssize_t
392 connection_read(sdb_conn_t *conn)
393 {
394 ssize_t n = 0;
396 if ((! conn) || (conn->fd < 0))
397 return -1;
399 while (42) {
400 ssize_t status;
402 errno = 0;
403 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
404 if (status < 0) {
405 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
406 break;
408 close(conn->fd);
409 conn->fd = -1;
410 return (int)status;
411 }
412 else if (! status) /* EOF */
413 break;
415 if (conn->skip_len) {
416 size_t len = (size_t)status < conn->skip_len
417 ? (size_t)status : conn->skip_len;
418 sdb_strbuf_skip(conn->buf, 0, len);
419 conn->skip_len -= len;
420 }
422 n += status;
424 /* give the main loop a chance to execute commands (and free up buffer
425 * space) on large amounts of incoming traffic */
426 if (n > 1024 * 1024)
427 break;
428 }
430 return n;
431 } /* connection_read */
433 /*
434 * public API
435 */
437 int
438 sdb_connection_enable_logging(void)
439 {
440 return sdb_plugin_register_log("connection-logger", connection_log,
441 /* user_data = */ NULL);
442 } /* sdb_connection_enable_logging */
444 sdb_conn_t *
445 sdb_connection_accept(int fd)
446 {
447 if (fd < 0)
448 return NULL;
450 /* the placeholder will be replaced with the accepted file
451 * descriptor when initializing the object */
452 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
453 connection_type, fd));
454 } /* sdb_connection_create */
456 void
457 sdb_connection_close(sdb_conn_t *conn)
458 {
459 if (! conn)
460 return;
462 /* close the connection even if someone else still references it */
463 if (conn->fd >= 0)
464 close(conn->fd);
465 conn->fd = -1;
466 } /* sdb_connection_close */
468 ssize_t
469 sdb_connection_handle(sdb_conn_t *conn)
470 {
471 ssize_t n = 0;
473 sdb_conn_set_ctx(conn);
475 while (42) {
476 ssize_t status = connection_read(conn);
478 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
479 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
480 command_init(conn);
481 if ((conn->cmd != SDB_CONNECTION_IDLE)
482 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
483 command_handle(conn);
485 /* remove the command from the buffer */
486 if (conn->cmd_len)
487 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
488 conn->cmd = SDB_CONNECTION_IDLE;
489 conn->cmd_len = 0;
490 }
492 if (status <= 0)
493 break;
495 n += status;
496 }
498 sdb_conn_set_ctx(NULL);
499 return n;
500 } /* sdb_connection_handle */
502 ssize_t
503 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
504 uint32_t msg_len, const char *msg)
505 {
506 char buf[2 * sizeof(uint32_t) + msg_len];
507 ssize_t status;
509 if ((! conn) || (conn->fd < 0))
510 return -1;
511 if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
512 return -1;
514 status = sdb_write(conn->fd, sizeof(buf), buf);
515 if (status < 0) {
516 char errbuf[1024];
518 /* tell other code that there was a problem and, more importantly,
519 * make sure we don't try to send further logs to the connection */
520 close(conn->fd);
521 conn->fd = -1;
522 conn->ready = 0;
524 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
525 "(code: %u, len: %u) to client: %s", code, msg_len,
526 sdb_strerror(errno, errbuf, sizeof(errbuf)));
527 }
528 return status;
529 } /* sdb_connection_send */
531 int
532 sdb_connection_ping(sdb_conn_t *conn)
533 {
534 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
535 return -1;
537 /* we're alive */
538 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
539 return 0;
540 } /* sdb_connection_ping */
542 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */