Explorar o código

ncd: modules: add sys_request_server. Also add ncd-request tool.

ambrop7 %!s(int64=14) %!d(string=hai) anos
pai
achega
44039edcda

+ 1 - 0
CMakeLists.txt

@@ -273,6 +273,7 @@ endif ()
 # ncd
 if (BUILD_NCD)
     add_subdirectory(ncd)
+    add_subdirectory(ncd-request)
 endif ()
 
 message(STATUS "Building components:")

+ 2 - 0
blog_channels.txt

@@ -105,3 +105,5 @@ ncd_from_string 4
 ncd_to_string 4
 ncd_value 4
 ncd_try 4
+ncd_sys_request_server 4
+NCDRequest 4

+ 4 - 0
generated/blog_channel_NCDRequest.h

@@ -0,0 +1,4 @@
+#ifdef BLOG_CURRENT_CHANNEL
+#undef BLOG_CURRENT_CHANNEL
+#endif
+#define BLOG_CURRENT_CHANNEL BLOG_CHANNEL_NCDRequest

+ 4 - 0
generated/blog_channel_ncd_sys_request_server.h

@@ -0,0 +1,4 @@
+#ifdef BLOG_CURRENT_CHANNEL
+#undef BLOG_CURRENT_CHANNEL
+#endif
+#define BLOG_CURRENT_CHANNEL BLOG_CHANNEL_ncd_sys_request_server

+ 3 - 1
generated/blog_channels_defines.h

@@ -105,4 +105,6 @@
 #define BLOG_CHANNEL_ncd_to_string 104
 #define BLOG_CHANNEL_ncd_value 105
 #define BLOG_CHANNEL_ncd_try 106
-#define BLOG_NUM_CHANNELS 107
+#define BLOG_CHANNEL_ncd_sys_request_server 107
+#define BLOG_CHANNEL_NCDRequest 108
+#define BLOG_NUM_CHANNELS 109

+ 2 - 0
generated/blog_channels_list.h

@@ -105,3 +105,5 @@
 {.name = "ncd_to_string", .loglevel = 4},
 {.name = "ncd_value", .loglevel = 4},
 {.name = "ncd_try", .loglevel = 4},
+{.name = "ncd_sys_request_server", .loglevel = 4},
+{.name = "NCDRequest", .loglevel = 4},

+ 9 - 0
ncd-request/CMakeLists.txt

@@ -0,0 +1,9 @@
+add_executable(badvpn-ncd-request
+    ncd-request.c
+)
+target_link_libraries(badvpn-ncd-request ncdrequest)
+
+install(
+    TARGETS badvpn-ncd-request
+    RUNTIME DESTINATION bin
+)

+ 153 - 0
ncd-request/ncd-request.c

@@ -0,0 +1,153 @@
+/**
+ * @file ncd-request.c
+ * @author Ambroz Bizjak <ambrop7@gmail.com>
+ * 
+ * @section LICENSE
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the author nor the
+ *    names of its contributors may be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <base/BLog.h>
+#include <base/DebugObject.h>
+#include <system/BNetwork.h>
+#include <system/BReactor.h>
+#include <ncd/NCDValueParser.h>
+#include <ncd/NCDValueGenerator.h>
+#include <ncd/NCDRequest.h>
+
+static void request_handler_finished (void *user, int is_error);
+static void request_handler_reply (void *user, NCDValue reply_data);
+static int write_all (int fd, const uint8_t *data, size_t len);
+
+BReactor reactor;
+NCDRequest request;
+
+int main (int argc, char *argv[])
+{
+    int res = 1;
+    
+    if (argc != 3) {
+        fprintf(stderr, "Usage: %s <socket_path> <request_payload>\n", (argc > 0 ? argv[0] : ""));
+        goto fail0;
+    }
+    
+    char *socket_path = argv[1];
+    char *request_payload_string = argv[2];
+    
+    BLog_InitStderr();
+    
+    BTime_Init();
+    
+    if (!BNetwork_GlobalInit()) {
+        BLog(BLOG_ERROR, "BNetwork_Init failed");
+        goto fail1;
+    }
+    
+    if (!BReactor_Init(&reactor)) {
+        BLog(BLOG_ERROR, "BReactor_Init failed");
+        goto fail1;
+    }
+    
+    NCDValue request_payload;
+    if (!NCDValueParser_Parse(request_payload_string, strlen(request_payload_string), &request_payload)) {
+        BLog(BLOG_ERROR, "BReactor_Init failed");
+        goto fail2;
+    }
+    
+    if (!NCDRequest_Init(&request, socket_path, &request_payload, &reactor, NULL, request_handler_finished, request_handler_reply)) {
+        BLog(BLOG_ERROR, "NCDRequest_Init failed");
+        NCDValue_Free(&request_payload);
+        goto fail2;
+    }
+    NCDValue_Free(&request_payload);
+    
+    res = BReactor_Exec(&reactor);
+    
+    NCDRequest_Free(&request);
+fail2:
+    BReactor_Free(&reactor);
+fail1:
+    BLog_Free();
+fail0:
+    DebugObjectGlobal_Finish();
+    return res;
+}
+
+static void request_handler_finished (void *user, int is_error)
+{
+    if (is_error) {
+        BLog(BLOG_ERROR, "error");
+        BReactor_Quit(&reactor, 1);
+        return;
+    }
+    
+    BReactor_Quit(&reactor, 0);
+}
+
+static void request_handler_reply (void *user, NCDValue reply_data)
+{
+    char *str = NCDValueGenerator_Generate(&reply_data);
+    if (!str) {
+        BLog(BLOG_ERROR, "NCDValueGenerator_Generate failed");
+        goto fail0;
+    }
+    
+    if (!write_all(1, str, strlen(str))) {
+        goto fail1;
+    }
+    if (!write_all(1, "\n", 1)) {
+        goto fail1;
+    }
+    
+    NCDRequest_Next(&request);
+    
+    free(str);
+    NCDValue_Free(&reply_data);
+    return;
+    
+fail1:
+    free(str);
+fail0:
+    NCDValue_Free(&reply_data);
+    BReactor_Quit(&reactor, 1);
+}
+
+static int write_all (int fd, const uint8_t *data, size_t len)
+{
+    while (len > 0) {
+        ssize_t res = write(fd, data, len);
+        if (res <= 0) {
+            BLog(BLOG_ERROR, "write failed");
+            return 0;
+        }
+        data += res;
+        len -= res;
+    }
+    
+    return 1;
+}

+ 6 - 0
ncd/CMakeLists.txt

@@ -35,6 +35,11 @@ add_library(ncdvalue
 )
 target_link_libraries(ncdvalue ncdconfig)
 
+add_library(ncdrequest
+    NCDRequest.c
+)
+target_link_libraries(ncdrequest base system ncdvalue)
+
 add_executable(badvpn-ncd
     ncd.c
     NCDModule.c
@@ -91,6 +96,7 @@ add_executable(badvpn-ncd
     modules/net_watch_interfaces.c
     modules/sys_watch_input.c
     modules/sys_watch_usb.c
+    modules/sys_request_server.c
     ${NCD_ADDITIONAL_SOURCES}
 )
 target_link_libraries(badvpn-ncd system flow flowextra dhcpclient arpprobe ncdconfig ncdvalue udevmonitor)

+ 325 - 0
ncd/NCDRequest.c

@@ -0,0 +1,325 @@
+/**
+ * @file NCDRequest.c
+ * @author Ambroz Bizjak <ambrop7@gmail.com>
+ * 
+ * @section LICENSE
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the author nor the
+ *    names of its contributors may be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+#include <limits.h>
+
+#include <misc/byteorder.h>
+#include <misc/expstring.h>
+#include <protocol/packetproto.h>
+#include <protocol/requestproto.h>
+#include <base/BLog.h>
+
+#include "NCDRequest.h"
+
+#include <generated/blog_channel_NCDRequest.h>
+
+#define SEND_PAYLOAD_MTU 32768
+#define RECV_PAYLOAD_MTU 32768
+
+#define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header))
+#define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header))
+
+#define STATE_CONNECTING 1
+#define STATE_CONNECTED 2
+
+static int build_requestproto_packet (uint32_t request_id, uint32_t flags, NCDValue *payload_value, uint8_t **out_data, int *out_len);
+static void report_finished (NCDRequest *o, int is_error);
+static void connector_handler (NCDRequest *o, int is_error);
+static void connection_handler (NCDRequest *o, int event);
+static void decoder_handler_error (NCDRequest *o);
+static void recv_if_handler_send (NCDRequest *o, uint8_t *data, int data_len);
+static void send_sender_iface_handler_done (NCDRequest *o);
+
+static int build_requestproto_packet (uint32_t request_id, uint32_t flags, NCDValue *payload_value, uint8_t **out_data, int *out_len)
+{
+    struct header {
+        struct packetproto_header pp;
+        struct requestproto_header rp;
+    };
+    
+    ExpString str;
+    if (!ExpString_Init(&str)) {
+        BLog(BLOG_ERROR, "ExpString_Init failed");
+        goto fail0;
+    }
+    
+    if (!ExpString_AppendZeros(&str, sizeof(struct header))) {
+        BLog(BLOG_ERROR, "ExpString_AppendBinary failed");
+        goto fail1;
+    }
+    
+    if (payload_value && !NCDValueGenerator_AppendGenerate(payload_value, &str)) {
+        BLog(BLOG_ERROR, "NCDValueGenerator_AppendGenerate failed");
+        goto fail1;
+    }
+    
+    size_t len = ExpString_Length(&str);
+    if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
+        BLog(BLOG_ERROR, "reply is too long");
+        goto fail1;
+    }
+    
+    uint8_t *packet = ExpString_Get(&str);
+    
+    struct header *header = (void *)packet;
+    header->pp.len = htol16(len - sizeof(struct packetproto_header));
+    header->rp.request_id = htol32(request_id);
+    header->rp.flags = htol32(flags);
+    
+    *out_data = packet;
+    *out_len = len;
+    return 1;
+    
+fail1:
+    ExpString_Free(&str);
+fail0:
+    return 0;
+}
+
+static void report_finished (NCDRequest *o, int is_error)
+{
+    DEBUGERROR(&o->d_err, o->handler_finished(o->user, is_error))
+}
+
+static void connector_handler (NCDRequest *o, int is_error)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTING)
+    
+    // check error
+    if (is_error) {
+        BLog(BLOG_ERROR, "failed to connect to socket");
+        goto fail0;
+    }
+    
+    BPendingGroup *pg = BReactor_PendingGroup(o->reactor);
+    
+    // init connection
+    if (!BConnection_Init(&o->con, BCONNECTION_SOURCE_CONNECTOR(&o->connector), o->reactor, o, (BConnection_handler)connection_handler)) {
+        BLog(BLOG_ERROR, "BConnection_Init failed");
+        goto fail0;
+    }
+    
+    // init connection interfaces
+    BConnection_SendAsync_Init(&o->con);
+    BConnection_RecvAsync_Init(&o->con);
+    StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&o->con);
+    StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&o->con);
+    
+    // init receive interface
+    PacketPassInterface_Init(&o->recv_if, RECV_MTU, (PacketPassInterface_handler_send)recv_if_handler_send, o, pg);
+    
+    // init receive decoder
+    if (!PacketProtoDecoder_Init(&o->recv_decoder, con_recv_if, &o->recv_if, pg, o, (PacketProtoDecoder_handler_error)decoder_handler_error)) {
+        BLog(BLOG_ERROR, "PacketProtoDecoder_Init failed");
+        goto fail1;
+    }
+    
+    // init send sender
+    PacketStreamSender_Init(&o->send_sender, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
+    o->send_sender_iface = PacketStreamSender_GetInput(&o->send_sender);
+    
+    // init send interface
+    PacketPassInterface_Sender_Init(o->send_sender_iface, (PacketPassInterface_handler_done)send_sender_iface_handler_done, o);
+    
+    // send request
+    PacketPassInterface_Sender_Send(o->send_sender_iface, o->request_data, o->request_len);
+    
+    // set state connected
+    o->state = STATE_CONNECTED;
+    return;
+    
+fail1:
+    PacketPassInterface_Free(&o->recv_if);
+    BConnection_RecvAsync_Free(&o->con);
+    BConnection_SendAsync_Free(&o->con);
+    BConnection_Free(&o->con);
+fail0:
+    report_finished(o, 1);
+}
+
+static void connection_handler (NCDRequest *o, int event)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTED)
+    
+    BLog(BLOG_ERROR, "connection error");
+    
+    report_finished(o, 1);
+}
+
+static void decoder_handler_error (NCDRequest *o)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTED)
+    
+    BLog(BLOG_ERROR, "decoder error");
+    
+    report_finished(o, 1);
+}
+
+static void recv_if_handler_send (NCDRequest *o, uint8_t *data, int data_len)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTED)
+    ASSERT(!o->processing)
+    ASSERT(data_len >= 0)
+    ASSERT(data_len <= RECV_MTU)
+    
+    if (data_len < sizeof(struct requestproto_header)) {
+        BLog(BLOG_ERROR, "missing requestproto header");
+        goto fail;
+    }
+    
+    struct requestproto_header *header = (struct requestproto_header *)data;
+    uint32_t request_id = ltoh32(header->request_id);
+    uint32_t flags = ltoh32(header->flags);
+    
+    uint8_t *payload = data + sizeof(*header);
+    int payload_len = data_len - sizeof(*header);
+    
+    if (request_id != o->request_id) {
+        BLog(BLOG_ERROR, "invalid request ID");
+        goto fail;
+    }
+    
+    if (flags == REQUESTPROTO_REPLY_FLAG_DATA) {
+        NCDValue value;
+        if (!NCDValueParser_Parse(payload, payload_len, &value)) {
+            BLog(BLOG_ERROR, "NCDValueParser_Parse failed");
+            goto fail;
+        }
+        
+        // set processing
+        o->processing = 1;
+        
+        // call reply handler
+        o->handler_reply(o->user, value);
+        return;
+    }
+    
+    if (flags == REQUESTPROTO_REPLY_FLAG_END) {
+        if (payload_len != 0) {
+            BLog(BLOG_ERROR, "end reply has non-empty payload");
+            goto fail;
+        }
+        
+        // call finished handler
+        report_finished(o, 0);
+        return;
+    }
+    
+    BLog(BLOG_ERROR, "invalid requestproto flags");
+    
+fail:
+    report_finished(o, 1);
+}
+
+static void send_sender_iface_handler_done (NCDRequest *o)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTED)
+}
+
+int NCDRequest_Init (NCDRequest *o, const char *socket_path, NCDValue *payload_value, BReactor *reactor, void *user, NCDRequest_handler_finished handler_finished, NCDRequest_handler_reply handler_reply)
+{
+    ASSERT(socket_path)
+    NCDValue_Type(payload_value);
+    ASSERT(handler_finished)
+    ASSERT(handler_reply)
+    
+    // init arguments
+    o->reactor = reactor;
+    o->user = user;
+    o->handler_finished = handler_finished;
+    o->handler_reply = handler_reply;
+    
+    // choose request ID
+    o->request_id = 175;
+    
+    // build request
+    if (!build_requestproto_packet(o->request_id, REQUESTPROTO_REQUEST_FLAG, payload_value, &o->request_data, &o->request_len)) {
+        BLog(BLOG_ERROR, "failed to build request");
+        goto fail0;
+    }
+    
+    // init connector
+    if (!BConnector_InitUnix(&o->connector, socket_path, reactor, o, (BConnector_handler)connector_handler)) {
+        BLog(BLOG_ERROR, "BConnector_InitUnix failed");
+        goto fail1;
+    }
+    
+    // set state connecting
+    o->state = STATE_CONNECTING;
+    
+    // set not processing
+    o->processing = 0;
+    
+    DebugError_Init(&o->d_err, BReactor_PendingGroup(reactor));
+    DebugObject_Init(&o->d_obj);
+    return 1;
+    
+fail1:
+    free(o->request_data);
+fail0:
+    return 0;
+}
+
+void NCDRequest_Free (NCDRequest *o)
+{
+    DebugObject_Free(&o->d_obj);
+    DebugError_Free(&o->d_err);
+    
+    if (o->state == STATE_CONNECTED) {
+        PacketStreamSender_Free(&o->send_sender);
+        PacketProtoDecoder_Free(&o->recv_decoder);
+        PacketPassInterface_Free(&o->recv_if);
+        BConnection_RecvAsync_Free(&o->con);
+        BConnection_SendAsync_Free(&o->con);
+        BConnection_Free(&o->con);
+    }
+    
+    BConnector_Free(&o->connector);
+    free(o->request_data);
+}
+
+void NCDRequest_Next (NCDRequest *o)
+{
+    DebugObject_Access(&o->d_obj);
+    ASSERT(o->state == STATE_CONNECTED)
+    ASSERT(o->processing)
+    
+    // set not processing
+    o->processing = 0;
+    
+    // accept received packet
+    PacketPassInterface_Done(&o->recv_if);
+}

+ 71 - 0
ncd/NCDRequest.h

@@ -0,0 +1,71 @@
+/**
+ * @file NCDRequest.h
+ * @author Ambroz Bizjak <ambrop7@gmail.com>
+ * 
+ * @section LICENSE
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the author nor the
+ *    names of its contributors may be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BADVPN_NCDREQUEST_H
+#define BADVPN_NCDREQUEST_H
+
+#include <stdint.h>
+
+#include <misc/debug.h>
+#include <misc/debugerror.h>
+#include <base/DebugObject.h>
+#include <system/BConnection.h>
+#include <flow/PacketProtoDecoder.h>
+#include <flow/PacketStreamSender.h>
+#include <ncd/NCDValueGenerator.h>
+#include <ncd/NCDValueParser.h>
+
+typedef void (*NCDRequest_handler_finished) (void *user, int is_error);
+typedef void (*NCDRequest_handler_reply) (void *user, NCDValue reply_data);
+
+typedef struct {
+    BReactor *reactor;
+    void *user;
+    NCDRequest_handler_finished handler_finished;
+    NCDRequest_handler_reply handler_reply;
+    uint32_t request_id;
+    uint8_t *request_data;
+    int request_len;
+    BConnector connector;
+    BConnection con;
+    PacketPassInterface recv_if;
+    PacketProtoDecoder recv_decoder;
+    PacketStreamSender send_sender;
+    PacketPassInterface *send_sender_iface;
+    int state;
+    int processing;
+    DebugError d_err;
+    DebugObject d_obj;
+} NCDRequest;
+
+int NCDRequest_Init (NCDRequest *o, const char *socket_path, NCDValue *payload_value, BReactor *reactor, void *user, NCDRequest_handler_finished handler_finished, NCDRequest_handler_reply handler_reply) WARN_UNUSED;
+void NCDRequest_Free (NCDRequest *o);
+void NCDRequest_Next (NCDRequest *o);
+
+#endif

+ 2 - 0
ncd/modules/modules.h

@@ -89,6 +89,7 @@ extern const struct NCDModuleGroup ncdmodule_sys_evdev;
 #ifdef BADVPN_USE_INOTIFY
 extern const struct NCDModuleGroup ncdmodule_sys_watch_directory;
 #endif
+extern const struct NCDModuleGroup ncdmodule_sys_request_server;
 
 static const struct NCDModuleGroup *ncd_modules[] = {
     &ncdmodule_var,
@@ -146,6 +147,7 @@ static const struct NCDModuleGroup *ncd_modules[] = {
 #ifdef BADVPN_USE_INOTIFY
     &ncdmodule_sys_watch_directory,
 #endif
+    &ncdmodule_sys_request_server,
     NULL
 };
 

+ 720 - 0
ncd/modules/sys_request_server.c

@@ -0,0 +1,720 @@
+/**
+ * @file sys_request_server.c
+ * @author Ambroz Bizjak <ambrop7@gmail.com>
+ * 
+ * @section LICENSE
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the author nor the
+ *    names of its contributors may be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * @section DESCRIPTION
+ * 
+ * A simple a IPC interface for NCD to talk to other processes over a Unix socket.
+ * 
+ * Synopsis:
+ *   sys.request_server(string socket_path, string request_handler_template, list args)
+ * 
+ * Description:
+ *   Initializes a request server on the given socket path. Requests are served by
+ *   starting a template process for every request. Multiple such processes may
+ *   exist simultaneously. Termination of these processess may be initiated at
+ *   any time if the request server no longer needs the request in question served.
+ *   The payload of a request is a value, and can be accessed as _request.data
+ *   from within the handler process. Replies to the request can be sent using
+ *   _request->reply(data); replies are values too. Finally, _request->finish()
+ *   should be called to indicate that no further replies will be sent. Calling
+ *   finish() will immediately initiate termination of the handler process.
+ *   Requests can be sent to NCD using the badvpn-ncd-request program.
+ * 
+ * Synopsis:
+ *   sys.request_server.request::reply(reply_data)
+ * 
+ * Synopsis:
+ *   sys.request_server.request::finish()
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <inttypes.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include <misc/offset.h>
+#include <misc/debug.h>
+#include <misc/byteorder.h>
+#include <protocol/packetproto.h>
+#include <protocol/requestproto.h>
+#include <structure/LinkedList0.h>
+#include <system/BConnection.h>
+#include <flow/PacketProtoDecoder.h>
+#include <flow/PacketStreamSender.h>
+#include <flow/PacketPassFifoQueue.h>
+#include <ncd/NCDValueParser.h>
+#include <ncd/NCDValueGenerator.h>
+#include <ncd/NCDModule.h>
+
+#include <generated/blog_channel_ncd_sys_request_server.h>
+
+#define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
+
+#define SEND_PAYLOAD_MTU 32768
+#define RECV_PAYLOAD_MTU 32768
+
+#define SEND_MTU (SEND_PAYLOAD_MTU + sizeof(struct requestproto_header))
+#define RECV_MTU (RECV_PAYLOAD_MTU + sizeof(struct requestproto_header))
+
+struct instance {
+    NCDModuleInst *i;
+    char *socket_path;
+    char *request_handler_template;
+    NCDValue *args;
+    BListener listener;
+    LinkedList0 connections_list;
+    int dying;
+};
+
+#define CONNECTION_STATE_RUNNING 1
+#define CONNECTION_STATE_TERMINATING 2
+
+struct connection {
+    struct instance *inst;
+    LinkedList0Node connections_list_node;
+    BConnection con;
+    PacketProtoDecoder recv_decoder;
+    PacketPassInterface recv_if;
+    PacketPassFifoQueue send_queue;
+    PacketStreamSender send_pss;
+    LinkedList0 requests_list;
+    LinkedList0 replies_list;
+    int state;
+};
+
+struct request {
+    struct connection *con;
+    uint32_t request_id;
+    LinkedList0Node requests_list_node;
+    NCDValue request_data;
+    NCDModuleProcess process;
+    BPending finish_job;
+    int finished;
+};
+
+struct reply {
+    struct connection *con;
+    LinkedList0Node replies_list_node;
+    PacketPassFifoQueueFlow send_qflow;
+    PacketPassInterface *send_qflow_if;
+    uint8_t *send_buf;
+};
+
+static void listener_handler (struct instance *o);
+static void connection_free (struct connection *c);
+static void connection_free_link (struct connection *c);
+static void connection_terminate (struct connection *c);
+static void connection_con_handler (struct connection *c, int event);
+static void connection_recv_decoder_handler_error (struct connection *c);
+static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len);
+static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len);
+static void request_free (struct request *r);
+static void request_process_handler_event (struct request *r, int event);
+static int request_process_func_getspecialobj (struct request *r, const char *name, NCDObject *out_object);
+static int request_process_request_obj_func_getvar (struct request *r, const char *name, NCDValue *out_value);
+static void request_finish_job_handler (struct request *r);
+static int reply_init (struct connection *c, uint32_t request_id, uint32_t flags, NCDValue *reply_data);
+static void reply_free (struct reply *r);
+static void reply_send_qflow_if_handler_done (struct reply *r);
+static void instance_free (struct instance *o);
+
+static void listener_handler (struct instance *o)
+{
+    ASSERT(!o->dying)
+    
+    BReactor *reactor = o->i->params->reactor;
+    BPendingGroup *pg = BReactor_PendingGroup(reactor);
+    
+    struct connection *c = malloc(sizeof(*c));
+    if (!c) {
+        ModuleLog(o->i, BLOG_ERROR, "malloc failed");
+        goto fail0;
+    }
+    
+    c->inst = o;
+    
+    LinkedList0_Prepend(&o->connections_list, &c->connections_list_node);
+    
+    if (!BConnection_Init(&c->con, BCONNECTION_SOURCE_LISTENER(&o->listener, NULL), reactor, c, (BConnection_handler)connection_con_handler)) {
+        ModuleLog(o->i, BLOG_ERROR, "BConnection_Init failed");
+        goto fail1;
+    }
+    
+    BConnection_SendAsync_Init(&c->con);
+    BConnection_RecvAsync_Init(&c->con);
+    StreamPassInterface *con_send_if = BConnection_SendAsync_GetIf(&c->con);
+    StreamRecvInterface *con_recv_if = BConnection_RecvAsync_GetIf(&c->con);
+    
+    PacketPassInterface_Init(&c->recv_if, RECV_MTU, (PacketPassInterface_handler_send)connection_recv_if_handler_send, c, pg);
+    
+    if (!PacketProtoDecoder_Init(&c->recv_decoder, con_recv_if, &c->recv_if, pg, c, (PacketProtoDecoder_handler_error)connection_recv_decoder_handler_error)) {
+        ModuleLog(o->i, BLOG_ERROR, "PacketProtoDecoder_Init failed");
+        goto fail2;
+    }
+    
+    PacketStreamSender_Init(&c->send_pss, con_send_if, PACKETPROTO_ENCLEN(SEND_MTU), pg);
+    
+    PacketPassFifoQueue_Init(&c->send_queue, PacketStreamSender_GetInput(&c->send_pss), pg);
+    
+    LinkedList0_Init(&c->requests_list);
+    
+    LinkedList0_Init(&c->replies_list);
+    
+    c->state = CONNECTION_STATE_RUNNING;
+    
+    ModuleLog(o->i, BLOG_INFO, "connection initialized");
+    return;
+    
+fail3:
+    PacketStreamSender_Free(&c->send_pss);
+    PacketProtoDecoder_Free(&c->recv_decoder);
+fail2:
+    PacketPassInterface_Free(&c->recv_if);
+    BConnection_RecvAsync_Free(&c->con);
+    BConnection_SendAsync_Free(&c->con);
+    BConnection_Free(&c->con);
+fail1:
+    LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
+    free(c);
+fail0:
+    return;
+}
+
+static void connection_free (struct connection *c)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_TERMINATING)
+    ASSERT(LinkedList0_IsEmpty(&c->requests_list))
+    ASSERT(LinkedList0_IsEmpty(&c->replies_list))
+    
+    LinkedList0_Remove(&o->connections_list, &c->connections_list_node);
+    free(c);
+}
+
+static void connection_free_link (struct connection *c)
+{
+    PacketPassFifoQueue_PrepareFree(&c->send_queue);
+    
+    LinkedList0Node *ln;
+    while (ln = LinkedList0_GetFirst(&c->replies_list)) {
+        struct reply *r = UPPER_OBJECT(ln, struct reply, replies_list_node);
+        ASSERT(r->con == c)
+        reply_free(r);
+    }
+    
+    PacketPassFifoQueue_Free(&c->send_queue);
+    PacketStreamSender_Free(&c->send_pss);
+    PacketProtoDecoder_Free(&c->recv_decoder);
+    PacketPassInterface_Free(&c->recv_if);
+    BConnection_RecvAsync_Free(&c->con);
+    BConnection_SendAsync_Free(&c->con);
+    BConnection_Free(&c->con);
+}
+
+static void connection_terminate (struct connection *c)
+{
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    
+    for (LinkedList0Node *ln = LinkedList0_GetFirst(&c->requests_list); ln; ln = LinkedList0Node_Next(ln)) {
+        struct request *r = UPPER_OBJECT(ln, struct request, requests_list_node);
+        
+        if (!r->finished) {
+            NCDModuleProcess_Terminate(&r->process);
+        }
+        BPending_Unset(&r->finish_job);
+    }
+    
+    connection_free_link(c);
+    
+    c->state = CONNECTION_STATE_TERMINATING;
+    
+    if (LinkedList0_IsEmpty(&c->requests_list)) {
+        connection_free(c);
+        return;
+    }
+}
+
+static void connection_con_handler (struct connection *c, int event)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    
+    ModuleLog(o->i, BLOG_INFO, "connection closed");
+    
+    connection_terminate(c);
+}
+
+static void connection_recv_decoder_handler_error (struct connection *c)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    
+    ModuleLog(o->i, BLOG_INFO, "decoder error");
+    
+    connection_terminate(c);
+}
+
+static void connection_recv_if_handler_send (struct connection *c, uint8_t *data, int data_len)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    ASSERT(data_len >= 0)
+    ASSERT(data_len <= RECV_MTU)
+    
+    PacketPassInterface_Done(&c->recv_if);
+    
+    if (data_len < sizeof(struct requestproto_header)) {
+        ModuleLog(o->i, BLOG_INFO, "missing requestproto header");
+        return;
+    }
+    
+    struct requestproto_header *header = (struct requestproto_header *)data;
+    uint32_t request_id = ltoh32(header->request_id);
+    uint32_t flags = ltoh32(header->flags);
+    
+    if (flags != REQUESTPROTO_REQUEST_FLAG) {
+        ModuleLog(o->i, BLOG_INFO, "invalid requestproto flags");
+        return;
+    }
+    
+    request_init(c, request_id, data + sizeof(*header), data_len - sizeof(*header));
+}
+
+static int request_init (struct connection *c, uint32_t request_id, const uint8_t *data, int data_len)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    ASSERT(data_len >= 0)
+    ASSERT(data_len <= RECV_PAYLOAD_MTU)
+    
+    struct request *r = malloc(sizeof(*r));
+    if (!r) {
+        ModuleLog(o->i, BLOG_ERROR, "malloc failed");
+        goto fail0;
+    }
+    
+    r->con = c;
+    r->request_id = request_id;
+    
+    LinkedList0_Prepend(&c->requests_list, &r->requests_list_node);
+    
+    if (!NCDValueParser_Parse(data, data_len, &r->request_data)) {
+        ModuleLog(o->i, BLOG_ERROR, "NCDValueParser_Parse failed");
+        goto fail1;
+    }
+    
+    NCDValue args;
+    if (!NCDValue_InitCopy(&args, o->args)) {
+        ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitCopy failed");
+        goto fail2;
+    }
+    
+    if (!NCDModuleProcess_Init(&r->process, o->i, o->request_handler_template, args, r, (NCDModuleProcess_handler_event)request_process_handler_event)) {
+        ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed");
+        NCDValue_Free(&args);
+        goto fail2;
+    }
+    
+    NCDModuleProcess_SetSpecialFuncs(&r->process, (NCDModuleProcess_func_getspecialobj)request_process_func_getspecialobj);
+    
+    BPending_Init(&r->finish_job, BReactor_PendingGroup(o->i->params->reactor), (BPending_handler)request_finish_job_handler, r);
+    
+    r->finished = 0;
+    
+    ModuleLog(o->i, BLOG_INFO, "request initialized");
+    return 1;
+    
+fail2:
+    NCDValue_Free(&r->request_data);
+fail1:
+    LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
+    free(r);
+fail0:
+    return 0;
+}
+
+static void request_free (struct request *r)
+{
+    struct connection *c = r->con;
+    
+    BPending_Free(&r->finish_job);
+    NCDModuleProcess_Free(&r->process);
+    NCDValue_Free(&r->request_data);
+    LinkedList0_Remove(&c->requests_list, &r->requests_list_node);
+    free(r);
+}
+
+static void request_process_handler_event (struct request *r, int event)
+{
+    struct connection *c = r->con;
+    struct instance *o = c->inst;
+    
+    switch (event) {
+        case NCDMODULEPROCESS_EVENT_UP: {
+            ASSERT(c->state == CONNECTION_STATE_RUNNING)
+        } break;
+        
+        case NCDMODULEPROCESS_EVENT_DOWN: {
+            NCDModuleProcess_Continue(&r->process);
+        } break;
+        
+        case NCDMODULEPROCESS_EVENT_TERMINATED: {
+            ASSERT(r->finished || c->state == CONNECTION_STATE_TERMINATING)
+            
+            request_free(r);
+            
+            if (c->state == CONNECTION_STATE_TERMINATING && LinkedList0_IsEmpty(&c->requests_list)) {
+                connection_free(c);
+                
+                if (o->dying && LinkedList0_IsEmpty(&o->connections_list)) {
+                    instance_free(o);
+                    return;
+                }
+            }
+        } break;
+        
+        default: ASSERT(0);
+    }
+}
+
+static int request_process_func_getspecialobj (struct request *r, const char *name, NCDObject *out_object)
+{
+    if (!strcmp(name, "_request")) {
+        *out_object = NCDObject_Build("sys.request_server.request", r, (NCDObject_func_getvar)request_process_request_obj_func_getvar, NULL);
+        return 1;
+    }
+    
+    return 0;
+}
+
+static int request_process_request_obj_func_getvar (struct request *r, const char *name, NCDValue *out_value)
+{
+    struct instance *o = r->con->inst;
+    
+    if (!strcmp(name, "data")) {
+        if (!NCDValue_InitCopy(out_value, &r->request_data)) {
+            ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitCopy failed");
+            return 0;
+        }
+        return 1;
+    }
+    
+    return 0;
+}
+
+static void request_finish_job_handler (struct request *r)
+{
+    struct connection *c = r->con;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    ASSERT(!r->finished)
+    
+    NCDModuleProcess_Terminate(&r->process);
+    
+    r->finished = 1;
+}
+
+static int reply_init (struct connection *c, uint32_t request_id, uint32_t flags, NCDValue *reply_data)
+{
+    struct instance *o = c->inst;
+    ASSERT(c->state == CONNECTION_STATE_RUNNING)
+    
+    struct reply *r = malloc(sizeof(*r));
+    if (!r) {
+        ModuleLog(o->i, BLOG_ERROR, "malloc failed");
+        goto fail0;
+    }
+    
+    r->con = c;
+    
+    LinkedList0_Prepend(&c->replies_list, &r->replies_list_node);
+    
+    PacketPassFifoQueueFlow_Init(&r->send_qflow, &c->send_queue);
+    
+    r->send_qflow_if = PacketPassFifoQueueFlow_GetInput(&r->send_qflow);
+    PacketPassInterface_Sender_Init(r->send_qflow_if, (PacketPassInterface_handler_done)reply_send_qflow_if_handler_done, r);
+    
+    struct reply_header {
+        struct packetproto_header pp;
+        struct requestproto_header rp;
+    };
+    
+    ExpString str;
+    if (!ExpString_Init(&str)) {
+        ModuleLog(o->i, BLOG_ERROR, "ExpString_Init failed");
+        goto fail1;
+    }
+    
+    if (!ExpString_AppendZeros(&str, sizeof(struct reply_header))) {
+        ModuleLog(o->i, BLOG_ERROR, "ExpString_AppendBinary failed");
+        goto fail2;
+    }
+    
+    if (reply_data && !NCDValueGenerator_AppendGenerate(reply_data, &str)) {
+        ModuleLog(o->i, BLOG_ERROR, "NCDValueGenerator_AppendGenerate failed");
+        goto fail2;
+    }
+    
+    size_t len = ExpString_Length(&str);
+    if (len > INT_MAX || len > PACKETPROTO_ENCLEN(SEND_MTU) || len - sizeof(struct packetproto_header) > UINT16_MAX) {
+        ModuleLog(o->i, BLOG_ERROR, "reply is too long");
+        goto fail2;
+    }
+    
+    r->send_buf = ExpString_Get(&str);
+    
+    struct reply_header *header = (struct reply_header *)r->send_buf;
+    header->pp.len = htol16(len - sizeof(struct packetproto_header));
+    header->rp.request_id = htol32(request_id);
+    header->rp.flags = htol32(flags);
+    
+    PacketPassInterface_Sender_Send(r->send_qflow_if, r->send_buf, len);
+    return 1;
+    
+fail2:
+    ExpString_Free(&str);
+fail1:
+    PacketPassFifoQueueFlow_Free(&r->send_qflow);
+    LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
+    free(r);
+fail0:
+    return 0;
+}
+
+static void reply_free (struct reply *r)
+{
+    struct connection *c = r->con;
+    PacketPassFifoQueueFlow_AssertFree(&r->send_qflow);
+    
+    free(r->send_buf);
+    PacketPassFifoQueueFlow_Free(&r->send_qflow);
+    LinkedList0_Remove(&c->replies_list, &r->replies_list_node);
+    free(r);
+}
+
+static void reply_send_qflow_if_handler_done (struct reply *r)
+{
+    reply_free(r);
+}
+
+static void func_new (NCDModuleInst *i)
+{
+    // allocate structure
+    struct instance *o = malloc(sizeof(*o));
+    if (!o) {
+        ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
+        goto fail0;
+    }
+    o->i = i;
+    NCDModuleInst_Backend_SetUser(i, o);
+    
+    // check arguments
+    NCDValue *socket_path_arg;
+    NCDValue *request_handler_template_arg;
+    NCDValue *args_arg;
+    if (!NCDValue_ListRead(i->args, 3, &socket_path_arg, &request_handler_template_arg, &args_arg)) {
+        ModuleLog(o->i, BLOG_ERROR, "wrong arity");
+        goto fail1;
+    }
+    if (NCDValue_Type(socket_path_arg) != NCDVALUE_STRING || NCDValue_Type(request_handler_template_arg) != NCDVALUE_STRING ||
+        NCDValue_Type(args_arg) != NCDVALUE_LIST) {
+        ModuleLog(o->i, BLOG_ERROR, "wrong type");
+        goto fail1;
+    }
+    o->socket_path = NCDValue_StringValue(socket_path_arg);
+    o->request_handler_template = NCDValue_StringValue(request_handler_template_arg);
+    o->args = args_arg;
+    
+    // make sure socket file doesn't exist
+    if (unlink(o->socket_path) < 0 && errno != ENOENT) {
+        ModuleLog(o->i, BLOG_ERROR, "unlink failed");
+        goto fail1;
+    }
+    
+    // init listener
+    if (!BListener_InitUnix(&o->listener, o->socket_path, i->params->reactor, o, (BListener_handler)listener_handler)) {
+        ModuleLog(o->i, BLOG_ERROR, "BListener_InitUnix failed");
+        goto fail1;
+    }
+    
+    // init connections list
+    LinkedList0_Init(&o->connections_list);
+    
+    // set not dying
+    o->dying = 0;
+    
+    // signal up
+    NCDModuleInst_Backend_Up(i);
+    return;
+    
+fail1:
+    free(o);
+fail0:
+    NCDModuleInst_Backend_SetError(i);
+    NCDModuleInst_Backend_Dead(i);
+}
+
+static void instance_free (struct instance *o)
+{
+    NCDModuleInst *i = o->i;
+    ASSERT(o->dying)
+    ASSERT(LinkedList0_IsEmpty(&o->connections_list))
+    
+    // free structure
+    free(o);
+    
+    NCDModuleInst_Backend_Dead(i);
+}
+
+static void func_die (void *vo)
+{
+    struct instance *o = vo;
+    NCDModuleInst *i = o->i;
+    ASSERT(!o->dying)
+    
+    // free listener
+    BListener_Free(&o->listener);
+    
+    // remove socket file
+    if (unlink(o->socket_path)) {
+        ModuleLog(o->i, BLOG_ERROR, "unlink failed");
+    }
+    
+    // terminate connections
+    LinkedList0Node *next_ln;
+    for (LinkedList0Node *ln = LinkedList0_GetFirst(&o->connections_list); ln && (next_ln = LinkedList0Node_Next(ln)), ln; ln = next_ln) { 
+        struct connection *c = UPPER_OBJECT(ln, struct connection, connections_list_node);
+        ASSERT(c->inst == o)
+        
+        if (c->state != CONNECTION_STATE_TERMINATING) {
+            connection_terminate(c);
+        }
+    }
+    
+    // set dying
+    o->dying = 1;
+    
+    // if no connections, die right away
+    if (LinkedList0_IsEmpty(&o->connections_list)) {
+        instance_free(o);
+        return;
+    }
+}
+
+static void reply_func_new (NCDModuleInst *i)
+{
+    NCDValue *reply_data;
+    if (!NCDValue_ListRead(i->args, 1, &reply_data)) {
+        ModuleLog(i, BLOG_ERROR, "wrong arity");
+        goto fail;
+    }
+    
+    NCDModuleInst_Backend_Up(i);
+    
+    struct request *r = i->method_user;
+    struct connection *c = r->con;
+    
+    if (c->state != CONNECTION_STATE_RUNNING) {
+        ModuleLog(i, BLOG_ERROR, "connection is terminating, cannot submit reply");
+        goto fail;
+    }
+    
+    if (r->finished || BPending_IsSet(&r->finish_job)) {
+        ModuleLog(i, BLOG_ERROR, "request is already finished, cannot submit reply");
+        goto fail;
+    }
+    
+    if (!reply_init(c, r->request_id, REQUESTPROTO_REPLY_FLAG_DATA, reply_data)) {
+        ModuleLog(i, BLOG_ERROR, "failed to submit reply");
+        goto fail;
+    }
+    
+    return;
+    
+fail:
+    NCDModuleInst_Backend_SetError(i);
+    NCDModuleInst_Backend_Dead(i);
+}
+
+static void finish_func_new (NCDModuleInst *i)
+{
+    if (!NCDValue_ListRead(i->args, 0)) {
+        ModuleLog(i, BLOG_ERROR, "wrong arity");
+        goto fail;
+    }
+    
+    NCDModuleInst_Backend_Up(i);
+    
+    struct request *r = i->method_user;
+    struct connection *c = r->con;
+    
+    if (c->state != CONNECTION_STATE_RUNNING) {
+        ModuleLog(i, BLOG_ERROR, "connection is terminating, cannot submit reply");
+        goto fail;
+    }
+    
+    if (r->finished || BPending_IsSet(&r->finish_job)) {
+        ModuleLog(i, BLOG_ERROR, "request is already finished, cannot submit reply");
+        goto fail;
+    }
+    
+    BPending_Set(&r->finish_job);
+    
+    if (!reply_init(c, r->request_id, REQUESTPROTO_REPLY_FLAG_END, NULL)) {
+        ModuleLog(i, BLOG_ERROR, "failed to submit reply");
+        BPending_Unset(&r->finish_job); // don't terminate request process!
+        goto fail;
+    }
+    
+    return;
+    
+fail:
+    NCDModuleInst_Backend_SetError(i);
+    NCDModuleInst_Backend_Dead(i);
+}
+
+static const struct NCDModule modules[] = {
+    {
+        .type = "sys.request_server",
+        .func_new = func_new,
+        .func_die = func_die
+    }, {
+        .type = "sys.request_server.request::reply",
+        .func_new = reply_func_new
+    }, {
+        .type = "sys.request_server.request::finish",
+        .func_new = finish_func_new
+    }, {
+        .type = NULL
+    }
+};
+
+const struct NCDModuleGroup ncdmodule_sys_request_server = {
+    .modules = modules
+};