nlplug-findfs.c 33.7 KB
Newer Older
Natanael Copa's avatar
Natanael Copa committed
1
2
3
4
5
/*
 * Copy me if you can.
 * by 20h
 *
 * Copyright (c) 2015 Natanael Copa <ncopa@alpinelinux.org>
6
 * Copyright (c) 2016 Timo Teräs <timo.teras@iki.fi>
Natanael Copa's avatar
Natanael Copa committed
7
8
 */

9
10
11
12
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

13
#include <dirent.h>
Natanael Copa's avatar
Natanael Copa committed
14
15
#include <err.h>
#include <errno.h>
16
17
#include <fnmatch.h>
#include <getopt.h>
18
#include <limits.h>
Natanael Copa's avatar
Natanael Copa committed
19
#include <poll.h>
20
#include <pthread.h>
21
#include <stdint.h>
Natanael Copa's avatar
Natanael Copa committed
22
23
24
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
25
#include <termios.h>
Natanael Copa's avatar
Natanael Copa committed
26
27
#include <unistd.h>

28
#include <sys/eventfd.h>
Natanael Copa's avatar
Natanael Copa committed
29
#include <sys/mount.h>
30
#include <sys/signalfd.h>
Natanael Copa's avatar
Natanael Copa committed
31
#include <sys/socket.h>
32
#include <sys/stat.h>
33
#include <sys/sysmacros.h>
Natanael Copa's avatar
Natanael Copa committed
34
35
36
37
38
39
40
41
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>

#include <linux/netlink.h>

#include <libkmod.h>
#include <blkid.h>
42
#include <libcryptsetup.h>
Natanael Copa's avatar
Natanael Copa committed
43

44
#define MAX_EVENT_TIMEOUT	5000
45
#define DEFAULT_EVENT_TIMEOUT	250
46
47
/* usb mass storage needs 1 sec to settle */
#define USB_STORAGE_TIMEOUT	1000
Natanael Copa's avatar
Natanael Copa committed
48

49
50
51
52
#define FOUND_DEVICE	0x1
#define FOUND_BOOTREPO	0x2
#define FOUND_APKOVL	0x4

53
54
#define LVM_PATH	"/sbin/lvm"
#define MDADM_PATH	"/sbin/mdadm"
Mark Riedesel's avatar
Mark Riedesel committed
55
#define ZPOOL_PATH	"/usr/sbin/zpool"
56

Natanael Copa's avatar
Natanael Copa committed
57
static int dodebug;
58
static char *default_envp[2];
Natanael Copa's avatar
Natanael Copa committed
59
char *argv0;
Mark Riedesel's avatar
Mark Riedesel committed
60
static int use_mdadm, use_lvm, use_zpool;
Natanael Copa's avatar
Natanael Copa committed
61
62
63
64
65
66
67
68
69

#if defined(DEBUG)
#include <stdarg.h>
static void dbg(const char *fmt, ...)
{
	va_list fmtargs;
	if (!dodebug)
		return;

70
	flockfile(stderr);
Natanael Copa's avatar
Natanael Copa committed
71
72
73
74
75
	fprintf(stderr, "%s: ", argv0);
	va_start(fmtargs, fmt);
	vfprintf(stderr, fmt, fmtargs);
	va_end(fmtargs);
	fprintf(stderr, "\n");
76
	funlockfile(stderr);
Natanael Copa's avatar
Natanael Copa committed
77
78
79
80
81
}
#else
#define dbg(...)
#endif

82
83
#define envcmp(env, key) (strncmp(env, key "=", strlen(key "=")) == 0)

84
85
86
87
88
89
90
91
92
#ifndef container_of
#define container_of(ptr, type, member) ({                      \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
        (type *)( (char *)__mptr - offsetof(type,member) );})
#endif

struct list_head {
	struct list_head *next, *prev;
};
93
#define LIST_INITIALIZER(l) (struct list_head){ .next = &l, .prev = &l }
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

static inline void list_init(struct list_head *list)
{
	list->next = list;
	list->prev = list;
}

static inline void __list_add(struct list_head *new, struct list_head *prev,
			      struct list_head *next)
{
	next->prev = new;
	new->next = next;
	new->prev = prev;
	prev->next = new;
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}

static inline void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	prev->next = next;
}

static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = NULL;
	entry->prev = NULL;
}

static inline int list_hashed(const struct list_head *n)
{
	return n->next != n && n->next != NULL;
}

static inline int list_empty(const struct list_head *n)
{
	return !list_hashed(n);
}

#define list_next(ptr, type, member) \
	(list_hashed(ptr) ? container_of((ptr)->next,type,member) : NULL)

#define list_entry(ptr, type, member) container_of(ptr,type,member)

#define list_for_each_entry(pos, head, member)				\
	for (pos = list_entry((head)->next, typeof(*pos), member);	\
	     &pos->member != (head); 					\
	     pos = list_entry(pos->member.next, typeof(*pos), member))

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
static char **clone_array(char *const *const a)
{
	size_t i, s;
	char **c, *p;

	if (!a) return 0;

	s = sizeof(char*);
	for (i = 0; a[i]; i++)
		s += sizeof(char*) + strlen(a[i]) + 1;
	c = malloc(s);
	p = (char*)(c + i + 1);
	for (i = 0; a[i]; i++) {
		c[i] = p;
		p += sprintf(p, "%s", a[i]) + 1;
	}
	c[i] = 0;
	return c;
}

struct spawn_task {
174
	struct list_head node;
175
	void (*done)(void *ctx, int status);
176
	pid_t pid;
177
	void *ctx;
178
179
	char **argv, **envp;
};
180
181

#define SPAWNMGR_PID_HASH_SIZE 32
182
183
184
struct spawn_manager {
	int num_running;
	int max_running;
185
186
	struct list_head queue;
	struct list_head running[SPAWNMGR_PID_HASH_SIZE];
187
188
189
190
};

static struct spawn_manager spawnmgr;

191
192
193
194
195
196
197
198
199
static void dbgT(struct spawn_task *task, const char *fmt, ...)
{
#if defined(DEBUG)
	va_list fmtargs;
	int i;

	if (!dodebug)
		return;

200
	flockfile(stderr);
201
202
203
204
205
206
207
208
209
210
211
212
	fprintf(stderr, "%s: [%d] ", argv0, task->pid);
	va_start(fmtargs, fmt);
	vfprintf(stderr, fmt, fmtargs);
	va_end(fmtargs);
	for (i = 0; task->argv[i]; i++)
		fprintf(stderr, " %s", task->argv[i]);
	if (task->envp) {
		fprintf(stderr, ":");
		for (i = 1; task->envp[i]; i++)
			fprintf(stderr, " %s", task->envp[i]);
	}
	fprintf(stderr, "\n");
213
	funlockfile(stderr);
214
215
216
#endif
}

217
218
219
220
221
222
223
224
static void spawn_init(struct spawn_manager *mgr)
{
	int i;

	mgr->max_running = sysconf(_SC_NPROCESSORS_ONLN);
	list_init(&mgr->queue);
	for (i = 0; i < SPAWNMGR_PID_HASH_SIZE; i++)
		list_init(&mgr->running[i]);
225
226

	dbg("max_running=%d", mgr->max_running);
227
228
}

229
230
231
232
233
234
235
236
237
static void spawn_task_done(struct spawn_task *task, int status)
{
	if (task->done) task->done(task->ctx, status);
	list_del(&task->node);
	free(task->argv);
	free(task->envp);
	free(task);
}

238
static void spawn_execute(struct spawn_manager *mgr, struct spawn_task *task)
239
240
241
242
{
	pid_t pid;

	if (!(pid = fork())) {
243
244
		execve(task->argv[0], task->argv, task->envp ? task->envp : default_envp);
		err(127, task->argv[0]);
245
246
	}
	if (pid < 0)
247
		err(1, "fork");
248

249
250
	task->pid = pid;
	list_add_tail(&task->node, &mgr->running[pid % SPAWNMGR_PID_HASH_SIZE]);
251
	mgr->num_running++;
252

253
	dbgT(task, "spawned (%d running):", mgr->num_running);
254
255
}

256
static void spawn_command_cb(struct spawn_manager *mgr, char **argv, char **envp, void (*done)(void *, int), void *ctx)
257
258
259
260
261
262
{
	struct spawn_task *task;

	task = malloc(sizeof *task);
	if (!task) return;
	*task = (struct spawn_task) {
263
264
		.done = done,
		.node = LIST_INITIALIZER(task->node),
265
266
		.argv = clone_array(argv),
		.envp = clone_array(envp),
267
		.ctx  = ctx,
268
269
270
	};

	if (mgr->num_running < mgr->max_running)
271
		spawn_execute(mgr, task);
272
	else
273
		list_add_tail(&task->node, &mgr->queue);
274
275
}

276
277
278
279
280
281
static void spawn_command(struct spawn_manager *mgr, char **argv, char **envp)
{
	spawn_command_cb(mgr, argv, envp, 0, 0);
}

static void spawn_reap(struct spawn_manager *mgr, pid_t pid, int status)
282
{
283
284
285
286
287
288
289
290
291
292
	struct spawn_task *task;

	list_for_each_entry(task, &mgr->running[pid % SPAWNMGR_PID_HASH_SIZE], node) {
		if (task->pid == pid)
			goto found;
	}
	dbg("pid %d not found", pid);
	return;

found:
293
	mgr->num_running--;
294
295
	dbgT(task, "reaped (%d running):", mgr->num_running);
	spawn_task_done(task, status);
296

297
298
299
300
	if (!list_empty(&mgr->queue) && mgr->num_running < mgr->max_running) {
		struct spawn_task *task = list_next(&mgr->queue, struct spawn_task, node);
		list_del(&task->node);
		spawn_execute(mgr, task);
301
302
303
304
305
	}
}

static int spawn_active(struct spawn_manager *mgr)
{
306
	return mgr->num_running || !list_empty(&mgr->queue);
307
308
}

309
struct cryptdev {
310
311
	char *device;
	char *name;
lemmarathon's avatar
lemmarathon committed
312
	char *key;
313
314
315
	char devnode[256];
};

316
317
318
319
320
321
struct cryptconf {
	struct cryptdev data;
	struct cryptdev header;
	size_t payload_offset;
	pthread_t tid;
	pthread_mutex_t mutex;
Sören Tempel's avatar
Sören Tempel committed
322
	uint32_t flags;
323
324
};

Natanael Copa's avatar
Natanael Copa committed
325
326
327
struct ueventconf {
	char **program_argv;
	char *search_device;
328
	blkid_cache blkid_cache;
329
	struct cryptconf crypt;
Natanael Copa's avatar
Natanael Copa committed
330
331
332
	char *subsystem_filter;
	int modalias_count;
	int fork_count;
333
	char *bootrepos;
334
	char *apkovls;
335
	int timeout;
336
	int usb_storage_timeout;
337
	int uevent_timeout;
338
	int efd;
339
	int found;
340
341
342
343
344
345
346
347

	int running_threads;

	pthread_mutex_t trigger_mutex;
	pthread_cond_t trigger_cond;
	struct list_head trigger_list;

	int cryptsetup_running;
Natanael Copa's avatar
Natanael Copa committed
348
349
};

350
351
352
353
354
355
356
357
358
struct uevent {
	struct ueventconf *conf;
	int ref;
	size_t bufsize;
	char *message;
	char *subsystem;
	char *action;
	char *modalias;
	char *devname;
359
	char *devpath;
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
	char *major;
	char *minor;
	char devnode[256];
	char *envp[64];
	char buf[];
};

static struct uevent *uevent_ref(struct uevent *ev)
{
	ev->ref++;
	return ev;
}

static void uevent_unref(struct uevent *ev)
{
	ev->ref--;
	if (ev->ref != 0) return;
	free(ev);
}
Natanael Copa's avatar
Natanael Copa committed
379
380
381

static void sighandler(int sig)
{
382
	switch (sig) {
Natanael Copa's avatar
Natanael Copa committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
	case SIGHUP:
	case SIGINT:
	case SIGQUIT:
	case SIGABRT:
	case SIGTERM:
		exit(0);
	default:
		break;
	}
}

static void initsignals(void)
{
	signal(SIGHUP, sighandler);
	signal(SIGINT, sighandler);
	signal(SIGQUIT, sighandler);
	signal(SIGABRT, sighandler);
	signal(SIGTERM, sighandler);
401
	signal(SIGCHLD, sighandler);
Natanael Copa's avatar
Natanael Copa committed
402
403
404
405
406
407
408
409
410
411
412
413
414
	signal(SIGPIPE, SIG_IGN);
}

static int init_netlink_socket(void)
{
	struct sockaddr_nl nls;
	int fd, slen;

	memset(&nls, 0, sizeof(nls));
	nls.nl_family = AF_NETLINK;
	nls.nl_pid = getpid();
	nls.nl_groups = -1;

415
416
	fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC,
		    NETLINK_KOBJECT_UEVENT);
Natanael Copa's avatar
Natanael Copa committed
417
418
419
420
421
	if (fd < 0)
		err(1, "socket");

	/* kernel will not create events bigger than 16kb, but we need
	   buffer up all events during coldplug */
422
	slen = 512*1024;
Natanael Copa's avatar
Natanael Copa committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &slen,
				sizeof(slen)) < 0) {
		err(1, "setsockopt");
	}
	slen = 1;
	if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &slen,
				sizeof(slen)) < 0) {
		err(1, "setsockopt");
	}

	if (bind(fd, (void *)&nls, sizeof(nls)))
		err(1, "bind");

	return fd;
}

439
static int load_kmod(const char *modalias, char *driver, size_t len)
Natanael Copa's avatar
Natanael Copa committed
440
441
442
443
444
445
{
	static struct kmod_ctx *ctx = NULL;
	struct kmod_list *list = NULL;
	struct kmod_list *node;
	int r, count=0;

446
447
	if (driver) driver[0] = 0;

Natanael Copa's avatar
Natanael Copa committed
448
449
450
451
452
453
454
455
456
457
458
	if (ctx == NULL) {
		dbg("initializing kmod");
		ctx = kmod_new(NULL, NULL);
		if (ctx == NULL)
			return -1;
		kmod_set_log_fn(ctx, NULL, NULL);
		r = kmod_load_resources(ctx);
	}

	r = kmod_module_new_from_lookup(ctx, modalias, &list);
	if (r < 0) {
459
		dbg("alias '%s' lookup failure: %d", modalias, r);
Natanael Copa's avatar
Natanael Copa committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
		return r;
	}

	kmod_list_foreach(node, list) {
		struct kmod_module *mod = kmod_module_get_module(node);
		const char *fmt;
		r = kmod_module_probe_insert_module(mod,
						    KMOD_PROBE_APPLY_BLACKLIST,
						    NULL, NULL, NULL, NULL);
		if (r == 0) {
			fmt = "module '%s' inserted";
			count++;
		} else if (r == KMOD_PROBE_APPLY_BLACKLIST) {
			fmt = "module '%s' is blacklisted";
		} else {
			fmt = "module '%s' failed";
		}
		dbg(fmt, kmod_module_get_name(mod));
478
		if (driver) strlcpy(driver, kmod_module_get_name(mod), len);
Natanael Copa's avatar
Natanael Copa committed
479
480
481
482
483
484
		kmod_module_unref(mod);
	}
	kmod_module_unref_list(list);
	return count;
}

485
static void start_mdadm(char *devnode)
Natanael Copa's avatar
Natanael Copa committed
486
487
{
	char *mdadm_argv[] = {
488
		MDADM_PATH,
Natanael Copa's avatar
Natanael Copa committed
489
		"--incremental",
490
		"--run",
Natanael Copa's avatar
Natanael Copa committed
491
492
493
494
		"--quiet",
		devnode,
		NULL
	};
495
496
	if (use_mdadm)
		spawn_command(&spawnmgr, mdadm_argv, 0);
Natanael Copa's avatar
Natanael Copa committed
497
498
}

499
static void start_lvm2(char *devnode)
Natanael Copa's avatar
Natanael Copa committed
500
501
{
	char *lvm2_argv[] = {
502
		LVM_PATH, "vgchange",
503
		"--activate" , "ay", "--noudevsync", "--sysinit", "-q", "-q",
Natanael Copa's avatar
Natanael Copa committed
504
505
		NULL
	};
506
507
	if (use_lvm)
		spawn_command(&spawnmgr, lvm2_argv, 0);
Natanael Copa's avatar
Natanael Copa committed
508
509
}

Mark Riedesel's avatar
Mark Riedesel committed
510
511
static void start_zpool(char *uuid) {
	char *zpool_argv[] = {
512
		ZPOOL_PATH, "import", "-N", uuid,
Mark Riedesel's avatar
Mark Riedesel committed
513
514
515
516
517
518
		NULL
	};
	if (use_zpool && uuid)
		spawn_command(&spawnmgr, zpool_argv, 0);
}

519
static int read_pass(char *pass, size_t pass_size)
Natanael Copa's avatar
Natanael Copa committed
520
{
521
522
523
524
525
526
527
528
	struct termios old_flags, new_flags;
	int r;

	tcgetattr(STDIN_FILENO, &old_flags);
	new_flags = old_flags;
	new_flags.c_lflag &= ~ECHO;
	new_flags.c_lflag |= ECHONL;

529
530
531
532
533
534
535
536
537
	if (isatty(STDIN_FILENO)) {
		r = tcsetattr(STDIN_FILENO, TCSANOW, &new_flags);
		if (r < 0) {
			warn("tcsetattr");
			return r;
		}
	}// else {
	//	fprintf(stderr, "The program isn't executed in a TTY, the echo-disabling has been skipped.\n");
	//}
538
539
540
541
542
543
544

	if (fgets(pass, pass_size, stdin) == NULL) {
		warn("fgets");
		return -1;
	}
	pass[strlen(pass) - 1] = '\0';

545
546
547
548
549
550
551
	if (isatty(STDIN_FILENO)) {
		if (tcsetattr(STDIN_FILENO, TCSANOW, &old_flags) < 0) {
			warn("tcsetattr");
		}
	}// else {
	//	fprintf(stderr, "The program isn't executed in a TTY, the echo-reenabling has been skipped.\n");
	//}
552
553
554
555

	return 0;
}

556
557
558
559
560
561
static void notify_main(struct ueventconf *conf)
{
	uint64_t one = 1;
	write(conf->efd, &one, sizeof one);
}

562
563
564
static void *cryptsetup_thread(void *data)
{
	struct ueventconf *c = (struct ueventconf *)data;
565
	const char *data_devnode, *header_devnode;
566
	struct crypt_params_luks1 param_struct;
567
	struct crypt_params_luks1 *params = NULL;
568
569
570
	struct crypt_device *cd;
	int r, passwd_tries = 5;

571
	data_devnode = header_devnode = c->crypt.data.devnode;
572

573
574
575
	if(c->crypt.header.devnode[0] != '\0') {
		params = &param_struct;
		params->hash = NULL; /* No way of finding this */
576
577
578
		params->data_alignment = c->crypt.payload_offset; /* Memset did set that to 0, so default is 0 */
		params->data_device = c->crypt.data.devnode;
		header_devnode = c->crypt.header.devnode;
579
580
581
	}

	r = crypt_init(&cd, header_devnode);
582
	if (r < 0) {
583
		warnx("crypt_init(%s)", header_devnode);
584
585
586
		goto notify_out;
	}

587
	r = crypt_load(cd, CRYPT_LUKS, params);
588
	if (r < 0) {
589
		warnx("crypt_load(%s)", data_devnode);
590
591
592
		goto free_out;
	}

593
594
595
596
597
598
	r = crypt_set_data_device(cd, data_devnode);
	if (r < 0) {
		warnx("crypt_set_data_device(%s)", data_devnode);
		goto free_out;
	}

lemmarathon's avatar
lemmarathon committed
599
600
601
602
603
604
605
606
607
608
609
610
	struct stat st;
	if (!stat(c->crypt.data.key, &st)) {
		pthread_mutex_lock(&c->crypt.mutex);
		r = crypt_activate_by_keyfile(cd, c->crypt.data.name,
					      CRYPT_ANY_SLOT,
					      c->crypt.data.key, st.st_size,
					      c->crypt.flags);
		pthread_mutex_unlock(&c->crypt.mutex);
		if (r >= 0)
			goto free_out;
	}

611
612
613
	while (passwd_tries > 0) {
		char pass[1024];

614
		printf("Enter passphrase for %s: ", c->crypt.data.devnode);
615
616
617
618
619
620
		fflush(stdout);

		if (read_pass(pass, sizeof(pass)) < 0)
			goto free_out;
		passwd_tries--;

621
622
		pthread_mutex_lock(&c->crypt.mutex);
		r = crypt_activate_by_passphrase(cd, c->crypt.data.name,
623
						 CRYPT_ANY_SLOT,
Sören Tempel's avatar
Sören Tempel committed
624
625
						 pass, strlen(pass),
						 c->crypt.flags);
626
		pthread_mutex_unlock(&c->crypt.mutex);
627
		memset(pass, 0, sizeof(pass)); /* wipe pass after use */
628

629
		if (r >= 0)
7heo .tk's avatar
7heo .tk committed
630
			goto free_out;
631
632
		printf("No key available with this passphrase.\n");
	}
633
	printf("Mounting %s failed, amount of tries exhausted.\n", c->crypt.data.devnode);
634
635
636
637

free_out:
	crypt_free(cd);
notify_out:
638
639
	c->cryptsetup_running = 0;
	notify_main(c);
640
641
642
	return NULL;
}

643
644
645
646
647
648
649
650
651
652
653
654
static void start_thread(struct ueventconf *conf, void *(*thread_main)(void *))
{
	pthread_t tid;
	pthread_attr_t attr;

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (pthread_create(&tid, &attr, thread_main, conf) != 0)
		err(1, "failed to create thread");
	pthread_attr_destroy(&attr);
}

655
656
static void start_cryptsetup(struct ueventconf *conf)
{
657
	if(conf->crypt.header.devnode[0] != '\0') {
658
		dbg("starting cryptsetup %s -> %s (header: %s)",
659
660
		    conf->crypt.data.devnode, conf->crypt.data.name,
		    conf->crypt.header.devnode);
661
	} else {
662
663
		dbg("starting cryptsetup %s -> %s", conf->crypt.data.devnode,
		    conf->crypt.data.name);
664
	}
665
	load_kmod("dm-crypt", NULL, 0);
666
667
668
	conf->cryptsetup_running = 1;
	conf->running_threads = 1;
	start_thread(conf, cryptsetup_thread);
Natanael Copa's avatar
Natanael Copa committed
669
670
}

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
static int is_mounted(const char *devnode) {
	char line[PATH_MAX];
	FILE *f = fopen("/proc/mounts", "r");
	int r = 0;
	if (f == NULL)
		return 0;
	while (fgets(line, sizeof(line), f) != NULL) {
		strtok(line, " ");
		if (strcmp(devnode, line) == 0) {
			r = 1;
			break;
		}
	}
	fclose(f);
	return r;
}

struct recurse_opts {
689
690
691
692
	size_t pathlen;
	char path[PATH_MAX], *filename;
	int is_dir;
	int matchdepth;
693
	int curdepth, maxdepth;
694
	void (*callback)(struct recurse_opts *opts, void *userdata);
695
696
697
	void *userdata;
};

698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
static int recurse_push(struct recurse_opts *opts, size_t *oldlen, const char *path)
{
	size_t pathlen = strlen(path);
	if (opts->pathlen + 1 + pathlen + 1 >= sizeof opts->path)
		return 0;
	*oldlen = opts->pathlen;
	opts->path[opts->pathlen++] = '/';
	strcpy(&opts->path[opts->pathlen], path);
	opts->pathlen += strlen(path);
	return 1;
}

static void recurse_pop(struct recurse_opts *opts, size_t len)
{
	opts->pathlen = len;
	opts->path[len] = 0;
}

static void do_recurse_dir(struct recurse_opts *opts)
717
{
718
	size_t oldlen;
719
	struct dirent *entry;
720
721
	DIR *d;
	int is_dir;
722

723
	d = opendir(opts->path);
724
	if (!d) return;
725
726

	while ((entry = readdir(d)) != NULL) {
727
728
729
		if (strcmp(entry->d_name, ".") == 0 ||
		    strcmp(entry->d_name, "..") == 0)
			continue;
730

731
		if (!recurse_push(opts, &oldlen, entry->d_name))
732
			continue;
733

734
		if (entry->d_type == DT_UNKNOWN) {
735
736
			/* some filesystems like iso9660 does not support
			   the d_type so we use lstat */
737
			struct stat st;
738
739
			if (lstat(opts->path, &st) < 0) {
				dbg("%s: %s", opts->path, strerror(errno));
740
741
742
				goto next;
			}
			is_dir = S_ISDIR(st.st_mode);
743
		} else
744
			is_dir = entry->d_type & DT_DIR;
745

746
747
748
749
750
		if (opts->matchdepth == 0 || opts->matchdepth == opts->curdepth) {
			opts->filename = &opts->path[oldlen+1];
			opts->is_dir = is_dir;
			opts->callback(opts, opts->userdata);
		}
751

752
753
		if (is_dir && opts->curdepth < opts->maxdepth) {
			opts->curdepth++;
754
			do_recurse_dir(opts);
755
756
			opts->curdepth--;
		}
757
next:
758
		recurse_pop(opts, oldlen);
759
760
761
762
	}
	closedir(d);
}

763
static void recurse_dir(struct recurse_opts *opts)
764
{
765
	opts->pathlen = strlen(opts->path);
766
	opts->curdepth = 1;
767
	do_recurse_dir(opts);
768
769
770
771
772
773
774
775
}

struct trigger_entry {
	struct list_head node;
	int max_depth;
	char pathname[];
};

776
static void trigger_uevent_cb(struct recurse_opts *opts, void *data)
777
{
778
	size_t oldlen;
779
780
	int fd;

781
	if (!recurse_push(opts, &oldlen, "uevent"))
782
783
		return;

784
	fd = open(opts->path, O_WRONLY | O_CLOEXEC);
785
786
787
788
	if (fd >= 0) {
		write(fd, "add", 3);
		close(fd);
	}
789
	recurse_pop(opts, oldlen);
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
}

static void trigger_path(struct ueventconf *conf, char *path, char *subdir, int max_depth)
{
	struct trigger_entry *e;
	size_t pathlen = strlen(path);

	e = malloc(pathlen + (subdir ? strlen(subdir) : 0) + 1 + sizeof *e);
	if (!e) return;

	list_init(&e->node);
	e->max_depth = max_depth;
	strcpy(e->pathname, path);
	if (subdir) strcpy(&e->pathname[pathlen], subdir);

	pthread_mutex_lock(&conf->trigger_mutex);
	conf->running_threads = 1;
	list_add_tail(&e->node, &conf->trigger_list);
	pthread_cond_signal(&conf->trigger_cond);
	pthread_mutex_unlock(&conf->trigger_mutex);
}

static void *trigger_thread(void *data)
{
	struct ueventconf *conf = data;
	struct recurse_opts opts;
	struct trigger_entry *entry = NULL;

	while (1) {
		pthread_mutex_lock(&conf->trigger_mutex);
		if (entry) {
			list_del(&entry->node);
			free(entry);
		}
		entry = list_next(&conf->trigger_list, struct trigger_entry, node);
		while (!entry) {
			notify_main(conf);
			pthread_cond_wait(&conf->trigger_cond, &conf->trigger_mutex);
			entry = list_next(&conf->trigger_list, struct trigger_entry, node);
		}
		pthread_mutex_unlock(&conf->trigger_mutex);

		opts = (struct recurse_opts) {
			.callback = trigger_uevent_cb,
			.userdata = entry,
			.maxdepth = entry->max_depth,
			.matchdepth = entry->max_depth,
		};
838
839
840
841
		snprintf(opts.path, sizeof opts.path, "/sys%s", entry->pathname);
		dbg("trigger_thread: scanning %s", opts.path);

		recurse_dir(&opts);
842
843
844
845
846
	}

	return NULL;
}

847
static void append_line(const char *outfile, const char *data)
848
{
849
850
	int fd;
	if (outfile == 0) return;
851
	fd = open(outfile, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC);
852
	if (fd == -1)
853
854
		err(1, "%s", outfile);
	write(fd, data, strlen(data));
855
856
857
858
	write(fd, "\n", 1);
	close(fd);
}

859
860
861
862
struct scandevctx {
	struct ueventconf *conf;
	int found;
};
863

864
865
866
867
static void scandev_cb(struct recurse_opts *opts, void *data)
{
	struct scandevctx *ctx = data;
	struct ueventconf *conf = ctx->conf;
868

869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
	if (opts->is_dir) {
		size_t oldlen;
		int ok = 0;
		if (recurse_push(opts, &oldlen, ".boot_repository")) {
			ok = access(opts->path, F_OK) == 0;
			recurse_pop(opts, oldlen);
		}
		if (ok) {
			dbg("added boot repository %s to %s", opts->path, conf->bootrepos);
			append_line(conf->bootrepos, opts->path);
			ctx->found |= FOUND_BOOTREPO;
		}
	} else if (fnmatch("*.apkovl.tar.gz*", opts->filename, 0) == 0) {
		dbg("found apkovl %s", opts->path);
		append_line(conf->apkovls, opts->path);
		ctx->found |= FOUND_APKOVL;
885
886
	}
}
887

888
static int scandev(struct ueventconf *conf, const char *devnode, const char *type)
889
{
890
891
	struct scandevctx ctx = {
		.conf = conf,
892
893
	};
	struct recurse_opts opts = {
894
895
896
		.maxdepth = 1,
		.callback = scandev_cb,
		.userdata = &ctx,
897
	};
898
899
	char *devname;
	int r;
900
901
902

	/* skip already mounted devices */
	if (is_mounted(devnode)) {
903
		dbg("%s is mounted (%s). skipping", devnode, type);
904
905
906
		return 0;
	}
	devname = strrchr(devnode, '/');
907
908
	if (!devname)
		return 0;
909

910
911
912
	snprintf(opts.path, sizeof opts.path, "/media%s", devname);
	dbg("mounting %s on %s (%s)", devnode, opts.path, type);
	mkdir(opts.path, 0755);
913

914
	r = mount(devnode, opts.path, type, MS_RDONLY, NULL);
915
916
	if (r < 0) {
		dbg("Failed to mount %s on %s: %s",
917
		    devnode, opts.path, strerror(errno));
918
		return 0;
919
	}
920

921
	recurse_dir(&opts);
922

923
924
	if (ctx.found == 0)
		umount(opts.path);
925

926
	return ctx.found;
927
928
}

929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
static int is_same_device(const struct uevent *ev, const char *nodepath)
{
	struct stat st;
	unsigned int maj, min;
	if (stat(nodepath, &st) < 0)
		return 0;

	if (ev->major == NULL || ev->minor == NULL)
		return 0;

	maj = atoi(ev->major);
	min = atoi(ev->minor);
	return S_ISBLK(st.st_mode) && makedev(maj, min) == st.st_rdev;
}

944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
static void founddev(struct ueventconf *conf, int found)
{
	conf->found |= found;
	if ((found & FOUND_DEVICE)
	    || ((found & FOUND_BOOTREPO) &&
		(found & FOUND_APKOVL))) {
		/* we have found everything we need, so no
		   no need to wait for anything new event */
		if (conf->timeout)
			dbg("FOUND! setting timeout to 0");
		conf->timeout = 0;
		conf->usb_storage_timeout= 0;
	} else if ((found & FOUND_BOOTREPO) && conf->timeout) {
		/* we have found boot repo, but not apkovl
		   we reduce timeout to default timeout */
		if (conf->timeout != conf->uevent_timeout)
			dbg("Setting timeout to %d", conf->uevent_timeout);
		conf->timeout = conf->uevent_timeout;
	}
}

Natanael Copa's avatar
Natanael Copa committed
965
966
967
968
969
970
971
972
973
974
static int is_zfs_pool(const char *path, const char *label)
{
	char pool_name[256];
	char *p;
	snprintf(pool_name, sizeof(pool_name), "%s", path);
	if ((p = strchr(pool_name, '/')))
		*p = '\0';
	return strcmp(label, pool_name) == 0 ? FOUND_DEVICE : 0;
}

975
static int searchdev(struct uevent *ev, const char *searchdev, int scanbootmedia)
Natanael Copa's avatar
Natanael Copa committed
976
{
977
	struct ueventconf *conf = ev->conf;
Natanael Copa's avatar
Natanael Copa committed
978
979
980
	char *type = NULL, *label = NULL, *uuid = NULL;
	int rc = 0;

981
	if (searchdev == NULL && !scanbootmedia)
Natanael Copa's avatar
Natanael Copa committed
982
983
		return 0;

984
985
986
	if (searchdev && (strcmp(ev->devname, searchdev) == 0
			  || strcmp(ev->devnode, searchdev) == 0
	                  || is_same_device(ev, searchdev))) {
987
		return FOUND_DEVICE;
Natanael Copa's avatar
Natanael Copa committed
988
989
	}

990
991
	if (conf->blkid_cache == NULL)
		blkid_get_cache(&conf->blkid_cache, NULL);
Natanael Copa's avatar
Natanael Copa committed
992

993
	type = blkid_get_tag_value(conf->blkid_cache, "TYPE", ev->devnode);
Mark Riedesel's avatar
Mark Riedesel committed
994
	uuid = blkid_get_tag_value(conf->blkid_cache, "UUID", ev->devnode);
Natanael Copa's avatar
Natanael Copa committed
995
	label = blkid_get_tag_value(conf->blkid_cache, "LABEL", ev->devnode);
Natanael Copa's avatar
Natanael Copa committed
996

997
998
	if (searchdev != NULL) {
		if (strncmp("LABEL=", searchdev, 6) == 0) {
999
1000
			if (label && strcmp(label, searchdev+6) == 0)
				rc = FOUND_DEVICE;
For faster browsing, not all history is shown. View entire blame