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