Code

connection: Log peer information after accepting a connection.
[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 <sys/socket.h>
48 #include <sys/un.h>
50 #include <stdlib.h>
51 #include <string.h>
53 #include <pthread.h>
54 #include <netdb.h>
56 /*
57  * private variables
58  */
60 static pthread_key_t conn_ctx_key;
61 static bool          conn_ctx_key_initialized = 0;
63 /*
64  * private types
65  */
67 /* name of connection objects */
68 #define CONN_FD_PREFIX "conn#"
69 #define CONN_FD_PLACEHOLDER "XXXXXXX"
71 static ssize_t
72 conn_read(sdb_conn_t *conn, size_t len)
73 {
74         return sdb_strbuf_read(conn->buf, conn->fd, len);
75 } /* conn_read */
77 static ssize_t
78 conn_write(sdb_conn_t *conn, const void *buf, size_t len)
79 {
80         return sdb_write(conn->fd, len, buf);
81 } /* conn_write */
83 static int
84 connection_init(sdb_object_t *obj, va_list ap)
85 {
86         sdb_conn_t *conn;
87         int sock_fd;
88         int sock_fl;
90         assert(obj);
91         conn = CONN(obj);
93         sock_fd = va_arg(ap, int);
95         conn->buf = sdb_strbuf_create(/* size = */ 128);
96         if (! conn->buf) {
97                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
98                                 "for a new connection");
99                 return -1;
100         }
101         conn->errbuf = sdb_strbuf_create(0);
102         if (! conn->errbuf) {
103                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate an error buffer "
104                                 "for a new connection");
105                 return -1;
106         }
108         conn->client_addr_len = sizeof(conn->client_addr);
109         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
110                         &conn->client_addr_len);
112         if (conn->fd < 0) {
113                 char buf[1024];
114                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
115                                 "connection: %s", sdb_strerror(errno,
116                                         buf, sizeof(buf)));
117                 return -1;
118         }
120         /* update the object name */
121         snprintf(obj->name + strlen(CONN_FD_PREFIX),
122                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
124         /* defaults */
125         conn->read = conn_read;
126         conn->write = conn_write;
127         conn->finish = NULL;
128         conn->session = NULL;
130         sock_fl = fcntl(conn->fd, F_GETFL);
131         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
132                 char buf[1024];
133                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
134                                 "to non-blocking mode: %s", conn->fd,
135                                 sdb_strerror(errno, buf, sizeof(buf)));
136                 return -1;
137         }
139         conn->username = NULL;
140         conn->ready = 0;
142         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
143                         conn->fd);
145         conn->cmd = SDB_CONNECTION_IDLE;
146         conn->cmd_len = 0;
147         conn->skip_len = 0;
148         return 0;
149 } /* connection_init */
151 static void
152 connection_destroy(sdb_object_t *obj)
154         sdb_conn_t *conn;
155         size_t len;
157         assert(obj);
158         conn = CONN(obj);
160         conn->ready = 0;
162         if (conn->finish)
163                 conn->finish(conn);
164         conn->finish = NULL;
166         if (conn->buf) {
167                 len = sdb_strbuf_len(conn->buf);
168                 if (len)
169                         sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
170                                         "(%zu byte%s left in buffer)", len, len == 1 ? "" : "s");
171         }
173         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection %s", obj->name);
174         sdb_connection_close(conn);
176         if (conn->username)
177                 free(conn->username);
178         conn->username = NULL;
180         sdb_strbuf_destroy(conn->buf);
181         conn->buf = NULL;
182         sdb_strbuf_destroy(conn->errbuf);
183         conn->errbuf = NULL;
184 } /* connection_destroy */
186 static sdb_type_t connection_type = {
187         /* size = */ sizeof(sdb_conn_t),
188         /* init = */ connection_init,
189         /* destroy = */ connection_destroy,
190 };
192 /*
193  * private helper functions
194  */
196 static void
197 sdb_conn_ctx_destructor(void *c)
199         sdb_object_t *conn = c;
201         if (! conn)
202                 return;
203         sdb_object_deref(conn);
204 } /* sdb_conn_ctx_destructor */
206 static void
207 sdb_conn_ctx_init(void)
209         if (conn_ctx_key_initialized)
210                 return;
212         pthread_key_create(&conn_ctx_key, sdb_conn_ctx_destructor);
213         conn_ctx_key_initialized = 1;
214 } /* sdb_conn_ctx_init */
216 static void
217 sdb_conn_set_ctx(sdb_conn_t *conn)
219         sdb_conn_t *old;
221         sdb_conn_ctx_init();
223         old = pthread_getspecific(conn_ctx_key);
224         if (old)
225                 sdb_object_deref(SDB_OBJ(old));
226         if (conn)
227                 sdb_object_ref(SDB_OBJ(conn));
228         pthread_setspecific(conn_ctx_key, conn);
229 } /* sdb_conn_set_ctx */
231 static sdb_conn_t *
232 sdb_conn_get_ctx(void)
234         if (! conn_ctx_key_initialized)
235                 return NULL;
236         return pthread_getspecific(conn_ctx_key);
237 } /* sdb_conn_get_ctx */
239 /*
240  * connection handler functions
241  */
243 /*
244  * connection_log:
245  * Send a log message originating from the current thread to the client.
246  */
247 static int
248 connection_log(int prio, const char *msg,
249                 sdb_object_t __attribute__((unused)) *user_data)
251         uint32_t len = (uint32_t)sizeof(uint32_t) + (uint32_t)strlen(msg);
252         uint32_t p = htonl((uint32_t)prio);
253         char tmp[len + 1];
255         sdb_conn_t *conn;
257         conn = sdb_conn_get_ctx();
258         /* no connection associated to this thread
259          * or startup not done yet => don't leak any information */
260         if ((! conn) || (! conn->ready))
261                 return 0;
263         /* XXX: make the log-level configurable by the client at runtime */
264         if (prio >= SDB_LOG_DEBUG)
265                 return 0;
267         memcpy(tmp, &p, sizeof(p));
268         strcpy(tmp + sizeof(p), msg);
270         if (sdb_connection_send(conn, SDB_CONNECTION_LOG, len, tmp) < 0)
271                 return -1;
272         return 0;
273 } /* connection_log */
275 static int
276 command_handle(sdb_conn_t *conn)
278         int status = -1;
280         assert(conn && (conn->cmd != SDB_CONNECTION_IDLE));
281         assert(! conn->skip_len);
283         sdb_log(SDB_LOG_DEBUG, "frontend: Handling command %u (len: %u)",
284                         conn->cmd, conn->cmd_len);
286         if (conn->cmd == SDB_CONNECTION_PING)
287                 status = sdb_connection_ping(conn);
288         else if (conn->cmd == SDB_CONNECTION_STARTUP)
289                 status = sdb_fe_session_start(conn);
290         else if (conn->cmd == SDB_CONNECTION_QUERY)
291                 status = sdb_fe_query(conn);
292         else if (conn->cmd == SDB_CONNECTION_FETCH)
293                 status = sdb_fe_fetch(conn);
294         else if (conn->cmd == SDB_CONNECTION_LIST)
295                 status = sdb_fe_list(conn);
296         else if (conn->cmd == SDB_CONNECTION_LOOKUP)
297                 status = sdb_fe_lookup(conn);
298         else if (conn->cmd == SDB_CONNECTION_STORE)
299                 status = sdb_fe_store(conn);
300         else {
301                 sdb_log(SDB_LOG_WARNING, "frontend: Ignoring invalid command %#x",
302                                 conn->cmd);
303                 sdb_strbuf_sprintf(conn->errbuf, "Invalid command %#x", conn->cmd);
304                 status = -1;
305         }
307         if (status) {
308                 if (! sdb_strbuf_len(conn->errbuf))
309                         sdb_strbuf_sprintf(conn->errbuf, "Failed to execute command");
310                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
311                                 (uint32_t)sdb_strbuf_len(conn->errbuf),
312                                 sdb_strbuf_string(conn->errbuf));
313         }
314         return status;
315 } /* command_handle */
317 /* initialize the connection state information */
318 static int
319 command_init(sdb_conn_t *conn)
321         const char *errmsg = NULL;
323         assert(conn && (conn->cmd == SDB_CONNECTION_IDLE) && (! conn->cmd_len));
325         if (conn->skip_len)
326                 return -1;
328         /* reset */
329         sdb_strbuf_clear(conn->errbuf);
331         if (sdb_proto_unmarshal_header(SDB_STRBUF_STR(conn->buf),
332                                 &conn->cmd, &conn->cmd_len) < 0)
333                 return -1;
334         sdb_strbuf_skip(conn->buf, 0, 2 * sizeof(uint32_t));
336         if ((! conn->ready) && (conn->cmd != SDB_CONNECTION_STARTUP))
337                 errmsg = "Authentication required";
338         else if (conn->cmd == SDB_CONNECTION_IDLE)
339                 errmsg = "Invalid command 0";
341         if (errmsg) {
342                 size_t len = sdb_strbuf_len(conn->buf);
344                 sdb_strbuf_sprintf(conn->errbuf, "%s", errmsg);
345                 sdb_connection_send(conn, SDB_CONNECTION_ERROR,
346                                 (uint32_t)strlen(errmsg), errmsg);
347                 conn->skip_len += conn->cmd_len;
348                 conn->cmd = SDB_CONNECTION_IDLE;
349                 conn->cmd_len = 0;
351                 if (len > conn->skip_len)
352                         len = conn->skip_len;
353                 sdb_strbuf_skip(conn->buf, 0, len);
354                 conn->skip_len -= len;
355                 /* connection_read will handle anything else */
356         }
357         return 0;
358 } /* command_init */
360 /* returns negative value on error, 0 on EOF, number of octets else */
361 static ssize_t
362 connection_read(sdb_conn_t *conn)
364         ssize_t n = 0;
366         if ((! conn) || (conn->fd < 0))
367                 return -1;
369         while (42) {
370                 ssize_t status;
372                 errno = 0;
373                 status = conn->read(conn, 1024);
374                 if (status < 0) {
375                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
376                                 break;
378                         sdb_connection_close(conn);
379                         return (int)status;
380                 }
381                 else if (! status) /* EOF */
382                         break;
384                 if (conn->skip_len) {
385                         size_t len = (size_t)status < conn->skip_len
386                                 ? (size_t)status : conn->skip_len;
387                         sdb_strbuf_skip(conn->buf, 0, len);
388                         conn->skip_len -= len;
389                 }
391                 n += status;
393                 /* give the main loop a chance to execute commands (and free up buffer
394                  * space) on large amounts of incoming traffic */
395                 if (n > 1024 * 1024)
396                         break;
397         }
399         return n;
400 } /* connection_read */
402 /*
403  * public API
404  */
406 int
407 sdb_connection_enable_logging(void)
409         return sdb_plugin_register_log("connection-logger", connection_log,
410                         /* user_data = */ NULL);
411 } /* sdb_connection_enable_logging */
413 sdb_conn_t *
414 sdb_connection_accept(int fd, sdb_conn_setup_cb setup, void *user_data)
416         sdb_conn_t *conn;
417         const char *peer = "unknown";
419         if (fd < 0)
420                 return NULL;
422         /* the placeholder will be replaced with the accepted file
423          * descriptor when initializing the object */
424         conn = CONN(sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
425                                 connection_type, fd));
426         if (setup && (setup(conn, user_data) < 0)) {
427                 sdb_object_deref(SDB_OBJ(conn));
428                 return NULL;
429         }
431         if (conn->username)
432                 peer = conn->username;
434         if (conn->client_addr.ss_family == AF_UNIX) {
435                 sdb_log(SDB_LOG_INFO,
436                                 "frontend: Accepted connection from peer %s", peer);
437         }
438         else {
439                 char host[1024] = "<unknown>", port[32] = "";
440                 getnameinfo((struct sockaddr *)&conn->client_addr,
441                                 conn->client_addr_len, host, sizeof(host), port, sizeof(port),
442                                 NI_NUMERICHOST | NI_NUMERICSERV);
443                 sdb_log(SDB_LOG_INFO, "frontend: Accepted connection from "
444                                 "peer %s at %s:%s", peer, host, port);
445         }
446         return conn;
447 } /* sdb_connection_create */
449 void
450 sdb_connection_close(sdb_conn_t *conn)
452         if (! conn)
453                 return;
455         if (conn->finish)
456                 conn->finish(conn);
457         conn->finish = NULL;
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 = conn->write(conn, buf, sizeof(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 : */