diff options
author | sijanec <anton@sijanec.eu> | 2021-03-15 23:22:14 +0100 |
---|---|---|
committer | sijanec <anton@sijanec.eu> | 2021-03-15 23:22:14 +0100 |
commit | 7737e334db8259870d64d8c5f18745f285203ea1 (patch) | |
tree | 10178f68b2761930b554f2e165a7c888d874bfd2 /src | |
parent | neki delu na novem api.c (diff) | |
download | discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar.gz discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar.bz2 discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar.lz discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar.xz discord.c-7737e334db8259870d64d8c5f18745f285203ea1.tar.zst discord.c-7737e334db8259870d64d8c5f18745f285203ea1.zip |
Diffstat (limited to 'src')
-rw-r--r-- | src/api.c | 108 | ||||
-rw-r--r-- | src/main.c | 300 |
2 files changed, 68 insertions, 340 deletions
@@ -12,6 +12,8 @@ #include <time.h> #include <stdarg.h> #include <printf.h> +#include <pthread.h> +#include <stdatomic.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" @@ -20,11 +22,37 @@ #define DC_API(curl, body, endpoint, ...) dc_api(curl, 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" +/* + 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 + 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 and when appending to the array shall be incremented **after** the element is appended, so reading threads may function normally + - keep arrays as arrays of pointers, not direct structs, as that allows reading an array when appending is in progress by another thread + - threading and races 101: when popping arrays, always lock in a non-shared way, same obviously applies for sorting, but not necessarily for appending (when only a shared lock is needed) + 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, you also shared lock it when appending + - 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 and appending to arrays and other types + TODO: make it work. + - 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 + - make mutex locks in api (and ui thread) + - make the ui thread +*/ struct dc_error { size_t line; - const char * function /* this is a static string, so it is not copied, do not free it */; - char * file /* this is a static string, so it is not copied, do not free it */; - char * message /* this is copied, caller can free it if it was dynamically created by it, it must be freed before destroying struct */; + 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 */; }; @@ -37,13 +65,14 @@ int dc_error_free(struct dc_error * e) { free(e); }; struct dc_message { - char * username; + char * username; /* yesfree */ int discriminator; - char * content; + char * content; /* yesfree */ time_t time; - struct dc_channel * channel; + struct dc_channel * channel; /* nofree */ unsigned short int tts; - unsigned long long int id; + 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 */ }; int dc_message_free (struct dc_message * m) { free(m->username); m->username = NULL; @@ -62,13 +91,12 @@ int dc_message_compare (const void * a, const void * b) { return c->time > d->time ? -1 : c->time < d->time ? 1 : 0; } struct dc_channel { - char * name; - char * topic; - unsigned long long int id; - struct dc_guild * guild; - struct dc_message * messages; - size_t messages_sizeof; - unsigned short int sent /* describes status, was message already sent (1) or is it to-be sent (0)? */; + char * name; /* yesfree, nouiw */ + char * topic; /* yesfree, nouiw */ + unsigned long long int id; /* nouiw */ + struct dc_guild * guild; /* nofree, nouiw */ + struct dc_message ** messages; /* yesfree, nouiw */ + _Atomic(size_t) messages_sizeof; /* nouiw */ }; int dc_channel_free (struct dc_channel * ch) { free(ch->name); ch->name = NULL; @@ -76,39 +104,39 @@ int dc_channel_free (struct dc_channel * ch) { ch->guild = NULL; ch->id = 0; for (int i = 0; i < ch->messages_sizeof; i++) - dc_message_free(&ch->messages[i]); + dc_message_free(ch->messages[i]); ch->messages_sizeof = 0; free(ch); } struct dc_guild { - char * name; - unsigned long long id; - size_t channels_sizeof; - struct dc_channel * channels; + char * name; /* nouiw, yesfree */ + unsigned long long id; /* nouiw */ + _Atomic(size_t) channels_sizeof; /* nouiw */ + struct dc_channel ** channels; /* yesfree, nouiw */ }; int dc_guild_free (struct dc_guild * g) { free(g->name); g->name = NULL; g->id = 0; for (int i = 0; i < g->channels_sizeof; i++) - dc_channel_free(&g->channels[i]); + dc_channel_free(g->channels[i]); g->channels_sizeof = 0; free(g); } struct dc_client { - CURL * curl; - struct curl_slist * curl_headers; - char * authorization; - char * email; /* email and password are copied, even though they are sometimes static ENV vars - they are not always! */ - char * password; - char * username; - int discriminator; - struct dc_guild * guilds; - size_t guilds_sizeof; - struct dc_channel * joinedchannel; - struct dc_error * errors; - size_t errors_sizeof; - struct dc_message * sent_messages; - size_t sent_messages_sizeof; + CURL * curl; /* noui */ + struct curl_slist * curl_headers; /* noui */ + char * authorization; /* noui */ + char * email; /* yesfree, noapiw */ + char * password; /* yesfree, noapiw */ + char * username; /* yesfree, nouiw */ + int discriminator; /* nouiw */ + struct dc_guild ** guilds; /* yesfree, nouiw */ + _Atomic(size_t) guilds_sizeof; /* nouiw */ + struct dc_channel * joinedchannel; /* nofree, nouiw */ + struct dc_error ** errors; /* yesfree */ + _Atomic(size_t) errors_sizeof; + struct dc_message ** sent_messages; /* yesfree - ui appends, api pops and moves to messages */ + _Atomic(size_t) sent_messages_sizeof; }; int dc_client_free (struct dc_client * c) { curl_easy_cleanup(c->curl); @@ -120,13 +148,13 @@ int dc_client_free (struct dc_client * c) { c->discriminator = -1; c->joinedchannel = NULL; for (int i = 0; i < c->guilds_sizeof; i++) - dc_guild_free(&c->guilds[i]); + dc_guild_free(c->guilds[i]); c->guilds_sizeof = 0; for (int i = 0; i < c->errors_sizeof; i++) - dc_error_free(&c->errors[i]); + dc_error_free(c->errors[i]); c->errors_sizeof = 0; for (int i = 0; i < c->sent_messages_sizeof; c++) - dc_message_free(&c->sent_messages[i]); + dc_message_free(c->sent_messages[i]); c->sent_messages_sizeof = 0; free(c); } @@ -502,7 +530,7 @@ int dc_fetch_messages (struct dc_client * c, struct dc_channel * ch) { DC_CLIENT_ERROR(c, "!ch || !ch->id"); return -3; } - cJSON * json = DC_API(c->curl, NULL, DC_API_PREFIX "channels/%llu/messages?limit=100", ch->id); + cJSON * json = DC_API(c->curl, NULL, DC_API_PREFIX "channels/%llu/messages?limit=100&_=", ch->id, rand()); if (!json) { const char *error_ptr = cJSON_GetErrorPtr(); if (!error_ptr) { @@ -566,9 +594,9 @@ int dc_fetch_messages (struct dc_client * c, struct dc_channel * ch) { } struct dc_api_thread_control { unsigned short int power; /* 1 if the thread should run, set it to 0 for the thread to return at the end of the loop */ - struct dc_client * clients; /* "array" of clients the thread should manage, ONLY ONE dc_api_thread PER PROCESS! */ + struct dc_client ** clients; /* "array" of pointers to clients the thread should manage, ONLY ONE dc_api_thread PER PROCESS! */ size_t dc_clients_sizeof; }; int dc_api_thread (struct dc_api_thread_control * t) { /* updates messages and sends messages when they are in the outbox */ - return -1; + return 1; } /* the thread shall use mutexes when doing things with shared memory - client structs */ diff --git a/src/main.c b/src/main.c deleted file mode 100644 index ad7c174..0000000 --- a/src/main.c +++ /dev/null @@ -1,300 +0,0 @@ -#include <stdlib.h> -#include <stdio.h> -#include <curl/curl.h> -#include <unistd.h> -#include <i18n.h> -#include <string.h> -#include <lib.c> -#include <cJSON.h> -#include <cJSON.c> -#define DC_API_PREFIX "https://discord.com/api/v8/" -#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_DEBUG 0 -#define DC_COMMAND_LINE_LENGTH 2000 -#define cJSON_Izbrisi(item) do { item != NULL ? cJSON_Delete(item) : 0; } while (0) -#define DC_COMMAND_CHAR '/' -int main(int argc, char ** argv) { - srand(time(NULL)); - int returnstatus = 0; - int opt; - cJSON * guilds = 0; - char * email = getenv("DC_E"); - char * password = getenv("DC_P"); - while ((opt = getopt(argc, argv, "e:p:h")) != -1) { - switch (opt) { - case 'h': - fprintf(stdout, DC_I18N_USAGE); - break; - case 'e': - if (!email) { - email = malloc(strlen(optarg)+1); - strcpy(email, optarg); - } else - fprintf(stderr, DC_I18N_ARG_ALREADY_SET "\n", opt); - break; - case 'p': - if (!password) { - password = malloc(strlen(optarg)+1); - strcpy(password, optarg); - } else - fprintf(stderr, DC_I18N_ARG_ALREADY_SET "\n", opt); - break; - default: - fprintf(stderr, DC_I18N_UNREC_ARG "\n", opt); - } - } - if (!email || !password) { - fprintf(stderr, DC_I18N_MISSING_EP "\n"); - free(email); email = NULL; - free(password); password = NULL; - return 1; - } - CURL *curl; - CURLcode res; - curl = curl_easy_init(); - if (!curl) { - fprintf(stderr, "curl_easy_init() " DC_I18N_FAILED ".\n"); - return 1; - } - struct writefunc_string s; - init_writefunc_string(&s); - - char * data = malloc(strlen(DC_LOGIN_FORMAT)+strlen(email)+strlen(password)); - sprintf(data, DC_LOGIN_FORMAT, email, password); - struct curl_slist *headers = NULL; - headers = curl_slist_append(headers, "Content-Type: application/json"); - headers = curl_slist_append(headers, "User-Agent: " DC_USER_AGENT); - curl_easy_setopt(curl, CURLOPT_URL, DC_API_PREFIX "auth/login"); - curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); - res = curl_easy_perform(curl); - if (res != CURLE_OK) - fprintf(stderr, "curl_easy_perform() " DC_I18N_FAILED ": %s\n", curl_easy_strerror(res)); - cJSON * json = cJSON_Parse(s.ptr); - cJSON * token = cJSON_GetObjectItemCaseSensitive(json, "token"); - char * authorization = NULL; - if (cJSON_IsString(token) && (token->valuestring != NULL)) { - authorization = malloc(strlen(token->valuestring)+strlen("authorization: ")+1); - strcpy(authorization, "Authorization: "); - strcat(authorization, token->valuestring); - if(DC_DEBUG) fprintf(stderr, "d: %s\n", s.ptr); - cJSON_Izbrisi(json); - } else { - fprintf(stderr, DC_I18N_LOGIN_FAILED "\n", s.ptr); - cJSON_Izbrisi(json); - returnstatus = 3; - free(s.ptr); s.ptr = NULL; - goto returncleanly; - } - free(s.ptr); s.ptr = NULL; - init_writefunc_string(&s); - curl_easy_setopt(curl, CURLOPT_URL, DC_API_PREFIX "users/@me"); - curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); - headers = curl_slist_append(headers, authorization); - res = curl_easy_perform(curl); - if (res != CURLE_OK) - fprintf(stderr, "curl_easy_perform() " DC_I18N_FAILED ": %s\n", curl_easy_strerror(res)); - json = cJSON_Parse(s.ptr); - token = cJSON_GetObjectItemCaseSensitive(json, "username"); - cJSON * token2 = cJSON_GetObjectItemCaseSensitive(json, "discriminator"); - char * handle = NULL; - if (cJSON_IsString(token) && (token->valuestring != NULL) - && cJSON_IsString(token2) && (token2->valuestring != NULL)) { - handle = malloc(strlen(token->valuestring)+1+strlen(token2->valuestring)+1); - strcpy(handle, token->valuestring); - strcat(handle, "#"); - strcat(handle, token2->valuestring); - fprintf(stdout, DC_I18N_LOGGED_IN "\n", handle); - } else { - fprintf(stderr, DC_I18N_LOGIN_FAILED "\n", s.ptr); - cJSON_Izbrisi(json); - returnstatus = 4; - free(s.ptr); s.ptr = NULL; - goto returncleanly; - } - free(s.ptr); s.ptr = NULL; - /* start command listener */ - char * fgetsret = NULL; - char cmd[DC_COMMAND_LINE_LENGTH+1]; - long long int setguild = 0; - long long int setchannel = 0; - char * joinedchannelname = NULL; - char * joinedchannelid = NULL; - char * tempstring = NULL; - while (1) { - fprintf(stderr, "%s%s> ", joinedchannelname ? "#" : "", joinedchannelname ? joinedchannelname : ""); - fflush(stderr); - fgetsret = fgets(cmd, DC_COMMAND_LINE_LENGTH, stdin); - if (fgetsret == NULL) { - fprintf(stderr, "fgets() " DC_I18N_FAILED "\n"); - returnstatus = 5; - goto returncleanly; - break; - } - if (cmd[0] == DC_COMMAND_CHAR) { - switch (cmd[1]) { - case 'g': - case 'G': - case 's': /* /guilds */ - case 'S': /* /guilds force-update */ - if (!guilds || (strchr(cmd, ' ') ? (strchr(cmd, ' ')+1)[0] == 'f' : 0)) { -#define DC_API_METHOD_GET(body) curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L) -#define DC_API_METHOD_POST(body) curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body) -#define DC_API(endpoint, method, body, output) do {\ - curl_easy_setopt(curl, CURLOPT_URL, endpoint); \ - DC_API_METHOD_##method(body); \ - free(s.ptr); s.ptr = NULL; \ - init_writefunc_string(&s); \ - res = curl_easy_perform(curl); \ - if (res != CURLE_OK) \ - fprintf(stderr, "curl_easy_perform() " DC_I18N_FAILED ": %s\n", curl_easy_strerror(res)); \ - cJSON_Izbrisi(output); \ - output = cJSON_Parse(s.ptr); } while (0) - DC_API(DC_API_PREFIX "users/@me/guilds", GET, "", guilds); - } - int i = 0; - cJSON * guild = NULL; - cJSON_ArrayForEach(guild, guilds) { - token = cJSON_GetObjectItem(guild, "name"); - fprintf(stdout, " %d. %s\n", i++, token->valuestring); - } - break; - case 'c': - case 'C': - case 'k': /* /channels <guild number> [force-update] */ - case 'K': - if (strchr(cmd, ' ') == NULL) { - fprintf(stderr, DC_I18N_GUILD_NOT_SET "\n"); - break; - } - setguild = strtoll(strchr(cmd, ' ')+1, NULL, 10); - if (!guilds || !cJSON_IsObject(guilds)) - DC_API(DC_API_PREFIX "users/@me/guilds", GET, "", guilds); - cJSON_ArrayForEach(guild, guilds) { - if (setguild-- == 0) { - cJSON * guildchannels = cJSON_GetObjectItem(guild, "channels"); - if (!cJSON_IsArray(guildchannels) || strchr(strchr(cmd,' ')+1,' ') ? 1 : 0) { -#define DC_UPDATE_CHANNELS(guild) do {\ - token = cJSON_GetObjectItem(guild, "id"); \ - tempstring = realloc(tempstring, strlen(token->valuestring)+strlen("guilds//channels")+1+ strlen(DC_API_PREFIX)); \ - sprintf(tempstring, DC_API_PREFIX "guilds/%s/channels", token->valuestring); \ - guildchannels = cJSON_CreateObject(); \ - DC_API(tempstring, GET, "", guildchannels); \ - cJSON_AddItemToObject(guild, "channels", guildchannels); \ - free(tempstring); tempstring = NULL; } while (0) - DC_UPDATE_CHANNELS(guild); - } - setguild = 0; - cJSON * guildchannel = NULL; - cJSON_ArrayForEach(guildchannel, guildchannels) { - token = cJSON_GetObjectItem(guildchannel, "name"); - token2 = cJSON_GetObjectItem(guildchannel, "topic"); - cJSON * type = cJSON_GetObjectItem(guildchannel, "type"); - if (type->valuedouble == 0) /* samo za besedilne kanale */ - fprintf(stdout, " %lld. #%s%s%s\n", setguild++, token->valuestring, token2->valuestring ? " - " : "", token2->valuestring ? token2->valuestring : ""); - } - break; - } - } - break; - case 'j': - case 'J': - case 'p': - case 'P': - if (strchr(cmd, ' ') == NULL) { - fprintf(stderr, DC_I18N_GUILD_NOT_SET "\n"); - break; - } - if (strchr(strchr(cmd, ' ')+1, ' ') == NULL) { - fprintf(stderr, DC_I18N_CHANNEL_NOT_SET "\n"); - break; - } - setguild = strtoll(strchr(cmd, ' ')+1, NULL, 10); - setchannel = strtoll(strchr(strchr(cmd, ' ')+1, ' ')+1, NULL, 10); - if (!guilds) - DC_API(DC_API_PREFIX "users/@me/guilds", GET, "", guilds); - cJSON_ArrayForEach(guild, guilds) { - if (setguild-- == 0) { - cJSON * guildchannels = cJSON_GetObjectItem(guild, "channels"); - if (!cJSON_IsArray(guildchannels)) - DC_UPDATE_CHANNELS(guild); - cJSON * guildchannel = NULL; - cJSON_ArrayForEach(guildchannel, guildchannels) { - cJSON * type = cJSON_GetObjectItem(guildchannel, "type"); - if (type->valueint != 0) setchannel++; - if (setchannel-- == 0) { - char * joinedchannel_pointer = (cJSON_GetObjectItem(guildchannel, "id")->valuestring); - joinedchannelid = realloc(joinedchannelid, strlen(joinedchannel_pointer)+1); - strcpy(joinedchannelid, joinedchannel_pointer); - joinedchannel_pointer = cJSON_GetObjectItem(guildchannel, "name")->valuestring; - joinedchannelname = realloc(joinedchannelname, strlen(joinedchannel_pointer)+1); - strcpy(joinedchannelname, joinedchannel_pointer); - } - } - } - } - char * queryparam = malloc(strlen(DC_API_PREFIX "channels//messages?limit=100")+strlen(joinedchannelid)+1); - sprintf(queryparam, DC_API_PREFIX "channels/%s/messages?limit=100", joinedchannelid); - DC_API(queryparam, GET, "", token); - if (!cJSON_IsArray(token)) { - fprintf(stderr, DC_I18N_MESSAGES_GET_FAIL "\n"); - free(queryparam); queryparam = NULL; - joinedchannelid = NULL; - joinedchannelname = NULL; - break; - } - cJSON * sporocilo = cJSON_GetArrayItem(token, cJSON_GetArraySize(token)-1); /* last item in array is the first chat */ - do { -#define cJSON_GetObjectItem2(root, name1, name2) (cJSON_GetObjectItem(root, name1) ? cJSON_GetObjectItem(cJSON_GetObjectItem(root, name1), name2) : NULL) - fprintf(stdout, "%.19s %s#%s: %s\n", - cJSON_GetObjectItem(sporocilo, "timestamp")->valuestring, - cJSON_GetObjectItem2(sporocilo, "author", "username")->valuestring, - cJSON_GetObjectItem2(sporocilo, "author", "discriminator")->valuestring, - cJSON_GetObjectItem(sporocilo, "content")->valuestring - ); - sporocilo = sporocilo->prev; - } while (sporocilo->prev->next != NULL); - free(queryparam); queryparam = NULL; - break; - case 'q': - case 'Q': - case 'i': - case 'I': - goto returncleanly; - default: - goto to_je_sporocilo; - } - } else { - to_je_sporocilo: - if (joinedchannelid == NULL) { - fprintf(stderr, DC_I18N_NOT_JOINED "\n"); - continue; - } - cJSON * message = cJSON_CreateObject(); - cJSON * nons = cJSON_CreateNumber(rand()); - cJSON_AddItemToObject(message, "nonce", nons); - cJSON * content = cJSON_CreateString(cmd); - cJSON_AddItemToObject(message, "content", content); - cJSON * tts = cJSON_CreateFalse(); - cJSON_AddItemToObject(message, "tts", tts); - char * jsonmessage = cJSON_Print(message); - char * target = malloc(strlen(joinedchannelid)+strlen("channels//messages")+strlen(DC_API_PREFIX)+1); - sprintf(target, DC_API_PREFIX "channels/%s/messages", joinedchannelid); - cJSON * jsonresponse = NULL; - DC_API(target, POST, jsonmessage, jsonresponse); - free(jsonmessage); jsonmessage = NULL; - free(target); target = NULL; - cJSON_Izbrisi(message); - cJSON_Izbrisi(jsonresponse); /* jsonresponse izgleda sploh nismo uporabili */ - } - } - returncleanly: - cJSON_Izbrisi(guilds); - curl_easy_cleanup(curl); - curl_slist_free_all(headers); - return 0; -} |