+static void configure_tcp(connection_t *c) {
+ int option;
+
+#ifdef O_NONBLOCK
+ int flags = fcntl(c->socket, F_GETFL);
+
+ if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
+ }
+#elif defined(WIN32)
+ unsigned long arg = 1;
+
+ if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
+ }
+#endif
+
+#if defined(SOL_TCP) && defined(TCP_NODELAY)
+ option = 1;
+ setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
+#endif
+
+#if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
+ option = IPTOS_LOWDELAY;
+ setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
+#endif
+}
+
+static bool bind_to_address(connection_t *c) {
+ int s = -1;
+
+ for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
+ if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
+ continue;
+ if(s >= 0)
+ return false;
+ s = i;
+ }
+
+ if(s < 0)
+ return false;
+
+ sockaddr_t sa = listen_socket[s].sa;
+ if(sa.sa.sa_family == AF_INET)
+ sa.in.sin_port = 0;
+ else if(sa.sa.sa_family == AF_INET6)
+ sa.in6.sin6_port = 0;
+
+ if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
+ logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
+ return false;
+ }
+
+ return true;
+}
+
+int setup_listen_socket(const sockaddr_t *sa) {