summaryrefslogtreecommitdiff
path: root/src/hub/nmdc.c
blob: 06ca7f307f60621bbbd07dba1eb0353b90deae0b (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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
/* 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>


/* Number of seconds since the last new non-self $MyINFO that we consider as a
 * user list completetion. */
#define USERLISTCOMPLETE_TIMEOUT 10.0

#define QUIT_TIMEOUT 0.3

#define cmd_send(h, ...) do {\
		kstring_t _cmd = {};\
		ksprintf(&_cmd, __VA_ARGS__);\
		ydebug("%d: Sending message: %s", (h)->id, _cmd.s);\
		nets_write((h)->c.n, _cmd.s, _cmd.l, NULL);\
	} while(0)



__KHASH_IMPL(nmdcdefer, static kh_inline, int64_t, hub_nmdc_defer_t, 1, kh_int64_hash_func, kh_int64_hash_equal);


static hub_nmdc_defer_t *hub_nmdc_defer_del(hub_t *h, int64_t uid) {
	khiter_t k = kh_get(nmdcdefer, h->n.defer, uid);
	if(k == kh_end(h->n.defer))
		return NULL;
	/* XXX: The value is used after deleting it from the hash table. This
	 * relies on khash behaviour: It won't shrink the table on delete, nor will
	 * it modify deleted values until their slots are being re-used. */
	kh_del(nmdcdefer, h->n.defer, k);
	return &kh_value(h->n.defer, k);
}


static hub_nmdc_defer_t *hub_nmdc_defer_put(hub_t *h, int64_t uid) {
	int r;
	khiter_t k = kh_put(nmdcdefer, h->n.defer, uid, &r);
	hub_nmdc_defer_t *def = &kh_value(h->n.defer, k);
	if(r != 0)
		memset(def, 0, sizeof(hub_nmdc_defer_t));
	return def;
}


static int64_t hub_nmdc_userid(hub_t *h, const char *nick, int len) {
	return len == (int)strlen(h->n.nick) && strncmp(h->n.nick, nick, len) == 0 ? 0 : hub_users_genid(h, nick, len);
}


/* Called when we supposedly have the complete user list (either after timeout,
 * or after receiving a non-self $MyINFO update). May be called multiple times.
 */
static void hub_nmdc_userlist_done(hub_t *h) {
	if(!h->n.listcomplete) {
		h->n.listcomplete = true;
		hub_users_listcomplete(h);
	}
	ev_timer_stop(EV_DEFAULT_UC_ &h->n.listtimer);
}


static void hub_nmdc_userlist_timeout(EV_P_ ev_timer *w, int revents) {
	hub_nmdc_userlist_done(w->data);
}


/* The first call to this functions initiates the timeout. */
static void hub_nmdc_userlist_activity(hub_t *h) {
	if(!h->n.listcomplete) {
		h->n.listtimer.repeat = USERLISTCOMPLETE_TIMEOUT;
		ev_timer_again(EV_DEFAULT_UC_ &h->n.listtimer);
	}
}


static void hub_nmdc_sendinf(hub_t *h) {
	kstring_t inf = {};

	char conn[32];
	if(hub_hub_myconnection(h))
		snprintf(conn, 31, "%d KiB/s", hub_hub_myconnection(h)/1024);
	else
		strcpy(conn, "0.005");

	char *desc = nmdc_escape(hub_hub_encoding(h), hub_hub_mydescription(h), -1);
	char *mail = nmdc_escape(hub_hub_encoding(h), hub_hub_myemail(h), -1);
	ksprintf(&inf, "%s %s<%s V:%s,M:P,H:%"PRIu16"/%"PRIu16"/%"PRIu16",S:1>$ $%s\x01$%s$0$",
		h->n.nick, desc, PACKAGE_NAME, app_version_short(),
		hub_manager_hnorm(), hub_manager_hreg(), hub_manager_hop(), conn, mail);
	free(desc);
	free(mail);

	if(!h->n.lastinfo || strcmp(h->n.lastinfo, inf.s) != 0)
		cmd_send(h, "$MyINFO $ALL %s|", inf.s);
	free(h->n.lastinfo);
	h->n.lastinfo = inf.s;
}


static void hub_nmdc_myinfo_update(nmdc_myinfo_t *nfo, hub_user_update_t *d) {
	/* Connection */
	uint32_t conn = nmdc_conn2speed(nfo->conn);
	if(conn != d->u->conn) {
		d->u->conn = conn;
		hub_user_update_field(d, HUBU_CONN);
	}

	/* Flags */
	bool away = nfo->flag & 2;
	bool tls = nfo->flag & 0x10;
	bool active = nfo->mode == 'A';
	if(away != d->u->away || tls != d->u->tls || active != d->u->active)
		hub_user_update_field(d, HUBU_FLAGS);
	d->u->away = away;
	d->u->tls = tls;
	d->u->active = active;

	/* Description / email / client */
#define STR(f, n)\
	if(!d->u->f != !nfo->f || (nfo->f && d->u->f && strcmp(nfo->f, d->u->f) != 0)) {\
		free(d->u->f);\
		d->u->f = nfo->f;\
		nfo->f = NULL;\
		hub_user_update_field(d, n);\
	}
	STR(desc, HUBU_DESCRIPTION);
	STR(mail, HUBU_MAIL);
	STR(client, HUBU_CLIENT);
#undef STR

	/* Various numbers. These require that the numeric fields in nfo have the
	 * same type as those in the user struct. Otherwise some
	 * limiting/conversion may be necessary. */
#define NUM(uf, nf, n)\
	if(d->u->uf != nfo->nf) {\
		d->u->uf = nfo->nf;\
		hub_user_update_field(d, n);\
	}
	NUM(hnorm,     hn,    HUBU_HUBS);
	NUM(hreg,      hr,    HUBU_HUBS);
	NUM(hop,       ho,    HUBU_HUBS);
	NUM(slots,     slots, HUBU_SLOTS);
	NUM(sharesize, share, HUBU_SHARESIZE);
	NUM(as,        as,    HUBU_AS);
#undef NUM
}


static void hub_nmdc_myinfo_initnewuser(nmdc_myinfo_t *nfo, hub_user_update_t *d, int64_t uid) {
	d->u->id = uid;

	char *unick = nmdc_convert("UTF-8", hub_hub_encoding(d->h), nfo->nick, strlen(nfo->nick));
	d->u->nick = unick;
	if(strcmp(unick, nfo->nick) != 0) {
		d->u->n.nick = malloc(strlen(nfo->nick)+1);
		strcpy(d->u->n.nick, nfo->nick);
	}
	hub_user_update_field(d, HUBU_NICK);

	/* If we have some deferred info, we can merge it now */
	hub_nmdc_defer_t *def = hub_nmdc_defer_del(d->h, d->u->id);
	if(!def)
		return;
	if(def->op)
		hub_user_update_field(d, HUBU_FLAGS);
	if(!net_ip4_isany(def->ip4))
		hub_user_update_field(d, HUBU_IP4);
	if(!net_ip6_isany(def->ip6))
		hub_user_update_field(d, HUBU_IP6);
	d->u->op = def->op;
	d->u->ip4 = def->ip4;
	d->u->ip6 = def->ip6;
}


static void hub_nmdc_myinfo(hub_t *h, const char *cmd, int len) {
	nmdc_myinfo_t nfo;
	if(!nmdc_myinfo_parse(&nfo, hub_hub_encoding(h), cmd)) {
		nmdc_myinfo_free(&nfo);
		ywarn("%d: Invalid info format: %.*s", h->id, len, cmd);
		return;
	}
	hub_user_update_t d[1];
	int64_t uid = hub_nmdc_userid(h, nfo.nick, strlen(nfo.nick));
	hub_user_t *u = hub_users_get(h, uid);
	bool newuser = !u || !u->online;
	if(newuser)
		u = hub_user_new(false);
	hub_user_update_init(h, d, u);

	if(newuser)
		hub_nmdc_myinfo_initnewuser(&nfo, d, uid);
	hub_nmdc_myinfo_update(&nfo, d);

	hub_user_update_done(d, newuser);
	nmdc_myinfo_free(&nfo);

	/* User list completion detection: If this is a new user, reset the
	 * timeout. If this is an update to a user already in the list, then we
	 * must have received the complete list already. Note that some hubs
	 * (Flexhub and Verlihub) send our own $MyINFO twice, but the second one
	 * always comes at the end of the user list, so that's nice.  */
	if(newuser)
		hub_nmdc_userlist_activity(h);
	else
		hub_nmdc_userlist_done(h);
}


static void hub_nmdc_quit_reset(hub_t *h) {
	if(h->n.quituser != -1) {
		hub_nmdc_defer_del(h, h->n.quituser);
		if(!hub_user_left(h, h->n.quituser, h->n.quitinitiator, h->n.quitmessage ? h->n.quitmessage : ""))
			ywarn("%d: Quit for user not on the hub: %"PRIi64, h->id, h->n.quituser);
		h->n.quituser = -1;
		h->n.quitinitiator = -2;
		free(h->n.quitmessage);
		h->n.quitmessage = NULL;
		ev_timer_stop(EV_DEFAULT_UC_ &h->n.quittimer);
	}
}

static void hub_nmdc_quit(hub_t *h, const char *cmd, int len) {
	const char *nick = cmd + sizeof "$Quit";
	int nicklen = len - 1 - sizeof "$Quit";
	int64_t uid = hub_nmdc_userid(h, nick, nicklen);
	if(uid != h->n.quituser)
		hub_nmdc_quit_reset(h);
	if(uid) {
		h->n.quituser = uid;
		if(h->n.quitinitiator != -2)
			hub_nmdc_quit_reset(h);
		else {
			ev_timer_set(&h->n.quittimer, QUIT_TIMEOUT, 0.0);
			ev_timer_start(EV_DEFAULT_UC_ &h->n.quittimer);
		}
	}
}

static void hub_nmdc_quit_timeout(EV_P_ ev_timer *w, int revents) {
	hub_nmdc_quit_reset(w->data);
}


static void hub_nmdc_hello(hub_t *h, const char *cmd, int len) {
	const char *nick = cmd + sizeof "$Hello";
	int nicklen = len - 1 - sizeof "$Hello";
	int64_t uid = hub_nmdc_userid(h, nick, nicklen);

	/* Our own nick in the IDENTIFY state = we've successfully logged in */
	if(!uid && h->n.state & (HUBN_IDENTIFY|HUBN_VERIFY)) {
		h->n.state = HUBN_NORMAL;
		hub_hub_loggedin(h);
		hub_manager_settype(h, h->n.isreg ? HUBM_HREG : HUBM_HNORM);

		cmd_send(h, "$Version 1,0091|");
		hub_nmdc_sendinf(h);
		cmd_send(h, "$GetNickList|");
	}

	if(uid && !h->n.nogetinfo && !hub_users_get(h, uid))
		cmd_send(h, "$GetINFO %.*s %s|", nicklen, nick, h->n.nick);
}


static void hub_nmdc_to(hub_t *h, const char *cmd, int len) {
	const char *msg = cmd + sizeof "$To:";
	if(strncmp(msg, h->n.nick, strlen(h->n.nick)) != 0) {
		ywarn("%d: PM not intended for us: %.*s", h->id, len, cmd);
		return;
	}
	msg += strlen(h->n.nick);
	if(strncmp(msg, " From: ", 7) != 0) {
		ywarn("%d: Invalid PM message: %.*s", h->id, len, cmd);
		return;
	}
	msg += 7;

	int l = strcspn(msg, "$|");
	if(l <= 1 || msg[l] == '|' || msg[l-1] != ' ') {
		ywarn("%d: Invalid PM message: %.*s", h->id, len, cmd);
		return;
	}
	int64_t group = hub_nmdc_userid(h, msg, l-1);
	if(!hub_users_get(h, group))
		group = -1;
	msg += l+1;

	char *nick;
	int nicklen;
	bool me;
	const char *off = nmdc_chat_parse(msg, &nick, &nicklen, &me);
	int64_t uid = !nick ? -1 : hub_nmdc_userid(h, nick, nicklen);
	if(uid > 0 && !hub_users_get(h, uid)) {
		me = false;
		off = cmd;
	}

	char *message = nmdc_unescape(hub_hub_encoding(h), off, len-1-(off-cmd));
	hub_chat_message(h, group, uid, message, me);
	free(message);
}


static void hub_nmdc_userip_set(hub_t *h, int64_t uid, const char *ip) {
	hub_user_t *u = hub_users_get(h, uid);

	/* User is online, modify struct directly */
	if(u) {
		hub_user_update_t d;
		hub_user_update_init(h, &d, u);
		if(inet_pton(AF_INET, ip, &d.u->ip4) == 1)
			hub_user_update_field(&d, HUBU_IP4);
		else if(inet_pton(AF_INET6, ip, &d.u->ip6) == 1)
			hub_user_update_field(&d, HUBU_IP6);
		hub_user_update_done(&d, false);
		return;
	}

	/* Otherwise, defer this information */
	hub_nmdc_defer_t *def = hub_nmdc_defer_put(h, uid);
	if(inet_pton(AF_INET, ip, &def->ip4) != 1)
		inet_pton(AF_INET6, ip, &def->ip6);
}


static void hub_nmdc_userip(hub_t *h, const char *cmd, int len) {
	const char *lst = cmd + sizeof "$UserIP";
	char buf[40];
	while(*lst == ' ')
		lst++;
	while(*lst != '|') {
		const char *end = lst;
		while(*end != '|' && !(*end == '$' && end[1] == '$'))
			end++;
		if(lst == end) {
			end += *end == '|' ? 0 : 2;
			continue;
		}
		const char *sep = lst + strcspn(lst, " |");
		if(*sep == '|')
			return;
		int l = end-sep-1 > (int)sizeof(buf)-1 ? (int)sizeof(buf)-1 : end-sep-1;
		strncpy(buf, sep+1, l);
		buf[l] = 0;
		hub_nmdc_userip_set(h, hub_nmdc_userid(h, lst, sep-lst), buf);
		lst = end + (*end == '|' ? 0 : 2);
	}
}


static void hub_nmdc_oplist_set(hub_t *h, int64_t uid) {
	/* If *we* are OP, update our hub counts */
	if(uid == 0)
		hub_manager_settype(h, HUBM_HOP);

	/* User is online, modify struct directly */
	hub_user_t *u = hub_users_get(h, uid);
	if(u) {
		hub_user_update_t d;
		hub_user_update_init(h, &d, u);
		if(!d.u->op)
			hub_user_update_field(&d, HUBU_FLAGS);
		d.u->op = true;
		hub_user_update_done(&d, false);
		return;
	}

	/* Otherwise, defer this information */
	hub_nmdc_defer_put(h, uid)->op = true;
}


static void hub_nmdc_oplist(hub_t *h, const char *cmd, int len) {
	const char *lst = cmd + sizeof "$OpList";
	while(*lst == ' ')
		lst++;
	/* XXX: Strictly speaking, users *not* mentioned in the $OpList
	 * should have their ->op flag set to false. I'm not sure if OP
	 * status is ever removed from a user without reconnect, though. */
	while(*lst != '|') {
		const char *nickend = lst;
		while(*nickend != '|' && !(*nickend == '$' && nickend[1] == '$'))
			nickend++;
		if(lst == nickend) {
			nickend += *nickend == '|' ? 0 : 2;
			continue;
		}
		hub_nmdc_oplist_set(h, hub_nmdc_userid(h, lst, nickend-lst));
		lst = nickend + (*nickend == '|' ? 0 : 2);
	}
}


static void hub_nmdc_nicklist(hub_t *h, const char *cmd, int len) {
	const char *lst = cmd + sizeof "$NickList";
	/* Just ignore the $NickList if the hub supports NoGetINFO, since we should
	 * be receiving a $MyINFO for each user anyway. */
	if(h->n.nogetinfo)
		return;

	while(*lst == ' ')
		lst++;
	while(*lst != '|') {
		const char *nickend = lst;
		while(*nickend != '|' && !(*nickend == '$' && nickend[1] == '$'))
			nickend++;
		if(lst == nickend) {
			nickend += *nickend == '|' ? 0 : 2;
			continue;
		}
		hub_user_t *u = hub_users_get(h, hub_nmdc_userid(h, lst, nickend-lst));
		if(!u || !u->online)
			cmd_send(h, "$GetINFO %.*s %s|", (int)(nickend-lst), lst, h->n.nick);
		lst = nickend + (*nickend == '|' ? 0 : 2);
	}
}


static void hub_nmdc_hubname(hub_t *h, const char *cmd, int len) {
	cmd += sizeof "$HubName";
	len -= 1 + sizeof "$HubName";
	char *name = nmdc_unescape(hub_hub_encoding(h), cmd, len);
	hub_hub_setname(h, name);
	free(name);
}


static void hub_nmdc_hubtopic(hub_t *h, const char *cmd, int len) {
	cmd += sizeof "$HubTopic";
	len -= 1 + sizeof "$HubTopic";
	char *desc = nmdc_unescape(hub_hub_encoding(h), cmd, len);
	hub_hub_setdescription(h, desc);
	free(desc);
}


static void hub_nmdc_supports(hub_t *h, const char *cmd, int len) {
	const char *lst = cmd + sizeof "$Supports";
	int ilen = -1;
	do {
		lst += ilen+1;
		while(*lst == ' ')
			lst++;
		ilen = strcspn(lst, "| ");
		if(ilen == 9 && strncmp(lst, "NoGetINFO", 9) == 0) {
			h->n.nogetinfo = true;
			ydebug("%d: Hub supports NoGetINFO", h->id);
		}
	} while(lst[ilen] == ' ');
}


static void hub_nmdc_getpass(hub_t *h, const char *cmd, int len) {
	const char *passwd = hub_hub_mypassword(h);
	if(!passwd || !*passwd) {
		yerror("%d: Hub requires a password", h->id);
		hub_hub_seterror(h, 0, "NeedPassword", "Hub requires a password", NULL);
		return;
	}
	cmd_send(h, "$MyPass %s|", passwd);
	h->n.isreg = true;
	h->n.state = HUBN_VERIFY;
}


static void hub_nmdc_validatedenide(hub_t *h, const char *cmd, int len) {
	hub_hub_seterror(h, HUBCD_RECONNECT, "InvalidNick", "Username invalid or already taken", NULL);
}


static void hub_nmdc_hubisfull(hub_t *h, const char *cmd, int len) {
	hub_hub_seterror(h, HUBCD_RECONNECT, "Full", "Hub is full", NULL);
}


static void hub_nmdc_forcemove(hub_t *h, const char *cmd, int len) {
	cmd += sizeof "$ForceMove";
	len -= 1 + sizeof "$ForceMove";
	char *addr = nmdc_unescape(hub_hub_encoding(h), cmd, len);
	hub_hub_seterror(h, 0, "Redirect", "Redirect", addr);
	free(addr);
}


static void hub_nmdc_badpass(hub_t *h, const char *cmd, int len) {
	hub_hub_seterror(h, 0, "InvalidPassword", "Incorrect password", NULL);
}


static void hub_nmdc_logedin(hub_t *h, const char *cmd, int len) {
	hub_manager_settype(h, HUBM_HOP);
}


static void hub_nmdc_mainchat(hub_t *h, const char *cmd, int len) {
	char *nick;
	int nicklen;
	bool me;
	const char *off = nmdc_chat_parse(cmd, &nick, &nicklen, &me);
	int64_t uid = !nick ? -1 : hub_nmdc_userid(h, nick, nicklen);
	if(uid > 0 && !hub_users_get(h, uid)) {
		me = false;
		off = cmd;
		uid = -1;
	}

	char *msg = nmdc_unescape(hub_hub_encoding(h), off, len-1-(off-cmd));

	/* Handle "is kicking $x because" messages */
	bool iskick = false;
	if(!me && strncmp(msg, "is kicking ", 11) == 0) {
		off = msg + 11;
		nicklen = strcspn(off, " |");
		int64_t quituser = hub_nmdc_userid(h, off, nicklen);
		off += nicklen;
		while(*off == ' ')
			off++;
		if(strncmp(off, "because:", 8) == 0) {
			off += 8;
			while(*off == ' ')
				off++;
			iskick = true;
			if(h->n.quituser != quituser)
				hub_nmdc_quit_reset(h);
			h->n.quitinitiator = uid;
			h->n.quitmessage = strdup(off);
			if(h->n.quituser != -2)
				hub_nmdc_quit_reset(h);
			else {
				ev_timer_set(&h->n.quittimer, QUIT_TIMEOUT, 0.0);
				ev_timer_start(EV_DEFAULT_UC_ &h->n.quittimer);
				h->n.quituser = quituser;
			}
		}
	}

	if(!iskick)
		hub_chat_message(h, -1, uid, msg, me);

	free(msg);
}


static void hub_nmdc_lock(hub_t *h, const char *cmd, int len) {
	const char *lock = cmd + sizeof "$Lock";
	while(*lock == ' ')
		lock++;
	int locklen = strcspn(lock, " |");
	if(locklen <= 3) {
		ywarn("%d: Too short lock string: %.*s", h->id, len, cmd);
		return;
	}

	if(strncmp(lock, "EXTENDEDPROTOCOL", 16) == 0)
		cmd_send(h, "$Supports NoGetINFO NoHello UserIP2|");

	char *key = nmdc_lock2key(lock, locklen);
	cmd_send(h, "$Key %s|", key);
	free(key);

	cmd_send(h, "$ValidateNick %s|", h->n.nick);
	h->n.state = HUBN_IDENTIFY;
}


static void hub_nmdc_handle(hub_t *h, const char *cmd, int len) {
	static const struct {
		const char *prefix;
		int states;
		void (*func)(hub_t *, const char *, int);
	} cmds[] = {
		{ "$MyINFO $ALL ",    HUBN_NORMAL,                          hub_nmdc_myinfo         },
		{ "$Quit ",           HUBN_NORMAL,                          hub_nmdc_quit           },
		{ "$Hello ",          HUBN_IDENTIFY|HUBN_VERIFY|HUBN_NORMAL,hub_nmdc_hello          },
		{ "$To: ",            HUBN_IDENTIFY|HUBN_VERIFY|HUBN_NORMAL,hub_nmdc_to             },
		{ "$UserIP ",         HUBN_IDENTIFY|HUBN_VERIFY|HUBN_NORMAL,hub_nmdc_userip         },
		{ "$OpList ",         HUBN_NORMAL,                          hub_nmdc_oplist         },
		{ "$NickList ",       HUBN_NORMAL,                          hub_nmdc_nicklist       },
		{ "$Lock ",           HUBN_LOCK,                            hub_nmdc_lock           },
		{ "$HubName ",        0,                                    hub_nmdc_hubname        },
		{ "$HubTopic ",       0,                                    hub_nmdc_hubtopic       },
		{ "$Supports ",       HUBN_IDENTIFY|HUBN_VERIFY|HUBN_NORMAL,hub_nmdc_supports       },
		{ "$GetPass",         HUBN_IDENTIFY,                        hub_nmdc_getpass        },
		{ "$ValidateDenide",  HUBN_IDENTIFY|HUBN_VERIFY,            hub_nmdc_validatedenide },
		{ "$HubIsFull",       HUBN_IDENTIFY|HUBN_VERIFY,            hub_nmdc_hubisfull      },
		{ "$ForceMove",       0,                                    hub_nmdc_forcemove      },
		{ "$BadPass",         HUBN_VERIFY,                          hub_nmdc_badpass        },
		{ "$LogedIn",         HUBN_NORMAL,                          hub_nmdc_logedin        }
	};

	/* Empty command */
	if(len == 1)
		return;

	/* Main chat message */
	if(*cmd != '$') {
		hub_nmdc_mainchat(h, cmd, len);
		return;
	}

	int i, l;
	for(i=0; i<(int)(sizeof(cmds)/sizeof(*cmds)); i++) {
		l = strlen(cmds[i].prefix);
		if(len >= l && strncmp(cmd, cmds[i].prefix, l) == 0)
			break;
	}
	if(i == (int)(sizeof(cmds)/sizeof(*cmds))) {
		yinfo("%d: Unhandled command: %.*s", h->id, len, cmd);
		return;
	}
	if(cmds[i].states && !(h->n.state & cmds[i].states)) {
		ywarn("%d: Command received in wrong state: %.*s", h->id, len, cmd);
		return;
	}
	cmds[i].func(h, cmd, len);
}


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


static bool hub_nmdc_chat(hub_t *h, hub_user_t *u, const char *message, bool me) {
	if(hub_conn_state(h) != HUBC_CONN || h->n.state != HUBN_NORMAL)
		return false;
	char *enc = nmdc_escape(hub_hub_encoding(h), message, -1);
	if(!u)
		cmd_send(h, "<%s> %s%s|", h->n.nick, me ? "/me " : "", enc);
	else
		cmd_send(h, "$To: %s From: %s $<%s> %s%s|", u->n.nick ? u->n.nick : u->nick, h->n.nick, h->n.nick, me ? "/me " : "", enc);
	free(enc);

	/* Emulate protocol echo for PMs */
	if(u)
		hub_chat_message(h, u->id, 0, message, me);
	return true;
}


static int hub_nmdc_read(hub_t *h, const char *buf, int oldlen, int len) {
	int con = 0;
	char *next;
	if((next = memchr(buf+oldlen, '|', len-oldlen)) == NULL)
		return 0;

	do {
		ydebug("%d: Received message: %.*s", h->id, (int)(next-buf+1), buf);
		hub_nmdc_handle(h, buf, next-buf+1);
		con += next-buf+1;
		buf = next+1;
	} while(hub_conn_state(h) == HUBC_CONN && (next = memchr(buf, '|', len-con)) != NULL);

	return con;
}


static void hub_nmdc_connected(hub_t *h) {
	h->n.state = HUBN_LOCK;
	h->n.isreg = false;
	h->n.nogetinfo = false;
	h->n.listcomplete = false;
	h->n.lastinfo = NULL;
	h->n.nick = nmdc_convert(hub_hub_encoding(h), "UTF-8", hub_hub_mynick(h), -1);

	h->n.defer = kh_init(nmdcdefer);

	ev_init(&h->n.listtimer, hub_nmdc_userlist_timeout);
	h->n.listtimer.data = h;

	h->n.quituser = -1;
	h->n.quitinitiator = -2;
	h->n.quitmessage = NULL;
	ev_init(&h->n.quittimer, hub_nmdc_quit_timeout);
	h->n.quittimer.data = h;
}


static void hub_nmdc_disconnected(hub_t *h) {
	free(h->n.nick);
	free(h->n.lastinfo);
	free(h->n.quitmessage);
	kh_destroy(nmdcdefer, h->n.defer);
	hub_manager_settype(h, HUBM_HNONE);
	ev_timer_stop(EV_DEFAULT_UC_ &h->n.listtimer);
	ev_timer_stop(EV_DEFAULT_UC_ &h->n.quittimer);
}


const hub_proto_t hub_nmdc = {
	hub_nmdc_connected,
	hub_nmdc_disconnected,
	hub_nmdc_sendinf,
	hub_nmdc_sendkeepalive,
	hub_nmdc_chat,
	hub_nmdc_read
};

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