xref: /linux/lib/kobject_uevent.c (revision d9d16e16a3f82e88fec99222c9c7e26563b05688)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * kernel userspace event delivery
4  *
5  * Copyright (C) 2004 Red Hat, Inc.  All rights reserved.
6  * Copyright (C) 2004 Novell, Inc.  All rights reserved.
7  * Copyright (C) 2004 IBM, Inc. All rights reserved.
8  *
9  * Licensed under the GNU GPL v2.
10  *
11  * Authors:
12  *	Robert Love		<rml@novell.com>
13  *	Kay Sievers		<kay.sievers@vrfy.org>
14  *	Arjan van de Ven	<arjanv@redhat.com>
15  *	Greg Kroah-Hartman	<greg@kroah.com>
16  */
17 
18 #include <linux/spinlock.h>
19 #include <linux/string.h>
20 #include <linux/kobject.h>
21 #include <linux/export.h>
22 #include <linux/kmod.h>
23 #include <linux/slab.h>
24 #include <linux/socket.h>
25 #include <linux/skbuff.h>
26 #include <linux/netlink.h>
27 #include <linux/uuid.h>
28 #include <linux/ctype.h>
29 #include <net/sock.h>
30 #include <net/net_namespace.h>
31 
32 
33 u64 uevent_seqnum;
34 #ifdef CONFIG_UEVENT_HELPER
35 char uevent_helper[UEVENT_HELPER_PATH_LEN] = CONFIG_UEVENT_HELPER_PATH;
36 #endif
37 #ifdef CONFIG_NET
38 struct uevent_sock {
39 	struct list_head list;
40 	struct sock *sk;
41 };
42 static LIST_HEAD(uevent_sock_list);
43 #endif
44 
45 /* This lock protects uevent_seqnum and uevent_sock_list */
46 static DEFINE_MUTEX(uevent_sock_mutex);
47 
48 /* the strings here must match the enum in include/linux/kobject.h */
49 static const char *kobject_actions[] = {
50 	[KOBJ_ADD] =		"add",
51 	[KOBJ_REMOVE] =		"remove",
52 	[KOBJ_CHANGE] =		"change",
53 	[KOBJ_MOVE] =		"move",
54 	[KOBJ_ONLINE] =		"online",
55 	[KOBJ_OFFLINE] =	"offline",
56 	[KOBJ_BIND] =		"bind",
57 	[KOBJ_UNBIND] =		"unbind",
58 };
59 
60 static int kobject_action_type(const char *buf, size_t count,
61 			       enum kobject_action *type,
62 			       const char **args)
63 {
64 	enum kobject_action action;
65 	size_t count_first;
66 	const char *args_start;
67 	int ret = -EINVAL;
68 
69 	if (count && (buf[count-1] == '\n' || buf[count-1] == '\0'))
70 		count--;
71 
72 	if (!count)
73 		goto out;
74 
75 	args_start = strnchr(buf, count, ' ');
76 	if (args_start) {
77 		count_first = args_start - buf;
78 		args_start = args_start + 1;
79 	} else
80 		count_first = count;
81 
82 	for (action = 0; action < ARRAY_SIZE(kobject_actions); action++) {
83 		if (strncmp(kobject_actions[action], buf, count_first) != 0)
84 			continue;
85 		if (kobject_actions[action][count_first] != '\0')
86 			continue;
87 		if (args)
88 			*args = args_start;
89 		*type = action;
90 		ret = 0;
91 		break;
92 	}
93 out:
94 	return ret;
95 }
96 
97 static const char *action_arg_word_end(const char *buf, const char *buf_end,
98 				       char delim)
99 {
100 	const char *next = buf;
101 
102 	while (next <= buf_end && *next != delim)
103 		if (!isalnum(*next++))
104 			return NULL;
105 
106 	if (next == buf)
107 		return NULL;
108 
109 	return next;
110 }
111 
112 static int kobject_action_args(const char *buf, size_t count,
113 			       struct kobj_uevent_env **ret_env)
114 {
115 	struct kobj_uevent_env *env = NULL;
116 	const char *next, *buf_end, *key;
117 	int key_len;
118 	int r = -EINVAL;
119 
120 	if (count && (buf[count - 1] == '\n' || buf[count - 1] == '\0'))
121 		count--;
122 
123 	if (!count)
124 		return -EINVAL;
125 
126 	env = kzalloc(sizeof(*env), GFP_KERNEL);
127 	if (!env)
128 		return -ENOMEM;
129 
130 	/* first arg is UUID */
131 	if (count < UUID_STRING_LEN || !uuid_is_valid(buf) ||
132 	    add_uevent_var(env, "SYNTH_UUID=%.*s", UUID_STRING_LEN, buf))
133 		goto out;
134 
135 	/*
136 	 * the rest are custom environment variables in KEY=VALUE
137 	 * format with ' ' delimiter between each KEY=VALUE pair
138 	 */
139 	next = buf + UUID_STRING_LEN;
140 	buf_end = buf + count - 1;
141 
142 	while (next <= buf_end) {
143 		if (*next != ' ')
144 			goto out;
145 
146 		/* skip the ' ', key must follow */
147 		key = ++next;
148 		if (key > buf_end)
149 			goto out;
150 
151 		buf = next;
152 		next = action_arg_word_end(buf, buf_end, '=');
153 		if (!next || next > buf_end || *next != '=')
154 			goto out;
155 		key_len = next - buf;
156 
157 		/* skip the '=', value must follow */
158 		if (++next > buf_end)
159 			goto out;
160 
161 		buf = next;
162 		next = action_arg_word_end(buf, buf_end, ' ');
163 		if (!next)
164 			goto out;
165 
166 		if (add_uevent_var(env, "SYNTH_ARG_%.*s=%.*s",
167 				   key_len, key, (int) (next - buf), buf))
168 			goto out;
169 	}
170 
171 	r = 0;
172 out:
173 	if (r)
174 		kfree(env);
175 	else
176 		*ret_env = env;
177 	return r;
178 }
179 
180 /**
181  * kobject_synth_uevent - send synthetic uevent with arguments
182  *
183  * @kobj: struct kobject for which synthetic uevent is to be generated
184  * @buf: buffer containing action type and action args, newline is ignored
185  * @count: length of buffer
186  *
187  * Returns 0 if kobject_synthetic_uevent() is completed with success or the
188  * corresponding error when it fails.
189  */
190 int kobject_synth_uevent(struct kobject *kobj, const char *buf, size_t count)
191 {
192 	char *no_uuid_envp[] = { "SYNTH_UUID=0", NULL };
193 	enum kobject_action action;
194 	const char *action_args;
195 	struct kobj_uevent_env *env;
196 	const char *msg = NULL, *devpath;
197 	int r;
198 
199 	r = kobject_action_type(buf, count, &action, &action_args);
200 	if (r) {
201 		msg = "unknown uevent action string\n";
202 		goto out;
203 	}
204 
205 	if (!action_args) {
206 		r = kobject_uevent_env(kobj, action, no_uuid_envp);
207 		goto out;
208 	}
209 
210 	r = kobject_action_args(action_args,
211 				count - (action_args - buf), &env);
212 	if (r == -EINVAL) {
213 		msg = "incorrect uevent action arguments\n";
214 		goto out;
215 	}
216 
217 	if (r)
218 		goto out;
219 
220 	r = kobject_uevent_env(kobj, action, env->envp);
221 	kfree(env);
222 out:
223 	if (r) {
224 		devpath = kobject_get_path(kobj, GFP_KERNEL);
225 		printk(KERN_WARNING "synth uevent: %s: %s",
226 		       devpath ?: "unknown device",
227 		       msg ?: "failed to send uevent");
228 		kfree(devpath);
229 	}
230 	return r;
231 }
232 
233 #ifdef CONFIG_NET
234 static int kobj_bcast_filter(struct sock *dsk, struct sk_buff *skb, void *data)
235 {
236 	struct kobject *kobj = data, *ksobj;
237 	const struct kobj_ns_type_operations *ops;
238 
239 	ops = kobj_ns_ops(kobj);
240 	if (!ops && kobj->kset) {
241 		ksobj = &kobj->kset->kobj;
242 		if (ksobj->parent != NULL)
243 			ops = kobj_ns_ops(ksobj->parent);
244 	}
245 
246 	if (ops && ops->netlink_ns && kobj->ktype->namespace) {
247 		const void *sock_ns, *ns;
248 		ns = kobj->ktype->namespace(kobj);
249 		sock_ns = ops->netlink_ns(dsk);
250 		return sock_ns != ns;
251 	}
252 
253 	return 0;
254 }
255 #endif
256 
257 #ifdef CONFIG_UEVENT_HELPER
258 static int kobj_usermode_filter(struct kobject *kobj)
259 {
260 	const struct kobj_ns_type_operations *ops;
261 
262 	ops = kobj_ns_ops(kobj);
263 	if (ops) {
264 		const void *init_ns, *ns;
265 		ns = kobj->ktype->namespace(kobj);
266 		init_ns = ops->initial_ns();
267 		return ns != init_ns;
268 	}
269 
270 	return 0;
271 }
272 
273 static int init_uevent_argv(struct kobj_uevent_env *env, const char *subsystem)
274 {
275 	int len;
276 
277 	len = strlcpy(&env->buf[env->buflen], subsystem,
278 		      sizeof(env->buf) - env->buflen);
279 	if (len >= (sizeof(env->buf) - env->buflen)) {
280 		WARN(1, KERN_ERR "init_uevent_argv: buffer size too small\n");
281 		return -ENOMEM;
282 	}
283 
284 	env->argv[0] = uevent_helper;
285 	env->argv[1] = &env->buf[env->buflen];
286 	env->argv[2] = NULL;
287 
288 	env->buflen += len + 1;
289 	return 0;
290 }
291 
292 static void cleanup_uevent_env(struct subprocess_info *info)
293 {
294 	kfree(info->data);
295 }
296 #endif
297 
298 static int kobject_uevent_net_broadcast(struct kobject *kobj,
299 					struct kobj_uevent_env *env,
300 					const char *action_string,
301 					const char *devpath)
302 {
303 	int retval = 0;
304 #if defined(CONFIG_NET)
305 	struct sk_buff *skb = NULL;
306 	struct uevent_sock *ue_sk;
307 
308 	/* send netlink message */
309 	list_for_each_entry(ue_sk, &uevent_sock_list, list) {
310 		struct sock *uevent_sock = ue_sk->sk;
311 
312 		if (!netlink_has_listeners(uevent_sock, 1))
313 			continue;
314 
315 		if (!skb) {
316 			/* allocate message with the maximum possible size */
317 			size_t len = strlen(action_string) + strlen(devpath) + 2;
318 			char *scratch;
319 
320 			retval = -ENOMEM;
321 			skb = alloc_skb(len + env->buflen, GFP_KERNEL);
322 			if (!skb)
323 				continue;
324 
325 			/* add header */
326 			scratch = skb_put(skb, len);
327 			sprintf(scratch, "%s@%s", action_string, devpath);
328 
329 			skb_put_data(skb, env->buf, env->buflen);
330 
331 			NETLINK_CB(skb).dst_group = 1;
332 		}
333 
334 		retval = netlink_broadcast_filtered(uevent_sock, skb_get(skb),
335 						    0, 1, GFP_KERNEL,
336 						    kobj_bcast_filter,
337 						    kobj);
338 		/* ENOBUFS should be handled in userspace */
339 		if (retval == -ENOBUFS || retval == -ESRCH)
340 			retval = 0;
341 	}
342 	consume_skb(skb);
343 #endif
344 	return retval;
345 }
346 
347 static void zap_modalias_env(struct kobj_uevent_env *env)
348 {
349 	static const char modalias_prefix[] = "MODALIAS=";
350 	int i;
351 
352 	for (i = 0; i < env->envp_idx;) {
353 		if (strncmp(env->envp[i], modalias_prefix,
354 			    sizeof(modalias_prefix) - 1)) {
355 			i++;
356 			continue;
357 		}
358 
359 		if (i != env->envp_idx - 1)
360 			memmove(&env->envp[i], &env->envp[i + 1],
361 				sizeof(env->envp[i]) * env->envp_idx - 1);
362 
363 		env->envp_idx--;
364 	}
365 }
366 
367 /**
368  * kobject_uevent_env - send an uevent with environmental data
369  *
370  * @kobj: struct kobject that the action is happening to
371  * @action: action that is happening
372  * @envp_ext: pointer to environmental data
373  *
374  * Returns 0 if kobject_uevent_env() is completed with success or the
375  * corresponding error when it fails.
376  */
377 int kobject_uevent_env(struct kobject *kobj, enum kobject_action action,
378 		       char *envp_ext[])
379 {
380 	struct kobj_uevent_env *env;
381 	const char *action_string = kobject_actions[action];
382 	const char *devpath = NULL;
383 	const char *subsystem;
384 	struct kobject *top_kobj;
385 	struct kset *kset;
386 	const struct kset_uevent_ops *uevent_ops;
387 	int i = 0;
388 	int retval = 0;
389 
390 	pr_debug("kobject: '%s' (%p): %s\n",
391 		 kobject_name(kobj), kobj, __func__);
392 
393 	/* search the kset we belong to */
394 	top_kobj = kobj;
395 	while (!top_kobj->kset && top_kobj->parent)
396 		top_kobj = top_kobj->parent;
397 
398 	if (!top_kobj->kset) {
399 		pr_debug("kobject: '%s' (%p): %s: attempted to send uevent "
400 			 "without kset!\n", kobject_name(kobj), kobj,
401 			 __func__);
402 		return -EINVAL;
403 	}
404 
405 	kset = top_kobj->kset;
406 	uevent_ops = kset->uevent_ops;
407 
408 	/* skip the event, if uevent_suppress is set*/
409 	if (kobj->uevent_suppress) {
410 		pr_debug("kobject: '%s' (%p): %s: uevent_suppress "
411 				 "caused the event to drop!\n",
412 				 kobject_name(kobj), kobj, __func__);
413 		return 0;
414 	}
415 	/* skip the event, if the filter returns zero. */
416 	if (uevent_ops && uevent_ops->filter)
417 		if (!uevent_ops->filter(kset, kobj)) {
418 			pr_debug("kobject: '%s' (%p): %s: filter function "
419 				 "caused the event to drop!\n",
420 				 kobject_name(kobj), kobj, __func__);
421 			return 0;
422 		}
423 
424 	/* originating subsystem */
425 	if (uevent_ops && uevent_ops->name)
426 		subsystem = uevent_ops->name(kset, kobj);
427 	else
428 		subsystem = kobject_name(&kset->kobj);
429 	if (!subsystem) {
430 		pr_debug("kobject: '%s' (%p): %s: unset subsystem caused the "
431 			 "event to drop!\n", kobject_name(kobj), kobj,
432 			 __func__);
433 		return 0;
434 	}
435 
436 	/* environment buffer */
437 	env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
438 	if (!env)
439 		return -ENOMEM;
440 
441 	/* complete object path */
442 	devpath = kobject_get_path(kobj, GFP_KERNEL);
443 	if (!devpath) {
444 		retval = -ENOENT;
445 		goto exit;
446 	}
447 
448 	/* default keys */
449 	retval = add_uevent_var(env, "ACTION=%s", action_string);
450 	if (retval)
451 		goto exit;
452 	retval = add_uevent_var(env, "DEVPATH=%s", devpath);
453 	if (retval)
454 		goto exit;
455 	retval = add_uevent_var(env, "SUBSYSTEM=%s", subsystem);
456 	if (retval)
457 		goto exit;
458 
459 	/* keys passed in from the caller */
460 	if (envp_ext) {
461 		for (i = 0; envp_ext[i]; i++) {
462 			retval = add_uevent_var(env, "%s", envp_ext[i]);
463 			if (retval)
464 				goto exit;
465 		}
466 	}
467 
468 	/* let the kset specific function add its stuff */
469 	if (uevent_ops && uevent_ops->uevent) {
470 		retval = uevent_ops->uevent(kset, kobj, env);
471 		if (retval) {
472 			pr_debug("kobject: '%s' (%p): %s: uevent() returned "
473 				 "%d\n", kobject_name(kobj), kobj,
474 				 __func__, retval);
475 			goto exit;
476 		}
477 	}
478 
479 	switch (action) {
480 	case KOBJ_ADD:
481 		/*
482 		 * Mark "add" event so we can make sure we deliver "remove"
483 		 * event to userspace during automatic cleanup. If
484 		 * the object did send an "add" event, "remove" will
485 		 * automatically generated by the core, if not already done
486 		 * by the caller.
487 		 */
488 		kobj->state_add_uevent_sent = 1;
489 		break;
490 
491 	case KOBJ_REMOVE:
492 		kobj->state_remove_uevent_sent = 1;
493 		break;
494 
495 	case KOBJ_UNBIND:
496 		zap_modalias_env(env);
497 		break;
498 
499 	default:
500 		break;
501 	}
502 
503 	mutex_lock(&uevent_sock_mutex);
504 	/* we will send an event, so request a new sequence number */
505 	retval = add_uevent_var(env, "SEQNUM=%llu", (unsigned long long)++uevent_seqnum);
506 	if (retval) {
507 		mutex_unlock(&uevent_sock_mutex);
508 		goto exit;
509 	}
510 	retval = kobject_uevent_net_broadcast(kobj, env, action_string,
511 					      devpath);
512 	mutex_unlock(&uevent_sock_mutex);
513 
514 #ifdef CONFIG_UEVENT_HELPER
515 	/* call uevent_helper, usually only enabled during early boot */
516 	if (uevent_helper[0] && !kobj_usermode_filter(kobj)) {
517 		struct subprocess_info *info;
518 
519 		retval = add_uevent_var(env, "HOME=/");
520 		if (retval)
521 			goto exit;
522 		retval = add_uevent_var(env,
523 					"PATH=/sbin:/bin:/usr/sbin:/usr/bin");
524 		if (retval)
525 			goto exit;
526 		retval = init_uevent_argv(env, subsystem);
527 		if (retval)
528 			goto exit;
529 
530 		retval = -ENOMEM;
531 		info = call_usermodehelper_setup(env->argv[0], env->argv,
532 						 env->envp, GFP_KERNEL,
533 						 NULL, cleanup_uevent_env, env);
534 		if (info) {
535 			retval = call_usermodehelper_exec(info, UMH_NO_WAIT);
536 			env = NULL;	/* freed by cleanup_uevent_env */
537 		}
538 	}
539 #endif
540 
541 exit:
542 	kfree(devpath);
543 	kfree(env);
544 	return retval;
545 }
546 EXPORT_SYMBOL_GPL(kobject_uevent_env);
547 
548 /**
549  * kobject_uevent - notify userspace by sending an uevent
550  *
551  * @kobj: struct kobject that the action is happening to
552  * @action: action that is happening
553  *
554  * Returns 0 if kobject_uevent() is completed with success or the
555  * corresponding error when it fails.
556  */
557 int kobject_uevent(struct kobject *kobj, enum kobject_action action)
558 {
559 	return kobject_uevent_env(kobj, action, NULL);
560 }
561 EXPORT_SYMBOL_GPL(kobject_uevent);
562 
563 /**
564  * add_uevent_var - add key value string to the environment buffer
565  * @env: environment buffer structure
566  * @format: printf format for the key=value pair
567  *
568  * Returns 0 if environment variable was added successfully or -ENOMEM
569  * if no space was available.
570  */
571 int add_uevent_var(struct kobj_uevent_env *env, const char *format, ...)
572 {
573 	va_list args;
574 	int len;
575 
576 	if (env->envp_idx >= ARRAY_SIZE(env->envp)) {
577 		WARN(1, KERN_ERR "add_uevent_var: too many keys\n");
578 		return -ENOMEM;
579 	}
580 
581 	va_start(args, format);
582 	len = vsnprintf(&env->buf[env->buflen],
583 			sizeof(env->buf) - env->buflen,
584 			format, args);
585 	va_end(args);
586 
587 	if (len >= (sizeof(env->buf) - env->buflen)) {
588 		WARN(1, KERN_ERR "add_uevent_var: buffer size too small\n");
589 		return -ENOMEM;
590 	}
591 
592 	env->envp[env->envp_idx++] = &env->buf[env->buflen];
593 	env->buflen += len + 1;
594 	return 0;
595 }
596 EXPORT_SYMBOL_GPL(add_uevent_var);
597 
598 #if defined(CONFIG_NET)
599 static int uevent_net_init(struct net *net)
600 {
601 	struct uevent_sock *ue_sk;
602 	struct netlink_kernel_cfg cfg = {
603 		.groups	= 1,
604 		.flags	= NL_CFG_F_NONROOT_RECV,
605 	};
606 
607 	ue_sk = kzalloc(sizeof(*ue_sk), GFP_KERNEL);
608 	if (!ue_sk)
609 		return -ENOMEM;
610 
611 	ue_sk->sk = netlink_kernel_create(net, NETLINK_KOBJECT_UEVENT, &cfg);
612 	if (!ue_sk->sk) {
613 		printk(KERN_ERR
614 		       "kobject_uevent: unable to create netlink socket!\n");
615 		kfree(ue_sk);
616 		return -ENODEV;
617 	}
618 	mutex_lock(&uevent_sock_mutex);
619 	list_add_tail(&ue_sk->list, &uevent_sock_list);
620 	mutex_unlock(&uevent_sock_mutex);
621 	return 0;
622 }
623 
624 static void uevent_net_exit(struct net *net)
625 {
626 	struct uevent_sock *ue_sk;
627 
628 	mutex_lock(&uevent_sock_mutex);
629 	list_for_each_entry(ue_sk, &uevent_sock_list, list) {
630 		if (sock_net(ue_sk->sk) == net)
631 			goto found;
632 	}
633 	mutex_unlock(&uevent_sock_mutex);
634 	return;
635 
636 found:
637 	list_del(&ue_sk->list);
638 	mutex_unlock(&uevent_sock_mutex);
639 
640 	netlink_kernel_release(ue_sk->sk);
641 	kfree(ue_sk);
642 }
643 
644 static struct pernet_operations uevent_net_ops = {
645 	.init	= uevent_net_init,
646 	.exit	= uevent_net_exit,
647 };
648 
649 static int __init kobject_uevent_init(void)
650 {
651 	return register_pernet_subsys(&uevent_net_ops);
652 }
653 
654 
655 postcore_initcall(kobject_uevent_init);
656 #endif
657