aboutsummaryrefslogtreecommitdiffstats
path: root/v3/libglouglou/utils.c
blob: 42b278951491ee84b9a8c6f594fd5eaf704f2d6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <sys/types.h>

#if !defined(__OpenBSD__)
#define __USE_GNU
#define _GNU_SOURCE
#endif

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <err.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>

#include "libglouglou.h"

/*
 * Various utils
 */

void *
xmalloc(size_t size)
{
	void *data;

	data = malloc(size);
	if (!data)
		err(1, "could not malloc %d", (int)size);
	return data;
}

void *
xcalloc(size_t nmemb, size_t size)
{
	void *data;

	data = calloc(nmemb, size);
	if (!data)
		err(1, "could not calloc %d", (int)size);
	return data;
}

void
fd_nonblock(int fd)
{
	int flags = fcntl(fd, F_GETFL, 0);
	int rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
	if (rc == -1)
		err(1, "failed to set fd %i non-blocking", fd);
}

void
addrcpy(struct sockaddr_in *dst, struct sockaddr_in *src)
{
	dst->sin_addr.s_addr = src->sin_addr.s_addr;
	dst->sin_port = src->sin_port;
	dst->sin_family = src->sin_family;
}

int
addrcmp(struct sockaddr_in *a, struct sockaddr_in *b)
{
	if (a->sin_addr.s_addr != b->sin_addr.s_addr)
		return -1;
	if (a->sin_port != b->sin_port)
		return -2;
	if (a->sin_family != b->sin_family)
		return -3;
	return 0;
}

void
droppriv(char *user, int do_chroot, char *chroot_path)
{
	struct passwd	*pw;

	pw = getpwnam(user);
	if (!pw)
		err(1, "unknown user %s", user);
	if (do_chroot) {
		if (!chroot_path)
			chroot_path = pw->pw_dir;
		if (chroot(chroot_path) != 0)
			err(1, "unable to chroot");
	}
	if (chdir("/") != 0)
		err(1, "unable to chdir");
	if (setgroups(1, &pw->pw_gid) == -1)
		err(1, "setgroups() failed");
	if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1)
		err(1, "setresgid failed");
	if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
		err(1, "setresuid() failed");
	endpwent();
}