summary refs log tree commit diff
path: root/state.c
blob: 21669c4752fe82e79b58593fa3ebd98579d85b29 (plain) (blame)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/* Copyright (C) 2019  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Additional permission under GNU GPL version 3 section 7:
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with OpenSSL (or a modified version of that library),
 * containing parts covered by the terms of the OpenSSL License and the
 * original SSLeay license, the licensors of this Program grant you
 * additional permission to convey the resulting work. Corresponding
 * Source for a non-source form of such a combination shall include the
 * source code for the parts of OpenSSL used as well as that of the
 * covered work.
 */

#include <assert.h>
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sysexits.h>

#include "bounce.h"

bool stateNoNames;
enum Cap stateCaps;

typedef void Handler(struct Message *msg);

static void require(const struct Message *msg, bool origin, size_t len) {
	if (origin && !msg->origin) {
		errx(EX_PROTOCOL, "%s missing origin", msg->cmd);
	}
	for (size_t i = 0; i < len; ++i) {
		if (msg->params[i]) continue;
		errx(EX_PROTOCOL, "%s missing parameter %zu", msg->cmd, 1 + i);
	}
}

// Maximum size of one AUTHENTICATE message.
enum { AuthLen = 299 };
static char plainBase64[BASE64_SIZE(AuthLen)];

void stateLogin(
	const char *pass, enum Cap blind, const char *plain,
	const char *nick, const char *user, const char *real
) {
	serverFormat("CAP LS 302\r\n");
	if (pass) serverFormat("PASS :%s\r\n", pass);
	if (blind) serverFormat("CAP REQ :%s\r\n", capList(blind, NULL));
	if (plain) {
		byte buf[AuthLen];
		size_t len = 1 + strlen(plain);
		if (sizeof(buf) < len) {
			errx(EX_SOFTWARE, "SASL PLAIN is too long");
		}
		buf[0] = 0;
		for (size_t i = 0; plain[i]; ++i) {
			buf[1 + i] = (plain[i] == ':' ? 0 : plain[i]);
		}
		base64(plainBase64, buf, len);
		explicit_bzero(buf, sizeof(buf));
	}
	serverFormat("NICK %s\r\n", nick);
	serverFormat("USER %s 0 * :%s\r\n", user, real);
}

static void handleCap(struct Message *msg) {
	require(msg, false, 3);
	enum Cap caps;
	if (!strcmp(msg->params[2], "*") && msg->params[3]) {
		caps = capParse(msg->params[3], NULL);
	} else {
		caps = capParse(msg->params[2], NULL);
	}

	if (!strcmp(msg->params[1], "LS") || !strcmp(msg->params[1], "NEW")) {
		caps &= ~(CapSASL | CapSTS | CapUnsupported);
		if (caps & CapEchoMessage && !(caps & CapLabeledResponse)) {
			caps &= ~CapEchoMessage;
		}
		if (caps) {
			serverFormat("CAP REQ :%s\r\n", capList(caps, NULL));
		} else {
			if (!(stateCaps & CapSASL)) serverFormat("CAP END\r\n");
		}

	} else if (!strcmp(msg->params[1], "ACK")) {
		stateCaps |= caps;
		if (caps & CapSASL) {
			serverFormat(
				"AUTHENTICATE %s\r\n", (plainBase64[0] ? "PLAIN" : "EXTERNAL")
			);
		}
		if (!(stateCaps & CapSASL)) serverFormat("CAP END\r\n");

	} else if (!strcmp(msg->params[1], "DEL")) {
		stateCaps &= ~caps;

	} else if (!strcmp(msg->params[1], "NAK")) {
		errx(EX_CONFIG, "server does not support %s", msg->params[2]);
	}
}

static void handleAuthenticate(struct Message *msg) {
	(void)msg;
	if (plainBase64[0]) {
		serverFormat("AUTHENTICATE %s\r\n", plainBase64);
		explicit_bzero(plainBase64, sizeof(plainBase64));
	} else {
		serverFormat("AUTHENTICATE +\r\n");
	}
}

static void handleReplyLoggedIn(struct Message *msg) {
	(void)msg;
	serverFormat("CAP END\r\n");
}

static void handleErrorSASLFail(struct Message *msg) {
	require(msg, false, 2);
	errx(EX_CONFIG, "%s", msg->params[1]);
}

static struct {
	char *nick;
	char *origin;
} self;

static struct {
	char *origin;
	char *welcome;
	char *yourHost;
	char *created;
	char *myInfo[5];
} intro;

const char *stateNick(void) {
	return (self.nick ? self.nick : "*");
}

const char *stateEcho(void) {
	return (self.origin ? self.origin : stateNick());
}

bool stateReady(void) {
	return self.nick
		&& intro.origin
		&& intro.welcome
		&& intro.yourHost
		&& intro.created
		&& intro.myInfo[0];
}

static void set(char **field, const char *value) {
	if (*field) free(*field);
	*field = strdup(value);
	if (!*field) err(EX_OSERR, "strdup");
}

static void handleErrorNicknameInUse(struct Message *msg) {
	if (self.nick) return;
	require(msg, false, 2);
	serverFormat("NICK %s_\r\n", msg->params[1]);
}

static void handleReplyWelcome(struct Message *msg) {
	require(msg, true, 2);
	set(&intro.origin, msg->origin);
	set(&self.nick, msg->params[0]);
	set(&intro.welcome, msg->params[1]);
}

static void handleReplyYourHost(struct Message *msg) {
	require(msg, false, 2);
	set(&intro.yourHost, msg->params[1]);
}

static void handleReplyCreated(struct Message *msg) {
	require(msg, false, 2);
	set(&intro.created, msg->params[1]);
}

static void handleReplyMyInfo(struct Message *msg) {
	require(msg, false, 5);
	set(&intro.myInfo[0], msg->params[1]);
	set(&intro.myInfo[1], msg->params[2]);
	set(&intro.myInfo[2], msg->params[3]);
	set(&intro.myInfo[3], msg->params[4]);
	if (msg->params[5]) set(&intro.myInfo[4], msg->params[5]);
}

static struct {
	bool done;
	char **tokens;
	size_t cap, len;
} support;

static void supportAdd(const char *token) {
	if (support.len == support.cap) {
		support.cap = (support.cap ? support.cap * 2 : 8);
		support.tokens = realloc(support.tokens, sizeof(char *) * support.cap);
		if (!support.tokens) err(EX_OSERR, "realloc");
	}
	support.tokens[support.len] = strdup(token);
	if (!support.tokens[support.len]) err(EX_OSERR, "strdup");
	support.len++;
}

static void handleReplyISupport(struct Message *msg) {
	require(msg, false, 1);
	if (support.done) return;
	for (size_t i = 1; i < ParamCap; ++i) {
		if (!msg->params[i] || strchr(msg->params[i], ' ')) break;
		supportAdd(msg->params[i]);
	}
}

static void handleReplyMOTDStart(struct Message *msg) {
	(void)msg;
	support.done = true;
}

struct Channel {
	char *name;
	char *topic;
};

static struct {
	struct Channel *ptr;
	size_t cap, len;
} chans;

static void chanAdd(const char *name) {
	if (chans.len == chans.cap) {
		chans.cap = (chans.cap ? chans.cap * 2 : 8);
		chans.ptr = realloc(chans.ptr, sizeof(*chans.ptr) * chans.cap);
		if (!chans.ptr) err(EX_OSERR, "realloc");
	}
	struct Channel *chan = &chans.ptr[chans.len++];
	chan->name = strdup(name);
	if (!chan->name) err(EX_OSERR, "strdup");
	chan->topic = NULL;
}

static void chanTopic(const char *name, const char *topic) {
	for (size_t i = 0; i < chans.len; ++i) {
		if (strcmp(chans.ptr[i].name, name)) continue;
		set(&chans.ptr[i].topic, topic);
		break;
	}
}

static void chanRemove(const char *name) {
	for (size_t i = 0; i < chans.len; ++i) {
		if (strcmp(chans.ptr[i].name, name)) continue;
		free(chans.ptr[i].name);
		free(chans.ptr[i].topic);
		chans.ptr[i] = chans.ptr[--chans.len];
		break;
	}
}

static bool originSelf(const char *origin) {
	if (!self.nick) return false;

	size_t len = strlen(self.nick);
	if (strlen(origin) < len) return false;
	if (strncmp(origin, self.nick, len)) return false;
	if (origin[len] != '!') return false;

	if (!self.origin || strcmp(self.origin, origin)) {
		set(&self.origin, origin);
	}
	return true;
}

static void handleNick(struct Message *msg) {
	require(msg, true, 1);
	if (!originSelf(msg->origin)) return;
	set(&self.nick, msg->params[0]);

	char *rest = strchr(self.origin, '!');
	assert(rest);
	size_t size = strlen(self.nick) + strlen(rest) + 1;
	char *origin = malloc(size);
	if (!origin) err(EX_OSERR, "malloc");
	snprintf(origin, size, "%s%s", self.nick, rest);
	free(self.origin);
	self.origin = origin;
}

static void handleJoin(struct Message *msg) {
	require(msg, true, 1);
	if (originSelf(msg->origin)) chanAdd(msg->params[0]);
}

static void handlePart(struct Message *msg) {
	require(msg, true, 1);
	if (originSelf(msg->origin)) chanRemove(msg->params[0]);
}

static void handleKick(struct Message *msg) {
	require(msg, false, 2);
	if (self.nick && !strcmp(msg->params[1], self.nick)) {
		chanRemove(msg->params[0]);
	}
}

static void handleTopic(struct Message *msg) {
	require(msg, false, 2);
	chanTopic(msg->params[0], msg->params[1]);
}

static void handleReplyTopic(struct Message *msg) {
	require(msg, false, 3);
	chanTopic(msg->params[1], msg->params[2]);
}

static void handleError(struct Message *msg) {
	require(msg, false, 1);
	errx(EX_UNAVAILABLE, "%s", msg->params[0]);
}

static const struct {
	const char *cmd;
	Handler *fn;
} Handlers[] = {
	{ "001", handleReplyWelcome },
	{ "002", handleReplyYourHost },
	{ "003", handleReplyCreated },
	{ "004", handleReplyMyInfo },
	{ "005", handleReplyISupport },
	{ "332", handleReplyTopic },
	{ "375", handleReplyMOTDStart },
	{ "422", handleReplyMOTDStart },
	{ "433", handleErrorNicknameInUse },
	{ "437", handleErrorNicknameInUse },
	{ "900", handleReplyLoggedIn },
	{ "904", handleErrorSASLFail },
	{ "905", handleErrorSASLFail },
	{ "906", handleErrorSASLFail },
	{ "AUTHENTICATE", handleAuthenticate },
	{ "CAP", handleCap },
	{ "ERROR", handleError },
	{ "JOIN", handleJoin },
	{ "KICK", handleKick },
	{ "NICK", handleNick },
	{ "PART", handlePart },
	{ "TOPIC", handleTopic },
};

void stateParse(char *line) {
	struct Message msg = parse(line);
	if (!msg.cmd) return;
	for (size_t i = 0; i < ARRAY_LEN(Handlers); ++i) {
		if (strcmp(msg.cmd, Handlers[i].cmd)) continue;
		Handlers[i].fn(&msg);
		break;
	}
}

void stateSync(struct Client *client) {
	assert(stateReady());

	clientFormat(
		client,
		":%s NOTICE %s :"
		"pounce is GPLv3 fwee softwawe ^w^  code is avaiwable fwom %s\r\n",
		ORIGIN, self.nick, SOURCE_URL
	);

	clientFormat(
		client,
		":%s 001 %s :%s\r\n"
		":%s 002 %s :%s\r\n"
		":%s 003 %s :%s\r\n"
		":%s 004 %s %s %s %s %s%s%s\r\n",
		intro.origin, self.nick, intro.welcome,
		intro.origin, self.nick, intro.yourHost,
		intro.origin, self.nick, intro.created,
		intro.origin, self.nick,
		intro.myInfo[0], intro.myInfo[1], intro.myInfo[2], intro.myInfo[3],
		(intro.myInfo[4] ? " " : ""), (intro.myInfo[4] ? intro.myInfo[4] : "")
	);

	size_t i;
	for (i = 0; support.len - i >= 13; i += 13) {
		clientFormat(
			client,
			":%s 005 %s"
			" %s %s %s %s %s %s %s %s %s %s %s %s %s"
			" :are supported by this server\r\n",
			intro.origin, self.nick,
			support.tokens[i + 0], support.tokens[i + 1],
			support.tokens[i + 2], support.tokens[i + 3],
			support.tokens[i + 4], support.tokens[i + 5],
			support.tokens[i + 6], support.tokens[i + 7],
			support.tokens[i + 8], support.tokens[i + 9],
			support.tokens[i + 10], support.tokens[i + 11],
			support.tokens[i + 12]
		);
	}
	if (i < support.len) {
		char buf[512], *ptr = buf, *end = &buf[sizeof(buf)];
		ptr = seprintf(ptr, end, ":%s 005 %s", intro.origin, self.nick);
		for (; i < support.len; ++i) {
			ptr = seprintf(ptr, end, " %s", support.tokens[i]);
		}
		ptr = seprintf(ptr, end, " :are supported by this server\r\n");
		clientSend(client, buf, ptr - buf);
	}

	clientFormat(
		client, ":%s 422 %s :MOTD File is missing\r\n",
		ORIGIN, self.nick
	);

	if (chans.len) assert(self.origin);
	for (size_t i = 0; i < chans.len; ++i) {
		const struct Channel *chan = &chans.ptr[i];
		clientFormat(client, ":%s JOIN %s\r\n", self.origin, chan->name);
		if (chan->topic) {
			clientFormat(
				client, ":%s 332 %s %s :%s\r\n",
				ORIGIN, self.nick, chan->name, chan->topic
			);
		}
		if (stateNoNames) continue;
		serverEnqueue("NAMES %s\r\n", chan->name);
	}
}