aboutsummaryrefslogtreecommitdiffstats
path: root/servers-kernel.c
blob: a5e3871da4a5802c1cc17c81009a82788bcf30a5 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/* See LICENSE file for copyright and license details. */
#include "servers-kernel.h"
#include "state.h"
#include "util.h"

#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <libgamma.h>


/**
 * Get the pathname of the runtime file
 * 
 * @param   suffix  The suffix for the file
 * @return          The pathname of the file, `NULL` on error
 */
GCC_ONLY(__attribute__((__malloc__, __nonnull__)))
static char *
get_pathname(const char *restrict suffix)
{
	const char *restrict rundir = getenv("XDG_RUNTIME_DIR");
	const char *restrict username = "";
	const char *const_name;
	char *name = NULL;
	char *p;
	char *restrict rc;
	struct passwd *restrict pw;
	size_t n;

	if (sitename) {
		name = memdup(sitename, strlen(sitename) + 1);
		if (!name)
			goto fail;
	} else if ((const_name = libgamma_method_default_site(method))) {
		name = memdup(const_name, strlen(const_name) + 1);
		if (!name)
			goto fail;
	}

	if (name) {
		switch (method) {
		case LIBGAMMA_METHOD_X_RANDR:
		case LIBGAMMA_METHOD_X_VIDMODE:
			if ((p = strrchr(name, ':')))
				if ((p = strchr(p, '.')))
					*p = '\0';
			break;
		default:
			break;
		}
	}

	if (!rundir || !*rundir)
		rundir = "/tmp";

	if ((pw = getpwuid(getuid())))
		username = pw->pw_name ? pw->pw_name : "";

	n = sizeof("/.coopgammad/~/.") + 3 * sizeof(int);
	n += strlen(rundir) + strlen(username) + (name ? strlen(name) : 0) + strlen(suffix);
	if (!(rc = malloc(n)))
		goto fail;
	sprintf(rc, "%s/.coopgammad/~%s/%i%s%s%s",
	        rundir, username, method, name ? "." : "", name ? name : "", suffix);
	free(name);
	return rc;

fail:
	free(name);
	return NULL;
}


/**
 * Get the pathname of the socket
 * 
 * @return  The pathname of the socket, `NULL` on error
 */
char *
get_socket_pathname(void)
{
	return get_pathname(".socket");
}


/**
 * Get the pathname of the PID file
 * 
 * @return  The pathname of the PID file, `NULL` on error
 */
char *
get_pidfile_pathname(void)
{
	return get_pathname(".pid");
}


/**
 * Get the pathname of the state file
 * 
 * @return  The pathname of the state file, `NULL` on error
 */
char *
get_state_pathname(void)
{
	return get_pathname(".state");
}


/**
 * Check whether a PID file is outdated
 * 
 * @param   pidpath  The PID file
 * @param   token    An environment variable (including both key and value)
 *                   that must exist in the process if it is a coopgammad process
 * @return           -1: An error occurred
 *                    0: The service is already running
 *                    1: The PID file is outdated
 */
GCC_ONLY(__attribute__((__nonnull__)))
static int
is_pidfile_reusable(const char *restrict pidpath, const char *restrict token)
{
	/* PORTERS: /proc/$PID/environ is Linux specific */

	char temp[sizeof("/proc//environ") + 3 * sizeof(long long int)];
	int fd = -1, saved_errno, tries = 0;
	char *content = NULL;
	char *p;
	pid_t pid = 0;
	size_t n;
#if defined(__linux__) || defined(HAVE_LINUX_PROCFS)
	char *end;
#else
	(void) token;
#endif

	/* Get PID */
retry:
	fd = open(pidpath, O_RDONLY);
	if (fd < 0)
		return -1;
	content = nread(fd, &n);
	if (!content)
		goto fail;
	close(fd);
	fd = -1;

	if (!n) {
		if (++tries > 1)
			goto bad;
		msleep(100); /* 1 tenth of a second */
		goto retry;
	}

	if ('0' > content[0] || content[0] > '9')
		goto bad;
	if (content[0] == '0' && '0' <= content[1] && content[1] <= '9')
		goto bad;
	for (p = content; *p; p++)
		if ('0' <= *p && *p <= '9')
			pid = pid * 10 + (*p & 15);
		else
			break;
	if (*p++ != '\n')
		goto bad;
	if (*p)
		goto bad;
	if ((size_t)(p - content) != n)
		goto bad;
	sprintf(temp, "%llu\n", (unsigned long long int)pid);
	if (strcmp(content, temp))
		goto bad;
	free(content);

	/* Validate PID */
#if defined(__linux__) || defined(HAVE_LINUX_PROCFS)
	sprintf(temp, "/proc/%llu/environ", (unsigned long long int)pid);
	fd = open(temp, O_RDONLY);
	if (fd < 0)
		return (errno == ENOENT || errno == EACCES) ? 1 : -1;
	content = nread(fd, &n);
	if (!content)
		goto fail;
	close(fd), fd = -1;

	for (end = &(p = content)[n]; p != end; p = &strchr(p, '\0')[1])
		if (!strcmp(p, token))
			return free(content), 0;
	free(content);
#else
	if (!kill(pid, 0) || errno == EINVAL)
		return 0;
#endif

	return 1;

bad:
	fprintf(stderr, "%s: pid file contains invalid content: %s\n", argv0, pidpath);
	errno = 0;
	return -1;

fail:
	saved_errno = errno;
	free(content);
	if (fd >= 0)
		close(fd);
	errno = saved_errno;
	return -1;
}


/**
 * Create PID file
 * 
 * @param   pidpath  The pathname of the PID file
 * @return           Zero on success, -1 on error,
 *                   -2 if the service is already running
 */
int
create_pidfile(char *pidpath)
{
	int fd = -1, r, saved_errno;
	char *p;
	char *restrict token = NULL;

	/* Create token used to validate the service. */
	token = malloc(sizeof("COOPGAMMAD_PIDFILE_TOKEN=") + strlen(pidpath));
	if (!token)
		return -1;
	sprintf(token, "COOPGAMMAD_PIDFILE_TOKEN=%s", pidpath);
#if !defined(USE_VALGRIND)
	if (putenv(token))
		goto putenv_fail;
	/* `token` must not be free! */
#else
	{
		static char static_token[sizeof("COOPGAMMAD_PIDFILE_TOKEN=") + PATH_MAX];
		if (strlen(pidpath) > PATH_MAX)
			abort();
		strcpy(static_token, token);
		if (putenv(static_token))
			goto fail;
	}
#endif

	/* Create PID file's directory. */
	for (p = pidpath; *p == '/'; p++);
	while ((p = strchr(p, '/'))) {
		*p = '\0';
		if (mkdir(pidpath, 0755) < 0) {
			if (errno != EEXIST) {
				*p = '/';
				goto fail;
			}
		}
		*p++ = '/';
	}

	/* Create PID file. */
retry:
	fd = open(pidpath, O_CREAT | O_EXCL | O_WRONLY, 0644);
	if (fd < 0) {
		if (errno == EINTR)
			goto retry;
		if (errno != EEXIST)
			return -1;
		r = is_pidfile_reusable(pidpath, token);
		if (r > 0) {
			unlink(pidpath);
			goto retry;
		} else if (r < 0) {
			goto fail;
		}
		fprintf(stderr, "%s: service is already running\n", argv0);
		errno = 0;
		return -2;
	}

	/* Write PID to PID file. */
	if (dprintf(fd, "%llu\n", (unsigned long long)getpid()) < 0)
		goto fail;

	/* Done */
#if defined(USE_VALGRIND)
	free(token);
#endif
	if (close(fd) < 0)
		if (errno != EINTR)
			return -1;
	return 0;
#if !defined(USE_VALGRIND)
putenv_fail:
	free(token);
#endif
fail:
#if defined(USE_VALGRIND)
	free(token);
#endif
	if (fd >= 0) {
		saved_errno = errno;
		close(fd);
		unlink(pidpath);
		errno = saved_errno;
	}
	return -1;
}


/**
 * Create socket and start listening
 * 
 * @param   socketpath  The pathname of the socket
 * @return              Zero on success, -1 on error
 */
int
create_socket(const char *socketpath)
{
	struct sockaddr_un address;

	address.sun_family = AF_UNIX;
	if (strlen(socketpath) >= sizeof(address.sun_path)) {
		errno = ENAMETOOLONG;
		return -1;
	}
	strcpy(address.sun_path, socketpath);
	unlink(socketpath);
	socketfd = socket(PF_UNIX, SOCK_STREAM, 0);
	if (socketfd < 0)
		return -1;
	if (fchmod(socketfd, S_IRWXU) < 0)
		return -1;
	if (bind(socketfd, (struct sockaddr *)&address, (socklen_t)sizeof(address)) < 0)
		return -1;
	if (listen(socketfd, SOMAXCONN) < 0)
		return -1;

	return 0;
}


/**
 * Close and unlink the socket
 * 
 * @param  socketpath  The pathname of the socket
 */
void
close_socket(const char *socketpath)
{
	if (socketfd >= 0) {
		shutdown(socketfd, SHUT_RDWR);
		close(socketfd);
		unlink(socketpath);
	}
}