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