Files
fastfetch/src/modules/publicip.c
T

75 lines
2.2 KiB
C
Raw Normal View History

2022-01-10 20:20:18 +01:00
#include "fastfetch.h"
#include "common/printing.h"
#include "common/networking.h"
2022-01-10 20:20:18 +01:00
#define FF_PUBLICIP_MODULE_NAME "Public IP"
#define FF_PUBLICIP_NUM_FORMAT_ARGS 1
static FFNetworkingState state;
static int status = -1;
2022-09-28 03:10:33 +08:00
void ffPreparePublicIp(FFinstance* instance)
{
if(instance->config.publicIpUrl.length == 0)
status = ffNetworkingSendHttpRequest(&state, "ipinfo.io", "/ip", NULL);
else
{
FFstrbuf host;
ffStrbufInitCopy(&host, &instance->config.publicIpUrl);
ffStrbufSubstrAfterFirstS(&host, "://");
uint32_t pathStartIndex = ffStrbufFirstIndexC(&host, '/');
FFstrbuf path;
ffStrbufInit(&path);
if(pathStartIndex != host.length)
{
ffStrbufAppendNS(&path, pathStartIndex, host.chars + (host.length - pathStartIndex));
host.length = pathStartIndex;
host.chars[pathStartIndex] = '\0';
}
status = ffNetworkingSendHttpRequest(&state, host.chars, path.length == 0 ? "/" : path.chars, NULL);
ffStrbufDestroy(&path);
ffStrbufDestroy(&host);
}
2022-09-28 03:10:33 +08:00
}
2022-01-10 20:20:18 +01:00
void ffPrintPublicIp(FFinstance* instance)
{
if(status == -1)
2022-09-28 03:10:33 +08:00
ffPreparePublicIp(instance);
if(status == 0)
2022-09-28 03:10:33 +08:00
{
ffPrintError(instance, FF_PUBLICIP_MODULE_NAME, 0, &instance->config.publicIP, "Failed to connect to an IP detection server");
return;
}
2022-01-10 20:20:18 +01:00
FFstrbuf result;
ffStrbufInitA(&result, 4096);
bool success = ffNetworkingRecvHttpResponse(&state, &result, instance->config.publicIpTimeout);
2022-09-30 17:43:23 +08:00
if(success) ffStrbufSubstrAfterFirstS(&result, "\r\n\r\n");
2022-01-10 20:20:18 +01:00
2022-09-30 17:43:23 +08:00
if(!success || result.length == 0)
2022-01-10 20:20:18 +01:00
{
2022-09-28 03:10:33 +08:00
ffPrintError(instance, FF_PUBLICIP_MODULE_NAME, 0, &instance->config.publicIP, "Failed to receive the server response");
2022-09-22 21:28:20 +08:00
ffStrbufDestroy(&result);
2022-01-10 20:20:18 +01:00
return;
}
2022-06-17 18:15:36 +02:00
if(instance->config.publicIP.outputFormat.length == 0)
2022-01-10 20:20:18 +01:00
{
2022-06-17 18:15:36 +02:00
ffPrintLogoAndKey(instance, FF_PUBLICIP_MODULE_NAME, 0, &instance->config.publicIP.key);
2022-01-10 20:20:18 +01:00
ffStrbufPutTo(&result, stdout);
}
else
{
2022-06-17 18:15:36 +02:00
ffPrintFormat(instance, FF_PUBLICIP_MODULE_NAME, 0, &instance->config.publicIP, FF_PUBLICIP_NUM_FORMAT_ARGS, (FFformatarg[]) {
2022-01-10 20:20:18 +01:00
{FF_FORMAT_ARG_TYPE_STRBUF, &result}
});
}
2022-09-22 21:28:20 +08:00
ffStrbufDestroy(&result);
2022-01-10 20:20:18 +01:00
}