explicitly include json/json.h where needed
[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/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_queue {
39         struct list_head list;
40
41         struct blob_attr *msg;
42         struct blob_attr *data;
43         void (*handler)(struct blob_attr *msg, struct blob_attr *data);
44 };
45
46 static LIST_HEAD(cmd_queue);
47 static struct uloop_process queue_proc;
48 static struct uloop_timeout last_event;
49 static struct blob_buf b;
50 static char *rule_file;
51 static struct blob_buf script;
52
53 static char *hotplug_msg_find_var(struct blob_attr *msg, const char *name)
54 {
55         struct blob_attr *cur;
56         int rem;
57
58         blobmsg_for_each_attr(cur, msg, rem) {
59                 if (blobmsg_type(cur) != BLOBMSG_TYPE_STRING)
60                         continue;
61
62                 if (strcmp(blobmsg_name(cur), name) != 0)
63                         continue;
64
65                 return blobmsg_data(cur);
66         }
67
68         return NULL;
69 }
70
71 static void mkdir_p(char *dir)
72 {
73         char *l = strrchr(dir, '/');
74
75         if (l) {
76                 *l = '\0';
77                 mkdir_p(dir);
78                 *l = '/';
79                 mkdir(dir, 0755);
80         }
81 }
82
83 static void handle_makedev(struct blob_attr *msg, struct blob_attr *data)
84 {
85         unsigned int oldumask = umask(0);
86         static struct blobmsg_policy mkdev_policy[2] = {
87                 { .type = BLOBMSG_TYPE_STRING },
88                 { .type = BLOBMSG_TYPE_STRING },
89         };
90         struct blob_attr *tb[2];
91         char *minor = hotplug_msg_find_var(msg, "MINOR");
92         char *major = hotplug_msg_find_var(msg, "MAJOR");
93         char *subsystem = hotplug_msg_find_var(msg, "SUBSYSTEM");
94
95         blobmsg_parse_array(mkdev_policy, 2, tb, blobmsg_data(data), blobmsg_data_len(data));
96         if (tb[0] && tb[1] && minor && major && subsystem) {
97                 mode_t m = S_IFCHR;
98                 char *d = strdup(blobmsg_get_string(tb[0]));
99
100                 d = dirname(d);
101                 mkdir_p(d);
102                 free(d);
103
104                 if (!strcmp(subsystem, "block"))
105                         m = S_IFBLK;
106                 mknod(blobmsg_get_string(tb[0]),
107                                 m | strtoul(blobmsg_data(tb[1]), NULL, 8),
108                                 makedev(atoi(major), atoi(minor)));
109         }
110         umask(oldumask);
111 }
112
113 static void handle_rm(struct blob_attr *msg, struct blob_attr *data)
114 {
115         static struct blobmsg_policy rm_policy = {
116                 .type = BLOBMSG_TYPE_STRING,
117         };
118         struct blob_attr *tb;
119
120         blobmsg_parse_array(&rm_policy, 1, &tb, blobmsg_data(data), blobmsg_data_len(data));
121         if (tb)
122                 unlink(blobmsg_data(tb));
123 }
124
125 static void handle_exec(struct blob_attr *msg, struct blob_attr *data)
126 {
127         char *argv[8];
128         struct blob_attr *cur;
129         int rem, fd;
130         int i = 0;
131
132         blobmsg_for_each_attr(cur, msg, rem)
133                 setenv(blobmsg_name(cur), blobmsg_data(cur), 1);
134
135         blobmsg_for_each_attr(cur, data, rem) {
136                 argv[i] = blobmsg_data(cur);
137                 i++;
138                 if (i == 7)
139                         break;
140         }
141
142         if (debug < 3) {
143                 fd = open("/dev/null", O_RDWR);
144                 if (fd > -1) {
145                         dup2(fd, STDIN_FILENO);
146                         dup2(fd, STDOUT_FILENO);
147                         dup2(fd, STDERR_FILENO);
148                         if (fd > STDERR_FILENO)
149                                 close(fd);
150                 }
151         }
152
153         if (i > 0) {
154                 argv[i] = NULL;
155                 execvp(argv[0], &argv[0]);
156         }
157         exit(-1);
158 }
159
160 static void handle_firmware(struct blob_attr *msg, struct blob_attr *data)
161 {
162         char *dir = blobmsg_get_string(blobmsg_data(data));
163         char *file = hotplug_msg_find_var(msg, "FIRMWARE");
164         char *dev = hotplug_msg_find_var(msg, "DEVPATH");
165         struct stat s = { 0 };
166         char *path, loadpath[256], syspath[256];
167         int fw, src, load, len;
168         static char buf[4096];
169
170         DEBUG(2, "Firmware request for %s/%s\n", dir, file);
171
172         if (!file || !dir || !dev) {
173                 ERROR("Request for unknown firmware %s/%s\n", dir, file);
174                 exit(-1);
175         }
176
177         path = alloca(strlen(dir) + strlen(file) + 2);
178         sprintf(path, "%s/%s", dir, file);
179
180         if (stat(path, &s)) {
181                 ERROR("Could not find firmware %s\n", path);
182                 src = -1;
183                 s.st_size = 0;
184                 goto send_to_kernel;
185         }
186
187         src = open(path, O_RDONLY);
188         if (src < 0) {
189                 ERROR("Failed to open %s\n", path);
190                 s.st_size = 0;
191                 goto send_to_kernel;
192         }
193
194 send_to_kernel:
195         snprintf(loadpath, sizeof(loadpath), "/sys/%s/loading", dev);
196         load = open(loadpath, O_WRONLY);
197         if (!load) {
198                 ERROR("Failed to open %s\n", loadpath);
199                 exit(-1);
200         }
201         write(load, "1", 1);
202         close(load);
203
204         snprintf(syspath, sizeof(syspath), "/sys/%s/data", dev);
205         fw = open(syspath, O_WRONLY);
206         if (fw < 0) {
207                 ERROR("Failed to open %s\n", syspath);
208                 exit(-1);
209         }
210
211         len = s.st_size;
212         while (len) {
213                 len = read(src, buf, sizeof(buf));
214                 if (len <= 0)
215                         break;
216
217                 write(fw, buf, len);
218         }
219
220         if (src >= 0)
221                 close(src);
222         close(fw);
223
224         load = open(loadpath, O_WRONLY);
225         write(load, "0", 1);
226         close(load);
227
228         DEBUG(2, "Done loading %s\n", path);
229
230         exit(-1);
231 }
232
233 static struct cmd_handler {
234         char *name;
235         int atomic;
236         void (*handler)(struct blob_attr *msg, struct blob_attr *data);
237 } handlers[] = {
238         {
239                 .name = "makedev",
240                 .atomic = 1,
241                 .handler = handle_makedev,
242         }, {
243                 .name = "rm",
244                 .atomic = 1,
245                 .handler = handle_rm,
246         }, {
247                 .name = "exec",
248                 .handler = handle_exec,
249         }, {
250                 .name = "load-firmware",
251                 .handler = handle_firmware,
252         },
253 };
254
255 static void queue_next(void)
256 {
257         struct cmd_queue *c;
258
259         if (queue_proc.pending || list_empty(&cmd_queue))
260                 return;
261
262         c = list_first_entry(&cmd_queue, struct cmd_queue, list);
263
264         queue_proc.pid = fork();
265         if (!queue_proc.pid) {
266                 uloop_done();
267                 c->handler(c->msg, c->data);
268                 exit(0);
269         }
270
271         list_del(&c->list);
272         free(c);
273
274         if (queue_proc.pid <= 0) {
275                 queue_next();
276                 return;
277         }
278
279         uloop_process_add(&queue_proc);
280
281         DEBUG(4, "Launched hotplug exec instance, pid=%d\n", (int) queue_proc.pid);
282 }
283
284 static void queue_proc_cb(struct uloop_process *c, int ret)
285 {
286         DEBUG(4, "Finished hotplug exec instance, pid=%d\n", (int) c->pid);
287
288         queue_next();
289 }
290
291 static void queue_add(struct cmd_handler *h, struct blob_attr *msg, struct blob_attr *data)
292 {
293         struct cmd_queue *c = NULL;
294         struct blob_attr *_msg, *_data;
295
296         c = calloc_a(sizeof(struct cmd_queue),
297                 &_msg, blob_pad_len(msg),
298                 &_data, blob_pad_len(data),
299                 NULL);
300
301         c->msg = _msg;
302         c->data = _data;
303
304         if (!c)
305                 return;
306
307         memcpy(c->msg, msg, blob_pad_len(msg));
308         memcpy(c->data, data, blob_pad_len(data));
309         c->handler = h->handler;
310         list_add_tail(&c->list, &cmd_queue);
311         queue_next();
312 }
313
314 static const char* rule_handle_var(struct json_script_ctx *ctx, const char *name, struct blob_attr *vars)
315 {
316         const char *str, *sep;
317
318         if (!strcmp(name, "DEVICENAME") || !strcmp(name, "DEVNAME")) {
319                 str = json_script_find_var(ctx, vars, "DEVPATH");
320                 if (!str)
321                         return NULL;
322
323                 sep = strrchr(str, '/');
324                 if (sep)
325                         return sep + 1;
326
327                 return str;
328         }
329
330         return NULL;
331 }
332
333 static struct json_script_file *
334 rule_handle_file(struct json_script_ctx *ctx, const char *name)
335 {
336         json_object *obj;
337
338         obj = json_object_from_file((char*)name);
339         if (is_error(obj))
340                 return NULL;
341
342         blob_buf_init(&script, 0);
343         blobmsg_add_json_element(&script, "", obj);
344
345         return json_script_file_from_blobmsg(name, blob_data(script.head), blob_len(script.head));
346 }
347
348 static void rule_handle_command(struct json_script_ctx *ctx, const char *name,
349                                 struct blob_attr *data, struct blob_attr *vars)
350 {
351         struct blob_attr *cur;
352         int rem, i;
353
354         if (debug > 3) {
355                 DEBUG(4, "Command: %s", name);
356                 blobmsg_for_each_attr(cur, data, rem)
357                         DEBUG(4, " %s", (char *) blobmsg_data(cur));
358                 DEBUG(4, "\n");
359
360                 DEBUG(4, "Message:");
361                 blobmsg_for_each_attr(cur, vars, rem)
362                         DEBUG(4, " %s=%s", blobmsg_name(cur), (char *) blobmsg_data(cur));
363                 DEBUG(4, "\n");
364         }
365
366         for (i = 0; i < ARRAY_SIZE(handlers); i++)
367                 if (!strcmp(handlers[i].name, name)) {
368                         if (handlers[i].atomic)
369                                 handlers[i].handler(vars, data);
370                         else
371                                 queue_add(&handlers[i], vars, data);
372                         break;
373                 }
374
375         if (last_event.cb)
376                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
377 }
378
379 static void rule_handle_error(struct json_script_ctx *ctx, const char *msg,
380                                 struct blob_attr *context)
381 {
382         char *s;
383
384         s = blobmsg_format_json(context, false);
385         ERROR("ERROR: %s in block: %s\n", msg, s);
386         free(s);
387 }
388
389 static struct json_script_ctx jctx = {
390         .handle_var = rule_handle_var,
391         .handle_error = rule_handle_error,
392         .handle_command = rule_handle_command,
393         .handle_file = rule_handle_file,
394 };
395
396 static void hotplug_handler_debug(struct blob_attr *data)
397 {
398         char *str;
399
400         if (debug < 3)
401                 return;
402
403         str = blobmsg_format_json(data, true);
404         DEBUG(3, "%s\n", str);
405         free(str);
406 }
407
408 static void hotplug_handler(struct uloop_fd *u, unsigned int ev)
409 {
410         int i = 0;
411         static char buf[4096];
412         int len = recv(u->fd, buf, sizeof(buf), MSG_DONTWAIT);
413         void *index;
414         if (len < 1)
415                 return;
416
417         blob_buf_init(&b, 0);
418         index = blobmsg_open_table(&b, NULL);
419         while (i < len) {
420                 int l = strlen(buf + i) + 1;
421                 char *e = strstr(&buf[i], "=");
422
423                 if (e) {
424                         *e = '\0';
425                         blobmsg_add_string(&b, &buf[i], &e[1]);
426                 }
427                 i += l;
428         }
429         blobmsg_close_table(&b, index);
430         hotplug_handler_debug(b.head);
431         json_script_run(&jctx, rule_file, blob_data(b.head));
432 }
433
434 static struct uloop_fd hotplug_fd = {
435         .cb = hotplug_handler,
436 };
437
438 void hotplug_last_event(uloop_timeout_handler handler)
439 {
440         last_event.cb = handler;
441         if (handler)
442                 uloop_timeout_set(&last_event, HOTPLUG_WAIT);
443         else
444                 uloop_timeout_cancel(&last_event);
445 }
446
447 void hotplug(char *rules)
448 {
449         struct sockaddr_nl nls;
450         int nlbufsize = 512 * 1024;
451
452         rule_file = strdup(rules);
453         memset(&nls,0,sizeof(struct sockaddr_nl));
454         nls.nl_family = AF_NETLINK;
455         nls.nl_pid = getpid();
456         nls.nl_groups = -1;
457
458         if ((hotplug_fd.fd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT)) == -1) {
459                 ERROR("Failed to open hotplug socket: %s\n", strerror(errno));
460                 exit(1);
461         }
462         if (bind(hotplug_fd.fd, (void *)&nls, sizeof(struct sockaddr_nl))) {
463                 ERROR("Failed to bind hotplug socket: %s\n", strerror(errno));
464                 exit(1);
465         }
466
467         if (setsockopt(hotplug_fd.fd, SOL_SOCKET, SO_RCVBUFFORCE, &nlbufsize, sizeof(nlbufsize)))
468                 ERROR("Failed to resize receive buffer: %s\n", strerror(errno));
469
470         json_script_init(&jctx);
471         queue_proc.cb = queue_proc_cb;
472         uloop_fd_add(&hotplug_fd, ULOOP_READ);
473 }
474
475 int hotplug_run(char *rules)
476 {
477         uloop_init();
478         hotplug(rules);
479         uloop_run();
480
481         return 0;
482 }
483
484 void hotplug_shutdown(void)
485 {
486         uloop_fd_delete(&hotplug_fd);
487         close(hotplug_fd.fd);
488 }