Resolve device paths in kernel and initrd locations.
[petitboot] / devices / udev-helper.c
1
2 #define _GNU_SOURCE
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <stdarg.h>
7 #include <stdint.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/socket.h>
12 #include <sys/wait.h>
13 #include <sys/un.h>
14 #include <fcntl.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <asm/byteorder.h>
18 #include <linux/cdrom.h>
19 #include <sys/ioctl.h>
20
21 #include "parser.h"
22 #include "petitboot-paths.h"
23
24 /* Define below to operate without the frontend */
25 #undef USE_FAKE_SOCKET
26
27 /* Delay in seconds between polling of removable devices */
28 #define REMOVABLE_SLEEP_DELAY   2
29
30 static FILE *logf;
31 static int sock;
32
33 void pb_log(const char *fmt, ...)
34 {
35         va_list ap;
36
37         va_start(ap, fmt);
38         vfprintf(logf, fmt, ap);
39         va_end(ap);
40 }
41
42 static void print_boot_option(const struct boot_option *opt)
43 {
44         pb_log("\tname: %s\n", opt->name);
45         pb_log("\tdescription: %s\n", opt->description);
46         pb_log("\tboot_image: %s\n", opt->boot_image_file);
47         pb_log("\tinitrd: %s\n", opt->initrd_file);
48         pb_log("\tboot_args: %s\n", opt->boot_args);
49
50 }
51
52 static void print_device(const struct device *dev)
53 {
54         pb_log("\tid: %s\n", dev->id);
55         pb_log("\tname: %s\n", dev->name);
56         pb_log("\tdescription: %s\n", dev->description);
57         pb_log("\tboot_image: %s\n", dev->icon_file);
58 }
59
60 static int write_action(int fd, enum device_action action)
61 {
62         uint8_t action_buf = action;
63         return write(fd, &action_buf, sizeof(action_buf)) != sizeof(action_buf);
64 }
65
66 static int write_string(int fd, const char *str)
67 {
68         int len, pos = 0;
69         uint32_t len_buf;
70
71         if (!str) {
72                 len_buf = 0;
73                 if (write(fd, &len_buf, sizeof(len_buf)) != sizeof(len_buf)) {
74                         pb_log("write failed: %s\n", strerror(errno));
75                         return -1;
76                 }
77                 return 0;
78         }
79
80         len = strlen(str);
81         if (len > (1ull << (sizeof(len_buf) * 8 - 1))) {
82                 pb_log("string too large\n");
83                 return -1;
84         }
85
86         len_buf = __cpu_to_be32(len);
87         if (write(fd, &len_buf, sizeof(len_buf)) != sizeof(len_buf)) {
88                 pb_log("write failed: %s\n", strerror(errno));
89                 return -1;
90         }
91
92         while (pos < len) {
93                 int rc = write(fd, str, len - pos);
94                 if (rc <= 0) {
95                         pb_log("write failed: %s\n", strerror(errno));
96                         return -1;
97                 }
98                 pos += rc;
99                 str += rc;
100         }
101
102         return 0;
103 }
104
105 int add_device(const struct device *dev)
106 {
107         int rc;
108
109         pb_log("device added:\n");
110         print_device(dev);
111         rc = write_action(sock, DEV_ACTION_ADD_DEVICE) ||
112                 write_string(sock, dev->id) ||
113                 write_string(sock, dev->name) ||
114                 write_string(sock, dev->description) ||
115                 write_string(sock, dev->icon_file);
116
117         if (rc)
118                 pb_log("error writing device %s to socket\n", dev->name);
119
120         return rc;
121 }
122
123 int add_boot_option(const struct boot_option *opt)
124 {
125         int rc;
126
127         pb_log("boot option added:\n");
128         print_boot_option(opt);
129
130         rc = write_action(sock, DEV_ACTION_ADD_OPTION) ||
131                 write_string(sock, opt->id) ||
132                 write_string(sock, opt->name) ||
133                 write_string(sock, opt->description) ||
134                 write_string(sock, opt->icon_file) ||
135                 write_string(sock, opt->boot_image_file) ||
136                 write_string(sock, opt->initrd_file) ||
137                 write_string(sock, opt->boot_args);
138
139         if (rc)
140                 pb_log("error writing boot option %s to socket\n", opt->name);
141
142         return rc;
143 }
144
145 int remove_device(const char *dev_path)
146 {
147         return write_action(sock, DEV_ACTION_REMOVE_DEVICE) ||
148                 write_string(sock, dev_path);
149 }
150
151 int connect_to_socket()
152 {
153 #ifndef USE_FAKE_SOCKET
154         int fd;
155         struct sockaddr_un addr;
156
157         fd = socket(PF_UNIX, SOCK_STREAM, 0);
158         if (fd == -1) {
159                 pb_log("can't create socket: %s\n", strerror(errno));
160                 return -1;
161         }
162
163         addr.sun_family = AF_UNIX;
164         strcpy(addr.sun_path, PBOOT_DEVICE_SOCKET);
165
166         if (connect(fd, (struct sockaddr *)&addr, sizeof(addr))) {
167                 pb_log("can't connect to %s: %s\n",
168                                 addr.sun_path, strerror(errno));
169                 return -1;
170         }
171         sock = fd;
172
173         return 0;
174 #else
175         int fd;
176         fd = open("./debug_socket", O_WRONLY | O_CREAT, 0640);
177         if (fd < 0) {
178                 pb_log("can't create output file: %s\n", strerror(errno));
179                 return -1;
180         }
181         sock = fd;
182         return 0;
183 #endif
184 }
185
186 struct device_map {
187         char *dev, *mnt;
188 };
189
190 #define DEVICE_MAP_SIZE 32
191 static struct device_map device_map[DEVICE_MAP_SIZE];
192
193 const char *mountpoint_for_device(const char *dev_path)
194 {
195         int i;
196         const char *basename;
197
198         /* shorten '/dev/foo' to 'foo' */
199         basename = strrchr(dev_path, '/');
200         if (basename)
201                 basename++;
202         else
203                 basename = dev_path;
204
205         /* check existing entries in the map */
206         for (i = 0; (i < DEVICE_MAP_SIZE) && device_map[i].dev; i++)
207                 if (!strcmp(device_map[i].dev, basename))
208                         return device_map[i].mnt;
209
210         if (i == DEVICE_MAP_SIZE)
211                 return NULL;
212
213         device_map[i].dev = strdup(dev_path);
214         asprintf(&device_map[i].mnt, "%s/%s", TMP_DIR, basename);
215         return device_map[i].mnt;
216 }
217
218 /**
219  * Resolve a path given in a config file, to a path in the local filesystem.
220  * Paths may be of the form:
221  *  device:path (eg /dev/sda:/boot/vmlinux)
222  *
223  * or just a path:
224  *  /boot/vmlinux
225  * - in this case, the default mountpoint is used.
226  *
227  * Returns a newly-allocated string containing a full path to the file in path
228  */
229 char *resolve_path(const char *path, const char *default_mountpoint)
230 {
231         char *ret;
232         const char *devpath, *sep;
233
234         sep = strchr(path, ':');
235         if (!sep) {
236                 devpath = default_mountpoint;
237                 asprintf(&ret, "%s/%s", devpath, path);
238         } else {
239                 /* copy just the device name into tmp */
240                 char *dev = strndup(path, sep - path);
241                 devpath = mountpoint_for_device(dev);
242                 asprintf(&ret, "%s/%s", devpath, sep + 1);
243                 free(dev);
244         }
245
246         return ret;
247 }
248
249 int mount_device(const char *dev_path)
250 {
251         const char *dir;
252         int pid, status, rc = -1;
253         struct stat statbuf;
254
255         dir = mountpoint_for_device(dev_path);
256
257         if (stat(dir, &statbuf)) {
258                 if (mkdir(dir, 0755)) {
259                         pb_log("couldn't create directory %s: %s\n",
260                                         dir, strerror(errno));
261                         goto out;
262                 }
263         } else {
264                 if (!S_ISDIR(statbuf.st_mode)) {
265                         pb_log("mountpoint %s exists, "
266                                         "but isn't a directory\n", dir);
267                         goto out;
268                 }
269         }
270
271
272         pid = fork();
273         if (pid == -1) {
274                 pb_log("%s: fork failed: %s\n", __FUNCTION__, strerror(errno));
275                 goto out;
276         }
277
278         if (pid == 0) {
279                 execl(MOUNT_BIN, MOUNT_BIN, dev_path, dir, "-o", "ro", NULL);
280                 exit(EXIT_FAILURE);
281         }
282
283         if (waitpid(pid, &status, 0) == -1) {
284                 pb_log("%s: waitpid failed: %s\n", __FUNCTION__,
285                                 strerror(errno));
286                 goto out;
287         }
288
289         if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
290                 rc = 0;
291
292 out:
293         return rc;
294 }
295
296 static int unmount_device(const char *dev_path)
297 {
298         int pid, status, rc;
299
300         pid = fork();
301
302         if (pid == -1) {
303                 pb_log("%s: fork failed: %s\n", __FUNCTION__, strerror(errno));
304                 return -1;
305         }
306
307         if (pid == 0) {
308                 execl(UMOUNT_BIN, UMOUNT_BIN, dev_path, NULL);
309                 exit(EXIT_FAILURE);
310         }
311
312         if (waitpid(pid, &status, 0) == -1) {
313                 pb_log("%s: waitpid failed: %s\n", __FUNCTION__,
314                                 strerror(errno));
315                 return -1;
316         }
317
318         rc = !WIFEXITED(status) || WEXITSTATUS(status) != 0;
319
320         return rc;
321 }
322
323 static const struct device fake_boot_devices[] =
324 {
325         {
326                 .id             = "fakeDisk0",
327                 .name           = "Hard Disk",
328                 .icon_file      = artwork_pathname("hdd.png"),
329         },
330         {
331                 .id             = "fakeDisk1",
332                 .name           = "PinkCat Linux CD",
333                 .icon_file      = artwork_pathname("cdrom.png"),
334         }
335 };
336
337 static const struct boot_option fake_boot_options[] =
338 {
339         {
340                 .id             = "fakeBoot0",
341                 .name           = "Bloobuntu Linux",
342                 .description    = "Boot Bloobuntu Linux",
343                 .icon_file      = artwork_pathname("hdd.png"),
344         },
345         {
346                 .id             = "fakeBoot1",
347                 .name           = "Pendora Gore 6",
348                 .description    = "Boot Pendora Gora 6",
349                 .icon_file      = artwork_pathname("hdd.png"),
350         },
351         {
352                 .id             = "fakeBoot2",
353                 .name           = "Genfoo Minux",
354                 .description    = "Boot Genfoo Minux",
355                 .icon_file      = artwork_pathname("hdd.png"),
356         },
357         {
358                 .id             = "fakeBoot3",
359                 .name           = "PinkCat Linux",
360                 .description    = "Install PinkCat Linux - Graphical install",
361                 .icon_file      = artwork_pathname("cdrom.png"),
362         },
363 };
364
365 enum generic_icon_type guess_device_type(void)
366 {
367         const char *type = getenv("ID_TYPE");
368         const char *bus = getenv("ID_BUS");
369         if (type && streq(type, "cd"))
370                 return ICON_TYPE_OPTICAL;
371         if (!bus)
372                 return ICON_TYPE_UNKNOWN;
373         if (streq(bus, "usb"))
374                 return ICON_TYPE_USB;
375         if (streq(bus, "ata") || streq(bus, "scsi"))
376                 return ICON_TYPE_DISK;
377         return ICON_TYPE_UNKNOWN;
378 }
379
380
381 static int is_removable_device(const char *sysfs_path) 
382 {
383         char full_path[PATH_MAX];
384         char buf[80];
385         int fd, buf_len;
386
387         sprintf(full_path, "/sys/%s/removable", sysfs_path);    
388         fd = open(full_path, O_RDONLY);
389         pb_log(" -> removable check on %s, fd=%d\n", full_path, fd);
390         if (fd < 0)
391                 return 0;
392         buf_len = read(fd, buf, 79);
393         close(fd);
394         if (buf_len < 0)
395                 return 0;
396         buf[buf_len] = 0;
397         return strtol(buf, NULL, 10);
398 }
399
400 static int is_ignored_device(const char *devname)
401 {
402         static const char *ignored_devices[] = { "/dev/ram", NULL };
403         const char **dev;
404
405         for (dev = ignored_devices; *dev; dev++)
406                 if (!strncmp(devname, *dev, strlen(*dev)))
407                         return 1;
408
409         return 0;
410 }
411
412 static int found_new_device(const char *dev_path)
413 {
414         const char *mountpoint = mountpoint_for_device(dev_path);
415
416         if (mount_device(dev_path)) {
417                 pb_log("failed to mount %s\n", dev_path);
418                 return EXIT_FAILURE;
419         }
420
421         pb_log("mounted %s at %s\n", dev_path, mountpoint);
422
423         iterate_parsers(dev_path, mountpoint);
424
425         return EXIT_SUCCESS;
426 }
427
428 static void detach_and_sleep(int sec)
429 {
430         static int forked = 0;
431         int rc = 0;
432
433         if (sec <= 0)
434                 return;
435
436         if (!forked) {
437                 pb_log("running in background...");
438                 rc = fork();
439                 forked = 1;
440         }
441
442         if (rc == 0) {
443                 sleep(sec);
444
445         } else if (rc == -1) {
446                 perror("fork()");
447                 exit(EXIT_FAILURE);
448         } else {
449                 exit(EXIT_SUCCESS);
450         }
451 }
452
453 static int poll_device_plug(const char *dev_path,
454                             int *optical)
455 {
456         int rc, fd;
457
458         /* Polling loop for optical drive */
459         for (; (*optical) != 0; ) {
460                 pb_log("poll for optical drive insertion ...\n");
461                 fd = open(dev_path, O_RDONLY|O_NONBLOCK);
462                 if (fd < 0)
463                         return EXIT_FAILURE;
464                 rc = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
465                 close(fd);
466                 if (rc == -1) {
467                         pb_log("not an optical drive, fallback...\n");
468                         break;
469                 }
470                 *optical = 1;
471                 if (rc == CDS_DISC_OK)
472                         return EXIT_SUCCESS;
473
474                 pb_log("no... waiting\n");
475                 detach_and_sleep(REMOVABLE_SLEEP_DELAY);
476         }
477
478         /* Fall back to bare open() */
479         *optical = 0;
480         for (;;) {
481                 pb_log("poll for non-optical drive insertion ...\n");
482                 fd = open(dev_path, O_RDONLY);
483                 if (fd < 0 && errno != ENOMEDIUM)
484                         return EXIT_FAILURE;
485                 close(fd);
486                 if (fd >= 0)
487                         return EXIT_SUCCESS;
488                 pb_log("no... waiting\n");
489                 detach_and_sleep(REMOVABLE_SLEEP_DELAY);
490         }
491 }
492
493 static int poll_device_unplug(const char *dev_path, int optical)
494 {
495         int rc, fd;
496
497         for (;optical;) {
498                 pb_log("poll for optical drive removal ...\n");
499                 fd = open(dev_path, O_RDONLY|O_NONBLOCK);
500                 if (fd < 0)
501                         return EXIT_FAILURE;
502                 rc = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
503                 close(fd);
504                 if (rc != CDS_DISC_OK)
505                         return EXIT_SUCCESS;
506                 pb_log("no... waiting\n");
507                 detach_and_sleep(REMOVABLE_SLEEP_DELAY);
508         }
509
510         /* Fall back to bare open() */
511         for (;;) {
512                 pb_log("poll for non-optical drive removal ...\n");
513                 fd = open(dev_path, O_RDONLY);
514                 if (fd < 0 && errno != ENOMEDIUM)
515                         return EXIT_FAILURE;
516                 close(fd);
517                 if (fd < 0)
518                         return EXIT_SUCCESS;
519                 pb_log("no... waiting\n");
520                 detach_and_sleep(REMOVABLE_SLEEP_DELAY);
521         }
522 }
523
524 static int poll_removable_device(const char *sysfs_path,
525                                  const char *dev_path)
526 {
527         int rc, mounted, optical = -1;
528        
529         for (;;) {
530                 rc = poll_device_plug(dev_path, &optical);
531                 if (rc == EXIT_FAILURE)
532                         return rc;
533                 rc = found_new_device(dev_path);
534                 mounted = (rc == EXIT_SUCCESS);
535
536                 poll_device_unplug(dev_path, optical);
537
538                 remove_device(dev_path);
539
540                 /* Unmount it repeatedly, if needs be */
541                 while (mounted && !unmount_device(dev_path))
542                         ;
543                 detach_and_sleep(1);
544         }
545 }
546
547 int main(int argc, char **argv)
548 {
549         char *dev_path, *action;
550         int rc;
551
552         action = getenv("ACTION");
553
554         logf = fopen("/var/tmp/petitboot-udev-helpers.log", "a");
555         if (!logf)
556                 logf = stdout;
557         pb_log("%d started\n", getpid());
558         rc = EXIT_SUCCESS;
559
560         if (!action) {
561                 pb_log("missing environment?\n");
562                 return EXIT_FAILURE;
563         }
564
565         if (connect_to_socket())
566                 return EXIT_FAILURE;
567
568         if (streq(action, "fake")) {
569                 pb_log("fake mode");
570
571                 add_device(&fake_boot_devices[0]);
572                 add_boot_option(&fake_boot_options[0]);
573                 add_boot_option(&fake_boot_options[1]);
574                 add_boot_option(&fake_boot_options[2]);
575                 add_device(&fake_boot_devices[1]);
576                 add_boot_option(&fake_boot_options[3]);
577
578                 return EXIT_SUCCESS;
579         }
580
581         dev_path = getenv("DEVNAME");
582         if (!dev_path) {
583                 pb_log("missing environment?\n");
584                 return EXIT_FAILURE;
585         }
586
587         if (is_ignored_device(dev_path))
588                 return EXIT_SUCCESS;
589
590         if (streq(action, "add")) {
591                 char *sysfs_path = getenv("DEVPATH");
592                 if (sysfs_path && is_removable_device(sysfs_path))
593                         rc = poll_removable_device(sysfs_path, dev_path);
594                 else
595                         rc = found_new_device(dev_path);
596         } else if (streq(action, "remove")) {
597                 pb_log("%s removed\n", dev_path);
598
599                 remove_device(dev_path);
600
601                 /* Unmount it repeatedly, if needs be */
602                 while (!unmount_device(dev_path))
603                         ;
604
605         } else {
606                 pb_log("invalid action '%s'\n", action);
607                 rc = EXIT_FAILURE;
608         }
609         return rc;
610 }