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