summaryrefslogtreecommitdiffstats
path: root/src/api.c
blob: c405cfff1aa56c55bbce831180f5a0ec6fd57c49 (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
#define DC_LOGIN_FORMAT "{\"login\":\"%s\",\"password\":\"%s\",\"undelete\":false,\"captcha_key\":null,\"login_source\":null,\"gift_code_sku_id\":null}"
#define DC_COMPILE_INFO __VERSION__ " "  __BASE_FILE__ " " __FILE__ " " __TIMESTAMP__
#define DC_STR(x) x
#define DC_USER_AGENT "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36" /* this is so we can fool the login system */
#define DC_SERVER_ADDRESS "discord.com"
#define DC_SERVER_PORT 443
#define DC_SERVER_SSL 1
#define DC_SERVER_ORIGIN "https://discord.com"
#define DC_WS_ADDRESS "gateway.discord.gg"
#define DC_WS_PORT DC_SERVER_PORT
#define DC_WS_SSL DC_SERVER_SSL
#define DC_WS_ORIGIN DC_SERVER_ORIGIN
#define DC_WS_PATH "/?encoding=json&v=9"
#define DC_API_PREFIX "/api/v9/"
#define DC_LWS_ABLE_TO_PARSE_HEADERS 1
#define DC_RECONNECT_DELAY 10
unsigned char dc_api_identify_u[] = {
#include <identify.xxd>
};
char * dc_api_identify = (char *) dc_api_identify_u;
/* libwebsockets information: libwebsockets works with event loops and discord.c primary targets debian for building (it must work on debian), but debian does not ship libwebsockets with glib or libevent event loop support, so loops are implemented in the classic poll() style. this reduces performance probably. if you use discord.c API with support for a platform specific event loop, you may rewrite LWS to do things differently. currently calls into API (dc_api_i and dc_api_o) will both do LWS stuff. */
void dc_api_stack (struct dc_api_io i) { /* stack output struct to be delivered via dc_api_o 2usr */
	DC_MR(i.program->api_ios);
	assert((i.program->api_ios[i.program->api_ios_length] = malloc(sizeof(i))));
	*(i.program->api_ios[i.program->api_ios_length++]) = i;
	return;
}
signed char dc_json_cb (struct lejp_ctx * ctx, char reason) { /* to prevent warnings of incompatible pointer times, we create a new type with enum later on */
	enum dc_json_paths path = ctx->path_match-1; /* we assume that the order of incoming data is */
	struct dc_lws_pass * pass = ctx->user; /* correct. op and t should come first, etc. */
	struct dc_client * client = pass->api_io.client; 
	struct dc_program * program = pass->api_io.program;
	pass->json_reason = reason;
	if (reason == LEJPCB_FAILED || reason == LEJPCB_COMPLETE || reason == LEJPCB_START) {
		DC_API_IO_GC(pass->api_io);
		pass->packet = DC_NONE;
		return '\0';
	}
	if (getenv("DC_J")) /* print json to standard error */
		fprintf(stderr, "JSON: %s %s\n", ctx->path, ctx->buf);
	if (ctx->path_match && reason & LEJP_FLAG_CB_IS_VALUE) {
		switch (path) {
			case DC_JSON_S: /* packet sequence number */
				pass->api_io.client->last_packet = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_OP:
				switch (atoi(ctx->buf)) {
					case DC_PING:
						client->last_ping = 0;
						dc_handle_ping(pass->api_io, NULL);
						break;
					default:
						break;
				}
				break;
			case DC_JSON_PING:
				pass->api_io.client->ping_interval = atoi(ctx->buf)/1000-1;
				pass->api_io.client->last_ping = time(NULL); /* we don't ping b4 IDENT */
				break;
			case DC_JSON_T:
				for (size_t i = 0; i < sizeof(dc_ws_packet)/sizeof(dc_ws_packet[0]); i++)
					if (strcmp(dc_ws_packet[i], ctx->buf)) {
						pass->packet = DC_STRPKTOFF+i;
						break;
					}
				break;
			default: /* to prevent warning: enumeration value DC_JSON_* not handled */
				break;
		}
	}
	if (reason & LEJP_FLAG_CB_IS_VALUE && (path == DC_JSON_ME_USERNAME || path == DC_JSON_ME_ID || path == DC_JSON_ME_DISCRIMINATOR) && (!client->user || !client->user->username || !client->user->id || client->user->status & DC_INCOMPLETE)) { /* if filled, then it's someone else */
		if (!client->user) { /* on first d.user this is our user, subsequent are someone else! */
			DC_MR(program->users); /* don't need DC_IN_PROGRESS, we have ref in cl */
			program->users[program->users_length++] = client->user = dc_user_init();
			client->user->status |= DC_INCOMPLETE; /* when ->disc is set, it's complete */
		} /* we do not check on the object end */
		switch (path) { /* email is already set from login */
			case DC_JSON_ME_USERNAME:
				if (!client->user->username) client->user->username = strdup(ctx->buf);
				break;
			case DC_JSON_ME_ID:
				if (!client->user->id) client->user->id = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_ME_DISCRIMINATOR:
				if (client->user->status & DC_INCOMPLETE) { /* we can't just check if */
					client->user->discriminator = atoi(ctx->buf); /* !discriminat, */
					client->user->status &= ~DC_INCOMPLETE; /* because 0 is allowd */
				}
				break;
			default:
				break;
		}
		return '\0'; /* because we use same checks for parsing other users GUILD_MEMBER_UPDATE */
	}
	if ((path == DC_JSON_ME || path == DC_JSON_USER || path == DC_JSON_MESSAGE_AUTHOR || path == DC_JSON_MESSAGE_REFOBJ_AUTHOR || path == DC_JSON_MESSAGE_MENTION_USER || path == DC_JSON_MESSAGE_REFOBJ_MENTION_USER || path == DC_JSON_MEMBER) && reason == LEJPCB_OBJECT_START) {
		/* dc_user_free(pass->api_io.user); */ /* parser branches MUST ALWAYS set to 0 */
		pass->api_io.user = dc_user_init(); /* and possibly free api_io members after! */
		pass->api_io.user->status |= DC_IN_PROGRESS; /* if we never get here again */
	}
	if ((path == DC_JSON_ME || path == DC_JSON_USER || path == DC_JSON_MESSAGE_AUTHOR || path == DC_JSON_MESSAGE_REFOBJ_AUTHOR || path == DC_JSON_MESSAGE_MENTION_USER || path == DC_JSON_MESSAGE_REFOBJ_MENTION_USER || path == DC_JSON_MEMBER) && reason == LEJPCB_OBJECT_END) {
		if (getenv("DC_R"))
			assert(pass->api_io.user->id);
		if (!pass->api_io.user->id) {
			dc_user_free(pass->api_io.user, DC_UNSET);
			pass->api_io.user = NULL;
			return '\0';
		}
		pass->api_io.user->status &= ~DC_IN_PROGRESS;
		pass->api_io.user = dc_addr_user(program, DC_ISAE(program->users), pass->api_io.user, DC_MAY_FREE);
		switch (path) {
			case DC_JSON_MESSAGE_AUTHOR:
				if (pass->api_io.message)
					pass->api_io.message->user = pass->api_io.user;
				break;
			case DC_JSON_MESSAGE_REFOBJ_AUTHOR:
				if (pass->api_io.message && pass->api_io.message->reply)
					pass->api_io.message->reply->user = pass->api_io.user;
				break;
			case DC_JSON_MESSAGE_MENTION_USER:
				if (pass->api_io.message)
					dc_add_user(DC_ISAE(pass->api_io.message->users), pass->api_io.user, DC_UNSET);
				break;
			case DC_JSON_MESSAGE_REFOBJ_MENTION_USER:
				if (pass->api_io.message && pass->api_io.message->reply)
					dc_add_user(DC_ISAE(pass->api_io.message->reply->users), pass->api_io.user, DC_UNSET);
				break;
			default:
				break;
		}
		pass->api_io.user = NULL;
	}
	if ((path == DC_JSON_DM || path == DC_JSON_GUILD_CHANNEL) && reason == LEJPCB_OBJECT_START) {
		pass->api_io.channel = dc_channel_init();
		pass->api_io.channel->status |= DC_IN_PROGRESS;
	}
	if (path == DC_JSON_DM && reason == LEJPCB_OBJECT_END) {
		struct dc_channel ** channel = &client->guilds[0]->channel; /* 1. guild = DMs */
		while (*channel)
			channel = &(*channel)->next;
		if (!pass->api_io.channel->id) {
			dc_channel_free(pass->api_io.channel, DC_UNSET);
			pass->api_io.channel = NULL;
			return '\0';
		}
		pass->api_io.channel->next = NULL;
		pass->api_io.channel->guild = client->guilds[0]; /* client->guilds[0] always exists */
		pass->api_io.channel->status &= ~DC_IN_PROGRESS;
		free(pass->api_io.channel->topic);
		pass->api_io.channel->topic = strdup("");
		for (size_t i = 0; i < pass->api_io.channel->users_length; i++) {
			pass->api_io.channel->topic = realloc(pass->api_io.channel->topic, strlen(pass->api_io.channel->topic) + strlen(pass->api_io.channel->users[i]->username) + 1 + 2 + 1 + 4);
			char buf[64];
			snprintf(buf, 63, "#%04d%s", pass->api_io.channel->users[i]->discriminator, i+1 < pass->api_io.channel->users_length ? ", " : "");
			strcat(pass->api_io.channel->topic, pass->api_io.channel->users[i]->username);
			strcat(pass->api_io.channel->topic, buf);
		}
		struct dc_channel * ch;
		if ((ch = dc_find_channel(program->channels, program->channels_length, pass->api_io.channel->id)))
			DC_TRANSFER_CHANNEL(pass->api_io.channel, ch);
		pass->api_io.channel = dc_addr_channel(program, DC_ISAE(program->channels), pass->api_io.channel, DC_MAY_FREE | DC_REPLACE);
		if (!dc_find_ll_channel(client->guilds[0]->channel, pass->api_io.channel->id)) {
			fprintf(stderr, "new DM id=%llu (:\n", pass->api_io.channel->id);
			pass->api_io.channel->next = NULL;
			*channel = pass->api_io.channel;
		}
		pass->api_io.channel->guild = client->guilds[0];
		pass->api_io.channel = NULL; /* we're done, NULL it or PROBLEMS WILL APPEAR!!! */
	}
	if (path == DC_JSON_GUILD_CHANNEL && reason == LEJPCB_OBJECT_END) {
		if (!pass->api_io.channel->id || !DC_CHANNEL_SUPPORTED(pass->api_io.channel->type)) {
			dc_channel_free(pass->api_io.channel, DC_UNSET);
			pass->api_io.channel = NULL;
			return '\0';
		}
		struct dc_channel ** channel = &pass->api_io.guild->channel;
		while (*channel)
			channel = &(*channel)->next;
		struct dc_channel * ch;
		if ((ch = dc_find_channel(program->channels, program->channels_length, pass->api_io.channel->id)))
			DC_TRANSFER_CHANNEL(pass->api_io.channel, ch);
		pass->api_io.channel = dc_addr_channel(program, DC_ISAE(program->channels), pass->api_io.channel, DC_MAY_FREE | DC_REPLACE);
		if (!dc_find_ll_channel(pass->api_io.guild->channel, pass->api_io.channel->id)) {
			fprintf(stderr, "new channel id=%llu (:\n", pass->api_io.channel->id);
			pass->api_io.channel->next = NULL;
			*channel = pass->api_io.channel;
		}
		struct dc_permission ** pe = &pass->api_io.channel->permission;
		while (*pe) { /* fix all permission pointers to channel to this new channel */
			(*pe)->channel = pass->api_io.channel;
			pe = &(*pe)->next;
		}
		pass->api_io.channel = NULL; /* we're done, NULL it or  */
	}
	if (path == DC_JSON_GUILD && reason == LEJPCB_OBJECT_START) {
		pass->api_io.guild = dc_guild_init();
		pass->api_io.guild->status |= DC_IN_PROGRESS;
	}
	if (path == DC_JSON_GUILD && reason == LEJPCB_OBJECT_END) {
		if (!pass->api_io.guild->id) {
			dc_guild_free(pass->api_io.guild, DC_UNSET);
			pass->api_io.guild = NULL;
			return '\0';
		}
		pass->api_io.guild->status &= ~DC_IN_PROGRESS;
		pass->api_io.guild = dc_addr_guild(program, DC_ISAE(program->guilds), pass->api_io.guild, DC_MAY_FREE | DC_REPLACE); /* when we replace, new guild's chs' & roles' ptrs */
		struct dc_channel ** channel = &pass->api_io.guild->channel; /* to guild will be inv. */
		struct dc_role ** role = &pass->api_io.guild->role;
		while (*channel) {
			(*channel)->guild = pass->api_io.guild;
			channel = &(*channel)->next;
		}
		while (*role) {
			(*role)->guild = pass->api_io.guild;
			role = &(*role)->next;
		}
		struct dc_guild * gu;
		if ((gu = dc_find_guild(program->guilds, program->guilds_length, pass->api_io.guild->id)))
			DC_TRANSFER_GUILD(pass->api_io.guild, gu);
		dc_add_guild(DC_ISAE(client->guilds), pass->api_io.guild, DC_UNSET);
		pass->api_io.guild = NULL; /* we're done, NULL it or PROBLEMS WILL APPEAR!!! */
	}
	if (path == DC_JSON_GUILD_ROLE && reason == LEJPCB_OBJECT_START) {
		pass->api_io.role = dc_role_init();
		pass->api_io.role->status |= DC_IN_PROGRESS;
	}
	if (path == DC_JSON_GUILD_ROLE && reason == LEJPCB_OBJECT_END) {
		if (!pass->api_io.role->id) {
			dc_role_free(pass->api_io.role, DC_UNSET);
			pass->api_io.role = NULL;
			return '\0';
		}
		pass->api_io.role->status &= ~DC_IN_PROGRESS;
		struct dc_role * ro;
		if ((ro = dc_find_role(program->roles, program->roles_length, pass->api_io.role->id)))
			dc_transfer_role(pass->api_io.role, ro);
		pass->api_io.role = dc_add_role(DC_ISAE(program->roles), pass->api_io.role, DC_MAY_FREE | DC_REPLACE);
		struct dc_role ** role;
		role = &pass->api_io.guild->role;
		while (*role)
			role = &(*role)->next;
		*role = pass->api_io.guild->role;
		pass->api_io.role->guild = pass->api_io.guild;
		if (pass->api_io.role->name && !strncmp(pass->api_io.role->name, "@everyone", strlen(pass->api_io.role->name)))
			pass->api_io.role->status |= DC_EVERYONE;
		pass->api_io.role = NULL; /* we're done, NULL it or PROBLEMS WILL APPEAR!!! */
	}
	if (path == DC_JSON_MEMBERSHIP && (reason == LEJPCB_OBJECT_END || reason == LEJPCB_OBJECT_START))
		pass->api_io.id = 0;
	if (reason & LEJP_FLAG_CB_IS_VALUE) {
		struct dc_user * user; /* this is just a var for you use */
		struct dc_role * role; /* now we rely on -Wuninitialized to detect weird stuff */
		unsigned long long int id; /* so don't initialize them here, that'd be wrong */
		int št;
		switch (path) {
			case DC_JSON_FRIEND: /* we assume we get users[] before relationships[] */
				user = dc_find_user(program->users, program->users_length, strtoull(ctx->buf, NULL, 10));
				if (user)
					dc_add_user(DC_ISAE(client->users), user, DC_UNSET);
				break;
			case DC_JSON_DM_USER: /* we assume we get users[] before private_channels[] */
				user = dc_find_user(program->users, program->users_length, strtoull(ctx->buf, NULL, 10));
				if (user && pass->api_io.channel)
					dc_add_user(DC_ISAE(pass->api_io.channel->users), user,DC_UNSET);
				break;
			case DC_JSON_ME_USERNAME: /* we are always checking for user because evil srv */
			case DC_JSON_USER_NAME: /* might insert dots in keys and prevent OBJECT_CREATE */
			case DC_JSON_MEMBER_USERNAME:
				if (pass->api_io.user && !pass->api_io.user->username) /* no trust srv */
					pass->api_io.user->username = strdup(ctx->buf);
				break;
			case DC_JSON_ME_ID:
			case DC_JSON_USER_ID:
			case DC_JSON_MEMBER_ID:
				if (pass->api_io.user)
					pass->api_io.user->id = strtoll(ctx->buf, NULL, 10);
				break;
			case DC_JSON_ME_DISCRIMINATOR:
			case DC_JSON_USER_DISCRIMINATOR:
			case DC_JSON_MEMBER_DISCRIMINATOR:
				if (pass->api_io.user)
					pass->api_io.user->discriminator = atoi(ctx->buf);
				break; /* yeah, we don't care about nicknames */
			case DC_JSON_DM_TYPE:
			case DC_JSON_GUILD_CHANNEL_TYPE:
				if (pass->api_io.channel)
					pass->api_io.channel->type = atoi(ctx->buf);
				break;
			case DC_JSON_DM_ID:
			case DC_JSON_GUILD_CHANNEL_ID:
				if (pass->api_io.channel)
					pass->api_io.channel->id = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_DM_NAME:
			case DC_JSON_GUILD_CHANNEL_NAME:
				if (pass->api_io.channel && !pass->api_io.channel->name)
					pass->api_io.channel->name = strdup(ctx->buf);
				break;
			case DC_JSON_GUILD_NAME:
				if (pass->api_io.guild && !pass->api_io.guild->name)
					pass->api_io.guild->name = strdup(ctx->buf);
				break;
			case DC_JSON_GUILD_ID:
				if (pass->api_io.guild)
					pass->api_io.guild->id = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_GUILD_CHANNEL_TOPIC:
				if (pass->api_io.channel && !pass->api_io.channel->topic)
					pass->api_io.channel->topic = strdup(ctx->buf);
				break;
			case DC_JSON_GUILD_ROLE_ID:
				if (pass->api_io.role)
					pass->api_io.role->id = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_GUILD_ROLE_NAME:
				if (pass->api_io.role && !pass->api_io.role->name)
					pass->api_io.role->name = strdup(ctx->buf);
				break;
			case DC_JSON_GUILD_ROLE_PERMISSION:
				if (pass->api_io.role) {
					if (strtoull(ctx->buf, NULL, 10) & DC_ADMIN)
						pass->api_io.role->permissions = DC_ALL_PERMISSIONS;
					else
						pass->api_io.role->permissions = strtoull(ctx->buf, NULL, 10);
				}
				break;
			case DC_JSON_MEMBERSHIP_USER:
				pass->api_io.id = strtoull(ctx->buf, NULL, 10);
				break;
			case DC_JSON_MEMBERSHIP_ROLE:
			case DC_JSON_MEMBER_ROLE:
				if (!pass->api_io.id) /* we assume we get ID first */
					if (!pass->api_io.user || !(pass->api_io.id = pass->api_io.user->id))
						break;
				if (!(id = strtoull(ctx->buf, NULL, 10)))
					break;
				št = 0;
				if (!(user = dc_find_user(program->users, program->users_length, pass->api_io.id))) {
					št |= 1;
					user = dc_user_init();
				}
				if (!(role = dc_find_role(program->roles, program->roles_length, id))) {
					št |= 2;
					role = dc_role_init();
					role->id = id;
				}
				dc_add_user(DC_ISAE(role->users), user, DC_UNSET);
				if (št & 1)
					dc_addr_user(program, DC_ISAE(program->users), user, DC_UNSET);
				if (št & 2)
					dc_addr_role(program, DC_ISAE(program->roles), role, DC_UNSET);
				fprintf(stderr, "new role membership user %s#%d (usr=%llu role=%llu)\n", user->username ? user->username : "", user->discriminator, user->id, role->id);
				pass->api_io.id = 0;
				break;
			default:
				break;
		}
	}
	if (pass->packet == DC_NONE) /* useless to do anything BELOW if we haven't recvd packet type */
		return '\0';
	switch (pass->packet) {
		case DC_MESSAGE_CREATE:
			break;
		default:
			break;
	}
	return '\0'; /* by the way, what does the return value do here? write in the comments below (; */
}
static int dc_lws_cb (struct lws * wsi, enum lws_callback_reasons rs, void * us, void * in, size_t len) {
	struct dc_lws_pass * pass = (struct dc_lws_pass *) us;
	unsigned char buf[LWS_PRE+DC_LWS_BUF+1]; /* whooh, boy, this is more than a meg of stack! */
	switch (rs) {
		case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: /* TODO: handle and report somehow */
			if (pass) {
				pass->api_io.status = DC_NET_ERROR;
				pass->wsi = NULL;
				pass->api_io.status |= DC_FROM_LWS;
				dc_api_i(pass->api_io);
				pass->api_io.status &= ~DC_FROM_LWS;
			}
			lwsl_err("CLIENT_CONNECTION_ERROR: %s\n", in ? (char *) in : "(null)");
			break;
		case LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: /* lws gives us len space after *in */
			;
			unsigned char ** p = (unsigned char **) in, * end = (*p)+len;
			for (int i = 0; i < DC_LWS_HEADERS_LENGTH; i++)
				if (pass->headers[i][0])
					if (lws_add_http_header_by_name(wsi, (const unsigned char *) dc_lws_headers[i], (const unsigned char *) pass->headers[i], strlen(pass->headers[i]), p, end))
						return -1;
			char slen[32];
			snprintf(slen, 32, "%u", pass->body_length);
			if (lws_add_http_header_by_name(wsi, (const unsigned char *) "Content-Length:", (const unsigned char *) slen, strlen(slen), p, end))
				return -1;
			if (!lws_http_is_redirected_to_get(wsi)) {
				lwsl_user("doing POST flow\n");
				lws_client_http_body_pending(wsi, 1);
				lws_callback_on_writable(wsi);
			} else
				lwsl_user("doing GET flow, got redirected - this is a bug, report!\n");
			break;
		case LWS_CALLBACK_CLIENT_HTTP_WRITEABLE: /* see minimal post example on how to send */
			if (lws_http_is_redirected_to_get(wsi)) {
				fprintf(stderr, "http is redirected to get\n");
				break;	/* for setting avatar pictures or uploading files. Yecch */
			}
			fprintf(stderr, "LWS_CALLBACK_CLIENT_HTTP_WRITABLE, %d\n", pass->api_io.status);
			if (lws_write(wsi, (unsigned char *) pass->body, pass->body_length, LWS_WRITE_HTTP_FINAL) != (int) pass->body_length) { /* TODO: fix to allow sending large bodies */
				fprintf(stderr, "lws_write can't write that much!\n");
				return 1;
			}
			lws_client_http_body_pending(wsi, 0);
			pass->body_length = 0;
			break;
		case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP:
			pass->status = lws_http_client_http_response(wsi); /* 200 OK, 404 Not Found,...*/
			fprintf(stderr, "Connected with server response: %d\n", pass->status);
#ifdef DC_LWS_ABLE_TO_PARSE_HEADERS
			/* how to query custom headers (http 1.x only at the moment) */
			for (int i = 0; i < DC_LWS_HEADERS_LENGTH; i++) {
				pass->headers[i][0] = '\0'; /* to clear any headers we requested with */
				int n = lws_hdr_custom_length(wsi, dc_lws_headers[i], strlen(dc_lws_headers[i]));
				if (n < -1)
					lwsl_notice("Error with header %s.\n", dc_lws_headers[i]);
				else
					if (lws_hdr_custom_copy(wsi, pass->headers[i], DC_LWS_MAX_HEADER_LENGTH, dc_lws_headers[i], strlen(dc_lws_headers[i])) < 0)
						lwsl_notice("Header %s too long or non existent.\n", dc_lws_headers[i]);
					else
						lwsl_notice("%s %s\n", dc_lws_headers[i], pass->headers[i]);
			}
#endif
			break;
		case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ: /* chunked body, without headers */
			fprintf(stderr, "RECEIVE_CLIENT_HTTP_READ: read %d, current pass->body_length %d\n", len, pass->body_length);
			pass->body = realloc(pass->body, pass->body_length + len + 1);
			memcpy(pass->body+pass->body_length, in, len);
			pass->body[(pass->body_length += len)] = '\0';
			fprintf(stderr, "contents of pass->body: %s\n", pass->body);
			return 0; /* don't pass to lws_callback_http_dummy */
		case LWS_CALLBACK_RECEIVE_CLIENT_HTTP: /* uninterpreted http content */
			;
			char * ptr = (char *) buf + LWS_PRE; /* see, BEFORE the pointer - lower addr */
			int len2 /* DC_LWS_BUF again */ = sizeof(buf) - LWS_PRE;
			if (lws_http_client_read(wsi, &ptr, &len2) < 0) {
				fprintf(stderr, "lws_http_client_read -1\n");
				return -1;
			}
			return 0; /* don't pass to lws_callback_http_dummy */
		case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
			lwsl_user("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
			break;
		case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
			lwsl_user("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
			break;
		case LWS_CALLBACK_WSI_DESTROY: /* if I understand the docs correctly, this is allways */
			if (pass->api_io.pass != pass)
				fprintf(stderr, "[!!!] REPORT THIS BUG: pass->api_io.pass != pass\n");
			if (pass->api_io.status & DC_DESTROY_CB) {
				pass->api_io.status |= DC_FROM_LWS;
				dc_api_i(pass->api_io);
				pass->api_io.status &= ~DC_FROM_LWS;
			}
			DC_API_IO_GC(pass->api_io); /* frees all unfinished parsing objects */
			pass->packet = DC_NONE;
			pass->api_io.client->pass = NULL;
			dc_lws_pass_free(pass, DC_UNSET); /* called the last time us ptr & wsi r still */
			break; /* accessible - we can free the struct that was passed in as a heap ptr */
		case LWS_CALLBACK_WSI_CREATE: /* first - outermost - call with wsi present */
			if (pass->api_io.client) {
				if (pass->api_io.status & DC_SET_PASS) {
					fprintf(stderr, "pass->api_io.client->pass = pass\n");
					pass->api_io.client->pass = pass;
				}
				if (pass->api_io.status & DC_SET_WS_ACTIVE) /* how to get if wsi is ws */
					pass->api_io.client->status |= DC_WS_ACTIVE; /* or http? IDFK. */
			}
			break;
		case LWS_CALLBACK_CLIENT_ESTABLISHED: /* websocket established */
			fprintf(stderr, "LWS_CALLBACK_CLIENT_ESTABLISHED\n");
			pass->api_io.status = DC_OK;
			pass->wsi = wsi;
			pass->api_io.status |= DC_FROM_LWS;
			dc_api_i(pass->api_io);
			pass->api_io.status &= ~DC_FROM_LWS;
			break;
		case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE:
			pass->reason = 0;
			if (len < 2)
				fprintf(stderr, "SERVER CLOSED CONNECTION WITHOUT PROIVIDING REASON!\n");
			else
				pass->reason = ntohs(*(uint16_t *) in /* i sure hope this is legal */);
			fprintf(stderr, "SERVER CLOSED CONNECTION WITH REASON %d\n", pass->reason);
			if (len > 2)
				fprintf(stderr, "with additional message: %.*s\n", len-2, (char *) in+2);
			break;
		case LWS_CALLBACK_CLIENT_CLOSED: /* websocket closed */
			pass->api_io.client->disconnect_time = time(NULL);
			DC_API_IO_GC(pass->api_io); /* frees all unfinished parsing objects */
			pass->packet = DC_NONE;
			pass->api_io.status = DC_NET_ERROR;
			pass->wsi = NULL;
			pass->api_io.status |= DC_FROM_LWS;
			dc_api_i(pass->api_io);
			pass->api_io.status &= ~DC_FROM_LWS;
			break;
		case LWS_CALLBACK_CLIENT_RECEIVE: /* websocket receive, pass to json parser ? */
			if (getenv("DC_N")) /* output received network to stdout */
				fprintf(stdout, "%.*s", len, (const unsigned char *) in);
			if (pass->json_reason == LEJPCB_COMPLETE || pass->json_reason == LEJPCB_FAILED || !(pass->api_io.status & DC_LEJP_CONSTRUCTED)) { /* we regenerate a new context in case we didn't do that yet or in case the previous one finished parsing */
				pass->api_io.status |= DC_LEJP_CONSTRUCTED;
				pass->packet = DC_NONE;
				lejp_construct(&pass->json_ctx, dc_json_cb, us /* == (void *) pass */, (const char * const *) dc_json_paths, LWS_ARRAY_SIZE(dc_json_paths));
			} /* lejp_parse does return number of excess bytes after parsing json. but I */
			pass->len = len; /* assume that server sends in chunks that always terminate */
			pass->cp = in; /* when json object terminates. valve pls fix */
			lejp_parse(&pass->json_ctx, (const unsigned char *) in, len);
			break;
		case LWS_CALLBACK_CLIENT_WRITEABLE: /* invoke with lws_callback_on_writeable(wsi) 4 ws */
			if (!pass->api_io.client) /* we empty all payloads from 0 to finish */
				break;
			for (size_t i = 0; i < pass->api_io.client->payloads_length; i++) {
				char * body = pass->api_io.client->payloads[i]->body;
				size_t length = pass->api_io.client->payloads[i]->length;
				fprintf(stderr, "going to write to ws: %.*s\n", length, body);
				if (lws_write(wsi, (unsigned char *) body, length, LWS_WRITE_BINARY) != (int) length) { /* body already has LWS_PRE bytes allocated before it */
					fprintf(stderr, "ws lws_write failed!\n");
					return -1;
				}
				dc_payload_free(pass->api_io.client->payloads[i], DC_UNSET);
				pass->api_io.client->payloads[i] = NULL; /* THIS MUST BE DONE, otherws */
			} /* _free function will double free, because it frees till _sizeof */
			pass->api_io.client->payloads_length = 0;
			break;
		default:
			break;
	}
	return lws_callback_http_dummy(wsi, rs, us, in, len);
}
void dc_api_i (struct dc_api_io i) { /* this function does not call attached functions, only output does that */
	struct lws_client_connect_info info;
	struct dc_lws_pass * pass;
	if (!i.program)
		return;
	if (i.program->lws_context && !(i.status & DC_FROM_LWS))
		lws_service(i.program->lws_context, 0); /* DO NOT CALL THIS FROM _cb! */
	switch (i.type) {
		case DC_API_MESSAGE:
			break;
		case DC_API_CHANNEL:
			break;
		case DC_API_GUILD:
			break;
		case DC_API_LOGIN: /* TODO: library currently only works for a single client */
			if (!i.program->clients_length) /* already attempted login */
				DC_MR(i.program->clients);
			i.program->clients[0] = i.client;
			i.program->clients_length = 1;
			memset(&info, 0, sizeof(info));
			info.context = i.program->lws_context;
#if DC_SERVER_SSL
			info.ssl_connection = LCCSCF_USE_SSL;
#endif
			info.port = DC_SERVER_PORT;
			info.address = DC_SERVER_ADDRESS;
			info.path = DC_API_PREFIX "auth/login";
			info.host = info.address;
			/* info.origin = DC_SERVER_ORIGIN; */ /* just don't send it */
			info.method = "POST";
			pass = calloc(1, sizeof(struct dc_lws_pass)); /* cb frees */
			fprintf(stderr, "allocated pass at %p\n", (void *) pass);
			i.status |= DC_DESTROY_CB; /* so that lws_cb will call api on destroy - fin rq */
			pass->body_length = asprintf(&pass->body, DC_LOGIN_FORMAT, i.client->email, i.client->password);
			fprintf(stderr, "length: %u string: %s\n", pass->body_length, pass->body);
			i.type = DC_API_LOGIN_CB;
			i.status &= ~DC_SET_PASS; /* this is a HTTP request, pass is for websockets */
			memcpy(&pass->api_io, &i, sizeof(i));
			pass->api_io.pass = pass;
			strcpy(pass->headers[DC_LWS_CONTENT_TYPE], "application/json");
			info.userdata = pass;
#if DC_LWS_ABLE_TO_PARSE_HEADERS
			info.alpn = "http/1.1";
#endif
			info.protocol = dc_lws_protocols[0].name;
			if (i.client->authorization) /* attempt cookie login without user/pass */
				strcpy(pass->headers[DC_LWS_AUTHORIZATION], i.client->authorization);
			i.status = DC_UNSET /* we clear the status */;
			lws_client_connect_via_info(&info);
			break;
		case DC_API_LOGIN_CB:
#define DC_STACK_RETURN(x) do { i.client->status = x; dc_api_stack(i); return; } while (0)
			i.type = DC_API_LOGIN;
			i.status &= ~DC_OK;
			if (!i.pass->body) {
				i.client->status |= DC_REQUEST_FAILED;
				dc_api_stack(i);
				break;
			}
			fprintf(stderr, "DEBUG: %s\n", i.pass->body);
			if (strstr(i.pass->body, "INVALID_LOGIN"))
				DC_STACK_RETURN(DC_BAD_LOGIN);
			if (strstr(i.pass->body, "captcha-required"))
				DC_STACK_RETURN(DC_CAPTCHA_NEEDED);
			if (strstr(i.pass->body, "ACCOUNT_LOGIN_VERIFICATION_EMAIL"))
				DC_STACK_RETURN(DC_VERIFICATION_NEEDED);
			char * cp, * c2;
#define DC_LTS "\"token\": \""
			if (!(cp = strstr(i.pass->body, DC_LTS)+strlen(DC_LTS)) || !(c2 = strchr(cp+strlen(DC_LTS), '"')))
				DC_STACK_RETURN(DC_ERROR);
			c2[0] = '\0'; /* body is on heap, we can edit it */
			free(i.client->authorization); /* in case we set it previously */
			i.client->authorization = strdup(cp);
			fprintf(stderr, "got token %s\n", i.client->authorization);
			i.client->status |= DC_OK | DC_INCOMPLETE;
			dc_api_stack(i);
			/* we now have to connect to the websocket */
			goto ws; /* we could call dc_api_i but that just fills stack */
			break;
		case DC_API_WS:
			fprintf(stderr, "DC_API_WS called\n");
			ws:
			memset(&info, 0, sizeof(info));
			info.context = i.program->lws_context;
			if (!info.context)
				fprintf(stderr, "[BUG] !!! !info.context\n");
			info.port = DC_WS_PORT;
			info.address = DC_WS_ADDRESS;
			info.path = DC_WS_PATH;
			info.host = info.address;
			info.origin = DC_WS_ORIGIN;
#if DC_WS_SSL
			info.ssl_connection = LCCSCF_USE_SSL;
#endif
			info.protocol = dc_lws_protocols[0].name;
			info.local_protocol_name = info.protocol;
			pass = calloc(1, sizeof(struct dc_lws_pass));
			i.type = DC_API_WS_CB;
			i.status |= DC_SET_PASS | DC_SET_WS_ACTIVE;
			i.status &= ~DC_DESTROY_CB; /* this is only for http requests */
			memcpy(&pass->api_io, &i, sizeof(i));
			pass->api_io.pass = pass;
			info.userdata = pass;
			if (i.client->authorization) /* attempt cookie login without user/pass */
				strcpy(pass->headers[DC_LWS_AUTHORIZATION], i.client->authorization);
			fprintf(stderr, "starting websocket session\n");
			i.status = DC_UNSET; /* we clear the status */
			if (!lws_client_connect_via_info(&info)) {
				i.client->status = DC_NET_ERROR;
				dc_api_stack(i);
			}
			break;
		case DC_API_WS_CB:
			i.client->status &= ~(DC_NET_ERROR | DC_OK);
			i.client->status |= i.status;
			if (i.status & DC_NET_ERROR) { /* pass and pass->body were freed on _DESTROY */
				fprintf(stderr, "websocket connection was closed by the remote host\n");
				i.pass = NULL; /* pass was/will be freed on _DESTROY, discard it! */
			} else if (!i.client->authorization) {
				fprintf(stderr, "what the fuck?! DC_API_WS_CB called without token!\n");
			} else { /* commerce identify */
				struct dc_payload * p = calloc(1, sizeof(struct dc_payload));
				p->length = asprintf(&p->body, dc_api_identify, i.client->authorization); /* body buffer to identify packet */
				dc_ws_stack(i.client, p, DC_NO_WRITE);
				p = calloc(1, sizeof(struct dc_payload)); /* official client sends a */
				p->length = asprintf(&p->body, DC_WS_PING_FORMAT, (unsigned long long int) 0);
				dc_ws_stack(i.client, p, DC_UNSET); /* right after identify. */
			}	
			dc_api_stack(i); /* cl.stat is either NET_ERROR 4 closed or error or OK 4 esta */
			break;
		case DC_API_REGISTER:
			break;
		case DC_API_STATUS:
			break;
		case DC_API_USER:
			break;
		case DC_API_ROLE:
			break;
		case DC_API_NONE:
			break;
		case DC_API_ATTACH:
			DC_MR(i.program->attached_functions); /* makes room for at least one */
			i.program->attached_functions[i.program->attached_functions_length++] = i.attached_function; /* is on heap */
			break;
	}
}
struct dc_api_io dc_api_o (struct dc_api_io i /* for ->program */) {
	if (i.program->lws_context)
		lws_service(i.program->lws_context, 0);
	for (size_t x = 0; x < i.program->clients_length; x++) {
		if (i.program->clients[x]->status & DC_WS_ACTIVE && !i.program->clients[x]->pass
				&& i.program->clients[x]->disconnect_time+DC_RECONNECT_DELAY<time(NULL)) {
			fprintf(stderr, "reconnecting client %u\n", x);
			i.client = i.program->clients[x];
			i.client->status &= ~DC_WS_ACTIVE; /* because we create a new WSI */
			i.type = DC_API_WS;
			dc_api_i(i);
		}
	}
	struct dc_api_io o = {
		.type = DC_API_NONE,
		.program = i.program
	};
	/* dc_api_stack pop: */
	if (i.program->api_ios_length) {
		memcpy(&o, (i.program->api_ios[--i.program->api_ios_length]), sizeof(o));
		dc_api_io_free(i.program->api_ios[i.program->api_ios_length], DC_UNSET);
		i.program->api_ios[i.program->api_ios_length] = NULL;

	}
	int is_broken = 0;
	for (size_t j = 0; j < i.program->attached_functions_length; j++) { /* call attached functions */
		if (i.program->attached_functions[j]->type != DC_API_TIMEOUT) {
			if (i.program->attached_functions[j]->type == o.type && !is_broken)
				if (i.program->attached_functions[j]->function(o, i.program->attached_functions[j]->user_data) & DC_BREAK)
					is_broken++;
		} else
			if (i.program->attached_functions[j]->last + i.program->attached_functions[j]->every < time(NULL))
				if (!(i.program->attached_functions[j]->function(o, i.program->attached_functions[j]->user_data) & DC_RETRY))
					i.program->attached_functions[j]->last = time(NULL);
	}
	return o;
}