summary refs log tree commit diff
path: root/rvnitctl.c
blob: 9920f3007d3537128ce76880faa723810c362f27 (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
#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 || (
	    strcmp(argv[1], "l") != 0 && strcmp(argv[1], "level") != 0 &&
	    strcmp(argv[1], "s") != 0 && strcmp(argv[1], "status") != 0 &&
	    strcmp(argv[1], "d") != 0 && strcmp(argv[1], "down") != 0 &&
	    strcmp(argv[1], "u") != 0 && strcmp(argv[1], "up") != 0 &&
	    strcmp(argv[1], "p") != 0 && strcmp(argv[1], "pause") != 0 &&
	    strcmp(argv[1], "c") != 0 && strcmp(argv[1], "cont") != 0 &&
	    strcmp(argv[1], "h") != 0 && strcmp(argv[1], "hup") != 0 &&
	    strcmp(argv[1], "a") != 0 && strcmp(argv[1], "alarm") != 0 &&
	    strcmp(argv[1], "i") != 0 && strcmp(argv[1], "interrupt") != 0 &&
	    strcmp(argv[1], "q") != 0 && strcmp(argv[1], "quit") != 0 &&
	    strcmp(argv[1], "t") != 0 && strcmp(argv[1], "term") != 0 &&
	    strcmp(argv[1], "k") != 0 && strcmp(argv[1], "kill") != 0 &&
	    strcmp(argv[1], "1") != 0 &&
	    strcmp(argv[1], "2") != 0 &&
	    strcmp(argv[1], "Restart") != 0 &&
	    strcmp(argv[1], "Shutdown") != 0)) {
		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;
}