Bot for Tox messenger
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tox-bot/src/misc.c

129 lines
2.6 KiB

3 years ago
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <time.h>
#include <tox/tox.h>
#include "misc.h"
char *hex_string_to_bin(const char *hex_string)
{
size_t len = strlen(hex_string);
char *val = malloc(len);
if (val == NULL) {
exit(EXIT_FAILURE);
}
size_t i;
for (i = 0; i < len; ++i, hex_string += 2) {
sscanf(hex_string, "%2hhx", &val[i]);
}
return val;
}
uint16_t copy_tox_str(char *msg, size_t size, const char *data, uint16_t length)
{
int len = MIN(length, size - 1);
memcpy(msg, data, len);
msg[len] = '\0';
return len;
}
int char_find(int idx, const char *s, char ch)
{
int i = idx;
for (i = idx; s[i]; ++i) {
if (s[i] == ch) {
break;
}
}
return i;
}
void log_msg(Tox *tox, const uint8_t *inmsg, uint32_t friend_number, bool user)
{
char name[TOX_MAX_NAME_LENGTH];
if (user == true) {
tox_friend_get_name(tox, friend_number, (uint8_t *) name, NULL);
size_t len = tox_friend_get_name_size(tox, friend_number, NULL);
name[len] = '\0';
} else {
tox_self_get_name(tox, (uint8_t *) name);
size_t len = tox_self_get_name_size(tox);
name[len] = '\0';
}
char cur_time[128];
time_t t;
struct tm* ptm;
t = time(NULL);
ptm = localtime(&t);
strftime(cur_time, 128, "%d-%b-%Y %H:%M:%S", ptm);
printf("%s (%s): %s\n", cur_time, name, inmsg);
}
int file_contains_key(const char *public_key, const char *path)
{
FILE *fp = NULL;
struct stat s;
if (stat(path, &s) != 0) {
FILE *fp = fopen(path, "w");
if (fp == NULL) {
fprintf(stderr, "Warning: failed to create '%s' file\n", path);
return -1;
}
fprintf(stderr, "Warning: creating new '%s' file. Did you lose the old one?\n", path);
fclose(fp);
return 0;
}
fp = fopen(path, "r");
if (fp == NULL) {
fprintf(stderr, "Warning: failed to read '%s' file\n", path);
return -1;
}
char id[256];
while (fgets(id, sizeof(id), fp)) {
int len = strlen(id);
if (--len < TOX_PUBLIC_KEY_SIZE) {
continue;
}
char *key_bin = hex_string_to_bin(id);
if (memcmp(key_bin, public_key, TOX_PUBLIC_KEY_SIZE) == 0) {
free(key_bin);
fclose(fp);
return 1;
}
free(key_bin);
}
fclose(fp);
return 0;
}