summaryrefslogtreecommitdiff
path: root/src/hub/users.c
blob: 40c951629d6118c2318c25d63dbf94638d38a9c4 (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
/* 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>


/* Delay between user list sweeps. A "sweep" walks through the userlist and
 * removes users that have had a zero reference count for at least one sweep
 * period. */
#define SWEEP_TIMEOUT 30.0



static const char *field_type(hub_user_field_t num) {
	switch(num) {
#define F(i, n, t) case HUBU_##n: return t; break;
		HUBU_FIELDS
#undef F
	}
	yerror("Unknown field number: %d", num);
	return NULL;
}


static bool field_known(uint16_t num) {
	switch(num) {
#define F(i, n, t) case i:
		HUBU_FIELDS
#undef F
		return true;
	}
	return false;
}


/* ID -> user lookup table */
#define hub_user_hash(a) ((khint_t)(a)->id)
#define hub_user_equal(a, b) ((a)->id == (b)->id)
__KHASH_IMPL(userlist, static kh_inline, hub_user_t *, char, 0, hub_user_hash, hub_user_equal);


hub_user_t *hub_user_new(bool adc) {
	hub_user_t *u;
	u = calloc(1, adc ? offsetof(hub_user_t, a) + sizeof((*u).a) : offsetof(hub_user_t, n) + sizeof((*u).n));
	u->adc = adc;
	u->id = -1;
	u->online = true;
	u->ref = 1;
	u->ip4.s_addr = INADDR_ANY;
	memcpy(&u->ip6, &in6addr_any, sizeof(struct in6_addr));
	return u;
}


static void hub_user_free(hub_user_t *u) {
	free(u->nick);
	free(u->desc);
	free(u->mail);
	free(u->client);
	if(!u->adc)
		free(u->n.nick);
	free(u);
}


void hub_user_ref(hub_user_t *u) {
	u->ref++;
}


void hub_user_unref(hub_t *h, hub_user_t *u) {
	u->ref--;
	assert(u->ref != UINT32_MAX);
	u->delmark = !h->u.delmark;
	h->u.needsweep = true;
}


int64_t hub_users_genid(hub_t *h, const char *data, int len) {
	uint8_t res[32]; /* 256 bits for SHA-256 */
	char *buf = malloc(len + sizeof(h->u.idsalt));
	memcpy(buf, h->u.idsalt, sizeof(h->u.idsalt));
	memcpy(buf+sizeof(h->u.idsalt), data, len);
	crypt_sha256(buf, len + sizeof(h->u.idsalt), res);
	free(buf);
	/* Construct the ID by taking 8 bytes from the hash, discarding one bit to
	 * ensure that the result fits in a positive signed 64-bit integer and uses
	 * its entire range. It shouldn't really matter which bytes we use, but,
	 * just to be different, let's shuffle them a bit. */
#define X(i,s) (((uint64_t)res[i]) << ((uint64_t)(s*8)))
	int64_t v = (X(6,7) | X(25,6) | X(28,5) | X(19,4) | X(10,3) | X(14,2) | X(30,1) | X(7,0)) >> 1;
#undef X
	/* 0 is reserved for self. This condition increases the probability of a
	 * collision for the '1' id, but that is unavoidable. */
	return v == 0 ? 1 : v;
}


static void hub_users_sweep(EV_P_ ev_timer *w, int revents) {
	hub_t *h = w->data;
	if(!h->u.needsweep)
		return;
	h->u.needsweep = false;

	khiter_t k;
	for(k=kh_begin(h->u.list); k != kh_end(h->u.list); k++) {
		if(!kh_exist(h->u.list, k))
			continue;
		hub_user_t *u = kh_key(h->u.list, k);
		if(u->ref > 0)
			continue;
		if(u->delmark == h->u.delmark) {
			kh_del(userlist, h->u.list, k);
			hub_user_free(u);
		} else
			h->u.needsweep = true; /* For next time */
	}
	h->u.delmark = !h->u.delmark;
}


/* Ownership of *u is transfered to the list.  Returns true on success, false
 * if there was a collision - in which case the user object is freed. */
static bool hub_user_add(hub_t *h, hub_user_t *u) {
	int r;
	khiter_t k;
	assert(u->ref == 1);

	k = kh_put(userlist, h->u.list, u, &r);
	if(r != 0) {
		kh_key(h->u.list, k) = u;
		return true;
	}

	/* User with that ID already exists. This can happen in two cases:
	 * 1. The user has left the hub earlier but hasn't been deleted in a sweep
	 *    yet, or still has ref > 0.
	 * 2, There is a collision on the user id and the other user is still
	 *    online.
	 * In case (1), we delete the old user and put the new one in place,
	 * copying the reference count.
	 * In case (2), we free the new user and pretend that it was never added.
	 */
	hub_user_t *oldu = kh_key(h->u.list, k);
	if(!oldu->online) { /* case (1) */
		u->ref += oldu->ref;
		hub_user_free(oldu);
		kh_key(h->u.list, k) = u;
		return false;
	}

	/* case (2) */
	ywarn("%d: User ID collision between %s and %s (%"PRId64")", h->id, u->nick, oldu->nick, u->id);
	hub_user_free(u);
	return false;
}


/* Appends a struct variant with user info to *iter. */
static void hub_users_append_struct(hub_user_t *u, uint16_t *fields, int num, DBusMessageIter *iter) {
	int i;
	uint32_t u32;
	char *emptystr = "";
	char buf[50];
	const char *strp;
	kstring_t sig =  {};
	DBusMessageIter variant, obj, tmp;

	/* Special case num == 0 */
	if(!num) {
		dbus_bool_t b = 1;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, "b", &variant);
		dbus_message_iter_append_basic(&variant, DBUS_TYPE_BOOLEAN, &b);
		dbus_message_iter_close_container(iter, &variant);
		return;
	}

	/* Construct type signature and open containers */
	kputc('(', &sig);
	for(i=0; i<num; i++)
		kputs(field_type(fields[i]), &sig);
	kputc(')', &sig);
	dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, sig.s, &variant);
	free(sig.s);
	dbus_message_iter_open_container(&variant, DBUS_TYPE_STRUCT, NULL, &obj);

	for(i=0; i<num; i++) {
		switch((hub_user_field_t)fields[i]) {
		case HUBU_NICK:        dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, u->nick   ? &u->nick   : &emptystr); break;
		case HUBU_DESCRIPTION: dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, u->desc   ? &u->desc   : &emptystr); break;
		case HUBU_CLIENT:      dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, u->client ? &u->client : &emptystr); break;
		case HUBU_MAIL:        dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, u->mail   ? &u->mail   : &emptystr); break;
		case HUBU_SLOTS:       u32 = u->slots; dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT32, &u32); break;
		case HUBU_SHAREDFILES: dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT32, &u->sharedfiles);   break;
		case HUBU_SHARESIZE:   dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT64, &u->sharesize);   break;
		case HUBU_CONN:        dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT32, &u->conn);   break;
		case HUBU_HUBS:
			dbus_message_iter_open_container(&obj, DBUS_TYPE_STRUCT, NULL, &tmp);
			u32 = u->hnorm; dbus_message_iter_append_basic(&tmp, DBUS_TYPE_UINT32, &u32);
			u32 = u->hreg;  dbus_message_iter_append_basic(&tmp, DBUS_TYPE_UINT32, &u32);
			u32 = u->hop;   dbus_message_iter_append_basic(&tmp, DBUS_TYPE_UINT32, &u32);
			dbus_message_iter_close_container(&obj, &tmp);
			break;
		case HUBU_IP4:
			strp = net_ip4_isany(u->ip4) ? "" : inet_ntop(AF_INET, &u->ip4, buf, sizeof(buf));
			dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, &strp);
			break;
		case HUBU_IP6:
			strp = net_ip6_isany(u->ip6) ? "" : inet_ntop(AF_INET6, &u->ip6, buf, sizeof(buf));
			dbus_message_iter_append_basic(&obj, DBUS_TYPE_STRING, &strp);
			break;
		case HUBU_AS: dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT32, &u->as); break;
		case HUBU_CID:
			dbus_message_iter_open_container(&obj, DBUS_TYPE_ARRAY, "y", &tmp);
			if(u->adc) {
				strp = u->a.cid;
				dbus_message_iter_append_fixed_array(&tmp, DBUS_TYPE_BYTE, &strp, sizeof(u->a.cid));
			}
			dbus_message_iter_close_container(&obj, &tmp);
			break;
		case HUBU_FLAGS:
			u32 = (u->online?1:0) | (u->away?2:0) | (u->op?4:0) | (u->tls?8:0) | (u->active?16:0);
			dbus_message_iter_append_basic(&obj, DBUS_TYPE_UINT32, &u32);
			break;
		}
	}

	dbus_message_iter_close_container(&variant, &obj);
	dbus_message_iter_close_container(iter, &variant);
}


void hub_user_update_init(hub_t *h, hub_user_update_t *d, hub_user_t *user) {
	assert(user->online);
	d->changenum = 0;
	d->u = user;
	d->h = h;
	d->oldsharesize = user->sharesize;
}


void hub_user_update_field(hub_user_update_t *d, hub_user_field_t field) {
	int i;

	for(i=0; i<d->changenum; i++)
		if(d->changes[i] == field)
			break;
	if(i == d->changenum) {
		assert(d->changenum < HUBU_FIELDNUM);
		d->changes[d->changenum++] = field;
	}
}


void hub_user_update_done(hub_user_update_t *d, bool newuser) {
	hub_t *h = d->h;
	assert(d->u->id >= 0);

	if(newuser)
		hub_user_add(h, d->u);

	if(h->u.props.UserListComplete && d->changenum > 0) {
		DBusMessage *sig = dbus_message_new_signal(h->dbo.path, "net.blicky.Globster.HubUsers", newuser ? "UserJoined" : "UserChanged");
		DBusMessageIter i1, i2;
		uint16_t *v = d->changes;
		dbus_message_iter_init_append(sig, &i1);
		dbus_message_iter_append_basic(&i1, DBUS_TYPE_INT64, &d->u->id);
		dbus_message_iter_open_container(&i1, DBUS_TYPE_ARRAY, "q", &i2);
		dbus_message_iter_append_fixed_array(&i2, DBUS_TYPE_UINT16, &v, d->changenum);
		dbus_message_iter_close_container(&i1, &i2);
		hub_users_append_struct(d->u, d->changes, d->changenum, &i1);
		dbo_sendfree(sig);
	}

	dbo_prop_changed_t props = {};
	if(newuser)
		dbo_hubu_UserCount_set_batch(&props, &h->u.props, h->u.props.UserCount+1);
	if(d->oldsharesize != d->u->sharesize)
		dbo_hubu_UserShareSize_set_batch(&props, &h->u.props,
			h->u.props.UserShareSize - d->oldsharesize + d->u->sharesize);
	if(h->u.props.UserListComplete)
		dbo_prop_changed(props, h, &dbo_hubu_interface, &h->u.props);
}


bool hub_user_left(hub_t *h, int64_t id, int64_t initiator, const char *message) {
	hub_user_t *u = hub_users_get(h, id);
	if(!u || !u->online)
		return false;

	dbo_prop_changed_t props = {};
	if(h->u.props.UserCount > 0)
		dbo_hubu_UserCount_set_batch(&props, &h->u.props, h->u.props.UserCount-1);
	if(h->u.props.UserShareSize > 0)
		dbo_hubu_UserShareSize_set_batch(&props, &h->u.props, h->u.props.UserShareSize-u->sharesize);

	if(h->u.props.UserListComplete) {
		dbo_hubu_UserLeft_signal(h, id, initiator, message);
		dbo_prop_changed(props, h, &dbo_hubu_interface, &h->u.props);
	}

	u->online = false;
	hub_user_unref(h, u);
	return true;
}


hub_user_t *hub_users_get(hub_t *h, int64_t id) {
	hub_user_t key = {};
	key.id = id;
	khiter_t k = kh_get(userlist, h->u.list, &key);
	return k == kh_end(h->u.list) ? NULL : kh_key(h->u.list, k);
}


/* Called by hub/proto when the user list has been completely fetched */
void hub_users_listcomplete(hub_t *h) {
	ydebug("%d: User list complete", h->id);

	dbo_prop_changed_t props = {};
	dbo_hubu_UserListComplete_set_batch(&props, &h->u.props, true);
	dbo_hubu_UserCount_add_batch(&props);
	dbo_hubu_UserShareSize_add_batch(&props);
	dbo_prop_changed(props, h, &dbo_hubu_interface, &h->u.props);
}


#define appenddict(u) do {\
		dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2);\
		dbus_message_iter_append_basic(&sub2, DBUS_TYPE_INT64, &(u)->id);\
		hub_users_append_struct((u), fields, numfields, &sub2);\
		dbus_message_iter_close_container(&sub, &sub2);\
	} while(0)

static void UserInfo(hub_t *h, DBusMessage *msg, int64_t user, DBusMessageIter *arg) {
	DBusMessageIter top, sub, sub2;
	uint16_t *argfields, fields[HUBU_FIELDNUM];
	int i, j, argnumfields, numfields = 0;

	dbus_message_iter_recurse(arg, &sub);
	dbus_message_iter_get_fixed_array(&sub, &argfields, &argnumfields);
	for(i=0; i<argnumfields; i++) {
		/* Ignore duplicate or unknown field */
		for(j=0; j<numfields; j++)
			if(fields[j] == argfields[i])
				break;
		if(j < numfields || !field_known(argfields[i]))
			continue;
		assert(numfields < HUBU_FIELDNUM);
		fields[numfields++] = argfields[i];
	}
	argfields = fields;

	DBusMessage *reply = dbus_message_new_method_return(msg);
	dbus_message_iter_init_append(reply, &top);
	dbus_message_iter_open_container(&top, DBUS_TYPE_ARRAY, "q", &sub);
	dbus_message_iter_append_fixed_array(&sub, DBUS_TYPE_UINT16, &argfields, numfields);
	dbus_message_iter_close_container(&top, &sub);
	dbus_message_iter_open_container(&top, DBUS_TYPE_ARRAY, "{xv}", &sub);

	khiter_t k;
	if(user >= 0) {
		hub_user_t key = {};
		key.id = user;
		k = kh_get(userlist, h->u.list, &key);
		if(k != kh_end(h->u.list))
			appenddict(kh_key(h->u.list, k));
	} else {
		for(k=kh_begin(h->u.list); k != kh_end(h->u.list); k++)
			if(kh_exist(h->u.list, k))
				appenddict(kh_key(h->u.list, k));
	}

	dbus_message_iter_close_container(&top, &sub);
	dbo_sendfree(reply);
}

#undef appenddict


void hub_users_disconnected(hub_t *h) {
	khiter_t k;

	dbo_prop_changed_t props = {};
	dbo_hubu_UserCount_set_batch(&props, &h->u.props, 0);
	dbo_hubu_UserShareSize_set_batch(&props, &h->u.props, 0);
	dbo_hubu_UserListComplete_set_batch(&props, &h->u.props, false);
	dbo_prop_changed(props, h, &dbo_hubu_interface, &h->u.props);

	for(k=kh_begin(h->u.list); k != kh_end(h->u.list); k++)
		if(kh_exist(h->u.list, k))
			hub_user_left(h, kh_key(h->u.list, k)->id, -2, "");
}


void hub_users_init(hub_t *h, const char *salt) {
	h->u.delmark = true;
	h->u.needsweep = false;
	h->u.list = kh_init(userlist);

	if(salt)
		base32_decode(salt, h->u.idsalt, sizeof(h->u.idsalt));
	else {
		crypt_rnd(h->u.idsalt, sizeof(h->u.idsalt));
		char *buf = malloc(53); /* assumes sizeof(h->u.idsalt) <= 32 */
		base32_encode(h->u.idsalt, buf, sizeof(h->u.idsalt));
		hub_hub_setvar(h, "UserIDSalt", sqlasync_text(SQLASYNC_FREE, buf));
	}

	ev_timer_init(&h->u.sweep, hub_users_sweep, SWEEP_TIMEOUT, SWEEP_TIMEOUT);
	h->u.sweep.data = h;
	ev_timer_start(EV_DEFAULT_UC_ &h->u.sweep);

	h->u.props.UserListComplete = false;
	h->u.props.UserShareSize = 0;
	h->u.props.UserCount = 0;
}


void hub_users_shutdown(hub_t *h) {
	ev_timer_stop(EV_DEFAULT_UC_ &h->u.sweep);
}


void hub_users_destroy(hub_t *h) {
	hub_users_shutdown(h);
	khiter_t k;
	for(k=kh_begin(h->u.list); k != kh_end(h->u.list); k++)
		if(kh_exist(h->u.list, k))
			hub_user_free(kh_key(h->u.list, k));

	kh_destroy(userlist, h->u.list);
}

const hub_users_vt_t hub_users_vt = dbo_hubu_funcs();


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