summaryrefslogtreecommitdiffstats
path: root/src/bencoding.c
blob: 801c5b6ea5b5f9f1c4760cb969177522ef30a597 (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
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
/**
 * enum of all possible bencoding types and some options to use
 * to check a type, use ORing, not direct comparison, as bdecoded structs inherit opts from bdecode function in their ->types
 */

enum benc {
	string = 1 << 0,
	num = 1 << 1,
	list = 1 << 2,
	dict = 1 << 3,
	replace = 1 << 4 /**< replace existing element with same key when using binsert() instead of prepending the new element before the old. see binsert() docs. */
};

/**
 * structure representation of bencoded data
 * the structure copies strings
 */

struct bencoding {
	struct bencoding * next; /**< NULL if element is not member of a list or dict */
	struct bencoding * prev;
	struct bencoding * child; /**< NULL if element is not a list or dict or if it has 0 children */
	struct bencoding * parent;
	enum benc type; /**< type | opts of this element */
	struct bencoding * key; /**< the key element, string according to the spec, applicable for dict */
	char * value; /**< set to the content of the element. \0 terminated. NULL for dict and list. */
	size_t valuelen; /**< length of string value. */
	long int intvalue;
	int index;
	const char * after; /**< internal, set to character after this bencoded element in input string, used by recursive bdecode */
};

/**
 * frees the passed bencoding struct or performs no action if NULL was passed. caller should NULL the pointer to prevent reuse.
 */

void free_bencoding (struct bencoding * b) {
	if (!b)
		return;
	free_bencoding(b->child); /* we free the child should it exist. it can be NULL. */
	free_bencoding(b->key); /* should this be an element of a dict, free the key */
	free_bencoding(b->next);
	free(b->value);
	free(b);
	return;
}

/**
 * compares two bencoding elements. used in binsert. elements with different types are always different.
 *
 * @param a	[in] if this one is higher, -1 is returned
 * @param b	[in] if this one is higher, 1 is returned
 * @return -1 if a is higher, 1 if b is higher, 0 if they are the same
 */

int bcompare (struct bencoding * a, struct bencoding * b) {
	if (!a && !b)
		return 0;
	if (!a && b)
		return -1;
	if (a && !b)
		return 1;
	if (a->type & (num | string | list | dict) < b->type (num | string | list | dict))
		return -1;
	if (a->type & (num | string | list | dict) > b->type (num | string | list | dict))
		return 1;
	int ret = bcompare(a->key, b->key);
	if (ret)
		return ret;
	if (a->type & num) {
		if (a->intvalue != b->intvalue)
			return a->intvalue < b->intvalue ? -1 : 1;
		else
			return 0;
	}
	if (a->type & string) {
		if (a->valuelen != b->valuelen)
			return a->valuelen < b->valuelen ? -1 : 1;
		else
			return memcmp(a->value, b->value, a->valuelen);
	}
	if (!a->child && b->child)
		return -1;
	if (a->child && !b->child)
		return 1;
	a = a->child;
	b = b->child;
	if (a->value & (list | dict)) {
		while (1) {
			if (!a && !b)
				return 0;
			int ret = bcompare(a, b);
			if (ret)
				return ret;
			a = a->next;
			b = b->next;
		}
	}
}

/**
 * insert into bencoding dict or list. if key already exists, it's prepended to the already existing key, unless opts has replace set.
 *
 * the memory pointed to by elem is considered ownership and responsibility of the dict now, so it shouldn't be freed by the caller. it can still be modified, however.
 *
 * if elem or benc is NULL, function does nothing.
 *
 * default (without replace), new element will be inserted into the dict, but before the old element, with the aim that finders, such as bpath(), would return the new element instead of the old.
 * replace option frees the old element and inserts this one instead if the key already exists in the dict. this is not the default, because it frees objects that may be used elsewhere.
 *
 * @param benc	[in]	the structure to which elem will be inserted into
 * @param elem	[in]	the element that will be inserted into the structure
 */

void binsert (struct bencoding * benc, struct bencoding * elem) {
	if (!benc || !elem)
		return NULL;
	elem->parent = benc;
	if (!benc->child) {
		elem->next = NULL;
		elem->prev = NULL;
		elem->parent = benc;
		benc->child = elem;
		return;
	}
	benc = benc->child;
	while (benc->next && bcompare(elem->key, benc->next->key) < 0)
		benc = benc->next;
	struct bencoding * oldnext = benc->next;
	benc->next = elem;
	elem->prev = benc;
	elem->next = oldnext;
	if (oldnext)
		oldnext->prev = elem;
}

/**
 * returns a bencoding element that represents a string
 *
 * the string ownership is not transfered, the string is strdup()ed
 *
 * @param str	[in]	the string to be converted to a bencoding element
 */

struct bencoding * bstr (const char * str) {
	struct bencoding * b = calloc(1, sizeof *b);
	if (!b)
		return NULL;
	b->type = string;
	b->valuelen = strlen(str);
	b->value = strdup(str);
	if (!b->value) {
		free(b);
		return NULL;
	}
	return b;
}

/**
 * returns a bencoding element that represents a number
 *
 * @param num	[in]	the number to be converted to a bencoding number
 */

struct bencoding * bnum (long int num) {
	struct bencoding * b = calloc(1, sizeof *b);
	if (!b)
		return NULL;
	b->type = num;
	char buf[512];
	sprintf(buf, "%ld", num);
	b->value = strdup(buf);
	if (!b->valueint) {
		free(b);
		return NULL;
	}
	b->valueint = num;
	return b;
}

/**
 * helper macros for number comparisons
 */

#define MAX(x, y) ((x) >= (y) ? (x) : (y))
#define MIN(x, y) ((x) <= (y) ? (x) : (y))

/**
 * return how much space a character in a string uses
 *
 * @param a	[in]	the character in question
 */

int b2json_charsize (unsigned char a) {
	if (a == '"')
		return 2;
	if (a == '\\')
		return 2;
	if (a == '\b')
		return 2;
	if (a == '\f')
		return 2;
	if (a == '\n')
		return 2;
	if (a == '\r')
		return 2;
	if (a == '\t')
		return 2;
	if (a < ' ')
		return 6;
	return 1;
}

/**
 * write a string representation of a character in a JSON string
 *
 * @param dest	[out]	destination
 * @param a	[in]	the character in question
 * @return the destination pointer, incremented for the number of bytes written
 */

char * b2json_charrepr (char * dest, unsigned char a) {
	switch (a) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
		case '"':
			strncpy(dest, "\\\"", 2);
			return dest+2;
		case '\\':
			strncpy(dest, "\\\\", 2);
			return dest+2;
		case '\b':
			strncpy(dest, "\\b", 2);
			return dest+2;
		case '\f':
			strncpy(dest, "\\f", 2);
			return dest+2;
		case '\n':
			strncpy(dest, "\\n", 2);
			return dest+2;
		case '\r':
			strncpy(dest, "\\r", 2);
			return dest+2;
		case '\t':
			strncpy(dest, "\\t", 2);
			return dest+2;
		default:
			if (a < ' ') {
				char buf[7];
				sprintf(buf, "\\u00%02x", a);
				strncpy(dest, buf, 6);
				return dest+6;
			} else {
				*dest++ = a;
				return dest;
			}
#pragma GCC diagnostic pop
	}
}


/**
 * get size required for JSON representation of a bencoding struct. terminating NULL byte is not counted, because b2json does not write it. write it yourself.
 *
 * @param b	[in]	bencoding structure of a bdecoded element
 */

int b2json_length (struct bencoding * b) {
	if (!b)
		return 4;
	if (b->type & string) {
		int size = 2;
		for (size_t i = 0; i < b->valuelen; i++)
			size += b2json_charsize(b->value[i]);
		return size;
	}
	if (b->type & num) {
		char buf[512];
		sprintf(buf, "%ld", b->intvalue);
		return strlen(buf);
	}
	if (b->type & list) {
		if (!b->child)
			return 2;
		struct bencoding * t = b->child;
		int size = 2 + b2json_length(t);
		while (t->next) {
			t = t->next;
			size += b2json_length(t) + 1;
		}
		return size;
	}
	if (b->type & dict) {
		if (!b->child)
			return 2;
		struct bencoding * t = b->child;
		int size = 3 + b2json_length(t) + b2json_length(t->key);
		while (t->next) {
			t = t->next;
			size += 1 + b2json_length(t) + 1 + b2json_length(t->key);
		}
		return size;
	}
	return 5;
}

/**
 * write json representation of a bencoding struct. does not write terminating nullbyte, b2json_length does not include it in count. add it yourself. should write exactly b2json_length bytes.
 *
 * writes false when struct has an incorrect type and null when NULL pointer is passed, this is in ordnung with b2json_length.
 *
 * @param dest	[in]	destination
 * @param b	[in]	bencoding structure of a bdecoded element
 * @return the destination pointer, incremented for the number of bytes written
 */

char * b2json (char * dest, struct bencoding * b) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
	if (!b) {
		strncpy(dest, "null", 4);
		return dest+4;
	}
	if (b->type & string) {
		*dest++ = '"';
		for (size_t i = 0; i < b->valuelen; i++)
			dest = b2json_charrepr(dest, b->value[i]);
		*dest++ = '"';
		return dest;
	}
	if (b->type & num) {
		char buf[512];
		sprintf(buf, "%ld", b->intvalue);
		strncpy(dest, buf, strlen(buf));
		return dest+strlen(buf);
	}
	if (b->type & list) {
		if (!b->child) {
			strncpy(dest, "[]", 2);
			return dest+2;
		}
		struct bencoding * t = b->child;
		*dest++ = '[';
		dest = b2json(dest, t);
		while (t->next) {
			t = t->next;
			*dest++ = ',';
			dest = b2json(dest, t);
		}
		*dest++ = ']';
		return dest;
	}
	if (b->type & dict) {
		if (!b->child) {
			strncpy(dest, "{}", 2);
			return dest+2;
		}
		*dest++ = '{';
		struct bencoding * t = b->child;
		dest = b2json(dest, t->key);
		*dest++ = ':';
		dest = b2json(dest, t);
		while (t->next) {
			t = t->next;
			*dest++ = ',';
			dest = b2json(dest, t->key);
			*dest++ = ':';
			dest = b2json(dest, t);
		}
		*dest++ = '}';
		return dest;
	}
	strncpy(dest, "false", 4);
	return dest+4;
#pragma GCC diagnostic pop
}

/**
 * bdecodes a bencoded structure from a string into a bencoding structure that must be free_bencodinged by the caller.
 * 
 * nonstandard things: this parser allows for dict keys to be of any type, valuekey
 *
 * @param len	[in]	* if set to -1, string is assumed to be correct and not NULL terminated, NULLs may be in strings.
 * 				- malicious strings may trigger reads past the end of the buffer, which may lead to undefined
 *				behaviour, crashes (DoS) or leaks of content, stored in memory.
 *				- if opts&terminate, another character will be written after the bencoded structure in memory if
 *				that structure is a string. beware and have space allocated for it!
 * 			* if set to -2, string is assumed to be NULL terminated and no further reading will be done after the NULL.
 * 				- if such terminator breaks an incomplete element, the resulting structure may be incomplete, but
 * 				will be correct - for example valuelen of a misterminated string will correctly be shortened.
 * 			* if set to a positive number, reading will only be allowed up to that many characters.
 * 				- if the input string reads the end and the structure is incomplete, same thing as with -2 happens.
 * 				- if the structure ends cleanly (string length satisfied or end of list, dict or num found),
 * 				processing stops, no mather how many characters of len are left.
 * @param opts	[in]	sets options. do not set the type bits here, this is the same enum as the ->type enum of returned struct.
 * 			opts will be reflected in the ->type of the returning struct. opts will apply to childs of lists&dicts too.
 */

struct bencoding * bdecode (const char * s, int len, enum benc opts) {
	if (!s || len < -2 || (len >= 0 && len < 2 /* 2 being the smallest bencoding string */))
		return NULL;
	if (len == -2)
		len = strlen(s);
	struct bencoding * b = calloc(1, sizeof(struct bencoding)); /* SEGV if OOM */
	char * ch = NULL;
	switch (s[0]) {
		case 'i': /* num */
			b->type = num;
			if (len == -1 || memchr(s, 'e', len)) { /* correct string or end found */
				b->intvalue = strtol(s+1, &ch, 10);
				b->valuelen = ch-(s+1);
				b->value = malloc(b->valuelen+1);
				if (!b->value)
					return NULL;
				strncpy(b->value, s+1, b->valuelen);
				b->value[b->valuelen] = '\0';
				b->after = s+2+b->valuelen;
			} else
				return NULL;
			break;
		case 'd': /* dict */
			b->type = dict;
			__attribute__((fallthrough));
		case 'l': /* list */
			if (!b->type)
				b->type = list;
			const char * cp = s+1;
			struct bencoding * arbeit = NULL;
			struct bencoding * oldarbeit = NULL;
			struct bencoding * oldoldarbeit = NULL; /* for dicts, holds previous value */
			int index = 0;
			while (len == -1 || cp <= s+len) {  /* s+len is max we are allowed to read */
				arbeit = bdecode(cp, len == -1 ? -1 : len-(cp-s), opts);
				if (arbeit)
					arbeit->parent = b;
				if (!arbeit) /* bdecoding failed or last element */
					break;
#define ISDICT (b->type & dict)
#define ISLIST !ISDICT
#define ISVAL (index % 2)
#define ISKEY !ISVAL
				if (ISDICT && ISVAL)
					arbeit->key = oldarbeit;
				cp = arbeit->after;
				arbeit->prev = ISDICT ? ISVAL ? oldoldarbeit : oldarbeit : oldarbeit;
				arbeit->index = ISDICT ? index/2 : index;
				if (ISLIST) {
					if (index)
						oldarbeit->next = arbeit;
					else
						b->child = arbeit;
				}
				if (ISDICT) {
					if (index == 1)
						b->child = arbeit;
					else if (ISVAL)
						oldoldarbeit->next = arbeit;
				}
				oldoldarbeit = oldarbeit;
				oldarbeit = arbeit;
				index++;
			}
			b->after = cp+1;
			b->type = b->type | opts;
			if (ISDICT && ISVAL) // e je torej value, če je prej samoten key
				free_bencoding(oldarbeit); // this key would be otherwise leaked
			return b;
		case 'e': /* end of list/dict */
			free(b);
			return NULL;
		default:
			if (!(s[0] >= '0' && s[0] <= '9')) { /* not a string. not checking this would allow DoS for parsing "lx" */
				fprintf(stderr, "bencoding: unknown type %c\n", s[0]);
				free(b);
				return NULL;
			}
			b->type = string;
			if (len == -1 || (b->value = memchr(s, ':', len))) {
				b->valuelen = strtol(s, &ch, 10);
				if (len != -1 && (unsigned)len < b->valuelen + (ch+1 - s) /* len minus prefix; strlen & colon */)
					b->valuelen = len - (ch+1 - s); /* malformed bencoded data, truncating string */
				b->value = malloc(b->valuelen+1);
				strncpy(b->value, ch+1, b->valuelen);
				b->value[b->valuelen] = '\0';
				b->after = ch+1+b->valuelen;
			} else {
				free(b);
				return NULL;
			}
			break;
	}
	b->type = b->type | opts;
	return b;
}

/**
 * returns a pointer to bencoding struct matching bencoding path or NULL if not found.
 *
 * path key/key2/key3 will given object {"key":{"key2":{"key3":val}}} return val
 * 
 * @param benc	[in]	the bencoding dict to look in
 * @param key	[in]	the path
 */

struct bencoding * bpath (struct bencoding * benc, const char * key) {
	if (!benc)
		return NULL;
	if (!benc->child)
		return NULL;
	benc = benc->child;
	if (key[0] == '/')
		key++;
	size_t len = strlen(key);
	char * c = strchr(key, '/');
	if (c)
		len = c - key;
	while (benc) {
		if (benc->key && benc->key->type & num) {
			char buf[512];
			sprintf(buf, "%ld", benc->key->intvalue);
			if (len == strlen(buf) && !strncmp(buf, key, len)) {
				if (!c)
					return benc;
				else
					return bpath(benc, key+len);
			}
		}
		if (benc->key && benc->key->type & string) {
			if (len == benc->key->valuelen && !strncmp(key, benc->key->value, len)) {
				if (!c)
					return benc;
				else
					return bpath(benc, key+len);
			}
		}
		benc = benc->next;
	}
	return NULL;
}

/**
 * macro that loops following code body across a list or values of dict
 *
 * @param elem	[out]	name of element that will be used for value while looping
 * @param list	[in]	list/dict of values
 */

#define bforeach(elem, list) \
	for (struct bencoding * elem = list ? list->child : NULL; elem; elem = elem->next)

/**
 * find a value in a list. returns NULL if not found.
 *
 * @param benc	[in]	the bencoding list or dict to look in
 * @param str	[in]	the value
 */

struct bencoding * bval (struct bencoding * benc, const char * val) {
	if (!benc)
		return NULL;
	if (!benc->child)
		return NULL;
	benc = benc->child;
	while (benc) {
		if (benc->type & num) {
			char buf[412];
			sprintf(buf, "%ld", benc->intvalue);
			if (!strcmp(buf, val))
				return benc;
		}
		if (benc->type & string && strlen(val) == benc->valuelen && !strncmp(benc->value, val, benc->valuelen))
			return benc;
		benc = benc->next;
	}
	return NULL;
}