summaryrefslogtreecommitdiff
path: root/stik.c
blob: f3f7a76973864c43c6369d2c01f119a7fc9912a9 (plain)
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
/*
 * stik - minimal removable device mount/unmount
 * https://rawnix.org
 *
 * Copyright (c) 2025 zorz@gmx.com
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Mounts removable devices to /media/<devname>.
 * Supports vfat, exfat, ntfs, ext2/3/4, btrfs, xfs, f2fs, iso9660, udf.
 *
 * Usage: stik mount [-nr] /dev/sdX
 *        stik umount /dev/sdX
 *
 * Installed setuid root; only root and members of the group plugdev
 * may use it.  Everything below assumes hostile input from an
 * unprivileged caller: no subprocesses, no shell, no environment trust.
 *
 * Filesystems that carry ownership on disk (ext*, btrfs, xfs, f2fs) are
 * mounted through an idmapped mount that maps on-disk uid/gid 0 to the
 * caller, so the caller can write to media formatted by root without
 * anything on disk being modified.  Requires Linux 5.12+; falls back to a
 * plain mount with a warning.
 */

#define _GNU_SOURCE

#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <limits.h>
#include <mntent.h>
#include <pwd.h>
#include <sched.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>

/* ------------------------------------------------------------------ *
 * syscall numbers and constants; kernel headers may predate them
 * ------------------------------------------------------------------ */

#ifndef SYS_fsopen
#define SYS_fsopen 430
#endif
#ifndef SYS_fsconfig
#define SYS_fsconfig 431
#endif
#ifndef SYS_fsmount
#define SYS_fsmount 432
#endif
#ifndef SYS_move_mount
#define SYS_move_mount 429
#endif
#ifndef SYS_mount_setattr
#define SYS_mount_setattr 442
#endif

#define FSCONFIG_SET_STRING 1
#define FSCONFIG_CMD_CREATE 6

#define MOUNT_ATTR_RDONLY 0x00000001
#define MOUNT_ATTR_NOSUID 0x00000002
#define MOUNT_ATTR_NODEV 0x00000004
#define MOUNT_ATTR_IDMAP 0x00100000

#define MOVE_MOUNT_F_EMPTY_PATH 0x00000004

struct stik_mount_attr {
	uint64_t attr_set;
	uint64_t attr_clr;
	uint64_t propagation;
	uint64_t userns_fd;
};

static int
sys_fsopen(const char *fsname)
{
	return (int)syscall(SYS_fsopen, fsname, 0U);
}

static int
sys_fsconfig(int fd, unsigned cmd, const char *key, const char *value)
{
	return (int)syscall(SYS_fsconfig, fd, cmd, key, value, 0);
}

static int
sys_fsmount(int fd, unsigned attr)
{
	return (int)syscall(SYS_fsmount, fd, 0U, attr);
}

static int
sys_move_mount(int from_fd, const char *from, int to_fd, const char *to,
	unsigned flags)
{
	return (int)syscall(SYS_move_mount, from_fd, from, to_fd, to, flags);
}

static int
sys_mount_setattr(int fd, const char *path, unsigned flags,
	struct stik_mount_attr *attr)
{
	return (int)syscall(SYS_mount_setattr, fd, path, flags, attr,
		sizeof(*attr));
}

/* ------------------------------------------------------------------ */

#define STIK_VERSION "1.2"

#define MEDIA_DIR "/media"
#define STIK_GROUP "plugdev"

static const char *prog = "stik";

static void
warnx_(const char *fmt, ...)
{
	va_list ap;

	fprintf(stderr, "%s: ", prog);
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	fputc('\n', stderr);
}

static void
info(const char *fmt, ...)
{
	va_list ap;

	fputs("==> ", stdout);
	va_start(ap, fmt);
	vfprintf(stdout, fmt, ap);
	va_end(ap);
	fputc('\n', stdout);
	fflush(stdout);
}

/* ------------------------------------------------------------------ *
 * filesystem probing: read the superblock ourselves.  No lsblk, no
 * popen, no shell, no util-linux dependency.
 * ------------------------------------------------------------------ */

enum optstyle {
	OPT_NATIVE,	/* ownership lives on disk; idmap candidate */
	OPT_DOS,	/* uid=,gid=,fmask=,dmask= */
	OPT_UIDGID	/* uid=,gid= only */
};

struct fsinfo {
	const char *names[4];	/* NULL-terminated candidates, best first */
	enum optstyle style;
	int rdonly;
};

static uint32_t
le32(const unsigned char *p)
{
	return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
		((uint32_t)p[3] << 24);
}

/*
 * Returns 0 on success, -1 on read error, 1 if nothing recognisable was
 * found (reason filled in).
 */
static int
probe_fs(const char *device, struct fsinfo *fi, char *reason, size_t rlen)
{
	unsigned char b[4096], x[16];
	int fd;
	ssize_t n;

	memset(fi, 0, sizeof(*fi));

	fd = open(device, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
	if (fd < 0) {
		snprintf(reason, rlen, "cannot read %s: %s", device,
			strerror(errno));
		return -1;
	}

	n = pread(fd, b, sizeof(b), 0);
	if (n < (ssize_t)sizeof(b)) {
		snprintf(reason, rlen, "short read on %s", device);
		close(fd);
		return -1;
	}

	/* encrypted containers: fail with something actionable */
	if (memcmp(b, "LUKS\xba\xbe", 6) == 0) {
		snprintf(reason, rlen,
			"%s is a LUKS volume; unlock it first", device);
		close(fd);
		return 1;
	}

	/* exFAT and NTFS carry their signature at offset 3, before FAT's */
	if (memcmp(b + 3, "EXFAT   ", 8) == 0) {
		fi->names[0] = "exfat";
		fi->style = OPT_DOS;
		close(fd);
		return 0;
	}
	if (memcmp(b + 3, "NTFS    ", 8) == 0) {
		fi->names[0] = "ntfs3";
		fi->names[1] = "ntfs";
		fi->style = OPT_DOS;
		close(fd);
		return 0;
	}
	if (b[510] == 0x55 && b[511] == 0xAA &&
	    (memcmp(b + 0x36, "FAT", 3) == 0 ||
	     memcmp(b + 0x52, "FAT32", 5) == 0)) {
		fi->names[0] = "vfat";
		fi->style = OPT_DOS;
		close(fd);
		return 0;
	}

	if (memcmp(b, "XFSB", 4) == 0) {
		fi->names[0] = "xfs";
		fi->style = OPT_NATIVE;
		close(fd);
		return 0;
	}

	/* ext2/3/4: superblock at 1024, magic 0xEF53 at sb offset 0x38 */
	if (b[1024 + 0x38] == 0x53 && b[1024 + 0x39] == 0xEF) {
		uint32_t compat = le32(b + 1024 + 0x5C);
		uint32_t incompat = le32(b + 1024 + 0x60);
		uint32_t rocompat = le32(b + 1024 + 0x64);

		if ((incompat & 0x02C0u) || (rocompat & 0x0478u)) {
			fi->names[0] = "ext4";
		} else if (compat & 0x0004u) {
			fi->names[0] = "ext3";
			fi->names[1] = "ext4";
		} else {
			fi->names[0] = "ext2";
			fi->names[1] = "ext4";
		}
		fi->style = OPT_NATIVE;
		close(fd);
		return 0;
	}

	/* f2fs: magic 0xF2F52010 at 1024 */
	if (le32(b + 1024) == 0xF2F52010u) {
		fi->names[0] = "f2fs";
		fi->style = OPT_NATIVE;
		close(fd);
		return 0;
	}

	/* btrfs: "_BHRfS_M" at 0x10040 */
	if (pread(fd, x, 8, 0x10040) == 8 && memcmp(x, "_BHRfS_M", 8) == 0) {
		fi->names[0] = "btrfs";
		fi->style = OPT_NATIVE;
		close(fd);
		return 0;
	}

	/* optical / image volumes at the ISO descriptor */
	if (pread(fd, x, 8, 0x8000) == 8) {
		if (memcmp(x + 1, "CD001", 5) == 0) {
			fi->names[0] = "iso9660";
			fi->style = OPT_UIDGID;
			fi->rdonly = 1;
			close(fd);
			return 0;
		}
		if (memcmp(x + 1, "BEA01", 5) == 0) {
			fi->names[0] = "udf";
			fi->style = OPT_UIDGID;
			fi->rdonly = 1;
			close(fd);
			return 0;
		}
	}

	/*
	 * Nothing matched: say something more useful than "unknown".
	 * Names ending in a digit take a "p" before the partition number
	 * (nvme0n1p1, mmcblk0p1), the rest do not (sda1).
	 */
	{
		size_t l = strlen(device);
		const char *sep = (l > 0 && device[l - 1] >= '0' &&
					  device[l - 1] <= '9') ? "p" : "";

		if (pread(fd, x, 8, 512) == 8 &&
		    memcmp(x, "EFI PART", 8) == 0) {
			snprintf(reason, rlen,
				"no filesystem on %s: it holds a GPT "
				"partition table (try %s%s1)",
				device, device, sep);
			close(fd);
			return 1;
		}
		if (b[510] == 0x55 && b[511] == 0xAA) {
			snprintf(reason, rlen,
				"no filesystem on %s: it holds a partition "
				"table (try %s%s1)", device, device, sep);
			close(fd);
			return 1;
		}
	}
	{
		snprintf(reason, rlen,
			"no recognised filesystem on %s", device);
	}

	close(fd);
	return 1;
}

/* ------------------------------------------------------------------ *
 * device gating: only removable / hotplug-bus block devices
 * ------------------------------------------------------------------ */

static int
sysfs_flag_is_one(const char *path)
{
	char c;
	int fd;
	ssize_t n;

	fd = open(path, O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return 0;
	n = read(fd, &c, 1);
	close(fd);
	return (n == 1 && c == '1');
}

/*
 * A device qualifies if the block device (or its parent disk) reports
 * removable, or if it sits behind a hotplug bus.  USB hard disks report
 * removable=0, SD cards likewise, so the bus path matters too.
 */
/*
 * The first line of a small sysfs file, newline stripped.  0 on success.
 */
static int
sysfs_read(const char *path, char *buf, size_t len)
{
	int fd;
	ssize_t n;

	fd = open(path, O_RDONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;
	n = read(fd, buf, len - 1);
	close(fd);
	if (n <= 0)
		return -1;
	buf[n] = '\0';
	buf[strcspn(buf, "\n")] = '\0';
	return 0;
}

/*
 * An MMC card is a hotplug SD card or, on many laptops and boards, the
 * soldered-in eMMC that holds the system -- including partitions that
 * are normally not mounted, such as the EFI system partition.  The card
 * type tells them apart: only "SD" is removable media.
 */
static int
mmc_is_sd(const char *devname)
{
	char path[PATH_MAX], type[16];

	snprintf(path, sizeof(path), "/sys/class/block/%s/device/type",
		devname);
	if (sysfs_read(path, type, sizeof(type)) != 0) {
		/* partition: the card belongs to the parent disk */
		snprintf(path, sizeof(path),
			"/sys/class/block/%s/../device/type", devname);
		if (sysfs_read(path, type, sizeof(type)) != 0)
			return 0;
	}
	return strcmp(type, "SD") == 0;
}

static int
device_is_eligible(const char *devname, dev_t rdev)
{
	char path[PATH_MAX], link[PATH_MAX], num[32], want[32];
	ssize_t n;

	snprintf(path, sizeof(path), "/sys/class/block/%s", devname);
	n = readlink(path, link, sizeof(link) - 1);
	if (n < 0)
		return 0;
	link[n] = '\0';

	/*
	 * The checks below go by name, the mount by device node: make sure
	 * both are the same device, so a node called sdb that is really
	 * something else cannot borrow sdb's eligibility.
	 */
	snprintf(path, sizeof(path), "/sys/class/block/%s/dev", devname);
	snprintf(want, sizeof(want), "%u:%u", major(rdev), minor(rdev));
	if (sysfs_read(path, num, sizeof(num)) != 0 || strcmp(num, want) != 0)
		return 0;

	if (strstr(link, "/usb") != NULL ||
	    strstr(link, "/firewire") != NULL)
		return 1;
	if (strstr(link, "/mmc_host/") != NULL)
		return mmc_is_sd(devname);

	snprintf(path, sizeof(path), "/sys/class/block/%s/removable", devname);
	if (sysfs_flag_is_one(path))
		return 1;

	/* partition: the parent directory is the whole disk */
	snprintf(path, sizeof(path), "/sys/class/block/%s/../removable",
		devname);
	if (sysfs_flag_is_one(path))
		return 1;

	return 0;
}

/* ------------------------------------------------------------------ *
 * caller identity
 * ------------------------------------------------------------------ */

static void
resolve_caller(uid_t *uid, gid_t *gid)
{
	const char *e;
	struct passwd *pw;

	*uid = getuid();
	*gid = getgid();

	/* Invoked by real root (e.g. under doas): honour the original user. */
	if (*uid != 0)
		return;

	e = getenv("DOAS_USER");
	if (e == NULL || *e == '\0')
		e = getenv("SUDO_USER");
	if (e != NULL && *e != '\0') {
		pw = getpwnam(e);
		if (pw != NULL) {
			*uid = pw->pw_uid;
			*gid = pw->pw_gid;
		}
	}
}

/*
 * Only root and members of plugdev may use stik.  The real ids are the
 * caller's; the supplementary groups are not changed by setuid.  A
 * missing group means nobody but root.
 */
static int
caller_allowed(void)
{
	struct group *gr;
	gid_t *groups;
	int i, n;

	if (getuid() == 0)
		return 1;

	gr = getgrnam(STIK_GROUP);
	if (gr == NULL)
		return 0;
	if (getgid() == gr->gr_gid)
		return 1;

	n = getgroups(0, NULL);
	if (n <= 0)
		return 0;
	groups = calloc((size_t)n, sizeof(*groups));
	if (groups == NULL)
		return 0;
	n = getgroups(n, groups);
	for (i = 0; i < n; i++) {
		if (groups[i] == gr->gr_gid) {
			free(groups);
			return 1;
		}
	}
	free(groups);
	return 0;
}

/* ------------------------------------------------------------------ *
 * idmapped mounts
 * ------------------------------------------------------------------ */

static int
write_file(const char *path, const char *data)
{
	int fd;
	ssize_t n;
	size_t len = strlen(data);

	fd = open(path, O_WRONLY | O_CLOEXEC);
	if (fd < 0)
		return -1;
	n = write(fd, data, len);
	close(fd);
	return (n == (ssize_t)len) ? 0 : -1;
}

/*
 * Create a user namespace whose uid/gid 0 maps to the caller, and return
 * a file descriptor to it.  Used purely as an idmap for the mount; the
 * helper process exits immediately afterwards.
 */
static int
make_idmap_ns(uid_t uid, gid_t gid)
{
	int ready[2], hold[2], fd = -1;
	char path[64], map[64];
	char c;
	pid_t pid;

	if (pipe(ready) != 0)
		return -1;
	if (pipe(hold) != 0) {
		close(ready[0]);
		close(ready[1]);
		return -1;
	}

	pid = fork();
	if (pid < 0) {
		close(ready[0]);
		close(ready[1]);
		close(hold[0]);
		close(hold[1]);
		return -1;
	}
	if (pid == 0) {
		close(ready[0]);
		close(hold[1]);
		if (unshare(CLONE_NEWUSER) != 0)
			_exit(1);
		if (write(ready[1], "x", 1) != 1)
			_exit(1);
		/* stay alive until the parent has grabbed the ns fd */
		if (read(hold[0], &c, 1) < 0)
			_exit(1);
		_exit(0);
	}

	close(ready[1]);
	close(hold[0]);

	if (read(ready[0], &c, 1) != 1)
		goto out;

	snprintf(path, sizeof(path), "/proc/%d/uid_map", (int)pid);
	snprintf(map, sizeof(map), "0 %u 1\n", (unsigned)uid);
	if (write_file(path, map) != 0)
		goto out;

	snprintf(path, sizeof(path), "/proc/%d/gid_map", (int)pid);
	snprintf(map, sizeof(map), "0 %u 1\n", (unsigned)gid);
	if (write_file(path, map) != 0)
		goto out;

	snprintf(path, sizeof(path), "/proc/%d/ns/user", (int)pid);
	fd = open(path, O_RDONLY | O_CLOEXEC);

out:
	close(ready[0]);
	close(hold[1]);
	(void)waitpid(pid, NULL, 0);
	return fd;
}

/* ------------------------------------------------------------------ *
 * mounting
 * ------------------------------------------------------------------ */

struct mopts {
	uid_t uid;
	gid_t gid;
	enum optstyle style;
	int rdonly;
	int no_idmap;
};

/*
 * New mount API path.  Returns 0 on success, -1 on failure (errno set),
 * or -2 if the API itself is unavailable and the caller should fall back.
 */
static int
mount_new_api(const char *device, const char *fstype, const char *mountpoint,
	const struct mopts *mo, int *idmapped)
{
	char buf[32];
	struct stik_mount_attr attr;
	unsigned mattr = MOUNT_ATTR_NOSUID | MOUNT_ATTR_NODEV;
	int fs, mnt, ns;
	int saved;

	*idmapped = 0;

	fs = sys_fsopen(fstype);
	if (fs < 0) {
		if (errno == ENOSYS)
			return -2;
		return -1;
	}

	if (sys_fsconfig(fs, FSCONFIG_SET_STRING, "source", device) != 0)
		goto fail_fs;

	if (mo->style == OPT_DOS || mo->style == OPT_UIDGID) {
		snprintf(buf, sizeof(buf), "%u", (unsigned)mo->uid);
		if (sys_fsconfig(fs, FSCONFIG_SET_STRING, "uid", buf) != 0)
			goto fail_fs;
		snprintf(buf, sizeof(buf), "%u", (unsigned)mo->gid);
		if (sys_fsconfig(fs, FSCONFIG_SET_STRING, "gid", buf) != 0)
			goto fail_fs;
	}
	if (mo->style == OPT_DOS) {
		if (sys_fsconfig(fs, FSCONFIG_SET_STRING, "fmask", "133") != 0)
			goto fail_fs;
		if (sys_fsconfig(fs, FSCONFIG_SET_STRING, "dmask", "022") != 0)
			goto fail_fs;
	}

	if (sys_fsconfig(fs, FSCONFIG_CMD_CREATE, NULL, NULL) != 0)
		goto fail_fs;

	if (mo->rdonly)
		mattr |= MOUNT_ATTR_RDONLY;

	mnt = sys_fsmount(fs, mattr);
	saved = errno;
	close(fs);
	if (mnt < 0) {
		errno = saved;
		return -1;
	}

	/*
	 * Ownership on disk only matters for filesystems that store it.
	 * Map on-disk 0 to the caller so root-owned media is usable
	 * without touching a single inode.
	 */
	if (mo->style == OPT_NATIVE && !mo->no_idmap && mo->uid != 0) {
		ns = make_idmap_ns(mo->uid, mo->gid);
		if (ns < 0) {
			warnx_("could not create id mapping: %s",
				strerror(errno));
		} else {
			memset(&attr, 0, sizeof(attr));
			attr.attr_set = MOUNT_ATTR_IDMAP;
			attr.userns_fd = (uint64_t)ns;
			if (sys_mount_setattr(mnt, "", AT_EMPTY_PATH,
				    &attr) == 0)
				*idmapped = 1;
			else
				warnx_("id mapping unsupported here (%s); "
				       "on-disk ownership applies",
					strerror(errno));
			close(ns);
		}
	}

	if (sys_move_mount(mnt, "", AT_FDCWD, mountpoint,
		    MOVE_MOUNT_F_EMPTY_PATH) != 0) {
		saved = errno;
		close(mnt);
		errno = saved;
		return -1;
	}

	close(mnt);
	return 0;

fail_fs:
	saved = errno;
	close(fs);
	errno = saved;
	return -1;
}

/* Classic mount(2), for kernels without the new mount API. */
static int
mount_legacy(const char *device, const char *fstype, const char *mountpoint,
	const struct mopts *mo)
{
	char opts[256];
	unsigned long flags = MS_NODEV | MS_NOSUID;

	opts[0] = '\0';
	if (mo->style == OPT_DOS)
		snprintf(opts, sizeof(opts),
			"uid=%u,gid=%u,fmask=133,dmask=022",
			(unsigned)mo->uid, (unsigned)mo->gid);
	else if (mo->style == OPT_UIDGID)
		snprintf(opts, sizeof(opts), "uid=%u,gid=%u",
			(unsigned)mo->uid, (unsigned)mo->gid);

	if (mo->rdonly)
		flags |= MS_RDONLY;

	return mount(device, mountpoint, fstype, flags,
		opts[0] ? opts : NULL);
}

/* ------------------------------------------------------------------ *
 * /proc/mounts lookup
 * ------------------------------------------------------------------ */

static char *
find_mountpoint(const char *device)
{
	FILE *fp;
	struct mntent *ent;
	char *mountpoint = NULL;

	fp = setmntent("/proc/mounts", "r");
	if (fp == NULL)
		return NULL;

	while ((ent = getmntent(fp)) != NULL) {
		if (strcmp(ent->mnt_fsname, device) == 0) {
			mountpoint = strdup(ent->mnt_dir);
			break;
		}
	}

	endmntent(fp);
	return mountpoint;
}

/* ------------------------------------------------------------------ *
 * argument validation
 * ------------------------------------------------------------------ */

/*
 * Accept exactly /dev/<name> where name is a single path component of
 * safe characters.  This is what keeps "/dev/../something" and friends
 * out of the mountpoint construction below.
 */
static const char *
validate_device(const char *device)
{
	const char *name;
	size_t i;

	if (strncmp(device, "/dev/", 5) != 0)
		return NULL;

	name = device + 5;
	if (*name == '\0' || strlen(name) > 64)
		return NULL;

	for (i = 0; name[i] != '\0'; i++) {
		if (!((name[i] >= 'a' && name[i] <= 'z') ||
		      (name[i] >= 'A' && name[i] <= 'Z') ||
		      (name[i] >= '0' && name[i] <= '9') ||
		      name[i] == '-' || name[i] == '_'))
			return NULL;
	}

	return name;
}

static int
prepare_mountpoint(const char *devname, char *out, size_t outlen)
{
	struct stat st;

	if (mkdir(MEDIA_DIR, 0755) != 0 && errno != EEXIST) {
		warnx_("cannot create %s: %s", MEDIA_DIR, strerror(errno));
		return -1;
	}

	snprintf(out, outlen, MEDIA_DIR "/%s", devname);

	if (mkdir(out, 0755) != 0 && errno != EEXIST) {
		warnx_("cannot create %s: %s", out, strerror(errno));
		return -1;
	}

	/* must be a real directory, not a symlink someone left behind */
	if (lstat(out, &st) != 0 || !S_ISDIR(st.st_mode)) {
		warnx_("%s is not a directory", out);
		return -1;
	}

	return 0;
}

/* ------------------------------------------------------------------ */

static int
cmd_mount(const char *device, const char *devname, int rdonly, int no_idmap)
{
	struct fsinfo fi;
	struct mopts mo;
	char mountpoint[PATH_MAX];
	char reason[256];
	char *existing;
	int i, rc, idmapped = 0, saved_errno = 0;

	existing = find_mountpoint(device);
	if (existing != NULL) {
		warnx_("%s is already mounted at %s", device, existing);
		free(existing);
		return 10;
	}

	rc = probe_fs(device, &fi, reason, sizeof(reason));
	if (rc != 0) {
		warnx_("%s", reason);
		return 4;
	}

	memset(&mo, 0, sizeof(mo));
	resolve_caller(&mo.uid, &mo.gid);
	mo.style = fi.style;
	mo.rdonly = rdonly || fi.rdonly;
	mo.no_idmap = no_idmap;

	if (prepare_mountpoint(devname, mountpoint, sizeof(mountpoint)) != 0)
		return 11;

	info("Mounting %s (%s) to %s", device, fi.names[0], mountpoint);

	rc = -1;
	for (i = 0; i < 4 && fi.names[i] != NULL; i++) {
		rc = mount_new_api(device, fi.names[i], mountpoint, &mo,
			&idmapped);
		if (rc == -2) {
			rc = mount_legacy(device, fi.names[i], mountpoint, &mo);
			if (rc != 0)
				rc = -1;
			else if (mo.style == OPT_NATIVE && !no_idmap &&
				 mo.uid != 0)
				warnx_("kernel too old for id mapping; "
				       "on-disk ownership applies");
		}
		if (rc == 0)
			break;
		saved_errno = errno;
	}

	if (rc != 0) {
		errno = saved_errno;
		warnx_("mount failed: %s", strerror(errno));
		rmdir(mountpoint);
		return 6;
	}

	if (mo.style == OPT_NATIVE && !idmapped && !no_idmap && mo.uid != 0)
		warnx_("files owned by other users remain unwritable; "
		       "run as root to change ownership");

	info("Mounted at %s%s", mountpoint, mo.rdonly ? " (read-only)" : "");
	return 0;
}

static int
cmd_umount(const char *device, const char *devname, int gone)
{
	char expected[PATH_MAX];
	char *mountpoint;

	mountpoint = find_mountpoint(device);
	if (mountpoint == NULL) {
		warnx_("%s is not mounted", device);
		return 7;
	}

	snprintf(expected, sizeof(expected), MEDIA_DIR "/%s", devname);

	/*
	 * Only ever unmount what stik would have mounted.  Without this an
	 * unprivileged caller could unmount /boot or / by naming the right
	 * device node.
	 */
	if (strcmp(mountpoint, expected) != 0) {
		warnx_("%s is mounted at %s, not under " MEDIA_DIR
		       "; refusing", device, mountpoint);
		free(mountpoint);
		return 12;
	}

	info("Unmounting %s from %s...", device, mountpoint);

	/*
	 * A stick pulled without unmounting leaves its mount behind with
	 * no device under it; detach it rather than fail on I/O.
	 */
	if (umount2(mountpoint, gone ? MNT_DETACH : 0) != 0) {
		warnx_("unmount failed: %s", strerror(errno));
		free(mountpoint);
		return 8;
	}

	if (rmdir(mountpoint) != 0 && errno != ENOTEMPTY && errno != ENOENT)
		warnx_("could not remove %s: %s", mountpoint, strerror(errno));

	free(mountpoint);
	info("Unmounted.");
	return 0;
}

static void
usage(void)
{
	fprintf(stderr,
		"usage: %s mount [-nr] /dev/sdX\n"
		"       %s umount /dev/sdX\n"
		"       %s -h | -V\n"
		"\n"
		"  -n  no id mapping; use ownership as stored on disk\n"
		"  -r  mount read-only\n",
		prog, prog, prog);
}

int
main(int argc, char *argv[])
{
	const char *action = NULL, *device = NULL, *devname;
	struct stat st;
	int rdonly = 0, no_idmap = 0, is_umount;
	int i;

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-' && argv[i][1] != '\0') {
			/* single-letter flags, alone or together: -r -n -rn */
			const char *f;

			for (f = argv[i] + 1; *f != '\0'; f++) {
				switch (*f) {
				case 'r':
					rdonly = 1;
					break;
				case 'n':
					no_idmap = 1;
					break;
				case 'h':
					usage();
					return 0;
				case 'V':
					printf("stik %s\n", STIK_VERSION);
					return 0;
				default:
					warnx_("unknown option '-%c'", *f);
					return 1;
				}
			}
		} else if (action == NULL) {
			action = argv[i];
		} else if (device == NULL) {
			device = argv[i];
		} else {
			usage();
			return 1;
		}
	}

	if (action == NULL || device == NULL) {
		usage();
		return 1;
	}

	if (!caller_allowed()) {
		warnx_("permission denied: you must be in the group "
		       STIK_GROUP);
		return 14;
	}

	devname = validate_device(device);
	if (devname == NULL) {
		warnx_("device must be /dev/<name>");
		return 2;
	}

	is_umount = strcmp(action, "umount") == 0 ||
		    strcmp(action, "unmount") == 0;

	if (stat(device, &st) != 0) {
		/*
		 * The stick was pulled while mounted: its node is gone.
		 * umount may still detach the leftover mount, which it
		 * only ever does at /media/<name>.
		 */
		if (is_umount && errno == ENOENT)
			return cmd_umount(device, devname, 1);
		warnx_("%s not found or not a block device", device);
		return 3;
	}
	if (!S_ISBLK(st.st_mode)) {
		warnx_("%s not found or not a block device", device);
		return 3;
	}

	if (!device_is_eligible(devname, st.st_rdev)) {
		warnx_("%s is not a removable device", device);
		return 13;
	}

	if (strcmp(action, "mount") == 0)
		return cmd_mount(device, devname, rdonly, no_idmap);

	if (is_umount)
		return cmd_umount(device, devname, 0);

	warnx_("invalid action '%s'", action);
	usage();
	return 9;
}