minrss/util.c

104 lines
2.0 KiB
C
Raw Normal View History

/*
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.
© 2021 dogeystamp <dogeystamp@disroot.org>
*/
2021-08-02 11:41:15 -04:00
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "config.h"
void
logMsg(int lvl, char *msg, ...)
{
2021-08-06 14:32:04 -04:00
va_list args;
va_start(args, msg);
2021-08-02 11:41:15 -04:00
2022-05-23 12:27:00 -04:00
if (lvl <= logLevel) {
if (lvl == LOG_OUTPUT) {
2022-05-23 12:27:00 -04:00
vfprintf(stdout, msg, args);
} else {
fprintf(stderr, "minrss: ");
2022-06-12 14:24:05 -04:00
vfprintf(stderr, msg, args);
2022-05-23 12:27:00 -04:00
}
}
2021-08-02 11:41:15 -04:00
va_end(args);
2021-08-06 14:32:04 -04:00
if (!lvl)
exit(1);
2021-08-02 11:41:15 -04:00
}
void *
ecalloc(size_t nmemb, size_t size)
{
void *p = calloc(nmemb, size);
if (!p)
logMsg(LOG_FATAL, "Error allocating memory.\n");
2021-08-02 11:41:15 -04:00
return p;
}
void *
erealloc(void *p, size_t size)
{
p = realloc(p, size);
if (!p)
logMsg(LOG_FATAL, "Error reallocating memory.\n");
2021-08-02 11:41:15 -04:00
return p;
}
char *
san(char *str)
2021-08-02 11:41:15 -04:00
{
if (!str)
return "";
unsigned long long int len = strlen(str);
unsigned long long int offset = 0;
2021-08-04 16:46:48 -04:00
len = len > 255 ? 255 : len;
2021-08-02 11:41:15 -04:00
char *dup = ecalloc(len + 1, sizeof(char));
2022-05-23 11:13:13 -04:00
memcpy(dup, str, (len + 1) * sizeof(char));
2021-08-02 11:41:15 -04:00
for (unsigned long long int i = 0; i < len; i++) {
2021-08-04 16:46:48 -04:00
char c = dup[i];
if ((c >= 'a' && c <= 'z') ||
2021-08-06 14:32:04 -04:00
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '.' && i - offset != 0) ||
c == '-' || c == '_' ||
c == ' ')
2021-08-02 11:41:15 -04:00
dup[i - offset] = dup[i];
else
offset++;
}
dup[len-offset] = '\0';
return dup;
}
char fsep()
{
#ifdef _WIN32
2021-08-06 14:32:04 -04:00
return '\\';
2021-08-02 11:41:15 -04:00
#else
2021-08-06 14:32:04 -04:00
return '/';
2021-08-02 11:41:15 -04:00
#endif
}