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 #include <sys/param.h>
31 #include <sys/filio.h>
32 #include <sys/mman.h>
33 #include <sys/stat.h>
34 #include <sys/syscall.h>
35 #include <sys/sysctl.h>
36 #include <sys/user.h>
37 #include <err.h>
38 #include <fcntl.h>
39 #include <grp.h>
40 #include <jail.h>
41 #include <libutil.h>
42 #include <pwd.h>
43 #include <stdbool.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 static void
50 usage(void)
51 {
52 
53 	fprintf(stderr, "Usage:\n"
54 	    "posixshmcontrol create [-m <mode>] [-l <largepage>] <path> ...\n"
55 	    "posixshmcontrol rm <path> ...\n"
56 	    "posixshmcontrol ls [-h] [-n] [-j jail]\n"
57 	    "posixshmcontrol dump <path> ...\n"
58 	    "posixshmcontrol stat [-h] [-n] <path> ...\n"
59 	    "posixshmcontrol truncate [-s <newlen>] <path> ...\n");
60 }
61 
62 static int
63 create_one_shm(const char *path, long mode, int idx)
64 {
65 	int fd;
66 
67 	if (idx == -1) {
68 		fd = shm_open(path, O_RDWR | O_CREAT, mode);
69 		if (fd == -1) {
70 			warn("create %s", path);
71 			return (1);
72 		}
73 	} else {
74 		fd = shm_create_largepage(path, O_RDWR, idx,
75 		    SHM_LARGEPAGE_ALLOC_DEFAULT, mode);
76 		if (fd == -1) {
77 			warn("shm_create_largepage %s psind %d", path, idx);
78 			return (1);
79 		}
80 	}
81 	close(fd);
82 	return (0);
83 }
84 
85 static int
86 create_shm(int argc, char **argv)
87 {
88 	char *end;
89 	size_t *pagesizes;
90 	long mode;
91 	uint64_t pgsz;
92 	int c, i, idx, pn, ret, ret1;
93 	bool printed;
94 
95 	mode = 0600;
96 	idx = -1;
97 	while ((c = getopt(argc, argv, "l:m:")) != -1) {
98 		switch (c) {
99 		case 'm':
100 			errno = 0;
101 			mode = strtol(optarg, &end, 0);
102 			if (mode == 0 && errno != 0)
103 				err(1, "mode");
104 			if (*end != '\0')
105 				errx(1, "non-integer mode");
106 			break;
107 		case 'l':
108 			if (expand_number(optarg, &pgsz) == -1)
109 				err(1, "size");
110 			pn = getpagesizes(NULL, 0);
111 			if (pn == -1)
112 				err(1, "getpagesizes");
113 			pagesizes = malloc(sizeof(size_t) * pn);
114 			if (pagesizes == NULL)
115 				err(1, "malloc");
116 			if (getpagesizes(pagesizes, pn) == -1)
117 				err(1, "gtpagesizes");
118 			for (idx = 0; idx < pn; idx++) {
119 				if (pagesizes[idx] == pgsz)
120 					break;
121 			}
122 			if (idx == pn) {
123 				fprintf(stderr,
124     "pagesize should be superpagesize, supported sizes:");
125 				printed = false;
126 				for (i = 0; i < pn; i++) {
127 					if (pagesizes[i] == 0 ||
128 					    pagesizes[i] == (size_t)
129 					    getpagesize())
130 						continue;
131 					printed = true;
132 					fprintf(stderr, " %zu", pagesizes[i]);
133 				}
134 				if (!printed)
135 					fprintf(stderr, " none");
136 				fprintf(stderr, "\n");
137 				exit(1);
138 			}
139 			if (pgsz == (uint64_t)getpagesize())
140 				errx(1, "pagesize should be large");
141 			free(pagesizes);
142 			break;
143 		case '?':
144 		default:
145 			usage();
146 			return (2);
147 		}
148 	}
149 	argc -= optind;
150 	argv += optind;
151 
152 	if (argc == 0) {
153 		usage();
154 		return (2);
155 	}
156 
157 	ret = 0;
158 	for (i = 0; i < argc; i++) {
159 		ret1 = create_one_shm(argv[i], mode, idx);
160 		if (ret1 != 0 && ret == 0)
161 			ret = ret1;
162 	}
163 	return (ret);
164 }
165 
166 static int
167 delete_one_shm(const char *path)
168 {
169 	int error, ret;
170 
171 	error = shm_unlink(path);
172 	if (error != 0) {
173 		warn("unlink of %s failed", path);
174 		ret = 1;
175 	} else {
176 		ret = 0;
177 	}
178 	return (ret);
179 }
180 
181 static int
182 delete_shm(int argc, char **argv)
183 {
184 	int i, ret, ret1;
185 
186 	if (argc == 1) {
187 		usage();
188 		return (2);
189 	}
190 
191 	ret = 0;
192 	for (i = 1; i < argc; i++) {
193 		ret1 = delete_one_shm(argv[i]);
194 		if (ret1 != 0 && ret == 0)
195 			ret = ret1;
196 	}
197 	return (ret);
198 }
199 
200 static const char listmib[] = "kern.ipc.posix_shm_list";
201 
202 static void
203 shm_decode_mode(mode_t m, char *str)
204 {
205 	int i;
206 
207 	i = 0;
208 	str[i++] = (m & S_IRUSR) != 0 ? 'r' : '-';
209 	str[i++] = (m & S_IWUSR) != 0 ? 'w' : '-';
210 	str[i++] = (m & S_IXUSR) != 0 ? 'x' : '-';
211 	str[i++] = (m & S_IRGRP) != 0 ? 'r' : '-';
212 	str[i++] = (m & S_IWGRP) != 0 ? 'w' : '-';
213 	str[i++] = (m & S_IXGRP) != 0 ? 'x' : '-';
214 	str[i++] = (m & S_IROTH) != 0 ? 'r' : '-';
215 	str[i++] = (m & S_IWOTH) != 0 ? 'w' : '-';
216 	str[i++] = (m & S_IXOTH) != 0 ? 'x' : '-';
217 	str[i] = '\0';
218 }
219 
220 static int
221 list_shm(int argc, char **argv)
222 {
223 	char *buf, *bp, *ep, jailpath[MAXPATHLEN], sizebuf[8], str[10];
224 	const char *jailparam;
225 	const struct kinfo_file *kif;
226 	struct stat st;
227 	int c, error, fd, jid, mib[3], ret;
228 	size_t len, jailpathlen, miblen;
229 	bool hsize, jailed, uname;
230 
231 	hsize = false;
232 	jailed = false;
233 	uname = true;
234 
235 	while ((c = getopt(argc, argv, "hj:n")) != -1) {
236 		switch (c) {
237 		case 'h':
238 			hsize = true;
239 			break;
240 		case 'n':
241 			uname = false;
242 			break;
243 		case 'j':
244 			jid = strtoul(optarg, &ep, 10);
245 			if (ep > optarg && !*ep) {
246 				jailparam = "jid";
247 				jailed = jid > 0;
248 			} else {
249 				jailparam = "name";
250 				jailed = true;
251 			}
252 			if (jailed) {
253 				if (jail_getv(0, jailparam, optarg, "path",
254 				    jailpath, NULL) < 0) {
255 					if (errno == ENOENT)
256 						warnx("no such jail: %s", optarg);
257 					else
258 						warnx("%s", jail_errmsg);
259 					return (1);
260 				}
261 				jailpathlen = strlen(jailpath);
262 				jailpath[jailpathlen] = '/';
263 			}
264 			break;
265 		default:
266 			usage();
267 			return (2);
268 		}
269 	}
270 	if (argc != optind) {
271 		usage();
272 		return (2);
273 	}
274 
275 	miblen = nitems(mib);
276 	error = sysctlnametomib(listmib, mib, &miblen);
277 	if (error == -1) {
278 		warn("cannot translate %s", listmib);
279 		return (1);
280 	}
281 	len = 0;
282 	error = sysctl(mib, miblen, NULL, &len, NULL, 0);
283 	if (error == -1) {
284 		warn("cannot get %s length", listmib);
285 		return (1);
286 	}
287 	len = len * 4 / 3;
288 	buf = malloc(len);
289 	if (buf == NULL) {
290 		warn("malloc");
291 		return (1);
292 	}
293 	error = sysctl(mib, miblen, buf, &len, NULL, 0);
294 	if (error != 0) {
295 		warn("reading %s", listmib);
296 		ret = 1;
297 		goto out;
298 	}
299 	ret = 0;
300 	printf("MODE    \tOWNER\tGROUP\tSIZE\tPATH\n");
301 	for (bp = buf; bp < buf + len; bp += kif->kf_structsize) {
302 		kif = (const struct kinfo_file *)(void *)bp;
303 		if (kif->kf_structsize == 0)
304 			break;
305 		if (jailed && strncmp(kif->kf_path, jailpath, jailpathlen + 1))
306 			continue;
307 		fd = shm_open(kif->kf_path, O_RDONLY, 0);
308 		if (fd == -1) {
309 			if (errno != EACCES) {
310 				warn("open %s", kif->kf_path);
311 				ret = 1;
312 			}
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 	struct shm_largepage_conf conf_dummy;
408 	bool largepage;
409 
410 	fd = shm_open(path, O_RDONLY, 0);
411 	if (fd == -1) {
412 		warn("open %s", path);
413 		return (1);
414 	}
415 	ret = 0;
416 	error = fstat(fd, &st);
417 	if (error == -1) {
418 		warn("stat %s", path);
419 		ret = 1;
420 	} else {
421 		printf("path\t%s\n", path);
422 		printf("inode\t%jd\n", (uintmax_t)st.st_ino);
423 		printf("mode\t%#o\n", st.st_mode);
424 		printf("nlink\t%jd\n", (uintmax_t)st.st_nlink);
425 		if (uname) {
426 			printf("owner\t%s\n", user_from_uid(st.st_uid, 0));
427 			printf("group\t%s\n", group_from_gid(st.st_gid, 0));
428 		} else {
429 			printf("uid\t%d\n", st.st_uid);
430 			printf("gid\t%d\n", st.st_gid);
431 		}
432 		if (hsize) {
433 			humanize_number(sizebuf, sizeof(sizebuf),
434 			    st.st_size, "", HN_AUTOSCALE, HN_NOSPACE);
435 			printf("size\t%s\n", sizebuf);
436 		} else {
437 			printf("size\t%jd\n", (uintmax_t)st.st_size);
438 		}
439 		printf("atime\t%ld.%09ld\n", (long)st.st_atime,
440 		    (long)st.st_atim.tv_nsec);
441 		printf("mtime\t%ld.%09ld\n", (long)st.st_mtime,
442 		    (long)st.st_mtim.tv_nsec);
443 		printf("ctime\t%ld.%09ld\n", (long)st.st_ctime,
444 		    (long)st.st_ctim.tv_nsec);
445 		printf("birth\t%ld.%09ld\n", (long)st.st_birthtim.tv_sec,
446 		    (long)st.st_birthtim.tv_nsec);
447 		error = ioctl(fd, FIOGSHMLPGCNF, &conf_dummy);
448 		largepage = error == 0;
449 		if (st.st_blocks != 0 && largepage)
450 			printf("pagesz\t%jd\n", roundup((uintmax_t)st.st_size,
451 			    PAGE_SIZE) / st.st_blocks);
452 		else
453 			printf("pages\t%jd\n", st.st_blocks);
454 	}
455 	close(fd);
456 	return (ret);
457 }
458 
459 static int
460 stat_shm(int argc, char **argv)
461 {
462 	int c, i, ret, ret1;
463 	bool hsize, uname;
464 
465 	hsize = false;
466 	uname = true;
467 
468 	while ((c = getopt(argc, argv, "hn")) != -1) {
469 		switch (c) {
470 		case 'h':
471 			hsize = true;
472 			break;
473 		case 'n':
474 			uname = false;
475 			break;
476 		default:
477 			usage();
478 			return (2);
479 		}
480 	}
481 	argc -= optind;
482 	argv += optind;
483 
484 	if (argc == 0) {
485 		usage();
486 		return (2);
487 	}
488 
489 	ret = 0;
490 	for (i = 0; i < argc; i++) {
491 		ret1 = stat_one_shm(argv[i], hsize, uname);
492 		if (ret1 != 0 && ret == 0)
493 			ret = ret1;
494 	}
495 	return (ret);
496 }
497 
498 static int
499 truncate_one_shm(const char *path, uint64_t newsize)
500 {
501 	int error, fd, ret;
502 
503 	ret = 0;
504 	fd = shm_open(path, O_RDWR, 0);
505 	if (fd == -1) {
506 		warn("open %s", path);
507 		return (1);
508 	}
509 	error = ftruncate(fd, newsize);
510 	if (error == -1) {
511 		warn("truncate %s", path);
512 		ret = 1;
513 	}
514 	close(fd);
515 	return (ret);
516 }
517 
518 static int
519 truncate_shm(int argc, char **argv)
520 {
521 	uint64_t newsize;
522 	int c, i, ret, ret1;
523 
524 	newsize = 0;
525 	while ((c = getopt(argc, argv, "s:")) != -1) {
526 		switch (c) {
527 		case 's':
528 			if (expand_number(optarg, &newsize) == -1)
529 				err(1, "size");
530 			break;
531 		case '?':
532 		default:
533 			return (2);
534 		}
535 	}
536 	argc -= optind;
537 	argv += optind;
538 
539 	if (argc == 0) {
540 		usage();
541 		return (2);
542 	}
543 
544 	ret = 0;
545 	for (i = 0; i < argc; i++) {
546 		ret1 = truncate_one_shm(argv[i], newsize);
547 		if (ret1 != 0 && ret == 0)
548 			ret = ret1;
549 	}
550 	return (ret);
551 }
552 
553 struct opmode {
554 	const char *cmd;
555 	int (*impl)(int argc, char **argv);
556 };
557 
558 static const struct opmode opmodes[] = {
559 	{ .cmd = "create",	.impl = create_shm},
560 	{ .cmd = "rm",		.impl = delete_shm, },
561 	{ .cmd = "list",	.impl = list_shm },
562 	{ .cmd = "ls",		.impl = list_shm },
563 	{ .cmd = "dump",	.impl = read_shm, },
564 	{ .cmd = "stat",	.impl = stat_shm, },
565 	{ .cmd = "truncate",	.impl = truncate_shm, },
566 };
567 
568 int
569 main(int argc, char *argv[])
570 {
571 	const struct opmode *opmode;
572 	int i, ret;
573 
574 	ret = 0;
575 	opmode = NULL;
576 
577 	if (argc < 2) {
578 		usage();
579 		exit(2);
580 	}
581 	for (i = 0; i < (int)nitems(opmodes); i++) {
582 		if (strcmp(argv[1], opmodes[i].cmd) == 0) {
583 			opmode = &opmodes[i];
584 			break;
585 		}
586 	}
587 	if (opmode == NULL) {
588 		usage();
589 		exit(2);
590 	}
591 	ret = opmode->impl(argc - 1, argv + 1);
592 	exit(ret);
593 }
594