summaryrefslogtreecommitdiff
path: root/src/hub/adc.c
blob: aa7d2d63d2513a2b8c52d11a556790c2be179885 (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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/* Copyright (c) 2012-2013 Yoran Heling

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <global.h>
#include <hub/local.h>
#include <tiger.h>


/* Finalize, send and free an ADC message */
#define cmd_flush(h, msg) do {\
		adc_final(msg);\
		ydebug("%d: Sending message: %.*s", (h)->id, (int)(msg)->l-1, (msg)->s);\
		nets_write((h)->c.n, (msg)->s, (msg)->l, NULL);\
	} while(0)


#define cmd_error(h, cmd, len, msg) do {\
		yerror("%d: %s: %.*s", (h)->id, msg, (len)-1, cmd);\
		hub_hub_seterror(h, HUBCD_RECONNECT, "Protocol", msg, NULL);\
	} while(0)

#define cmd_warn(h, cmd, len, msg) ywarn("%d: %s: %.*s", (h)->id, msg, (int)(len)-1, cmd)


/* Fill out a hub_adc_myinf_t struct with current info */
static void hub_adc_myinf_create(hub_t *h, hub_adc_myinf_t *n) {
	n->NI = strdup(hub_hub_mynick(h));
	n->DE = strdup(hub_hub_mydescription(h));
	n->EM = strdup(hub_hub_myemail(h));
	n->US = hub_hub_myconnection(h);
	n->HN = hub_manager_hnorm();
	n->HR = hub_manager_hreg();
	n->HO = hub_manager_hop();
}


/* Free memory associated with a hub_adc_myinf_t struct */
static void hub_adc_myinf_free(hub_adc_myinf_t *n) {
	free(n->NI);
	free(n->DE);
	free(n->EM);
}


static void hub_adc_sendinf(hub_t *h) {
	kstring_t msg = {};
	hub_adc_myinf_t n, *o = &h->a.lastinf;
	bool f = h->a.state == ADC_IDENTIFY;

	hub_adc_myinf_create(h, &n);
	adc_create(&msg, 'B', ADC_CMD_INF, h->a.mysid, 0);
	size_t empty_len = msg.l;

	if(f) {
		adc_appendf(&msg, "PD%s", app_tiger_pid());
		adc_appendf(&msg, "ID%s", app_tiger_cid());
		adc_appendf(&msg, "VE%s %s", PACKAGE_NAME, app_version_short());
		adc_append(&msg, "SL1");
	}
	if(f || strcmp(n.NI, o->NI) != 0) adc_appendf(&msg, "NI%s", n.NI);
	if(f || strcmp(n.DE, o->DE) != 0) adc_appendf(&msg, "DE%s", n.DE);
	if(f || strcmp(n.EM, o->EM) != 0) adc_appendf(&msg, "EM%s", n.EM);
	if(f || n.US != o->US) adc_appendf(&msg, "US%u", n.US);
	if(f || n.HN != o->HN) adc_appendf(&msg, "HN%"PRIu16, n.HN);
	if(f || n.HR != o->HR) adc_appendf(&msg, "HR%"PRIu16, n.HR);
	if(f || n.HO != o->HO) adc_appendf(&msg, "HO%"PRIu16, n.HO);

	if(!f)
		hub_adc_myinf_free(o);
	h->a.lastinf = n;

	/* Don't send an INF if nothing has changed */
	if(empty_len == msg.l)
		free(msg.s);
	else
		cmd_flush(h, &msg);
}


static void hub_adc_inf_hub(hub_t *h, const char *cmd, int len) {
	char *p, *ni = NULL, *de = NULL, *ve = NULL, *ap = NULL;

	/* Some hubs (PyAdc) send multiple NIs, just use the last one. */
	for(p=adc_param_start(cmd); p; p=adc_param_next(p)) {
		switch(adc_param_name(p)) {
		case ADC_PARAM('N','I'): ni = p; break;
		case ADC_PARAM('D','E'): de = p; break;
		case ADC_PARAM('V','E'): ve = p; break;
		case ADC_PARAM('A','P'): ap = p; break;
		}
	}

	/* Not all hubs send a NI but do include a DE, use the DE as name in that
	 * case. */
	if(!ni && !*hub_hub_name(h) && de) {
		ni = de;
		de = NULL;
	}

	if(ni) {
		p = adc_param_namevalue(ni);
		ydebug("%d: Setting hub name to: %s", h->id, p);
		hub_hub_setname(h, p);
		free(p);
	}
	if(de) {
		p = adc_param_namevalue(de);
		ydebug("%d: Setting hub description to: %s", h->id, p);
		hub_hub_setdescription(h, p);
		free(p);
	}

	if(ve) {
		/* Combine AP and VE. Luckily, the only hub that supports AP (ADCH++)
		 * doesn't include its AP in the VE, as some clients do with their INF.
		 */
		kstring_t buf = {};
		if(ap) {
			adc_unescape_kstr(&buf, ap+2);
			kputc(' ', &buf);
		}
		adc_unescape_kstr(&buf, ve+2);
		hub_hub_setversion(h, buf.s);
		free(buf.s);
	}
}


static void hub_adc_inf_user_client(hub_user_update_t *d, const char *ve, const char *ap) {
	/* VE and AP need some special care. There are currently three forms used
	 * in the wild:
	 *   1. VE<app>\s<version>            (non-AP aware clients)
	 *   2. VE<version> AP<app>           (clients that follow the AP spec)
	 *   3. VE<app>\s<version> AP<app>    (*cough* stupid clients)          */
	kstring_t buf = {};
	size_t aplen = 0;
	if(ap) {
		adc_unescape_kstr(&buf, ap+2);
		if((aplen = buf.l) > 0)
			kputc(' ', &buf);
	}
	adc_unescape_kstr(&buf, ve+2);
	if(aplen > 0 && strncmp(buf.s, buf.s+aplen+1, aplen) == 0) /* <app> <app> <version> */
		memmove(buf.s, buf.s+aplen+1, buf.l-aplen);
	free(d->u->client);
	d->u->client = buf.s;
	hub_user_update_field(d, HUBU_CLIENT);
}


#define ERR(msg) do {\
		cmd_warn(h, cmd, len, msg);\
		hub_user_update_abort(&d);\
		return;\
	} while(0)
#define UINT(param, max) do {\
		char *end = NULL;\
		uint64_t _v = strtoull(p+2, &end, 10);\
		if(!p[2] || !end || !adc_isparamend(*end))\
			ERR("Invalid integer value");\
		d.u->param = _v >= max ? max : _v;\
	} while(0)

static void hub_adc_inf_user(hub_t *h, const char *cmd, int len, adc_sid_t sid) {
	const char *p, *ve = NULL, *ap = NULL;
	hub_user_update_t d;
	hub_user_update_init(h, &d, sid == h->a.mysid ? 0 : hub_users_bysid(h, sid));
	d.u->online = true;
	d.u->a.sid = sid;
	bool isreg = false;

	for(p=adc_param_start(cmd); p; p=adc_param_next(p)) {
		switch(adc_param_name(p)) {
		case ADC_PARAM('N','I'): free(d.u->nick); d.u->nick = adc_param_namevalue(p); hub_user_update_field(&d, HUBU_NICK       ); break;
		case ADC_PARAM('D','E'): free(d.u->desc); d.u->desc = adc_param_namevalue(p); hub_user_update_field(&d, HUBU_DESCRIPTION); break;
		case ADC_PARAM('E','M'): free(d.u->mail); d.u->mail = adc_param_namevalue(p); hub_user_update_field(&d, HUBU_MAIL       ); break;
		case ADC_PARAM('V','E'): ve = p; break;
		case ADC_PARAM('A','P'): ap = p; break;
		case ADC_PARAM('S','S'): UINT(sharesize,   UINT64_MAX); hub_user_update_field(&d, HUBU_SHARESIZE  ); break;
		case ADC_PARAM('S','F'): UINT(sharedfiles, UINT32_MAX); hub_user_update_field(&d, HUBU_SHAREDFILES); break;
		case ADC_PARAM('H','N'): UINT(hnorm,        UINT8_MAX); hub_user_update_field(&d, HUBU_HUBS       ); break;
		case ADC_PARAM('H','R'): UINT(hreg,         UINT8_MAX); hub_user_update_field(&d, HUBU_HUBS       ); break;
		case ADC_PARAM('H','O'): UINT(hop,          UINT8_MAX); hub_user_update_field(&d, HUBU_HUBS       ); break;
		case ADC_PARAM('S','L'): UINT(hop,          UINT8_MAX); hub_user_update_field(&d, HUBU_SLOTS      ); break;
		case ADC_PARAM('A','S'): UINT(as,          UINT32_MAX); hub_user_update_field(&d, HUBU_AS         ); break;
		case ADC_PARAM('U','S'): UINT(conn,        UINT32_MAX); hub_user_update_field(&d, HUBU_CONN       ); break;
		case ADC_PARAM('I','D'): {
			char *cid = adc_param_namevalue(p);
			if(!isbase32_24(cid)) {
				free(cid);
				ERR("Invalid CID");
			}
			if(d.u->id >= 0) {
				cmd_warn(h, cmd, len, "Ignoring repeated/duplicate ID");
				free(cid);
				break;
			}
			base32_decode(cid, d.u->a.cid, 24);
			hub_user_update_field(&d, HUBU_CID);
			free(cid);
			break;
		}
		case ADC_PARAM('I','4'): {
			char *v = adc_param_namevalue(p);
			int r = inet_pton(AF_INET, v, &d.u->ip4);
			free(v);
			if(r != 1)
				ERR("Invalid IPv4 address");
			hub_user_update_field(&d, HUBU_IP4);
			break;
		}
		case ADC_PARAM('I','6'): {
			char *v = adc_param_namevalue(p);
			int r = inet_pton(AF_INET6, v, &d.u->ip6);
			free(v);
			if(r != 1)
				ERR("Invalid IPv6 address");
			hub_user_update_field(&d, HUBU_IP6);
			break;
		}
		case ADC_PARAM('C','T'): {
			char *end = NULL;\
			uint64_t _v = strtoull(p+2, &end, 10);\
			if(!p[2] || !end || !adc_isparamend(*end))\
				ERR("Invalid integer value");\
			isreg = _v & (2|4|8|16);
			bool op = _v & (4|8|16);
			if(op != d.u->op)
				hub_user_update_field(&d, HUBU_FLAGS);
			d.u->op = op;
			break;
		}
		case ADC_PARAM('S','U'): {
			char *v = adc_param_namevalue(p);
			bool active = strstr(v, "TCP4") || strstr(v, "TCP6");
			bool tls = strstr(v, "ADC0") || strstr(v, "ADCS");
			if(active != d.u->active || tls != d.u->tls)
				hub_user_update_field(&d, HUBU_FLAGS);
			d.u->active = active;
			d.u->tls = tls;
			free(v);
			break;
		}
		case ADC_PARAM('A','W'): {
			bool aw = !(adc_isparamend(p[2]) || p[2] == '0');
			if(aw != d.u->away)
				hub_user_update_field(&d, HUBU_FLAGS);
			d.u->away = aw;
			break;
		}
		/* TODO: U4 */
		}
	}

	if(ve)
		hub_adc_inf_user_client(&d, ve, ap);

	if(!d.u->nick || !*d.u->nick)
		ERR("No or empty nick");

	if(!hub_user_update_done(&d))
		cmd_warn(h, cmd, len, "No CID in INF for new user");

	/* Our own SID comes last, at which point we're in NORMAL */
	if(sid == h->a.mysid && h->a.state != ADC_NORMAL) {
		hub_hub_loggedin(h);
		hub_manager_settype(h, h->a.state == ADC_VERIFY ? HUBM_HREG : HUBM_HNORM);
		h->a.state = ADC_NORMAL;
		hub_users_listcomplete(h);
		if(isreg)
			hub_manager_settype(h, d.u->op ? HUBM_HOP : HUBM_HREG);
	}
}

#undef UINT
#undef ERR


static void hub_adc_inf(hub_t *h, const char *cmd, int len) {
	adc_sid_t src = adc_source(cmd);
	if(src == -1)
		hub_adc_inf_hub(h, cmd, len);
	else
		hub_adc_inf_user(h, cmd, len, src);
}


static void hub_adc_qui(hub_t *h, const char *cmd, int len) {
	const char *p = adc_param_start(cmd);
	adc_sid_t sid = p ? adc_str2sid(p) : -1;
	if(sid == -1) {
		cmd_warn(h, cmd, len, "Invalid SID argument");
		return;
	}

	adc_sid_t initiator = -1;
	char *message = NULL, *redir = NULL;
	while((p = adc_param_next(p))) {
		switch(adc_param_name(p)) {
		case ADC_PARAM('I','D'): initiator = adc_str2sid(p); break;
		case ADC_PARAM('M','S'): free(message); message = adc_param_namevalue(p); break;
		case ADC_PARAM('R','D'): free(redir); redir = adc_param_namevalue(p); break;
		}
	}

	if(sid != h->a.mysid) {
		int64_t id = hub_users_bysid(h, sid);
		if(id == -1)
			cmd_warn(h, cmd, len, "QUI for user not on this hub");
		else {
			int64_t initid = initiator == -1 ? -2 : hub_users_bysid(h, initiator);
			hub_user_left(h, id, initid, message ? message : "");
		}
	} else {
		/* We've been disconnected. */
		hub_hub_seterror(h, redir ? 0 : HUBCD_RECONNECT, redir ? "Redirect" : "Disconnect", message ? message : "Disconnected from hub", redir);
	}
	free(message);
}


static void hub_adc_msg(hub_t *h, const char *cmd, int len) {
	const char *p = adc_param_start(cmd);
	if(!p) {
		cmd_warn(h, cmd, len, "MSG without message parameter");
		return;
	}

	adc_sid_t src = adc_source(cmd);
	int64_t user = -1;
	if(src >= 0 && (user = hub_users_bysid(h, src)) == -1) {
		cmd_warn(h, cmd, len, "MSG from an unknown SID");
		return;
	}

	char *msg = adc_param_posvalue(p);
	bool me = false;
	adc_sid_t pmsid = -1;
	for(; p; p=adc_param_next(p)) {
		switch(adc_param_name(p)) {
		case ADC_PARAM('M','E'): me = p[2] == '1' && adc_isparamend(p[3]); break;
		case ADC_PARAM('P','M'): pmsid = adc_str2sid(p+2); pmsid = pmsid == -1 ? -2 : pmsid; break;
		}
	}

	int64_t group = -1;
	if(pmsid == -2 || (pmsid >= 0 && (group = hub_users_bysid(h, pmsid)) == -1)) {
		cmd_warn(h, cmd, len, "MSG with unknown SID in PM param");
		free(msg);
		return;
	}

	/* Don't consider a direct message as a mainchat one, even if there is no
	 * PM param. */
	adc_sid_t dest = adc_dest(cmd);
	if(group == -1 && dest != -1)
		group = user;

	/* If we sent a PM and this message is its echo, make sure to set the group
	 * to whatever SID we sent it to. */
	if(group == 0 && dest != -1 && (group = hub_users_bysid(h, dest)) == -1) {
		cmd_warn(h, cmd, len, "MSG with unknown SID as target");
		free(msg);
		return;
	}

	hub_chat_message(h, group, user, msg, me);
	free(msg);
}


static void hub_adc_sta(hub_t *h, const char *cmd, int len) {
	const char *code = adc_param_start(cmd);
	const char *msgpar = code ? adc_param_next(code) : NULL;
	if(!code || code[0] < '0' || code[0] > '4' || code[1] < '0' || code[1] > '9' || code[2] < '0' || code[2] > '9' || !adc_isparamend(code[3]) || !msgpar) {
		cmd_warn(h, cmd, len, "Invalid positional parameter");
		return;
	}

	adc_sid_t src = adc_source(cmd);
	char *msg = adc_param_posvalue(msgpar);

	/* Kick/ban */
	if(src == -1 && code[0] == '2' && code[1] == '3')
		/* Don't disconnect. It's the responsibility of the hub to disconnect
		 * us after a fatal STA message. In particular, ADCH++ usually first
		 * sends a fatal STA and then a QUI with potentially more information.
		 * Disconnecting here would miss that QUI. */
		hub_hub_seterror(h, HUBCD_NO, "Disconnect", msg, NULL);

	/* Nick invalid / taken */
	else if(src == -1 && code[1] == '2' && (code[2] == '1' || code[2] == '2'))
		hub_hub_seterror(h, HUBCD_RECONNECT, "InvalidNick", msg, NULL);

	/* Invalid password */
	else if(src == -1 && code[1] == '2' && code[2] == '3')
		hub_hub_seterror(h, 0, "InvalidPassword", msg, NULL);

	/* Full */
	else if(src == -1 && code[1] == '1' && code[2] == '1')
		hub_hub_seterror(h, HUBCD_RECONNECT, "Full", msg, NULL);

	/* Any other fatal STA from the hub */
	else if(src == -1 && *code == '2')
		hub_hub_seterror(h, HUBCD_NO, "Protocol", msg, NULL);

	/* Anything else is just logged and otherwise ignored at the moment */
	else if(*code == '0')
		yinfo("%d: Status message: %.*s", h->id, (int)len-1, cmd);
	else
		cmd_warn(h, cmd, len, "Error message");

	free(msg);
}


static void hub_adc_sup(hub_t *h, const char *cmd, int len) {
	bool hasbase = false, hastigr = false;
	const char *p;

	for(p=adc_param_start(cmd); p; p=adc_param_next(p)) {
		if(strncmp(p, "ADBASE", 6) == 0)
			hasbase = true;
		else if(strncmp(p, "ADTIGR", 6) == 0)
			hastigr = true;
		else if(strncmp(p, "RMBASE", 6) == 0 || strncmp(p, "RMTIGR", 6) == 0) {
			cmd_error(h, cmd, len, "Attempt to remove support for BASE or TIGR");
			return;
		}
	}

	if(h->a.state == ADC_PROTOCOL && (!hasbase || !hastigr)) {
		cmd_error(h, cmd, len, "Hub does not support BASE and/or TIGR");
		return;
	}
}


static void hub_adc_sid(hub_t *h, const char *cmd, int len) {
	char *arg = adc_param_start(cmd);
	if(!arg || (h->a.mysid = adc_str2sid(arg)) < 0) {
		cmd_error(h, cmd, len, "Invalid SID");
		return;
	}
	h->a.state = ADC_IDENTIFY;
	hub_adc_sendinf(h);
}


static void hub_adc_gpa(hub_t *h, const char *cmd, int len) {
	const char *passwd = hub_hub_mypassword(h);
	char *arg = adc_param_start(cmd);
	if(!arg) {
		cmd_warn(h, cmd, len, "Data parameter missing");
		return;
	}
	if(!passwd || !*passwd) {
		hub_hub_seterror(h, 0, "NeedPassword", "Hub requires a password", NULL);
		return;
	}
	char *data = adc_param_posvalue(arg);
	int binlength = base32_binlength(strlen(data));
	int paslength = strlen(passwd);
	/* The ADC 1.0.2 spec says that the length of the data should be at least
	 * 24 bytes. Some hubs don't follow this, unfortunately. There is strictly
	 * no maximum, but we don't want a stack overflow. */
	if(!isbase32(data) || binlength < 6 || binlength > 256) {
		cmd_error(h, cmd, len, "Hub did not provide valid or enough random salt");
		free(data);
		return;
	}
	char bindata[paslength + binlength];
	strcpy(bindata, passwd);
	base32_decode(data, bindata+paslength, binlength);
	free(data);

	t_res res;
	tiger(bindata, paslength + binlength, res);
	t_to_from_littleendian(res);
	char bres[40];
	base32_encode((char *)res, bres, 24);

	kstring_t msg = {};
	adc_create(&msg, 'H', ADC_CMD_PAS, 0, 0);
	adc_append(&msg, bres);
	cmd_flush(h, &msg);
	h->a.state = ADC_VERIFY;
}


static void hub_adc_zon(hub_t *h, const char *cmd, int len) {
	h->a.zlibenable = true;
}


static void hub_adc_zof(hub_t *h, const char *cmd, int len) {
	/* No need to do anything with it. The hub should close the zlib stream
	 * after this command, and netstream.c should detect that. */
}


static void hub_adc_handle(hub_t *h, const char *cmd, int len) {
	static const struct {
		adc_cmd_t cmd;
		adc_state_t states;  /* 0 = all */
		const char types[8]; /* empty = all */
		void (*func)(hub_t *, const char *, int);
	} cmds[] = {
		{ ADC_CMD_INF, ADC_IDENTIFY|ADC_VERIFY|ADC_NORMAL, "",  hub_adc_inf },
		{ ADC_CMD_QUI, ADC_IDENTIFY|ADC_VERIFY|ADC_NORMAL, "I", hub_adc_qui },
		/* MSG Should be NORMAL-only, but ADCH++ doesn't know that. */
		{ ADC_CMD_MSG, ADC_IDENTIFY|ADC_VERIFY|ADC_NORMAL, "",  hub_adc_msg },
		{ ADC_CMD_STA, 0,                                  "",  hub_adc_sta },
		{ ADC_CMD_SUP, 0,                                  "I", hub_adc_sup },
		{ ADC_CMD_SID, ADC_PROTOCOL,                       "I", hub_adc_sid },
		{ ADC_CMD_GPA, ADC_IDENTIFY,                       "I", hub_adc_gpa },
		{ ADC_CMD_ZON, 0,                                  "I", hub_adc_zon },
		{ ADC_CMD_ZOF, 0,                                  "I", hub_adc_zof }
	};

	adc_cmd_t c = adc_command(cmd);
	if(!c) /* Empty \n */
		return;

	int i;
	for(i=0; i<(int)(sizeof(cmds)/sizeof(*cmds)); i++)
		if(c == cmds[i].cmd)
			break;

	if(i == sizeof(cmds)/sizeof(*cmds)) {
		yinfo("%d: Unhandled command: %.*s", h->id, len-1, cmd);
		return;
	}

	if(cmds[i].states && !(h->a.state & cmds[i].states)) {
		cmd_warn(h, cmd, len, "Command received in wrong state");
		return;
	}

	const char *t = cmds[i].types;
	if(*t) {
		while(*t && *t != adc_type(cmd))
			t++;
		if(!*t) {
			/* This is as much an "error" as an unhandled command is, so just warn. */
			cmd_warn(h, cmd, len, "Ignoring command with wrong type");
			return;
		}
	}

	cmds[i].func(h, cmd, len);
}


static void hub_adc_sendkeepalive(hub_t *h) {
	nets_write(h->c.n, strdup("\n"), 1, NULL);
}


static int hub_adc_read(hub_t *h, const char *buf, int oldlen, int len) {
	int con = 0;
	char *next;
	/* Only check the newly added data. */
	if((next = memchr(buf+oldlen, '\n', len-oldlen)) == NULL)
		return 0;

	do {
		int l = adc_validate(buf, len-con);
		if(l != next-buf+1)
			cmd_warn(h, buf, next-buf+1, "Invalid ADC message");
		else {
			ydebug("%d: Received message: %.*s", h->id, l-1, buf);
			hub_adc_handle(h, buf, l);
		}
		con += next-buf+1;
		buf = next+1;
	} while(!h->a.zlibenable && hub_conn_state(h) == HUBC_CONN && (next = memchr(buf, '\n', len-con)) != NULL);

	/* We've received a ZON, make sure to unread all buffered data */
	if(h->a.zlibenable && hub_conn_state(h) == HUBC_CONN) {
		ydebug("%d: Enabling zlib, unreading %d bytes", h->id, len-con);
		nets_unread(h->c.n, buf, len-con);
		nets_zlibr_enable(h->c.n, NULL);
		con = len;
	}
	h->a.zlibenable = false;

	return con;
}


static bool hub_adc_chat(hub_t *h, hub_user_t *u, const char *message, bool me) {
	if(hub_conn_state(h) != HUBC_CONN || h->a.state != ADC_NORMAL)
		return false;
	kstring_t msg = {};
	adc_create(&msg, u ? 'E' : 'B', ADC_CMD_MSG, h->a.mysid, u ? u->a.sid : 0);
	adc_append(&msg, message);
	if(me)
		adc_append(&msg, "ME1");
	if(u) {
		char sid[5] = {};
		adc_sid2str(h->a.mysid, sid);
		adc_appendf(&msg, "PM%s", sid);
	}
	cmd_flush(h, &msg);
	return true;
}


static void hub_adc_connected(hub_t *h) {
	kstring_t msg = {};
	h->a.state = ADC_PROTOCOL;

	adc_create(&msg, 'H', ADC_CMD_SUP, 0, 0);
	adc_append(&msg, "ADBASE");
	adc_append(&msg, "ADTIGR");
	adc_append(&msg, "ADZLIF");
	cmd_flush(h, &msg);
}


static void hub_adc_disconnected(hub_t *h) {
	hub_adc_myinf_free(&h->a.lastinf);
	hub_manager_settype(h, HUBM_HNONE);
}


const hub_proto_t hub_adc = {
	hub_adc_connected,
	hub_adc_disconnected,
	hub_adc_sendinf,
	hub_adc_sendkeepalive,
	hub_adc_chat,
	hub_adc_read
};

/* vim: set noet sw=4 ts=4: */