summaryrefslogtreecommitdiff
path: root/tunnel.c
blob: 56bdcddb119dc548a0b739c1952cbed2333e895a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>

#include <stddef.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <err.h>

#include "tunnel.h"
#include "macro.h"

int tunnel_socket(struct sockaddr **sa, socklen_t *salen)
{
	int sock = socket(AF_UNIX, SOCK_SEQPACKET, 0);
	if (sock < 0) {
		warn("socket");
		return -1;
	}

	struct sockaddr_un sun = {
		.sun_family = AF_UNIX
	};

	const char *path = TUNNEL_SOCK_PATH;

	int n = snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
	socklen_t len = offsetof(struct sockaddr_un, sun_path) + n + 1;

	if (len > sizeof(sun)) {
		warnx("too large unix path");
		close(sock);
		return -1;
	}

	*sa = _copy(&sun, len);
	*salen = len;

	return sock;
}

int tunnel_listen(int sock, struct sockaddr *sa, socklen_t salen)
{
	if (bind(sock, sa, salen) < 0) {
		warn("bind");
		return -1;
	}

	if (listen(sock, 0) < 0) {
		warn("listen");
		return -1;
	}

	return 0;
}

int tunnel_server(void)
{
	struct sockaddr *sa = NULL;
	socklen_t salen = 0;

	int sock = tunnel_socket(&sa, &salen);
	if (sock < 0)
		return -1;

	defer {
		close(sock);
		free(sa);
	}

	if (tunnel_listen(sock, sa, salen) < 0)
		return -1;

	if (tunnel_daemon(sock) < 0)
		return -1;

	return 0;
}

int tunnel_connect(int sock, struct sockaddr *sa, socklen_t salen)
{
	if (connect(sock, sa, salen) < 0) {
		if (errno == ENOENT) {
			if (tunnel_server() < 0)
				return -1;
		}

		if (errno != ENOENT || connect(sock, sa, salen) < 0) {
			warn("connect");
			return -1;
		}
	}

	return 0;
}

int tunnel_client(void)
{
	struct sockaddr *sa = NULL;
	socklen_t salen = 0;

	int sock = tunnel_socket(&sa, &salen);
	if (sock < 0)
		return -1;

	defer { free(sa); }

	if (tunnel_connect(sock, sa, salen) < 0) {
		close(sock);
		return -1;
	}

	return sock;
}