summaryrefslogtreecommitdiff
path: root/src/query.c
blob: 6cc256a443ad85f0d266c2aa773cd512dfb83e22 (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
#include "query.h"
#include "benc.h"
#include "log.h"
#include "peers.h"
#include "sha256.h"

#include <string.h>
#include <errno.h>
#include <assert.h>
#include <arpa/inet.h>

int handle_request(struct nodeid* self, struct tokens *tokens, time_t now, const char* method, const struct sockaddr* src, socklen_t src_len, const char* packet, size_t packet_len, char** response, size_t response_len) {
	if(strcmp(method, "ping") == 0) {
		struct bcursor bcursor;
		struct benc_node stream[256];
		bcur_open(&bcursor, packet, packet+packet_len, stream, 256);

		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Packet is not a dict");
			return QUERY_EBADQ;
		}
		if(bcur_next(&bcursor, 1) < 0) {
			err("Bad query: No token after outer dict start");
			return QUERY_EBADQ;
		}

		if(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"a"}, (const size_t[]){1}, 1) != 0) {
			err("Bad query: No arguments to request");
			return QUERY_EBADQ;
		}
		bcur_next(&bcursor, 1);
		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Wrong value type for request");
			return QUERY_EBADQ;
		}
		// Skip the dict element
		bcur_next(&bcursor, 1);
		bool source_set = false;
		struct nodeid source_id;
		while(bcursor.readhead->type != BNT_END) {
			switch(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"id"}, (const size_t[]){6}, 1)) {
				case 0:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_STRING) {
						err("Bad query: Wrong value type for id");
						return QUERY_EBADQ;
					}

					if(bcursor.readhead->size != 20) {
						err("Bad query: Incorrect id length");
						return QUERY_EBADQ;
					}

					source_set = true;
					memcpy(&source_id, bcursor.readhead->loc, 20);

					// Skip the value
					bcur_next(&bcursor, 1);
					break;
			}
		}

		if(!source_set) {
			err("Id argument not set");
			return QUERY_EBADQ;
		}

		char* end = (*response) + response_len;

		int rc = snprintf(*response, end-*response, "d2:id20:");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		memcpy(*response, self, sizeof(struct nodeid));
		*response += sizeof(struct nodeid);
		rc = snprintf(*response, end-*response, "e");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
	} else if(strcmp(method, "find_node") == 0) {
		struct bcursor bcursor;
		struct benc_node stream[256];
		bcur_open(&bcursor, packet, packet+packet_len, stream, 256);

		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Packet is not a dict");
			return QUERY_EBADQ;
		}
		if(bcur_next(&bcursor, 1) < 0) {
			err("Bad query: No token after outer dict start");
			return QUERY_EBADQ;
		}

		if(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"a"}, (const size_t[]){1}, 1) != 0) {
			err("Bad query: No arguments to request");
			return QUERY_EBADQ;
		}
		bcur_next(&bcursor, 1);
		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Wrong value type for request");
			return QUERY_EBADQ;
		}
		// Skip the dict element
		bcur_next(&bcursor, 1);
		bool target_set = false;
		struct nodeid target;
		while(bcursor.readhead->type != BNT_END) {
			switch(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"target"}, (const size_t[]){6}, 1)) {
				case 0:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_STRING) {
						err("Bad query: Wrong value type for id");
						return QUERY_EBADQ;
					}

					if(bcursor.readhead->size != 20) {
						err("Bad query: Incorrect target length");
						return QUERY_EBADQ;
					}

					target_set = true;
					memcpy(&target, bcursor.readhead->loc, 20);

					// Skip the value
					bcur_next(&bcursor, 1);
					break;
			}
		}

		if(!target_set) {
			err("Target argument not set");
			return QUERY_EBADQ;
		}

		// Actually do the handling
		struct entry* closest[8];
		int found = routing_closest(&target, 8, closest);

		char* end = (*response) + response_len;

		int rc = snprintf(*response, end-*response, "d2:id20:");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);

		memcpy(*response, self, sizeof(struct nodeid));
		*response += sizeof(struct nodeid);
		assert(*response < end);

		rc = snprintf(*response, end-*response, "5:nodes%d:", found*26);
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);

		for(int i = 0; i < found; i++) {
			memcpy(*response, &closest[i]->id, sizeof(struct nodeid));
			*response += sizeof(struct nodeid); // 20
			assert(*response < end);
			memcpy(*response, &closest[i]->addr.ip, sizeof(uint32_t));
			*response += sizeof(uint32_t); // 4
			assert(*response < end);
			memcpy(*response, &closest[i]->addr.port, sizeof(uint16_t));
			*response += sizeof(uint16_t); // 2
			assert(*response < end);
		}

		rc = snprintf(*response, end-*response, "e");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);
	} else if(strcmp(method, "get_peers") == 0) {
		struct bcursor bcursor;
		struct benc_node stream[256];
		bcur_open(&bcursor, packet, packet+packet_len, stream, 256);

		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Packet is not a dict");
			return QUERY_EBADQ;
		}
		if(bcur_next(&bcursor, 1) < 0) {
			err("Bad query: No token after outer dict start");
			return QUERY_EBADQ;
		}

		if(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"a"}, (const size_t[]){1}, 1) != 0) {
			err("Bad query: No arguments to request");
			return QUERY_EBADQ;
		}
		bcur_next(&bcursor, 1);
		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Wrong value type for request");
			return QUERY_EBADQ;
		}
		// Skip the dict element
		bcur_next(&bcursor, 1);
		bool infohash_set = false;
		struct infohash infohash;
		while(bcursor.readhead->type != BNT_END) {
			switch(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"info_hash"}, (const size_t[]){9}, 1)) {
				case 0:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_STRING) {
						err("Bad query: Wrong value type for info_hash");
						return QUERY_EBADQ;
					}

					if(bcursor.readhead->size != 20) {
						err("Bad query: Incorrect target length");
						return QUERY_EBADQ;
					}

					infohash_set = true;
					memcpy(&infohash, bcursor.readhead->loc, 20);

					// Skip the value
					bcur_next(&bcursor, 1);
					break;
			}
		}

		if(!infohash_set) {
			err("info_hash argument not provided");
			return QUERY_EBADQ;
		}

		struct addr src_addr;
		{
			struct sockaddr_in* ipv4 = (struct sockaddr_in*)src;
			src_addr.ip = ipv4->sin_addr.s_addr;
			src_addr.port = ipv4->sin_port;
		}

		char* end = (*response) + response_len;

		int rc = snprintf(*response, end-*response, "d2:id20:");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);

		memcpy(*response, self, sizeof(struct nodeid));
		*response += sizeof(struct nodeid);
		assert(*response < end);

		struct addr* peers;
		size_t peers_len;
		get_peers(&infohash, &peers, &peers_len);

		char token[SHA256_BLOCK_SIZE];
		token_create(tokens, now, &src_addr, token);

		if(peers != NULL) {
			rc = snprintf(*response, end-*response, "5:token%ld:%.*s", sizeof(token), (int)sizeof(token), token);
			if(rc < 0)
				return QUERY_EBADQ;
			*response += rc;
			assert(*response < end);

			rc = snprintf(*response, end-*response, "6:valuesl");
			if(rc < 0)
				return QUERY_EBADQ;
			*response += rc;
			assert(*response < end);

			for(int i = 0; i < peers_len; i++) {
				*(*response) = '6';
				*(*response+1) = ':';
				(*response) += 2;
				memcpy(*response, &peers[i].ip, sizeof(uint32_t));
				*response += sizeof(uint32_t); // 4
				assert(*response < end);
				memcpy(*response, &peers[i].port, sizeof(uint16_t));
				*response += sizeof(uint16_t); // 2
				assert(*response < end);
			}

			(**response) = 'e';
			(*response)++;
			assert(*response < end);
		} else {
			// If we didn't get any peers we send back the closest nodes
			struct entry* closest[8];
			int found = routing_closest((struct nodeid*)&infohash, 8, closest);

			rc = snprintf(*response, end-*response, "5:nodes%d:", found*26);
			if(rc < 0)
				return QUERY_EBADQ;
			*response += rc;
			assert(*response < end);

			for(int i = 0; i < found; i++) {
				memcpy(*response, &closest[i]->id, sizeof(struct nodeid));
				*response += sizeof(struct nodeid); // 20
				assert(*response < end);
				memcpy(*response, &closest[i]->addr.ip, sizeof(uint32_t));
				*response += sizeof(uint32_t); // 4
				assert(*response < end);
				memcpy(*response, &closest[i]->addr.port, sizeof(uint16_t));
				*response += sizeof(uint16_t); // 2
				assert(*response < end);
			}

			int pos;
			rc = snprintf(*response, end-*response, "5:token%ld:%n%*s", sizeof(token), &pos, (int)sizeof(token), " ");
			memcpy((*response) + pos, token, sizeof(token));
			if(rc < 0)
				return QUERY_EBADQ;
			*response += rc;
			assert(*response < end);
		}

		rc = snprintf(*response, end-*response, "e");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);
	} else if(strcmp(method, "announce_peer") == 0) {
		struct bcursor bcursor;
		struct benc_node stream[256];
		bcur_open(&bcursor, packet, packet+packet_len, stream, 256);

		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Packet is not a dict");
			return QUERY_EBADQ;
		}
		if(bcur_next(&bcursor, 1) < 0) {
			err("Bad query: No token after outer dict start");
			return QUERY_EBADQ;
		}

		if(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING}, (const char*[]){"a"}, (const size_t[]){1}, 1) != 0) {
			err("Bad query: No arguments to request");
			return QUERY_EBADQ;
		}
		bcur_next(&bcursor, 1);
		if(bcursor.readhead->type != BNT_DICT) {
			err("Bad query: Wrong value type for request");
			return QUERY_EBADQ;
		}
		// Skip the dict element
		bcur_next(&bcursor, 1);

		bool implied_port = false;

		bool infohash_set = false;
		struct infohash infohash;

		bool port_set = false;
		uint16_t port;

		bool token_set = false;
		char token[SHA256_BLOCK_SIZE];

		while(bcursor.readhead->type != BNT_END) {
			switch(bcur_find_key(&bcursor, (const enum benc_nodetype[]){BNT_STRING, BNT_STRING, BNT_STRING, BNT_STRING}, (const char*[]){"implied_port", "info_hash", "port", "token"}, (const size_t[]){12, 9, 4, 5}, 4)) {
				case 0:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_INT) {
						err("Bad query: Wrong value type for implied_port");
						return QUERY_EBADQ;
					}

					if(*bcursor.readhead->loc == '0') {
						implied_port = false;
					} else {
						implied_port = true;
					}

					// Skip the value
					bcur_next(&bcursor, 1);
					break;
				case 1:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_STRING) {
						err("Bad query: Wrong value type for info_hash");
						return QUERY_EBADQ;
					}

					if(bcursor.readhead->size != 20) {
						err("Bad query: Incorrect info_hash length");
						return QUERY_EBADQ;
					}

					infohash_set = true;
					memcpy(&infohash, bcursor.readhead->loc, 20);

					bcur_next(&bcursor, 1);
					break;
				case 2:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_INT) {
						err("Bad query: Wrong value type for port");
						return QUERY_EBADQ;
					}

					port_set = true;
					port = strtol(bcursor.readhead->loc, NULL, 10);

					bcur_next(&bcursor, 1);
					break;
				case 3:
					// Skip the key
					bcur_next(&bcursor, 1);

					if(bcursor.readhead->type != BNT_STRING) {
						err("Bad query: Wrong value type for token");
						return QUERY_EBADQ;
					}

					if(bcursor.readhead->size != SHA256_BLOCK_SIZE) {
						err("Bad query: Incorrect token length");
						return QUERY_EBADQ;
					}

					token_set = true;
					memcpy(&token, bcursor.readhead->loc, SHA256_BLOCK_SIZE);

					bcur_next(&bcursor, 1);
					break;
			}
		}

		if(!infohash_set || (!implied_port && !port_set) || !token_set) {
			err("Missing argument to query");
			return QUERY_EBADQ;
		}

		{
			struct sockaddr_in* ipv4 = (struct sockaddr_in*)src;
			struct addr src_addr;
			src_addr.ip = ipv4->sin_addr.s_addr;

			src_addr.port = ipv4->sin_port;

			if(token_validate(tokens, now, &src_addr, token) != TOK_VALI) {
				err("Invalid token");
				return QUERY_EBADQ;
			}

			if(!implied_port) {
				src_addr.port = htons(port);
			}
			int rc = add_peer(&infohash, &src_addr);
			if(rc == PEER_EFULL) {
			} else if(rc != 0) {
				fatal("Could not add peer (%d)", rc);
			}
		}

		// Write out the response
		char* end = (*response) + response_len;

		int rc = snprintf(*response, end-*response, "d2:id20:");
		if(rc < 0)
			return QUERY_EBADQ;
		*response += rc;
		assert(*response < end);

		memcpy(*response, self, sizeof(struct nodeid));
		*response += sizeof(struct nodeid);
		assert(*response < end);

		(**response) = 'e';
		(*response)++;
		assert(*response < end);

		return 0;
	} else {
		return QUERY_EUNK;
	}

	return 0;
}