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