54cfbaeb3a4ebdc3bc304441a934435453ef4b1e
[sfrench/cifs-2.6.git] / lib / kobject_uevent.c
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  * Authors:
10  *      Robert Love             <rml@novell.com>
11  *      Kay Sievers             <kay.sievers@vrfy.org>
12  *      Arjan van de Ven        <arjanv@redhat.com>
13  *      Greg Kroah-Hartman      <greg@kroah.com>
14  */
15
16 #include <linux/spinlock.h>
17 #include <linux/string.h>
18 #include <linux/kobject.h>
19 #include <linux/export.h>
20 #include <linux/kmod.h>
21 #include <linux/slab.h>
22 #include <linux/socket.h>
23 #include <linux/skbuff.h>
24 #include <linux/netlink.h>
25 #include <linux/uuid.h>
26 #include <linux/ctype.h>
27 #include <net/sock.h>
28 #include <net/net_namespace.h>
29
30
31 u64 uevent_seqnum;
32 #ifdef CONFIG_UEVENT_HELPER
33 char uevent_helper[UEVENT_HELPER_PATH_LEN] = CONFIG_UEVENT_HELPER_PATH;
34 #endif
35
36 struct uevent_sock {
37         struct list_head list;
38         struct sock *sk;
39 };
40
41 #ifdef CONFIG_NET
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         size_t len;
351         int i, j;
352
353         for (i = 0; i < env->envp_idx;) {
354                 if (strncmp(env->envp[i], modalias_prefix,
355                             sizeof(modalias_prefix) - 1)) {
356                         i++;
357                         continue;
358                 }
359
360                 len = strlen(env->envp[i]) + 1;
361
362                 if (i != env->envp_idx - 1) {
363                         memmove(env->envp[i], env->envp[i + 1],
364                                 env->buflen - len);
365
366                         for (j = i; j < env->envp_idx - 1; j++)
367                                 env->envp[j] = env->envp[j + 1] - len;
368                 }
369
370                 env->envp_idx--;
371                 env->buflen -= len;
372         }
373 }
374
375 /**
376  * kobject_uevent_env - send an uevent with environmental data
377  *
378  * @kobj: struct kobject that the action is happening to
379  * @action: action that is happening
380  * @envp_ext: pointer to environmental data
381  *
382  * Returns 0 if kobject_uevent_env() is completed with success or the
383  * corresponding error when it fails.
384  */
385 int kobject_uevent_env(struct kobject *kobj, enum kobject_action action,
386                        char *envp_ext[])
387 {
388         struct kobj_uevent_env *env;
389         const char *action_string = kobject_actions[action];
390         const char *devpath = NULL;
391         const char *subsystem;
392         struct kobject *top_kobj;
393         struct kset *kset;
394         const struct kset_uevent_ops *uevent_ops;
395         int i = 0;
396         int retval = 0;
397
398         pr_debug("kobject: '%s' (%p): %s\n",
399                  kobject_name(kobj), kobj, __func__);
400
401         /* search the kset we belong to */
402         top_kobj = kobj;
403         while (!top_kobj->kset && top_kobj->parent)
404                 top_kobj = top_kobj->parent;
405
406         if (!top_kobj->kset) {
407                 pr_debug("kobject: '%s' (%p): %s: attempted to send uevent "
408                          "without kset!\n", kobject_name(kobj), kobj,
409                          __func__);
410                 return -EINVAL;
411         }
412
413         kset = top_kobj->kset;
414         uevent_ops = kset->uevent_ops;
415
416         /* skip the event, if uevent_suppress is set*/
417         if (kobj->uevent_suppress) {
418                 pr_debug("kobject: '%s' (%p): %s: uevent_suppress "
419                                  "caused the event to drop!\n",
420                                  kobject_name(kobj), kobj, __func__);
421                 return 0;
422         }
423         /* skip the event, if the filter returns zero. */
424         if (uevent_ops && uevent_ops->filter)
425                 if (!uevent_ops->filter(kset, kobj)) {
426                         pr_debug("kobject: '%s' (%p): %s: filter function "
427                                  "caused the event to drop!\n",
428                                  kobject_name(kobj), kobj, __func__);
429                         return 0;
430                 }
431
432         /* originating subsystem */
433         if (uevent_ops && uevent_ops->name)
434                 subsystem = uevent_ops->name(kset, kobj);
435         else
436                 subsystem = kobject_name(&kset->kobj);
437         if (!subsystem) {
438                 pr_debug("kobject: '%s' (%p): %s: unset subsystem caused the "
439                          "event to drop!\n", kobject_name(kobj), kobj,
440                          __func__);
441                 return 0;
442         }
443
444         /* environment buffer */
445         env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
446         if (!env)
447                 return -ENOMEM;
448
449         /* complete object path */
450         devpath = kobject_get_path(kobj, GFP_KERNEL);
451         if (!devpath) {
452                 retval = -ENOENT;
453                 goto exit;
454         }
455
456         /* default keys */
457         retval = add_uevent_var(env, "ACTION=%s", action_string);
458         if (retval)
459                 goto exit;
460         retval = add_uevent_var(env, "DEVPATH=%s", devpath);
461         if (retval)
462                 goto exit;
463         retval = add_uevent_var(env, "SUBSYSTEM=%s", subsystem);
464         if (retval)
465                 goto exit;
466
467         /* keys passed in from the caller */
468         if (envp_ext) {
469                 for (i = 0; envp_ext[i]; i++) {
470                         retval = add_uevent_var(env, "%s", envp_ext[i]);
471                         if (retval)
472                                 goto exit;
473                 }
474         }
475
476         /* let the kset specific function add its stuff */
477         if (uevent_ops && uevent_ops->uevent) {
478                 retval = uevent_ops->uevent(kset, kobj, env);
479                 if (retval) {
480                         pr_debug("kobject: '%s' (%p): %s: uevent() returned "
481                                  "%d\n", kobject_name(kobj), kobj,
482                                  __func__, retval);
483                         goto exit;
484                 }
485         }
486
487         switch (action) {
488         case KOBJ_ADD:
489                 /*
490                  * Mark "add" event so we can make sure we deliver "remove"
491                  * event to userspace during automatic cleanup. If
492                  * the object did send an "add" event, "remove" will
493                  * automatically generated by the core, if not already done
494                  * by the caller.
495                  */
496                 kobj->state_add_uevent_sent = 1;
497                 break;
498
499         case KOBJ_REMOVE:
500                 kobj->state_remove_uevent_sent = 1;
501                 break;
502
503         case KOBJ_UNBIND:
504                 zap_modalias_env(env);
505                 break;
506
507         default:
508                 break;
509         }
510
511         mutex_lock(&uevent_sock_mutex);
512         /* we will send an event, so request a new sequence number */
513         retval = add_uevent_var(env, "SEQNUM=%llu", (unsigned long long)++uevent_seqnum);
514         if (retval) {
515                 mutex_unlock(&uevent_sock_mutex);
516                 goto exit;
517         }
518         retval = kobject_uevent_net_broadcast(kobj, env, action_string,
519                                               devpath);
520         mutex_unlock(&uevent_sock_mutex);
521
522 #ifdef CONFIG_UEVENT_HELPER
523         /* call uevent_helper, usually only enabled during early boot */
524         if (uevent_helper[0] && !kobj_usermode_filter(kobj)) {
525                 struct subprocess_info *info;
526
527                 retval = add_uevent_var(env, "HOME=/");
528                 if (retval)
529                         goto exit;
530                 retval = add_uevent_var(env,
531                                         "PATH=/sbin:/bin:/usr/sbin:/usr/bin");
532                 if (retval)
533                         goto exit;
534                 retval = init_uevent_argv(env, subsystem);
535                 if (retval)
536                         goto exit;
537
538                 retval = -ENOMEM;
539                 info = call_usermodehelper_setup(env->argv[0], env->argv,
540                                                  env->envp, GFP_KERNEL,
541                                                  NULL, cleanup_uevent_env, env);
542                 if (info) {
543                         retval = call_usermodehelper_exec(info, UMH_NO_WAIT);
544                         env = NULL;     /* freed by cleanup_uevent_env */
545                 }
546         }
547 #endif
548
549 exit:
550         kfree(devpath);
551         kfree(env);
552         return retval;
553 }
554 EXPORT_SYMBOL_GPL(kobject_uevent_env);
555
556 /**
557  * kobject_uevent - notify userspace by sending an uevent
558  *
559  * @kobj: struct kobject that the action is happening to
560  * @action: action that is happening
561  *
562  * Returns 0 if kobject_uevent() is completed with success or the
563  * corresponding error when it fails.
564  */
565 int kobject_uevent(struct kobject *kobj, enum kobject_action action)
566 {
567         return kobject_uevent_env(kobj, action, NULL);
568 }
569 EXPORT_SYMBOL_GPL(kobject_uevent);
570
571 /**
572  * add_uevent_var - add key value string to the environment buffer
573  * @env: environment buffer structure
574  * @format: printf format for the key=value pair
575  *
576  * Returns 0 if environment variable was added successfully or -ENOMEM
577  * if no space was available.
578  */
579 int add_uevent_var(struct kobj_uevent_env *env, const char *format, ...)
580 {
581         va_list args;
582         int len;
583
584         if (env->envp_idx >= ARRAY_SIZE(env->envp)) {
585                 WARN(1, KERN_ERR "add_uevent_var: too many keys\n");
586                 return -ENOMEM;
587         }
588
589         va_start(args, format);
590         len = vsnprintf(&env->buf[env->buflen],
591                         sizeof(env->buf) - env->buflen,
592                         format, args);
593         va_end(args);
594
595         if (len >= (sizeof(env->buf) - env->buflen)) {
596                 WARN(1, KERN_ERR "add_uevent_var: buffer size too small\n");
597                 return -ENOMEM;
598         }
599
600         env->envp[env->envp_idx++] = &env->buf[env->buflen];
601         env->buflen += len + 1;
602         return 0;
603 }
604 EXPORT_SYMBOL_GPL(add_uevent_var);
605
606 #if defined(CONFIG_NET)
607 static int uevent_net_init(struct net *net)
608 {
609         struct uevent_sock *ue_sk;
610         struct netlink_kernel_cfg cfg = {
611                 .groups = 1,
612                 .flags  = NL_CFG_F_NONROOT_RECV,
613         };
614
615         ue_sk = kzalloc(sizeof(*ue_sk), GFP_KERNEL);
616         if (!ue_sk)
617                 return -ENOMEM;
618
619         ue_sk->sk = netlink_kernel_create(net, NETLINK_KOBJECT_UEVENT, &cfg);
620         if (!ue_sk->sk) {
621                 printk(KERN_ERR
622                        "kobject_uevent: unable to create netlink socket!\n");
623                 kfree(ue_sk);
624                 return -ENODEV;
625         }
626
627         net->uevent_sock = ue_sk;
628
629         mutex_lock(&uevent_sock_mutex);
630         list_add_tail(&ue_sk->list, &uevent_sock_list);
631         mutex_unlock(&uevent_sock_mutex);
632         return 0;
633 }
634
635 static void uevent_net_exit(struct net *net)
636 {
637         struct uevent_sock *ue_sk = net->uevent_sock;
638
639         mutex_lock(&uevent_sock_mutex);
640         list_del(&ue_sk->list);
641         mutex_unlock(&uevent_sock_mutex);
642
643         netlink_kernel_release(ue_sk->sk);
644         kfree(ue_sk);
645 }
646
647 static struct pernet_operations uevent_net_ops = {
648         .init   = uevent_net_init,
649         .exit   = uevent_net_exit,
650         .async  = true,
651 };
652
653 static int __init kobject_uevent_init(void)
654 {
655         return register_pernet_subsys(&uevent_net_ops);
656 }
657
658
659 postcore_initcall(kobject_uevent_init);
660 #endif