Home | History | Annotate | Line # | Download | only in dnstap
      1      1.1  christos /*
      2      1.1  christos  * dnstap/dtstream.c - Frame Streams thread for unbound DNSTAP
      3      1.1  christos  *
      4      1.1  christos  * Copyright (c) 2020, NLnet Labs. All rights reserved.
      5      1.1  christos  *
      6      1.1  christos  * This software is open source.
      7      1.1  christos  *
      8      1.1  christos  * Redistribution and use in source and binary forms, with or without
      9      1.1  christos  * modification, are permitted provided that the following conditions
     10      1.1  christos  * are met:
     11      1.1  christos  *
     12      1.1  christos  * Redistributions of source code must retain the above copyright notice,
     13      1.1  christos  * this list of conditions and the following disclaimer.
     14      1.1  christos  *
     15      1.1  christos  * Redistributions in binary form must reproduce the above copyright notice,
     16      1.1  christos  * this list of conditions and the following disclaimer in the documentation
     17      1.1  christos  * and/or other materials provided with the distribution.
     18      1.1  christos  *
     19      1.1  christos  * Neither the name of the NLNET LABS nor the names of its contributors may
     20      1.1  christos  * be used to endorse or promote products derived from this software without
     21      1.1  christos  * specific prior written permission.
     22      1.1  christos  *
     23      1.1  christos  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     24      1.1  christos  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     25      1.1  christos  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     26      1.1  christos  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     27      1.1  christos  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     28      1.1  christos  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
     29      1.1  christos  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     30      1.1  christos  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     31      1.1  christos  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     32      1.1  christos  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     33      1.1  christos  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     34      1.1  christos  *
     35      1.1  christos  */
     36      1.1  christos 
     37      1.1  christos /**
     38      1.1  christos  * \file
     39      1.1  christos  *
     40      1.1  christos  * An implementation of the Frame Streams data transport protocol for
     41      1.1  christos  * the Unbound DNSTAP message logging facility.
     42      1.1  christos  */
     43      1.1  christos 
     44      1.1  christos #include "config.h"
     45      1.1  christos #include "dnstap/dtstream.h"
     46      1.1  christos #include "dnstap/dnstap_fstrm.h"
     47      1.1  christos #include "util/config_file.h"
     48      1.1  christos #include "util/ub_event.h"
     49      1.1  christos #include "util/net_help.h"
     50      1.1  christos #include "services/outside_network.h"
     51      1.1  christos #include "sldns/sbuffer.h"
     52      1.1  christos #ifdef HAVE_SYS_UN_H
     53      1.1  christos #include <sys/un.h>
     54      1.1  christos #endif
     55      1.1  christos #include <fcntl.h>
     56      1.1  christos #ifdef HAVE_OPENSSL_SSL_H
     57      1.1  christos #include <openssl/ssl.h>
     58      1.1  christos #endif
     59      1.1  christos #ifdef HAVE_OPENSSL_ERR_H
     60      1.1  christos #include <openssl/err.h>
     61      1.1  christos #endif
     62      1.1  christos 
     63      1.1  christos /** number of messages to process in one output callback */
     64      1.1  christos #define DTIO_MESSAGES_PER_CALLBACK 100
     65      1.1  christos /** the msec to wait for reconnect (if not immediate, the first attempt) */
     66      1.1  christos #define DTIO_RECONNECT_TIMEOUT_MIN 10
     67      1.1  christos /** the msec to wait for reconnect max after backoff */
     68      1.1  christos #define DTIO_RECONNECT_TIMEOUT_MAX 1000
     69      1.1  christos /** the msec to wait for reconnect slow, to stop busy spinning on reconnect */
     70      1.1  christos #define DTIO_RECONNECT_TIMEOUT_SLOW 1000
     71      1.1  christos /** number of messages before wakeup of thread */
     72      1.1  christos #define DTIO_MSG_FOR_WAKEUP 32
     73      1.1  christos 
     74      1.1  christos /** maximum length of received frame */
     75      1.1  christos #define DTIO_RECV_FRAME_MAX_LEN 1000
     76      1.1  christos 
     77      1.1  christos struct stop_flush_info;
     78      1.1  christos /** DTIO command channel commands */
     79      1.1  christos enum {
     80      1.1  christos 	/** DTIO command channel stop */
     81      1.1  christos 	DTIO_COMMAND_STOP = 0,
     82      1.1  christos 	/** DTIO command channel wakeup */
     83      1.1  christos 	DTIO_COMMAND_WAKEUP = 1
     84      1.1  christos } dtio_channel_command;
     85      1.1  christos 
     86      1.1  christos /** open the output channel */
     87      1.1  christos static void dtio_open_output(struct dt_io_thread* dtio);
     88      1.1  christos /** add output event for read and write */
     89      1.1  christos static int dtio_add_output_event_write(struct dt_io_thread* dtio);
     90      1.1  christos /** start reconnection attempts */
     91      1.1  christos static void dtio_reconnect_enable(struct dt_io_thread* dtio);
     92      1.1  christos /** stop from stop_flush event loop */
     93      1.1  christos static void dtio_stop_flush_exit(struct stop_flush_info* info);
     94      1.1  christos /** setup a start control message */
     95      1.1  christos static int dtio_control_start_send(struct dt_io_thread* dtio);
     96      1.1  christos #ifdef HAVE_SSL
     97      1.1  christos /** enable briefly waiting for a read event, for SSL negotiation */
     98      1.1  christos static int dtio_enable_brief_read(struct dt_io_thread* dtio);
     99      1.1  christos /** enable briefly waiting for a write event, for SSL negotiation */
    100      1.1  christos static int dtio_enable_brief_write(struct dt_io_thread* dtio);
    101      1.1  christos #endif
    102      1.1  christos 
    103      1.1  christos struct dt_msg_queue*
    104      1.1  christos dt_msg_queue_create(struct comm_base* base)
    105      1.1  christos {
    106      1.1  christos 	struct dt_msg_queue* mq = calloc(1, sizeof(*mq));
    107      1.1  christos 	if(!mq) return NULL;
    108      1.1  christos 	mq->maxsize = 1*1024*1024; /* set max size of buffer, per worker,
    109      1.1  christos 		about 1 M should contain 64K messages with some overhead,
    110      1.1  christos 		or a whole bunch smaller ones */
    111      1.1  christos 	mq->wakeup_timer = comm_timer_create(base, mq_wakeup_cb, mq);
    112      1.1  christos 	if(!mq->wakeup_timer) {
    113      1.1  christos 		free(mq);
    114      1.1  christos 		return NULL;
    115      1.1  christos 	}
    116      1.1  christos 	lock_basic_init(&mq->lock);
    117      1.1  christos 	lock_protect(&mq->lock, mq, sizeof(*mq));
    118      1.1  christos 	return mq;
    119      1.1  christos }
    120      1.1  christos 
    121      1.1  christos /** clear the message list, caller must hold the lock */
    122      1.1  christos static void
    123      1.1  christos dt_msg_queue_clear(struct dt_msg_queue* mq)
    124      1.1  christos {
    125      1.1  christos 	struct dt_msg_entry* e = mq->first, *next=NULL;
    126      1.1  christos 	while(e) {
    127      1.1  christos 		next = e->next;
    128      1.1  christos 		free(e->buf);
    129      1.1  christos 		free(e);
    130      1.1  christos 		e = next;
    131      1.1  christos 	}
    132      1.1  christos 	mq->first = NULL;
    133      1.1  christos 	mq->last = NULL;
    134      1.1  christos 	mq->cursize = 0;
    135      1.1  christos 	mq->msgcount = 0;
    136      1.1  christos }
    137      1.1  christos 
    138      1.1  christos void
    139      1.1  christos dt_msg_queue_delete(struct dt_msg_queue* mq)
    140      1.1  christos {
    141      1.1  christos 	if(!mq) return;
    142      1.1  christos 	lock_basic_destroy(&mq->lock);
    143      1.1  christos 	dt_msg_queue_clear(mq);
    144      1.1  christos 	comm_timer_delete(mq->wakeup_timer);
    145      1.1  christos 	free(mq);
    146      1.1  christos }
    147      1.1  christos 
    148      1.1  christos /** make the dtio wake up by sending a wakeup command */
    149      1.1  christos static void dtio_wakeup(struct dt_io_thread* dtio)
    150      1.1  christos {
    151      1.1  christos 	uint8_t cmd = DTIO_COMMAND_WAKEUP;
    152      1.1  christos 	if(!dtio) return;
    153      1.1  christos 	if(!dtio->started) return;
    154      1.1  christos 
    155      1.1  christos 	while(1) {
    156      1.1  christos 		ssize_t r = write(dtio->commandpipe[1], &cmd, sizeof(cmd));
    157      1.1  christos 		if(r == -1) {
    158      1.1  christos #ifndef USE_WINSOCK
    159      1.1  christos 			if(errno == EINTR || errno == EAGAIN)
    160      1.1  christos 				continue;
    161      1.1  christos #else
    162      1.1  christos 			if(WSAGetLastError() == WSAEINPROGRESS)
    163      1.1  christos 				continue;
    164      1.1  christos 			if(WSAGetLastError() == WSAEWOULDBLOCK)
    165      1.1  christos 				continue;
    166      1.1  christos #endif
    167      1.1  christos 			log_err("dnstap io wakeup: write: %s",
    168      1.1  christos 				sock_strerror(errno));
    169      1.1  christos 			break;
    170      1.1  christos 		}
    171      1.1  christos 		break;
    172      1.1  christos 	}
    173      1.1  christos }
    174      1.1  christos 
    175      1.1  christos void
    176      1.1  christos mq_wakeup_cb(void* arg)
    177      1.1  christos {
    178      1.1  christos 	struct dt_msg_queue* mq = (struct dt_msg_queue*)arg;
    179  1.1.1.4  christos 
    180      1.1  christos 	lock_basic_lock(&mq->dtio->wakeup_timer_lock);
    181      1.1  christos 	mq->dtio->wakeup_timer_enabled = 0;
    182      1.1  christos 	lock_basic_unlock(&mq->dtio->wakeup_timer_lock);
    183      1.1  christos 	dtio_wakeup(mq->dtio);
    184      1.1  christos }
    185      1.1  christos 
    186      1.1  christos /** start timer to wakeup dtio because there is content in the queue */
    187      1.1  christos static void
    188  1.1.1.2  christos dt_msg_queue_start_timer(struct dt_msg_queue* mq, int wakeupnow)
    189      1.1  christos {
    190  1.1.1.2  christos 	struct timeval tv = {0};
    191      1.1  christos 	/* Start a timer to process messages to be logged.
    192      1.1  christos 	 * If we woke up the dtio thread for every message, the wakeup
    193      1.1  christos 	 * messages take up too much processing power.  If the queue
    194      1.1  christos 	 * fills up the wakeup happens immediately.  The timer wakes it up
    195      1.1  christos 	 * if there are infrequent messages to log. */
    196      1.1  christos 
    197      1.1  christos 	/* we cannot start a timer in dtio thread, because it is a different
    198      1.1  christos 	 * thread and its event base is in use by the other thread, it would
    199      1.1  christos 	 * give race conditions if we tried to modify its event base,
    200      1.1  christos 	 * and locks would wait until it woke up, and this is what we do. */
    201      1.1  christos 
    202      1.1  christos 	/* do not start the timer if a timer already exists, perhaps
    203      1.1  christos 	 * in another worker.  So this variable is protected by a lock in
    204  1.1.1.2  christos 	 * dtio. */
    205  1.1.1.2  christos 
    206  1.1.1.2  christos 	/* If we need to wakeupnow, 0 the timer to force the callback. */
    207      1.1  christos 	lock_basic_lock(&mq->dtio->wakeup_timer_lock);
    208      1.1  christos 	if(mq->dtio->wakeup_timer_enabled) {
    209  1.1.1.2  christos 		if(wakeupnow) {
    210  1.1.1.4  christos 			tv.tv_sec = 0;
    211  1.1.1.4  christos 			tv.tv_usec = 0;
    212  1.1.1.2  christos 			comm_timer_set(mq->wakeup_timer, &tv);
    213  1.1.1.2  christos 		}
    214      1.1  christos 		lock_basic_unlock(&mq->dtio->wakeup_timer_lock);
    215      1.1  christos 		return;
    216      1.1  christos 	}
    217      1.1  christos 	mq->dtio->wakeup_timer_enabled = 1; /* we are going to start one */
    218      1.1  christos 
    219      1.1  christos 	/* start the timer, in mq, in the event base of our worker */
    220  1.1.1.2  christos 	if(!wakeupnow) {
    221  1.1.1.2  christos 		tv.tv_sec = 1;
    222  1.1.1.2  christos 		tv.tv_usec = 0;
    223  1.1.1.4  christos 		/* If it is already set, keep it running. */
    224  1.1.1.4  christos 		if(!comm_timer_is_set(mq->wakeup_timer))
    225  1.1.1.4  christos 			comm_timer_set(mq->wakeup_timer, &tv);
    226  1.1.1.4  christos 	} else {
    227  1.1.1.4  christos 		tv.tv_sec = 0;
    228  1.1.1.4  christos 		tv.tv_usec = 0;
    229  1.1.1.4  christos 		comm_timer_set(mq->wakeup_timer, &tv);
    230  1.1.1.2  christos 	}
    231  1.1.1.2  christos 	lock_basic_unlock(&mq->dtio->wakeup_timer_lock);
    232      1.1  christos }
    233      1.1  christos 
    234      1.1  christos void
    235      1.1  christos dt_msg_queue_submit(struct dt_msg_queue* mq, void* buf, size_t len)
    236      1.1  christos {
    237      1.1  christos 	int wakeupnow = 0, wakeupstarttimer = 0;
    238      1.1  christos 	struct dt_msg_entry* entry;
    239      1.1  christos 
    240      1.1  christos 	/* check conditions */
    241      1.1  christos 	if(!buf) return;
    242      1.1  christos 	if(len == 0) {
    243      1.1  christos 		/* it is not possible to log entries with zero length,
    244      1.1  christos 		 * because the framestream protocol does not carry it.
    245      1.1  christos 		 * However the protobuf serialization does not create zero
    246      1.1  christos 		 * length datagrams for dnstap, so this should not happen. */
    247      1.1  christos 		free(buf);
    248      1.1  christos 		return;
    249      1.1  christos 	}
    250      1.1  christos 	if(!mq) {
    251      1.1  christos 		free(buf);
    252      1.1  christos 		return;
    253      1.1  christos 	}
    254      1.1  christos 
    255      1.1  christos 	/* allocate memory for queue entry */
    256      1.1  christos 	entry = malloc(sizeof(*entry));
    257      1.1  christos 	if(!entry) {
    258      1.1  christos 		log_err("out of memory logging dnstap");
    259      1.1  christos 		free(buf);
    260      1.1  christos 		return;
    261      1.1  christos 	}
    262      1.1  christos 	entry->next = NULL;
    263      1.1  christos 	entry->buf = buf;
    264      1.1  christos 	entry->len = len;
    265      1.1  christos 
    266  1.1.1.2  christos 	/* acquire lock */
    267      1.1  christos 	lock_basic_lock(&mq->lock);
    268  1.1.1.4  christos 	/* if list was empty, start timer for (eventual) wakeup,
    269  1.1.1.4  christos 	 * or if dtio is not writing now an eventual wakeup is needed. */
    270  1.1.1.4  christos 	if(mq->first == NULL || !mq->dtio->event_added_is_write)
    271      1.1  christos 		wakeupstarttimer = 1;
    272      1.1  christos 	/* if list contains more than wakeupnum elements, wakeup now,
    273      1.1  christos 	 * or if list is (going to be) almost full */
    274      1.1  christos 	if(mq->msgcount == DTIO_MSG_FOR_WAKEUP ||
    275      1.1  christos 		(mq->cursize < mq->maxsize * 9 / 10 &&
    276      1.1  christos 		mq->cursize+len >= mq->maxsize * 9 / 10))
    277      1.1  christos 		wakeupnow = 1;
    278      1.1  christos 	/* see if it is going to fit */
    279      1.1  christos 	if(mq->cursize + len > mq->maxsize) {
    280      1.1  christos 		/* buffer full, or congested. */
    281      1.1  christos 		/* drop */
    282      1.1  christos 		lock_basic_unlock(&mq->lock);
    283      1.1  christos 		free(buf);
    284      1.1  christos 		free(entry);
    285      1.1  christos 		return;
    286      1.1  christos 	}
    287      1.1  christos 	mq->cursize += len;
    288      1.1  christos 	mq->msgcount ++;
    289      1.1  christos 	/* append to list */
    290      1.1  christos 	if(mq->last) {
    291      1.1  christos 		mq->last->next = entry;
    292      1.1  christos 	} else {
    293      1.1  christos 		mq->first = entry;
    294      1.1  christos 	}
    295      1.1  christos 	mq->last = entry;
    296      1.1  christos 	/* release lock */
    297      1.1  christos 	lock_basic_unlock(&mq->lock);
    298      1.1  christos 
    299  1.1.1.2  christos 	if(wakeupnow || wakeupstarttimer) {
    300  1.1.1.2  christos 		dt_msg_queue_start_timer(mq, wakeupnow);
    301      1.1  christos 	}
    302      1.1  christos }
    303      1.1  christos 
    304      1.1  christos struct dt_io_thread* dt_io_thread_create(void)
    305      1.1  christos {
    306      1.1  christos 	struct dt_io_thread* dtio = calloc(1, sizeof(*dtio));
    307      1.1  christos 	lock_basic_init(&dtio->wakeup_timer_lock);
    308      1.1  christos 	lock_protect(&dtio->wakeup_timer_lock, &dtio->wakeup_timer_enabled,
    309      1.1  christos 		sizeof(dtio->wakeup_timer_enabled));
    310      1.1  christos 	return dtio;
    311      1.1  christos }
    312      1.1  christos 
    313      1.1  christos void dt_io_thread_delete(struct dt_io_thread* dtio)
    314      1.1  christos {
    315      1.1  christos 	struct dt_io_list_item* item, *nextitem;
    316      1.1  christos 	if(!dtio) return;
    317      1.1  christos 	lock_basic_destroy(&dtio->wakeup_timer_lock);
    318      1.1  christos 	item=dtio->io_list;
    319      1.1  christos 	while(item) {
    320      1.1  christos 		nextitem = item->next;
    321      1.1  christos 		free(item);
    322      1.1  christos 		item = nextitem;
    323      1.1  christos 	}
    324      1.1  christos 	free(dtio->socket_path);
    325      1.1  christos 	free(dtio->ip_str);
    326      1.1  christos 	free(dtio->tls_server_name);
    327      1.1  christos 	free(dtio->client_key_file);
    328      1.1  christos 	free(dtio->client_cert_file);
    329      1.1  christos 	if(dtio->ssl_ctx) {
    330      1.1  christos #ifdef HAVE_SSL
    331      1.1  christos 		SSL_CTX_free(dtio->ssl_ctx);
    332      1.1  christos #endif
    333      1.1  christos 	}
    334      1.1  christos 	free(dtio);
    335      1.1  christos }
    336      1.1  christos 
    337      1.1  christos int dt_io_thread_apply_cfg(struct dt_io_thread* dtio, struct config_file *cfg)
    338      1.1  christos {
    339      1.1  christos 	if(!cfg->dnstap) {
    340      1.1  christos 		log_warn("cannot setup dnstap because dnstap-enable is no");
    341      1.1  christos 		return 0;
    342      1.1  christos 	}
    343      1.1  christos 
    344      1.1  christos 	/* what type of connectivity do we have */
    345      1.1  christos 	if(cfg->dnstap_ip && cfg->dnstap_ip[0]) {
    346      1.1  christos 		if(cfg->dnstap_tls)
    347      1.1  christos 			dtio->upstream_is_tls = 1;
    348      1.1  christos 		else	dtio->upstream_is_tcp = 1;
    349      1.1  christos 	} else {
    350      1.1  christos 		dtio->upstream_is_unix = 1;
    351      1.1  christos 	}
    352      1.1  christos 	dtio->is_bidirectional = cfg->dnstap_bidirectional;
    353      1.1  christos 
    354      1.1  christos 	if(dtio->upstream_is_unix) {
    355      1.1  christos 		char* nm;
    356      1.1  christos 		if(!cfg->dnstap_socket_path ||
    357      1.1  christos 			cfg->dnstap_socket_path[0]==0) {
    358      1.1  christos 			log_err("dnstap setup: no dnstap-socket-path for "
    359      1.1  christos 				"socket connect");
    360      1.1  christos 			return 0;
    361      1.1  christos 		}
    362      1.1  christos 		nm = cfg->dnstap_socket_path;
    363      1.1  christos 		if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
    364      1.1  christos 			cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
    365      1.1  christos 			nm += strlen(cfg->chrootdir);
    366      1.1  christos 		free(dtio->socket_path);
    367      1.1  christos 		dtio->socket_path = strdup(nm);
    368      1.1  christos 		if(!dtio->socket_path) {
    369      1.1  christos 			log_err("dnstap setup: malloc failure");
    370      1.1  christos 			return 0;
    371      1.1  christos 		}
    372      1.1  christos 	}
    373      1.1  christos 
    374      1.1  christos 	if(dtio->upstream_is_tcp || dtio->upstream_is_tls) {
    375      1.1  christos 		if(!cfg->dnstap_ip || cfg->dnstap_ip[0] == 0) {
    376      1.1  christos 			log_err("dnstap setup: no dnstap-ip for TCP connect");
    377      1.1  christos 			return 0;
    378      1.1  christos 		}
    379      1.1  christos 		free(dtio->ip_str);
    380      1.1  christos 		dtio->ip_str = strdup(cfg->dnstap_ip);
    381      1.1  christos 		if(!dtio->ip_str) {
    382      1.1  christos 			log_err("dnstap setup: malloc failure");
    383      1.1  christos 			return 0;
    384      1.1  christos 		}
    385      1.1  christos 	}
    386      1.1  christos 
    387      1.1  christos 	if(dtio->upstream_is_tls) {
    388      1.1  christos #ifdef HAVE_SSL
    389      1.1  christos 		if(cfg->dnstap_tls_server_name &&
    390      1.1  christos 			cfg->dnstap_tls_server_name[0]) {
    391      1.1  christos 			free(dtio->tls_server_name);
    392      1.1  christos 			dtio->tls_server_name = strdup(
    393      1.1  christos 				cfg->dnstap_tls_server_name);
    394      1.1  christos 			if(!dtio->tls_server_name) {
    395      1.1  christos 				log_err("dnstap setup: malloc failure");
    396      1.1  christos 				return 0;
    397      1.1  christos 			}
    398      1.1  christos 			if(!check_auth_name_for_ssl(dtio->tls_server_name))
    399      1.1  christos 				return 0;
    400      1.1  christos 		}
    401      1.1  christos 		if(cfg->dnstap_tls_client_key_file &&
    402      1.1  christos 			cfg->dnstap_tls_client_key_file[0]) {
    403      1.1  christos 			dtio->use_client_certs = 1;
    404      1.1  christos 			free(dtio->client_key_file);
    405      1.1  christos 			dtio->client_key_file = strdup(
    406      1.1  christos 				cfg->dnstap_tls_client_key_file);
    407      1.1  christos 			if(!dtio->client_key_file) {
    408      1.1  christos 				log_err("dnstap setup: malloc failure");
    409      1.1  christos 				return 0;
    410      1.1  christos 			}
    411      1.1  christos 			if(!cfg->dnstap_tls_client_cert_file ||
    412      1.1  christos 				cfg->dnstap_tls_client_cert_file[0]==0) {
    413      1.1  christos 				log_err("dnstap setup: client key "
    414      1.1  christos 					"authentication enabled with "
    415      1.1  christos 					"dnstap-tls-client-key-file, but "
    416      1.1  christos 					"no dnstap-tls-client-cert-file "
    417      1.1  christos 					"is given");
    418      1.1  christos 				return 0;
    419      1.1  christos 			}
    420      1.1  christos 			free(dtio->client_cert_file);
    421      1.1  christos 			dtio->client_cert_file = strdup(
    422      1.1  christos 				cfg->dnstap_tls_client_cert_file);
    423      1.1  christos 			if(!dtio->client_cert_file) {
    424      1.1  christos 				log_err("dnstap setup: malloc failure");
    425      1.1  christos 				return 0;
    426      1.1  christos 			}
    427      1.1  christos 		} else {
    428      1.1  christos 			dtio->use_client_certs = 0;
    429      1.1  christos 			dtio->client_key_file = NULL;
    430      1.1  christos 			dtio->client_cert_file = NULL;
    431      1.1  christos 		}
    432      1.1  christos 
    433      1.1  christos 		if(cfg->dnstap_tls_cert_bundle) {
    434      1.1  christos 			dtio->ssl_ctx = connect_sslctx_create(
    435      1.1  christos 				dtio->client_key_file,
    436      1.1  christos 				dtio->client_cert_file,
    437      1.1  christos 				cfg->dnstap_tls_cert_bundle, 0);
    438      1.1  christos 		} else {
    439      1.1  christos 			dtio->ssl_ctx = connect_sslctx_create(
    440      1.1  christos 				dtio->client_key_file,
    441      1.1  christos 				dtio->client_cert_file,
    442      1.1  christos 				cfg->tls_cert_bundle, cfg->tls_win_cert);
    443      1.1  christos 		}
    444      1.1  christos 		if(!dtio->ssl_ctx) {
    445      1.1  christos 			log_err("could not setup SSL CTX");
    446      1.1  christos 			return 0;
    447      1.1  christos 		}
    448      1.1  christos 		dtio->tls_use_sni = cfg->tls_use_sni;
    449      1.1  christos #endif /* HAVE_SSL */
    450      1.1  christos 	}
    451      1.1  christos 	return 1;
    452      1.1  christos }
    453      1.1  christos 
    454      1.1  christos int dt_io_thread_register_queue(struct dt_io_thread* dtio,
    455      1.1  christos         struct dt_msg_queue* mq)
    456      1.1  christos {
    457      1.1  christos 	struct dt_io_list_item* item = malloc(sizeof(*item));
    458      1.1  christos 	if(!item) return 0;
    459      1.1  christos 	lock_basic_lock(&mq->lock);
    460      1.1  christos 	mq->dtio = dtio;
    461      1.1  christos 	lock_basic_unlock(&mq->lock);
    462      1.1  christos 	item->queue = mq;
    463      1.1  christos 	item->next = dtio->io_list;
    464      1.1  christos 	dtio->io_list = item;
    465      1.1  christos 	dtio->io_list_iter = NULL;
    466      1.1  christos 	return 1;
    467      1.1  christos }
    468      1.1  christos 
    469      1.1  christos void dt_io_thread_unregister_queue(struct dt_io_thread* dtio,
    470      1.1  christos         struct dt_msg_queue* mq)
    471      1.1  christos {
    472      1.1  christos 	struct dt_io_list_item* item, *prev=NULL;
    473      1.1  christos 	if(!dtio) return;
    474      1.1  christos 	item = dtio->io_list;
    475      1.1  christos 	while(item) {
    476      1.1  christos 		if(item->queue == mq) {
    477      1.1  christos 			/* found it */
    478      1.1  christos 			if(prev) prev->next = item->next;
    479      1.1  christos 			else dtio->io_list = item->next;
    480      1.1  christos 			/* the queue itself only registered, not deleted */
    481      1.1  christos 			lock_basic_lock(&item->queue->lock);
    482      1.1  christos 			item->queue->dtio = NULL;
    483      1.1  christos 			lock_basic_unlock(&item->queue->lock);
    484      1.1  christos 			free(item);
    485      1.1  christos 			dtio->io_list_iter = NULL;
    486      1.1  christos 			return;
    487      1.1  christos 		}
    488      1.1  christos 		prev = item;
    489      1.1  christos 		item = item->next;
    490      1.1  christos 	}
    491      1.1  christos }
    492      1.1  christos 
    493      1.1  christos /** pick a message from the queue, the routine locks and unlocks,
    494      1.1  christos  * returns true if there is a message */
    495      1.1  christos static int dt_msg_queue_pop(struct dt_msg_queue* mq, void** buf,
    496      1.1  christos 	size_t* len)
    497      1.1  christos {
    498      1.1  christos 	lock_basic_lock(&mq->lock);
    499      1.1  christos 	if(mq->first) {
    500      1.1  christos 		struct dt_msg_entry* entry = mq->first;
    501      1.1  christos 		mq->first = entry->next;
    502      1.1  christos 		if(!entry->next) mq->last = NULL;
    503      1.1  christos 		mq->cursize -= entry->len;
    504      1.1  christos 		mq->msgcount --;
    505      1.1  christos 		lock_basic_unlock(&mq->lock);
    506      1.1  christos 
    507      1.1  christos 		*buf = entry->buf;
    508      1.1  christos 		*len = entry->len;
    509      1.1  christos 		free(entry);
    510      1.1  christos 		return 1;
    511      1.1  christos 	}
    512      1.1  christos 	lock_basic_unlock(&mq->lock);
    513      1.1  christos 	return 0;
    514      1.1  christos }
    515      1.1  christos 
    516      1.1  christos /** find message in queue, false if no message, true if message to send */
    517      1.1  christos static int dtio_find_in_queue(struct dt_io_thread* dtio,
    518      1.1  christos 	struct dt_msg_queue* mq)
    519      1.1  christos {
    520      1.1  christos 	void* buf=NULL;
    521      1.1  christos 	size_t len=0;
    522      1.1  christos 	if(dt_msg_queue_pop(mq, &buf, &len)) {
    523      1.1  christos 		dtio->cur_msg = buf;
    524      1.1  christos 		dtio->cur_msg_len = len;
    525      1.1  christos 		dtio->cur_msg_done = 0;
    526      1.1  christos 		dtio->cur_msg_len_done = 0;
    527      1.1  christos 		return 1;
    528      1.1  christos 	}
    529      1.1  christos 	return 0;
    530      1.1  christos }
    531      1.1  christos 
    532      1.1  christos /** find a new message to write, search message queues, false if none */
    533      1.1  christos static int dtio_find_msg(struct dt_io_thread* dtio)
    534      1.1  christos {
    535      1.1  christos 	struct dt_io_list_item *spot, *item;
    536      1.1  christos 
    537      1.1  christos 	spot = dtio->io_list_iter;
    538      1.1  christos 	/* use the next queue for the next message lookup,
    539      1.1  christos 	 * if we hit the end(NULL) the NULL restarts the iter at start. */
    540      1.1  christos 	if(spot)
    541      1.1  christos 		dtio->io_list_iter = spot->next;
    542      1.1  christos 	else if(dtio->io_list)
    543      1.1  christos 		dtio->io_list_iter = dtio->io_list->next;
    544      1.1  christos 
    545      1.1  christos 	/* scan from spot to end-of-io_list */
    546      1.1  christos 	item = spot;
    547      1.1  christos 	while(item) {
    548      1.1  christos 		if(dtio_find_in_queue(dtio, item->queue))
    549      1.1  christos 			return 1;
    550      1.1  christos 		item = item->next;
    551      1.1  christos 	}
    552      1.1  christos 	/* scan starting at the start-of-list (to wrap around the end) */
    553      1.1  christos 	item = dtio->io_list;
    554      1.1  christos 	while(item) {
    555      1.1  christos 		if(dtio_find_in_queue(dtio, item->queue))
    556      1.1  christos 			return 1;
    557      1.1  christos 		item = item->next;
    558      1.1  christos 	}
    559      1.1  christos 	return 0;
    560      1.1  christos }
    561      1.1  christos 
    562      1.1  christos /** callback for the dnstap reconnect, to start reconnecting to output */
    563      1.1  christos void dtio_reconnect_timeout_cb(int ATTR_UNUSED(fd),
    564      1.1  christos 	short ATTR_UNUSED(bits), void* arg)
    565      1.1  christos {
    566      1.1  christos 	struct dt_io_thread* dtio = (struct dt_io_thread*)arg;
    567      1.1  christos 	dtio->reconnect_is_added = 0;
    568      1.1  christos 	verbose(VERB_ALGO, "dnstap io: reconnect timer");
    569      1.1  christos 
    570      1.1  christos 	dtio_open_output(dtio);
    571      1.1  christos 	if(dtio->event) {
    572      1.1  christos 		if(!dtio_add_output_event_write(dtio))
    573      1.1  christos 			return;
    574      1.1  christos 		/* nothing wrong so far, wait on the output event */
    575      1.1  christos 		return;
    576      1.1  christos 	}
    577      1.1  christos 	/* exponential backoff and retry on timer */
    578      1.1  christos 	dtio_reconnect_enable(dtio);
    579      1.1  christos }
    580      1.1  christos 
    581      1.1  christos /** attempt to reconnect to the output, after a timeout */
    582      1.1  christos static void dtio_reconnect_enable(struct dt_io_thread* dtio)
    583      1.1  christos {
    584      1.1  christos 	struct timeval tv;
    585      1.1  christos 	int msec;
    586      1.1  christos 	if(dtio->want_to_exit) return;
    587      1.1  christos 	if(dtio->reconnect_is_added)
    588      1.1  christos 		return; /* already done */
    589      1.1  christos 
    590      1.1  christos 	/* exponential backoff, store the value for next timeout */
    591      1.1  christos 	msec = dtio->reconnect_timeout;
    592      1.1  christos 	if(msec == 0) {
    593      1.1  christos 		dtio->reconnect_timeout = DTIO_RECONNECT_TIMEOUT_MIN;
    594      1.1  christos 	} else {
    595      1.1  christos 		dtio->reconnect_timeout = msec*2;
    596      1.1  christos 		if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MAX)
    597      1.1  christos 			dtio->reconnect_timeout = DTIO_RECONNECT_TIMEOUT_MAX;
    598      1.1  christos 	}
    599      1.1  christos 	verbose(VERB_ALGO, "dnstap io: set reconnect attempt after %d msec",
    600      1.1  christos 		msec);
    601      1.1  christos 
    602      1.1  christos 	/* setup wait timer */
    603      1.1  christos 	memset(&tv, 0, sizeof(tv));
    604      1.1  christos 	tv.tv_sec = msec/1000;
    605      1.1  christos 	tv.tv_usec = (msec%1000)*1000;
    606      1.1  christos 	if(ub_timer_add(dtio->reconnect_timer, dtio->event_base,
    607      1.1  christos 		&dtio_reconnect_timeout_cb, dtio, &tv) != 0) {
    608      1.1  christos 		log_err("dnstap io: could not reconnect ev timer add");
    609      1.1  christos 		return;
    610      1.1  christos 	}
    611      1.1  christos 	dtio->reconnect_is_added = 1;
    612      1.1  christos }
    613      1.1  christos 
    614      1.1  christos /** remove dtio reconnect timer */
    615      1.1  christos static void dtio_reconnect_del(struct dt_io_thread* dtio)
    616      1.1  christos {
    617      1.1  christos 	if(!dtio->reconnect_is_added)
    618      1.1  christos 		return;
    619      1.1  christos 	ub_timer_del(dtio->reconnect_timer);
    620      1.1  christos 	dtio->reconnect_is_added = 0;
    621      1.1  christos }
    622      1.1  christos 
    623      1.1  christos /** clear the reconnect exponential backoff timer.
    624      1.1  christos  * We have successfully connected so we can try again with short timeouts. */
    625      1.1  christos static void dtio_reconnect_clear(struct dt_io_thread* dtio)
    626      1.1  christos {
    627      1.1  christos 	dtio->reconnect_timeout = 0;
    628      1.1  christos 	dtio_reconnect_del(dtio);
    629      1.1  christos }
    630      1.1  christos 
    631      1.1  christos /** reconnect slowly, because we already know we have to wait for a bit */
    632      1.1  christos static void dtio_reconnect_slow(struct dt_io_thread* dtio, int msec)
    633      1.1  christos {
    634      1.1  christos 	dtio_reconnect_del(dtio);
    635      1.1  christos 	dtio->reconnect_timeout = msec;
    636      1.1  christos 	dtio_reconnect_enable(dtio);
    637      1.1  christos }
    638      1.1  christos 
    639      1.1  christos /** delete the current message in the dtio, and reset counters */
    640      1.1  christos static void dtio_cur_msg_free(struct dt_io_thread* dtio)
    641      1.1  christos {
    642      1.1  christos 	free(dtio->cur_msg);
    643      1.1  christos 	dtio->cur_msg = NULL;
    644      1.1  christos 	dtio->cur_msg_len = 0;
    645      1.1  christos 	dtio->cur_msg_done = 0;
    646      1.1  christos 	dtio->cur_msg_len_done = 0;
    647      1.1  christos }
    648      1.1  christos 
    649      1.1  christos /** delete the buffer and counters used to read frame */
    650      1.1  christos static void dtio_read_frame_free(struct dt_frame_read_buf* rb)
    651      1.1  christos {
    652      1.1  christos 	if(rb->buf) {
    653      1.1  christos 		free(rb->buf);
    654      1.1  christos 		rb->buf = NULL;
    655      1.1  christos 	}
    656      1.1  christos 	rb->buf_count = 0;
    657      1.1  christos 	rb->buf_cap = 0;
    658      1.1  christos 	rb->frame_len = 0;
    659      1.1  christos 	rb->frame_len_done = 0;
    660      1.1  christos 	rb->control_frame = 0;
    661      1.1  christos }
    662      1.1  christos 
    663      1.1  christos /** del the output file descriptor event for listening */
    664      1.1  christos static void dtio_del_output_event(struct dt_io_thread* dtio)
    665      1.1  christos {
    666      1.1  christos 	if(!dtio->event_added)
    667      1.1  christos 		return;
    668      1.1  christos 	ub_event_del(dtio->event);
    669      1.1  christos 	dtio->event_added = 0;
    670      1.1  christos 	dtio->event_added_is_write = 0;
    671      1.1  christos }
    672      1.1  christos 
    673      1.1  christos /** close dtio socket and set it to -1 */
    674      1.1  christos static void dtio_close_fd(struct dt_io_thread* dtio)
    675      1.1  christos {
    676      1.1  christos 	sock_close(dtio->fd);
    677      1.1  christos 	dtio->fd = -1;
    678      1.1  christos }
    679      1.1  christos 
    680      1.1  christos /** close and stop the output file descriptor event */
    681      1.1  christos static void dtio_close_output(struct dt_io_thread* dtio)
    682      1.1  christos {
    683      1.1  christos 	if(!dtio->event)
    684      1.1  christos 		return;
    685      1.1  christos 	ub_event_free(dtio->event);
    686      1.1  christos 	dtio->event = NULL;
    687      1.1  christos 	if(dtio->ssl) {
    688      1.1  christos #ifdef HAVE_SSL
    689      1.1  christos 		SSL_shutdown(dtio->ssl);
    690      1.1  christos 		SSL_free(dtio->ssl);
    691      1.1  christos 		dtio->ssl = NULL;
    692      1.1  christos #endif
    693      1.1  christos 	}
    694      1.1  christos 	dtio_close_fd(dtio);
    695      1.1  christos 
    696      1.1  christos 	/* if there is a (partial) message, discard it
    697      1.1  christos 	 * we cannot send (the remainder of) it, and a new
    698      1.1  christos 	 * connection needs to start with a control frame. */
    699      1.1  christos 	if(dtio->cur_msg) {
    700      1.1  christos 		dtio_cur_msg_free(dtio);
    701      1.1  christos 	}
    702      1.1  christos 
    703      1.1  christos 	dtio->ready_frame_sent = 0;
    704      1.1  christos 	dtio->accept_frame_received = 0;
    705      1.1  christos 	dtio_read_frame_free(&dtio->read_frame);
    706      1.1  christos 
    707      1.1  christos 	dtio_reconnect_enable(dtio);
    708      1.1  christos }
    709      1.1  christos 
    710      1.1  christos /** check for pending nonblocking connect errors,
    711      1.1  christos  * returns 1 if it is okay. -1 on error (close it), 0 to try later */
    712      1.1  christos static int dtio_check_nb_connect(struct dt_io_thread* dtio)
    713      1.1  christos {
    714      1.1  christos 	int error = 0;
    715      1.1  christos 	socklen_t len = (socklen_t)sizeof(error);
    716      1.1  christos 	if(!dtio->check_nb_connect)
    717      1.1  christos 		return 1; /* everything okay */
    718      1.1  christos 	if(getsockopt(dtio->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
    719      1.1  christos 		&len) < 0) {
    720      1.1  christos #ifndef USE_WINSOCK
    721      1.1  christos 		error = errno; /* on solaris errno is error */
    722      1.1  christos #else
    723      1.1  christos 		error = WSAGetLastError();
    724      1.1  christos #endif
    725      1.1  christos 	}
    726      1.1  christos #ifndef USE_WINSOCK
    727      1.1  christos #if defined(EINPROGRESS) && defined(EWOULDBLOCK)
    728      1.1  christos 	if(error == EINPROGRESS || error == EWOULDBLOCK)
    729      1.1  christos 		return 0; /* try again later */
    730      1.1  christos #endif
    731      1.1  christos #else
    732      1.1  christos 	if(error == WSAEINPROGRESS) {
    733      1.1  christos 		return 0; /* try again later */
    734      1.1  christos 	} else if(error == WSAEWOULDBLOCK) {
    735      1.1  christos 		ub_winsock_tcp_wouldblock((dtio->stop_flush_event?
    736      1.1  christos 			dtio->stop_flush_event:dtio->event), UB_EV_WRITE);
    737      1.1  christos 		return 0; /* try again later */
    738      1.1  christos 	}
    739      1.1  christos #endif
    740      1.1  christos 	if(error != 0) {
    741      1.1  christos 		char* to = dtio->socket_path;
    742      1.1  christos 		if(!to) to = dtio->ip_str;
    743      1.1  christos 		if(!to) to = "";
    744      1.1  christos 		log_err("dnstap io: failed to connect to \"%s\": %s",
    745      1.1  christos 			to, sock_strerror(error));
    746      1.1  christos 		return -1; /* error, close it */
    747      1.1  christos 	}
    748      1.1  christos 
    749      1.1  christos 	if(dtio->ip_str)
    750      1.1  christos 		verbose(VERB_DETAIL, "dnstap io: connected to %s",
    751      1.1  christos 			dtio->ip_str);
    752      1.1  christos 	else if(dtio->socket_path)
    753      1.1  christos 		verbose(VERB_DETAIL, "dnstap io: connected to \"%s\"",
    754      1.1  christos 			dtio->socket_path);
    755      1.1  christos 	dtio_reconnect_clear(dtio);
    756      1.1  christos 	dtio->check_nb_connect = 0;
    757      1.1  christos 	return 1; /* everything okay */
    758      1.1  christos }
    759      1.1  christos 
    760      1.1  christos #ifdef HAVE_SSL
    761      1.1  christos /** write to ssl output
    762      1.1  christos  * returns number of bytes written, 0 if nothing happened,
    763      1.1  christos  * try again later, or -1 if the channel is to be closed. */
    764      1.1  christos static int dtio_write_ssl(struct dt_io_thread* dtio, uint8_t* buf,
    765      1.1  christos 	size_t len)
    766      1.1  christos {
    767      1.1  christos 	int r;
    768      1.1  christos 	ERR_clear_error();
    769      1.1  christos 	r = SSL_write(dtio->ssl, buf, len);
    770      1.1  christos 	if(r <= 0) {
    771      1.1  christos 		int want = SSL_get_error(dtio->ssl, r);
    772      1.1  christos 		if(want == SSL_ERROR_ZERO_RETURN) {
    773      1.1  christos 			/* closed */
    774      1.1  christos 			return -1;
    775      1.1  christos 		} else if(want == SSL_ERROR_WANT_READ) {
    776      1.1  christos 			/* we want a brief read event */
    777      1.1  christos 			dtio_enable_brief_read(dtio);
    778      1.1  christos 			return 0;
    779      1.1  christos 		} else if(want == SSL_ERROR_WANT_WRITE) {
    780      1.1  christos 			/* write again later */
    781      1.1  christos 			return 0;
    782      1.1  christos 		} else if(want == SSL_ERROR_SYSCALL) {
    783      1.1  christos #ifdef EPIPE
    784      1.1  christos 			if(errno == EPIPE && verbosity < 2)
    785      1.1  christos 				return -1; /* silence 'broken pipe' */
    786      1.1  christos #endif
    787      1.1  christos #ifdef ECONNRESET
    788      1.1  christos 			if(errno == ECONNRESET && verbosity < 2)
    789      1.1  christos 				return -1; /* silence reset by peer */
    790      1.1  christos #endif
    791      1.1  christos 			if(errno != 0) {
    792      1.1  christos 				log_err("dnstap io, SSL_write syscall: %s",
    793      1.1  christos 					strerror(errno));
    794      1.1  christos 			}
    795      1.1  christos 			return -1;
    796      1.1  christos 		}
    797  1.1.1.3  christos 		log_crypto_err_io("dnstap io, could not SSL_write", want);
    798      1.1  christos 		return -1;
    799      1.1  christos 	}
    800      1.1  christos 	return r;
    801      1.1  christos }
    802      1.1  christos #endif /* HAVE_SSL */
    803      1.1  christos 
    804      1.1  christos /** write buffer to output.
    805      1.1  christos  * returns number of bytes written, 0 if nothing happened,
    806      1.1  christos  * try again later, or -1 if the channel is to be closed. */
    807      1.1  christos static int dtio_write_buf(struct dt_io_thread* dtio, uint8_t* buf,
    808      1.1  christos 	size_t len)
    809      1.1  christos {
    810      1.1  christos 	ssize_t ret;
    811      1.1  christos 	if(dtio->fd == -1)
    812      1.1  christos 		return -1;
    813      1.1  christos #ifdef HAVE_SSL
    814      1.1  christos 	if(dtio->ssl)
    815      1.1  christos 		return dtio_write_ssl(dtio, buf, len);
    816      1.1  christos #endif
    817      1.1  christos 	ret = send(dtio->fd, (void*)buf, len, 0);
    818      1.1  christos 	if(ret == -1) {
    819      1.1  christos #ifndef USE_WINSOCK
    820      1.1  christos 		if(errno == EINTR || errno == EAGAIN)
    821      1.1  christos 			return 0;
    822      1.1  christos #else
    823      1.1  christos 		if(WSAGetLastError() == WSAEINPROGRESS)
    824      1.1  christos 			return 0;
    825      1.1  christos 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
    826      1.1  christos 			ub_winsock_tcp_wouldblock((dtio->stop_flush_event?
    827      1.1  christos 				dtio->stop_flush_event:dtio->event),
    828      1.1  christos 				UB_EV_WRITE);
    829      1.1  christos 			return 0;
    830      1.1  christos 		}
    831      1.1  christos #endif
    832      1.1  christos 		log_err("dnstap io: failed send: %s", sock_strerror(errno));
    833      1.1  christos 		return -1;
    834      1.1  christos 	}
    835      1.1  christos 	return ret;
    836      1.1  christos }
    837      1.1  christos 
    838      1.1  christos #ifdef HAVE_WRITEV
    839      1.1  christos /** write with writev, len and message, in one write, if possible.
    840      1.1  christos  * return true if message is done, false if incomplete */
    841      1.1  christos static int dtio_write_with_writev(struct dt_io_thread* dtio)
    842      1.1  christos {
    843      1.1  christos 	uint32_t sendlen = htonl(dtio->cur_msg_len);
    844      1.1  christos 	struct iovec iov[2];
    845      1.1  christos 	ssize_t r;
    846      1.1  christos 	iov[0].iov_base = ((uint8_t*)&sendlen)+dtio->cur_msg_len_done;
    847      1.1  christos 	iov[0].iov_len = sizeof(sendlen)-dtio->cur_msg_len_done;
    848      1.1  christos 	iov[1].iov_base = dtio->cur_msg;
    849      1.1  christos 	iov[1].iov_len = dtio->cur_msg_len;
    850      1.1  christos 	log_assert(iov[0].iov_len > 0);
    851      1.1  christos 	r = writev(dtio->fd, iov, 2);
    852      1.1  christos 	if(r == -1) {
    853      1.1  christos #ifndef USE_WINSOCK
    854      1.1  christos 		if(errno == EINTR || errno == EAGAIN)
    855      1.1  christos 			return 0;
    856      1.1  christos #else
    857      1.1  christos 		if(WSAGetLastError() == WSAEINPROGRESS)
    858      1.1  christos 			return 0;
    859      1.1  christos 		if(WSAGetLastError() == WSAEWOULDBLOCK) {
    860      1.1  christos 			ub_winsock_tcp_wouldblock((dtio->stop_flush_event?
    861      1.1  christos 				dtio->stop_flush_event:dtio->event),
    862      1.1  christos 				UB_EV_WRITE);
    863      1.1  christos 			return 0;
    864      1.1  christos 		}
    865      1.1  christos #endif
    866      1.1  christos 		log_err("dnstap io: failed writev: %s", sock_strerror(errno));
    867      1.1  christos 		/* close the channel */
    868      1.1  christos 		dtio_del_output_event(dtio);
    869      1.1  christos 		dtio_close_output(dtio);
    870      1.1  christos 		return 0;
    871      1.1  christos 	}
    872      1.1  christos 	/* written r bytes */
    873      1.1  christos 	dtio->cur_msg_len_done += r;
    874      1.1  christos 	if(dtio->cur_msg_len_done < 4)
    875      1.1  christos 		return 0;
    876      1.1  christos 	if(dtio->cur_msg_len_done > 4) {
    877      1.1  christos 		dtio->cur_msg_done = dtio->cur_msg_len_done-4;
    878      1.1  christos 		dtio->cur_msg_len_done = 4;
    879      1.1  christos 	}
    880      1.1  christos 	if(dtio->cur_msg_done < dtio->cur_msg_len)
    881      1.1  christos 		return 0;
    882      1.1  christos 	return 1;
    883      1.1  christos }
    884      1.1  christos #endif /* HAVE_WRITEV */
    885      1.1  christos 
    886      1.1  christos /** write more of the length, preceding the data frame.
    887      1.1  christos  * return true if message is done, false if incomplete. */
    888      1.1  christos static int dtio_write_more_of_len(struct dt_io_thread* dtio)
    889      1.1  christos {
    890      1.1  christos 	uint32_t sendlen;
    891      1.1  christos 	int r;
    892      1.1  christos 	if(dtio->cur_msg_len_done >= 4)
    893      1.1  christos 		return 1;
    894      1.1  christos #ifdef HAVE_WRITEV
    895      1.1  christos 	if(!dtio->ssl) {
    896      1.1  christos 		/* we try writev for everything.*/
    897      1.1  christos 		return dtio_write_with_writev(dtio);
    898      1.1  christos 	}
    899      1.1  christos #endif /* HAVE_WRITEV */
    900      1.1  christos 	sendlen = htonl(dtio->cur_msg_len);
    901      1.1  christos 	r = dtio_write_buf(dtio,
    902      1.1  christos 		((uint8_t*)&sendlen)+dtio->cur_msg_len_done,
    903      1.1  christos 		sizeof(sendlen)-dtio->cur_msg_len_done);
    904      1.1  christos 	if(r == -1) {
    905      1.1  christos 		/* close the channel */
    906      1.1  christos 		dtio_del_output_event(dtio);
    907      1.1  christos 		dtio_close_output(dtio);
    908      1.1  christos 		return 0;
    909      1.1  christos 	} else if(r == 0) {
    910      1.1  christos 		/* try again later */
    911      1.1  christos 		return 0;
    912      1.1  christos 	}
    913      1.1  christos 	dtio->cur_msg_len_done += r;
    914      1.1  christos 	if(dtio->cur_msg_len_done < 4)
    915      1.1  christos 		return 0;
    916      1.1  christos 	return 1;
    917      1.1  christos }
    918      1.1  christos 
    919      1.1  christos /** write more of the data frame.
    920      1.1  christos  * return true if message is done, false if incomplete. */
    921      1.1  christos static int dtio_write_more_of_data(struct dt_io_thread* dtio)
    922      1.1  christos {
    923      1.1  christos 	int r;
    924      1.1  christos 	if(dtio->cur_msg_done >= dtio->cur_msg_len)
    925      1.1  christos 		return 1;
    926      1.1  christos 	r = dtio_write_buf(dtio,
    927      1.1  christos 		((uint8_t*)dtio->cur_msg)+dtio->cur_msg_done,
    928      1.1  christos 		dtio->cur_msg_len - dtio->cur_msg_done);
    929      1.1  christos 	if(r == -1) {
    930      1.1  christos 		/* close the channel */
    931      1.1  christos 		dtio_del_output_event(dtio);
    932      1.1  christos 		dtio_close_output(dtio);
    933      1.1  christos 		return 0;
    934      1.1  christos 	} else if(r == 0) {
    935      1.1  christos 		/* try again later */
    936      1.1  christos 		return 0;
    937      1.1  christos 	}
    938      1.1  christos 	dtio->cur_msg_done += r;
    939      1.1  christos 	if(dtio->cur_msg_done < dtio->cur_msg_len)
    940      1.1  christos 		return 0;
    941      1.1  christos 	return 1;
    942      1.1  christos }
    943      1.1  christos 
    944  1.1.1.2  christos /** write more of the current message. false if incomplete, true if
    945      1.1  christos  * the message is done */
    946      1.1  christos static int dtio_write_more(struct dt_io_thread* dtio)
    947      1.1  christos {
    948      1.1  christos 	if(dtio->cur_msg_len_done < 4) {
    949      1.1  christos 		if(!dtio_write_more_of_len(dtio))
    950      1.1  christos 			return 0;
    951      1.1  christos 	}
    952      1.1  christos 	if(dtio->cur_msg_done < dtio->cur_msg_len) {
    953      1.1  christos 		if(!dtio_write_more_of_data(dtio))
    954      1.1  christos 			return 0;
    955      1.1  christos 	}
    956      1.1  christos 	return 1;
    957      1.1  christos }
    958      1.1  christos 
    959      1.1  christos /** Receive bytes from dtio->fd, store in buffer. Returns 0: closed,
    960      1.1  christos  * -1: continue, >0: number of bytes read into buffer */
    961      1.1  christos static ssize_t receive_bytes(struct dt_io_thread* dtio, void* buf, size_t len) {
    962      1.1  christos 	ssize_t r;
    963  1.1.1.3  christos 	r = recv(dtio->fd, (void*)buf, len, MSG_DONTWAIT);
    964      1.1  christos 	if(r == -1) {
    965      1.1  christos 		char* to = dtio->socket_path;
    966      1.1  christos 		if(!to) to = dtio->ip_str;
    967      1.1  christos 		if(!to) to = "";
    968      1.1  christos #ifndef USE_WINSOCK
    969      1.1  christos 		if(errno == EINTR || errno == EAGAIN)
    970      1.1  christos 			return -1; /* try later */
    971      1.1  christos #else
    972      1.1  christos 		if(WSAGetLastError() == WSAEINPROGRESS) {
    973      1.1  christos 			return -1; /* try later */
    974      1.1  christos 		} else if(WSAGetLastError() == WSAEWOULDBLOCK) {
    975      1.1  christos 			ub_winsock_tcp_wouldblock(
    976      1.1  christos 				(dtio->stop_flush_event?
    977      1.1  christos 				dtio->stop_flush_event:dtio->event),
    978      1.1  christos 				UB_EV_READ);
    979      1.1  christos 			return -1; /* try later */
    980      1.1  christos 		}
    981      1.1  christos #endif
    982      1.1  christos 		if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
    983      1.1  christos 			verbosity < 4)
    984      1.1  christos 			return 0; /* no log retries on low verbosity */
    985      1.1  christos 		log_err("dnstap io: output closed, recv %s: %s", to,
    986      1.1  christos 			strerror(errno));
    987      1.1  christos 		/* and close below */
    988      1.1  christos 		return 0;
    989      1.1  christos 	}
    990      1.1  christos 	if(r == 0) {
    991      1.1  christos 		if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
    992      1.1  christos 			verbosity < 4)
    993      1.1  christos 			return 0; /* no log retries on low verbosity */
    994      1.1  christos 		verbose(VERB_DETAIL, "dnstap io: output closed by the other side");
    995      1.1  christos 		/* and close below */
    996      1.1  christos 		return 0;
    997      1.1  christos 	}
    998      1.1  christos 	/* something was received */
    999      1.1  christos 	return r;
   1000      1.1  christos }
   1001      1.1  christos 
   1002      1.1  christos #ifdef HAVE_SSL
   1003      1.1  christos /** Receive bytes over TLS from dtio->fd, store in buffer. Returns 0: closed,
   1004      1.1  christos  * -1: continue, >0: number of bytes read into buffer */
   1005      1.1  christos static int ssl_read_bytes(struct dt_io_thread* dtio, void* buf, size_t len)
   1006      1.1  christos {
   1007      1.1  christos 	int r;
   1008      1.1  christos 	ERR_clear_error();
   1009      1.1  christos 	r = SSL_read(dtio->ssl, buf, len);
   1010      1.1  christos 	if(r <= 0) {
   1011      1.1  christos 		int want = SSL_get_error(dtio->ssl, r);
   1012      1.1  christos 		if(want == SSL_ERROR_ZERO_RETURN) {
   1013      1.1  christos 			if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
   1014      1.1  christos 				verbosity < 4)
   1015      1.1  christos 				return 0; /* no log retries on low verbosity */
   1016      1.1  christos 			verbose(VERB_DETAIL, "dnstap io: output closed by the "
   1017      1.1  christos 				"other side");
   1018      1.1  christos 			return 0;
   1019      1.1  christos 		} else if(want == SSL_ERROR_WANT_READ) {
   1020      1.1  christos 			/* continue later */
   1021      1.1  christos 			return -1;
   1022      1.1  christos 		} else if(want == SSL_ERROR_WANT_WRITE) {
   1023      1.1  christos 			(void)dtio_enable_brief_write(dtio);
   1024      1.1  christos 			return -1;
   1025      1.1  christos 		} else if(want == SSL_ERROR_SYSCALL) {
   1026      1.1  christos #ifdef ECONNRESET
   1027      1.1  christos 			if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
   1028      1.1  christos 				errno == ECONNRESET && verbosity < 4)
   1029      1.1  christos 				return 0; /* silence reset by peer */
   1030      1.1  christos #endif
   1031      1.1  christos 			if(errno != 0)
   1032      1.1  christos 				log_err("SSL_read syscall: %s",
   1033      1.1  christos 					strerror(errno));
   1034      1.1  christos 			verbose(VERB_DETAIL, "dnstap io: output closed by the "
   1035      1.1  christos 				"other side");
   1036      1.1  christos 			return 0;
   1037      1.1  christos 		}
   1038  1.1.1.3  christos 		log_crypto_err_io("could not SSL_read", want);
   1039      1.1  christos 		verbose(VERB_DETAIL, "dnstap io: output closed by the "
   1040      1.1  christos 				"other side");
   1041      1.1  christos 		return 0;
   1042      1.1  christos 	}
   1043      1.1  christos 	return r;
   1044      1.1  christos }
   1045      1.1  christos #endif /* HAVE_SSL */
   1046      1.1  christos 
   1047      1.1  christos /** check if the output fd has been closed,
   1048      1.1  christos  * it returns false if the stream is closed. */
   1049      1.1  christos static int dtio_check_close(struct dt_io_thread* dtio)
   1050      1.1  christos {
   1051      1.1  christos 	/* we don't want to read any packets, but if there are we can
   1052      1.1  christos 	 * discard the input (ignore it).  Ignore of unknown (control)
   1053      1.1  christos 	 * packets is okay for the framestream protocol.  And also, the
   1054      1.1  christos 	 * read call can return that the stream has been closed by the
   1055      1.1  christos 	 * other side. */
   1056      1.1  christos 	uint8_t buf[1024];
   1057      1.1  christos 	int r = -1;
   1058      1.1  christos 
   1059      1.1  christos 
   1060      1.1  christos 	if(dtio->fd == -1) return 0;
   1061      1.1  christos 
   1062      1.1  christos 	while(r != 0) {
   1063      1.1  christos 		/* not interested in buffer content, overwrite */
   1064      1.1  christos 		r = receive_bytes(dtio, (void*)buf, sizeof(buf));
   1065      1.1  christos 		if(r == -1)
   1066      1.1  christos 			return 1;
   1067      1.1  christos 	}
   1068      1.1  christos 	/* the other end has been closed */
   1069      1.1  christos 	/* close the channel */
   1070      1.1  christos 	dtio_del_output_event(dtio);
   1071      1.1  christos 	dtio_close_output(dtio);
   1072      1.1  christos 	return 0;
   1073      1.1  christos }
   1074      1.1  christos 
   1075      1.1  christos /** Read accept frame. Returns -1: continue reading, 0: closed,
   1076      1.1  christos  * 1: valid accept received. */
   1077      1.1  christos static int dtio_read_accept_frame(struct dt_io_thread* dtio)
   1078      1.1  christos {
   1079      1.1  christos 	int r;
   1080      1.1  christos 	size_t read_frame_done;
   1081      1.1  christos 	while(dtio->read_frame.frame_len_done < 4) {
   1082      1.1  christos #ifdef HAVE_SSL
   1083      1.1  christos 		if(dtio->ssl) {
   1084      1.1  christos 			r = ssl_read_bytes(dtio,
   1085      1.1  christos 				(uint8_t*)&dtio->read_frame.frame_len+
   1086      1.1  christos 				dtio->read_frame.frame_len_done,
   1087      1.1  christos 				4-dtio->read_frame.frame_len_done);
   1088      1.1  christos 		} else {
   1089      1.1  christos #endif
   1090      1.1  christos 			r = receive_bytes(dtio,
   1091      1.1  christos 				(uint8_t*)&dtio->read_frame.frame_len+
   1092      1.1  christos 				dtio->read_frame.frame_len_done,
   1093      1.1  christos 				4-dtio->read_frame.frame_len_done);
   1094      1.1  christos #ifdef HAVE_SSL
   1095      1.1  christos 		}
   1096      1.1  christos #endif
   1097      1.1  christos 		if(r == -1)
   1098      1.1  christos 			return -1; /* continue reading */
   1099      1.1  christos 		if(r == 0) {
   1100      1.1  christos 			 /* connection closed */
   1101      1.1  christos 			goto close_connection;
   1102      1.1  christos 		}
   1103      1.1  christos 		dtio->read_frame.frame_len_done += r;
   1104      1.1  christos 		if(dtio->read_frame.frame_len_done < 4)
   1105      1.1  christos 			return -1; /* continue reading */
   1106      1.1  christos 
   1107      1.1  christos 		if(dtio->read_frame.frame_len == 0) {
   1108      1.1  christos 			dtio->read_frame.frame_len_done = 0;
   1109      1.1  christos 			dtio->read_frame.control_frame = 1;
   1110      1.1  christos 			continue;
   1111      1.1  christos 		}
   1112      1.1  christos 		dtio->read_frame.frame_len = ntohl(dtio->read_frame.frame_len);
   1113      1.1  christos 		if(dtio->read_frame.frame_len > DTIO_RECV_FRAME_MAX_LEN) {
   1114      1.1  christos 			verbose(VERB_OPS, "dnstap: received frame exceeds max "
   1115      1.1  christos 				"length of %d bytes, closing connection",
   1116      1.1  christos 				DTIO_RECV_FRAME_MAX_LEN);
   1117      1.1  christos 			goto close_connection;
   1118      1.1  christos 		}
   1119      1.1  christos 		dtio->read_frame.buf = calloc(1, dtio->read_frame.frame_len);
   1120      1.1  christos 		dtio->read_frame.buf_cap = dtio->read_frame.frame_len;
   1121      1.1  christos 		if(!dtio->read_frame.buf) {
   1122      1.1  christos 			log_err("dnstap io: out of memory (creating read "
   1123      1.1  christos 				"buffer)");
   1124      1.1  christos 			goto close_connection;
   1125      1.1  christos 		}
   1126      1.1  christos 	}
   1127      1.1  christos 	if(dtio->read_frame.buf_count < dtio->read_frame.frame_len) {
   1128      1.1  christos #ifdef HAVE_SSL
   1129      1.1  christos 		if(dtio->ssl) {
   1130      1.1  christos 			r = ssl_read_bytes(dtio, dtio->read_frame.buf+
   1131      1.1  christos 				dtio->read_frame.buf_count,
   1132      1.1  christos 				dtio->read_frame.buf_cap-
   1133      1.1  christos 				dtio->read_frame.buf_count);
   1134      1.1  christos 		} else {
   1135      1.1  christos #endif
   1136      1.1  christos 			r = receive_bytes(dtio, dtio->read_frame.buf+
   1137      1.1  christos 				dtio->read_frame.buf_count,
   1138      1.1  christos 				dtio->read_frame.buf_cap-
   1139      1.1  christos 				dtio->read_frame.buf_count);
   1140      1.1  christos #ifdef HAVE_SSL
   1141      1.1  christos 		}
   1142      1.1  christos #endif
   1143      1.1  christos 		if(r == -1)
   1144      1.1  christos 			return -1; /* continue reading */
   1145      1.1  christos 		if(r == 0) {
   1146      1.1  christos 			 /* connection closed */
   1147      1.1  christos 			goto close_connection;
   1148      1.1  christos 		}
   1149      1.1  christos 		dtio->read_frame.buf_count += r;
   1150      1.1  christos 		if(dtio->read_frame.buf_count < dtio->read_frame.frame_len)
   1151      1.1  christos 			return -1; /* continue reading */
   1152      1.1  christos 	}
   1153      1.1  christos 
   1154      1.1  christos 	/* Complete frame received, check if this is a valid ACCEPT control
   1155      1.1  christos 	 * frame. */
   1156      1.1  christos 	if(dtio->read_frame.frame_len < 4) {
   1157      1.1  christos 		verbose(VERB_OPS, "dnstap: invalid data received");
   1158      1.1  christos 		goto close_connection;
   1159      1.1  christos 	}
   1160      1.1  christos 	if(sldns_read_uint32(dtio->read_frame.buf) !=
   1161      1.1  christos 		FSTRM_CONTROL_FRAME_ACCEPT) {
   1162      1.1  christos 		verbose(VERB_ALGO, "dnstap: invalid control type received, "
   1163      1.1  christos 			"ignored");
   1164      1.1  christos 		dtio->ready_frame_sent = 0;
   1165      1.1  christos 		dtio->accept_frame_received = 0;
   1166      1.1  christos 		dtio_read_frame_free(&dtio->read_frame);
   1167      1.1  christos 		return -1;
   1168      1.1  christos 	}
   1169      1.1  christos 	read_frame_done = 4; /* control frame type */
   1170      1.1  christos 
   1171      1.1  christos 	/* Iterate over control fields, ignore unknown types.
   1172      1.1  christos 	 * Need to be able to read at least 8 bytes (control field type +
   1173      1.1  christos 	 * length). */
   1174      1.1  christos 	while(read_frame_done+8 < dtio->read_frame.frame_len) {
   1175      1.1  christos 		uint32_t type = sldns_read_uint32(dtio->read_frame.buf +
   1176      1.1  christos 			read_frame_done);
   1177      1.1  christos 		uint32_t len = sldns_read_uint32(dtio->read_frame.buf +
   1178      1.1  christos 			read_frame_done + 4);
   1179      1.1  christos 		if(type == FSTRM_CONTROL_FIELD_TYPE_CONTENT_TYPE) {
   1180      1.1  christos 			if(len == strlen(DNSTAP_CONTENT_TYPE) &&
   1181      1.1  christos 				read_frame_done+8+len <=
   1182      1.1  christos 				dtio->read_frame.frame_len &&
   1183      1.1  christos 				memcmp(dtio->read_frame.buf + read_frame_done +
   1184      1.1  christos 					+ 8, DNSTAP_CONTENT_TYPE, len) == 0) {
   1185      1.1  christos 				if(!dtio_control_start_send(dtio)) {
   1186      1.1  christos 					verbose(VERB_OPS, "dnstap io: out of "
   1187      1.1  christos 					 "memory while sending START frame");
   1188      1.1  christos 					goto close_connection;
   1189      1.1  christos 				}
   1190      1.1  christos 				dtio->accept_frame_received = 1;
   1191      1.1  christos 				if(!dtio_add_output_event_write(dtio))
   1192      1.1  christos 					goto close_connection;
   1193      1.1  christos 				return 1;
   1194      1.1  christos 			} else {
   1195  1.1.1.2  christos 				/* unknown content type */
   1196      1.1  christos 				verbose(VERB_ALGO, "dnstap: ACCEPT frame "
   1197      1.1  christos 					"contains unknown content type, "
   1198      1.1  christos 					"closing connection");
   1199      1.1  christos 				goto close_connection;
   1200      1.1  christos 			}
   1201      1.1  christos 		}
   1202      1.1  christos 		/* unknown option, try next */
   1203      1.1  christos 		read_frame_done += 8+len;
   1204      1.1  christos 	}
   1205      1.1  christos 
   1206      1.1  christos 
   1207      1.1  christos close_connection:
   1208      1.1  christos 	dtio_del_output_event(dtio);
   1209      1.1  christos 	dtio_reconnect_slow(dtio, DTIO_RECONNECT_TIMEOUT_SLOW);
   1210      1.1  christos 	dtio_close_output(dtio);
   1211      1.1  christos 	return 0;
   1212      1.1  christos }
   1213      1.1  christos 
   1214      1.1  christos /** add the output file descriptor event for listening, read only */
   1215      1.1  christos static int dtio_add_output_event_read(struct dt_io_thread* dtio)
   1216      1.1  christos {
   1217      1.1  christos 	if(!dtio->event)
   1218      1.1  christos 		return 0;
   1219      1.1  christos 	if(dtio->event_added && !dtio->event_added_is_write)
   1220      1.1  christos 		return 1;
   1221      1.1  christos 	/* we have to (re-)register the event */
   1222      1.1  christos 	if(dtio->event_added)
   1223      1.1  christos 		ub_event_del(dtio->event);
   1224      1.1  christos 	ub_event_del_bits(dtio->event, UB_EV_WRITE);
   1225      1.1  christos 	if(ub_event_add(dtio->event, NULL) != 0) {
   1226      1.1  christos 		log_err("dnstap io: out of memory (adding event)");
   1227      1.1  christos 		dtio->event_added = 0;
   1228      1.1  christos 		dtio->event_added_is_write = 0;
   1229      1.1  christos 		/* close output and start reattempts to open it */
   1230      1.1  christos 		dtio_close_output(dtio);
   1231      1.1  christos 		return 0;
   1232      1.1  christos 	}
   1233      1.1  christos 	dtio->event_added = 1;
   1234      1.1  christos 	dtio->event_added_is_write = 0;
   1235      1.1  christos 	return 1;
   1236      1.1  christos }
   1237      1.1  christos 
   1238      1.1  christos /** add the output file descriptor event for listening, read and write */
   1239      1.1  christos static int dtio_add_output_event_write(struct dt_io_thread* dtio)
   1240      1.1  christos {
   1241      1.1  christos 	if(!dtio->event)
   1242      1.1  christos 		return 0;
   1243      1.1  christos 	if(dtio->event_added && dtio->event_added_is_write)
   1244      1.1  christos 		return 1;
   1245      1.1  christos 	/* we have to (re-)register the event */
   1246      1.1  christos 	if(dtio->event_added)
   1247      1.1  christos 		ub_event_del(dtio->event);
   1248      1.1  christos 	ub_event_add_bits(dtio->event, UB_EV_WRITE);
   1249      1.1  christos 	if(ub_event_add(dtio->event, NULL) != 0) {
   1250      1.1  christos 		log_err("dnstap io: out of memory (adding event)");
   1251      1.1  christos 		dtio->event_added = 0;
   1252      1.1  christos 		dtio->event_added_is_write = 0;
   1253      1.1  christos 		/* close output and start reattempts to open it */
   1254      1.1  christos 		dtio_close_output(dtio);
   1255      1.1  christos 		return 0;
   1256      1.1  christos 	}
   1257      1.1  christos 	dtio->event_added = 1;
   1258      1.1  christos 	dtio->event_added_is_write = 1;
   1259      1.1  christos 	return 1;
   1260      1.1  christos }
   1261      1.1  christos 
   1262      1.1  christos /** put the dtio thread to sleep */
   1263      1.1  christos static void dtio_sleep(struct dt_io_thread* dtio)
   1264      1.1  christos {
   1265      1.1  christos 	/* unregister the event polling for write, because there is
   1266      1.1  christos 	 * nothing to be written */
   1267      1.1  christos 	(void)dtio_add_output_event_read(dtio);
   1268  1.1.1.4  christos 
   1269  1.1.1.4  christos 	/* Set wakeuptimer enabled off; so that the next worker thread that
   1270  1.1.1.4  christos 	 * wants to log starts a timer if needed, since the writer thread
   1271  1.1.1.4  christos 	 * has gone to sleep. */
   1272  1.1.1.4  christos 	lock_basic_lock(&dtio->wakeup_timer_lock);
   1273  1.1.1.4  christos 	dtio->wakeup_timer_enabled = 0;
   1274  1.1.1.4  christos 	lock_basic_unlock(&dtio->wakeup_timer_lock);
   1275      1.1  christos }
   1276      1.1  christos 
   1277      1.1  christos #ifdef HAVE_SSL
   1278      1.1  christos /** enable the brief read condition */
   1279      1.1  christos static int dtio_enable_brief_read(struct dt_io_thread* dtio)
   1280      1.1  christos {
   1281      1.1  christos 	dtio->ssl_brief_read = 1;
   1282      1.1  christos 	if(dtio->stop_flush_event) {
   1283      1.1  christos 		ub_event_del(dtio->stop_flush_event);
   1284      1.1  christos 		ub_event_del_bits(dtio->stop_flush_event, UB_EV_WRITE);
   1285      1.1  christos 		if(ub_event_add(dtio->stop_flush_event, NULL) != 0) {
   1286      1.1  christos 			log_err("dnstap io, stop flush, could not ub_event_add");
   1287      1.1  christos 			return 0;
   1288      1.1  christos 		}
   1289      1.1  christos 		return 1;
   1290      1.1  christos 	}
   1291      1.1  christos 	return dtio_add_output_event_read(dtio);
   1292      1.1  christos }
   1293      1.1  christos #endif /* HAVE_SSL */
   1294      1.1  christos 
   1295      1.1  christos #ifdef HAVE_SSL
   1296      1.1  christos /** disable the brief read condition */
   1297      1.1  christos static int dtio_disable_brief_read(struct dt_io_thread* dtio)
   1298      1.1  christos {
   1299      1.1  christos 	dtio->ssl_brief_read = 0;
   1300      1.1  christos 	if(dtio->stop_flush_event) {
   1301      1.1  christos 		ub_event_del(dtio->stop_flush_event);
   1302      1.1  christos 		ub_event_add_bits(dtio->stop_flush_event, UB_EV_WRITE);
   1303      1.1  christos 		if(ub_event_add(dtio->stop_flush_event, NULL) != 0) {
   1304      1.1  christos 			log_err("dnstap io, stop flush, could not ub_event_add");
   1305      1.1  christos 			return 0;
   1306      1.1  christos 		}
   1307      1.1  christos 		return 1;
   1308      1.1  christos 	}
   1309      1.1  christos 	return dtio_add_output_event_write(dtio);
   1310      1.1  christos }
   1311      1.1  christos #endif /* HAVE_SSL */
   1312      1.1  christos 
   1313      1.1  christos #ifdef HAVE_SSL
   1314      1.1  christos /** enable the brief write condition */
   1315      1.1  christos static int dtio_enable_brief_write(struct dt_io_thread* dtio)
   1316      1.1  christos {
   1317      1.1  christos 	dtio->ssl_brief_write = 1;
   1318      1.1  christos 	return dtio_add_output_event_write(dtio);
   1319      1.1  christos }
   1320      1.1  christos #endif /* HAVE_SSL */
   1321      1.1  christos 
   1322      1.1  christos #ifdef HAVE_SSL
   1323      1.1  christos /** disable the brief write condition */
   1324      1.1  christos static int dtio_disable_brief_write(struct dt_io_thread* dtio)
   1325      1.1  christos {
   1326      1.1  christos 	dtio->ssl_brief_write = 0;
   1327      1.1  christos 	return dtio_add_output_event_read(dtio);
   1328      1.1  christos }
   1329      1.1  christos #endif /* HAVE_SSL */
   1330      1.1  christos 
   1331      1.1  christos #ifdef HAVE_SSL
   1332      1.1  christos /** check peer verification after ssl handshake connection, false if closed*/
   1333      1.1  christos static int dtio_ssl_check_peer(struct dt_io_thread* dtio)
   1334      1.1  christos {
   1335      1.1  christos 	if((SSL_get_verify_mode(dtio->ssl)&SSL_VERIFY_PEER)) {
   1336      1.1  christos 		/* verification */
   1337      1.1  christos 		if(SSL_get_verify_result(dtio->ssl) == X509_V_OK) {
   1338  1.1.1.4  christos #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
   1339  1.1.1.4  christos 			X509* x = SSL_get1_peer_certificate(dtio->ssl);
   1340  1.1.1.4  christos #else
   1341      1.1  christos 			X509* x = SSL_get_peer_certificate(dtio->ssl);
   1342  1.1.1.4  christos #endif
   1343      1.1  christos 			if(!x) {
   1344      1.1  christos 				verbose(VERB_ALGO, "dnstap io, %s, SSL "
   1345      1.1  christos 					"connection failed no certificate",
   1346      1.1  christos 					dtio->ip_str);
   1347      1.1  christos 				return 0;
   1348      1.1  christos 			}
   1349      1.1  christos 			log_cert(VERB_ALGO, "dnstap io, peer certificate",
   1350      1.1  christos 				x);
   1351      1.1  christos #ifdef HAVE_SSL_GET0_PEERNAME
   1352      1.1  christos 			if(SSL_get0_peername(dtio->ssl)) {
   1353      1.1  christos 				verbose(VERB_ALGO, "dnstap io, %s, SSL "
   1354      1.1  christos 					"connection to %s authenticated",
   1355      1.1  christos 					dtio->ip_str,
   1356      1.1  christos 					SSL_get0_peername(dtio->ssl));
   1357      1.1  christos 			} else {
   1358      1.1  christos #endif
   1359      1.1  christos 				verbose(VERB_ALGO, "dnstap io, %s, SSL "
   1360      1.1  christos 					"connection authenticated",
   1361      1.1  christos 					dtio->ip_str);
   1362      1.1  christos #ifdef HAVE_SSL_GET0_PEERNAME
   1363      1.1  christos 			}
   1364      1.1  christos #endif
   1365      1.1  christos 			X509_free(x);
   1366      1.1  christos 		} else {
   1367  1.1.1.4  christos #ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
   1368  1.1.1.4  christos 			X509* x = SSL_get1_peer_certificate(dtio->ssl);
   1369  1.1.1.4  christos #else
   1370      1.1  christos 			X509* x = SSL_get_peer_certificate(dtio->ssl);
   1371  1.1.1.4  christos #endif
   1372      1.1  christos 			if(x) {
   1373      1.1  christos 				log_cert(VERB_ALGO, "dnstap io, peer "
   1374      1.1  christos 					"certificate", x);
   1375      1.1  christos 				X509_free(x);
   1376      1.1  christos 			}
   1377      1.1  christos 			verbose(VERB_ALGO, "dnstap io, %s, SSL connection "
   1378      1.1  christos 				"failed: failed to authenticate",
   1379      1.1  christos 				dtio->ip_str);
   1380      1.1  christos 			return 0;
   1381      1.1  christos 		}
   1382      1.1  christos 	} else {
   1383      1.1  christos 		/* unauthenticated, the verify peer flag was not set
   1384      1.1  christos 		 * in ssl when the ssl object was created from ssl_ctx */
   1385      1.1  christos 		verbose(VERB_ALGO, "dnstap io, %s, SSL connection",
   1386      1.1  christos 			dtio->ip_str);
   1387      1.1  christos 	}
   1388      1.1  christos 	return 1;
   1389      1.1  christos }
   1390      1.1  christos #endif /* HAVE_SSL */
   1391      1.1  christos 
   1392      1.1  christos #ifdef HAVE_SSL
   1393      1.1  christos /** perform ssl handshake, returns 1 if okay, 0 to stop */
   1394      1.1  christos static int dtio_ssl_handshake(struct dt_io_thread* dtio,
   1395      1.1  christos 	struct stop_flush_info* info)
   1396      1.1  christos {
   1397      1.1  christos 	int r;
   1398      1.1  christos 	if(dtio->ssl_brief_read) {
   1399      1.1  christos 		/* assume the brief read condition is satisfied,
   1400      1.1  christos 		 * if we need more or again, we can set it again */
   1401      1.1  christos 		if(!dtio_disable_brief_read(dtio)) {
   1402      1.1  christos 			if(info) dtio_stop_flush_exit(info);
   1403      1.1  christos 			return 0;
   1404      1.1  christos 		}
   1405      1.1  christos 	}
   1406      1.1  christos 	if(dtio->ssl_handshake_done)
   1407      1.1  christos 		return 1;
   1408      1.1  christos 
   1409      1.1  christos 	ERR_clear_error();
   1410      1.1  christos 	r = SSL_do_handshake(dtio->ssl);
   1411      1.1  christos 	if(r != 1) {
   1412      1.1  christos 		int want = SSL_get_error(dtio->ssl, r);
   1413      1.1  christos 		if(want == SSL_ERROR_WANT_READ) {
   1414      1.1  christos 			/* we want to read on the connection */
   1415      1.1  christos 			if(!dtio_enable_brief_read(dtio)) {
   1416      1.1  christos 				if(info) dtio_stop_flush_exit(info);
   1417      1.1  christos 				return 0;
   1418      1.1  christos 			}
   1419      1.1  christos 			return 0;
   1420      1.1  christos 		} else if(want == SSL_ERROR_WANT_WRITE) {
   1421      1.1  christos 			/* we want to write on the connection */
   1422      1.1  christos 			return 0;
   1423      1.1  christos 		} else if(r == 0) {
   1424      1.1  christos 			/* closed */
   1425      1.1  christos 			if(info) dtio_stop_flush_exit(info);
   1426      1.1  christos 			dtio_del_output_event(dtio);
   1427      1.1  christos 			dtio_reconnect_slow(dtio, DTIO_RECONNECT_TIMEOUT_SLOW);
   1428      1.1  christos 			dtio_close_output(dtio);
   1429      1.1  christos 			return 0;
   1430      1.1  christos 		} else if(want == SSL_ERROR_SYSCALL) {
   1431      1.1  christos 			/* SYSCALL and errno==0 means closed uncleanly */
   1432      1.1  christos 			int silent = 0;
   1433      1.1  christos #ifdef EPIPE
   1434      1.1  christos 			if(errno == EPIPE && verbosity < 2)
   1435      1.1  christos 				silent = 1; /* silence 'broken pipe' */
   1436      1.1  christos #endif
   1437      1.1  christos #ifdef ECONNRESET
   1438      1.1  christos 			if(errno == ECONNRESET && verbosity < 2)
   1439      1.1  christos 				silent = 1; /* silence reset by peer */
   1440      1.1  christos #endif
   1441      1.1  christos 			if(errno == 0)
   1442      1.1  christos 				silent = 1;
   1443      1.1  christos 			if(!silent)
   1444      1.1  christos 				log_err("dnstap io, SSL_handshake syscall: %s",
   1445      1.1  christos 					strerror(errno));
   1446      1.1  christos 			/* closed */
   1447      1.1  christos 			if(info) dtio_stop_flush_exit(info);
   1448      1.1  christos 			dtio_del_output_event(dtio);
   1449      1.1  christos 			dtio_reconnect_slow(dtio, DTIO_RECONNECT_TIMEOUT_SLOW);
   1450      1.1  christos 			dtio_close_output(dtio);
   1451      1.1  christos 			return 0;
   1452      1.1  christos 		} else {
   1453      1.1  christos 			unsigned long err = ERR_get_error();
   1454      1.1  christos 			if(!squelch_err_ssl_handshake(err)) {
   1455  1.1.1.3  christos 				log_crypto_err_io_code("dnstap io, ssl handshake failed",
   1456  1.1.1.3  christos 					want, err);
   1457      1.1  christos 				verbose(VERB_OPS, "dnstap io, ssl handshake failed "
   1458      1.1  christos 					"from %s", dtio->ip_str);
   1459      1.1  christos 			}
   1460      1.1  christos 			/* closed */
   1461      1.1  christos 			if(info) dtio_stop_flush_exit(info);
   1462      1.1  christos 			dtio_del_output_event(dtio);
   1463      1.1  christos 			dtio_reconnect_slow(dtio, DTIO_RECONNECT_TIMEOUT_SLOW);
   1464      1.1  christos 			dtio_close_output(dtio);
   1465      1.1  christos 			return 0;
   1466      1.1  christos 		}
   1467      1.1  christos 
   1468      1.1  christos 	}
   1469      1.1  christos 	/* check peer verification */
   1470      1.1  christos 	dtio->ssl_handshake_done = 1;
   1471      1.1  christos 
   1472      1.1  christos 	if(!dtio_ssl_check_peer(dtio)) {
   1473      1.1  christos 		/* closed */
   1474      1.1  christos 		if(info) dtio_stop_flush_exit(info);
   1475      1.1  christos 		dtio_del_output_event(dtio);
   1476      1.1  christos 		dtio_reconnect_slow(dtio, DTIO_RECONNECT_TIMEOUT_SLOW);
   1477      1.1  christos 		dtio_close_output(dtio);
   1478      1.1  christos 		return 0;
   1479      1.1  christos 	}
   1480      1.1  christos 	return 1;
   1481      1.1  christos }
   1482      1.1  christos #endif /* HAVE_SSL */
   1483      1.1  christos 
   1484      1.1  christos /** callback for the dnstap events, to write to the output */
   1485      1.1  christos void dtio_output_cb(int ATTR_UNUSED(fd), short bits, void* arg)
   1486      1.1  christos {
   1487      1.1  christos 	struct dt_io_thread* dtio = (struct dt_io_thread*)arg;
   1488      1.1  christos 	int i;
   1489      1.1  christos 
   1490      1.1  christos 	if(dtio->check_nb_connect) {
   1491      1.1  christos 		int connect_err = dtio_check_nb_connect(dtio);
   1492      1.1  christos 		if(connect_err == -1) {
   1493      1.1  christos 			/* close the channel */
   1494      1.1  christos 			dtio_del_output_event(dtio);
   1495      1.1  christos 			dtio_close_output(dtio);
   1496      1.1  christos 			return;
   1497      1.1  christos 		} else if(connect_err == 0) {
   1498      1.1  christos 			/* try again later */
   1499      1.1  christos 			return;
   1500      1.1  christos 		}
   1501      1.1  christos 		/* nonblocking connect check passed, continue */
   1502      1.1  christos 	}
   1503      1.1  christos 
   1504      1.1  christos #ifdef HAVE_SSL
   1505      1.1  christos 	if(dtio->ssl &&
   1506      1.1  christos 		(!dtio->ssl_handshake_done || dtio->ssl_brief_read)) {
   1507      1.1  christos 		if(!dtio_ssl_handshake(dtio, NULL))
   1508      1.1  christos 			return;
   1509      1.1  christos 	}
   1510      1.1  christos #endif
   1511      1.1  christos 
   1512  1.1.1.5  christos 	if((bits&UB_EV_READ) || dtio->ssl_brief_write) {
   1513  1.1.1.4  christos #ifdef HAVE_SSL
   1514      1.1  christos 		if(dtio->ssl_brief_write)
   1515      1.1  christos 			(void)dtio_disable_brief_write(dtio);
   1516  1.1.1.4  christos #endif
   1517      1.1  christos 		if(dtio->ready_frame_sent && !dtio->accept_frame_received) {
   1518      1.1  christos 			if(dtio_read_accept_frame(dtio) <= 0)
   1519      1.1  christos 				return;
   1520      1.1  christos 		} else if(!dtio_check_close(dtio))
   1521      1.1  christos 			return;
   1522      1.1  christos 	}
   1523      1.1  christos 
   1524      1.1  christos 	/* loop to process a number of messages.  This improves throughput,
   1525      1.1  christos 	 * because selecting on write-event if not needed for busy messages
   1526      1.1  christos 	 * (dnstap log) generation and if they need to all be written back.
   1527      1.1  christos 	 * The write event is usually not blocked up.  But not forever,
   1528      1.1  christos 	 * because the event loop needs to stay responsive for other events.
   1529      1.1  christos 	 * If there are no (more) messages, or if the output buffers get
   1530      1.1  christos 	 * full, it returns out of the loop. */
   1531      1.1  christos 	for(i=0; i<DTIO_MESSAGES_PER_CALLBACK; i++) {
   1532      1.1  christos 		/* see if there are messages that need writing */
   1533      1.1  christos 		if(!dtio->cur_msg) {
   1534      1.1  christos 			if(!dtio_find_msg(dtio)) {
   1535      1.1  christos 				if(i == 0) {
   1536      1.1  christos 					/* no messages on the first iteration,
   1537      1.1  christos 					 * the queues are all empty */
   1538      1.1  christos 					dtio_sleep(dtio);
   1539  1.1.1.4  christos 					/* After putting to sleep, see if
   1540  1.1.1.4  christos 					 * a message is in a message queue,
   1541  1.1.1.4  christos 					 * if so, resume service. Stops a
   1542  1.1.1.4  christos 					 * race condition where a thread could
   1543  1.1.1.4  christos 					 * have one message but the dtio
   1544  1.1.1.4  christos 					 * also just went to sleep. With the
   1545  1.1.1.4  christos 					 * message queued between the
   1546  1.1.1.4  christos 					 * dtio_find_msg and dtio_sleep
   1547  1.1.1.4  christos 					 * calls. */
   1548  1.1.1.4  christos 					if(dtio_find_msg(dtio)) {
   1549  1.1.1.4  christos 						if(!dtio_add_output_event_write(dtio))
   1550  1.1.1.4  christos 							return;
   1551  1.1.1.4  christos 					}
   1552      1.1  christos 				}
   1553  1.1.1.4  christos 				if(!dtio->cur_msg)
   1554  1.1.1.4  christos 					return; /* nothing to do */
   1555      1.1  christos 			}
   1556      1.1  christos 		}
   1557      1.1  christos 
   1558      1.1  christos 		/* write it */
   1559      1.1  christos 		if(dtio->cur_msg_done < dtio->cur_msg_len) {
   1560      1.1  christos 			if(!dtio_write_more(dtio))
   1561      1.1  christos 				return;
   1562      1.1  christos 		}
   1563      1.1  christos 
   1564      1.1  christos 		/* done with the current message */
   1565      1.1  christos 		dtio_cur_msg_free(dtio);
   1566      1.1  christos 
   1567      1.1  christos 		/* If this is a bidirectional stream the first message will be
   1568      1.1  christos 		 * the READY control frame. We can only continue writing after
   1569      1.1  christos 		 * receiving an ACCEPT control frame. */
   1570      1.1  christos 		if(dtio->is_bidirectional && !dtio->ready_frame_sent) {
   1571      1.1  christos 			dtio->ready_frame_sent = 1;
   1572      1.1  christos 			(void)dtio_add_output_event_read(dtio);
   1573      1.1  christos 			break;
   1574      1.1  christos 		}
   1575      1.1  christos 	}
   1576      1.1  christos }
   1577      1.1  christos 
   1578      1.1  christos /** callback for the dnstap commandpipe, to stop the dnstap IO */
   1579      1.1  christos void dtio_cmd_cb(int fd, short ATTR_UNUSED(bits), void* arg)
   1580      1.1  christos {
   1581      1.1  christos 	struct dt_io_thread* dtio = (struct dt_io_thread*)arg;
   1582      1.1  christos 	uint8_t cmd;
   1583      1.1  christos 	ssize_t r;
   1584      1.1  christos 	if(dtio->want_to_exit)
   1585      1.1  christos 		return;
   1586      1.1  christos 	r = read(fd, &cmd, sizeof(cmd));
   1587      1.1  christos 	if(r == -1) {
   1588      1.1  christos #ifndef USE_WINSOCK
   1589      1.1  christos 		if(errno == EINTR || errno == EAGAIN)
   1590      1.1  christos 			return; /* ignore this */
   1591      1.1  christos #else
   1592      1.1  christos 		if(WSAGetLastError() == WSAEINPROGRESS)
   1593      1.1  christos 			return;
   1594      1.1  christos 		if(WSAGetLastError() == WSAEWOULDBLOCK)
   1595      1.1  christos 			return;
   1596      1.1  christos #endif
   1597      1.1  christos 		log_err("dnstap io: failed to read: %s", sock_strerror(errno));
   1598      1.1  christos 		/* and then fall through to quit the thread */
   1599      1.1  christos 	} else if(r == 0) {
   1600      1.1  christos 		verbose(VERB_ALGO, "dnstap io: cmd channel closed");
   1601      1.1  christos 	} else if(r == 1 && cmd == DTIO_COMMAND_STOP) {
   1602      1.1  christos 		verbose(VERB_ALGO, "dnstap io: cmd channel cmd quit");
   1603      1.1  christos 	} else if(r == 1 && cmd == DTIO_COMMAND_WAKEUP) {
   1604      1.1  christos 		verbose(VERB_ALGO, "dnstap io: cmd channel cmd wakeup");
   1605      1.1  christos 
   1606      1.1  christos 		if(dtio->is_bidirectional && !dtio->accept_frame_received) {
   1607      1.1  christos 			verbose(VERB_ALGO, "dnstap io: cmd wakeup ignored, "
   1608      1.1  christos 				"waiting for ACCEPT control frame");
   1609      1.1  christos 			return;
   1610      1.1  christos 		}
   1611      1.1  christos 
   1612      1.1  christos 		/* reregister event */
   1613      1.1  christos 		if(!dtio_add_output_event_write(dtio))
   1614      1.1  christos 			return;
   1615      1.1  christos 		return;
   1616      1.1  christos 	} else if(r == 1) {
   1617      1.1  christos 		verbose(VERB_ALGO, "dnstap io: cmd channel unknown command");
   1618      1.1  christos 	}
   1619      1.1  christos 	dtio->want_to_exit = 1;
   1620      1.1  christos 	if(ub_event_base_loopexit((struct ub_event_base*)dtio->event_base)
   1621      1.1  christos 		!= 0) {
   1622      1.1  christos 		log_err("dnstap io: could not loopexit");
   1623      1.1  christos 	}
   1624      1.1  christos }
   1625      1.1  christos 
   1626      1.1  christos #ifndef THREADS_DISABLED
   1627      1.1  christos /** setup the event base for the dnstap io thread */
   1628      1.1  christos static void dtio_setup_base(struct dt_io_thread* dtio, time_t* secs,
   1629      1.1  christos 	struct timeval* now)
   1630      1.1  christos {
   1631      1.1  christos 	memset(now, 0, sizeof(*now));
   1632      1.1  christos 	dtio->event_base = ub_default_event_base(0, secs, now);
   1633      1.1  christos 	if(!dtio->event_base) {
   1634      1.1  christos 		fatal_exit("dnstap io: could not create event_base");
   1635      1.1  christos 	}
   1636      1.1  christos }
   1637      1.1  christos #endif /* THREADS_DISABLED */
   1638      1.1  christos 
   1639      1.1  christos /** setup the cmd event for dnstap io */
   1640      1.1  christos static void dtio_setup_cmd(struct dt_io_thread* dtio)
   1641      1.1  christos {
   1642      1.1  christos 	struct ub_event* cmdev;
   1643      1.1  christos 	fd_set_nonblock(dtio->commandpipe[0]);
   1644      1.1  christos 	cmdev = ub_event_new(dtio->event_base, dtio->commandpipe[0],
   1645      1.1  christos 		UB_EV_READ | UB_EV_PERSIST, &dtio_cmd_cb, dtio);
   1646      1.1  christos 	if(!cmdev) {
   1647      1.1  christos 		fatal_exit("dnstap io: out of memory");
   1648      1.1  christos 	}
   1649      1.1  christos 	dtio->command_event = cmdev;
   1650      1.1  christos 	if(ub_event_add(cmdev, NULL) != 0) {
   1651      1.1  christos 		fatal_exit("dnstap io: out of memory (adding event)");
   1652      1.1  christos 	}
   1653      1.1  christos }
   1654      1.1  christos 
   1655      1.1  christos /** setup the reconnect event for dnstap io */
   1656      1.1  christos static void dtio_setup_reconnect(struct dt_io_thread* dtio)
   1657      1.1  christos {
   1658      1.1  christos 	dtio_reconnect_clear(dtio);
   1659      1.1  christos 	dtio->reconnect_timer = ub_event_new(dtio->event_base, -1,
   1660      1.1  christos 		UB_EV_TIMEOUT, &dtio_reconnect_timeout_cb, dtio);
   1661      1.1  christos 	if(!dtio->reconnect_timer) {
   1662      1.1  christos 		fatal_exit("dnstap io: out of memory");
   1663      1.1  christos 	}
   1664      1.1  christos }
   1665      1.1  christos 
   1666      1.1  christos /**
   1667      1.1  christos  * structure to keep track of information during stop flush
   1668      1.1  christos  */
   1669      1.1  christos struct stop_flush_info {
   1670      1.1  christos 	/** the event base during stop flush */
   1671      1.1  christos 	struct ub_event_base* base;
   1672      1.1  christos 	/** did we already want to exit this stop-flush event base */
   1673      1.1  christos 	int want_to_exit_flush;
   1674      1.1  christos 	/** has the timer fired */
   1675      1.1  christos 	int timer_done;
   1676      1.1  christos 	/** the dtio */
   1677      1.1  christos 	struct dt_io_thread* dtio;
   1678      1.1  christos 	/** the stop control frame */
   1679      1.1  christos 	void* stop_frame;
   1680      1.1  christos 	/** length of the stop frame */
   1681      1.1  christos 	size_t stop_frame_len;
   1682      1.1  christos 	/** how much we have done of the stop frame */
   1683      1.1  christos 	size_t stop_frame_done;
   1684      1.1  christos };
   1685      1.1  christos 
   1686      1.1  christos /** exit the stop flush base */
   1687      1.1  christos static void dtio_stop_flush_exit(struct stop_flush_info* info)
   1688      1.1  christos {
   1689      1.1  christos 	if(info->want_to_exit_flush)
   1690      1.1  christos 		return;
   1691      1.1  christos 	info->want_to_exit_flush = 1;
   1692      1.1  christos 	if(ub_event_base_loopexit(info->base) != 0) {
   1693      1.1  christos 		log_err("dnstap io: could not loopexit");
   1694      1.1  christos 	}
   1695      1.1  christos }
   1696      1.1  christos 
   1697      1.1  christos /** send the stop control,
   1698      1.1  christos  * return true if completed the frame. */
   1699      1.1  christos static int dtio_control_stop_send(struct stop_flush_info* info)
   1700      1.1  christos {
   1701      1.1  christos 	struct dt_io_thread* dtio = info->dtio;
   1702      1.1  christos 	int r;
   1703      1.1  christos 	if(info->stop_frame_done >= info->stop_frame_len)
   1704      1.1  christos 		return 1;
   1705      1.1  christos 	r = dtio_write_buf(dtio, ((uint8_t*)info->stop_frame) +
   1706      1.1  christos 		info->stop_frame_done, info->stop_frame_len -
   1707      1.1  christos 		info->stop_frame_done);
   1708      1.1  christos 	if(r == -1) {
   1709      1.1  christos 		verbose(VERB_ALGO, "dnstap io: stop flush: output closed");
   1710      1.1  christos 		dtio_stop_flush_exit(info);
   1711      1.1  christos 		return 0;
   1712      1.1  christos 	}
   1713      1.1  christos 	if(r == 0) {
   1714      1.1  christos 		/* try again later, or timeout */
   1715      1.1  christos 		return 0;
   1716      1.1  christos 	}
   1717      1.1  christos 	info->stop_frame_done += r;
   1718      1.1  christos 	if(info->stop_frame_done < info->stop_frame_len)
   1719      1.1  christos 		return 0; /* not done yet */
   1720      1.1  christos 	return 1;
   1721      1.1  christos }
   1722      1.1  christos 
   1723      1.1  christos void dtio_stop_timer_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(bits),
   1724      1.1  christos 	void* arg)
   1725      1.1  christos {
   1726      1.1  christos 	struct stop_flush_info* info = (struct stop_flush_info*)arg;
   1727      1.1  christos 	if(info->want_to_exit_flush)
   1728      1.1  christos 		return;
   1729      1.1  christos 	verbose(VERB_ALGO, "dnstap io: stop flush timer expired, stop flush");
   1730      1.1  christos 	info->timer_done = 1;
   1731      1.1  christos 	dtio_stop_flush_exit(info);
   1732      1.1  christos }
   1733      1.1  christos 
   1734      1.1  christos void dtio_stop_ev_cb(int ATTR_UNUSED(fd), short bits, void* arg)
   1735      1.1  christos {
   1736      1.1  christos 	struct stop_flush_info* info = (struct stop_flush_info*)arg;
   1737      1.1  christos 	struct dt_io_thread* dtio = info->dtio;
   1738      1.1  christos 	if(info->want_to_exit_flush)
   1739      1.1  christos 		return;
   1740      1.1  christos 	if(dtio->check_nb_connect) {
   1741      1.1  christos 		/* we don't start the stop_flush if connect still
   1742      1.1  christos 		 * in progress, but the check code is here, just in case */
   1743      1.1  christos 		int connect_err = dtio_check_nb_connect(dtio);
   1744      1.1  christos 		if(connect_err == -1) {
   1745      1.1  christos 			/* close the channel, exit the stop flush */
   1746      1.1  christos 			dtio_stop_flush_exit(info);
   1747      1.1  christos 			dtio_del_output_event(dtio);
   1748      1.1  christos 			dtio_close_output(dtio);
   1749      1.1  christos 			return;
   1750      1.1  christos 		} else if(connect_err == 0) {
   1751      1.1  christos 			/* try again later */
   1752      1.1  christos 			return;
   1753      1.1  christos 		}
   1754      1.1  christos 		/* nonblocking connect check passed, continue */
   1755      1.1  christos 	}
   1756      1.1  christos #ifdef HAVE_SSL
   1757      1.1  christos 	if(dtio->ssl &&
   1758      1.1  christos 		(!dtio->ssl_handshake_done || dtio->ssl_brief_read)) {
   1759      1.1  christos 		if(!dtio_ssl_handshake(dtio, info))
   1760      1.1  christos 			return;
   1761      1.1  christos 	}
   1762      1.1  christos #endif
   1763      1.1  christos 
   1764      1.1  christos 	if((bits&UB_EV_READ)) {
   1765      1.1  christos 		if(!dtio_check_close(dtio)) {
   1766      1.1  christos 			if(dtio->fd == -1) {
   1767      1.1  christos 				verbose(VERB_ALGO, "dnstap io: "
   1768      1.1  christos 					"stop flush: output closed");
   1769      1.1  christos 				dtio_stop_flush_exit(info);
   1770      1.1  christos 			}
   1771      1.1  christos 			return;
   1772      1.1  christos 		}
   1773      1.1  christos 	}
   1774      1.1  christos 	/* write remainder of last frame */
   1775      1.1  christos 	if(dtio->cur_msg) {
   1776      1.1  christos 		if(dtio->cur_msg_done < dtio->cur_msg_len) {
   1777      1.1  christos 			if(!dtio_write_more(dtio)) {
   1778      1.1  christos 				if(dtio->fd == -1) {
   1779      1.1  christos 					verbose(VERB_ALGO, "dnstap io: "
   1780      1.1  christos 						"stop flush: output closed");
   1781      1.1  christos 					dtio_stop_flush_exit(info);
   1782      1.1  christos 				}
   1783      1.1  christos 				return;
   1784      1.1  christos 			}
   1785      1.1  christos 		}
   1786      1.1  christos 		verbose(VERB_ALGO, "dnstap io: stop flush completed "
   1787      1.1  christos 			"last frame");
   1788      1.1  christos 		dtio_cur_msg_free(dtio);
   1789      1.1  christos 	}
   1790      1.1  christos 	/* write stop frame */
   1791      1.1  christos 	if(info->stop_frame_done < info->stop_frame_len) {
   1792      1.1  christos 		if(!dtio_control_stop_send(info))
   1793      1.1  christos 			return;
   1794      1.1  christos 		verbose(VERB_ALGO, "dnstap io: stop flush completed "
   1795      1.1  christos 			"stop control frame");
   1796      1.1  christos 	}
   1797      1.1  christos 	/* when last frame and stop frame are sent, exit */
   1798      1.1  christos 	dtio_stop_flush_exit(info);
   1799      1.1  christos }
   1800      1.1  christos 
   1801      1.1  christos /** flush at end, last packet and stop control */
   1802      1.1  christos static void dtio_control_stop_flush(struct dt_io_thread* dtio)
   1803      1.1  christos {
   1804      1.1  christos 	/* briefly attempt to flush the previous packet to the output,
   1805      1.1  christos 	 * this could be a partial packet, or even the start control frame */
   1806      1.1  christos 	time_t secs = 0;
   1807      1.1  christos 	struct timeval now;
   1808      1.1  christos 	struct stop_flush_info info;
   1809      1.1  christos 	struct timeval tv;
   1810      1.1  christos 	struct ub_event* timer, *stopev;
   1811      1.1  christos 
   1812      1.1  christos 	if(dtio->fd == -1 || dtio->check_nb_connect) {
   1813      1.1  christos 		/* no connection or we have just connected, so nothing is
   1814      1.1  christos 		 * sent yet, so nothing to stop or flush */
   1815      1.1  christos 		return;
   1816      1.1  christos 	}
   1817      1.1  christos 	if(dtio->ssl && !dtio->ssl_handshake_done) {
   1818      1.1  christos 		/* no SSL connection has been established yet */
   1819      1.1  christos 		return;
   1820      1.1  christos 	}
   1821      1.1  christos 
   1822      1.1  christos 	memset(&info, 0, sizeof(info));
   1823      1.1  christos 	memset(&now, 0, sizeof(now));
   1824      1.1  christos 	info.dtio = dtio;
   1825      1.1  christos 	info.base = ub_default_event_base(0, &secs, &now);
   1826      1.1  christos 	if(!info.base) {
   1827      1.1  christos 		log_err("dnstap io: malloc failure");
   1828      1.1  christos 		return;
   1829      1.1  christos 	}
   1830      1.1  christos 	timer = ub_event_new(info.base, -1, UB_EV_TIMEOUT,
   1831      1.1  christos 		&dtio_stop_timer_cb, &info);
   1832      1.1  christos 	if(!timer) {
   1833      1.1  christos 		log_err("dnstap io: malloc failure");
   1834      1.1  christos 		ub_event_base_free(info.base);
   1835      1.1  christos 		return;
   1836      1.1  christos 	}
   1837      1.1  christos 	memset(&tv, 0, sizeof(tv));
   1838      1.1  christos 	tv.tv_sec = 2;
   1839      1.1  christos 	if(ub_timer_add(timer, info.base, &dtio_stop_timer_cb, &info,
   1840      1.1  christos 		&tv) != 0) {
   1841      1.1  christos 		log_err("dnstap io: cannot event_timer_add");
   1842      1.1  christos 		ub_event_free(timer);
   1843      1.1  christos 		ub_event_base_free(info.base);
   1844      1.1  christos 		return;
   1845      1.1  christos 	}
   1846      1.1  christos 	stopev = ub_event_new(info.base, dtio->fd, UB_EV_READ |
   1847      1.1  christos 		UB_EV_WRITE | UB_EV_PERSIST, &dtio_stop_ev_cb, &info);
   1848      1.1  christos 	if(!stopev) {
   1849      1.1  christos 		log_err("dnstap io: malloc failure");
   1850      1.1  christos 		ub_timer_del(timer);
   1851      1.1  christos 		ub_event_free(timer);
   1852      1.1  christos 		ub_event_base_free(info.base);
   1853      1.1  christos 		return;
   1854      1.1  christos 	}
   1855      1.1  christos 	if(ub_event_add(stopev, NULL) != 0) {
   1856      1.1  christos 		log_err("dnstap io: cannot event_add");
   1857      1.1  christos 		ub_event_free(stopev);
   1858      1.1  christos 		ub_timer_del(timer);
   1859      1.1  christos 		ub_event_free(timer);
   1860      1.1  christos 		ub_event_base_free(info.base);
   1861      1.1  christos 		return;
   1862      1.1  christos 	}
   1863      1.1  christos 	info.stop_frame = fstrm_create_control_frame_stop(
   1864      1.1  christos 		&info.stop_frame_len);
   1865      1.1  christos 	if(!info.stop_frame) {
   1866      1.1  christos 		log_err("dnstap io: malloc failure");
   1867      1.1  christos 		ub_event_del(stopev);
   1868      1.1  christos 		ub_event_free(stopev);
   1869      1.1  christos 		ub_timer_del(timer);
   1870      1.1  christos 		ub_event_free(timer);
   1871      1.1  christos 		ub_event_base_free(info.base);
   1872      1.1  christos 		return;
   1873      1.1  christos 	}
   1874      1.1  christos 	dtio->stop_flush_event = stopev;
   1875      1.1  christos 
   1876      1.1  christos 	/* wait briefly, or until finished */
   1877      1.1  christos 	verbose(VERB_ALGO, "dnstap io: stop flush started");
   1878      1.1  christos 	if(ub_event_base_dispatch(info.base) < 0) {
   1879      1.1  christos 		log_err("dnstap io: dispatch flush failed, errno is %s",
   1880      1.1  christos 			strerror(errno));
   1881      1.1  christos 	}
   1882      1.1  christos 	verbose(VERB_ALGO, "dnstap io: stop flush ended");
   1883      1.1  christos 	free(info.stop_frame);
   1884      1.1  christos 	dtio->stop_flush_event = NULL;
   1885      1.1  christos 	ub_event_del(stopev);
   1886      1.1  christos 	ub_event_free(stopev);
   1887      1.1  christos 	ub_timer_del(timer);
   1888      1.1  christos 	ub_event_free(timer);
   1889      1.1  christos 	ub_event_base_free(info.base);
   1890      1.1  christos }
   1891      1.1  christos 
   1892      1.1  christos /** perform desetup and free stuff when the dnstap io thread exits */
   1893      1.1  christos static void dtio_desetup(struct dt_io_thread* dtio)
   1894      1.1  christos {
   1895      1.1  christos 	dtio_control_stop_flush(dtio);
   1896      1.1  christos 	dtio_del_output_event(dtio);
   1897      1.1  christos 	dtio_close_output(dtio);
   1898      1.1  christos 	ub_event_del(dtio->command_event);
   1899      1.1  christos 	ub_event_free(dtio->command_event);
   1900      1.1  christos #ifndef USE_WINSOCK
   1901      1.1  christos 	close(dtio->commandpipe[0]);
   1902      1.1  christos #else
   1903      1.1  christos 	_close(dtio->commandpipe[0]);
   1904      1.1  christos #endif
   1905      1.1  christos 	dtio->commandpipe[0] = -1;
   1906      1.1  christos 	dtio_reconnect_del(dtio);
   1907      1.1  christos 	ub_event_free(dtio->reconnect_timer);
   1908      1.1  christos 	dtio_cur_msg_free(dtio);
   1909      1.1  christos #ifndef THREADS_DISABLED
   1910      1.1  christos 	ub_event_base_free(dtio->event_base);
   1911      1.1  christos #endif
   1912      1.1  christos }
   1913      1.1  christos 
   1914      1.1  christos /** setup a start control message */
   1915      1.1  christos static int dtio_control_start_send(struct dt_io_thread* dtio)
   1916      1.1  christos {
   1917      1.1  christos 	log_assert(dtio->cur_msg == NULL && dtio->cur_msg_len == 0);
   1918      1.1  christos 	dtio->cur_msg = fstrm_create_control_frame_start(DNSTAP_CONTENT_TYPE,
   1919      1.1  christos 		&dtio->cur_msg_len);
   1920      1.1  christos 	if(!dtio->cur_msg) {
   1921      1.1  christos 		return 0;
   1922      1.1  christos 	}
   1923      1.1  christos 	/* setup to send the control message */
   1924      1.1  christos 	/* set that the buffer needs to be sent, but the length
   1925      1.1  christos 	 * of that buffer is already written, that way the buffer can
   1926      1.1  christos 	 * start with 0 length and then the length of the control frame
   1927      1.1  christos 	 * in it */
   1928      1.1  christos 	dtio->cur_msg_done = 0;
   1929      1.1  christos 	dtio->cur_msg_len_done = 4;
   1930      1.1  christos 	return 1;
   1931      1.1  christos }
   1932      1.1  christos 
   1933      1.1  christos /** setup a ready control message */
   1934      1.1  christos static int dtio_control_ready_send(struct dt_io_thread* dtio)
   1935      1.1  christos {
   1936      1.1  christos 	log_assert(dtio->cur_msg == NULL && dtio->cur_msg_len == 0);
   1937      1.1  christos 	dtio->cur_msg = fstrm_create_control_frame_ready(DNSTAP_CONTENT_TYPE,
   1938      1.1  christos 		&dtio->cur_msg_len);
   1939      1.1  christos 	if(!dtio->cur_msg) {
   1940      1.1  christos 		return 0;
   1941      1.1  christos 	}
   1942      1.1  christos 	/* setup to send the control message */
   1943      1.1  christos 	/* set that the buffer needs to be sent, but the length
   1944      1.1  christos 	 * of that buffer is already written, that way the buffer can
   1945      1.1  christos 	 * start with 0 length and then the length of the control frame
   1946      1.1  christos 	 * in it */
   1947      1.1  christos 	dtio->cur_msg_done = 0;
   1948      1.1  christos 	dtio->cur_msg_len_done = 4;
   1949      1.1  christos 	return 1;
   1950      1.1  christos }
   1951      1.1  christos 
   1952      1.1  christos /** open the output file descriptor for af_local */
   1953      1.1  christos static int dtio_open_output_local(struct dt_io_thread* dtio)
   1954      1.1  christos {
   1955      1.1  christos #ifdef HAVE_SYS_UN_H
   1956      1.1  christos 	struct sockaddr_un s;
   1957      1.1  christos 	dtio->fd = socket(AF_LOCAL, SOCK_STREAM, 0);
   1958      1.1  christos 	if(dtio->fd == -1) {
   1959      1.1  christos 		log_err("dnstap io: failed to create socket: %s",
   1960      1.1  christos 			sock_strerror(errno));
   1961      1.1  christos 		return 0;
   1962      1.1  christos 	}
   1963      1.1  christos 	memset(&s, 0, sizeof(s));
   1964      1.1  christos #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
   1965      1.1  christos         /* this member exists on BSDs, not Linux */
   1966      1.1  christos         s.sun_len = (unsigned)sizeof(s);
   1967      1.1  christos #endif
   1968      1.1  christos 	s.sun_family = AF_LOCAL;
   1969      1.1  christos 	/* length is 92-108, 104 on FreeBSD */
   1970      1.1  christos         (void)strlcpy(s.sun_path, dtio->socket_path, sizeof(s.sun_path));
   1971      1.1  christos 	fd_set_nonblock(dtio->fd);
   1972      1.1  christos 	if(connect(dtio->fd, (struct sockaddr*)&s, (socklen_t)sizeof(s))
   1973      1.1  christos 		== -1) {
   1974      1.1  christos 		char* to = dtio->socket_path;
   1975      1.1  christos 		if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
   1976      1.1  christos 			verbosity < 4) {
   1977      1.1  christos 			dtio_close_fd(dtio);
   1978      1.1  christos 			return 0; /* no log retries on low verbosity */
   1979      1.1  christos 		}
   1980      1.1  christos 		log_err("dnstap io: failed to connect to \"%s\": %s",
   1981      1.1  christos 			to, sock_strerror(errno));
   1982      1.1  christos 		dtio_close_fd(dtio);
   1983      1.1  christos 		return 0;
   1984      1.1  christos 	}
   1985      1.1  christos 	return 1;
   1986      1.1  christos #else
   1987      1.1  christos 	log_err("cannot create af_local socket");
   1988      1.1  christos 	return 0;
   1989      1.1  christos #endif /* HAVE_SYS_UN_H */
   1990      1.1  christos }
   1991      1.1  christos 
   1992      1.1  christos /** open the output file descriptor for af_inet and af_inet6 */
   1993      1.1  christos static int dtio_open_output_tcp(struct dt_io_thread* dtio)
   1994      1.1  christos {
   1995      1.1  christos 	struct sockaddr_storage addr;
   1996      1.1  christos 	socklen_t addrlen;
   1997      1.1  christos 	memset(&addr, 0, sizeof(addr));
   1998      1.1  christos 	addrlen = (socklen_t)sizeof(addr);
   1999      1.1  christos 
   2000  1.1.1.3  christos 	if(!extstrtoaddr(dtio->ip_str, &addr, &addrlen, UNBOUND_DNS_PORT)) {
   2001      1.1  christos 		log_err("could not parse IP '%s'", dtio->ip_str);
   2002      1.1  christos 		return 0;
   2003      1.1  christos 	}
   2004      1.1  christos 	dtio->fd = socket(addr.ss_family, SOCK_STREAM, 0);
   2005      1.1  christos 	if(dtio->fd == -1) {
   2006      1.1  christos 		log_err("can't create socket: %s", sock_strerror(errno));
   2007      1.1  christos 		return 0;
   2008      1.1  christos 	}
   2009      1.1  christos 	fd_set_nonblock(dtio->fd);
   2010      1.1  christos 	if(connect(dtio->fd, (struct sockaddr*)&addr, addrlen) == -1) {
   2011      1.1  christos 		if(errno == EINPROGRESS)
   2012      1.1  christos 			return 1; /* wait until connect done*/
   2013      1.1  christos 		if(dtio->reconnect_timeout > DTIO_RECONNECT_TIMEOUT_MIN &&
   2014      1.1  christos 			verbosity < 4) {
   2015      1.1  christos 			dtio_close_fd(dtio);
   2016      1.1  christos 			return 0; /* no log retries on low verbosity */
   2017      1.1  christos 		}
   2018      1.1  christos #ifndef USE_WINSOCK
   2019      1.1  christos 		if(tcp_connect_errno_needs_log(
   2020      1.1  christos 			(struct sockaddr *)&addr, addrlen)) {
   2021      1.1  christos 			log_err("dnstap io: failed to connect to %s: %s",
   2022      1.1  christos 				dtio->ip_str, strerror(errno));
   2023      1.1  christos 		}
   2024      1.1  christos #else
   2025      1.1  christos 		if(WSAGetLastError() == WSAEINPROGRESS ||
   2026      1.1  christos 			WSAGetLastError() == WSAEWOULDBLOCK)
   2027      1.1  christos 			return 1; /* wait until connect done*/
   2028      1.1  christos 		if(tcp_connect_errno_needs_log(
   2029      1.1  christos 			(struct sockaddr *)&addr, addrlen)) {
   2030      1.1  christos 			log_err("dnstap io: failed to connect to %s: %s",
   2031      1.1  christos 				dtio->ip_str, wsa_strerror(WSAGetLastError()));
   2032      1.1  christos 		}
   2033      1.1  christos #endif
   2034      1.1  christos 		dtio_close_fd(dtio);
   2035      1.1  christos 		return 0;
   2036      1.1  christos 	}
   2037      1.1  christos 	return 1;
   2038      1.1  christos }
   2039      1.1  christos 
   2040      1.1  christos /** setup the SSL structure for new connection */
   2041      1.1  christos static int dtio_setup_ssl(struct dt_io_thread* dtio)
   2042      1.1  christos {
   2043      1.1  christos 	dtio->ssl = outgoing_ssl_fd(dtio->ssl_ctx, dtio->fd);
   2044      1.1  christos 	if(!dtio->ssl) return 0;
   2045      1.1  christos 	dtio->ssl_handshake_done = 0;
   2046      1.1  christos 	dtio->ssl_brief_read = 0;
   2047      1.1  christos 
   2048      1.1  christos 	if(!set_auth_name_on_ssl(dtio->ssl, dtio->tls_server_name,
   2049      1.1  christos 		dtio->tls_use_sni)) {
   2050      1.1  christos 		return 0;
   2051      1.1  christos 	}
   2052      1.1  christos 	return 1;
   2053      1.1  christos }
   2054      1.1  christos 
   2055      1.1  christos /** open the output file descriptor */
   2056      1.1  christos static void dtio_open_output(struct dt_io_thread* dtio)
   2057      1.1  christos {
   2058      1.1  christos 	struct ub_event* ev;
   2059      1.1  christos 	if(dtio->upstream_is_unix) {
   2060      1.1  christos 		if(!dtio_open_output_local(dtio)) {
   2061      1.1  christos 			dtio_reconnect_enable(dtio);
   2062      1.1  christos 			return;
   2063      1.1  christos 		}
   2064      1.1  christos 	} else if(dtio->upstream_is_tcp || dtio->upstream_is_tls) {
   2065      1.1  christos 		if(!dtio_open_output_tcp(dtio)) {
   2066      1.1  christos 			dtio_reconnect_enable(dtio);
   2067      1.1  christos 			return;
   2068      1.1  christos 		}
   2069      1.1  christos 		if(dtio->upstream_is_tls) {
   2070      1.1  christos 			if(!dtio_setup_ssl(dtio)) {
   2071      1.1  christos 				dtio_close_fd(dtio);
   2072      1.1  christos 				dtio_reconnect_enable(dtio);
   2073      1.1  christos 				return;
   2074      1.1  christos 			}
   2075      1.1  christos 		}
   2076      1.1  christos 	}
   2077      1.1  christos 	dtio->check_nb_connect = 1;
   2078      1.1  christos 
   2079      1.1  christos 	/* the EV_READ is to read ACCEPT control messages, and catch channel
   2080      1.1  christos 	 * close. EV_WRITE is to write packets */
   2081      1.1  christos 	ev = ub_event_new(dtio->event_base, dtio->fd,
   2082      1.1  christos 		UB_EV_READ | UB_EV_WRITE | UB_EV_PERSIST, &dtio_output_cb,
   2083      1.1  christos 		dtio);
   2084      1.1  christos 	if(!ev) {
   2085      1.1  christos 		log_err("dnstap io: out of memory");
   2086      1.1  christos 		if(dtio->ssl) {
   2087      1.1  christos #ifdef HAVE_SSL
   2088      1.1  christos 			SSL_free(dtio->ssl);
   2089      1.1  christos 			dtio->ssl = NULL;
   2090      1.1  christos #endif
   2091      1.1  christos 		}
   2092      1.1  christos 		dtio_close_fd(dtio);
   2093      1.1  christos 		dtio_reconnect_enable(dtio);
   2094      1.1  christos 		return;
   2095      1.1  christos 	}
   2096      1.1  christos 	dtio->event = ev;
   2097      1.1  christos 
   2098      1.1  christos 	/* setup protocol control message to start */
   2099      1.1  christos 	if((!dtio->is_bidirectional && !dtio_control_start_send(dtio)) ||
   2100      1.1  christos 		(dtio->is_bidirectional && !dtio_control_ready_send(dtio)) ) {
   2101      1.1  christos 		log_err("dnstap io: out of memory");
   2102      1.1  christos 		ub_event_free(dtio->event);
   2103      1.1  christos 		dtio->event = NULL;
   2104      1.1  christos 		if(dtio->ssl) {
   2105      1.1  christos #ifdef HAVE_SSL
   2106      1.1  christos 			SSL_free(dtio->ssl);
   2107      1.1  christos 			dtio->ssl = NULL;
   2108      1.1  christos #endif
   2109      1.1  christos 		}
   2110      1.1  christos 		dtio_close_fd(dtio);
   2111      1.1  christos 		dtio_reconnect_enable(dtio);
   2112      1.1  christos 		return;
   2113      1.1  christos 	}
   2114      1.1  christos }
   2115      1.1  christos 
   2116      1.1  christos /** perform the setup of the writer thread on the established event_base */
   2117      1.1  christos static void dtio_setup_on_base(struct dt_io_thread* dtio)
   2118      1.1  christos {
   2119      1.1  christos 	dtio_setup_cmd(dtio);
   2120      1.1  christos 	dtio_setup_reconnect(dtio);
   2121      1.1  christos 	dtio_open_output(dtio);
   2122      1.1  christos 	if(!dtio_add_output_event_write(dtio))
   2123      1.1  christos 		return;
   2124      1.1  christos }
   2125      1.1  christos 
   2126      1.1  christos #ifndef THREADS_DISABLED
   2127      1.1  christos /** the IO thread function for the DNSTAP IO */
   2128      1.1  christos static void* dnstap_io(void* arg)
   2129      1.1  christos {
   2130      1.1  christos 	struct dt_io_thread* dtio = (struct dt_io_thread*)arg;
   2131      1.1  christos 	time_t secs = 0;
   2132      1.1  christos 	struct timeval now;
   2133      1.1  christos 	log_thread_set(&dtio->threadnum);
   2134      1.1  christos 
   2135      1.1  christos 	/* setup */
   2136      1.1  christos 	verbose(VERB_ALGO, "start dnstap io thread");
   2137      1.1  christos 	dtio_setup_base(dtio, &secs, &now);
   2138      1.1  christos 	dtio_setup_on_base(dtio);
   2139      1.1  christos 
   2140      1.1  christos 	/* run */
   2141      1.1  christos 	if(ub_event_base_dispatch(dtio->event_base) < 0) {
   2142      1.1  christos 		log_err("dnstap io: dispatch failed, errno is %s",
   2143      1.1  christos 			strerror(errno));
   2144      1.1  christos 	}
   2145      1.1  christos 
   2146      1.1  christos 	/* cleanup */
   2147      1.1  christos 	verbose(VERB_ALGO, "stop dnstap io thread");
   2148      1.1  christos 	dtio_desetup(dtio);
   2149      1.1  christos 	return NULL;
   2150      1.1  christos }
   2151      1.1  christos #endif /* THREADS_DISABLED */
   2152      1.1  christos 
   2153      1.1  christos int dt_io_thread_start(struct dt_io_thread* dtio, void* event_base_nothr,
   2154      1.1  christos 	int numworkers)
   2155      1.1  christos {
   2156      1.1  christos 	/* set up the thread, can fail */
   2157      1.1  christos #ifndef USE_WINSOCK
   2158      1.1  christos 	if(pipe(dtio->commandpipe) == -1) {
   2159      1.1  christos 		log_err("failed to create pipe: %s", strerror(errno));
   2160      1.1  christos 		return 0;
   2161      1.1  christos 	}
   2162      1.1  christos #else
   2163      1.1  christos 	if(_pipe(dtio->commandpipe, 4096, _O_BINARY) == -1) {
   2164      1.1  christos 		log_err("failed to create _pipe: %s",
   2165      1.1  christos 			wsa_strerror(WSAGetLastError()));
   2166      1.1  christos 		return 0;
   2167      1.1  christos 	}
   2168      1.1  christos #endif
   2169      1.1  christos 
   2170      1.1  christos 	/* start the thread */
   2171      1.1  christos 	dtio->threadnum = numworkers+1;
   2172      1.1  christos 	dtio->started = 1;
   2173      1.1  christos #ifndef THREADS_DISABLED
   2174      1.1  christos 	ub_thread_create(&dtio->tid, dnstap_io, dtio);
   2175      1.1  christos 	(void)event_base_nothr;
   2176      1.1  christos #else
   2177      1.1  christos 	dtio->event_base = event_base_nothr;
   2178      1.1  christos 	dtio_setup_on_base(dtio);
   2179      1.1  christos #endif
   2180      1.1  christos 	return 1;
   2181      1.1  christos }
   2182      1.1  christos 
   2183      1.1  christos void dt_io_thread_stop(struct dt_io_thread* dtio)
   2184      1.1  christos {
   2185      1.1  christos #ifndef THREADS_DISABLED
   2186      1.1  christos 	uint8_t cmd = DTIO_COMMAND_STOP;
   2187      1.1  christos #endif
   2188      1.1  christos 	if(!dtio) return;
   2189      1.1  christos 	if(!dtio->started) return;
   2190      1.1  christos 	verbose(VERB_ALGO, "dnstap io: send stop cmd");
   2191      1.1  christos 
   2192      1.1  christos #ifndef THREADS_DISABLED
   2193      1.1  christos 	while(1) {
   2194      1.1  christos 		ssize_t r = write(dtio->commandpipe[1], &cmd, sizeof(cmd));
   2195      1.1  christos 		if(r == -1) {
   2196      1.1  christos #ifndef USE_WINSOCK
   2197      1.1  christos 			if(errno == EINTR || errno == EAGAIN)
   2198      1.1  christos 				continue;
   2199      1.1  christos #else
   2200      1.1  christos 			if(WSAGetLastError() == WSAEINPROGRESS)
   2201      1.1  christos 				continue;
   2202      1.1  christos 			if(WSAGetLastError() == WSAEWOULDBLOCK)
   2203      1.1  christos 				continue;
   2204      1.1  christos #endif
   2205      1.1  christos 			log_err("dnstap io stop: write: %s",
   2206      1.1  christos 				sock_strerror(errno));
   2207      1.1  christos 			break;
   2208      1.1  christos 		}
   2209      1.1  christos 		break;
   2210      1.1  christos 	}
   2211      1.1  christos 	dtio->started = 0;
   2212      1.1  christos #endif /* THREADS_DISABLED */
   2213      1.1  christos 
   2214      1.1  christos #ifndef USE_WINSOCK
   2215      1.1  christos 	close(dtio->commandpipe[1]);
   2216      1.1  christos #else
   2217      1.1  christos 	_close(dtio->commandpipe[1]);
   2218      1.1  christos #endif
   2219      1.1  christos 	dtio->commandpipe[1] = -1;
   2220      1.1  christos #ifndef THREADS_DISABLED
   2221      1.1  christos 	ub_thread_join(dtio->tid);
   2222      1.1  christos #else
   2223      1.1  christos 	dtio->want_to_exit = 1;
   2224      1.1  christos 	dtio_desetup(dtio);
   2225      1.1  christos #endif
   2226      1.1  christos }
   2227