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 	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