permanent-satori-hole/src/futami.c
2023-12-27 01:35:22 +01:00

125 lines
3.2 KiB
C

#include "futami.h"
sat_futami_ptr sat_futami_alloc(void) {
return malloc(sizeof(sat_futami));
}
void sat_futami_free(sat_futami_ptr ctx) {
if(ctx == NULL) return;
if(ctx->servers != NULL) {
while(ctx->serversCount > 0) {
--ctx->serversCount;
if(ctx->servers[ctx->serversCount] != NULL)
free(ctx->servers[ctx->serversCount]);
}
free(ctx->servers);
}
free(ctx);
}
int sat_futami_load_json(sat_futami_ptr ctx, json_object *obj) {
if(!obj) return -1;
json_object *value;
ctx->ping = json_object_object_get_ex(obj, "ping", &value)
? json_object_get_int(value)
: 69; // change default to 30, testing parsage
if(json_object_object_get_ex(obj, "servers", &value)) {
int serversCount = json_object_array_length(value);
ctx->serversCount = serversCount;
char **servers = calloc(serversCount, sizeof(char*));
ctx->servers = servers;
json_object *arrValue;
int arrStrLen;
const char* arrStr;
for(int i = 0; i < serversCount; ++i) {
arrValue = json_object_array_get_idx(value, i);
if(arrValue == NULL)
continue; // ???
arrStrLen = json_object_get_string_len(arrValue);
servers[i] = malloc(arrStrLen + 1);
servers[i][arrStrLen] = '\0';
if(arrStrLen > 0) {
arrStr = json_object_get_string(arrValue);
memcpy(servers[i], arrStr, arrStrLen);
}
}
} else {
ctx->serversCount = 0;
ctx->servers = NULL;
}
return 0;
}
int sat_futami_load_json_file(sat_futami_ptr ctx, char *path) {
json_object *obj = json_object_from_file(path);
if(!obj) return -11;
int err = sat_futami_load_json(ctx, obj);
json_object_put(obj);
return err;
}
int sat_futami_load_json_string(sat_futami_ptr ctx, char *str) {
if(!str) return -21;
json_object *obj = json_tokener_parse(str);
int err = sat_futami_load_json(ctx, obj);
json_object_put(obj);
return err;
}
// this only runs once during startup and is required to be completed before
// any connection is set up or module is loaded, but this should really be
// redone to be threaded or some shit rather than just block until done lol
int sat_futami_load_json_url(sat_futami_ptr ctx, char *url) {
if(!url) return -31;
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(!curl)
return -32;
sat_curl_string str;
sat_curl_string_init(&str);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 2L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, sat_curl_string_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str);
curl_easy_setopt(curl, CURLOPT_USERAGENT, SATORI_USERAGENT);
res = curl_easy_perform(curl);
if(res != CURLE_OK) // obv this random print shouldn't remain here
fprintf(stderr, "curl_easy_failed(): %s\r\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
if(res != CURLE_OK)
return res;
int err = sat_futami_load_json_string(ctx, str.str);
sat_curl_string_free(&str, false);
return err;
}