summaryrefslogtreecommitdiffstats
path: root/src/api.c
blob: ed5f06f8ea13571299eebf0b34476e8fc6b090ae (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
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
#pragma once
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <curl/curl.h>
#include <unistd.h>
#include <i18n.h>
#include <string.h>
#include <lib.c>
#include <cjson/cJSON.h>
#include <time.h>
#include <stdarg.h>
#include <printf.h>
#include <pthread.h>
#include <stdatomic.h>
#include <signal.h>
#define DC_API_PREFIX "https://discord.com/api/v8/" /* this can be a format string, DO NOT use format characters inside */
#define DC_LOGIN_FORMAT "{\"login\":\"%s\",\"password\":\"%s\",\"undelete\":false,\"captcha_key\":null,\"login_source\":null,\"gift_code_sku_id\":null}"
#define DC_USER_AGENT "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
#define DC_ERROR(c, m, ...) (dc_push_error(c, __func__, __FILE__, __LINE__, 0##__VA_OPT__(1), m __VA_OPT__(,) __VA_ARGS__))
/* #define DC_ERROR(c, m, ...) (fprintf(stderr, "%s()@" __FILE__ ":%d: " m "\n", __func__, __LINE__ __VA_OPT__(,) __VA_ARGS__)) */
#define DC_CLIENT_ERROR(c, m, ...) DC_ERROR(c, m __VA_OPT__(,) __VA_ARGS__) /* yeah, that m is not a typo */
#define DC_CAPI(c, body, endpoint, ...) dc_api(c, body, 0##__VA_OPT__(1), endpoint __VA_OPT__(,) __VA_ARGS__)
#define cJSON_GetObjectItem2(root, name1, name2) (cJSON_GetObjectItem(root, name1) ? cJSON_GetObjectItem(cJSON_GetObjectItem(root, name1), name2) : NULL)
#define DC_TIMESTAMP_FORMAT "%Y-%m-%dT%H:%M:%S.XXXXXX%z"
#define DC_SHORTTIMESTAMP_FORMAT "%Y-%m-%dT%T%z"
#define DC_CWLE(c, name) (pthread_rwlock_wrlock(name) ? (DC_CLIENT_ERROR(c, DC_I18N_LOCKING " " #name " " DC_I18N_FAILED) || 1) : 0)
#define DC_CRLE(c, name) (pthread_rwlock_rdlock(name) ? (DC_CLIENT_ERROR(c, DC_I18N_LOCKING " " #name " " DC_I18N_FAILED) || 1) : 0)
#define DC_CUE(c, name) (pthread_rwlock_unlock(name) ?(DC_CLIENT_ERROR(c, DC_I18N_UNLOCKING " " #name " " DC_I18N_FAILED) || 1) : 0)
/*
	struct members comment information:
	- noui: the ui thread must not use the member (for example curl pointers are noui)
	- noapi: the api thread must not use the member
	- nofree: the (string) pointer is of a static string, do not attempt to free it (for example function, file, message in dc_error)
	- yesfree: the (string) pointer is of a dynamically-allocated string, free it before losing pointer to the struct (most strings)
	- nouiw: ui must not write
	- noapiw: api must not write
	- nolock: no lock is required if only reading is done after a single write to the memory area or only one thread accesses it
	guidelines:
	- when threading, you must use mutexes to prevent accessing structs (and their pointers because of realloc!) (optionaly with timeouts that are optionaly reported with DC_CLIENT_ERROR)
	- error reporting function shall not report an error to itself when mutex lock times out for obvious reasons
	- _sizeofs shall represent the size of arrays in atomic types
	- keep arrays as arrays of pointers, not direct structs, as that allows pointing to individual elements without them changing pointer addresses
	- threading and races 101: when popping arrays, always lock in a non-shared way, same obviously applies for sorting, writing, appending (because of reallocs of pointer arrays)
	mutexes:
	- mutexes for child members are kept in the struct with the object that is being modified. if realloc is used on strings or those child objects (pointers change), the whole struct must be locked.
	- when reading arrays of pointers, you shared lock it
	- when writing, lock the memory in a non shared way, take note of the pointer in case of realloc
	struct pointed to from multiple sections (a great example is a channel)
	- when a channel is created, DO NOT destroy it - never free channels if you don't free messages, never free guilds if you don't free channels. that's because channels in guilds are backpointed to parent guilds and messages are backpointed to channels, realloc would lead to a segfault.
	- use posixes pthread_rwlock_init(3POSIX) mutexes to allow reading to arrays and other types
	- do not have the illusion that you can append to an array of pointers without non-shared locking, because you realloc that array of pointers, appending must also be non-shared locked
	- _free functions shall never fail - do not use timed locks
	- i changed arrays from type arrays to type pointer arrays, so code that allocates must be reimplemented, also struct free functions and -> instead of . in array elements
*/
struct dc_error {
	size_t line;
	const char * function; /* nofree */
	char * file; /* nofree */
	char * message; /* yesfree */
	time_t time;
	short unsigned int reported /* 0: error was not yet shown to the user, 1: error was already shown to the user */;
};
void dc_error_free(struct dc_error * e) { /* noui, noapi, nolock - only called by dc_client_free */
	free(e->message); e->message = NULL; /* other strings are static */
	e->line = 0;
	e->function = NULL;
	e->file = NULL;
	e->reported = 0;
	free(e);
}
struct dc_message {
	char * username; /* yesfree */
	int discriminator;
	char * content; /* yesfree */
	char * attachment; /* yesfree - url to the attachment should it exist */
	time_t time;
	_Atomic(struct dc_channel *) channel; /* nofree */
	unsigned short int tts;
	unsigned long long int id; /* nouiw */
	unsigned short int status; /* noapiw - 0 if it was not yet printed on the display, 1 if it was */
};
void dc_message_free (struct dc_message * m) { /* noui, noapi, nolock - only called by dc_channel_free */
	free(m->username); m->username = NULL;
	free(m->content); m->content = NULL;
	free(m->attachment); m->attachment = NULL;
	m->channel = NULL;
	m->tts = 0;
	m->discriminator = -1;
	m->id = 0;
	/* i'm not sure how to "unset" time_t ... */
	free(m);
}
int dc_message_compare (const void * a, const void * b) {
	struct dc_message * c = *(struct dc_message **) a;
	struct dc_message * d = *(struct dc_message **) b;
	/* strežnik v arrayu najprej pošlje sporočila iz sedanjosti, nato tista iz preteklosti, zato bo tudi sortiran array takšen */
	return c->time > d->time ? -1 : c->time < d->time ? 1 : 0;
}
struct dc_channel {
	char * name; /* yesfree, nouiw */
	char * topic; /* yesfree, nouiw */
	unsigned long long int id; /* nouiw */
	_Atomic(struct dc_guild *) guild; /* nofree, nouiw */
	struct dc_message ** messages; /* yesfree, nouiw */
	_Atomic(size_t) messages_sizeof; /* nouiw */
	int slowmode; /* nouiw - number of seconds to wait in case of slowmode, HANDLED BY THE USER INTERFACE!! */
	unsigned short int joined; /* noapiw, if joined (1) api will fetch messages and ui display them. api will still send messages even if this is not set */
	unsigned short int focused; /* noapi, if focused (1) ui will send messages to this channel */
};
void dc_channel_free (struct dc_channel * ch) { /* noui, noapi, nolock - only called by dc_guild_free */
	free(ch->name); ch->name = NULL;
	free(ch->topic); ch->topic = NULL;
	ch->guild = NULL;
	ch->id = 0;
	for (int i = 0; i < ch->messages_sizeof; i++)
		dc_message_free(ch->messages[i]);
	free(ch->messages);
	ch->messages_sizeof = 0;
	free(ch);
}
struct dc_guild {
	char * name; /* nouiw, yesfree */
	unsigned long long id; /* nouiw */
	_Atomic(size_t) channels_sizeof; /* nouiw */
	struct dc_channel ** channels; /* yesfree, nouiw */
	_Atomic(struct dc_client *) client; /* nofree - obviously */
	char * altmsgurl; /* yesfree - alternative messages url - used for virtual guild for DMs */
};
void dc_guild_free (struct dc_guild * g) { /* noui, noapi, nolock - only called by dc_client_free */
	free(g->name); g->name = NULL;
	g->id = 0;
	for (int i = 0; i < g->channels_sizeof; i++)
		dc_channel_free(g->channels[i]);
	free(g->channels);
	g->channels_sizeof = 0;
	free(g->altmsgurl);
	free(g);
}
struct dc_client {
	CURL * curl; /* noui, nolock */
	struct curl_slist * curl_headers; /* noui, nolock */
	char * authorization; /* nouiw */
	pthread_rwlock_t * authorization_lock;
	char * email; /* yesfree, noapiw, nolock */
	char * password; /* yesfree, noapiw, nolock */
	char * username; /* yesfree, nouiw */ 
	pthread_rwlock_t * username_lock;
	_Atomic(int) discriminator; /* nouiw - -1: the user is not logged in, -2: user login failed and will not be retried, < 0: the user is not logged in */
	struct dc_guild ** guilds; /* yesfree, nouiw */
	_Atomic(size_t) guilds_sizeof; /* nouiw */
	pthread_rwlock_t * guilds_lock;
	struct dc_error ** errors; /* yesfree */
	_Atomic(size_t) errors_sizeof;
	pthread_rwlock_t * errors_lock;
	struct dc_message ** sent_messages; /* yesfree - ui appends, api pops and moves to messages */
	_Atomic(size_t) sent_messages_sizeof;
	pthread_rwlock_t * sent_messages_lock;
	_Atomic(time_t) last_sent_message; /* for slowmode implementations */
	_Atomic(short unsigned int) newmessages; /* > 0 if api got new messages. ui resets to 0 - nolock - ui should still check without this flag for new messages - racy */
};
struct dc_client * dc_client_init () { /* gives you a prepared dc_client */
	struct dc_client * c = calloc(1, sizeof(struct dc_client));
	c->discriminator = -1;
	c->guilds_sizeof = 1;
	c->guilds = calloc(1, sizeof(struct dc_guild *));
	c->guilds[0] = calloc(1, sizeof(struct dc_guild));
	c->guilds[0]->name = malloc(strlen(DC_I18N_DMS)+1);
	strcpy(c->guilds[0]->name, DC_I18N_DMS);
	c->guilds[0]->altmsgurl = malloc(strlen(DC_API_PREFIX "users/@me/channels")+1);
	strcpy(c->guilds[0]->altmsgurl, DC_API_PREFIX "users/@me/channels");
	c->guilds[0]->client = c;
#define DC_CILI(name) /* Client Init Lock Init */ do { name##_lock = malloc(sizeof(pthread_rwlock_t)); pthread_rwlock_init(name##_lock, NULL); } while(0)
	DC_CILI(c->authorization);
	DC_CILI(c->username);
	DC_CILI(c->guilds);
	DC_CILI(c->errors);
	DC_CILI(c->sent_messages);
	return c;
}
void dc_client_free (struct dc_client * c) { /* noui, noapi, nolock - only called by main on exit */
	curl_easy_cleanup(c->curl);
	c->curl = NULL;
	curl_slist_free_all(c->curl_headers);
	c->curl_headers = NULL;
	free(c->authorization); c->authorization = NULL;
	free(c->email); c->email = NULL;
	free(c->password); c->password = NULL;
	free(c->username); c->username = NULL;
	c->discriminator = -1;
	for (int i = 0; i < c->guilds_sizeof; i++)
		dc_guild_free(c->guilds[i]);
	free(c->guilds);
	c->guilds_sizeof = 0;
	for (int i = 0; i < c->errors_sizeof; i++)
		dc_error_free(c->errors[i]);
	free(c->errors);
	c->errors_sizeof = 0;
	for (int i = 0; i < c->sent_messages_sizeof; c++)
		dc_message_free(c->sent_messages[i]);
	free(c->sent_messages);
	c->sent_messages_sizeof = 0;
#define DC_CFLD(name) do { pthread_rwlock_destroy(name##_lock); free(name##_lock); } while(0)
	DC_CFLD(c->authorization);
	DC_CFLD(c->username);
	DC_CFLD(c->guilds);
	DC_CFLD(c->errors);
	DC_CFLD(c->sent_messages);
	free(c);
}
int dc_push_error (struct dc_client * c, const char * caller, char * f, size_t l, unsigned short int isfmt, char * m, ...) {
#define DC_PEE /* dc scalnia oziroma push error error */ c->errors[c->errors_sizeof-1]
	if (!c)
		return -2;
	pthread_rwlock_t * lock = c->errors_lock;
	if (!lock)
		return -3;
	if (pthread_rwlock_wrlock(lock))
		return -1; /* does not report an error as that may make things even worse. I could try writing to stderr here but meh */
	c->errors = realloc(c->errors, sizeof(struct dc_error *)*++c->errors_sizeof); /* note: format arguments are evaluated twice */
	DC_PEE = malloc(sizeof(struct dc_error));
	size_t strlenm = strlen(m);
	size_t va_count = parse_printf_format(m, 0, NULL);
	if (isfmt && va_count > 0) {
		va_list ap, ap2;
		va_start(ap, m);
		va_copy(ap2, ap);
		strlenm = vsnprintf(NULL, 0, m, ap);
		DC_PEE->message = malloc(sizeof(char)*strlenm+1);
		vsnprintf(DC_PEE->message, strlenm+1, m, ap2);
		va_end(ap);
		va_end(ap2);
	} else {
		DC_PEE->message = malloc(sizeof(char)*strlenm+1);
		strcpy(DC_PEE->message, m);
	}
	DC_PEE->file = f;
	DC_PEE->line = l;
	DC_PEE->function = caller /* Caller */;
	DC_PEE->time = time(NULL);
	DC_PEE->reported = 0;
	if (lock && pthread_rwlock_unlock(lock))
		return -2;
	return 1;
}
cJSON * dc_api (struct dc_client * c, char * body, int isfmt, char * endpoint, ...) { /* note: format arguments are evaluated twice */
	if (!c)
		return NULL;
	if (!c->curl) {
		DC_CLIENT_ERROR(c, "!c->curl");
	}
	if (!c->curl) {
		DC_CLIENT_ERROR(c, "!c->curl");
		return NULL;
	}
	if (!endpoint) {
		DC_CLIENT_ERROR(c, "!endpoint");
		return NULL;
	}
	cJSON * json = NULL;
	struct writefunc_string * s = malloc(sizeof(struct writefunc_string));
	struct writefunc_string * h = malloc(sizeof(struct writefunc_string));
	size_t va_count = parse_printf_format(endpoint, 0, NULL);
	char * endpoint_formatted = NULL;
	int retried = 0;
	long response_code = 0;
	retry:
	init_writefunc_string(s);
	init_writefunc_string(h);
	if (isfmt && va_count > 0 && endpoint_formatted == NULL) {
		va_list ap, ap2;
		va_start(ap, endpoint);
		va_copy(ap2, ap);
		size_t strlenm = vsnprintf(NULL, 0, endpoint, ap);
		endpoint_formatted = malloc(sizeof(char)*strlenm+1);
		vsnprintf(endpoint_formatted, strlenm+1, endpoint, ap2); /* sn instead of s because double evaulation may produce */
		va_end(ap); /* larger output the next time and lead to overflow */
		va_end(ap2);
	}
	curl_easy_setopt(c->curl, CURLOPT_URL, endpoint_formatted ? endpoint_formatted : endpoint);
	curl_easy_setopt(c->curl, CURLOPT_POSTFIELDS, body); /* yes, even null is okay, it's actually a must as it makes sure curl clears old pointers and does not read freed memory. see https://github.com/curl/curl/issues/3214#issuecomment-435335974 */
	if (!body)
		curl_easy_setopt(c->curl, CURLOPT_HTTPGET, 1L); /* this must be done after postfields */
	curl_easy_setopt(c->curl, CURLOPT_WRITEDATA, s);
	curl_easy_setopt(c->curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(c->curl, CURLOPT_HEADERDATA, h);
	curl_easy_setopt(c->curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(c->curl, CURLOPT_HTTPHEADER, c->curl_headers);
	curl_easy_setopt(c->curl, CURLOPT_TIMEOUT, 20L); /* 20 second timeout */
	curl_easy_setopt(c->curl, CURLOPT_HEADERFUNCTION, writefunc);
	curl_easy_setopt(c->curl, CURLOPT_WRITEFUNCTION, writefunc);
	if (curl_easy_perform(c->curl) != CURLE_OK) {
		DC_CLIENT_ERROR(c, "curl_easy_perform(curl) != CURLE_OK");
		goto rc;
	} else {
		curl_easy_getinfo(c->curl, CURLINFO_RESPONSE_CODE, &response_code);
	}
#ifdef DC_NETREQ
	fprintf(netreq, "%s\n%s\n%s\n%s====================================\n", endpoint_formatted ? endpoint_formatted : endpoint, body ? body : "GET", h->ptr, s->ptr);
	fflush(netreq);
#endif
	json = cJSON_Parse(s->ptr);
	if (!json) {
		const char * error_ptr = cJSON_GetErrorPtr();
		if (error_ptr) {
			DC_CLIENT_ERROR(c, "cJSON_Parse " DC_I18N_FAILED ": " DC_I18N_JSON_ERROR_BEFORE ": %.21s s->ptr = %s", error_ptr, s->ptr);
		} else {
			DC_CLIENT_ERROR(c, "cJSON_Parse " DC_I18N_FAILED ". s->ptr = %s", s->ptr ? s->ptr : "NULL");
		}
		goto rc;
	}
	/* note that the server does not send x-ratelimit headers for normal users and cJSON has problems with parsing floats, so caveman approach is needed */
	char * cp = cJSON_GetStringValue(cJSON_GetObjectItem(json, "retry_after"));
	if (cp && (cp = strstr(cp, "\"retry_after\": "))) { /* note: make sure to always check if retry_after is in the root of the object, otherwise you can get dosed if a user somehow inserts "retry_after": into a message or something. we could check error code though, but naaaah */
		if (!(cp = strchr(cp, ' ')))
			goto rc;
		int retry_after = atoi(++cp)+1;
		DC_CLIENT_ERROR(c, DC_I18N_HITRL " %lfs. endpoint = %s", retry_after, endpoint_formatted ? endpoint_formatted : endpoint);
		sleep(retry_after); /* TODO: prevent hanging entire thread just for this */
		free(s->ptr); s->ptr = NULL;
		free(h->ptr); h->ptr = NULL;
		free(s); s = NULL;
		free(h); h = NULL;
		cJSON_Delete(json);
		json = NULL;
		if (retried++)
			return NULL;
		goto retry;
	}
	rc:
	curl_easy_setopt(c->curl, CURLOPT_HEADERFUNCTION, NULL); /* for usages that don't use headerfunction */
	free(endpoint_formatted);
	free(s->ptr); s->ptr = NULL;
	free(h->ptr); h->ptr = NULL;
	free(s); s = NULL;
	free(h); h = NULL;
	return json;
}
int dc_login (struct dc_client * c) { /* noui */
	int rs = 1;
	char * data = NULL;
	cJSON * json = NULL;
	if (!c)
		return -1;
	if (!c->email || !c->password) {
		DC_CLIENT_ERROR(c, DC_I18N_MISSING_EP);
		return -2;
	}
	if (!c->curl)
		c->curl = curl_easy_init();
	if (!c->curl) {
		DC_CLIENT_ERROR(c, "curl_easy_init() " DC_I18N_FAILED);
		return -3;
	}
	data = malloc(snprintf(NULL, 0, DC_LOGIN_FORMAT, c->email, c->password)+1);
	sprintf(data, DC_LOGIN_FORMAT, c->email, c->password);
	/* curl_slist_free_all(c->curl_headers); */
	c->curl_headers = curl_slist_append(c->curl_headers, "Content-Type: application/json");
	c->curl_headers = curl_slist_append(c->curl_headers, "User-Agent: " DC_USER_AGENT);
	json = DC_CAPI(c, data, DC_API_PREFIX "auth/login");
	if (!json) {
		DC_CLIENT_ERROR(c, "!DC_CAPI auth/login, data = %s", data);
		rs = -4;
		goto rc;
	}
	cJSON * token = cJSON_GetObjectItem(json, "token");
	if (!cJSON_IsString(token)) {
		DC_CLIENT_ERROR(c, "!cJSON_IsString(token)");
		rs = -6;
		goto rc;
	}
	if (DC_CWLE(c, c->authorization_lock)) {rs = -7; goto rc;}
	c->authorization = realloc(c->authorization, strlen(token->valuestring)+1);
	strcpy(c->authorization, token->valuestring);
	data = realloc(data, strlen(c->authorization)+strlen("Authorization: ")+1+1/* last one because valgrind was complaining */);
																					strcpy(data, "Authorization: ");
	strcat(data, c->authorization);
	if (DC_CUE(c, c->authorization_lock)) {rs = -8; goto rc;}
	c->curl_headers = curl_slist_append(c->curl_headers, data);
	cJSON_Delete(json);
	json = DC_CAPI(c, NULL, DC_API_PREFIX "users/@me");
	if (!json) {
		DC_CLIENT_ERROR(c, "!DC_CAPI users/@me");
		rs = -7;
		goto rc;
	}
	token = cJSON_GetObjectItem(json, "username");
	cJSON * token2 = cJSON_GetObjectItem(json, "discriminator");
	if (!cJSON_IsString(token) || !cJSON_IsString(token2)) {
		DC_CLIENT_ERROR(c, "!cJSON_IsString(token) || !cJSON_IsString(token2)");
		rs = -11;
		goto rc;
	}
	if (DC_CWLE(c, c->username_lock)) {rs = -11; goto rc;}
	c->username = realloc(c->username, strlen(token->valuestring)+1);
	strcpy(c->username, token->valuestring);
	if (DC_CUE(c, c->username_lock)) {rs = -12; goto rc;}
	c->discriminator = strtol(token2->valuestring, NULL, 10);
	rc:
	free(data); data = NULL;
	cJSON_Delete(json);
	return rs;
}
int dc_fetch_guilds (struct dc_client * c) {
	if (!c)
		return -5;
	int rs = 1;
	char * value = NULL;
	char * value2 = NULL;
	cJSON * json = NULL;
	if (c->discriminator < 0) {
		if ((rs = dc_login(c)) < 0) {
			DC_CLIENT_ERROR(c, "dc_login(c) " DC_I18N_FAILED " (%d)", rs);
			return -1;
		} else rs = 1;
	}
	json = DC_CAPI(c, NULL, DC_API_PREFIX "users/@me/guilds");
	if (!json) {
		DC_CLIENT_ERROR(c, "DC_CAPI users/@me/guilds " DC_I18N_FAILED);
		rs = -3;
		goto rc;
	}
	if (!cJSON_IsArray(json)) {
		DC_CLIENT_ERROR(c, "!cJSON_IsArray(json)");
		rs = -4;
		goto rc;
	}
	if(DC_CWLE(c, c->guilds_lock)) {rs = -5; goto rc;}
	cJSON * guild = NULL;
	cJSON_ArrayForEach(guild, json) {
		int skip = 0;
		value = cJSON_GetStringValue(cJSON_GetObjectItem(guild, "name"));
		value2 = cJSON_GetStringValue(cJSON_GetObjectItem(guild, "id"));
		if (!value || !value2) {
			char * jsonstr = cJSON_Print(json);
			DC_CLIENT_ERROR(c, "!cJSON_GetStringValue(cJSON_GetObjectItem(json, \"id\" || \"name\")) json = %s", jsonstr);
			free(jsonstr);
			continue;
		}
		unsigned long long int idull = strtoull(value2, NULL, 10);
		for (int i = 0; i < c->guilds_sizeof; i++)
			if (idull == c->guilds[i]->id) {
				skip = 1;
				break; /* remove duplicates */
			}
		if (skip) continue;
		c->guilds = realloc(c->guilds, sizeof(struct dc_guild *)*++c->guilds_sizeof);
		c->guilds[c->guilds_sizeof-1] = calloc(1, sizeof(struct dc_guild));
		c->guilds[c->guilds_sizeof-1]->name = malloc(strlen(value)+1);
		strcpy(c->guilds[c->guilds_sizeof-1]->name, value);
		c->guilds[c->guilds_sizeof-1]->id = idull;
		c->guilds[c->guilds_sizeof-1]->client = c;
	}
	if(DC_CUE(c, c->guilds_lock)) {rs = -6; goto rc;}
	rc:
	cJSON_Delete(json); json = NULL;
	return rs;
}
int dc_fetch_channels (struct dc_guild * g) {
	int rs = 1;
	if (!g)
		return -1;
	struct dc_client * c = g->client;
	if (!c)
		return -2;
	if (c->discriminator < 0) {
		if ((rs = dc_login(c)) < 0) {
			DC_CLIENT_ERROR(c, "dc_login(c) " DC_I18N_FAILED " (%d)", rs);
			return -3;
		} else rs = 1;
	}
	cJSON * json = NULL;
	if (g->altmsgurl)
		json = DC_CAPI(c, NULL, g->altmsgurl); /* used for private dm channels */
	else
		json = DC_CAPI(c, NULL, DC_API_PREFIX "guilds/%llu/channels", g->id); /* ids are only written by api thread, nolock */
	if (!json) {
		DC_CLIENT_ERROR(c, "DC_CAPI id = %llu, g->altmsgurl = %s" DC_I18N_FAILED, g->id, g->altmsgurl ? g->altmsgurl : "NULL" /* static string */);
		rs = -5;
		goto rc;
	}
	if (!cJSON_IsArray(json)) {
		char * jsonstr = cJSON_Print(json);
		DC_CLIENT_ERROR(c, "!cJSON_IsArray(json), g->id = %llu, g->altmsgurl = %s, json = %s", g->id, g->altmsgurl ? g->altmsgurl : "NULL", jsonstr);
		free(jsonstr);
		rs = -6;
		goto rc;
	}
	cJSON * channel = NULL;
	/* cJSON * perms = NULL; */ /* I'll rather not remove the channels with perms and let the user get banned for joining a channel without perms */
	/* cJSON * perm = NULL; */
	/* we lock all client guilds when doing stuff with channels */
	if (DC_CWLE(c, c->guilds_lock)) {rs = -7; goto rc;}
	cJSON_ArrayForEach(channel, json) {
		int skip = 0;
		/* if (cJSON_IsArray(perms = cJSON_GetObjectItem(channel, "permission_overwrites")));
		cJSON_ArrayForEach(perm, perms) {
			skip++;
		}
		if (skip) continue; */
		char * topic = cJSON_GetStringValue(cJSON_GetObjectItem(channel, "topic"));
		char * name = cJSON_GetStringValue(cJSON_GetObjectItem(channel, "name"));
		char * id = cJSON_GetStringValue(cJSON_GetObjectItem(channel, "id"));
		cJSON * type = cJSON_GetObjectItem(channel, "type");
		cJSON * jsonslowmode = cJSON_GetObjectItem(channel, "rate_limit_per_user");
		if (!cJSON_IsNumber(type) || !id) {
			char * krneki = cJSON_Print(channel);
			DC_CLIENT_ERROR(c, "!cJSON_IsNumber(type) || !id, channel = %s", krneki);
			free(krneki); krneki = NULL;
			continue;
		}
		if (type->valueint != 0 && type->valueint != 3 && type->valueint != 1)
			continue;
		if (!name) {
			cJSON * recipients = cJSON_GetObjectItem(channel, "recipients");
			if (!cJSON_IsArray(recipients))
				continue;
			cJSON * rec = NULL;
			name = calloc(1, 1);
			cJSON_ArrayForEach(rec, recipients) {
				char * recipient = cJSON_GetStringValue(cJSON_GetObjectItem(rec, "username"));
				if (!recipient)
					continue;
				name = realloc(name, strlen(name)+strlen(recipient)+3); /* +3: comma, space, null character */
				strcat(name, recipient);
				strcat(name, ", ");
			}
			name[strlen(name)-2] = '\0'; /* odrežemo zadnja dva znaka; vejico in presledek I: */
		}
		int slowmode = 0;
		if (cJSON_IsNumber(jsonslowmode))
			slowmode = jsonslowmode->valueint;
		if (!topic)
			topic = "";
		unsigned long long int idull = strtoull(id, NULL, 10);
		for (int i = 0; i < g->channels_sizeof; i++)
			if (idull == g->channels[i]->id) {
				skip++;
				break;
			}
		if (skip) continue;
		g->channels = realloc(g->channels, sizeof(struct dc_channel *)*++g->channels_sizeof);
		g->channels[g->channels_sizeof-1] = calloc(1, sizeof(struct dc_channel));
		g->channels[g->channels_sizeof-1]->name = malloc(strlen(name)+1);
		strcpy(g->channels[g->channels_sizeof-1]->name, name);
		g->channels[g->channels_sizeof-1]->topic = malloc(strlen(topic)+1);
		strcpy(g->channels[g->channels_sizeof-1]->topic, topic);
		g->channels[g->channels_sizeof-1]->id = strtoull(id, NULL, 10);
		g->channels[g->channels_sizeof-1]->guild = g;
		g->channels[g->channels_sizeof-1]->slowmode = slowmode;
	}
	if (DC_CUE(c, c->guilds_lock)) {rs = -8; goto rc;}
	rc:
	cJSON_Delete(json); json = NULL;
	return rs;
}
int dc_send_message (struct dc_message * m) { /* nolock - once message is appended to the c->sent_messages queue you must not remove it or alter it */
	int rs = 1;
	if (!m)
		return -1;
	struct dc_client * c = m->channel->guild->client; /* segfault senpai */
	if (!c)
		return -2;
	if (c->discriminator < 0) {
		if ((rs = dc_login(c)) < 0) {
			DC_CLIENT_ERROR(c, "dc_login(c) " DC_I18N_FAILED " (%d)", rs);
			return -3;
		} else rs = 1;
	}
	cJSON * json = cJSON_CreateObject();
	cJSON * nons = cJSON_CreateNumber(rand());
	cJSON_AddItemToObject(json, "nonce", nons);
	cJSON * content = cJSON_CreateString(m->content ? m->content : "dc_send_message(): !m->content");
	cJSON_AddItemToObject(json, "content", content);
	cJSON * tts = m->tts ? cJSON_CreateTrue() : cJSON_CreateFalse();
	cJSON_AddItemToObject(json, "tts", tts);
	char * body = cJSON_Print(json);
	if (!body) {
		DC_CLIENT_ERROR(c, "cJSON_Print " DC_I18N_FAILED);
		rs = -4;
		goto rc;
	}
	cJSON_Delete(json); json = NULL;
	/* {content: "yeet", nonce: "820762917392613376", tts: false} */
	json = DC_CAPI(c, body, DC_API_PREFIX "channels/%llu/messages", m->channel->id); /* ids are only written by api thread, nolock */
	if (!json) {
		DC_CLIENT_ERROR(c, "DC_CAPI channels/%llu/messages " DC_I18N_FAILED, m->channel->id);
		rs = -5;
		goto rc;
	}
	char * discriminator = cJSON_GetStringValue(cJSON_GetObjectItem2(json, "author", "discriminator"));
	if (!discriminator) {
		DC_CLIENT_ERROR(c, "!discriminator");
		rs = -6;
		goto rc;
	}
	m->discriminator = strtol(discriminator, NULL, 10);
	char * username = cJSON_GetStringValue(cJSON_GetObjectItem2(json, "author", "username"));
	if (!username) {
		DC_CLIENT_ERROR(c, "!username");
		rs = -6;
		goto rc;
	}
	m->username = malloc(strlen(username)+1);
	strcpy(m->username, username); /* we don't directly point as that changes when we delete */
	rc:
	free(body); body = NULL;
	cJSON_Delete(json); json = NULL;
	c->last_sent_message = time(NULL);
	return rs;
}
int dc_fetch_messages (struct dc_channel * ch) {
	int rs = 1;
	struct tm tm;
	if (!ch || !ch->id)
		return -1;
	struct dc_guild * g = ch->guild;
	if (!g || !g->client)
		return -2;
	struct dc_client * c = g->client;
	if (!c)
		return -3;
	if (c->discriminator < 0) {
		if ((rs = dc_login(c)) < 0) {
			DC_CLIENT_ERROR(c, "dc_login(c) " DC_I18N_FAILED " (%d)", rs);
			return -4;
		} else rs = 1;
	}
	cJSON * json = DC_CAPI(c, NULL, DC_API_PREFIX "channels/%llu/messages?limit=100&_=%d", ch->id, rand());
	if (!json) {
		DC_CLIENT_ERROR(c, "DC_CAPI channels/%llu/messages?limit=100&_=***rand()*** " DC_I18N_FAILED, ch->id);
		rs = -5;
		goto rc;
	}
	if (!cJSON_IsArray(json)) {
		DC_CLIENT_ERROR(c, "!cJSON_IsArray(json)");
		rs = -6;
		goto rc;
	}
	if (DC_CWLE(c, c->guilds_lock)) {rs = -7; goto rc;} /* we lock all guilds of a client when writing messages */
	cJSON * message = NULL;
	int msgs = 0;
	cJSON_ArrayForEach(message, json) {
		int skip = 0;
		char * timestamp = cJSON_GetStringValue(cJSON_GetObjectItem(message, "timestamp"));
		char * content = cJSON_GetStringValue(cJSON_GetObjectItem(message, "content"));
		char * id = cJSON_GetStringValue(cJSON_GetObjectItem(message, "id"));
		char * discriminator = cJSON_GetStringValue(cJSON_GetObjectItem2(message, "author", "discriminator"));
		char * username = cJSON_GetStringValue(cJSON_GetObjectItem2(message, "author", "username"));
		char * attachment = NULL;
		cJSON * attachmentj = NULL;
		cJSON * attachments = cJSON_GetObjectItem(message, "attachments");
		cJSON_ArrayForEach(attachmentj, attachments)
			if ((attachment = cJSON_GetStringValue(cJSON_GetObjectItem(attachmentj, "url"))))
				break; /* we only extract the first attachment */
		if (!id || !timestamp || (!content && !attachment) || !username || !discriminator) {
			DC_CLIENT_ERROR(c, "!id || (!timestamp && !attachment) || !content || !username || discriminator < 0");
			continue;
		}
		int kratekts = 0;
		if (strlen(timestamp) < 26) {
			if (strlen(timestamp) == strlen("2021-03-21T13:54:17+00:00")) {
				kratekts = 1;
			} else {
				char * jsonstring = cJSON_Print(message);
				DC_CLIENT_ERROR(c, "strlen(timestamp) < 26, json = %s", jsonstring);
				free(jsonstring);
				jsonstring = NULL;
				continue;
			}
		}
		if (!kratekts) {
			for (int i = 20; i <= 25; i++)
				timestamp[i] = 'X'; /* because strptime does not have wildcard support and those numbers are sub-second fractions */
			if (!strptime(timestamp, DC_TIMESTAMP_FORMAT, &tm)) {
				DC_CLIENT_ERROR(c, "!strptime(timestamp, DC_TIMESTAMP_FORMAT, &tm), timestamp = %s", timestamp);
				continue;
			}
		} else { /* if there are no subsecond fractions */
			if (!strptime(timestamp, DC_SHORTTIMESTAMP_FORMAT, &tm)) {
				DC_CLIENT_ERROR(c, "!strptime(timestamp, DC_SHORTTIMESTAMP_FORMAT, &tm), timestamp = %s", timestamp);
				continue;
			}
		}
		unsigned long long int idull = strtoull(id, NULL, 10);
		for (int i = 0; i < ch->messages_sizeof; i++)
			if (idull == ch->messages[i]->id) {
				skip++;
				break; /* remove duplicates */
			}
		if (skip) continue;
		ch->messages = realloc(ch->messages, sizeof(struct dc_message *)*++ch->messages_sizeof);
#define DC_FMTM /* fetch messages this message */ ch->messages[ch->messages_sizeof-1]
		/* DC_CLIENT_ERROR(c, "recvd msg %llu", idull); */ /* remember: continue in a nested forloop is not useful in some cases (: */
		DC_FMTM = calloc(1, sizeof(struct dc_message));
		DC_FMTM->time = mktime(&tm);
		if (content)
			strcpy(DC_FMTM->content = malloc(strlen(content)+1), content);
		if (attachment)
			strcpy(DC_FMTM->attachment = malloc(strlen(attachment)+1), attachment);
		DC_FMTM->username = malloc(strlen(username)+1);
		strcpy(DC_FMTM->username, username);
		DC_FMTM->id = idull;
		DC_FMTM->discriminator = strtol(discriminator, NULL, 10);
		DC_FMTM->channel = ch;
		msgs++;
	}
	qsort(ch->messages, ch->messages_sizeof, sizeof(struct dc_message *), dc_message_compare); /* we sort so that present messages are in the start of the array and old messages are to the end of the array */
	if (DC_CUE(c, c->guilds_lock)) {rs = -8; goto rc;}
	if (msgs > 0)
		rs = msgs;
	rc:
	cJSON_Delete(json); json = NULL;
	return rs;
}
struct dc_thread_control {
	unsigned short int power_api; /* 1 if the thread should run, set it to 2 for the thread to return at the end of the loop */
	unsigned short int power_ui; /* so same struct can be used for both api and ui thread, they have individual power switches */
	/* powers have a default state of 0, in this state, the thread should be paused, before first clearing 0 the thread should not do anything! */
	struct dc_client ** clients; /* "array" of pointers to clients the thread should manage, ONLY ONE dc_api_thread PER PROCESS! */
	_Atomic(size_t) clients_sizeof; /* noapiw */
	pthread_rwlock_t * clients_lock; /* do not lock yet. you can use safe-appending from the ui thread by never reallocing the pointers and only incrementing _sizeof - don't even init&destroy*/
	FILE * cout; /* file descriptor of the terminal for the ui thread to write to */
	FILE * cin; /* file descriptor of the terminal for the ui thread to read from */
	FILE * cerr; /* file descriptor of the terminal for the ui thread to write error messages to */
};
int dc_api_thread (struct dc_thread_control * t) { /* updates messages and sends messages when they are in the outbox */
	while (!t->power_api) usleep(250000); /* so as to not make the switcher go bankrupt */
	curl_global_init(CURL_GLOBAL_ALL);
	/* if (pthread_rwlock_wrlock(t->clients_lock))
		return -1; */ /* clients are not locked yet */
	for (int i = 0; i < t->clients_sizeof && t->power_api != 2; i++)
		dc_login(t->clients[i]);
	while (t->power_api != 2) { /* as there's only one api thread and only it modifies things that need a guilds_lock, it's okay to */
		for (int i = 0; i < t->clients_sizeof; i++) { /* perform such unsafe loops without read-locking. note that you will deadlock */
			if (t->clients[i]->discriminator < -1) /* should you attempt to read-lock guilds_lock. */
				continue; /* the only exception is sent_messages that is write-locked */
			if (t->clients[i]->guilds_sizeof <= 1 /* || !(rand() % 1000) */) /* guild 0 is a virtual ZS guild */
				dc_fetch_guilds(t->clients[i]);
			for (int j = 0; j < t->clients[i]->guilds_sizeof; j++) {
				if (!t->clients[i]->guilds[j]->channels_sizeof /*|| !(rand() % 100)*/) /* roughly every 100+inf cycles we'll update channels */
					dc_fetch_channels(t->clients[i]->guilds[j]);
			}
			for (int k = 0; k < t->clients[i]->guilds_sizeof; k++)
				for (int l = 0; l < t->clients[i]->guilds[k]->channels_sizeof; l++)
					if (t->clients[i]->guilds[k]->channels[l]->joined && !(rand() % 10)) /* roughly every 10 cycles we'll update messages in the joined channels */
						if (dc_fetch_messages(t->clients[i]->guilds[k]->channels[l]) > 0)
							t->clients[i]->newmessages++;
			if (DC_CWLE(t->clients[i], t->clients[i]->sent_messages_lock)) continue;
			if (t->clients[i]->sent_messages_sizeof > 0) {
				struct dc_message * msg2send = t->clients[i]->sent_messages[0];
				if (dc_send_message(msg2send) > 0) {
					/* DC_CWLE(t->clients[i], t->clients[i]->guilds_lock);
					msg2send->channel->messages = realloc(msg2send->channel->messages, sizeof(struct dc_message *)*++msg2send->channel->messages_sizeof);
					msg2send->channel->messages[msg2send->channel->messages_sizeof-1] = msg2send;
					DC_CUE(t->clients[i], t->clients[i]->guilds_lock); */ /* we will no longer do this, let the thread fetch the msg */
					for (int j = 0; j < t->clients[i]->sent_messages_sizeof-1; j++) /* shift, we removed one from the start */
						t->clients[i]->sent_messages[j] = t->clients[i]->sent_messages[j+1];
					t->clients[i]->sent_messages_sizeof--;
				}
			}
			DC_CUE(t->clients[i], t->clients[i]->sent_messages_lock);
			while (!t->power_api) usleep(250000); /* so as to not make the switcher go bankrupt */
		}
		usleep(250000);
	}
	curl_global_cleanup();
	/* if (pthread_rwlock_unlock(t->clients_lock))
		return -2; */
	return 1;
} /* the thread shall use mutexes when doing things with shared memory - client structs */