]> git.ipfire.org Git - ipfire-2.x.git/blob - src/installer/hw.c
suricata: Change midstream policy to "pass-flow"
[ipfire-2.x.git] / src / installer / hw.c
1 /*#############################################################################
2 # #
3 # IPFire - An Open Source Firewall Distribution #
4 # Copyright (C) 2007-2022 IPFire Team <info@ipfire.org> #
5 # #
6 # This program is free software: you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation, either version 3 of the License, or #
9 # (at your option) any later version. #
10 # #
11 # This program is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
15 # #
16 # You should have received a copy of the GNU General Public License #
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
18 # #
19 #############################################################################*/
20
21 #ifndef _GNU_SOURCE
22 #define _GNU_SOURCE
23 #endif
24
25 #include <assert.h>
26 #include <blkid/blkid.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <libudev.h>
30 #include <linux/loop.h>
31 #include <math.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/ioctl.h>
36 #include <sys/mount.h>
37 #include <sys/stat.h>
38 #include <sys/swap.h>
39 #include <sys/sysinfo.h>
40 #include <sys/utsname.h>
41 #include <unistd.h>
42
43 #include <libsmooth.h>
44
45 #include "hw.h"
46
47 static int system_chroot(const char* output, const char* path, const char* cmd) {
48 char chroot_cmd[STRING_SIZE];
49
50 snprintf(chroot_cmd, sizeof(chroot_cmd), "/usr/sbin/chroot %s %s", path, cmd);
51
52 return mysystem(output, chroot_cmd);
53 }
54
55 struct hw* hw_init() {
56 struct hw* hw = calloc(1, sizeof(*hw));
57 assert(hw);
58
59 // Initialize libudev
60 hw->udev = udev_new();
61 if (!hw->udev) {
62 fprintf(stderr, "Could not create udev instance\n");
63 exit(1);
64 }
65
66 // What architecture are we running on?
67 struct utsname uname_data;
68 int ret = uname(&uname_data);
69 if (ret == 0)
70 snprintf(hw->arch, sizeof(hw->arch), "%s", uname_data.machine);
71
72 // Should we install in EFI mode?
73 if ((strcmp(hw->arch, "x86_64") == 0) || (strcmp(hw->arch, "aarch64") == 0))
74 hw->efi = 1;
75
76 return hw;
77 }
78
79 void hw_free(struct hw* hw) {
80 if (hw->udev)
81 udev_unref(hw->udev);
82
83 free(hw);
84 }
85
86 static int strstartswith(const char* a, const char* b) {
87 return (strncmp(a, b, strlen(b)) == 0);
88 }
89
90 static char loop_device[STRING_SIZE];
91
92 static int setup_loop_device(const char* source, const char* device) {
93 int file_fd = open(source, O_RDWR);
94 if (file_fd < 0)
95 goto ERROR;
96
97 int device_fd = -1;
98 if ((device_fd = open(device, O_RDWR)) < 0)
99 goto ERROR;
100
101 if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0)
102 goto ERROR;
103
104 close(file_fd);
105 close(device_fd);
106
107 return 0;
108
109 ERROR:
110 if (file_fd >= 0)
111 close(file_fd);
112
113 if (device_fd >= 0) {
114 ioctl(device_fd, LOOP_CLR_FD, 0);
115 close(device_fd);
116 }
117
118 return -1;
119 }
120
121 int hw_mount(const char* source, const char* target, const char* fs, int flags) {
122 const char* loop_device = "/dev/loop0";
123
124 // Create target if it does not exist
125 if (access(target, X_OK) != 0)
126 mkdir(target, S_IRWXU|S_IRWXG|S_IRWXO);
127
128 struct stat st;
129 stat(source, &st);
130
131 if (S_ISREG(st.st_mode)) {
132 int r = setup_loop_device(source, loop_device);
133 if (r == 0) {
134 source = loop_device;
135 } else {
136 return -1;
137 }
138 }
139
140 return mount(source, target, fs, flags, NULL);
141 }
142
143 static int hw_bind_mount(const char* source, const char* prefix) {
144 if (!source || !prefix) {
145 errno = EINVAL;
146 return 1;
147 }
148
149 char target[PATH_MAX];
150 int r;
151
152 // Format target
153 r = snprintf(target, sizeof(target) - 1, "%s/%s", prefix, source);
154 if (r < 0)
155 return 1;
156
157 // Ensure target exists
158 mkdir(target, S_IRWXU|S_IRWXG|S_IRWXO);
159
160 return hw_mount(source, target, NULL, MS_BIND);
161 }
162
163 int hw_umount(const char* source, const char* prefix) {
164 char target[PATH_MAX];
165 int r;
166
167 if (prefix)
168 r = snprintf(target, sizeof(target) - 1, "%s/%s", prefix, source);
169 else
170 r = snprintf(target, sizeof(target) - 1, "%s", source);
171 if (r < 0)
172 return r;
173
174 // Perform umount
175 r = umount2(target, 0);
176 if (r) {
177 switch (errno) {
178 // Try again with force if umount wasn't successful
179 case EBUSY:
180 sleep(1);
181
182 r = umount2(target, MNT_FORCE);
183 break;
184
185 // target wasn't a mountpoint. Ignore.
186 case EINVAL:
187 r = 0;
188 break;
189
190 // target doesn't exist
191 case ENOENT:
192 r = 0;
193 break;
194 }
195 }
196
197 return r;
198 }
199
200 static int hw_test_source_medium(const char* path) {
201 int ret = hw_mount(path, SOURCE_MOUNT_PATH, "iso9660", MS_RDONLY);
202
203 if (ret != 0) {
204 // 2nd try, ntfs for a rufus converted usb key
205 ret = hw_mount(path, SOURCE_MOUNT_PATH, "ntfs3", MS_RDONLY);
206 }
207 if (ret != 0) {
208 // 3rd try, vfat for a rufus converted usb key
209 ret = hw_mount(path, SOURCE_MOUNT_PATH, "vfat", MS_RDONLY);
210 }
211
212 // If the source could not be mounted we
213 // cannot proceed.
214 if (ret != 0)
215 return ret;
216
217 // Check if the test file exists.
218 ret = access(SOURCE_TEST_FILE, R_OK);
219
220 // Umount the test device.
221 hw_umount(SOURCE_MOUNT_PATH, NULL);
222
223 return ret;
224 }
225
226 char* hw_find_source_medium(struct hw* hw) {
227 char* ret = NULL;
228
229 struct udev_enumerate* enumerate = udev_enumerate_new(hw->udev);
230
231 udev_enumerate_add_match_subsystem(enumerate, "block");
232 udev_enumerate_scan_devices(enumerate);
233
234 struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);
235
236 struct udev_list_entry* dev_list_entry;
237 udev_list_entry_foreach(dev_list_entry, devices) {
238 const char* path = udev_list_entry_get_name(dev_list_entry);
239 struct udev_device* dev = udev_device_new_from_syspath(hw->udev, path);
240
241 const char* dev_path = udev_device_get_devnode(dev);
242
243 // Skip everything what we cannot work with
244 if (strstartswith(dev_path, "/dev/loop") || strstartswith(dev_path, "/dev/fd") ||
245 strstartswith(dev_path, "/dev/ram") || strstartswith(dev_path, "/dev/md"))
246 continue;
247
248 if (hw_test_source_medium(dev_path) == 0) {
249 ret = strdup(dev_path);
250 }
251
252 udev_device_unref(dev);
253
254 // If a suitable device was found the search will end.
255 if (ret)
256 break;
257 }
258
259 udev_enumerate_unref(enumerate);
260
261 return ret;
262 }
263
264 static struct hw_disk** hw_create_disks() {
265 struct hw_disk** ret = malloc(sizeof(*ret) * (HW_MAX_DISKS + 1));
266
267 return ret;
268 }
269
270 static unsigned long long hw_block_device_get_size(const char* dev) {
271 int fd = open(dev, O_RDONLY);
272 if (fd < 0)
273 return 0;
274
275 unsigned long long size = blkid_get_dev_size(fd);
276 close(fd);
277
278 return size;
279 }
280
281 struct hw_disk** hw_find_disks(struct hw* hw, const char* sourcedrive) {
282 struct hw_disk** ret = hw_create_disks();
283 struct hw_disk** disks = ret;
284
285 // Determine the disk device of source if it is a partition
286 char* sourcedisk = NULL;
287 char syssource[PATH_MAX];
288 (void)snprintf(syssource, sizeof(syssource) - 1, "/sys/class/block/%s", sourcedrive + 5);
289 struct udev_device* s_dev = udev_device_new_from_syspath(hw->udev, syssource);
290 const char* s_devtype = udev_device_get_property_value(s_dev, "DEVTYPE");
291 if (s_devtype && (strcmp(s_devtype, "partition") == 0)) {
292 struct udev_device* p_dev = udev_device_get_parent_with_subsystem_devtype(s_dev,"block","disk");
293 if (p_dev) {
294 sourcedisk = udev_device_get_devnode(p_dev);
295 }
296 }
297 if (!sourcedisk) sourcedisk = sourcedrive;
298
299 struct udev_enumerate* enumerate = udev_enumerate_new(hw->udev);
300
301 udev_enumerate_add_match_subsystem(enumerate, "block");
302 udev_enumerate_scan_devices(enumerate);
303
304 struct udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate);
305
306 struct udev_list_entry* dev_list_entry;
307 unsigned int i = HW_MAX_DISKS;
308 udev_list_entry_foreach(dev_list_entry, devices) {
309 const char* path = udev_list_entry_get_name(dev_list_entry);
310 struct udev_device* dev = udev_device_new_from_syspath(hw->udev, path);
311
312 const char* dev_path = udev_device_get_devnode(dev);
313
314 // Skip everything what we cannot work with
315 if (strstartswith(dev_path, "/dev/loop") || strstartswith(dev_path, "/dev/fd") ||
316 strstartswith(dev_path, "/dev/ram") || strstartswith(dev_path, "/dev/sr") ||
317 strstartswith(dev_path, "/dev/md")) {
318 udev_device_unref(dev);
319 continue;
320 }
321
322 // Skip sourcedisk if we need to
323 if (sourcedisk && (strcmp(dev_path, sourcedisk) == 0)) {
324 udev_device_unref(dev);
325 continue;
326 }
327
328 // DEVTYPE must be disk (otherwise we will see all sorts of partitions here)
329 const char* devtype = udev_device_get_property_value(dev, "DEVTYPE");
330 if (devtype && (strcmp(devtype, "disk") != 0)) {
331 udev_device_unref(dev);
332 continue;
333 }
334
335 // Skip devices with a size of zero
336 unsigned long long size = hw_block_device_get_size(dev_path);
337 if (size == 0) {
338 udev_device_unref(dev);
339 continue;
340 }
341
342 struct hw_disk* disk = malloc(sizeof(*disk));
343 if (disk == NULL)
344 return NULL;
345
346 disk->ref = 1;
347
348 strncpy(disk->path, dev_path, sizeof(disk->path));
349 const char* p = disk->path + 5;
350
351 disk->size = size;
352
353 // Vendor
354 const char* vendor = udev_device_get_property_value(dev, "ID_VENDOR");
355 if (!vendor)
356 vendor = udev_device_get_sysattr_value(dev, "vendor");
357 if (!vendor)
358 vendor = udev_device_get_sysattr_value(dev, "manufacturer");
359
360 if (vendor)
361 strncpy(disk->vendor, vendor, sizeof(disk->vendor));
362 else
363 *disk->vendor = '\0';
364
365 // Model
366 const char* model = udev_device_get_property_value(dev, "ID_MODEL");
367 if (!model)
368 model = udev_device_get_sysattr_value(dev, "model");
369 if (!model)
370 model = udev_device_get_sysattr_value(dev, "product");
371
372 if (model)
373 strncpy(disk->model, model, sizeof(disk->model));
374 else
375 *disk->model = '\0';
376
377 // Format description
378 char size_str[STRING_SIZE];
379 snprintf(size_str, sizeof(size_str), "%4.1fGB", (double)disk->size / pow(1024, 3));
380
381 if (*disk->vendor && *disk->model) {
382 snprintf(disk->description, sizeof(disk->description),
383 "%s - %s - %s - %s", size_str, p, disk->vendor, disk->model);
384
385 } else if (*disk->vendor || *disk->model) {
386 snprintf(disk->description, sizeof(disk->description),
387 "%s - %s - %s", size_str, p, (*disk->vendor) ? disk->vendor : disk->model);
388
389 } else {
390 snprintf(disk->description, sizeof(disk->description),
391 "%s - %s", size_str, p);
392 }
393
394 // Cut off the description string after 40 characters
395 disk->description[41] = '\0';
396
397 *disks++ = disk;
398
399 if (--i == 0)
400 break;
401
402 udev_device_unref(dev);
403 }
404
405 udev_enumerate_unref(enumerate);
406
407 *disks = NULL;
408
409 return ret;
410 }
411
412 void hw_free_disks(struct hw_disk** disks) {
413 struct hw_disk** disk = disks;
414
415 while (*disk != NULL) {
416 if (--(*disk)->ref == 0)
417 free(*disk);
418
419 disk++;
420 }
421
422 free(disks);
423 }
424
425 unsigned int hw_count_disks(const struct hw_disk** disks) {
426 unsigned int ret = 0;
427
428 while (*disks++)
429 ret++;
430
431 return ret;
432 }
433
434 struct hw_disk** hw_select_disks(struct hw_disk** disks, int* selection) {
435 struct hw_disk** ret = hw_create_disks();
436 struct hw_disk** selected_disks = ret;
437
438 unsigned int num_disks = hw_count_disks((const struct hw_disk**)disks);
439
440 for (unsigned int i = 0; i < num_disks; i++) {
441 if (!selection || selection[i]) {
442 struct hw_disk *selected_disk = disks[i];
443 selected_disk->ref++;
444
445 *selected_disks++ = selected_disk;
446 }
447 }
448
449 // Set sentinel
450 *selected_disks = NULL;
451
452 return ret;
453 }
454
455 struct hw_disk** hw_select_first_disk(const struct hw_disk** disks) {
456 struct hw_disk** ret = hw_create_disks();
457 struct hw_disk** selected_disks = ret;
458
459 unsigned int num_disks = hw_count_disks(disks);
460 assert(num_disks > 0);
461
462 for (unsigned int i = 0; i < num_disks; i++) {
463 struct hw_disk *disk = disks[i];
464 disk->ref++;
465
466 *selected_disks++ = disk;
467 break;
468 }
469
470 // Set sentinel
471 *selected_disks = NULL;
472
473 return ret;
474 }
475
476 static unsigned long long hw_swap_size(struct hw_destination* dest) {
477 unsigned long long memory = hw_memory();
478
479 unsigned long long swap_size = memory / 4;
480
481 // Min. swap size is 128MB
482 if (swap_size < MB2BYTES(128))
483 swap_size = MB2BYTES(128);
484
485 // Cap swap size to 1GB
486 else if (swap_size > MB2BYTES(1024))
487 swap_size = MB2BYTES(1024);
488
489 return swap_size;
490 }
491
492 static unsigned long long hw_boot_size(struct hw_destination* dest) {
493 return MB2BYTES(512);
494 }
495
496 static int hw_device_has_p_suffix(const struct hw_destination* dest) {
497 // All RAID devices have the p suffix.
498 if (dest->is_raid)
499 return 1;
500
501 // Devices with a number at the end have the p suffix, too.
502 // e.g. mmcblk0, cciss0
503 unsigned int last_char = strlen(dest->path) - 1;
504 if ((dest->path[last_char] >= '0') && (dest->path[last_char] <= '9'))
505 return 1;
506
507 return 0;
508 }
509
510 static int hw_calculate_partition_table(struct hw* hw, struct hw_destination* dest, int disable_swap) {
511 char path[DEV_SIZE];
512 int part_idx = 1;
513
514 snprintf(path, sizeof(path), "%s%s", dest->path,
515 hw_device_has_p_suffix(dest) ? "p" : "");
516 dest->part_boot_idx = 0;
517
518 // Determine the size of the target block device
519 if (dest->is_raid) {
520 dest->size = (dest->disk1->size >= dest->disk2->size) ?
521 dest->disk2->size : dest->disk1->size;
522
523 // The RAID will install some metadata at the end of the disk
524 // and we will save up some space for that.
525 dest->size -= MB2BYTES(2);
526 } else {
527 dest->size = dest->disk1->size;
528 }
529
530 // As we add some extra space before the beginning of the first
531 // partition, we need to substract that here.
532 dest->size -= MB2BYTES(1);
533
534 // Add some more space for partition tables, etc.
535 dest->size -= MB2BYTES(1);
536
537 // The disk has to have at least 2GB
538 if (dest->size <= MB2BYTES(2048))
539 return -1;
540
541 // Determine partition table
542 dest->part_table = HW_PART_TABLE_MSDOS;
543
544 // Disks over 2TB need to use GPT
545 if (dest->size >= MB2BYTES(2047 * 1024))
546 dest->part_table = HW_PART_TABLE_GPT;
547
548 // We also use GPT on raid disks by default
549 else if (dest->is_raid)
550 dest->part_table = HW_PART_TABLE_GPT;
551
552 // When using GPT, GRUB2 needs a little bit of space to put
553 // itself in.
554 if (dest->part_table == HW_PART_TABLE_GPT) {
555 snprintf(dest->part_bootldr, sizeof(dest->part_bootldr),
556 "%s%d", path, part_idx);
557
558 dest->size_bootldr = MB2BYTES(4);
559
560 dest->part_boot_idx = part_idx++;
561 } else {
562 *dest->part_bootldr = '\0';
563 dest->size_bootldr = 0;
564 }
565
566 dest->size_boot = hw_boot_size(dest);
567
568 // Create an EFI partition when running in EFI mode
569 if (hw->efi)
570 dest->size_boot_efi = MB2BYTES(32);
571 else
572 dest->size_boot_efi = 0;
573
574 // Determine the size of the data partition.
575 unsigned long long space_left = dest->size - \
576 (dest->size_bootldr + dest->size_boot + dest->size_boot_efi);
577
578 // If we have less than 2GB left, we disable swap
579 if (space_left <= MB2BYTES(2048))
580 disable_swap = 1;
581
582 // Should we use swap?
583 if (disable_swap)
584 dest->size_swap = 0;
585 else
586 dest->size_swap = hw_swap_size(dest);
587
588 // Subtract swap
589 space_left -= dest->size_swap;
590
591 // Root is getting what ever is left
592 dest->size_root = space_left;
593
594 // Set partition names
595 if (dest->size_boot > 0) {
596 if (dest->part_boot_idx == 0)
597 dest->part_boot_idx = part_idx;
598
599 snprintf(dest->part_boot, sizeof(dest->part_boot), "%s%d", path, part_idx++);
600 } else
601 *dest->part_boot = '\0';
602
603 if (dest->size_boot_efi > 0) {
604 dest->part_boot_efi_idx = part_idx;
605
606 snprintf(dest->part_boot_efi, sizeof(dest->part_boot_efi),
607 "%s%d", path, part_idx++);
608 } else {
609 *dest->part_boot_efi = '\0';
610 dest->part_boot_efi_idx = 0;
611 }
612
613 if (dest->size_swap > 0)
614 snprintf(dest->part_swap, sizeof(dest->part_swap), "%s%d", path, part_idx++);
615 else
616 *dest->part_swap = '\0';
617
618 // There is always a root partition
619 if (dest->part_boot_idx == 0)
620 dest->part_boot_idx = part_idx;
621
622 snprintf(dest->part_root, sizeof(dest->part_root), "%s%d", path, part_idx++);
623
624 return 0;
625 }
626
627 struct hw_destination* hw_make_destination(struct hw* hw, int part_type, struct hw_disk** disks, int disable_swap) {
628 struct hw_destination* dest = malloc(sizeof(*dest));
629
630 if (part_type == HW_PART_TYPE_NORMAL) {
631 dest->disk1 = *disks;
632 dest->disk2 = NULL;
633
634 strncpy(dest->path, dest->disk1->path, sizeof(dest->path));
635
636 } else if (part_type == HW_PART_TYPE_RAID1) {
637 dest->disk1 = *disks++;
638 dest->disk2 = *disks;
639 dest->raid_level = 1;
640
641 snprintf(dest->path, sizeof(dest->path), "/dev/md0");
642 }
643
644 // Is this a RAID device?
645 dest->is_raid = (part_type > HW_PART_TYPE_NORMAL);
646
647 int r = hw_calculate_partition_table(hw, dest, disable_swap);
648 if (r)
649 return NULL;
650
651 // Set default filesystem
652 dest->filesystem = HW_FS_DEFAULT;
653
654 return dest;
655 }
656
657 unsigned long long hw_memory() {
658 struct sysinfo si;
659
660 int r = sysinfo(&si);
661 if (r < 0)
662 return 0;
663
664 return si.totalram;
665 }
666
667 static int hw_zero_out_device(const char* path, int bytes) {
668 char block[512];
669 memset(block, 0, sizeof(block));
670
671 int blocks = bytes / sizeof(block);
672
673 int fd = open(path, O_WRONLY);
674 if (fd < 0)
675 return -1;
676
677 unsigned int bytes_written = 0;
678 while (blocks-- > 0) {
679 bytes_written += write(fd, block, sizeof(block));
680 }
681
682 fsync(fd);
683 close(fd);
684
685 return bytes_written;
686 }
687
688 static int try_open(const char* path) {
689 FILE* f = fopen(path, "r");
690 if (f) {
691 fclose(f);
692 return 0;
693 }
694
695 return -1;
696 }
697
698 int hw_create_partitions(struct hw_destination* dest, const char* output) {
699 // Before we write a new partition table to the disk, we will erase
700 // the first couple of megabytes at the beginning of the device to
701 // get rid of all left other things like bootloaders and partition tables.
702 // This solves some problems when changing from MBR to GPT partitions or
703 // the other way around.
704 int r = hw_zero_out_device(dest->path, MB2BYTES(10));
705 if (r <= 0)
706 return r;
707
708 char* cmd = NULL;
709 asprintf(&cmd, "/usr/sbin/parted -s %s -a optimal", dest->path);
710
711 // Set partition type
712 if (dest->part_table == HW_PART_TABLE_MSDOS)
713 asprintf(&cmd, "%s mklabel msdos", cmd);
714 else if (dest->part_table == HW_PART_TABLE_GPT)
715 asprintf(&cmd, "%s mklabel gpt", cmd);
716
717 unsigned long long part_start = MB2BYTES(1);
718
719 if (*dest->part_bootldr) {
720 asprintf(&cmd, "%s mkpart %s ext2 %lluB %lluB", cmd,
721 (dest->part_table == HW_PART_TABLE_GPT) ? "BOOTLDR" : "primary",
722 part_start, part_start + dest->size_bootldr - 1);
723
724 part_start += dest->size_bootldr;
725 }
726
727 if (*dest->part_boot) {
728 asprintf(&cmd, "%s mkpart %s ext2 %lluB %lluB", cmd,
729 (dest->part_table == HW_PART_TABLE_GPT) ? "BOOT" : "primary",
730 part_start, part_start + dest->size_boot - 1);
731
732 part_start += dest->size_boot;
733 }
734
735 if (*dest->part_boot_efi) {
736 asprintf(&cmd, "%s mkpart %s fat32 %lluB %lluB", cmd,
737 (dest->part_table == HW_PART_TABLE_GPT) ? "ESP" : "primary",
738 part_start, part_start + dest->size_boot_efi - 1);
739
740 part_start += dest->size_boot_efi;
741 }
742
743 if (*dest->part_swap) {
744 asprintf(&cmd, "%s mkpart %s linux-swap %lluB %lluB", cmd,
745 (dest->part_table == HW_PART_TABLE_GPT) ? "SWAP" : "primary",
746 part_start, part_start + dest->size_swap - 1);
747
748 part_start += dest->size_swap;
749 }
750
751 if (*dest->part_root) {
752 asprintf(&cmd, "%s mkpart %s ext2 %lluB %lluB", cmd,
753 (dest->part_table == HW_PART_TABLE_GPT) ? "ROOT" : "primary",
754 part_start, part_start + dest->size_root - 1);
755
756 part_start += dest->size_root;
757 }
758
759 if (dest->part_boot_idx > 0)
760 asprintf(&cmd, "%s set %d boot on", cmd, dest->part_boot_idx);
761
762 if (dest->part_boot_efi_idx > 0)
763 asprintf(&cmd, "%s set %d esp on", cmd, dest->part_boot_efi_idx);
764
765 if (dest->part_table == HW_PART_TABLE_GPT) {
766 if (*dest->part_bootldr) {
767 asprintf(&cmd, "%s set %d bios_grub on", cmd, dest->part_boot_idx);
768 }
769 }
770
771 r = mysystem(output, cmd);
772
773 // Wait until the system re-read the partition table
774 if (r == 0) {
775 unsigned int counter = 10;
776
777 while (counter-- > 0) {
778 sleep(1);
779
780 if (*dest->part_bootldr && (try_open(dest->part_bootldr) != 0))
781 continue;
782
783 if (*dest->part_boot && (try_open(dest->part_boot) != 0))
784 continue;
785
786 if (*dest->part_boot_efi && (try_open(dest->part_boot_efi) != 0))
787 continue;
788
789 if (*dest->part_swap && (try_open(dest->part_swap) != 0))
790 continue;
791
792 if (*dest->part_root && (try_open(dest->part_root) != 0))
793 continue;
794
795 // All partitions do exist, exiting the loop.
796 break;
797 }
798 }
799
800 if (cmd)
801 free(cmd);
802
803 return r;
804 }
805
806 static int hw_format_filesystem(const char* path, int fs, const char* output) {
807 char cmd[STRING_SIZE] = "\0";
808
809 // Swap
810 if (fs == HW_FS_SWAP) {
811 snprintf(cmd, sizeof(cmd), "/sbin/mkswap -v1 %s &>/dev/null", path);
812
813 // EXT4
814 } else if (fs == HW_FS_EXT4) {
815 snprintf(cmd, sizeof(cmd), "/sbin/mke2fs -FF -T ext4 %s", path);
816
817 // EXT4 w/o journal
818 } else if (fs == HW_FS_EXT4_WO_JOURNAL) {
819 snprintf(cmd, sizeof(cmd), "/sbin/mke2fs -FF -T ext4 -O ^has_journal %s", path);
820
821 // XFS
822 } else if (fs == HW_FS_XFS) {
823 snprintf(cmd, sizeof(cmd), "/sbin/mkfs.xfs -f %s", path);
824
825 // FAT32
826 } else if (fs == HW_FS_FAT32) {
827 snprintf(cmd, sizeof(cmd), "/sbin/mkfs.vfat %s", path);
828 }
829
830 assert(*cmd);
831
832 int r = mysystem(output, cmd);
833
834 return r;
835 }
836
837 int hw_create_filesystems(struct hw_destination* dest, const char* output) {
838 int r;
839
840 // boot
841 if (*dest->part_boot) {
842 r = hw_format_filesystem(dest->part_boot, dest->filesystem, output);
843 if (r)
844 return r;
845 }
846
847 // ESP
848 if (*dest->part_boot_efi) {
849 r = hw_format_filesystem(dest->part_boot_efi, HW_FS_FAT32, output);
850 if (r)
851 return r;
852 }
853
854 // swap
855 if (*dest->part_swap) {
856 r = hw_format_filesystem(dest->part_swap, HW_FS_SWAP, output);
857 if (r)
858 return r;
859 }
860
861 // root
862 r = hw_format_filesystem(dest->part_root, dest->filesystem, output);
863 if (r)
864 return r;
865
866 return 0;
867 }
868
869 int hw_mount_filesystems(struct hw_destination* dest, const char* prefix) {
870 char target[STRING_SIZE];
871
872 assert(*prefix == '/');
873
874 const char* filesystem;
875 switch (dest->filesystem) {
876 case HW_FS_EXT4:
877 case HW_FS_EXT4_WO_JOURNAL:
878 filesystem = "ext4";
879 break;
880
881 case HW_FS_XFS:
882 filesystem = "xfs";
883 break;
884
885 case HW_FS_FAT32:
886 filesystem = "vfat";
887 break;
888
889 default:
890 assert(0);
891 }
892
893 // root
894 int r = hw_mount(dest->part_root, prefix, filesystem, 0);
895 if (r)
896 return r;
897
898 // boot
899 if (*dest->part_boot) {
900 snprintf(target, sizeof(target), "%s%s", prefix, HW_PATH_BOOT);
901 mkdir(target, S_IRWXU|S_IRWXG|S_IRWXO);
902
903 r = hw_mount(dest->part_boot, target, filesystem, 0);
904 if (r) {
905 hw_umount_filesystems(dest, prefix);
906
907 return r;
908 }
909 }
910
911 // ESP
912 if (*dest->part_boot_efi) {
913 snprintf(target, sizeof(target), "%s%s", prefix, HW_PATH_BOOT_EFI);
914 mkdir(target, S_IRWXU|S_IRWXG|S_IRWXO);
915
916 r = hw_mount(dest->part_boot_efi, target, "vfat", 0);
917 if (r) {
918 hw_umount_filesystems(dest, prefix);
919
920 return r;
921 }
922 }
923
924 // swap
925 if (*dest->part_swap) {
926 r = swapon(dest->part_swap, 0);
927 if (r) {
928 hw_umount_filesystems(dest, prefix);
929
930 return r;
931 }
932 }
933
934 // bind-mount misc filesystems
935 r = hw_bind_mount("/dev", prefix);
936 if (r)
937 return r;
938
939 r = hw_bind_mount("/proc", prefix);
940 if (r)
941 return r;
942
943 r = hw_bind_mount("/sys", prefix);
944 if (r)
945 return r;
946
947 r = hw_bind_mount("/sys/firmware/efi/efivars", prefix);
948 if (r && errno != ENOENT)
949 return r;
950
951 return 0;
952 }
953
954 int hw_umount_filesystems(struct hw_destination* dest, const char* prefix) {
955 int r;
956 char target[STRING_SIZE];
957
958 // Write all buffers to disk before umounting
959 hw_sync();
960
961 // ESP
962 if (*dest->part_boot_efi) {
963 r = hw_umount(HW_PATH_BOOT_EFI, prefix);
964 if (r)
965 return -1;
966 }
967
968 // boot
969 if (*dest->part_boot) {
970 r = hw_umount(HW_PATH_BOOT, prefix);
971 if (r)
972 return -1;
973 }
974
975 // swap
976 if (*dest->part_swap) {
977 swapoff(dest->part_swap);
978 }
979
980 // misc filesystems
981 r = hw_umount("/sys/firmware/efi/efivars", prefix);
982 if (r)
983 return -1;
984
985 r = hw_umount("/sys", prefix);
986 if (r)
987 return -1;
988
989 r = hw_umount("/proc", prefix);
990 if (r)
991 return -1;
992
993 r = hw_umount("/dev", prefix);
994 if (r)
995 return -1;
996
997 // root
998 r = hw_umount(prefix, NULL);
999 if (r)
1000 return -1;
1001
1002 return 0;
1003 }
1004
1005 int hw_destroy_raid_superblocks(const struct hw_destination* dest, const char* output) {
1006 char cmd[STRING_SIZE];
1007
1008 hw_stop_all_raid_arrays(output);
1009 hw_stop_all_raid_arrays(output);
1010
1011 if (dest->disk1) {
1012 snprintf(cmd, sizeof(cmd), "/sbin/mdadm --zero-superblock %s", dest->disk1->path);
1013 mysystem(output, cmd);
1014 }
1015
1016 if (dest->disk2) {
1017 snprintf(cmd, sizeof(cmd), "/sbin/mdadm --zero-superblock %s", dest->disk2->path);
1018 mysystem(output, cmd);
1019 }
1020
1021 return 0;
1022 }
1023
1024 int hw_setup_raid(struct hw_destination* dest, const char* output) {
1025 char* cmd = NULL;
1026 int r;
1027
1028 assert(dest->is_raid);
1029
1030 // Stop all RAID arrays that might be around (again).
1031 // It seems that there is some sort of race-condition with udev re-enabling
1032 // the raid arrays and therefore locking the disks.
1033 r = hw_destroy_raid_superblocks(dest, output);
1034
1035 asprintf(&cmd, "echo \"y\" | /sbin/mdadm --create --verbose --metadata=%s --auto=mdp %s",
1036 RAID_METADATA, dest->path);
1037
1038 switch (dest->raid_level) {
1039 case 1:
1040 asprintf(&cmd, "%s --level=1 --raid-devices=2", cmd);
1041 break;
1042
1043 default:
1044 assert(0);
1045 }
1046
1047 if (dest->disk1) {
1048 asprintf(&cmd, "%s %s", cmd, dest->disk1->path);
1049
1050 // Clear all data at the beginning
1051 r = hw_zero_out_device(dest->disk1->path, MB2BYTES(10));
1052 if (r <= 0)
1053 return r;
1054 }
1055
1056 if (dest->disk2) {
1057 asprintf(&cmd, "%s %s", cmd, dest->disk2->path);
1058
1059 // Clear all data at the beginning
1060 r = hw_zero_out_device(dest->disk2->path, MB2BYTES(10));
1061 if (r <= 0)
1062 return r;
1063 }
1064
1065 r = mysystem(output, cmd);
1066 free(cmd);
1067
1068 // Wait a moment until the device has been properly brought up
1069 if (r == 0) {
1070 unsigned int counter = 10;
1071 while (counter-- > 0) {
1072 sleep(1);
1073
1074 // If the raid device has not yet been properly brought up,
1075 // opening it will fail with the message: Device or resource busy
1076 // Hence we will wait a bit until it becomes usable.
1077 if (try_open(dest->path) == 0)
1078 break;
1079 }
1080 }
1081
1082 return r;
1083 }
1084
1085 int hw_stop_all_raid_arrays(const char* output) {
1086 return mysystem(output, "/sbin/mdadm --stop --scan --verbose");
1087 }
1088
1089 int hw_install_bootloader(struct hw* hw, struct hw_destination* dest, const char* output) {
1090 char cmd[STRING_SIZE];
1091
1092 snprintf(cmd, sizeof(cmd), "/usr/bin/install-bootloader %s", dest->path);
1093 int r = system_chroot(output, DESTINATION_MOUNT_PATH, cmd);
1094 if (r)
1095 return r;
1096
1097 hw_sync();
1098
1099 return 0;
1100 }
1101
1102 static char* hw_get_uuid(const char* dev) {
1103 blkid_probe p = blkid_new_probe_from_filename(dev);
1104 const char* buffer = NULL;
1105 char* uuid = NULL;
1106
1107 if (!p)
1108 return NULL;
1109
1110 blkid_do_probe(p);
1111 blkid_probe_lookup_value(p, "UUID", &buffer, NULL);
1112
1113 if (buffer)
1114 uuid = strdup(buffer);
1115
1116 blkid_free_probe(p);
1117
1118 return uuid;
1119 }
1120
1121 #define FSTAB_FMT "UUID=%s %-8s %-4s %-10s %d %d\n"
1122
1123 int hw_write_fstab(struct hw_destination* dest) {
1124 FILE* f = fopen(DESTINATION_MOUNT_PATH "/etc/fstab", "w");
1125 if (!f)
1126 return -1;
1127
1128 char* uuid = NULL;
1129
1130 // boot
1131 if (*dest->part_boot) {
1132 uuid = hw_get_uuid(dest->part_boot);
1133
1134 if (uuid) {
1135 fprintf(f, FSTAB_FMT, uuid, "/boot", "auto", "defaults,nodev,noexec,nosuid", 1, 2);
1136 free(uuid);
1137 }
1138 }
1139
1140 // ESP
1141 if (*dest->part_boot_efi) {
1142 uuid = hw_get_uuid(dest->part_boot_efi);
1143
1144 if (uuid) {
1145 fprintf(f, FSTAB_FMT, uuid, "/boot/efi", "auto", "defaults", 1, 2);
1146 free(uuid);
1147 }
1148 }
1149
1150
1151 // swap
1152 if (*dest->part_swap) {
1153 uuid = hw_get_uuid(dest->part_swap);
1154
1155 if (uuid) {
1156 fprintf(f, FSTAB_FMT, uuid, "swap", "swap", "defaults,pri=1", 0, 0);
1157 free(uuid);
1158 }
1159 }
1160
1161 // root
1162 uuid = hw_get_uuid(dest->part_root);
1163 if (uuid) {
1164 fprintf(f, FSTAB_FMT, uuid, "/", "auto", "defaults", 1, 1);
1165 free(uuid);
1166 }
1167
1168 fclose(f);
1169
1170 return 0;
1171 }
1172
1173 void hw_sync() {
1174 sync();
1175 sync();
1176 sync();
1177 }
1178
1179 int hw_start_networking(const char* output) {
1180 return mysystem(output, "/usr/bin/start-networking.sh");
1181 }
1182
1183 char* hw_find_backup_file(const char* output, const char* search_path) {
1184 char path[STRING_SIZE];
1185
1186 snprintf(path, sizeof(path), "%s/backup.ipf", search_path);
1187 int r = access(path, R_OK);
1188
1189 if (r == 0)
1190 return strdup(path);
1191
1192 return NULL;
1193 }
1194
1195 int hw_restore_backup(const char* output, const char* backup_path, const char* destination) {
1196 char command[STRING_SIZE];
1197
1198 snprintf(command, sizeof(command), "/bin/tar xzpf %s -C %s "
1199 "--exclude-from=%s/var/ipfire/backup/exclude --exclude-from=%s/var/ipfire/backup/exclude.user",
1200 backup_path, destination, destination, destination);
1201 int rc = mysystem(output, command);
1202
1203 if (rc)
1204 return -1;
1205
1206 return 0;
1207 }