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