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"
40 #include <assert.h>
41 #include <errno.h>
43 #include <arpa/inet.h>
44 #include <fcntl.h>
46 #include <stdlib.h>
47 #include <string.h>
49 #include <sys/socket.h>
50 #include <sys/types.h>
51 #include <sys/param.h>
53 #ifdef HAVE_UCRED_H
54 # include <ucred.h>
55 #endif
56 #ifdef HAVE_SYS_UCRED_H
57 # include <sys/ucred.h>
58 #endif
60 #include <pwd.h>
62 #include <pthread.h>
64 /*
65 * private variables
66 */
68 static pthread_key_t conn_ctx_key;
69 static bool conn_ctx_key_initialized = 0;
71 /*
72 * private types
73 */
75 /* name of connection objects */
76 #define CONN_FD_PREFIX "conn#"
77 #define CONN_FD_PLACEHOLDER "XXXXXXX"
79 /* XXX: only supports UNIX sockets so far */
80 static char *
81 peer(int sockfd)
82 {
83 uid_t uid;
85 struct passwd pw_entry;
86 struct passwd *result = NULL;
87 char buf[1024];
89 #ifdef SO_PEERCRED
90 struct ucred cred;
91 socklen_t len = sizeof(cred);
93 if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cred, &len)
94 || (len != sizeof(cred)))
95 return NULL;
96 uid = cred.uid;
97 #else /* SO_PEERCRED */
98 errno = ENOSYS;
99 return NULL;
100 #endif
102 memset(&pw_entry, 0, sizeof(pw_entry));
103 if (getpwuid_r(uid, &pw_entry, buf, sizeof(buf), &result)
104 || (! result))
105 return NULL;
106 return strdup(result->pw_name);
107 } /* peer */
109 static int
110 connection_init(sdb_object_t *obj, va_list ap)
111 {
112 sdb_conn_t *conn;
113 int sock_fd;
114 int sock_fl;
116 assert(obj);
117 conn = CONN(obj);
119 sock_fd = va_arg(ap, int);
121 conn->buf = sdb_strbuf_create(/* size = */ 128);
122 if (! conn->buf) {
123 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
124 "for a new connection");
125 return -1;
126 }
127 conn->errbuf = sdb_strbuf_create(0);
128 if (! conn->errbuf) {
129 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
130 "for a new connection");
131 return -1;
132 }
134 conn->client_addr_len = sizeof(conn->client_addr);
135 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
136 &conn->client_addr_len);
138 if (conn->fd < 0) {
139 char buf[1024];
140 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
141 "connection: %s", sdb_strerror(errno,
142 buf, sizeof(buf)));
143 return -1;
144 }
146 if (conn->client_addr.ss_family != AF_UNIX) {
147 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
148 "unexpected family type %d", conn->client_addr.ss_family);
149 return -1;
150 }
152 sock_fl = fcntl(conn->fd, F_GETFL);
153 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
154 char buf[1024];
155 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
156 "to non-blocking mode: %s", conn->fd,
157 sdb_strerror(errno, buf, sizeof(buf)));
158 return -1;
159 }
161 conn->username = peer(conn->fd);
162 if (! conn->username) {
163 char buf[1024];
164 sdb_log(SDB_LOG_ERR, "frontend: Failed to retrieve peer for "
165 "connection conn#%i: %s", conn->fd,
166 sdb_strerror(errno, buf, sizeof(buf)));
167 return -1;
168 }
169 conn->ready = 0;
171 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
172 conn->fd);
174 conn->cmd = SDB_CONNECTION_IDLE;
175 conn->cmd_len = 0;
176 conn->skip_len = 0;
178 /* update the object name */
179 snprintf(obj->name + strlen(CONN_FD_PREFIX),
180 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
181 return 0;
182 } /* connection_init */
184 static void
185 connection_destroy(sdb_object_t *obj)
186 {
187 sdb_conn_t *conn;
188 size_t len;
190 assert(obj);
191 conn = CONN(obj);
193 conn->ready = 0;
195 if (conn->buf) {
196 len = sdb_strbuf_len(conn->buf);
197 if (len)
198 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
199 "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
200 }
202 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
203 if (conn->fd >= 0)
204 close(conn->fd);
205 conn->fd = -1;
207 if (conn->username)
208 free(conn->username);
209 conn->username = NULL;
211 sdb_strbuf_destroy(conn->buf);
212 conn->buf = NULL;
213 sdb_strbuf_destroy(conn->errbuf);
214 conn->errbuf = NULL;
215 } /* connection_destroy */
217 static sdb_type_t connection_type = {
218 /* size = */ sizeof(sdb_conn_t),
219 /* init = */ connection_init,
220 /* destroy = */ connection_destroy,
221 };
223 /*
224 * private helper functions
225 */
227 static void
228 sdb_conn_ctx_destructor(void *c)
229 {
230 sdb_object_t *conn = c;
232 if (! conn)
233 return;
234 sdb_object_deref(conn);
235 } /* sdb_conn_ctx_destructor */
237 static void
238 sdb_conn_ctx_init(void)
239 {
240 if (conn_ctx_key_initialized)
241 return;
243 pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
244 conn_ctx_key_initialized = 1;
245 } /* sdb_conn_ctx_init */
247 static void
248 sdb_conn_set_ctx(sdb_conn_t *conn)
249 {
250 sdb_conn_t *old;
252 sdb_conn_ctx_init();
254 old = pthread_getspecific(conn_ctx_key);
255 if (old)
256 sdb_object_deref(SDB_OBJ(old));
257 if (conn)
258 sdb_object_ref(SDB_OBJ(conn));
259 pthread_setspecific(conn_ctx_key, conn);
260 } /* sdb_conn_set_ctx */
262 static sdb_conn_t *
263 sdb_conn_get_ctx(void)
264 {
265 if (! conn_ctx_key_initialized)
266 return NULL;
267 return pthread_getspecific(conn_ctx_key);
268 } /* sdb_conn_get_ctx */
270 /*
271 * connection handler functions
272 */
274 /*
275 * connection_log:
276 * Send a log message originating from the current thread to the client.
277 */
278 static int
279 connection_log(int prio, const char *msg,
280 sdb_object_t __attribute__((unused)) *user_data)
281 {
282 uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
283 uint32_t p = htonl((uint32_t)prio);
284 char tmp[len + 1];
286 sdb_conn_t *conn;
288 conn = sdb_conn_get_ctx();
289 /* no connection associated to this thread
290 * or startup not done yet => don't leak any information */
291 if ((! conn) || (! conn->ready))
292 return 0;
294 /* XXX: make the log-level configurable by the client at runtime */
295 if (prio >= SDB_LOG_DEBUG)
296 return 0;
298 memcpy(tmp, &p, sizeof(p));
299 strcpy(tmp + sizeof(p), msg);
301 if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
302 return -1;
303 return 0;
304 } /* connection_log */
306 static int
307 command_handle(sdb_conn_t *conn)
308 {
309 int status = -1;
311 assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
312 assert(! conn->skip_len);
314 sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
315 conn->cmd, conn->cmd_len);
317 if (conn->cmd == SDB_CONNECTION_PING)
318 status = sdb_connection_ping(conn);
319 else if (conn->cmd == SDB_CONNECTION_STARTUP)
320 status = sdb_fe_session_start(conn);
321 else if (conn->cmd == SDB_CONNECTION_QUERY)
322 status = sdb_fe_query(conn);
323 else if (conn->cmd == SDB_CONNECTION_FETCH)
324 status = sdb_fe_fetch(conn);
325 else if (conn->cmd == SDB_CONNECTION_LIST)
326 status = sdb_fe_list(conn);
327 else if (conn->cmd == SDB_CONNECTION_LOOKUP)
328 status = sdb_fe_lookup(conn);
329 else {
330 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
331 conn->cmd);
332 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
333 status = -1;
334 }
336 if (status) {
337 if (! sdb_strbuf_len(conn->errbuf))
338 sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
339 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
340 (uint32_t)sdb_strbuf_len(conn->errbuf),
341 sdb_strbuf_string(conn->errbuf));
342 }
343 return status;
344 } /* command_handle */
346 /* initialize the connection state information */
347 static int
348 command_init(sdb_conn_t *conn)
349 {
350 const char *errmsg = NULL;
352 assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
354 if (conn->skip_len)
355 return -1;
357 /* reset */
358 sdb_strbuf_clear(conn->errbuf);
360 conn->cmd = sdb_proto_get_int(conn->buf, 0);
361 conn->cmd_len = sdb_proto_get_int(conn->buf, sizeof(uint32_t));
363 sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
365 if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
366 errmsg = "Authentication required";
367 else if (conn->cmd == SDB_CONNECTION_IDLE)
368 errmsg = "Invalid command 0";
370 if (errmsg) {
371 size_t len = sdb_strbuf_len(conn->buf);
373 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
374 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
375 (uint32_t)strlen(errmsg), errmsg);
376 conn->skip_len += conn->cmd_len;
377 conn->cmd = SDB_CONNECTION_IDLE;
378 conn->cmd_len = 0;
380 if (len > conn->skip_len)
381 len = conn->skip_len;
382 sdb_strbuf_skip(conn->buf, 0, len);
383 conn->skip_len -= len;
384 /* connection_read will handle anything else */
385 }
386 return 0;
387 } /* command_init */
389 /* returns negative value on error, 0 on EOF, number of octets else */
390 static ssize_t
391 connection_read(sdb_conn_t *conn)
392 {
393 ssize_t n = 0;
395 if ((! conn) || (conn->fd < 0))
396 return -1;
398 while (42) {
399 ssize_t status;
401 errno = 0;
402 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
403 if (status < 0) {
404 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
405 break;
407 close(conn->fd);
408 conn->fd = -1;
409 return (int)status;
410 }
411 else if (! status) /* EOF */
412 break;
414 if (conn->skip_len) {
415 size_t len = (size_t)status < conn->skip_len
416 ? (size_t)status : conn->skip_len;
417 sdb_strbuf_skip(conn->buf, 0, len);
418 conn->skip_len -= len;
419 }
421 n += status;
423 /* give the main loop a chance to execute commands (and free up buffer
424 * space) on large amounts of incoming traffic */
425 if (n > 1024 * 1024)
426 break;
427 }
429 return n;
430 } /* connection_read */
432 /*
433 * public API
434 */
436 int
437 sdb_connection_enable_logging(void)
438 {
439 return sdb_plugin_register_log("connection-logger", connection_log,
440 /* user_data = */ NULL);
441 } /* sdb_connection_enable_logging */
443 sdb_conn_t *
444 sdb_connection_accept(int fd)
445 {
446 if (fd < 0)
447 return NULL;
449 /* the placeholder will be replaced with the accepted file
450 * descriptor when initializing the object */
451 return CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
452 connection_type, fd));
453 } /* sdb_connection_create */
455 void
456 sdb_connection_close(sdb_conn_t *conn)
457 {
458 if (! conn)
459 return;
461 /* close the connection even if someone else still references it */
462 if (conn->fd >= 0)
463 close(conn->fd);
464 conn->fd = -1;
466 sdb_object_deref(SDB_OBJ(conn));
467 } /* sdb_connection_close */
469 ssize_t
470 sdb_connection_read(sdb_conn_t *conn)
471 {
472 ssize_t n = 0;
474 sdb_conn_set_ctx(conn);
476 while (42) {
477 ssize_t status = connection_read(conn);
479 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
480 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
481 command_init(conn);
482 if ((conn->cmd != SDB_CONNECTION_IDLE)
483 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
484 command_handle(conn);
486 /* remove the command from the buffer */
487 if (conn->cmd_len)
488 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
489 conn->cmd = SDB_CONNECTION_IDLE;
490 conn->cmd_len = 0;
491 }
493 if (status <= 0)
494 break;
496 n += status;
497 }
499 sdb_conn_set_ctx(NULL);
500 return n;
501 } /* sdb_connection_read */
503 ssize_t
504 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
505 uint32_t msg_len, const char *msg)
506 {
507 ssize_t status;
509 if ((! conn) || (conn->fd < 0))
510 return -1;
512 status = sdb_proto_send_msg(conn->fd, code, msg_len, msg);
513 if (status < 0) {
514 char errbuf[1024];
516 /* tell other code that there was a problem and, more importantly,
517 * make sure we don't try to send further logs to the connection */
518 close(conn->fd);
519 conn->fd = -1;
520 conn->ready = 0;
522 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
523 "(code: %u, len: %u) to client: %s", code, msg_len,
524 sdb_strerror(errno, errbuf, sizeof(errbuf)));
525 }
526 return status;
527 } /* sdb_connection_send */
529 int
530 sdb_connection_ping(sdb_conn_t *conn)
531 {
532 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
533 return -1;
535 /* we're alive */
536 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
537 return 0;
538 } /* sdb_connection_ping */
540 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */