summaryrefslogtreecommitdiff
path: root/hotplug-dispatch.c
blob: f1ece3833f235d59b321d6d9bd89ea3ef621fcd9 (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
/*
 * Copyright (C) 2021 Daniel Golle <daniel@makrotopia.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 2.1
 * as published by the Free Software Foundation
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#define _GNU_SOURCE

#include <sys/inotify.h>
#include <sys/types.h>

#include <dirent.h>
#include <errno.h>
#include <glob.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <libubox/avl.h>
#include <libubox/avl-cmp.h>
#include <libubox/list.h>
#include <libubox/uloop.h>
#include <libubus.h>

#include "procd.h"

#define HOTPLUG_BASEDIR "/etc/hotplug.d"
#define HOTPLUG_OBJECT_PREFIX "hotplug."

#define INOTIFY_SZ (sizeof(struct inotify_event) + PATH_MAX + 1)

struct ubus_context *ctx;
static char *inotify_buffer;
static struct uloop_fd fd_inotify_read;

static LIST_HEAD(subsystems);

extern char **environ;

struct hotplug_subsys {
	struct list_head list;
	struct ubus_object ubus;
};

struct envlist {
	struct avl_node avl;
	char *env;
};

struct hotplug_process {
	struct ubus_object *ubus;
	char **envp;
	struct uloop_timeout timeout;
	struct uloop_process process;
	glob_t globbuf;
	unsigned int cnt;
	int ret;
};

static void env_free(char **envp)
{
	char **tmp;

	tmp = envp;
	while (*tmp)
		free(*(tmp++));
	free(envp);
}

static void hotplug_free(struct hotplug_process *pc)
{
	env_free(pc->envp);
	globfree(&pc->globbuf);
	free(pc);
}

static void hotplug_done(struct uloop_process *c, int ret)
{
	struct hotplug_process *pc = container_of(c, struct hotplug_process, process);

	pc->ret = ret;

	uloop_timeout_set(&pc->timeout, 50);
}

static void hotplug_exec(struct uloop_timeout *t)
{
	struct hotplug_process *pc = container_of(t, struct hotplug_process, timeout);
	char *script;
	char *exec_argv[4];
	/* we have reached the last entry in the globbuf */
	if (pc->cnt == pc->globbuf.gl_pathc) {
		hotplug_free(pc);
		return;
	}

	if (asprintf(&script, ". /lib/functions.sh\n. %s\n", pc->globbuf.gl_pathv[pc->cnt++]) == -1) {
		pc->ret = ENOMEM;
		return;
	}

	/* prepare for execve() */
	exec_argv[0] = "/bin/sh";
	exec_argv[1] = "-c";
	exec_argv[2] = script;
	exec_argv[3] = NULL;

	/* set callback in uloop_process */
	pc->process.cb = hotplug_done;
	pc->process.pid = fork();
	if (pc->process.pid == 0) {
		/* child */
		exit(execve(exec_argv[0], exec_argv, pc->envp));
	} else if (pc->process.pid < 0) {
		/* fork error */
		free(script);
		hotplug_free(pc);
		return;
	}
	/* parent */
	free(script);
	uloop_process_add(&pc->process);
}

static int avl_envcmp(const void *k1, const void *k2, void *ptr)
{
	const char *tmp;

	tmp = strchr(k1, '=');
	if (!tmp)
		return -1;

	/*
	 * compare the variable name only, ie. limit strncmp to check
	 * only up to and including the '=' sign
	 */
	return strncmp(k1, k2, (tmp - (char *)k1) + 1);
}

/* validate NULL-terminated environment variable name */
static int validate_envvarname(const char *envvarname)
{
	const char *tmp = envvarname;

	/* check for illegal characters in env variable name */
	while (tmp[0] != '\0') {
		if (!((tmp[0] >= 'a' && tmp[0] <= 'z') ||
		      (tmp[0] >= 'A' && tmp[0] <= 'Z') ||
		      (tmp[0] == '_') ||
		      /* allow numbers unless they are at the first character */
		      ((tmp != envvarname) && tmp[0] >= '0' && tmp[0] <= '9')))
			return EINVAL;
		++tmp;
	}

	return 0;
}

enum {
	HOTPLUG_ENV,
	__HOTPLUG_MAX
};

static const struct blobmsg_policy hotplug_policy[__HOTPLUG_MAX] = {
	[HOTPLUG_ENV] = { .name = "env", .type = BLOBMSG_TYPE_ARRAY },
};

static int hotplug_call(struct ubus_context *ctx, struct ubus_object *obj,
			struct ubus_request_data *req, const char *method,
			struct blob_attr *msg)
{
	const char *subsys = &obj->name[strlen(HOTPLUG_OBJECT_PREFIX)];
	struct blob_attr *tb[__HOTPLUG_MAX], *cur;
	AVL_TREE(env, avl_envcmp, false, NULL);
	struct envlist *envle, *p;
	int rem;
	char **envp, *globstr, *tmp, **tmpenv;
	size_t envz = 0;
	struct hotplug_process *pc;
	bool async = true;
	int err = UBUS_STATUS_UNKNOWN_ERROR;

	blobmsg_parse(hotplug_policy, __HOTPLUG_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));

	if (!tb[HOTPLUG_ENV])
		return UBUS_STATUS_INVALID_ARGUMENT;

	tmpenv = environ;

	/* first adding existing environment to avl_tree */
	while (*tmpenv) {
		envle = calloc(1, sizeof(struct envlist));
		if (!envle)
			goto err_envle;

		envle->env = strdup(*tmpenv);
		if (!envle->env) {
			free(envle);
			goto err_envle;
		}
		envle->avl.key = envle->env;
		if (avl_insert(&env, &envle->avl) == -1) {
			free(envle->env);
			free(envle);
			goto err_envle;
		}

		++tmpenv;
	}

	/* then adding additional variables from ubus call */
	blobmsg_for_each_attr(cur, tb[HOTPLUG_ENV], rem) {
		char *enve = blobmsg_get_string(cur);
		if (!enve)
			continue;

		if (!strncmp(enve, "LD_", 3))
			continue;

		if (!strcmp(enve, "PATH"))
			continue;

		if (strlen(enve) < 3)
			continue;

		if (!(tmp = strchr(enve, '=')))
			continue;

		*tmp = '\0';
		if (validate_envvarname(enve))
			continue;
		*tmp = '=';

		if (!strlen(++tmp))
			continue;

		if (!strcmp(enve, "ASYNC=0"))
			async = false;

		envle = calloc(1, sizeof(struct envlist));
		if (!envle)
			goto err_envle;

		envle->env = strdup(enve);
		if (!envle->env) {
			free(envle);
			goto err_envle;
		}
		envle->avl.key = envle->env;
		if (avl_insert(&env, &envle->avl)) {
			/* do not override existing env values, just skip */
			free((void*)envle->env);
			free(envle);
		}
	}

	/* synchronous calls are unsupported for now */
	if (!async) {
		err = UBUS_STATUS_NOT_SUPPORTED;
		goto err_envle;
	}

	/* allocating new environment */
	avl_for_each_element(&env, envle, avl)
		++envz;

	envp = calloc(envz + 1, sizeof(char *));
	if (!envp)
		goto err_envle;

	/* populating new environment */
	envz = 0;
	avl_for_each_element_safe(&env, envle, avl, p) {
		envp[envz++] = envle->env;
		avl_delete(&env, &envle->avl);
		free(envle);
	}

	pc = calloc(1, sizeof(struct hotplug_process));
	if (!pc) {
		env_free(envp);
		return UBUS_STATUS_UNKNOWN_ERROR;
	}
	pc->timeout.cb = hotplug_exec;
	pc->envp = envp;
	pc->cnt = 0;
	pc->ubus = obj;

	/* glob'ing for hotplug scripts */
	if (asprintf(&globstr, "%s/%s/*", HOTPLUG_BASEDIR, subsys) == -1) {
		hotplug_free(pc);
		return UBUS_STATUS_UNKNOWN_ERROR;
	}

	if (glob(globstr, GLOB_DOOFFS, NULL, &pc->globbuf)) {
		free(globstr);
		hotplug_free(pc);
		return UBUS_STATUS_OK;
	}

	free(globstr);

	/* asynchronous call to hotplug_exec() */
	uloop_timeout_set(&pc->timeout, 50);

	return UBUS_STATUS_OK;

err_envle:
	avl_for_each_element_safe(&env, envle, avl, p) {
		if (envle->env)
			free(envle->env);

		avl_delete(&env, &envle->avl);
		free(envle);
	}

	return err;
}

static const struct ubus_method hotplug_methods[] = {
	UBUS_METHOD("call", hotplug_call, hotplug_policy),
};

static struct ubus_object_type hotplug_object_type =
	UBUS_OBJECT_TYPE("hotplug", hotplug_methods);

static void add_subsystem(int nlen, char *newname)
{
	struct hotplug_subsys *nh = calloc(1, sizeof(struct hotplug_subsys));
	char *name;

	if (asprintf(&name, "%s%.*s", HOTPLUG_OBJECT_PREFIX, nlen, newname) == -1)
		exit(ENOMEM);

	/* prepare and add ubus object */
	nh->ubus.name = name;
	nh->ubus.type = &hotplug_object_type;
	nh->ubus.methods = hotplug_object_type.methods;
	nh->ubus.n_methods = hotplug_object_type.n_methods;
	list_add(&nh->list, &subsystems);
	ubus_add_object(ctx, &nh->ubus);
}

static void remove_subsystem(int nlen, char *name)
{
	struct hotplug_subsys *n, *h;

	/* find match subsystem object by name or any if not given */
	list_for_each_entry_safe(h, n, &subsystems, list) {
		if (nlen && (strlen(h->ubus.name) != strnlen(name, nlen) + strlen(HOTPLUG_OBJECT_PREFIX)))
			continue;
		if (nlen && (strncmp(name, &h->ubus.name[strlen(HOTPLUG_OBJECT_PREFIX)], nlen)))
			continue;

		list_del(&h->list);
		ubus_remove_object(ctx, &h->ubus);
		free((void*)h->ubus.name);
		free(h);
	}
}

static int init_subsystems(void)
{
	DIR *dir;
	struct dirent *dirent;

	dir = opendir(HOTPLUG_BASEDIR);
	if (dir == NULL)
		return ENOENT;

	while ((dirent = readdir(dir))) {
		/* skip everything but directories */
		if (dirent->d_type != DT_DIR)
			continue;

		/* skip '.' and '..' as well as hidden files */
		if (dirent->d_name[0] == '.')
			continue;

		add_subsystem(strlen(dirent->d_name), dirent->d_name);
	}
	closedir(dir);

	return 0;
}

static void inotify_read_handler(struct uloop_fd *u, unsigned int events)
{
	int rc;
	char *p;
	struct inotify_event *in;

	/* read inotify events */
	while ((rc = read(u->fd, inotify_buffer, INOTIFY_SZ)) == -1 && errno == EINTR);

	if (rc <= 0)
		return;

	/* process events from buffer */
	for (p = inotify_buffer;
	     rc - (p - inotify_buffer) >= (int)sizeof(struct inotify_event);
	     p += sizeof(struct inotify_event) + in->len) {
		in = (struct inotify_event*)p;

		/* skip everything but directories */
		if (!(in->mask & IN_ISDIR))
			continue;

		if (in->len < 1)
			continue;

		/* skip hidden files */
		if (in->name[0] == '.')
			continue;

		/* add/remove subsystem objects */
		if (in->mask & (IN_CREATE | IN_MOVED_TO))
			add_subsystem(in->len, in->name);
		else if (in->mask & (IN_DELETE | IN_MOVED_FROM))
			remove_subsystem(in->len, in->name);
	}
}

void ubus_init_hotplug(struct ubus_context *newctx)
{
	ctx = newctx;
	remove_subsystem(0, NULL);
	if (init_subsystems()) {
		printf("failed to initialize hotplug subsystems from %s\n", HOTPLUG_BASEDIR);
		return;
	}
	fd_inotify_read.fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
	fd_inotify_read.cb = inotify_read_handler;
	if (fd_inotify_read.fd == -1) {
		printf("failed to initialize inotify handler for %s\n", HOTPLUG_BASEDIR);
		return;
	}

	inotify_buffer = calloc(1, INOTIFY_SZ);
	if (!inotify_buffer)
		return;

	if (inotify_add_watch(fd_inotify_read.fd, HOTPLUG_BASEDIR,
		IN_CREATE | IN_MOVED_TO | IN_DELETE | IN_MOVED_FROM | IN_ONLYDIR) == -1)
		return;

	uloop_fd_add(&fd_inotify_read, ULOOP_READ);
}