aboutsummaryrefslogtreecommitdiffhomepage
path: root/backends/libmmbackend.c
blob: 92adc3c8740c9b49bfe2f3b70dfb12548584b3ad (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
#include "libmmbackend.h"

#define LOGPF(format, ...) fprintf(stderr, "libmmbe\t" format "\n", __VA_ARGS__)
#define LOG(message) fprintf(stderr, "libmmbe\t%s\n", (message))

int mmbackend_strdup(char** dest, char* src){
	if(*dest){
		free(*dest);
	}

	*dest = strdup(src);

	if(!*dest){
		LOG("Failed to allocate memory");
		return 1;
	}
	return 0;
}

char* mmbackend_socket_strerror(int err_no){
	#ifdef _WIN32
	static char error[2048] = "";
	ssize_t u; 
	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, WSAGetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), error, sizeof(error), NULL);
	//remove trailing newline that for some reason is included in most of these...
	for(u = strlen(error) - 1; u > 0; u--){
		if(!isprint(error[u])){
			error[u] = 0;
		}
	}
	return error;
	#else
	return strerror(err_no);
	#endif
}

const char* mmbackend_sockaddr_ntop(struct sockaddr* peer, char* buffer, size_t length){
	union {
		struct sockaddr* in;
		struct sockaddr_in* in4;
		struct sockaddr_in6* in6;
	} addr;
	addr.in = peer;
	#ifdef _WIN32
	uint8_t* data = NULL;
	#endif

	switch(addr.in->sa_family){
		//inet_ntop has become available in the winapi with vista, but eh.
		#ifdef _WIN32
		case AF_INET6:
			data = addr.in6->sin6_addr.s6_addr;
			snprintf(buffer, length, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
					data[0], data[1], data[2], data[3],
					data[4], data[5], data[6], data[7],
					data[8], data[9], data[10], data[11],
					data[12], data[13], data[14], data[15]);
			return buffer;
		case AF_INET:
			data = (uint8_t*) &(addr.in4->sin_addr.s_addr);
			snprintf(buffer, length, "%d.%d.%d.%d", data[0], data[1], data[2], data[3]);
			return buffer;
		#else
		case AF_INET6:
			return inet_ntop(addr.in->sa_family, &(addr.in6->sin6_addr), buffer, length);
		case AF_INET:
			return inet_ntop(addr.in->sa_family, &(addr.in4->sin_addr), buffer, length);
		#endif
		default:
			snprintf(buffer, length, "Socket family not implemented");
			return buffer;
	}
}

void mmbackend_parse_hostspec(char* spec, char** host, char** port, char** options){
	size_t u = 0;

	if(!spec || !host || !port){
		return;
	}

	*port = NULL;

	//skip leading spaces
	for(; spec[u] && isspace(spec[u]); u++){
	}

	if(!spec[u]){
		*host = NULL;
		return;
	}

	*host = spec + u;

	//scan until string end or space
	for(; spec[u] && !isspace(spec[u]); u++){
	}

	//if space, the rest should be the port
	if(spec[u]){
		spec[u] = 0;
		*port = spec + u + 1;
	}

	if(options){
		*options = NULL;
		if(*port){
			//scan for space after port
			for(u = 0; (*port)[u] && !isspace((*port)[u]); u++){
			}
			if(isspace((*port)[u])){
				(*port)[u] = 0;
				*options = (*port) + u + 1;
			}
		}
	}
}

int mmbackend_parse_sockaddr(char* host, char* port, struct sockaddr_storage* addr, socklen_t* len){
	struct addrinfo* head;
	struct addrinfo hints = {
		.ai_family = AF_UNSPEC
	};

	int error = getaddrinfo(host, port, &hints, &head);
	if(error || !head){
		LOGPF("Failed to parse address %s port %s: %s", host, port, gai_strerror(error));
		return 1;
	}

	memcpy(addr, head->ai_addr, head->ai_addrlen);
	if(len){
		*len = head->ai_addrlen;
	}

	freeaddrinfo(head);
	return 0;
}

int mmbackend_socket(char* host, char* port, int socktype, uint8_t listener, uint8_t mcast){
	int fd = -1, status, yes = 1;
	struct addrinfo hints = {
		.ai_family = AF_UNSPEC,
		.ai_socktype = socktype,
		.ai_flags = (listener ? AI_PASSIVE : 0)
	};
	struct addrinfo *info, *addr_it;

	status = getaddrinfo(host, port, &hints, &info);
	if(status){
		LOGPF("Failed to parse address %s port %s: %s", host, port, gai_strerror(status));
		return -1;
	}

	//traverse the result list
	for(addr_it = info; addr_it; addr_it = addr_it->ai_next){
		fd = socket(addr_it->ai_family, addr_it->ai_socktype, addr_it->ai_protocol);
		if(fd < 0){
			continue;
		}

		//set required socket options
		yes = 1;
		if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(yes)) < 0){
			LOGPF("Failed to enable SO_REUSEADDR on socket: %s", mmbackend_socket_strerror(errno));
		}

		if(mcast){
			yes = 1;
			if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (void*)&yes, sizeof(yes)) < 0){
				LOGPF("Failed to enable SO_BROADCAST on socket: %s", mmbackend_socket_strerror(errno));
			}

			yes = 0;
			if(setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, (void*)&yes, sizeof(yes)) < 0){
				LOGPF("Failed to disable IP_MULTICAST_LOOP on socket: %s", mmbackend_socket_strerror(errno));
			}
		}

		if(listener){
			status = bind(fd, addr_it->ai_addr, addr_it->ai_addrlen);
			if(status < 0){
				close(fd);
				continue;
			}
		}
		else{
			status = connect(fd, addr_it->ai_addr, addr_it->ai_addrlen);
			if(status < 0){
				close(fd);
				continue;
			}
		}

		break;
	}
	freeaddrinfo(info);

	if(!addr_it){
		LOGPF("Failed to create socket for %s port %s", host, port);
		return -1;
	}

	//set nonblocking
	#ifdef _WIN32
	u_long mode = 1;
	if(ioctlsocket(fd, FIONBIO, &mode) != NO_ERROR){
		closesocket(fd);
		return 1;
	}
	#else
	int flags = fcntl(fd, F_GETFL, 0);
	if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0){
		LOGPF("Failed to set socket nonblocking: %s", mmbackend_socket_strerror(errno));
		close(fd);
		return -1;
	}
	#endif

	return fd;
}

int mmbackend_send(int fd, uint8_t* data, size_t length){
	ssize_t total = 0, sent;
	while(total < length){
		#ifndef LIBMMBACKEND_TCP_TORTURE
		sent = send(fd, data + total, length - total, 0);
		#else
		sent = send(fd, data + total, 1, 0);
		#endif
		if(sent < 0){
			LOGPF("Failed to send: %s", mmbackend_socket_strerror(errno));
			return 1;
		}
		total += sent;
	}
	return 0;
}

int mmbackend_send_str(int fd, char* data){
	return mmbackend_send(fd, (uint8_t*) data, strlen(data));
}

json_type json_identify(char* json, size_t length){
	size_t n;

	//skip leading blanks
	for(n = 0; json[n] && n < length && isspace(json[n]); n++){
	}

	if(n == length){
		return JSON_INVALID;
	}

	switch(json[n]){
		case '{':
			return JSON_OBJECT;
		case '[':
			return JSON_ARRAY;
		case '"':
			return JSON_STRING;
		case '-':
		case '+':
			return JSON_NUMBER;
		default:
			//true false null number
			if(!strncmp(json + n, "true", 4)
					|| !strncmp(json + n, "false", 5)){
				return JSON_BOOL;
			}
			else if(!strncmp(json + n, "null", 4)){
				return JSON_NULL;
			}
			//a bit simplistic but it should do
			if(isdigit(json[n])){
				return JSON_NUMBER;
			}
	}
	return JSON_INVALID;
}

size_t json_validate(char* json, size_t length){
	switch(json_identify(json, length)){
		case JSON_STRING:
			return json_validate_string(json, length);
		case JSON_ARRAY:
			return json_validate_array(json, length);
		case JSON_OBJECT:
			return json_validate_object(json, length);
		case JSON_INVALID:
			return 0;
		default:
			return json_validate_value(json, length);
	}
}

size_t json_validate_string(char* json, size_t length){
	size_t string_length = 0, offset;

	//skip leading whitespace
	for(offset = 0; json[offset] && offset < length && isspace(json[offset]); offset++){
	}

	if(offset == length || json[offset] != '"'){
		return 0;
	}

	//find terminating quotation mark not preceded by escape
	for(string_length = 1; offset + string_length < length
			&& isprint(json[offset + string_length])
			&& (json[offset + string_length] != '"' || json[offset + string_length - 1] == '\\'); string_length++){
	}

	//complete string found
	if(json[offset + string_length] == '"' && json[offset + string_length - 1] != '\\'){
		return offset + string_length + 1;
	}

	return 0;
}

size_t json_validate_array(char* json, size_t length){
	size_t offset = 0;

	//skip leading whitespace
	for(offset = 0; json[offset] && offset < length && isspace(json[offset]); offset++){
	}

	if(offset == length || json[offset] != '['){
		return 0;
	}

	for(offset++; offset < length; offset++){
		offset += json_validate(json + offset, length - offset);

		//skip trailing whitespace, find terminator
		for(; offset < length && isspace(json[offset]); offset++){
		}

		if(json[offset] == ','){
			continue;
		}

		if(json[offset] == ']'){
			return offset + 1;
		}

		break;
	}

	return 0;
}

size_t json_validate_object(char* json, size_t length){
	size_t offset = 0;

	//skip whitespace
	for(offset = 0; json[offset] && isspace(json[offset]); offset++){
	}

	if(offset == length || json[offset] != '{'){
		return 0;
	}

	for(offset++; offset < length; offset++){
		if(json_identify(json + offset, length - offset) != JSON_STRING){
			//still could be an empty object...
			for(; offset < length && isspace(json[offset]); offset++){
			}
			if(json[offset] == '}'){
				return offset + 1;
			}
			return 0;
		}
		offset += json_validate(json + offset, length - offset);

		//find value separator
		for(; offset < length && isspace(json[offset]); offset++){
		}

		if(json[offset] != ':'){
			return 0;
		}

		offset++;
		offset += json_validate(json + offset, length - offset);

		//skip trailing whitespace
		for(; json[offset] && isspace(json[offset]); offset++){
		}

		if(json[offset] == '}'){
			return offset + 1;
		}
		else if(json[offset] != ','){
			return 0;
		}
	}
	return 0;
}

size_t json_validate_value(char* json, size_t length){
	size_t offset = 0, value_length;

	//skip leading whitespace
	for(offset = 0; json[offset] && offset < length && isspace(json[offset]); offset++){
	}

	if(offset == length){
		return 0;
	}

	//match complete values
	if(length - offset >= 4 && !strncmp(json + offset, "null", 4)){
		return offset + 4;
	}
	else if(length - offset >= 4 && !strncmp(json + offset, "true", 4)){
		return offset + 4;
	}
	else if(length - offset >= 5 && !strncmp(json + offset, "false", 5)){
		return offset + 5;
	}

	if(json[offset] == '-' || isdigit(json[offset])){
		//json number parsing is dumb.
		for(value_length = 1; offset + value_length < length &&
					(isdigit(json[offset + value_length])
					|| json[offset + value_length] == '+'
					|| json[offset + value_length] == '-'
					|| json[offset + value_length] == '.'
					|| tolower(json[offset + value_length]) == 'e'); value_length++){
		}

		if(value_length > 0){
			return offset + value_length;
		}
	}

	return 0;
}

size_t json_obj_offset(char* json, char* key){
	size_t offset = 0;
	uint8_t match = 0;

	//skip whitespace
	for(offset = 0; json[offset] && isspace(json[offset]); offset++){
	}

	if(json[offset] != '{'){
		return 0;
	}
	offset++;

	while(json_identify(json + offset, strlen(json + offset)) == JSON_STRING){
		//skip to key begin
		for(; json[offset] && json[offset] != '"'; offset++){
		}

		if(!strncmp(json + offset + 1, key, strlen(key)) && json[offset + 1 + strlen(key)] == '"'){
			//key found
			match = 1;
		}

		offset += json_validate_string(json + offset, strlen(json + offset));

		//skip to value separator
		for(; json[offset] && json[offset] != ':'; offset++){
		}

		//skip whitespace
		for(offset++; json[offset] && isspace(json[offset]); offset++){
		}

		if(match){
			return offset;
		}

		//add length of value
		offset += json_validate(json + offset, strlen(json + offset));

		//skip trailing whitespace
		for(; json[offset] && isspace(json[offset]); offset++){
		}

		if(json[offset] == ','){
			offset++;
			continue;
		}

		break;
	}

	return 0;
}

size_t json_array_offset(char* json, uint64_t key){
	size_t offset = 0, index = 0;

	//skip leading whitespace
	for(offset = 0; json[offset] && isspace(json[offset]); offset++){
	}

	if(json[offset] != '['){
		return 0;
	}

	for(offset++; index <= key; offset++){
		//skip whitespace
		for(; json[offset] && isspace(json[offset]); offset++){
		}

		if(index == key){
			return offset;
		}

		offset += json_validate(json + offset, strlen(json + offset));

		//skip trailing whitespace, find terminator
		for(; json[offset] && isspace(json[offset]); offset++){
		}

		if(json[offset] != ','){
			break;
		}
		index++;
	}

	return 0;
}

json_type json_obj(char* json, char* key){
	size_t offset = json_obj_offset(json, key);
	if(offset){
		return json_identify(json + offset, strlen(json + offset));
	}
	return JSON_INVALID;
}

json_type json_array(char* json, uint64_t key){
	size_t offset = json_array_offset(json, key);
	if(offset){
		return json_identify(json + offset, strlen(json + offset));
	}
	return JSON_INVALID;
}

uint8_t json_obj_bool(char* json, char* key, uint8_t fallback){
	size_t offset = json_obj_offset(json, key);
	if(offset){
		if(!strncmp(json + offset, "true", 4)){
			return 1;
		}
		if(!strncmp(json + offset, "false", 5)){
			return 0;
		}
	}
	return fallback;
}

uint8_t json_array_bool(char* json, uint64_t key, uint8_t fallback){
	size_t offset = json_array_offset(json, key);
	if(offset){
		if(!strncmp(json + offset, "true", 4)){
			return 1;
		}
		if(!strncmp(json + offset, "false", 5)){
			return 0;
		}
	}
	return fallback;
}

int64_t json_obj_int(char* json, char* key, int64_t fallback){
	char* next_token = NULL;
	int64_t result;
	size_t offset = json_obj_offset(json, key);
	if(offset){
		result = strtol(json + offset, &next_token, 10);
		if(next_token != json + offset){
			return result;
		}
	}
	return fallback;
}

double json_obj_double(char* json, char* key, double fallback){
	char* next_token = NULL;
	double result;
	size_t offset = json_obj_offset(json, key);
	if(offset){
		result = strtod(json + offset, &next_token);
		if(next_token != json + offset){
			return result;
		}
	}
	return fallback;
}

int64_t json_array_int(char* json, uint64_t key, int64_t fallback){
	char* next_token = NULL;
	int64_t result;
	size_t offset = json_array_offset(json, key);
	if(offset){
		result = strtol(json + offset, &next_token, 10);
		if(next_token != json + offset){
			return result;
		}
	}
	return fallback;
}

double json_array_double(char* json, uint64_t key, double fallback){
	char* next_token = NULL;
	double result;
	size_t offset = json_array_offset(json, key);
	if(offset){
		result = strtod(json + offset, &next_token);
		if(next_token != json + offset){
			return result;
		}
	}
	return fallback;
}

char* json_obj_str(char* json, char* key, size_t* length){
	size_t offset = json_obj_offset(json, key), raw_length;
	if(offset){
		raw_length = json_validate_string(json + offset, strlen(json + offset));
		if(length){
			*length = raw_length - 2;
		}
		return json + offset + 1;
	}
	return NULL;
}

char* json_obj_strdup(char* json, char* key){
	size_t len = 0;
	char* value = json_obj_str(json, key, &len), *rv = NULL;
	if(len){
		rv = calloc(len + 1, sizeof(char));
		if(rv){
			memcpy(rv, value, len);
		}
	}
	return rv;
}

char* json_array_str(char* json, uint64_t key, size_t* length){
	size_t offset = json_array_offset(json, key), raw_length;
	if(offset){
		raw_length = json_validate_string(json + offset, strlen(json + offset));
		if(length){
			*length = raw_length - 2;
		}
		return json + offset + 1;
	}
	return NULL;
}

char* json_array_strdup(char* json, uint64_t key){
	size_t len = 0;
	char* value = json_array_str(json, key, &len), *rv = NULL;
	if(len){
		rv = calloc(len + 1, sizeof(char));
		if(rv){
			memcpy(rv, value, len);
		}
	}
	return rv;
}