Use autoclear for overlay loopback device
[oweals/fstools.git] / blockd.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <sys/mount.h>
4 #include <sys/wait.h>
5
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10
11 #include <errno.h>
12
13 #include <linux/limits.h>
14 #include <linux/auto_fs4.h>
15
16 #include <libubox/uloop.h>
17 #include <libubox/vlist.h>
18 #include <libubox/ulog.h>
19 #include <libubox/avl-cmp.h>
20 #include <libubus.h>
21
22 #include "libfstools/libfstools.h"
23
24 #define AUTOFS_MOUNT_PATH       "/tmp/run/blockd/"
25 #define AUTOFS_TIMEOUT          30
26 #define AUTOFS_EXPIRE_TIMER     (5 * 1000)
27
28 struct hotplug_context {
29         struct uloop_process process;
30         void *priv;
31 };
32
33 struct device {
34         struct vlist_node node;
35         struct blob_attr *msg;
36         char *name;
37         char *target;
38         int autofs;
39         int anon;
40 };
41
42 static struct uloop_fd fd_autofs_read;
43 static int fd_autofs_write = 0;
44 static struct ubus_auto_conn conn;
45 struct blob_buf bb = { 0 };
46
47 enum {
48         MOUNT_UUID,
49         MOUNT_LABEL,
50         MOUNT_ENABLE,
51         MOUNT_TARGET,
52         MOUNT_DEVICE,
53         MOUNT_OPTIONS,
54         MOUNT_AUTOFS,
55         MOUNT_ANON,
56         MOUNT_REMOVE,
57         __MOUNT_MAX
58 };
59
60 static const struct blobmsg_policy mount_policy[__MOUNT_MAX] = {
61         [MOUNT_UUID] = { .name = "uuid", .type = BLOBMSG_TYPE_STRING },
62         [MOUNT_LABEL] = { .name = "label", .type = BLOBMSG_TYPE_STRING },
63         [MOUNT_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
64         [MOUNT_TARGET] = { .name = "target", .type = BLOBMSG_TYPE_STRING },
65         [MOUNT_OPTIONS] = { .name = "options", .type = BLOBMSG_TYPE_STRING },
66         [MOUNT_ENABLE] = { .name = "enabled", .type = BLOBMSG_TYPE_INT32 },
67         [MOUNT_AUTOFS] = { .name = "autofs", .type = BLOBMSG_TYPE_INT32 },
68         [MOUNT_ANON] = { .name = "anon", .type = BLOBMSG_TYPE_INT32 },
69         [MOUNT_REMOVE] = { .name = "remove", .type = BLOBMSG_TYPE_INT32 },
70 };
71
72 enum {
73         INFO_DEVICE,
74         __INFO_MAX
75 };
76
77 static const struct blobmsg_policy info_policy[__INFO_MAX] = {
78         [INFO_DEVICE] = { .name = "device", .type = BLOBMSG_TYPE_STRING },
79 };
80
81 static char*
82 _find_mount_point(char *device)
83 {
84         char dev[32] = { 0 };
85
86         snprintf(dev, sizeof(dev), "/dev/%s", device);
87
88         return find_mount_point(dev, 0);
89 }
90
91 static int
92 block(char *cmd, char *action, char *device)
93 {
94         pid_t pid = fork();
95         int ret = -1;
96         int status;
97         char *argv[5] = { 0 };
98         int a = 0;
99
100         switch (pid) {
101         case -1:
102                 ULOG_ERR("failed to fork block process\n");
103                 break;
104
105         case 0:
106                 argv[a++] = "/sbin/block";
107                 argv[a++] = cmd;
108                 argv[a++] = action;
109                 argv[a++] = device;
110                 execvp(argv[0], argv);
111                 ULOG_ERR("failed to spawn %s %s %s\n", *argv, action, device);
112                 exit(EXIT_FAILURE);
113
114         default:
115                 waitpid(pid, &status, 0);
116                 ret = WEXITSTATUS(status);
117                 if (ret)
118                         ULOG_ERR("failed to run block. %s/%s\n", action, device);
119                 break;
120         }
121
122         return ret;
123 }
124
125 static int hotplug_call_mount(const char *action, const char *devname,
126                               uloop_process_handler cb, void *priv)
127 {
128         char * const argv[] = { "hotplug-call", "mount", NULL };
129         struct hotplug_context *c = NULL;
130         pid_t pid;
131         int err;
132
133         if (cb) {
134                 c = calloc(1, sizeof(*c));
135                 if (!c)
136                         return -ENOMEM;
137         }
138
139         pid = fork();
140         switch (pid) {
141         case -1:
142                 err = -errno;
143                 ULOG_ERR("fork() failed\n");
144                 return err;
145         case 0:
146                 uloop_end();
147
148                 setenv("ACTION", action, 1);
149                 setenv("DEVICE", devname, 1);
150
151                 execv("/sbin/hotplug-call", argv);
152                 exit(-1);
153                 break;
154         default:
155                 if (c) {
156                         c->process.pid = pid;
157                         c->process.cb = cb;
158                         c->priv = priv;
159                         uloop_process_add(&c->process);
160                 }
161                 break;
162         }
163
164         return 0;
165 }
166
167 static void device_mount_remove_hotplug_cb(struct uloop_process *p, int stat)
168 {
169         struct hotplug_context *hctx = container_of(p, struct hotplug_context, process);
170         struct device *device = hctx->priv;
171         char *mp;
172
173         if (device->target)
174                 unlink(device->target);
175
176         mp = _find_mount_point(device->name);
177         if (mp) {
178                 block("autofs", "remove", device->name);
179                 free(mp);
180         }
181
182         free(device);
183         free(hctx);
184 }
185
186 static void device_mount_remove(struct device *device)
187 {
188         hotplug_call_mount("remove", device->name,
189                            device_mount_remove_hotplug_cb, device);
190 }
191
192 static void device_mount_add(struct device *device)
193 {
194         struct stat st;
195         char path[64];
196
197         snprintf(path, sizeof(path), "/tmp/run/blockd/%s", device->name);
198         if (!lstat(device->target, &st)) {
199                 if (S_ISLNK(st.st_mode))
200                         unlink(device->target);
201                 else if (S_ISDIR(st.st_mode))
202                         rmdir(device->target);
203         }
204         if (symlink(path, device->target))
205                 ULOG_ERR("failed to symlink %s->%s (%d) - %m\n", device->target, path, errno);
206         else
207                 hotplug_call_mount("add", device->name, NULL, NULL);
208 }
209
210 static int
211 device_move(struct device *device_o, struct device *device_n)
212 {
213         char path[64];
214
215         if (device_o->autofs != device_n->autofs)
216                 return -1;
217
218         if (device_o->anon || device_n->anon)
219                 return -1;
220
221         if (device_o->autofs) {
222                 unlink(device_o->target);
223                 snprintf(path, sizeof(path), "/tmp/run/blockd/%s", device_n->name);
224                 if (symlink(path, device_n->target))
225                         ULOG_ERR("failed to symlink %s->%s (%d) - %m\n", device_n->target, path, errno);
226         } else {
227                 mkdir(device_n->target, 0755);
228                 if (mount(device_o->target, device_n->target, NULL, MS_MOVE, NULL))
229                         rmdir(device_n->target);
230                 else
231                         rmdir(device_o->target);
232         }
233
234         return 0;
235 }
236
237 static void vlist_nop_update(struct vlist_tree *tree,
238                              struct vlist_node *node_new,
239                              struct vlist_node *node_old)
240 {
241 }
242
243 VLIST_TREE(devices, avl_strcmp, vlist_nop_update, false, false);
244
245 static int
246 block_hotplug(struct ubus_context *ctx, struct ubus_object *obj,
247               struct ubus_request_data *req, const char *method,
248               struct blob_attr *msg)
249 {
250         struct blob_attr *data[__MOUNT_MAX];
251         struct device *device;
252         struct blob_attr *_msg;
253         char *devname, *_name;
254         char *target = NULL, *__target;
255         char _target[32];
256
257         blobmsg_parse(mount_policy, __MOUNT_MAX, data, blob_data(msg), blob_len(msg));
258
259         if (!data[MOUNT_DEVICE])
260                 return UBUS_STATUS_INVALID_ARGUMENT;
261
262         devname = blobmsg_get_string(data[MOUNT_DEVICE]);
263
264         if (data[MOUNT_TARGET]) {
265                 target = blobmsg_get_string(data[MOUNT_TARGET]);
266         } else {
267                 snprintf(_target, sizeof(_target), "/mnt/%s",
268                          blobmsg_get_string(data[MOUNT_DEVICE]));
269                 target = _target;
270         }
271
272         if (data[MOUNT_REMOVE])
273                 device = vlist_find(&devices, devname, device, node);
274         else
275                 device = calloc_a(sizeof(*device), &_msg, blob_raw_len(msg),
276                                   &_name, strlen(devname) + 1, &__target, strlen(target) + 1);
277
278         if (!device)
279                 return UBUS_STATUS_UNKNOWN_ERROR;
280
281         if (data[MOUNT_REMOVE]) {
282                 vlist_delete(&devices, &device->node);
283
284                 if (device->autofs)
285                         device_mount_remove(device);
286                 else
287                         free(device);
288         } else {
289                 struct device *old = vlist_find(&devices, devname, device, node);
290
291                 device->autofs = data[MOUNT_AUTOFS] ? blobmsg_get_u32(data[MOUNT_AUTOFS]) : 0;
292                 device->anon = data[MOUNT_ANON] ? blobmsg_get_u32(data[MOUNT_ANON]) : 0;
293                 device->msg = _msg;
294                 memcpy(_msg, msg, blob_raw_len(msg));
295                 device->name = _name;
296                 strcpy(_name, devname);
297                 device->target = __target;
298                 strcpy(__target, target);
299
300                 vlist_add(&devices, &device->node, device->name);
301
302                 if (old && !device_move(old, device)) {
303                         if (device->autofs) {
304                                 device_mount_remove(old);
305                                 device_mount_add(device);
306                         } else {
307                                 block("mount", NULL, NULL);
308                         }
309                 } else if (device->autofs) {
310                         device_mount_add(device);
311                 }
312         }
313
314         return 0;
315 }
316
317 static int blockd_mount(struct ubus_context *ctx, struct ubus_object *obj,
318                         struct ubus_request_data *req, const char *method,
319                         struct blob_attr *msg)
320 {
321         struct blob_attr *data[__MOUNT_MAX];
322         struct device *device;
323         char *devname;
324
325         blobmsg_parse(mount_policy, __MOUNT_MAX, data, blob_data(msg), blob_len(msg));
326
327         if (!data[MOUNT_DEVICE])
328                 return UBUS_STATUS_INVALID_ARGUMENT;
329
330         devname = blobmsg_get_string(data[MOUNT_DEVICE]);
331
332         device = vlist_find(&devices, devname, device, node);
333         if (!device)
334                 return UBUS_STATUS_UNKNOWN_ERROR;
335
336         hotplug_call_mount("add", device->name, NULL, NULL);
337
338         return 0;
339 }
340
341 struct blockd_umount_context {
342         struct ubus_context *ctx;
343         struct ubus_request_data req;
344 };
345
346 static void blockd_umount_hotplug_cb(struct uloop_process *p, int stat)
347 {
348         struct hotplug_context *hctx = container_of(p, struct hotplug_context, process);
349         struct blockd_umount_context *c = hctx->priv;
350
351         ubus_complete_deferred_request(c->ctx, &c->req, 0);
352
353         free(c);
354         free(hctx);
355 }
356
357 static int blockd_umount(struct ubus_context *ctx, struct ubus_object *obj,
358                          struct ubus_request_data *req, const char *method,
359                          struct blob_attr *msg)
360 {
361         struct blob_attr *data[__MOUNT_MAX];
362         struct blockd_umount_context *c;
363         char *devname;
364         int err;
365
366         blobmsg_parse(mount_policy, __MOUNT_MAX, data, blob_data(msg), blob_len(msg));
367
368         if (!data[MOUNT_DEVICE])
369                 return UBUS_STATUS_INVALID_ARGUMENT;
370
371         devname = blobmsg_get_string(data[MOUNT_DEVICE]);
372
373         c = calloc(1, sizeof(*c));
374         if (!c)
375                 return UBUS_STATUS_UNKNOWN_ERROR;
376
377         c->ctx = ctx;
378         ubus_defer_request(ctx, req, &c->req);
379
380         err = hotplug_call_mount("remove", devname, blockd_umount_hotplug_cb, c);
381         if (err) {
382                 free(c);
383                 return UBUS_STATUS_UNKNOWN_ERROR;
384         }
385
386         return 0;
387 }
388
389 static void block_info_dump(struct blob_buf *b, struct device *device)
390 {
391         struct blob_attr *v;
392         char *mp;
393         int rem;
394
395         blob_for_each_attr(v, device->msg, rem)
396                 blobmsg_add_blob(b, v);
397
398         mp = _find_mount_point(device->name);
399         if (mp) {
400                 blobmsg_add_string(b, "mount", mp);
401                 free(mp);
402         } else if (device->autofs && device->target) {
403                 blobmsg_add_string(b, "mount", device->target);
404         }
405 }
406
407 static int
408 block_info(struct ubus_context *ctx, struct ubus_object *obj,
409            struct ubus_request_data *req, const char *method,
410            struct blob_attr *msg)
411 {
412         struct blob_attr *data[__INFO_MAX];
413         struct device *device = NULL;
414
415         blobmsg_parse(info_policy, __INFO_MAX, data, blob_data(msg), blob_len(msg));
416
417         if (data[INFO_DEVICE]) {
418                 device = vlist_find(&devices, blobmsg_get_string(data[INFO_DEVICE]), device, node);
419                 if (!device)
420                         return UBUS_STATUS_INVALID_ARGUMENT;
421         }
422
423         blob_buf_init(&bb, 0);
424         if (device) {
425                 block_info_dump(&bb, device);
426         } else {
427                 void *a;
428
429                 a = blobmsg_open_array(&bb, "devices");
430                 vlist_for_each_element(&devices, device, node) {
431                         void *t;
432
433                         t = blobmsg_open_table(&bb, "");
434                         block_info_dump(&bb, device);
435                         blobmsg_close_table(&bb, t);
436                 }
437                 blobmsg_close_array(&bb, a);
438         }
439         ubus_send_reply(ctx, req, bb.head);
440
441         return 0;
442 }
443
444 static const struct ubus_method block_methods[] = {
445         UBUS_METHOD("hotplug", block_hotplug, mount_policy),
446         UBUS_METHOD("mount", blockd_mount, mount_policy),
447         UBUS_METHOD("umount", blockd_umount, mount_policy),
448         UBUS_METHOD("info", block_info, info_policy),
449 };
450
451 static struct ubus_object_type block_object_type =
452         UBUS_OBJECT_TYPE("block", block_methods);
453
454 static struct ubus_object block_object = {
455         .name = "block",
456         .type = &block_object_type,
457         .methods = block_methods,
458         .n_methods = ARRAY_SIZE(block_methods),
459 };
460
461 static void
462 ubus_connect_handler(struct ubus_context *ctx)
463 {
464         int ret;
465
466         ret = ubus_add_object(ctx, &block_object);
467         if (ret)
468                 fprintf(stderr, "Failed to add object: %s\n", ubus_strerror(ret));
469 }
470
471 static int autofs_umount(void)
472 {
473         umount2(AUTOFS_MOUNT_PATH, MNT_DETACH);
474         return 0;
475 }
476
477 static void autofs_read_handler(struct uloop_fd *u, unsigned int events)
478 {
479         union autofs_v5_packet_union pktu;
480         const struct autofs_v5_packet *pkt;
481         int cmd = AUTOFS_IOC_READY;
482         struct stat st;
483
484         while (read(u->fd, &pktu, sizeof(pktu)) == -1) {
485                 if (errno != EINTR)
486                         return;
487                 continue;
488         }
489
490         if (pktu.hdr.type != autofs_ptype_missing_indirect) {
491                 ULOG_ERR("unknown packet type %d\n", pktu.hdr.type);
492                 return;
493         }
494
495         pkt = &pktu.missing_indirect;
496         ULOG_ERR("kernel is requesting a mount -> %s\n", pkt->name);
497         if (lstat(pkt->name, &st) == -1)
498                 if (block("autofs", "add", (char *)pkt->name))
499                         cmd = AUTOFS_IOC_FAIL;
500
501         if (ioctl(fd_autofs_write, cmd, pkt->wait_queue_token) < 0)
502                 ULOG_ERR("failed to report back to kernel\n");
503 }
504
505 static void autofs_expire(struct uloop_timeout *t)
506 {
507         struct autofs_packet_expire pkt;
508
509         while (ioctl(fd_autofs_write, AUTOFS_IOC_EXPIRE, &pkt) == 0)
510                 block("autofs", "remove", pkt.name);
511
512         uloop_timeout_set(t, AUTOFS_EXPIRE_TIMER);
513 }
514
515 struct uloop_timeout autofs_expire_timer = {
516         .cb = autofs_expire,
517 };
518
519 static int autofs_mount(void)
520 {
521         int autofs_timeout = AUTOFS_TIMEOUT;
522         int kproto_version;
523         int pipefd[2];
524         char source[64];
525         char opts[64];
526
527         if (pipe(pipefd) < 0) {
528                 ULOG_ERR("failed to get kernel pipe\n");
529                 return -1;
530         }
531
532         snprintf(source, sizeof(source), "mountd(pid%u)", getpid());
533         snprintf(opts, sizeof(opts), "fd=%d,pgrp=%u,minproto=5,maxproto=5", pipefd[1], (unsigned) getpgrp());
534         mkdir(AUTOFS_MOUNT_PATH, 0555);
535         if (mount(source, AUTOFS_MOUNT_PATH, "autofs", 0, opts)) {
536                 ULOG_ERR("unable to mount autofs on %s\n", AUTOFS_MOUNT_PATH);
537                 close(pipefd[0]);
538                 close(pipefd[1]);
539                 return -1;
540         }
541         close(pipefd[1]);
542         fd_autofs_read.fd = pipefd[0];
543         fd_autofs_read.cb = autofs_read_handler;
544         uloop_fd_add(&fd_autofs_read, ULOOP_READ);
545
546         fd_autofs_write = open(AUTOFS_MOUNT_PATH, O_RDONLY);
547         if(fd_autofs_write < 0) {
548                 autofs_umount();
549                 ULOG_ERR("failed to open direcory\n");
550                 return -1;
551         }
552
553         ioctl(fd_autofs_write, AUTOFS_IOC_PROTOVER, &kproto_version);
554         if (kproto_version != 5) {
555                 ULOG_ERR("only kernel protocol version 5 is tested. You have %d.\n",
556                         kproto_version);
557                 exit(EXIT_FAILURE);
558         }
559         if (ioctl(fd_autofs_write, AUTOFS_IOC_SETTIMEOUT, &autofs_timeout))
560                 ULOG_ERR("failed to set autofs timeout\n");
561
562         uloop_timeout_set(&autofs_expire_timer, AUTOFS_EXPIRE_TIMER);
563
564         fcntl(fd_autofs_write, F_SETFD, fcntl(fd_autofs_write, F_GETFD) | FD_CLOEXEC);
565         fcntl(fd_autofs_read.fd, F_SETFD, fcntl(fd_autofs_read.fd, F_GETFD) | FD_CLOEXEC);
566
567         return 0;
568 }
569
570 static void blockd_startup(struct uloop_timeout *t)
571 {
572         block("autofs", "start", NULL);
573 }
574
575 struct uloop_timeout startup = {
576         .cb = blockd_startup,
577 };
578
579 int main(int argc, char **argv)
580 {
581         ulog_open(ULOG_SYSLOG | ULOG_STDIO, LOG_DAEMON, "blockd");
582         uloop_init();
583
584         autofs_mount();
585
586         conn.cb = ubus_connect_handler;
587         ubus_auto_connect(&conn);
588
589         uloop_timeout_set(&startup, 1000);
590
591         uloop_run();
592         uloop_done();
593
594         autofs_umount();
595
596         vlist_flush_all(&devices);
597
598         return 0;
599 }