xref: /freebsd/usr.bin/posixshmcontrol/posixshmcontrol.c (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 /*-
2  * Copyright (c) 2019 The FreeBSD Foundation
3  *
4  * This software was developed by Konstantin Belousov <kib@FreeBSD.org>
5  * under sponsorship from the FreeBSD Foundation.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/filio.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 #include <sys/syscall.h>
37 #include <sys/sysctl.h>
38 #include <sys/user.h>
39 #include <err.h>
40 #include <fcntl.h>
41 #include <grp.h>
42 #include <jail.h>
43 #include <libutil.h>
44 #include <pwd.h>
45 #include <stdbool.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 static void
52 usage(void)
53 {
54 
55 	fprintf(stderr, "Usage:\n"
56 	    "posixshmcontrol create [-m <mode>] [-l <largepage>] <path> ...\n"
57 	    "posixshmcontrol rm <path> ...\n"
58 	    "posixshmcontrol ls [-h] [-n] [-j jail]\n"
59 	    "posixshmcontrol dump <path> ...\n"
60 	    "posixshmcontrol stat [-h] [-n] <path> ...\n"
61 	    "posixshmcontrol truncate [-s <newlen>] <path> ...\n");
62 }
63 
64 static int
65 create_one_shm(const char *path, long mode, int idx)
66 {
67 	int fd;
68 
69 	if (idx == -1) {
70 		fd = shm_open(path, O_RDWR | O_CREAT, mode);
71 		if (fd == -1) {
72 			warn("create %s", path);
73 			return (1);
74 		}
75 	} else {
76 		fd = shm_create_largepage(path, O_RDWR, idx,
77 		    SHM_LARGEPAGE_ALLOC_DEFAULT, mode);
78 		if (fd == -1) {
79 			warn("shm_create_largepage %s psind %d", path, idx);
80 			return (1);
81 		}
82 	}
83 	close(fd);
84 	return (0);
85 }
86 
87 static int
88 create_shm(int argc, char **argv)
89 {
90 	char *end;
91 	size_t *pagesizes;
92 	long mode;
93 	uint64_t pgsz;
94 	int c, i, idx, pn, ret, ret1;
95 	bool printed;
96 
97 	mode = 0600;
98 	idx = -1;
99 	while ((c = getopt(argc, argv, "l:m:")) != -1) {
100 		switch (c) {
101 		case 'm':
102 			errno = 0;
103 			mode = strtol(optarg, &end, 0);
104 			if (mode == 0 && errno != 0)
105 				err(1, "mode");
106 			if (*end != '\0')
107 				errx(1, "non-integer mode");
108 			break;
109 		case 'l':
110 			if (expand_number(optarg, &pgsz) == -1)
111 				err(1, "size");
112 			pn = getpagesizes(NULL, 0);
113 			if (pn == -1)
114 				err(1, "getpagesizes");
115 			pagesizes = malloc(sizeof(size_t) * pn);
116 			if (pagesizes == NULL)
117 				err(1, "malloc");
118 			if (getpagesizes(pagesizes, pn) == -1)
119 				err(1, "gtpagesizes");
120 			for (idx = 0; idx < pn; idx++) {
121 				if (pagesizes[idx] == pgsz)
122 					break;
123 			}
124 			if (idx == pn) {
125 				fprintf(stderr,
126     "pagesize should be superpagesize, supported sizes:");
127 				printed = false;
128 				for (i = 0; i < pn; i++) {
129 					if (pagesizes[i] == 0 ||
130 					    pagesizes[i] == (size_t)
131 					    getpagesize())
132 						continue;
133 					printed = true;
134 					fprintf(stderr, " %zu", pagesizes[i]);
135 				}
136 				if (!printed)
137 					fprintf(stderr, " none");
138 				fprintf(stderr, "\n");
139 				exit(1);
140 			}
141 			if (pgsz == (uint64_t)getpagesize())
142 				errx(1, "pagesize should be large");
143 			free(pagesizes);
144 			break;
145 		case '?':
146 		default:
147 			usage();
148 			return (2);
149 		}
150 	}
151 	argc -= optind;
152 	argv += optind;
153 
154 	if (argc == 0) {
155 		usage();
156 		return (2);
157 	}
158 
159 	ret = 0;
160 	for (i = 0; i < argc; i++) {
161 		ret1 = create_one_shm(argv[i], mode, idx);
162 		if (ret1 != 0 && ret == 0)
163 			ret = ret1;
164 	}
165 	return (ret);
166 }
167 
168 static int
169 delete_one_shm(const char *path)
170 {
171 	int error, ret;
172 
173 	error = shm_unlink(path);
174 	if (error != 0) {
175 		warn("unlink of %s failed", path);
176 		ret = 1;
177 	} else {
178 		ret = 0;
179 	}
180 	return (ret);
181 }
182 
183 static int
184 delete_shm(int argc, char **argv)
185 {
186 	int i, ret, ret1;
187 
188 	if (argc == 1) {
189 		usage();
190 		return (2);
191 	}
192 
193 	ret = 0;
194 	for (i = 1; i < argc; i++) {
195 		ret1 = delete_one_shm(argv[i]);
196 		if (ret1 != 0 && ret == 0)
197 			ret = ret1;
198 	}
199 	return (ret);
200 }
201 
202 static const char listmib[] = "kern.ipc.posix_shm_list";
203 
204 static void
205 shm_decode_mode(mode_t m, char *str)
206 {
207 	int i;
208 
209 	i = 0;
210 	str[i++] = (m & S_IRUSR) != 0 ? 'r' : '-';
211 	str[i++] = (m & S_IWUSR) != 0 ? 'w' : '-';
212 	str[i++] = (m & S_IXUSR) != 0 ? 'x' : '-';
213 	str[i++] = (m & S_IRGRP) != 0 ? 'r' : '-';
214 	str[i++] = (m & S_IWGRP) != 0 ? 'w' : '-';
215 	str[i++] = (m & S_IXGRP) != 0 ? 'x' : '-';
216 	str[i++] = (m & S_IROTH) != 0 ? 'r' : '-';
217 	str[i++] = (m & S_IWOTH) != 0 ? 'w' : '-';
218 	str[i++] = (m & S_IXOTH) != 0 ? 'x' : '-';
219 	str[i] = '\0';
220 }
221 
222 static int
223 list_shm(int argc, char **argv)
224 {
225 	char *buf, *bp, *ep, jailpath[MAXPATHLEN], sizebuf[8], str[10];
226 	const char *jailparam;
227 	const struct kinfo_file *kif;
228 	struct stat st;
229 	int c, error, fd, jid, mib[3], ret;
230 	size_t len, jailpathlen, miblen;
231 	bool hsize, jailed, uname;
232 
233 	hsize = false;
234 	jailed = false;
235 	uname = true;
236 
237 	while ((c = getopt(argc, argv, "hj:n")) != -1) {
238 		switch (c) {
239 		case 'h':
240 			hsize = true;
241 			break;
242 		case 'n':
243 			uname = false;
244 			break;
245 		case 'j':
246 			jid = strtoul(optarg, &ep, 10);
247 			if (ep > optarg && !*ep) {
248 				jailparam = "jid";
249 				jailed = jid > 0;
250 			} else {
251 				jailparam = "name";
252 				jailed = true;
253 			}
254 			if (jailed) {
255 				if (jail_getv(0, jailparam, optarg, "path",
256 				    jailpath, NULL) < 0) {
257 					if (errno == ENOENT)
258 						warnx("no such jail: %s", optarg);
259 					else
260 						warnx("%s", jail_errmsg);
261 					return (1);
262 				}
263 				jailpathlen = strlen(jailpath);
264 				jailpath[jailpathlen] = '/';
265 			}
266 			break;
267 		default:
268 			usage();
269 			return (2);
270 		}
271 	}
272 	if (argc != optind) {
273 		usage();
274 		return (2);
275 	}
276 
277 	miblen = nitems(mib);
278 	error = sysctlnametomib(listmib, mib, &miblen);
279 	if (error == -1) {
280 		warn("cannot translate %s", listmib);
281 		return (1);
282 	}
283 	len = 0;
284 	error = sysctl(mib, miblen, NULL, &len, NULL, 0);
285 	if (error == -1) {
286 		warn("cannot get %s length", listmib);
287 		return (1);
288 	}
289 	len = len * 4 / 3;
290 	buf = malloc(len);
291 	if (buf == NULL) {
292 		warn("malloc");
293 		return (1);
294 	}
295 	error = sysctl(mib, miblen, buf, &len, NULL, 0);
296 	if (error != 0) {
297 		warn("reading %s", listmib);
298 		ret = 1;
299 		goto out;
300 	}
301 	ret = 0;
302 	printf("MODE    \tOWNER\tGROUP\tSIZE\tPATH\n");
303 	for (bp = buf; bp < buf + len; bp += kif->kf_structsize) {
304 		kif = (const struct kinfo_file *)(void *)bp;
305 		if (kif->kf_structsize == 0)
306 			break;
307 		if (jailed && strncmp(kif->kf_path, jailpath, jailpathlen + 1))
308 			continue;
309 		fd = shm_open(kif->kf_path, O_RDONLY, 0);
310 		if (fd == -1) {
311 			warn("open %s", kif->kf_path);
312 			ret = 1;
313 			continue;
314 		}
315 		error = fstat(fd, &st);
316 		close(fd);
317 		if (error != 0) {
318 			warn("stat %s", kif->kf_path);
319 			ret = 1;
320 			continue;
321 		}
322 		shm_decode_mode(kif->kf_un.kf_file.kf_file_mode, str);
323 		printf("%s\t", str);
324 		if (uname) {
325 			printf("%s\t%s\t", user_from_uid(st.st_uid, 0),
326 			    group_from_gid(st.st_gid, 0));
327 		} else {
328 			printf("%d\t%d\t", st.st_uid, st.st_gid);
329 		}
330 		if (hsize) {
331 			humanize_number(sizebuf, sizeof(sizebuf),
332 			    kif->kf_un.kf_file.kf_file_size, "", HN_AUTOSCALE,
333 			    HN_NOSPACE);
334 			printf("%s\t", sizebuf);
335 		} else {
336 			printf("%jd\t",
337 			    (uintmax_t)kif->kf_un.kf_file.kf_file_size);
338 		}
339 		printf("%s\n", kif->kf_path);
340 	}
341 out:
342 	free(buf);
343 	return (ret);
344 }
345 
346 static int
347 read_one_shm(const char *path)
348 {
349 	char buf[4096];
350 	ssize_t size, se;
351 	int fd, ret;
352 
353 	ret = 1;
354 	fd = shm_open(path, O_RDONLY, 0);
355 	if (fd == -1) {
356 		warn("open %s", path);
357 		goto out;
358 	}
359 	for (;;) {
360 		size = read(fd, buf, sizeof(buf));
361 		if (size > 0) {
362 			se = fwrite(buf, 1, size, stdout);
363 			if (se < size) {
364 				warnx("short write to stdout");
365 				goto out;
366 			}
367 		}
368 		if (size == (ssize_t)sizeof(buf))
369 			continue;
370 		if (size >= 0 && size < (ssize_t)sizeof(buf)) {
371 			ret = 0;
372 			goto out;
373 		}
374 		warn("read from %s", path);
375 		goto out;
376 	}
377 out:
378 	close(fd);
379 	return (ret);
380 }
381 
382 static int
383 read_shm(int argc, char **argv)
384 {
385 	int i, ret, ret1;
386 
387 	if (argc == 1) {
388 		usage();
389 		return (2);
390 	}
391 
392 	ret = 0;
393 	for (i = 1; i < argc; i++) {
394 		ret1 = read_one_shm(argv[i]);
395 		if (ret1 != 0 && ret == 0)
396 			ret = ret1;
397 	}
398 	return (ret);
399 }
400 
401 static int
402 stat_one_shm(const char *path, bool hsize, bool uname)
403 {
404 	char sizebuf[8];
405 	struct stat st;
406 	int error, fd, ret;
407 
408 	fd = shm_open(path, O_RDONLY, 0);
409 	if (fd == -1) {
410 		warn("open %s", path);
411 		return (1);
412 	}
413 	ret = 0;
414 	error = fstat(fd, &st);
415 	if (error == -1) {
416 		warn("stat %s", path);
417 		ret = 1;
418 	} else {
419 		printf("path\t%s\n", path);
420 		printf("inode\t%jd\n", (uintmax_t)st.st_ino);
421 		printf("mode\t%#o\n", st.st_mode);
422 		printf("nlink\t%jd\n", (uintmax_t)st.st_nlink);
423 		if (uname) {
424 			printf("owner\t%s\n", user_from_uid(st.st_uid, 0));
425 			printf("group\t%s\n", group_from_gid(st.st_gid, 0));
426 		} else {
427 			printf("uid\t%d\n", st.st_uid);
428 			printf("gid\t%d\n", st.st_gid);
429 		}
430 		if (hsize) {
431 			humanize_number(sizebuf, sizeof(sizebuf),
432 			    st.st_size, "", HN_AUTOSCALE, HN_NOSPACE);
433 			printf("size\t%s\n", sizebuf);
434 		} else {
435 			printf("size\t%jd\n", (uintmax_t)st.st_size);
436 		}
437 		printf("atime\t%ld.%09ld\n", (long)st.st_atime,
438 		    (long)st.st_atim.tv_nsec);
439 		printf("mtime\t%ld.%09ld\n", (long)st.st_mtime,
440 		    (long)st.st_mtim.tv_nsec);
441 		printf("ctime\t%ld.%09ld\n", (long)st.st_ctime,
442 		    (long)st.st_ctim.tv_nsec);
443 		printf("birth\t%ld.%09ld\n", (long)st.st_birthtim.tv_sec,
444 		    (long)st.st_birthtim.tv_nsec);
445 		if (st.st_blocks != 0)
446 			printf("pagesz\t%jd\n", roundup((uintmax_t)st.st_size,
447 			    PAGE_SIZE) / st.st_blocks);
448 	}
449 	close(fd);
450 	return (ret);
451 }
452 
453 static int
454 stat_shm(int argc, char **argv)
455 {
456 	int c, i, ret, ret1;
457 	bool hsize, uname;
458 
459 	hsize = false;
460 	uname = true;
461 
462 	while ((c = getopt(argc, argv, "hn")) != -1) {
463 		switch (c) {
464 		case 'h':
465 			hsize = true;
466 			break;
467 		case 'n':
468 			uname = false;
469 			break;
470 		default:
471 			usage();
472 			return (2);
473 		}
474 	}
475 	argc -= optind;
476 	argv += optind;
477 
478 	if (argc == 0) {
479 		usage();
480 		return (2);
481 	}
482 
483 	ret = 0;
484 	for (i = 0; i < argc; i++) {
485 		ret1 = stat_one_shm(argv[i], hsize, uname);
486 		if (ret1 != 0 && ret == 0)
487 			ret = ret1;
488 	}
489 	return (ret);
490 }
491 
492 static int
493 truncate_one_shm(const char *path, uint64_t newsize)
494 {
495 	int error, fd, ret;
496 
497 	ret = 0;
498 	fd = shm_open(path, O_RDWR, 0);
499 	if (fd == -1) {
500 		warn("open %s", path);
501 		return (1);
502 	}
503 	error = ftruncate(fd, newsize);
504 	if (error == -1) {
505 		warn("truncate %s", path);
506 		ret = 1;
507 	}
508 	close(fd);
509 	return (ret);
510 }
511 
512 static int
513 truncate_shm(int argc, char **argv)
514 {
515 	uint64_t newsize;
516 	int c, i, ret, ret1;
517 
518 	newsize = 0;
519 	while ((c = getopt(argc, argv, "s:")) != -1) {
520 		switch (c) {
521 		case 's':
522 			if (expand_number(optarg, &newsize) == -1)
523 				err(1, "size");
524 			break;
525 		case '?':
526 		default:
527 			return (2);
528 		}
529 	}
530 	argc -= optind;
531 	argv += optind;
532 
533 	if (argc == 0) {
534 		usage();
535 		return (2);
536 	}
537 
538 	ret = 0;
539 	for (i = 0; i < argc; i++) {
540 		ret1 = truncate_one_shm(argv[i], newsize);
541 		if (ret1 != 0 && ret == 0)
542 			ret = ret1;
543 	}
544 	return (ret);
545 }
546 
547 struct opmode {
548 	const char *cmd;
549 	int (*impl)(int argc, char **argv);
550 };
551 
552 static const struct opmode opmodes[] = {
553 	{ .cmd = "create",	.impl = create_shm},
554 	{ .cmd = "rm",		.impl = delete_shm, },
555 	{ .cmd = "list",	.impl = list_shm },
556 	{ .cmd = "ls",		.impl = list_shm },
557 	{ .cmd = "dump",	.impl = read_shm, },
558 	{ .cmd = "stat",	.impl = stat_shm, },
559 	{ .cmd = "truncate",	.impl = truncate_shm, },
560 };
561 
562 int
563 main(int argc, char *argv[])
564 {
565 	const struct opmode *opmode;
566 	int i, ret;
567 
568 	ret = 0;
569 	opmode = NULL;
570 
571 	if (argc < 2) {
572 		usage();
573 		exit(2);
574 	}
575 	for (i = 0; i < (int)nitems(opmodes); i++) {
576 		if (strcmp(argv[1], opmodes[i].cmd) == 0) {
577 			opmode = &opmodes[i];
578 			break;
579 		}
580 	}
581 	if (opmode == NULL) {
582 		usage();
583 		exit(2);
584 	}
585 	ret = opmode->impl(argc - 1, argv + 1);
586 	exit(ret);
587 }
588