Expose EARLY_PATH as cmake flag
[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, "BUTTON", b->name);
403         blobmsg_add_string(&button_buf, "ACTION", "timeout");
404         snprintf(seen, sizeof(seen), "%d", b->seen);
405         blobmsg_add_string(&button_buf, "SEEN", seen);
406         queue_add(&handlers[HANDLER_EXEC], button_buf.head, b->data);
407         button_free(b);
408 }
409
410 static void handle_button_complete(struct blob_attr *msg, struct blob_attr *data, int ret)
411 {
412         char *name = hotplug_msg_find_var(msg, "BUTTON");
413         struct button_timeout *b;
414         int timeout = ret >> 8;
415
416         if (!timeout)
417                 return;
418
419         b = malloc(sizeof(*b));
420         if (!b || !name)
421                 return;
422
423         memset(b, 0, sizeof(*b));
424
425         b->data = malloc(blob_pad_len(data));
426         b->name = strdup(name);
427         b->seen = timeout;
428
429         memcpy(b->data, data, blob_pad_len(data));
430         b->timeout.cb = handle_button_timeout;
431
432         uloop_timeout_set(&b->timeout, timeout * 1000);
433         list_add(&b->list, &button_timer);
434 }
435
436 static const char* rule_handle_var(struct json_script_ctx *ctx, const char *name, struct blob_attr *vars)
437 {
438         const char *str, *sep;
439
440         if (!strcmp(name, "DEVICENAME") || !strcmp(name, "DEVNAME")) {
441                 str = json_script_find_var(ctx, vars, "DEVPATH");
442                 if (!str)
443                         return NULL;
444
445                 sep = strrchr(str, '/');
446                 if (sep)
447                         return sep + 1;
448
449                 return str;
450         }
451
452         return NULL;
453 }
454
455 static struct json_script_file *
456 rule_handle_file(struct json_script_ctx *ctx, const char *name)
457 {
458         json_object *obj;
459
460         obj = json_object_from_file((char*)name);
461         if (!obj)
462                 return NULL;
463
464         blob_buf_init(&script, 0);
465         blobmsg_add_json_element(&script, "", obj);
466
467         return json_script_file_from_blobmsg(name, blob_data(script.head), blob_len(script.head));
468 }
469
470 static void rule_handle_command(struct json_script_ctx *ctx, const char *name,
471                                 struct blob_attr *data, struct blob_attr *vars)
472 {
473         struct blob_attr *cur;
474         int rem, i;
475
476         if (debug > 3) {
477                 DEBUG(4, "Command: %s", name);
478                 blobmsg_for_each_attr(cur, data, rem)
479                         DEBUG(4, " %s", (char *) blobmsg_data(cur));
480                 DEBUG(4, "\n");
481
482                 DEBUG(4, "Message:");
483                 blobmsg_for_each_attr(cur, vars, rem)
484                         DEBUG(4, " %s=%s", blobmsg_name(cur), (char *) blobmsg_data(cur));
485                 DEBUG(4, "\n");
486         }
487
488         for (i = 0; i < ARRAY_SIZE(handlers); i++)
489                 if (!strcmp(handlers[i].name, name)) {
490                         if (handlers[i].atomic)
491                                 handlers[i].handler(vars, data);
492                         else
493                                 queue_add(&handlers[i], vars, data);
494                         break;
495                 }
496
497         if (last_event.cb)
498                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
499 }
500
501 static void rule_handle_error(struct json_script_ctx *ctx, const char *msg,
502                                 struct blob_attr *context)
503 {
504         char *s;
505
506         s = blobmsg_format_json(context, false);
507         ERROR("ERROR: %s in block: %s\n", msg, s);
508         free(s);
509 }
510
511 static struct json_script_ctx jctx = {
512         .handle_var = rule_handle_var,
513         .handle_error = rule_handle_error,
514         .handle_command = rule_handle_command,
515         .handle_file = rule_handle_file,
516 };
517
518 static void hotplug_handler_debug(struct blob_attr *data)
519 {
520         char *str;
521
522         if (debug < 3)
523                 return;
524
525         str = blobmsg_format_json(data, true);
526         DEBUG(3, "%s\n", str);
527         free(str);
528 }
529
530 static void hotplug_handler(struct uloop_fd *u, unsigned int ev)
531 {
532         int i = 0;
533         static char buf[4096];
534         int len = recv(u->fd, buf, sizeof(buf), MSG_DONTWAIT);
535         void *index;
536         if (len < 1)
537                 return;
538
539         blob_buf_init(&b, 0);
540         index = blobmsg_open_table(&b, NULL);
541         while (i < len) {
542                 int l = strlen(buf + i) + 1;
543                 char *e = strstr(&buf[i], "=");
544
545                 if (e) {
546                         *e = '\0';
547                         blobmsg_add_string(&b, &buf[i], &e[1]);
548                 }
549                 i += l;
550         }
551         blobmsg_close_table(&b, index);
552         hotplug_handler_debug(b.head);
553         json_script_run(&jctx, rule_file, blob_data(b.head));
554 }
555
556 static struct uloop_fd hotplug_fd = {
557         .cb = hotplug_handler,
558 };
559
560 void hotplug_last_event(uloop_timeout_handler handler)
561 {
562         last_event.cb = handler;
563         if (handler)
564                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
565         else
566                 uloop_timeout_cancel(&last_event);
567 }
568
569 void hotplug(char *rules)
570 {
571         struct sockaddr_nl nls;
572         int nlbufsize = 512 * 1024;
573
574         rule_file = strdup(rules);
575         memset(&nls,0,sizeof(struct sockaddr_nl));
576         nls.nl_family = AF_NETLINK;
577         nls.nl_pid = getpid();
578         nls.nl_groups = -1;
579
580         if ((hotplug_fd.fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) == -1) {
581                 ERROR("Failed to open hotplug socket: %s\n", strerror(errno));
582                 exit(1);
583         }
584         if (bind(hotplug_fd.fd, (void *)&nls, sizeof(struct sockaddr_nl))) {
585                 ERROR("Failed to bind hotplug socket: %s\n", strerror(errno));
586                 exit(1);
587         }
588
589         if (setsockopt(hotplug_fd.fd, SOL_SOCKET, SO_RCVBUFFORCE, &nlbufsize, sizeof(nlbufsize)))
590                 ERROR("Failed to resize receive buffer: %s\n", strerror(errno));
591
592         json_script_init(&jctx);
593         queue_proc.cb = queue_proc_cb;
594         uloop_fd_add(&hotplug_fd, ULOOP_READ);
595 }
596
597 int hotplug_run(char *rules)
598 {
599         uloop_init();
600         hotplug(rules);
601         uloop_run();
602
603         return 0;
604 }
605
606 void hotplug_shutdown(void)
607 {
608         uloop_fd_delete(&hotplug_fd);
609         close(hotplug_fd.fd);
610 }