vger/utils.c

117 lines
2.3 KiB
C

#include <err.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>
#include "utils.h"
#include "vger.h"
#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined( __NetBSD__) || defined(__DragonFly__)
#include <string.h>
#else
#include <bsd/string.h>
#endif
/* e*foo() functions are the equivalent of foo() but handle errors.
* In case an error happens:
* The error is printed to stdout
* return 1
*/
#ifdef __OpenBSD__
void
eunveil(const char *path, const char *permissions)
{
if (unveil(path, permissions) == -1) {
status(41, "Error when unveil(), see logs");
stop(EXIT_FAILURE, "unveil on %s failed", path);
}
}
void
epledge(const char *promises, const char *execpromises)
{
if (pledge(promises, execpromises) == -1) {
status(41, "Error when pledge(), see logs");
stop(EXIT_FAILURE, "pledge failed for: %s", promises);
}
}
#endif
size_t
estrlcpy(char *dst, const char *src, size_t dstsize)
{
size_t n = 0;
n = strlcpy(dst, src, dstsize);
if (n >= dstsize) {
status(41, "strlcpy failed, see logs");
stop(EXIT_FAILURE, "strlcpy() failed for %s = %s", dst, src);
}
return n;
}
size_t
estrlcat(char *dst, const char *src, size_t dstsize)
{
size_t size;
if ((size = strlcat(dst, src, dstsize)) >= dstsize) {
status(41, "strlcat() failed, see logs");
stop(EXIT_FAILURE, "strlcat on %s + %s", dst, src);
}
return size;
}
int
esetenv(const char *name, const char *value, int overwrite)
{
int ret = 0;
ret = setenv(name, value, overwrite);
if (ret != 0) {
status(41, "setenv() failed, see logs");
stop(EXIT_FAILURE, "setenv() %s:%s", name, value);
}
return ret;
}
void
echdir(const char *path)
{
if (chdir(path) == -1) {
switch (errno) {
case ENOTDIR: /* FALLTHROUGH */
case ENOENT:
status(51, "file not found");
break;
case EACCES:
status(50, "Forbidden path");
break;
default:
status(50, "Internal server error");
break;
}
stop(EXIT_FAILURE, "chdir(%s) failed", path);
}
}
/* read the file fd byte after byte in buffer and write it to stdout
* return number of bytes read
*/
size_t
print_file(FILE *fd)
{
ssize_t nread = 0;
char *buffer[BUFSIZ];
while ((nread = fread(buffer, 1, sizeof(buffer), fd)) != 0)
fwrite(buffer, 1, nread, stdout);
return nread;
}