~stacyharper/bonsai

ref: 85e31796dc4d796bf4dd20aa770728cc3a7ecb51 bonsai/cmd/bonsaid/socket.ha -rw-r--r-- 6.0 KiB
85e31796Stacy Harper Minimize socket conversation line count 2 months ago
                                                                                
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use bytes;
use dirs;
use encoding::utf8;
use errors;
use fmt;
use fs;
use io;
use log;
use net::unix;
use net;
use os;
use path;
use strings;
use unix::poll::{event};
use unix::poll;
use unix::signal;
use unix;
use bonsai;

def CLIENT_MAXBUF: size = 16777216; // 16 MiB
def MAX_CLIENTS: size = 256;
def POLLFD_RESERVED: size = 3;

type server = struct {
	sock: net::socket,
	signalfd: io::file,
	pollfd: []poll::pollfd,
	clients: []client,
	disconnected: bool, // XXX: Bit of a hack here

	daemonized: bool,
	terminate: bool,

	state: bonsai::state_machine,
};

fn bind(
	signalfd: io::file,
	daemonize: bool,
	state: bonsai::state_machine
) server = {
	const statedir = match (dirs::runtime()) {
	case let err: fs::error =>
		fmt::fatalf("Unable to initialize socket: {}", fs::strerror(err));
	case let dir: str =>
		yield dir;
	};

	let buf = path::init();
	path::set(&buf, statedir, "bonsai")!;
	const sockpath = path::string(&buf);
	const sock = match (unix::listen(sockpath, net::sockflags::NOCLOEXEC)) {
	case let l: net::socket =>
		yield l;
	case let err: net::error =>
		log::fatal(net::strerror(err));
	};
	os::chmod(sockpath, 0o700)!;

	let wait_pipes = state.wait_pipes as (io::file, io::file);
	let pollfd = alloc([
		poll::pollfd {
			fd = sock,
			events = event::POLLIN,
			...
		},
		poll::pollfd {
			fd = signalfd,
			events = event::POLLIN,
			...
		},
		poll::pollfd {
			fd = wait_pipes.0,
			events = event::POLLIN,
			...
		}
	]);

	return server {
		signalfd = signalfd,
		pollfd = pollfd,
		daemonized = daemonize,
		sock = sock,
		state = state,
		...
	};
};

fn shutdown(serv: *server) void = {
	for (let i = 0z; i < len(serv.clients); i += 1) {
		io::close(serv.clients[i].sock)!;
		free(serv.clients[i].rbuf);
		free(serv.clients[i].wbuf);
	};
	free(serv.clients);
	free(serv.pollfd);

	let buf = path::init();
	path::set(&buf, dirs::runtime()!, "bonsai")!;
	os::remove(path::string(&buf))!;

	net::close(serv.sock)!;
};

fn dispatch(serv: *server) bool = {
	if (serv.terminate) {
		return false;
	};

	match (poll::poll(serv.pollfd, poll::INDEF)) {
	case uint =>
		if (serv.pollfd[0].revents & event::POLLIN != 0) {
			log::println("socket client entrance");
			accept(serv);
		};
		if (serv.pollfd[1].revents & event::POLLIN != 0) {
			log::println("signal received");
			signal::read(serv.signalfd)!;
			return false;
		};
		if (serv.pollfd[2].revents & event::POLLIN != 0) {
			log::println("child waiter talks");
			const synced = bonsai::sync_back_wait_child(&serv.state, false);

			const wait_pipes = serv.state.wait_pipes as (io::file, io::file);
			io::close(wait_pipes.0)!;
			io::close(wait_pipes.1)!;

			if (synced) {
				log::println("child waiter updated the state. moving forward...");
				bonsai::state_forward_available_transitions(&serv.state);
			};

			serv.state.wait_pipes = unix::pipe(unix::pipe_flag::NONBLOCK)!;
			const wait_pipes = serv.state.wait_pipes as (io::file, io::file);

			if (synced) {
				log::println("start eventually new delay");
				bonsai::trigger_delay_transition(&serv.state);
			};

			serv.pollfd[2].fd = wait_pipes.0;
		};
		for (let i = POLLFD_RESERVED; i < len(serv.pollfd); i += 1) {
			log::println("socket client conversation...");
			dispatch_client(serv, &serv.clients[i - POLLFD_RESERVED]);
			if (serv.disconnected) {
				// Restart loop on client disconnect
				serv.disconnected = false;
				i = POLLFD_RESERVED;
			};
		};
	case errors::interrupted =>
		yield;
	case let err: errors::error =>
		log::fatal("poll:", errors::strerror(err));
	};

	return true;
};

fn accept(serv: *server) void = {
	// TODO: O_NONBLOCK
	const sock = match (net::accept(serv.sock)) {
	case let sock: net::socket =>
		yield sock;
	case let err: net::error =>
		log::fatal(net::strerror(err));
	};
	if (len(serv.clients) >= MAX_CLIENTS) {
		log::println("max clients exceeded; dropping client");
		io::close(sock)!;
		return;
	};

	append(serv.pollfd, poll::pollfd {
		fd = sock,
		events = event::POLLIN | event::POLLHUP,
		...
	});
	const pollfd = &serv.pollfd[len(serv.pollfd) - 1];
	append(serv.clients, client {
		server = serv,
		sock = sock,
		pollfd = pollfd,
		...
	});
};

fn dispatch_client(serv: *server, client: *client) void = {
	const pollfd = client.pollfd;
	if (pollfd.revents & event::POLLERR != 0) {
		disconnect(client);
		return;
	};
	if (pollfd.revents & event::POLLHUP != 0) {
		disconnect(client);
		return;
	};
	if (pollfd.revents & event::POLLIN != 0) {
		client_readable(serv, client);
	};
	if (pollfd.revents & event::POLLOUT != 0) {
		client_writable(serv, client);
	};
};

fn client_readable(serv: *server, client: *client) void = {
	let buf: [os::BUFSIZ]u8 = [0...];
	const z = match (io::read(client.sock, buf)) {
	case let z: size =>
		yield z;
	case io::EOF =>
		disconnect(client);
		return;
	case let err: io::error =>
		disconnect(client);
		return;
	};
	append(client.rbuf, buf[..z]...);
	if (len(client.rbuf) >= CLIENT_MAXBUF) {
		disconnect_error(client, "error Buffer exceeded\n");
		return;
	};

	for (true) {
		let i = match (bytes::index(client.rbuf, '\n')) {
		case let i: size =>
			yield i;
		case void =>
			return;
		};

		const line = match (strings::try_fromutf8(client.rbuf[..i])) {
		case let s: str =>
			yield s;
		case utf8::invalid =>
			disconnect_error(client, "error Invalid UTF-8\n");
			return;
		};
		defer delete(client.rbuf[..i+1]);
		match (exec(serv, client, line)) {
			case let err: servererror =>
				log::printfln("error processing user command: {}",
					strerror(err));
			case void =>
				yield;
		};
		if (serv.disconnected) {
			break;
		};
	};
};

fn client_writable(serv: *server, client: *client) void = {
	const z = match (io::write(client.sock, client.wbuf)) {
	case let z: size =>
		yield z;
	case errors::again =>
		return;
	case let err: io::error =>
		disconnect(client);
		return;
	};
	delete(client.wbuf[..z]);
	if (len(client.wbuf) != 0) {
		return;
	};

	switch (client.state) {
	case state::WRITE =>
		client.state = state::READ;
		client.pollfd.events = event::POLLIN | event::POLLHUP;
	case state::WRITE_ERROR =>
		disconnect(client);
	case => abort();
	};
};