+static void handle_meta_io(void *data, int flags) {
+ connection_t *c = data;
+
+ if(c->status.connecting) {
+ /*
+ The event loop does not protect against spurious events. Verify that we are actually connected
+ by issuing an empty send() call.
+
+ Note that the behavior of send() on potentially unconnected sockets differ between platforms:
+ +------------+-----------+-------------+-----------+
+ | Event | POSIX | Linux | Windows |
+ +------------+-----------+-------------+-----------+
+ | Spurious | ENOTCONN | EWOULDBLOCK | ENOTCONN |
+ | Failed | ENOTCONN | (cause) | ENOTCONN |
+ | Successful | (success) | (success) | (success) |
+ +------------+-----------+-------------+-----------+
+ */
+ if(send(c->socket, NULL, 0, 0) != 0) {
+ if(sockwouldblock(sockerrno)) {
+ return;
+ }
+
+ int socket_error;
+
+ if(!socknotconn(sockerrno)) {
+ socket_error = sockerrno;
+ } else {
+ socklen_t len = sizeof(socket_error);
+ getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&socket_error, &len);
+ }
+
+ if(socket_error) {
+ logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(socket_error));
+ terminate_connection(c, false);
+ }
+
+ return;
+ }
+
+ c->status.connecting = false;
+ finish_connecting(c);
+ }
+
+ if(flags & IO_WRITE) {
+ handle_meta_write(c);
+ } else {
+ handle_meta_connection_data(c);
+ }
+}
+
+bool do_outgoing_connection(outgoing_t *outgoing) {
+ const sockaddr_t *sa;
+ struct addrinfo *proxyai = NULL;
+ int result;
+
+begin:
+ sa = get_recent_address(outgoing->node->address_cache);
+
+ if(!sa) {
+ logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->node->name);
+ retry_outgoing(outgoing);
+ return false;
+ }
+
+ connection_t *c = new_connection();
+ c->outgoing = outgoing;
+ memcpy(&c->address, sa, SALEN(sa->sa));
+ c->hostname = sockaddr2hostname(&c->address);
+
+ logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->node->name, c->hostname);
+
+ if(!proxytype) {
+ c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
+ configure_tcp(c);
+ } else if(proxytype == PROXY_EXEC) {
+ do_outgoing_pipe(c, proxyhost);
+ } else {
+ proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
+
+ if(!proxyai) {
+ free_connection(c);
+ goto begin;
+ }
+
+ logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
+ c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
+ configure_tcp(c);
+ }
+
+ if(c->socket == -1) {
+ logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
+ free_connection(c);
+ goto begin;
+ }
+
+#ifdef FD_CLOEXEC
+ fcntl(c->socket, F_SETFD, FD_CLOEXEC);