usermodehelper: Tidy up waiting
[safe/jmp/linux-2.6] / kernel / kmod.c
1 /*
2         kmod, the new module loader (replaces kerneld)
3         Kirk Petersen
4
5         Reorganized not to be a daemon by Adam Richter, with guidance
6         from Greg Zornetzer.
7
8         Modified to avoid chroot and file sharing problems.
9         Mikael Pettersson
10
11         Limit the concurrent number of kmod modprobes to catch loops from
12         "modprobe needs a service that is in a module".
13         Keith Owens <kaos@ocs.com.au> December 1999
14
15         Unblock all signals when we exec a usermode process.
16         Shuu Yamaguchi <shuu@wondernetworkresources.com> December 2000
17
18         call_usermodehelper wait flag, and remove exec_usermodehelper.
19         Rusty Russell <rusty@rustcorp.com.au>  Jan 2003
20 */
21 #include <linux/module.h>
22 #include <linux/sched.h>
23 #include <linux/syscalls.h>
24 #include <linux/unistd.h>
25 #include <linux/kmod.h>
26 #include <linux/slab.h>
27 #include <linux/mnt_namespace.h>
28 #include <linux/completion.h>
29 #include <linux/file.h>
30 #include <linux/workqueue.h>
31 #include <linux/security.h>
32 #include <linux/mount.h>
33 #include <linux/kernel.h>
34 #include <linux/init.h>
35 #include <linux/resource.h>
36 #include <asm/uaccess.h>
37
38 extern int max_threads;
39
40 static struct workqueue_struct *khelper_wq;
41
42 #ifdef CONFIG_KMOD
43
44 /*
45         modprobe_path is set via /proc/sys.
46 */
47 char modprobe_path[KMOD_PATH_LEN] = "/sbin/modprobe";
48
49 /**
50  * request_module - try to load a kernel module
51  * @fmt:     printf style format string for the name of the module
52  * @varargs: arguements as specified in the format string
53  *
54  * Load a module using the user mode module loader. The function returns
55  * zero on success or a negative errno code on failure. Note that a
56  * successful module load does not mean the module did not then unload
57  * and exit on an error of its own. Callers must check that the service
58  * they requested is now available not blindly invoke it.
59  *
60  * If module auto-loading support is disabled then this function
61  * becomes a no-operation.
62  */
63 int request_module(const char *fmt, ...)
64 {
65         va_list args;
66         char module_name[MODULE_NAME_LEN];
67         unsigned int max_modprobes;
68         int ret;
69         char *argv[] = { modprobe_path, "-q", "--", module_name, NULL };
70         static char *envp[] = { "HOME=/",
71                                 "TERM=linux",
72                                 "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
73                                 NULL };
74         static atomic_t kmod_concurrent = ATOMIC_INIT(0);
75 #define MAX_KMOD_CONCURRENT 50  /* Completely arbitrary value - KAO */
76         static int kmod_loop_msg;
77
78         va_start(args, fmt);
79         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
80         va_end(args);
81         if (ret >= MODULE_NAME_LEN)
82                 return -ENAMETOOLONG;
83
84         /* If modprobe needs a service that is in a module, we get a recursive
85          * loop.  Limit the number of running kmod threads to max_threads/2 or
86          * MAX_KMOD_CONCURRENT, whichever is the smaller.  A cleaner method
87          * would be to run the parents of this process, counting how many times
88          * kmod was invoked.  That would mean accessing the internals of the
89          * process tables to get the command line, proc_pid_cmdline is static
90          * and it is not worth changing the proc code just to handle this case. 
91          * KAO.
92          *
93          * "trace the ppid" is simple, but will fail if someone's
94          * parent exits.  I think this is as good as it gets. --RR
95          */
96         max_modprobes = min(max_threads/2, MAX_KMOD_CONCURRENT);
97         atomic_inc(&kmod_concurrent);
98         if (atomic_read(&kmod_concurrent) > max_modprobes) {
99                 /* We may be blaming an innocent here, but unlikely */
100                 if (kmod_loop_msg++ < 5)
101                         printk(KERN_ERR
102                                "request_module: runaway loop modprobe %s\n",
103                                module_name);
104                 atomic_dec(&kmod_concurrent);
105                 return -ENOMEM;
106         }
107
108         ret = call_usermodehelper(modprobe_path, argv, envp, 1);
109         atomic_dec(&kmod_concurrent);
110         return ret;
111 }
112 EXPORT_SYMBOL(request_module);
113 #endif /* CONFIG_KMOD */
114
115 struct subprocess_info {
116         struct work_struct work;
117         struct completion *complete;
118         char *path;
119         char **argv;
120         char **envp;
121         struct key *ring;
122         enum umh_wait wait;
123         int retval;
124         struct file *stdin;
125         void (*cleanup)(char **argv, char **envp);
126 };
127
128 /*
129  * This is the task which runs the usermode application
130  */
131 static int ____call_usermodehelper(void *data)
132 {
133         struct subprocess_info *sub_info = data;
134         struct key *new_session, *old_session;
135         int retval;
136
137         /* Unblock all signals and set the session keyring. */
138         new_session = key_get(sub_info->ring);
139         spin_lock_irq(&current->sighand->siglock);
140         old_session = __install_session_keyring(current, new_session);
141         flush_signal_handlers(current, 1);
142         sigemptyset(&current->blocked);
143         recalc_sigpending();
144         spin_unlock_irq(&current->sighand->siglock);
145
146         key_put(old_session);
147
148         /* Install input pipe when needed */
149         if (sub_info->stdin) {
150                 struct files_struct *f = current->files;
151                 struct fdtable *fdt;
152                 /* no races because files should be private here */
153                 sys_close(0);
154                 fd_install(0, sub_info->stdin);
155                 spin_lock(&f->file_lock);
156                 fdt = files_fdtable(f);
157                 FD_SET(0, fdt->open_fds);
158                 FD_CLR(0, fdt->close_on_exec);
159                 spin_unlock(&f->file_lock);
160
161                 /* and disallow core files too */
162                 current->signal->rlim[RLIMIT_CORE] = (struct rlimit){0, 0};
163         }
164
165         /* We can run anywhere, unlike our parent keventd(). */
166         set_cpus_allowed(current, CPU_MASK_ALL);
167
168         /*
169          * Our parent is keventd, which runs with elevated scheduling priority.
170          * Avoid propagating that into the userspace child.
171          */
172         set_user_nice(current, 0);
173
174         retval = -EPERM;
175         if (current->fs->root)
176                 retval = kernel_execve(sub_info->path,
177                                 sub_info->argv, sub_info->envp);
178
179         /* Exec failed? */
180         sub_info->retval = retval;
181         do_exit(0);
182 }
183
184 void call_usermodehelper_freeinfo(struct subprocess_info *info)
185 {
186         if (info->cleanup)
187                 (*info->cleanup)(info->argv, info->envp);
188         kfree(info);
189 }
190 EXPORT_SYMBOL(call_usermodehelper_freeinfo);
191
192 /* Keventd can't block, but this (a child) can. */
193 static int wait_for_helper(void *data)
194 {
195         struct subprocess_info *sub_info = data;
196         pid_t pid;
197
198         /* Install a handler: if SIGCLD isn't handled sys_wait4 won't
199          * populate the status, but will return -ECHILD. */
200         allow_signal(SIGCHLD);
201
202         pid = kernel_thread(____call_usermodehelper, sub_info, SIGCHLD);
203         if (pid < 0) {
204                 sub_info->retval = pid;
205         } else {
206                 int ret;
207
208                 /*
209                  * Normally it is bogus to call wait4() from in-kernel because
210                  * wait4() wants to write the exit code to a userspace address.
211                  * But wait_for_helper() always runs as keventd, and put_user()
212                  * to a kernel address works OK for kernel threads, due to their
213                  * having an mm_segment_t which spans the entire address space.
214                  *
215                  * Thus the __user pointer cast is valid here.
216                  */
217                 sys_wait4(pid, (int __user *)&ret, 0, NULL);
218
219                 /*
220                  * If ret is 0, either ____call_usermodehelper failed and the
221                  * real error code is already in sub_info->retval or
222                  * sub_info->retval is 0 anyway, so don't mess with it then.
223                  */
224                 if (ret)
225                         sub_info->retval = ret;
226         }
227
228         if (sub_info->wait == UMH_NO_WAIT)
229                 call_usermodehelper_freeinfo(sub_info);
230         else
231                 complete(sub_info->complete);
232         return 0;
233 }
234
235 /* This is run by khelper thread  */
236 static void __call_usermodehelper(struct work_struct *work)
237 {
238         struct subprocess_info *sub_info =
239                 container_of(work, struct subprocess_info, work);
240         pid_t pid;
241         enum umh_wait wait = sub_info->wait;
242
243         /* CLONE_VFORK: wait until the usermode helper has execve'd
244          * successfully We need the data structures to stay around
245          * until that is done.  */
246         if (wait == UMH_WAIT_PROC || wait == UMH_NO_WAIT)
247                 pid = kernel_thread(wait_for_helper, sub_info,
248                                     CLONE_FS | CLONE_FILES | SIGCHLD);
249         else
250                 pid = kernel_thread(____call_usermodehelper, sub_info,
251                                     CLONE_VFORK | SIGCHLD);
252
253         switch (wait) {
254         case UMH_NO_WAIT:
255                 break;
256
257         case UMH_WAIT_PROC:
258                 if (pid > 0)
259                         break;
260                 sub_info->retval = pid;
261                 /* FALLTHROUGH */
262
263         case UMH_WAIT_EXEC:
264                 complete(sub_info->complete);
265         }
266 }
267
268 /**
269  * call_usermodehelper_setup - prepare to call a usermode helper
270  * @path - path to usermode executable
271  * @argv - arg vector for process
272  * @envp - environment for process
273  *
274  * Returns either NULL on allocation failure, or a subprocess_info
275  * structure.  This should be passed to call_usermodehelper_exec to
276  * exec the process and free the structure.
277  */
278 struct subprocess_info *call_usermodehelper_setup(char *path,
279                                                   char **argv, char **envp)
280 {
281         struct subprocess_info *sub_info;
282         sub_info = kzalloc(sizeof(struct subprocess_info),  GFP_ATOMIC);
283         if (!sub_info)
284                 goto out;
285
286         INIT_WORK(&sub_info->work, __call_usermodehelper);
287         sub_info->path = path;
288         sub_info->argv = argv;
289         sub_info->envp = envp;
290
291   out:
292         return sub_info;
293 }
294 EXPORT_SYMBOL(call_usermodehelper_setup);
295
296 /**
297  * call_usermodehelper_setkeys - set the session keys for usermode helper
298  * @info: a subprocess_info returned by call_usermodehelper_setup
299  * @session_keyring: the session keyring for the process
300  */
301 void call_usermodehelper_setkeys(struct subprocess_info *info,
302                                  struct key *session_keyring)
303 {
304         info->ring = session_keyring;
305 }
306 EXPORT_SYMBOL(call_usermodehelper_setkeys);
307
308 /**
309  * call_usermodehelper_setcleanup - set a cleanup function
310  * @info: a subprocess_info returned by call_usermodehelper_setup
311  * @cleanup: a cleanup function
312  *
313  * The cleanup function is just befor ethe subprocess_info is about to
314  * be freed.  This can be used for freeing the argv and envp.  The
315  * Function must be runnable in either a process context or the
316  * context in which call_usermodehelper_exec is called.
317  */
318 void call_usermodehelper_setcleanup(struct subprocess_info *info,
319                                     void (*cleanup)(char **argv, char **envp))
320 {
321         info->cleanup = cleanup;
322 }
323 EXPORT_SYMBOL(call_usermodehelper_setcleanup);
324
325 /**
326  * call_usermodehelper_stdinpipe - set up a pipe to be used for stdin
327  * @sub_info: a subprocess_info returned by call_usermodehelper_setup
328  * @filp: set to the write-end of a pipe
329  *
330  * This constructs a pipe, and sets the read end to be the stdin of the
331  * subprocess, and returns the write-end in *@filp.
332  */
333 int call_usermodehelper_stdinpipe(struct subprocess_info *sub_info,
334                                   struct file **filp)
335 {
336         struct file *f;
337
338         f = create_write_pipe();
339         if (IS_ERR(f))
340                 return PTR_ERR(f);
341         *filp = f;
342
343         f = create_read_pipe(f);
344         if (IS_ERR(f)) {
345                 free_write_pipe(*filp);
346                 return PTR_ERR(f);
347         }
348         sub_info->stdin = f;
349
350         return 0;
351 }
352 EXPORT_SYMBOL(call_usermodehelper_stdinpipe);
353
354 /**
355  * call_usermodehelper_exec - start a usermode application
356  * @sub_info: information about the subprocessa
357  * @wait: wait for the application to finish and return status.
358  *        when -1 don't wait at all, but you get no useful error back when
359  *        the program couldn't be exec'ed. This makes it safe to call
360  *        from interrupt context.
361  *
362  * Runs a user-space application.  The application is started
363  * asynchronously if wait is not set, and runs as a child of keventd.
364  * (ie. it runs with full root capabilities).
365  */
366 int call_usermodehelper_exec(struct subprocess_info *sub_info,
367                              enum umh_wait wait)
368 {
369         DECLARE_COMPLETION_ONSTACK(done);
370         int retval;
371
372         if (sub_info->path[0] == '\0') {
373                 retval = 0;
374                 goto out;
375         }
376
377         if (!khelper_wq) {
378                 retval = -EBUSY;
379                 goto out;
380         }
381
382         sub_info->complete = &done;
383         sub_info->wait = wait;
384
385         queue_work(khelper_wq, &sub_info->work);
386         if (wait == UMH_NO_WAIT) /* task has freed sub_info */
387                 return 0;
388         wait_for_completion(&done);
389         retval = sub_info->retval;
390
391   out:
392         call_usermodehelper_freeinfo(sub_info);
393         return retval;
394 }
395 EXPORT_SYMBOL(call_usermodehelper_exec);
396
397 /**
398  * call_usermodehelper_pipe - call a usermode helper process with a pipe stdin
399  * @path: path to usermode executable
400  * @argv: arg vector for process
401  * @envp: environment for process
402  * @filp: set to the write-end of a pipe
403  *
404  * This is a simple wrapper which executes a usermode-helper function
405  * with a pipe as stdin.  It is implemented entirely in terms of
406  * lower-level call_usermodehelper_* functions.
407  */
408 int call_usermodehelper_pipe(char *path, char **argv, char **envp,
409                              struct file **filp)
410 {
411         struct subprocess_info *sub_info;
412         int ret;
413
414         sub_info = call_usermodehelper_setup(path, argv, envp);
415         if (sub_info == NULL)
416                 return -ENOMEM;
417
418         ret = call_usermodehelper_stdinpipe(sub_info, filp);
419         if (ret < 0)
420                 goto out;
421
422         return call_usermodehelper_exec(sub_info, 1);
423
424   out:
425         call_usermodehelper_freeinfo(sub_info);
426         return ret;
427 }
428 EXPORT_SYMBOL(call_usermodehelper_pipe);
429
430 void __init usermodehelper_init(void)
431 {
432         khelper_wq = create_singlethread_workqueue("khelper");
433         BUG_ON(!khelper_wq);
434 }