summary refs log tree commit diff
path: root/rvnitctl.c
blob: 7cc8bde7afd895016fda9b3e86e5f36c613821cf (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
#include <sys/socket.h>
#include <sys/un.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
	if (argc < 2) {
		dprintf(2, "usage: rvnitctl COMMAND [SERVICE]\n");
		exit(2);
	}

	static const char default_sock[] = "/run/rvnit/rvnit.sock";
	const char *path = getenv("RVNIT_SOCK");
	if (!path || !*path)
		path = default_sock;

	struct sockaddr_un addr = { 0 };
	addr.sun_family = AF_UNIX;
	strncpy(addr.sun_path, path, sizeof addr.sun_path - 1);
	int connfd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (connfd < 0) {
		perror("socket");
		exit(111);
	}

	if (connect(connfd, (struct sockaddr *)&addr, sizeof addr) < 0) {
		perror("connect");
		exit(111);
	}

	dprintf(connfd, "%c%s", *argv[1], argv[2] ? argv[2] : "");

	int status = 1;

	ssize_t rd;
	do {
		char buf[4096];
		rd = read(connfd, buf, sizeof buf);
		if (rd < 0) {
			perror("read");
			exit(111);
		}
		if (rd > 0)
			status = 0;
		write(1, buf, rd);
	} while (rd > 0);

	return status;
}