09f906c045183fc9ab4e6d59b538580d7eed5e1f
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 if (sdb_proto_unmarshal_header(conn->buf, &conn->cmd, &conn->cmd_len))
362 return -1;
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;
465 } /* sdb_connection_close */
467 ssize_t
468 sdb_connection_handle(sdb_conn_t *conn)
469 {
470 ssize_t n = 0;
472 sdb_conn_set_ctx(conn);
474 while (42) {
475 ssize_t status = connection_read(conn);
477 if ((conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len)
478 && (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t)))
479 command_init(conn);
480 if ((conn->cmd != SDB_CONNECTION_IDLE)
481 && (sdb_strbuf_len(conn->buf) >= conn->cmd_len)) {
482 command_handle(conn);
484 /* remove the command from the buffer */
485 if (conn->cmd_len)
486 sdb_strbuf_skip(conn->buf, 0, conn->cmd_len);
487 conn->cmd = SDB_CONNECTION_IDLE;
488 conn->cmd_len = 0;
489 }
491 if (status <= 0)
492 break;
494 n += status;
495 }
497 sdb_conn_set_ctx(NULL);
498 return n;
499 } /* sdb_connection_handle */
501 ssize_t
502 sdb_connection_send(sdb_conn_t *conn, uint32_t code,
503 uint32_t msg_len, const char *msg)
504 {
505 char buf[2 * sizeof(uint32_t) + msg_len];
506 ssize_t status;
508 if ((! conn) || (conn->fd < 0))
509 return -1;
510 if (sdb_proto_marshal(buf, sizeof(buf), code, msg_len, msg) < 0)
511 return -1;
513 status = sdb_write(conn->fd, sizeof(buf), buf);
514 if (status < 0) {
515 char errbuf[1024];
517 /* tell other code that there was a problem and, more importantly,
518 * make sure we don't try to send further logs to the connection */
519 close(conn->fd);
520 conn->fd = -1;
521 conn->ready = 0;
523 sdb_log(SDB_LOG_ERR, "frontend: Failed to send msg "
524 "(code: %u, len: %u) to client: %s", code, msg_len,
525 sdb_strerror(errno, errbuf, sizeof(errbuf)));
526 }
527 return status;
528 } /* sdb_connection_send */
530 int
531 sdb_connection_ping(sdb_conn_t *conn)
532 {
533 if ((! conn) || (conn->cmd != SDB_CONNECTION_PING))
534 return -1;
536 /* we're alive */
537 sdb_connection_send(conn, SDB_CONNECTION_OK, 0, NULL);
538 return 0;
539 } /* sdb_connection_ping */
541 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */