procd: replace exit(-1) with exit(EXIT_FAILURE)
[oweals/procd.git] / plug / hotplug.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <sys/stat.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/sysmacros.h>
19
20 #include <linux/types.h>
21 #include <linux/netlink.h>
22
23 #include <libubox/blobmsg_json.h>
24 #include <libubox/json_script.h>
25 #include <libubox/uloop.h>
26 #include <json-c/json.h>
27
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <libgen.h>
33 #include <grp.h>
34
35 #include "../procd.h"
36
37 #include "hotplug.h"
38
39 #define HOTPLUG_WAIT    500
40
41 struct cmd_handler;
42 struct cmd_queue {
43         struct list_head list;
44
45         struct blob_attr *msg;
46         struct blob_attr *data;
47         int timeout;
48
49         void (*handler)(struct blob_attr *msg, struct blob_attr *data);
50         void (*start)(struct blob_attr *msg, struct blob_attr *data);
51         void (*complete)(struct blob_attr *msg, struct blob_attr *data, int ret);
52 };
53
54 struct button_timeout {
55         struct list_head list;
56         struct uloop_timeout timeout;
57         char *name;
58         int seen;
59         struct blob_attr *data;
60 };
61
62 static LIST_HEAD(cmd_queue);
63 static LIST_HEAD(button_timer);
64 static struct uloop_process queue_proc;
65 static struct uloop_timeout last_event;
66 static struct blob_buf b, button_buf;
67 static char *rule_file;
68 static struct blob_buf script;
69 static struct cmd_queue *current;
70
71 static void queue_add(struct cmd_handler *h, struct blob_attr *msg, struct blob_attr *data);
72 static void handle_button_complete(struct blob_attr *msg, struct blob_attr *data, int ret);
73
74 static void button_free(struct button_timeout *b)
75 {
76         uloop_timeout_cancel(&b->timeout);
77         list_del(&b->list);
78         free(b->data);
79         free(b->name);
80         free(b);
81 }
82
83 static void button_timeout_remove(char *button)
84 {
85         struct button_timeout *b, *c;
86
87         if (!list_empty(&button_timer)) list_for_each_entry_safe(b, c, &button_timer, list) {
88                 if (!strcmp(b->name, button))
89                         button_free(b);
90         }
91 }
92
93 static char *hotplug_msg_find_var(struct blob_attr *msg, const char *name)
94 {
95         struct blob_attr *cur;
96         int rem;
97
98         blobmsg_for_each_attr(cur, msg, rem) {
99                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
100                         continue;
101
102                 if (strcmp(blobmsg_name(cur), name) != 0)
103                         continue;
104
105                 return blobmsg_data(cur);
106         }
107
108         return NULL;
109 }
110
111 static void mkdir_p(char *dir)
112 {
113         char *l = strrchr(dir, '/');
114
115         if (l) {
116                 *l = '\0';
117                 mkdir_p(dir);
118                 *l = '/';
119                 mkdir(dir, 0755);
120         }
121 }
122
123 static void chgrp_error(const char *group, const char *target, const char *failed)
124 {
125         ERROR("cannot set group %s for %s (%s: %d)\n",
126                group, target, failed, errno);
127 }
128
129 static void chgrp_target(struct blob_attr *bgroup, struct blob_attr *btarget)
130 {
131         int ret = 0;
132         struct group *g = NULL;
133         const char *group = blobmsg_get_string(bgroup);
134         const char *target = blobmsg_get_string(btarget);
135
136         errno = 0;
137
138         g = getgrnam(group);
139         if (!g)
140                 return chgrp_error(group, target, "getgrnam");
141
142         ret = chown(target, 0, g->gr_gid);
143         if (ret < 0)
144                 return chgrp_error(group, target, "chown");
145 }
146
147 static void handle_makedev(struct blob_attr *msg, struct blob_attr *data)
148 {
149         unsigned int oldumask = umask(0);
150         static struct blobmsg_policy mkdev_policy[3] = {
151                 { .type = BLOBMSG_TYPE_STRING },
152                 { .type = BLOBMSG_TYPE_STRING },
153                 { .type = BLOBMSG_TYPE_STRING },
154         };
155         struct blob_attr *tb[3];
156         char *minor = hotplug_msg_find_var(msg, "MINOR");
157         char *major = hotplug_msg_find_var(msg, "MAJOR");
158         char *subsystem = hotplug_msg_find_var(msg, "SUBSYSTEM");
159
160         blobmsg_parse_array(mkdev_policy, 3, tb, blobmsg_data(data), blobmsg_data_len(data));
161         if (tb[0] && tb[1] && minor && major && subsystem) {
162                 mode_t m = S_IFCHR;
163                 char *d = strdup(blobmsg_get_string(tb[0]));
164
165                 d = dirname(d);
166                 mkdir_p(d);
167                 free(d);
168
169                 if (!strcmp(subsystem, "block"))
170                         m = S_IFBLK;
171                 mknod(blobmsg_get_string(tb[0]),
172                                 m | strtoul(blobmsg_data(tb[1]), NULL, 8),
173                                 makedev(atoi(major), atoi(minor)));
174                 if (tb[2])
175                         chgrp_target(tb[2], tb[0]);
176         }
177         umask(oldumask);
178 }
179
180 static void handle_rm(struct blob_attr *msg, struct blob_attr *data)
181 {
182         static struct blobmsg_policy rm_policy = {
183                 .type = BLOBMSG_TYPE_STRING,
184         };
185         struct blob_attr *tb;
186
187         blobmsg_parse_array(&rm_policy, 1, &tb, blobmsg_data(data), blobmsg_data_len(data));
188         if (tb)
189                 unlink(blobmsg_data(tb));
190 }
191
192 static void handle_exec(struct blob_attr *msg, struct blob_attr *data)
193 {
194         char *argv[8];
195         struct blob_attr *cur;
196         int rem, fd;
197         int i = 0;
198
199         blobmsg_for_each_attr(cur, msg, rem)
200                 setenv(blobmsg_name(cur), blobmsg_data(cur), 1);
201
202         blobmsg_for_each_attr(cur, data, rem) {
203                 argv[i] = blobmsg_data(cur);
204                 i++;
205                 if (i == 7)
206                         break;
207         }
208
209         if (debug < 3) {
210                 fd = open("/dev/null", O_RDWR);
211                 if (fd > -1) {
212                         dup2(fd, STDIN_FILENO);
213                         dup2(fd, STDOUT_FILENO);
214                         dup2(fd, STDERR_FILENO);
215                         if (fd > STDERR_FILENO)
216                                 close(fd);
217                 }
218         }
219
220         if (i > 0) {
221                 argv[i] = NULL;
222                 execvp(argv[0], &argv[0]);
223         }
224         exit(EXIT_FAILURE);
225 }
226
227 static void handle_button_start(struct blob_attr *msg, struct blob_attr *data)
228 {
229         char *button = hotplug_msg_find_var(msg, "BUTTON");
230
231         if (button)
232                 button_timeout_remove(button);
233 }
234
235 static void handle_firmware(struct blob_attr *msg, struct blob_attr *data)
236 {
237         char *dir = blobmsg_get_string(blobmsg_data(data));
238         char *file = hotplug_msg_find_var(msg, "FIRMWARE");
239         char *dev = hotplug_msg_find_var(msg, "DEVPATH");
240         struct stat s = { 0 };
241         char *path, loadpath[256], syspath[256];
242         int fw, src, load, len;
243         static char buf[4096];
244
245         DEBUG(2, "Firmware request for %s/%s\n", dir, file);
246
247         if (!file || !dir || !dev) {
248                 ERROR("Request for unknown firmware %s/%s\n", dir, file);
249                 exit(EXIT_FAILURE);
250         }
251
252         path = alloca(strlen(dir) + strlen(file) + 2);
253         sprintf(path, "%s/%s", dir, file);
254
255         if (stat(path, &s)) {
256                 ERROR("Could not find firmware %s: %m\n", path);
257                 src = -1;
258                 s.st_size = 0;
259                 goto send_to_kernel;
260         }
261
262         src = open(path, O_RDONLY);
263         if (src < 0) {
264                 ERROR("Failed to open %s: %m\n", path);
265                 s.st_size = 0;
266                 goto send_to_kernel;
267         }
268
269 send_to_kernel:
270         snprintf(loadpath, sizeof(loadpath), "/sys/%s/loading", dev);
271         load = open(loadpath, O_WRONLY);
272         if (!load) {
273                 ERROR("Failed to open %s: %m\n", loadpath);
274                 exit(EXIT_FAILURE);
275         }
276         if (write(load, "1", 1) == -1) {
277                 ERROR("Failed to write to %s: %m\n", loadpath);
278                 exit(EXIT_FAILURE);
279         }
280         close(load);
281
282         snprintf(syspath, sizeof(syspath), "/sys/%s/data", dev);
283         fw = open(syspath, O_WRONLY);
284         if (fw < 0) {
285                 ERROR("Failed to open %s: %m\n", syspath);
286                 exit(EXIT_FAILURE);
287         }
288
289         len = s.st_size;
290         while (len) {
291                 len = read(src, buf, sizeof(buf));
292                 if (len <= 0)
293                         break;
294
295                 if (write(fw, buf, len) == -1) {
296                         ERROR("failed to write firmware file %s/%s to %s: %m\n", dir, file, dev);
297                         break;
298                 }
299         }
300
301         if (src >= 0)
302                 close(src);
303         close(fw);
304
305         load = open(loadpath, O_WRONLY);
306         if (write(load, "0", 1) == -1)
307                 ERROR("failed to write to %s: %m\n", loadpath);
308         close(load);
309
310         DEBUG(2, "Done loading %s\n", path);
311
312         exit(EXIT_FAILURE);
313 }
314
315 static void handle_start_console(struct blob_attr *msg, struct blob_attr *data)
316 {
317         char *dev = blobmsg_get_string(blobmsg_data(data));
318
319         DEBUG(2, "Start console request for %s\n", dev);
320
321         procd_inittab_run("respawn");
322         procd_inittab_run("askfirst");
323
324         DEBUG(2, "Done starting console for %s\n", dev);
325
326         exit(EXIT_FAILURE);
327 }
328
329 enum {
330         HANDLER_MKDEV = 0,
331         HANDLER_RM,
332         HANDLER_EXEC,
333         HANDLER_BUTTON,
334         HANDLER_FW,
335         HANDLER_START_CONSOLE,
336 };
337
338 static struct cmd_handler {
339         char *name;
340         int atomic;
341         void (*handler)(struct blob_attr *msg, struct blob_attr *data);
342         void (*start)(struct blob_attr *msg, struct blob_attr *data);
343         void (*complete)(struct blob_attr *msg, struct blob_attr *data, int ret);
344 } handlers[] = {
345         [HANDLER_MKDEV] = {
346                 .name = "makedev",
347                 .atomic = 1,
348                 .handler = handle_makedev,
349         },
350         [HANDLER_RM] = {
351                 .name = "rm",
352                 .atomic = 1,
353                 .handler = handle_rm,
354         },
355         [HANDLER_EXEC] = {
356                 .name = "exec",
357                 .handler = handle_exec,
358         },
359         [HANDLER_BUTTON] = {
360                 .name = "button",
361                 .handler = handle_exec,
362                 .start = handle_button_start,
363                 .complete = handle_button_complete,
364         },
365         [HANDLER_FW] = {
366                 .name = "load-firmware",
367                 .handler = handle_firmware,
368         },
369         [HANDLER_START_CONSOLE] = {
370                 .name = "start-console",
371                 .handler = handle_start_console,
372         },
373 };
374
375 static void queue_next(void)
376 {
377         struct cmd_queue *c;
378
379         if (queue_proc.pending || list_empty(&cmd_queue))
380                 return;
381
382         c = list_first_entry(&cmd_queue, struct cmd_queue, list);
383
384         queue_proc.pid = fork();
385         if (!queue_proc.pid) {
386                 uloop_done();
387                 c->handler(c->msg, c->data);
388                 exit(0);
389         }
390         if (c->start)
391                 c->start(c->msg, c->data);
392         list_del(&c->list);
393         if (c->complete)
394                 current = c;
395         else
396                 free(c);
397         if (queue_proc.pid <= 0) {
398                 queue_next();
399                 return;
400         }
401
402         uloop_process_add(&queue_proc);
403
404         DEBUG(4, "Launched hotplug exec instance, pid=%d\n", (int) queue_proc.pid);
405 }
406
407 static void queue_proc_cb(struct uloop_process *c, int ret)
408 {
409         DEBUG(4, "Finished hotplug exec instance, pid=%d\n", (int) c->pid);
410
411         if (current) {
412                 current->complete(current->msg, current->data, ret);
413                 free(current);
414                 current = NULL;
415         }
416         queue_next();
417 }
418
419 static void queue_add(struct cmd_handler *h, struct blob_attr *msg, struct blob_attr *data)
420 {
421         struct cmd_queue *c = NULL;
422         struct blob_attr *_msg, *_data;
423
424         c = calloc_a(sizeof(struct cmd_queue),
425                 &_msg, blob_pad_len(msg),
426                 &_data, blob_pad_len(data),
427                 NULL);
428
429         if (!c)
430                 return;
431
432         c->msg = _msg;
433         c->data = _data;
434
435         memcpy(c->msg, msg, blob_pad_len(msg));
436         memcpy(c->data, data, blob_pad_len(data));
437         c->handler = h->handler;
438         c->complete = h->complete;
439         c->start = h->start;
440         list_add_tail(&c->list, &cmd_queue);
441         queue_next();
442 }
443
444 static void handle_button_timeout(struct uloop_timeout *t)
445 {
446         struct button_timeout *b;
447         char seen[16];
448
449         b = container_of(t, struct button_timeout, timeout);
450         blob_buf_init(&button_buf, 0);
451         blobmsg_add_string(&button_buf, "BUTTON", b->name);
452         blobmsg_add_string(&button_buf, "ACTION", "timeout");
453         snprintf(seen, sizeof(seen), "%d", b->seen);
454         blobmsg_add_string(&button_buf, "SEEN", seen);
455         queue_add(&handlers[HANDLER_EXEC], button_buf.head, b->data);
456         button_free(b);
457 }
458
459 static void handle_button_complete(struct blob_attr *msg, struct blob_attr *data, int ret)
460 {
461         char *name = hotplug_msg_find_var(msg, "BUTTON");
462         struct button_timeout *b;
463         int timeout = ret >> 8;
464
465         if (!timeout)
466                 return;
467
468         if (!name)
469                 return;
470
471         b = calloc(1, sizeof(*b));
472         if (!b)
473                 return;
474
475         b->data = malloc(blob_pad_len(data));
476         b->name = strdup(name);
477         b->seen = timeout;
478
479         memcpy(b->data, data, blob_pad_len(data));
480         b->timeout.cb = handle_button_timeout;
481
482         uloop_timeout_set(&b->timeout, timeout * 1000);
483         list_add(&b->list, &button_timer);
484 }
485
486 static const char* rule_handle_var(struct json_script_ctx *ctx, const char *name, struct blob_attr *vars)
487 {
488         const char *str, *sep;
489
490         if (!strcmp(name, "DEVICENAME") || !strcmp(name, "DEVNAME")) {
491                 str = json_script_find_var(ctx, vars, "DEVPATH");
492                 if (!str)
493                         return NULL;
494
495                 sep = strrchr(str, '/');
496                 if (sep)
497                         return sep + 1;
498
499                 return str;
500         }
501
502         return NULL;
503 }
504
505 static struct json_script_file *
506 rule_handle_file(struct json_script_ctx *ctx, const char *name)
507 {
508         json_object *obj;
509
510         obj = json_object_from_file((char*)name);
511         if (!obj)
512                 return NULL;
513
514         blob_buf_init(&script, 0);
515         blobmsg_add_json_element(&script, "", obj);
516
517         return json_script_file_from_blobmsg(name, blob_data(script.head), blob_len(script.head));
518 }
519
520 static void rule_handle_command(struct json_script_ctx *ctx, const char *name,
521                                 struct blob_attr *data, struct blob_attr *vars)
522 {
523         struct blob_attr *cur;
524         int rem, i;
525
526         if (debug > 3) {
527                 DEBUG(4, "Command: %s\n", name);
528                 blobmsg_for_each_attr(cur, data, rem)
529                         DEBUG(4, " %s\n", (char *) blobmsg_data(cur));
530
531                 DEBUG(4, "Message:\n");
532                 blobmsg_for_each_attr(cur, vars, rem)
533                         DEBUG(4, " %s=%s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
534         }
535
536         for (i = 0; i < ARRAY_SIZE(handlers); i++)
537                 if (!strcmp(handlers[i].name, name)) {
538                         if (handlers[i].atomic)
539                                 handlers[i].handler(vars, data);
540                         else
541                                 queue_add(&handlers[i], vars, data);
542                         break;
543                 }
544
545         if (last_event.cb)
546                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
547 }
548
549 static void rule_handle_error(struct json_script_ctx *ctx, const char *msg,
550                                 struct blob_attr *context)
551 {
552         char *s;
553
554         s = blobmsg_format_json(context, false);
555         ERROR("ERROR: %s in block: %s\n", msg, s);
556         free(s);
557 }
558
559 static struct json_script_ctx jctx = {
560         .handle_var = rule_handle_var,
561         .handle_error = rule_handle_error,
562         .handle_command = rule_handle_command,
563         .handle_file = rule_handle_file,
564 };
565
566 static void hotplug_handler_debug(struct blob_attr *data)
567 {
568         char *str;
569
570         if (debug < 3)
571                 return;
572
573         str = blobmsg_format_json(data, true);
574         DEBUG(3, "%s\n", str);
575         free(str);
576 }
577
578 static void hotplug_handler(struct uloop_fd *u, unsigned int ev)
579 {
580         int i = 0;
581         static char buf[4096];
582         int len = recv(u->fd, buf, sizeof(buf) - 1, MSG_DONTWAIT);
583         void *index;
584         if (len < 1)
585                 return;
586
587         buf[len] = '\0';
588
589         blob_buf_init(&b, 0);
590         index = blobmsg_open_table(&b, NULL);
591         while (i < len) {
592                 int l = strlen(buf + i) + 1;
593                 char *e = strstr(&buf[i], "=");
594
595                 if (e) {
596                         *e = '\0';
597                         blobmsg_add_string(&b, &buf[i], &e[1]);
598                 }
599                 i += l;
600         }
601         blobmsg_close_table(&b, index);
602         hotplug_handler_debug(b.head);
603         json_script_run(&jctx, rule_file, blob_data(b.head));
604 }
605
606 static struct uloop_fd hotplug_fd = {
607         .cb = hotplug_handler,
608 };
609
610 void hotplug_last_event(uloop_timeout_handler handler)
611 {
612         last_event.cb = handler;
613         if (handler)
614                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
615         else
616                 uloop_timeout_cancel(&last_event);
617 }
618
619 void hotplug(char *rules)
620 {
621         struct sockaddr_nl nls = {};
622         int nlbufsize = 512 * 1024;
623
624         rule_file = strdup(rules);
625         nls.nl_family = AF_NETLINK;
626         nls.nl_pid = getpid();
627         nls.nl_groups = -1;
628
629         if ((hotplug_fd.fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) == -1) {
630                 ERROR("Failed to open hotplug socket: %m\n");
631                 exit(1);
632         }
633         if (bind(hotplug_fd.fd, (void *)&nls, sizeof(struct sockaddr_nl))) {
634                 ERROR("Failed to bind hotplug socket: %m\n");
635                 exit(1);
636         }
637
638         if (setsockopt(hotplug_fd.fd, SOL_SOCKET, SO_RCVBUFFORCE, &nlbufsize, sizeof(nlbufsize)))
639                 ERROR("Failed to resize receive buffer: %m\n");
640
641         json_script_init(&jctx);
642         queue_proc.cb = queue_proc_cb;
643         uloop_fd_add(&hotplug_fd, ULOOP_READ);
644 }
645
646 int hotplug_run(char *rules)
647 {
648         uloop_init();
649         hotplug(rules);
650         uloop_run();
651
652         return 0;
653 }
654
655 void hotplug_shutdown(void)
656 {
657         uloop_fd_delete(&hotplug_fd);
658         close(hotplug_fd.fd);
659 }