Exemplo n.º 1
0
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(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(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

#if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
	option = IPTOS_LOWDELAY;
	setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
#endif
}
Exemplo n.º 2
0
Arquivo: meta.c Projeto: Phillyun/tinc
bool flush_meta(connection_t *c) {
	int result;
	
	ifdebug(META) logger(LOG_DEBUG, "Flushing %d bytes to %s (%s)",
			 c->outbuflen, c->name, c->hostname);

	while(c->outbuflen) {
		result = send(c->socket, c->outbuf + c->outbufstart, c->outbuflen, 0);
		if(result <= 0) {
			if(!errno || errno == EPIPE) {
				ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection closed by %s (%s)",
						   c->name, c->hostname);
			} else if(errno == EINTR) {
				continue;
			} else if(sockwouldblock(sockerrno)) {
				ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Flushing %d bytes to %s (%s) would block",
						c->outbuflen, c->name, c->hostname);
				return true;
			} else {
				logger(LOG_ERR, "Flushing meta data to %s (%s) failed: %s", c->name,
					   c->hostname, sockstrerror(sockerrno));
			}

			return false;
		}

		c->outbufstart += result;
		c->outbuflen -= result;
	}

	c->outbufstart = 0; /* avoid unnecessary memmoves */
	return true;
}
Exemplo n.º 3
0
/*
  accept a new tcp connect and create a
  new connection
*/
bool handle_new_meta_connection(int sock) {
	connection_t *c;
	sockaddr_t sa;
	int fd;
	socklen_t len = sizeof(sa);

	fd = accept(sock, &sa.sa, &len);

	if(fd < 0) {
		logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
		return false;
	}

	sockaddrunmap(&sa);

	c = new_connection();
	c->name = xstrdup("<unknown>");
	c->outcipher = myself->connection->outcipher;
	c->outdigest = myself->connection->outdigest;
	c->outmaclength = myself->connection->outmaclength;
	c->outcompression = myself->connection->outcompression;

	c->address = sa;
	c->hostname = sockaddr2hostname(&sa);
	c->socket = fd;
	c->last_ping_time = now;

	ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);

	configure_tcp(c);

	connection_add(c);

	c->allow_request = ID;
	send_id(c);

	return true;
}
Exemplo n.º 4
0
Arquivo: net.c Projeto: 95ulisse/tinc
/*
  this is where it all happens...
*/
int main_loop(void) {
	fd_set readset, writeset;
#ifdef HAVE_PSELECT
	struct timespec tv;
	sigset_t omask, block_mask;
	time_t next_event;
#else
	struct timeval tv;
#endif
	int r, maxfd;
	time_t last_ping_check, last_config_check, last_graph_dump;
	event_t *event;

	last_ping_check = now;
	last_config_check = now;
	last_graph_dump = now;
	
	srand(now);

#ifdef HAVE_PSELECT
	if(lookup_config(config_tree, "GraphDumpFile"))
		graph_dump = true;
	/* Block SIGHUP & SIGALRM */
	sigemptyset(&block_mask);
	sigaddset(&block_mask, SIGHUP);
	sigaddset(&block_mask, SIGALRM);
	sigprocmask(SIG_BLOCK, &block_mask, &omask);
#endif

	running = true;

	while(running) {
#ifdef HAVE_PSELECT
		next_event = last_ping_check + pingtimeout;
		if(graph_dump && next_event > last_graph_dump + 60)
			next_event = last_graph_dump + 60;

		if((event = peek_next_event()) && next_event > event->time)
			next_event = event->time;

		if(next_event <= now)
			tv.tv_sec = 0;
		else
			tv.tv_sec = next_event - now;
		tv.tv_nsec = 0;
#else
		tv.tv_sec = 1;
		tv.tv_usec = 0;
#endif

		maxfd = build_fdset(&readset, &writeset);

#ifdef HAVE_MINGW
		LeaveCriticalSection(&mutex);
#endif
#ifdef HAVE_PSELECT
		r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
#else
		r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
#endif
		now = time(NULL);
#ifdef HAVE_MINGW
		EnterCriticalSection(&mutex);
#endif

		if(r < 0) {
			if(!sockwouldblock(sockerrno)) {
				logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
				dump_connections();
				return 1;
			}
		}

		if(r > 0)
			check_network_activity(&readset, &writeset);

		if(do_purge) {
			purge();
			do_purge = false;
		}

		/* Let's check if everybody is still alive */

		if(last_ping_check + pingtimeout <= now) {
			check_dead_connections();
			last_ping_check = now;

			if(routing_mode == RMODE_SWITCH)
				age_subnets();

			age_past_requests();

			/* Should we regenerate our key? */

			if(keyexpires <= now) {
				avl_node_t *node;
				node_t *n;

				ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");

				for(node = node_tree->head; node; node = node->next) {
					n = node->data;
					if(n->inkey) {
						free(n->inkey);
						n->inkey = NULL;
					}
				}

				send_key_changed();
				keyexpires = now + keylifetime;
			}

			/* Detect ADD_EDGE/DEL_EDGE storms that are caused when
			 * two tinc daemons with the same name are on the VPN.
			 * If so, sleep a while. If this happens multiple times
			 * in a row, sleep longer. */

			if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
				logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
				usleep(sleeptime * 1000000LL);
				sleeptime *= 2;
				if(sleeptime < 0)
					sleeptime = 3600;
			} else {
				sleeptime /= 2;
				if(sleeptime < 10)
					sleeptime = 10;
			}

			contradicting_add_edge = 0;
			contradicting_del_edge = 0;
		}

		if(sigalrm) {
			avl_node_t *node;
			logger(LOG_INFO, "Flushing event queue");
			expire_events();
			for(node = connection_tree->head; node; node = node->next) {
				connection_t *c = node->data;
				if(c->status.active)
					send_ping(c);
			}
			sigalrm = false;
		}

		while((event = get_expired_event())) {
			event->handler(event->data);
			free_event(event);
		}

		if(sighup) {
			connection_t *c;
			avl_node_t *node, *next;
			char *fname;
			struct stat s;
			
			sighup = false;

			reopenlogger();
			
			/* Reread our own configuration file */

			exit_configuration(&config_tree);
			init_configuration(&config_tree);

			if(!read_server_config()) {
				logger(LOG_ERR, "Unable to reread configuration file, exitting.");
				return 1;
			}

			/* Cancel non-active outgoing connections */

			for(node = connection_tree->head; node; node = next) {
				next = node->next;
				c = node->data;

				c->outgoing = NULL;

				if(c->status.connecting) {
					terminate_connection(c, false);
					connection_del(c);
				}
			}

			/* Wipe list of outgoing connections */

			for(list_node_t *node = outgoing_list->head; node; node = node->next) {
				outgoing_t *outgoing = node->data;

				if(outgoing->event)
					event_del(outgoing->event);
			}

			list_delete_list(outgoing_list);

			/* Close connections to hosts that have a changed or deleted host config file */
			
			for(node = connection_tree->head; node; node = node->next) {
				c = node->data;
				
				xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
				if(stat(fname, &s) || s.st_mtime > last_config_check)
					terminate_connection(c, c->status.active);
				free(fname);
			}

			last_config_check = now;

			/* If StrictSubnet is set, expire deleted Subnets and read new ones in */

			if(strictsubnets) {
				subnet_t *subnet;

				for(node = subnet_tree->head; node; node = node->next) {
					subnet = node->data;
					subnet->expires = 1;
				}

				load_all_subnets();

				for(node = subnet_tree->head; node; node = next) {
					next = node->next;
					subnet = node->data;
					if(subnet->expires == 1) {
						send_del_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, false);
						subnet_del(subnet->owner, subnet);
					} else if(subnet->expires == -1) {
						subnet->expires = 0;
					} else {
						send_add_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, true);
					}
				}
			}

			/* Try to make outgoing connections */
			
			try_outgoing_connections();
		}
		
		/* Dump graph if wanted every 60 seconds*/

		if(last_graph_dump + 60 <= now) {
			dump_graph();
			last_graph_dump = now;
		}
	}

#ifdef HAVE_PSELECT
	/* Restore SIGHUP & SIGALARM mask */
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif

	return 0;
}
Exemplo n.º 5
0
Arquivo: net.c Projeto: 95ulisse/tinc
/*
  check all connections to see if anything
  happened on their sockets
*/
static void check_network_activity(fd_set * readset, fd_set * writeset) {
	connection_t *c;
	avl_node_t *node;
	int result, i;
	socklen_t len = sizeof(result);
	vpn_packet_t packet;
	static int errors = 0;

	/* check input from kernel */
	if(device_fd >= 0 && FD_ISSET(device_fd, readset)) {
		if(devops.read(&packet)) {
			if(packet.len) {
				errors = 0;
				packet.priority = 0;
				route(myself, &packet);
			}
		} else {
			usleep(errors * 50000);
			errors++;
			if(errors > 10) {
				logger(LOG_ERR, "Too many errors from %s, exiting!", device);
				running = false;
			}
		}
	}

	/* check meta connections */
	for(node = connection_tree->head; node; node = node->next) {
		c = node->data;

		if(c->status.remove)
			continue;

		if(FD_ISSET(c->socket, writeset)) {
			if(c->status.connecting) {
				c->status.connecting = false;
				getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);

				if(!result)
					finish_connecting(c);
				else {
					ifdebug(CONNECTIONS) logger(LOG_DEBUG,
							   "Error while connecting to %s (%s): %s",
							   c->name, c->hostname, sockstrerror(result));
					closesocket(c->socket);
					do_outgoing_connection(c);
					continue;
				}
			}

			if(!flush_meta(c)) {
				terminate_connection(c, c->status.active);
				continue;
			}
		}

		if(FD_ISSET(c->socket, readset)) {
			if(!receive_meta(c)) {
				terminate_connection(c, c->status.active);
				continue;
			}
		}
	}

	for(i = 0; i < listen_sockets; i++) {
		if(FD_ISSET(listen_socket[i].udp, readset))
			handle_incoming_vpn_data(i);

		if(FD_ISSET(listen_socket[i].tcp, readset))
			handle_new_meta_connection(listen_socket[i].tcp);
	}
}
Exemplo n.º 6
0
Arquivo: meta.c Projeto: Phillyun/tinc
bool receive_meta(connection_t *c) {
	int oldlen, i, result;
	int lenin, lenout, reqlen;
	bool decrypted = false;
	char inbuf[MAXBUFSIZE];

	/* Strategy:
	   - Read as much as possible from the TCP socket in one go.
	   - Decrypt it.
	   - Check if a full request is in the input buffer.
	   - If yes, process request and remove it from the buffer,
	   then check again.
	   - If not, keep stuff in buffer and exit.
	 */

	lenin = recv(c->socket, c->buffer + c->buflen, MAXBUFSIZE - c->buflen, 0);

	if(lenin <= 0) {
		if(!lenin || !errno) {
			ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection closed by %s (%s)",
					   c->name, c->hostname);
		} else if(sockwouldblock(sockerrno))
			return true;
		else
			logger(LOG_ERR, "Metadata socket read error for %s (%s): %s",
				   c->name, c->hostname, sockstrerror(sockerrno));

		return false;
	}

	oldlen = c->buflen;
	c->buflen += lenin;

	while(lenin > 0) {
		/* Decrypt */

		if(c->status.decryptin && !decrypted) {
			result = EVP_DecryptUpdate(c->inctx, (unsigned char *)inbuf, &lenout, (unsigned char *)c->buffer + oldlen, lenin);
			if(!result || lenout != lenin) {
				logger(LOG_ERR, "Error while decrypting metadata from %s (%s): %s",
						c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
				return false;
			}
			memcpy(c->buffer + oldlen, inbuf, lenin);
			decrypted = true;
		}

		/* Are we receiving a TCPpacket? */

		if(c->tcplen) {
			if(c->tcplen <= c->buflen) {
				if(!c->node) {
					if(c->outgoing && proxytype == PROXY_SOCKS4 && c->allow_request == ID) {
						if(c->buffer[0] == 0 && c->buffer[1] == 0x5a) {
							ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Proxy request granted");
						} else {
							logger(LOG_ERR, "Proxy request rejected");
							return false;
						}
					} else if(c->outgoing && proxytype == PROXY_SOCKS5 && c->allow_request == ID) {
						if(c->buffer[0] != 5) {
							logger(LOG_ERR, "Invalid response from proxy server");
							return false;
						}
						if(c->buffer[1] == (char)0xff) {
							logger(LOG_ERR, "Proxy request rejected: unsuitable authentication method");
							return false;
						}
						if(c->buffer[2] != 5) {
							logger(LOG_ERR, "Invalid response from proxy server");
							return false;
						}
						if(c->buffer[3] == 0) {
							ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Proxy request granted");
						} else {
							logger(LOG_ERR, "Proxy request rejected");
							return false;
						}
					} else {
						logger(LOG_ERR, "c->tcplen set but c->node is NULL!");
						abort();
					}
				} else {
					if(c->allow_request == ALL) {
						receive_tcppacket(c, c->buffer, c->tcplen);
					} else {
						logger(LOG_ERR, "Got unauthorized TCP packet from %s (%s)", c->name, c->hostname);
						return false;
					}
				}

				c->buflen -= c->tcplen;
				lenin -= c->tcplen - oldlen;
				memmove(c->buffer, c->buffer + c->tcplen, c->buflen);
				oldlen = 0;
				c->tcplen = 0;
				continue;
			} else {
				break;
			}
		}

		/* Otherwise we are waiting for a request */

		reqlen = 0;

		for(i = oldlen; i < c->buflen; i++) {
			if(c->buffer[i] == '\n') {
				c->buffer[i] = '\0';	/* replace end-of-line by end-of-string so we can use sscanf */
				reqlen = i + 1;
				break;
			}
		}

		if(reqlen) {
			c->reqlen = reqlen;
			if(!receive_request(c))
				return false;

			c->buflen -= reqlen;
			lenin -= reqlen - oldlen;
			memmove(c->buffer, c->buffer + reqlen, c->buflen);
			oldlen = 0;
			continue;
		} else {
			break;
		}
	}

	if(c->buflen >= MAXBUFSIZE) {
		logger(LOG_ERR, "Metadata read buffer overflow for %s (%s)",
			   c->name, c->hostname);
		return false;
	}

	return true;
}
Exemplo n.º 7
0
int setup_vpn_in_socket(const sockaddr_t *sa) {
	int nfd;
	char *addrstr;
	int option;

	nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);

	if(nfd < 0) {
		logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
		return -1;
	}

#ifdef FD_CLOEXEC
	fcntl(nfd, F_SETFD, FD_CLOEXEC);
#endif

#ifdef O_NONBLOCK
	{
		int flags = fcntl(nfd, F_GETFL);

		if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
			closesocket(nfd);
			logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
				   strerror(errno));
			return -1;
		}
	}
#elif defined(WIN32)
	{
		unsigned long arg = 1;
		if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
			closesocket(nfd);
			logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
			return -1;
		}
	}
#endif

	option = 1;
	setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
	setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));

	if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
		logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));

	if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
		logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));

#if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
	if(sa->sa.sa_family == AF_INET6)
		setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
#endif

#if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
#define IP_DONTFRAGMENT IP_DONTFRAG
#endif

#if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
	if(myself->options & OPTION_PMTU_DISCOVERY) {
		option = IP_PMTUDISC_DO;
		setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
	}
#elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
	if(myself->options & OPTION_PMTU_DISCOVERY) {
		option = 1;
		setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
	}
#endif

#if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
	if(myself->options & OPTION_PMTU_DISCOVERY) {
		option = IPV6_PMTUDISC_DO;
		setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
	}
#elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
	if(myself->options & OPTION_PMTU_DISCOVERY) {
		option = 1;
		setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
	}
#endif

	if (!bind_to_interface(nfd)) {
		closesocket(nfd);
		return -1;
	}

	if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
		closesocket(nfd);
		addrstr = sockaddr2hostname(sa);
		logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
		free(addrstr);
		return -1;
	}

	return nfd;
} /* int setup_vpn_in_socket */
Exemplo n.º 8
0
void do_outgoing_connection(connection_t *c) {
	char *address, *port, *space;
	struct addrinfo *proxyai = NULL;
	int result;

	if(!c->outgoing) {
		logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
		abort();
	}

begin:
	if(!c->outgoing->ai) {
		if(!c->outgoing->cfg) {
			ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
					   c->name);
			c->status.remove = true;
			retry_outgoing(c->outgoing);
			c->outgoing = NULL;
			return;
		}

		get_config_string(c->outgoing->cfg, &address);

		space = strchr(address, ' ');
		if(space) {
			port = xstrdup(space + 1);
			*space = 0;
		} else {
			if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
				port = xstrdup("655");
		}

		c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
		free(address);
		free(port);

		c->outgoing->aip = c->outgoing->ai;
		c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
	}

	if(!c->outgoing->aip) {
		if(c->outgoing->ai)
			freeaddrinfo(c->outgoing->ai);
		c->outgoing->ai = NULL;
		goto begin;
	}

	memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
	c->outgoing->aip = c->outgoing->aip->ai_next;

	if(c->hostname)
		free(c->hostname);

	c->hostname = sockaddr2hostname(&c->address);

	ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
			   c->hostname);

	if(!proxytype) {
		c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
	} else if(proxytype == PROXY_EXEC) {
		do_outgoing_pipe(c, proxyhost);
	} else {
		proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
		if(!proxyai)
			goto begin;
		ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
		c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
	}

	if(c->socket == -1) {
		ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
		goto begin;
	}

	if(proxytype != PROXY_EXEC)
		configure_tcp(c);

#ifdef FD_CLOEXEC
	fcntl(c->socket, F_SETFD, FD_CLOEXEC);
#endif

	if(proxytype != PROXY_EXEC) {
#if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
		int option = 1;
		if(c->address.sa.sa_family == AF_INET6)
			setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
#endif

		bind_to_interface(c->socket);
	}

	/* Connect */

	if(!proxytype) {
		result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
	} else if(proxytype == PROXY_EXEC) {
		result = 0;
	} else {
		result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
		freeaddrinfo(proxyai);
	}

	if(result == -1) {
		if(sockinprogress(sockerrno)) {
			c->status.connecting = true;
			return;
		}

		closesocket(c->socket);

		ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));

		goto begin;
	}

	finish_connecting(c);

	return;
}
Exemplo n.º 9
0
int setup_listen_socket(const sockaddr_t *sa) {
	int nfd;
	char *addrstr;
	int option;
	char *iface;

	nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);

	if(nfd < 0) {
		ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
		return -1;
	}

#ifdef FD_CLOEXEC
	fcntl(nfd, F_SETFD, FD_CLOEXEC);
#endif

	/* Optimize TCP settings */

	option = 1;
	setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));

#if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
	if(sa->sa.sa_family == AF_INET6)
		setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
#endif

	if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
#if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
		struct ifreq ifr;

		memset(&ifr, 0, sizeof(ifr));
		strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
		ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
		free(iface);

		if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
			closesocket(nfd);
			logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
			return -1;
		}

#else
		logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
#endif
	}

	if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
		closesocket(nfd);
		addrstr = sockaddr2hostname(sa);
		logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
		free(addrstr);
		return -1;
	}

	if(listen(nfd, 3)) {
		closesocket(nfd);
		logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
		return -1;
	}

	return nfd;
}
Exemplo n.º 10
0
Arquivo: meta.c Projeto: Rumko/tinc
bool receive_meta(connection_t *c) {
	int oldlen, i, result;
	int lenin, lenout, reqlen;
	bool decrypted = false;
	char inbuf[MAXBUFSIZE];

	/* Strategy:
	   - Read as much as possible from the TCP socket in one go.
	   - Decrypt it.
	   - Check if a full request is in the input buffer.
	   - If yes, process request and remove it from the buffer,
	   then check again.
	   - If not, keep stuff in buffer and exit.
	 */

	lenin = recv(c->socket, c->buffer + c->buflen, MAXBUFSIZE - c->buflen, 0);

	if(lenin <= 0) {
		if(!lenin || !errno) {
			ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection closed by %s (%s)",
					   c->name, c->hostname);
		} else if(sockwouldblock(sockerrno))
			return true;
		else
			logger(LOG_ERR, "Metadata socket read error for %s (%s): %s",
				   c->name, c->hostname, sockstrerror(sockerrno));

		return false;
	}

	oldlen = c->buflen;
	c->buflen += lenin;

	while(lenin > 0) {
		/* Decrypt */

		if(c->status.decryptin && !decrypted) {
			result = EVP_DecryptUpdate(c->inctx, (unsigned char *)inbuf, &lenout, (unsigned char *)c->buffer + oldlen, lenin);
			if(!result || lenout != lenin) {
				logger(LOG_ERR, "Error while decrypting metadata from %s (%s): %s",
						c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL));
				return false;
			}
			memcpy(c->buffer + oldlen, inbuf, lenin);
			decrypted = true;
		}

		/* Are we receiving a TCPpacket? */

		if(c->tcplen) {
			if(c->tcplen <= c->buflen) {
				receive_tcppacket(c, c->buffer, c->tcplen);

				c->buflen -= c->tcplen;
				lenin -= c->tcplen - oldlen;
				memmove(c->buffer, c->buffer + c->tcplen, c->buflen);
				oldlen = 0;
				c->tcplen = 0;
				continue;
			} else {
				break;
			}
		}

		/* Otherwise we are waiting for a request */

		reqlen = 0;

		for(i = oldlen; i < c->buflen; i++) {
			if(c->buffer[i] == '\n') {
				c->buffer[i] = '\0';	/* replace end-of-line by end-of-string so we can use sscanf */
				reqlen = i + 1;
				break;
			}
		}

		if(reqlen) {
			c->reqlen = reqlen;
			if(!receive_request(c))
				return false;

			c->buflen -= reqlen;
			lenin -= reqlen - oldlen;
			memmove(c->buffer, c->buffer + reqlen, c->buflen);
			oldlen = 0;
			continue;
		} else {
			break;
		}
	}

	if(c->buflen >= MAXBUFSIZE) {
		logger(LOG_ERR, "Metadata read buffer overflow for %s (%s)",
			   c->name, c->hostname);
		return false;
	}

	return true;
}
Exemplo n.º 11
0
/*
  Configure node_t myself and set up the local sockets (listen only)
*/
static bool setup_myself(void) {
    config_t *cfg;
    subnet_t *subnet;
    char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
    char *fname = NULL;
    char *address = NULL;
    char *proxy = NULL;
    char *space;
    char *envp[5] = {NULL};
    struct addrinfo *ai, *aip, hint = {0};
    bool choice;
    int i, err;
    int replaywin_int;
    bool port_specified = false;

    myself = new_node();
    myself->connection = new_connection();

    myself->hostname = xstrdup("MYSELF");
    myself->connection->hostname = xstrdup("MYSELF");

    myself->connection->options = 0;
    myself->connection->protocol_version = PROT_CURRENT;

    if(!(name = get_name())) {
        logger(LOG_ERR, "Name for tinc daemon required!");
        return false;
    }

    /* Read tinc.conf and our own host config file */

    myself->name = name;
    myself->connection->name = xstrdup(name);
    xasprintf(&fname, "%s/hosts/%s", confbase, name);
    read_config_options(config_tree, name);
    read_config_file(config_tree, fname);
    free(fname);

    if(!read_rsa_private_key())
        return false;

    if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
        myport = xstrdup("655");
    else
        port_specified = true;

    /* Ensure myport is numeric */

    if(!atoi(myport)) {
        struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
        sockaddr_t sa;
        if(!ai || !ai->ai_addr)
            return false;
        free(myport);
        memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
        sockaddr2str(&sa, NULL, &myport);
    }

    get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
    if(proxy) {
        if((space = strchr(proxy, ' ')))
            *space++ = 0;

        if(!strcasecmp(proxy, "none")) {
            proxytype = PROXY_NONE;
        } else if(!strcasecmp(proxy, "socks4")) {
            proxytype = PROXY_SOCKS4;
        } else if(!strcasecmp(proxy, "socks4a")) {
            proxytype = PROXY_SOCKS4A;
        } else if(!strcasecmp(proxy, "socks5")) {
            proxytype = PROXY_SOCKS5;
        } else if(!strcasecmp(proxy, "http")) {
            proxytype = PROXY_HTTP;
        } else if(!strcasecmp(proxy, "exec")) {
            proxytype = PROXY_EXEC;
        } else {
            logger(LOG_ERR, "Unknown proxy type %s!", proxy);
            return false;
        }

        switch(proxytype) {
        case PROXY_NONE:
        default:
            break;

        case PROXY_EXEC:
            if(!space || !*space) {
                logger(LOG_ERR, "Argument expected for proxy type exec!");
                return false;
            }
            proxyhost =  xstrdup(space);
            break;

        case PROXY_SOCKS4:
        case PROXY_SOCKS4A:
        case PROXY_SOCKS5:
        case PROXY_HTTP:
            proxyhost = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxyport = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxyuser = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxypass = space;
            if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
                logger(LOG_ERR, "Host and port argument expected for proxy!");
                return false;
            }
            proxyhost = xstrdup(proxyhost);
            proxyport = xstrdup(proxyport);
            if(proxyuser && *proxyuser)
                proxyuser = xstrdup(proxyuser);
            if(proxypass && *proxypass)
                proxypass = xstrdup(proxypass);
            break;
        }

        free(proxy);
    }

    /* Read in all the subnets specified in the host configuration file */

    cfg = lookup_config(config_tree, "Subnet");

    while(cfg) {
        if(!get_config_subnet(cfg, &subnet))
            return false;

        subnet_add(myself, subnet);

        cfg = lookup_config_next(config_tree, cfg);
    }

    /* Check some options */

    if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
        myself->options |= OPTION_INDIRECT;

    if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
        myself->options |= OPTION_TCPONLY;

    if(myself->options & OPTION_TCPONLY)
        myself->options |= OPTION_INDIRECT;

    get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
    get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
    get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
    get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
    strictsubnets |= tunnelserver;

    if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
        if(!strcasecmp(mode, "router"))
            routing_mode = RMODE_ROUTER;
        else if(!strcasecmp(mode, "switch"))
            routing_mode = RMODE_SWITCH;
        else if(!strcasecmp(mode, "hub"))
            routing_mode = RMODE_HUB;
        else {
            logger(LOG_ERR, "Invalid routing mode!");
            return false;
        }
        free(mode);
    }

    if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
        if(!strcasecmp(mode, "off"))
            forwarding_mode = FMODE_OFF;
        else if(!strcasecmp(mode, "internal"))
            forwarding_mode = FMODE_INTERNAL;
        else if(!strcasecmp(mode, "kernel"))
            forwarding_mode = FMODE_KERNEL;
        else {
            logger(LOG_ERR, "Invalid forwarding mode!");
            return false;
        }
        free(mode);
    }

    choice = true;
    get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
    if(choice)
        myself->options |= OPTION_PMTU_DISCOVERY;

    choice = true;
    get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
    if(choice)
        myself->options |= OPTION_CLAMP_MSS;

    get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
    get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
    if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
        if(!strcasecmp(mode, "no"))
            broadcast_mode = BMODE_NONE;
        else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
            broadcast_mode = BMODE_MST;
        else if(!strcasecmp(mode, "direct"))
            broadcast_mode = BMODE_DIRECT;
        else {
            logger(LOG_ERR, "Invalid broadcast mode!");
            return false;
        }
        free(mode);
    }

#if !defined(SOL_IP) || !defined(IP_TOS)
    if(priorityinheritance)
        logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
#endif

    if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
        macexpire = 600;

    if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
        if(maxtimeout <= 0) {
            logger(LOG_ERR, "Bogus maximum timeout!");
            return false;
        }
    } else
        maxtimeout = 900;

    if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
        if(udp_rcvbuf <= 0) {
            logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
            return false;
        }
    }

    if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
        if(udp_sndbuf <= 0) {
            logger(LOG_ERR, "UDPSndBuf cannot be negative!");
            return false;
        }
    }

    if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
        if(replaywin_int < 0) {
            logger(LOG_ERR, "ReplayWindow cannot be negative!");
            return false;
        }
        replaywin = (unsigned)replaywin_int;
    }

    if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
        if(!strcasecmp(afname, "IPv4"))
            addressfamily = AF_INET;
        else if(!strcasecmp(afname, "IPv6"))
            addressfamily = AF_INET6;
        else if(!strcasecmp(afname, "any"))
            addressfamily = AF_UNSPEC;
        else {
            logger(LOG_ERR, "Invalid address family!");
            return false;
        }
        free(afname);
    }

    get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);

    /* Generate packet encryption key */

    if(get_config_string
            (lookup_config(config_tree, "Cipher"), &cipher)) {
        if(!strcasecmp(cipher, "none")) {
            myself->incipher = NULL;
        } else {
            myself->incipher = EVP_get_cipherbyname(cipher);

            if(!myself->incipher) {
                logger(LOG_ERR, "Unrecognized cipher type!");
                return false;
            }
        }
    } else
        myself->incipher = EVP_bf_cbc();

    if(myself->incipher)
        myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
    else
        myself->inkeylength = 1;

    myself->connection->outcipher = EVP_bf_ofb();

    if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
        keylifetime = 3600;

    keyexpires = now + keylifetime;

    /* Check if we want to use message authentication codes... */

    if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
        if(!strcasecmp(digest, "none")) {
            myself->indigest = NULL;
        } else {
            myself->indigest = EVP_get_digestbyname(digest);

            if(!myself->indigest) {
                logger(LOG_ERR, "Unrecognized digest type!");
                return false;
            }
        }
    } else
        myself->indigest = EVP_sha1();

    myself->connection->outdigest = EVP_sha1();

    if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
        if(myself->indigest) {
            if(myself->inmaclength > myself->indigest->md_size) {
                logger(LOG_ERR, "MAC length exceeds size of digest!");
                return false;
            } else if(myself->inmaclength < 0) {
                logger(LOG_ERR, "Bogus MAC length!");
                return false;
            }
        }
    } else
        myself->inmaclength = 4;

    myself->connection->outmaclength = 0;

    /* Compression */

    if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
        if(myself->incompression < 0 || myself->incompression > 11) {
            logger(LOG_ERR, "Bogus compression level!");
            return false;
        }
    } else
        myself->incompression = 0;

    myself->connection->outcompression = 0;

    /* Done */

    myself->nexthop = myself;
    myself->via = myself;
    myself->status.reachable = true;
    node_add(myself);

    graph();

    if(strictsubnets)
        load_all_subnets();

    /* Open device */

    devops = os_devops;

    if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
        if(!strcasecmp(type, "dummy"))
            devops = dummy_devops;
        else if(!strcasecmp(type, "raw_socket"))
            devops = raw_socket_devops;
        else if(!strcasecmp(type, "multicast"))
            devops = multicast_devops;
#ifdef ENABLE_UML
        else if(!strcasecmp(type, "uml"))
            devops = uml_devops;
#endif
#ifdef ENABLE_VDE
        else if(!strcasecmp(type, "vde"))
            devops = vde_devops;
#endif
    }

    if(!devops.setup())
        return false;

    /* Run tinc-up script to further initialize the tap interface */
    xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
    xasprintf(&envp[1], "DEVICE=%s", device ? : "");
    xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
    xasprintf(&envp[3], "NAME=%s", myself->name);

    execute_script("tinc-up", envp);

    for(i = 0; i < 4; i++)
        free(envp[i]);

    /* Run subnet-up scripts for our own subnets */

    subnet_update(myself, NULL, true);

    /* Open sockets */

    if(!do_detach && getenv("LISTEN_FDS")) {
        sockaddr_t sa;
        socklen_t salen;

        listen_sockets = atoi(getenv("LISTEN_FDS"));
#ifdef HAVE_UNSETENV
        unsetenv("LISTEN_FDS");
#endif

        if(listen_sockets > MAXSOCKETS) {
            logger(LOG_ERR, "Too many listening sockets");
            return false;
        }

        for(i = 0; i < listen_sockets; i++) {
            salen = sizeof sa;
            if(getsockname(i + 3, &sa.sa, &salen) < 0) {
                logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
                return false;
            }

            listen_socket[i].tcp = i + 3;

#ifdef FD_CLOEXEC
            fcntl(i + 3, F_SETFD, FD_CLOEXEC);
#endif

            listen_socket[i].udp = setup_vpn_in_socket(&sa);
            if(listen_socket[i].udp < 0)
                return false;

            ifdebug(CONNECTIONS) {
                hostname = sockaddr2hostname(&sa);
                logger(LOG_NOTICE, "Listening on %s", hostname);
                free(hostname);
            }

            memcpy(&listen_socket[i].sa, &sa, salen);
        }
    } else {
Exemplo n.º 12
0
int main(int argc, char *argv[]) {
	program_name = argv[0];
	bool initiator = false;
	bool datagram = false;
#ifdef HAVE_LINUX
	bool tun = false;
#endif
	int packetloss = 0;
	int r;
	int option_index = 0;
	ecdsa_t *mykey = NULL, *hiskey = NULL;
	bool quit = false;

	while((r = getopt_long(argc, argv, "dqrtwL:W:v", long_options, &option_index)) != EOF) {
		switch (r) {
			case 0:   /* long option */
				break;

			case 'd': /* datagram mode */
				datagram = true;
				break;

			case 'q': /* close connection on EOF from stdin */
				quit = true;
				break;

			case 'r': /* read only */
				readonly = true;
				break;

			case 't': /* read only */
#ifdef HAVE_LINUX
				tun = true;
#else
				fprintf(stderr, "--tun is only supported on Linux.\n");
				usage();
				return 1;
#endif
				break;

			case 'w': /* write only */
				writeonly = true;
				break;

			case 'L': /* packet loss rate */
				packetloss = atoi(optarg);
				break;

			case 'W': /* replay window size */
				sptps_replaywin = atoi(optarg);
				break;

			case 'v': /* be verbose */
				verbose = true;
				break;

			case '?': /* wrong options */
				usage();
				return 1;

			case 1: /* help */
				usage();
				return 0;

			default:
				break;
		}
	}

	argc -= optind - 1;
	argv += optind - 1;

	if(argc < 4 || argc > 5) {
		fprintf(stderr, "Wrong number of arguments.\n");
		usage();
		return 1;
	}

	if(argc > 4)
		initiator = true;

	srand(time(NULL));

#ifdef HAVE_LINUX
	if(tun) {
		in = out = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
		if(in < 0) {
			fprintf(stderr, "Could not open tun device: %s\n", strerror(errno));
			return 1;
		}
		struct ifreq ifr = {
			.ifr_flags = IFF_TUN
		};
		if(ioctl(in, TUNSETIFF, &ifr)) {
			fprintf(stderr, "Could not configure tun interface: %s\n", strerror(errno));
			return 1;
		}
		ifr.ifr_name[IFNAMSIZ - 1] = 0;
		fprintf(stderr, "Using tun interface %s\n", ifr.ifr_name);
	}
#endif

#ifdef HAVE_MINGW
	static struct WSAData wsa_state;
	if(WSAStartup(MAKEWORD(2, 2), &wsa_state))
		return 1;
#endif

	struct addrinfo *ai, hint;
	memset(&hint, 0, sizeof hint);

	hint.ai_family = AF_UNSPEC;
	hint.ai_socktype = datagram ? SOCK_DGRAM : SOCK_STREAM;
	hint.ai_protocol = datagram ? IPPROTO_UDP : IPPROTO_TCP;
	hint.ai_flags = initiator ? 0 : AI_PASSIVE;

	if(getaddrinfo(initiator ? argv[3] : NULL, initiator ? argv[4] : argv[3], &hint, &ai) || !ai) {
		fprintf(stderr, "getaddrinfo() failed: %s\n", sockstrerror(sockerrno));
		return 1;
	}

	int sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if(sock < 0) {
		fprintf(stderr, "Could not create socket: %s\n", sockstrerror(sockerrno));
		return 1;
	}

	int one = 1;
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof one);

	if(initiator) {
		if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
			fprintf(stderr, "Could not connect to peer: %s\n", sockstrerror(sockerrno));
			return 1;
		}
		fprintf(stderr, "Connected\n");
	} else {
		if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
			fprintf(stderr, "Could not bind socket: %s\n", sockstrerror(sockerrno));
			return 1;
		}

		if(!datagram) {
			if(listen(sock, 1)) {
				fprintf(stderr, "Could not listen on socket: %s\n", sockstrerror(sockerrno));
				return 1;
			}
			fprintf(stderr, "Listening...\n");

			sock = accept(sock, NULL, NULL);
			if(sock < 0) {
				fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
				return 1;
			}
		} else {
			fprintf(stderr, "Listening...\n");

			char buf[65536];
			struct sockaddr addr;
			socklen_t addrlen = sizeof addr;

			if(recvfrom(sock, buf, sizeof buf, MSG_PEEK, &addr, &addrlen) <= 0) {
				fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
				return 1;
			}

			if(connect(sock, &addr, addrlen)) {
				fprintf(stderr, "Could not accept connection: %s\n", sockstrerror(sockerrno));
				return 1;
			}
		}

		fprintf(stderr, "Connected\n");
	}

	crypto_init();

	FILE *fp = fopen(argv[1], "r");
	if(!fp) {
		fprintf(stderr, "Could not open %s: %s\n", argv[1], strerror(errno));
		return 1;
	}
	if(!(mykey = ecdsa_read_pem_private_key(fp)))
		return 1;
	fclose(fp);

	fp = fopen(argv[2], "r");
	if(!fp) {
		fprintf(stderr, "Could not open %s: %s\n", argv[2], strerror(errno));
		return 1;
	}
	if(!(hiskey = ecdsa_read_pem_public_key(fp)))
		return 1;
	fclose(fp);

	if(verbose)
		fprintf(stderr, "Keys loaded\n");

	sptps_t s;
	if(!sptps_start(&s, &sock, initiator, datagram, mykey, hiskey, "sptps_test", 10, send_data, receive_record))
		return 1;

	while(true) {
		if(writeonly && readonly)
			break;

		char buf[65535] = "";

		fd_set fds;
		FD_ZERO(&fds);
#ifndef HAVE_MINGW
		if(!readonly && s.instate)
			FD_SET(in, &fds);
#endif
		FD_SET(sock, &fds);
		if(select(sock + 1, &fds, NULL, NULL, NULL) <= 0)
			return 1;

		if(FD_ISSET(in, &fds)) {
			ssize_t len = read(in, buf, sizeof buf);
			if(len < 0) {
				fprintf(stderr, "Could not read from stdin: %s\n", strerror(errno));
				return 1;
			}
			if(len == 0) {
				if(quit)
					break;
				readonly = true;
				continue;
			}
			if(buf[0] == '#')
				s.outseqno = atoi(buf + 1);
			if(buf[0] == '^')
				sptps_send_record(&s, SPTPS_HANDSHAKE, NULL, 0);
			else if(buf[0] == '$') {
				sptps_force_kex(&s);
				if(len > 1)
					sptps_send_record(&s, 0, buf, len);
			} else
			if(!sptps_send_record(&s, buf[0] == '!' ? 1 : 0, buf, (len == 1 && buf[0] == '\n') ? 0 : buf[0] == '*' ? sizeof buf : len))
				return 1;
		}

		if(FD_ISSET(sock, &fds)) {
			ssize_t len = recv(sock, buf, sizeof buf, 0);
			if(len < 0) {
				fprintf(stderr, "Could not read from socket: %s\n", sockstrerror(sockerrno));
				return 1;
			}
			if(len == 0) {
				fprintf(stderr, "Connection terminated by peer.\n");
				break;
			}
			if(verbose) {
				char hex[len * 2 + 1];
				bin2hex(buf, hex, len);
				fprintf(stderr, "Received %d bytes of data:\n%s\n", (int)len, hex);
			}
			if(packetloss && (rand() % 100) < packetloss) {
				if(verbose)
					fprintf(stderr, "Dropped.\n");
				continue;
			}
			char *bufp = buf;
			while(len) {
				size_t done = sptps_receive_data(&s, bufp, len);
				if(!done) {
					if(!datagram)
						return 1;
				} else {
					break;
				}

				bufp += done;
				len -= done;
			}
		}
	}

	if(!sptps_stop(&s))
		return 1;

	return 0;
}
Exemplo n.º 13
0
int main(int argc, char *argv[]) {
	ecdsa_t *key1, *key2;
	ecdh_t *ecdh1, *ecdh2;
	sptps_t sptps1, sptps2;
	char buf1[4096], buf2[4096], buf3[4096];
	double duration = argc > 1 ? atof(argv[1]) : 10;

	crypto_init();

	randomize(buf1, sizeof buf1);
	randomize(buf2, sizeof buf2);
	randomize(buf3, sizeof buf3);

	// Key generation

	fprintf(stderr, "Generating keys for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);)
		ecdsa_free(ecdsa_generate());
	fprintf(stderr, "%17.2lf op/s\n", rate);

	key1 = ecdsa_generate();
	key2 = ecdsa_generate();

	// Ed25519 signatures

	fprintf(stderr, "Ed25519 sign for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);)
		if(!ecdsa_sign(key1, buf1, 256, buf2))
			return 1;
	fprintf(stderr, "%20.2lf op/s\n", rate);

	fprintf(stderr, "Ed25519 verify for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);)
		if(!ecdsa_verify(key1, buf1, 256, buf2)) {
			fprintf(stderr, "Signature verification failed\n");
			return 1;
		}
	fprintf(stderr, "%18.2lf op/s\n", rate);

	ecdh1 = ecdh_generate_public(buf1);
	fprintf(stderr, "ECDH for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);) {
		ecdh2 = ecdh_generate_public(buf2);
		if(!ecdh2)
			return 1;
		if(!ecdh_compute_shared(ecdh2, buf1, buf3))
			return 1;
	}
	fprintf(stderr, "%28.2lf op/s\n", rate);
	ecdh_free(ecdh1);

	// SPTPS authentication phase

	int fd[2];
	if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
		fprintf(stderr, "Could not create a UNIX socket pair: %s\n", sockstrerror(sockerrno));
		return 1;
	}

	struct pollfd pfd[2] = {{fd[0], POLLIN}, {fd[1], POLLIN}};

	fprintf(stderr, "SPTPS/TCP authenticate for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);) {
		sptps_start(&sptps1, fd + 0, true, false, key1, key2, "sptps_speed", 11, send_data, receive_record);
		sptps_start(&sptps2, fd + 1, false, false, key2, key1, "sptps_speed", 11, send_data, receive_record);
		while(poll(pfd, 2, 0)) {
			if(pfd[0].revents)
				receive_data(&sptps1);
			if(pfd[1].revents)
				receive_data(&sptps2);
		}
		sptps_stop(&sptps1);
		sptps_stop(&sptps2);
	}
	fprintf(stderr, "%10.2lf op/s\n", rate * 2);

	// SPTPS data

	sptps_start(&sptps1, fd + 0, true, false, key1, key2, "sptps_speed", 11, send_data, receive_record);
	sptps_start(&sptps2, fd + 1, false, false, key2, key1, "sptps_speed", 11, send_data, receive_record);
	while(poll(pfd, 2, 0)) {
		if(pfd[0].revents)
			receive_data(&sptps1);
		if(pfd[1].revents)
			receive_data(&sptps2);
	}
	fprintf(stderr, "SPTPS/TCP transmit for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);) {
		if(!sptps_send_record(&sptps1, 0, buf1, 1451))
			abort();
		receive_data(&sptps2);
	}
	rate *= 2 * 1451 * 8;
	if(rate > 1e9)
		fprintf(stderr, "%14.2lf Gbit/s\n", rate / 1e9);
	else if(rate > 1e6)
		fprintf(stderr, "%14.2lf Mbit/s\n", rate / 1e6);
	else if(rate > 1e3)
		fprintf(stderr, "%14.2lf kbit/s\n", rate / 1e3);
	sptps_stop(&sptps1);
	sptps_stop(&sptps2);

	// SPTPS datagram authentication phase

	close(fd[0]);
	close(fd[1]);

	if(socketpair(AF_UNIX, SOCK_DGRAM, 0, fd)) {
		fprintf(stderr, "Could not create a UNIX socket pair: %s\n", sockstrerror(sockerrno));
		return 1;
	}

	fprintf(stderr, "SPTPS/UDP authenticate for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);) {
		sptps_start(&sptps1, fd + 0, true, true, key1, key2, "sptps_speed", 11, send_data, receive_record);
		sptps_start(&sptps2, fd + 1, false, true, key2, key1, "sptps_speed", 11, send_data, receive_record);
		while(poll(pfd, 2, 0)) {
			if(pfd[0].revents)
				receive_data(&sptps1);
			if(pfd[1].revents)
				receive_data(&sptps2);
		}
		sptps_stop(&sptps1);
		sptps_stop(&sptps2);
	}
	fprintf(stderr, "%10.2lf op/s\n", rate * 2);

	// SPTPS datagram data

	sptps_start(&sptps1, fd + 0, true, true, key1, key2, "sptps_speed", 11, send_data, receive_record);
	sptps_start(&sptps2, fd + 1, false, true, key2, key1, "sptps_speed", 11, send_data, receive_record);
	while(poll(pfd, 2, 0)) {
		if(pfd[0].revents)
			receive_data(&sptps1);
		if(pfd[1].revents)
			receive_data(&sptps2);
	}
	fprintf(stderr, "SPTPS/UDP transmit for %lg seconds: ", duration);
	for(clock_start(); clock_countto(duration);) {
		if(!sptps_send_record(&sptps1, 0, buf1, 1451))
			abort();
		receive_data(&sptps2);
	}
	rate *= 2 * 1451 * 8;
	if(rate > 1e9)
		fprintf(stderr, "%14.2lf Gbit/s\n", rate / 1e9);
	else if(rate > 1e6)
		fprintf(stderr, "%14.2lf Mbit/s\n", rate / 1e6);
	else if(rate > 1e3)
		fprintf(stderr, "%14.2lf kbit/s\n", rate / 1e3);
	sptps_stop(&sptps1);
	sptps_stop(&sptps2);

	// Clean up

	close(fd[0]);
	close(fd[1]);
	ecdsa_free(key1);
	ecdsa_free(key2);
	crypto_exit();

	return 0;
}