Version 0.4
[apps/pfixtools.git] / postlicyd / main-postlicyd.c
index 60ecb3a..08c6a2b 100644 (file)
 
 #include "buffer.h"
 #include "common.h"
-#include "epoll.h"
 #include "policy_tokens.h"
 #include "server.h"
-#include "query.h"
 #include "config.h"
+#include "query.h"
 
 #define DAEMON_NAME             "postlicyd"
+#define DAEMON_VERSION          "0.4"
 #define DEFAULT_PORT            10000
 #define RUNAS_USER              "nobody"
 #define RUNAS_GROUP             "nogroup"
 
 DECLARE_MAIN
 
-static void *query_starter(server_t* server)
+typedef struct query_context_t {
+    query_t query;
+    filter_context_t context;
+    client_t *client;
+} query_context_t;
+
+static config_t *config  = NULL;
+static bool refresh      = false;
+static PA(client_t) busy = ARRAY_INIT;
+
+static void *query_starter(listener_t* server)
 {
-    return query_new();
+    query_context_t *context = p_new(query_context_t, 1);
+    filter_context_prepare(&context->context, context);
+    return context;
 }
 
-static bool config_refresh(void *config)
+static void query_stopper(void *data)
 {
-    return config_reload(config);
+    query_context_t **context = data;
+    if (*context) {
+        filter_context_wipe(&(*context)->context);
+        p_delete(context);
+    }
 }
 
-__attribute__((format(printf,2,0)))
-static void policy_answer(server_t *pcy, const char *fmt, ...)
+static bool config_refresh(void *mconfig)
 {
-    va_list args;
-    const query_t* query = pcy->data;
-
-    buffer_addstr(&pcy->obuf, "action=");
-    va_start(args, fmt);
-    buffer_addvf(&pcy->obuf, fmt, args);
-    va_end(args);
-    buffer_addstr(&pcy->obuf, "\n\n");
-    buffer_consume(&pcy->ibuf, query->eoq - pcy->ibuf.data);
-    epoll_modify(pcy->fd, EPOLLIN | EPOLLOUT, pcy);
+    refresh = true;
+    if (filter_running > 0) {
+        return true;
+    }
+    bool ret = config_reload(mconfig);
+    foreach (client_t **server, busy) {
+        client_io_ro(*server);
+    }}
+    array_len(busy) = 0;
+    refresh = false;
+    return ret;
+}
+
+static void policy_answer(client_t *pcy, const char *message)
+{
+    query_context_t *context = client_data(pcy);
+    const query_t* query = &context->query;
+    buffer_t *buf = client_output_buffer(pcy);
+
+    /* Write reply "action=ACTION [text]" */
+    buffer_addstr(buf, "action=");
+    buffer_ensure(buf, m_strlen(message) + 64);
+
+    ssize_t size = array_size(*buf) - array_len(*buf);
+    ssize_t format_size = query_format(array_ptr(*buf, array_len(*buf)),
+                                       size, message, query);
+    if (format_size == -1) {
+        buffer_addstr(buf, message);
+    } else if (format_size > size) {
+        buffer_ensure(buf, format_size + 1);
+        query_format(array_ptr(*buf, array_len(*buf)),
+                     array_size(*buf) - array_len(*buf),
+                     message, query);
+        array_len(*buf) += format_size;
+    } else {
+        array_len(*buf) += format_size;
+    }
+    buffer_addstr(buf, "\n\n");
+
+    /* Finalize query. */
+    buf = client_input_buffer(pcy);
+    buffer_consume(buf, query->eoq - buf->data);
+    client_io_rw(pcy);
 }
 
-static bool policy_process(server_t *pcy, const config_t *config)
+static const filter_t *next_filter(client_t *pcy, const filter_t *filter,
+                                   const query_t *query, const filter_hook_t *hook, bool *ok) {
+#define MESSAGE_FORMAT "request client=%s from=<%s> to=<%s> at %s: "
+#define MESSAGE_PARAMS query->client_name,                                          \
+                  query->sender == NULL ? "undefined" : query->sender,              \
+                  query->recipient == NULL ? "undefined" : query->recipient,        \
+                  smtp_state_names[query->state]
+
+    if (hook != NULL) {
+        query_context_t *context = client_data(pcy);
+        if (hook->counter >= 0 && hook->counter < MAX_COUNTERS && hook->cost > 0) {
+            context->context.counters[hook->counter] += hook->cost;
+            debug(MESSAGE_FORMAT "added %d to counter %d (now %u)", MESSAGE_PARAMS,
+                  hook->cost, hook->counter, context->context.counters[hook->counter]);
+        }
+    }
+    if (hook == NULL) {
+        warn(MESSAGE_FORMAT "aborted", MESSAGE_PARAMS);
+        *ok = false;
+        return NULL;
+    } else if (hook->async) {
+        debug(MESSAGE_FORMAT "asynchronous filter from filter %s",
+              MESSAGE_PARAMS, filter->name);
+        *ok = true;
+        return NULL;
+    } else if (hook->postfix) {
+        info(MESSAGE_FORMAT "awswer %s from filter %s: \"%s\"", MESSAGE_PARAMS,
+             htokens[hook->type], filter->name, hook->value);
+        policy_answer(pcy, hook->value);
+        *ok = true;
+        return NULL;
+    } else {
+        debug(MESSAGE_FORMAT "awswer %s from filter %s: next filter %s",
+              MESSAGE_PARAMS, htokens[hook->type], filter->name,
+              (array_ptr(config->filters, hook->filter_id))->name);
+        return array_ptr(config->filters, hook->filter_id);
+    }
+#undef MESSAGE_PARAMS
+#undef MESSAGE_FORMAT
+}
+
+static bool policy_process(client_t *pcy, const config_t *mconfig)
 {
-    const query_t* query = pcy->data;
+    query_context_t *context = client_data(pcy);
+    const query_t* query = &context->query;
     const filter_t *filter;
-    if (config->entry_points[query->state] == -1) {
-        syslog(LOG_WARNING, "no filter defined for current protocol_state (%d)", query->state);
+    if (mconfig->entry_points[query->state] == -1) {
+        warn("no filter defined for current protocol_state (%s)", smtp_state_names[query->state]);
         return false;
     }
-    filter = array_ptr(config->filters, config->entry_points[query->state]);
+    if (context->context.current_filter != NULL) {
+        filter = context->context.current_filter;
+    } else {
+        filter = array_ptr(mconfig->filters, mconfig->entry_points[query->state]);
+    }
+    context->context.current_filter = NULL;
     while (true) {
-        const filter_hook_t *hook = filter_run(filter, query);
-        if (hook == NULL) {
-            syslog(LOG_WARNING, "request aborted");
-            return false;
-        } else if (hook->postfix) {
-            policy_answer(pcy, "%s", hook->value);
-            return true;
-        } else {
-            filter = array_ptr(config->filters, hook->filter_id);
+        bool  ok = false;
+        const filter_hook_t *hook = filter_run(filter, query, &context->context);
+        filter = next_filter(pcy, filter, query, hook, &ok);
+        if (filter == NULL) {
+            return ok;
         }
     }
 }
 
-static int policy_run(server_t *pcy, void* vconfig)
+static int policy_run(client_t *pcy, void* vconfig)
 {
-    ssize_t search_offs = MAX(0, (ssize_t)(pcy->ibuf.len - 1));
-    int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
+    const config_t *mconfig = vconfig;
+    if (refresh) {
+        array_add(busy, pcy);
+        return 0;
+    }
+
+    query_context_t *context = client_data(pcy);
+    query_t         *query   = &context->query;
+    context->client = pcy;
+
+    buffer_t *buf   = client_input_buffer(pcy);
+    int search_offs = MAX(0, (int)(buf->len - 1));
+    int nb          = client_read(pcy);
     const char *eoq;
-    query_t  *query  = pcy->data;
-    const config_t *config = vconfig;
 
     if (nb < 0) {
         if (errno == EAGAIN || errno == EINTR)
@@ -114,25 +214,62 @@ static int policy_run(server_t *pcy, void* vconfig)
         return -1;
     }
     if (nb == 0) {
-        if (pcy->ibuf.len)
-            syslog(LOG_ERR, "unexpected end of data");
+        if (buf->len)
+            err("unexpected end of data");
         return -1;
     }
 
-    if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
+    if (!(eoq = strstr(buf->data + search_offs, "\n\n"))) {
         return 0;
+    }
 
-    if (!query_parse(pcy->data, pcy->ibuf.data))
+    if (!query_parse(query, buf->data)) {
         return -1;
+    }
     query->eoq = eoq + strlen("\n\n");
-    epoll_modify(pcy->fd, 0, pcy);
-    return policy_process(pcy, config) ? 0 : -1;
+
+    /* The instance changed => reset the static context */
+    if (query->instance == NULL || strcmp(context->context.instance, query->instance) != 0) {
+        filter_context_clean(&context->context);
+        m_strcat(context->context.instance, 64, query->instance);
+    }
+    client_io_none(pcy);
+    return policy_process(pcy, mconfig) ? 0 : -1;
+}
+
+static void policy_async_handler(filter_context_t *context,
+                                 const filter_hook_t *hook)
+{
+    bool ok = false;
+    const filter_t *filter = context->current_filter;
+    query_context_t *qctx  = context->data;
+    query_t         *query = &qctx->query;
+    client_t        *server = qctx->client;
+
+    context->current_filter = next_filter(server, filter, query, hook, &ok);
+    if (context->current_filter != NULL) {
+        ok = policy_process(server, config);
+    }
+    if (!ok) {
+        client_release(server);
+    }
+    if (refresh && filter_running == 0) {
+        config_refresh(config);
+    }
+}
+
+static int postlicyd_init(void)
+{
+    filter_async_handler_register(policy_async_handler);
+    return 0;
 }
 
-int start_listener(int port)
+static void postlicyd_shutdown(void)
 {
-    return start_server(port, NULL, NULL);
+    array_deep_wipe(busy, client_delete);
 }
+module_init(postlicyd_init);
+module_exit(postlicyd_shutdown);
 
 /* administrivia {{{ */
 
@@ -144,6 +281,8 @@ void usage(void)
           "    -l <port>    port to listen to\n"
           "    -p <pidfile> file to write our pid to\n"
           "    -f           stay in foreground\n"
+          "    -d           grow logging level\n"
+          "    -u           unsafe mode (don't drop privileges)\n"
          , stderr);
 }
 
@@ -157,7 +296,7 @@ int main(int argc, char *argv[])
     int port = DEFAULT_PORT;
     bool port_from_cli = false;
 
-    for (int c = 0; (c = getopt(argc, argv, "hf" "l:p:")) >= 0; ) {
+    for (int c = 0; (c = getopt(argc, argv, "ufd" "l:p:")) >= 0; ) {
         switch (c) {
           case 'p':
             pidfile = optarg;
@@ -172,23 +311,37 @@ int main(int argc, char *argv[])
           case 'f':
             daemonize = false;
             break;
+          case 'd':
+            ++log_level;
+            break;
           default:
             usage();
             return EXIT_FAILURE;
         }
     }
 
+    if (!daemonize) {
+        log_syslog = false;
+    }
+
     if (argc - optind != 1) {
         usage();
         return EXIT_FAILURE;
     }
 
+    info("%s v%s...", DAEMON_NAME, DAEMON_VERSION);
+
+    if (pidfile_open(pidfile) < 0) {
+        crit("unable to write pidfile %s", pidfile);
+        return EXIT_FAILURE;
+    }
+
     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
-        syslog(LOG_CRIT, "unable to drop privileges");
+        crit("unable to drop privileges");
         return EXIT_FAILURE;
     }
 
-    config_t *config = config_read(argv[optind]);
+    config = config_read(argv[optind]);
     if (config == NULL) {
         return EXIT_FAILURE;
     }
@@ -196,14 +349,17 @@ int main(int argc, char *argv[])
         config->port = port;
     }
 
-    if (common_setup(pidfile, true, NULL, NULL, daemonize) != EXIT_SUCCESS
-        || start_listener(config->port) < 0) {
-        config_delete(&config);
+    if (daemonize && daemon_detach() < 0) {
+        crit("unable to fork");
+        return EXIT_FAILURE;
+    }
+
+    pidfile_refresh();
+
+    if (start_listener(config->port) == NULL) {
         return EXIT_FAILURE;
     } else {
-        int res = server_loop(query_starter, (delete_client_t)query_delete,
-                              policy_run, config_refresh, config);
-        config_delete(&config);
-        return res;
+        return server_loop(query_starter, query_stopper,
+                           policy_run, config_refresh, config);
     }
 }