cd9660_eltorito.c revision 221387
1/*	$NetBSD: cd9660_eltorito.c,v 1.14 2010/10/27 18:51:35 christos Exp $	*/
2
3/*
4 * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
5 * Perez-Rathke and Ram Vedam.  All rights reserved.
6 *
7 * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
8 * Alan Perez-Rathke and Ram Vedam.
9 *
10 * Redistribution and use in source and binary forms, with or
11 * without modification, are permitted provided that the following
12 * conditions are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above
16 *    copyright notice, this list of conditions and the following
17 *    disclaimer in the documentation and/or other materials provided
18 *    with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN
21 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 * DISCLAIMED.  IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN
25 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
32 * OF SUCH DAMAGE.
33 */
34
35#include <netinet/in.h>
36
37#include "cd9660.h"
38#include "cd9660_eltorito.h"
39
40#include <sys/cdefs.h>
41__FBSDID("$FreeBSD: head/usr.sbin/makefs/cd9660/cd9660_eltorito.c 221387 2011-05-03 15:12:01Z nwhitehorn $");
42
43#ifdef DEBUG
44#define	ELTORITO_DPRINTF(__x)	printf __x
45#else
46#define	ELTORITO_DPRINTF(__x)
47#endif
48
49static struct boot_catalog_entry *cd9660_init_boot_catalog_entry(void);
50static struct boot_catalog_entry *cd9660_boot_setup_validation_entry(char);
51static struct boot_catalog_entry *cd9660_boot_setup_default_entry(
52    struct cd9660_boot_image *);
53static struct boot_catalog_entry *cd9660_boot_setup_section_head(char);
54static struct boot_catalog_entry *cd9660_boot_setup_validation_entry(char);
55#if 0
56static u_char cd9660_boot_get_system_type(struct cd9660_boot_image *);
57#endif
58
59int
60cd9660_add_boot_disk(const char *boot_info)
61{
62	struct stat stbuf;
63	const char *mode_msg;
64	char *temp;
65	char *sysname;
66	char *filename;
67	struct cd9660_boot_image *new_image, *tmp_image;
68
69	assert(boot_info != NULL);
70
71	if (*boot_info == '\0') {
72		warnx("Error: Boot disk information must be in the "
73		      "format 'system;filename'");
74		return 0;
75	}
76
77	/* First decode the boot information */
78	if ((temp = strdup(boot_info)) == NULL) {
79		warn("%s: strdup", __func__);
80		return 0;
81	}
82
83	sysname = temp;
84	filename = strchr(sysname, ';');
85	if (filename == NULL) {
86		warnx("supply boot disk information in the format "
87		    "'system;filename'");
88		free(temp);
89		return 0;
90	}
91
92	*filename++ = '\0';
93
94	if (diskStructure.verbose_level > 0) {
95		printf("Found bootdisk with system %s, and filename %s\n",
96		    sysname, filename);
97	}
98	if ((new_image = malloc(sizeof(*new_image))) == NULL) {
99		warn("%s: malloc", __func__);
100		free(temp);
101		return 0;
102	}
103	(void)memset(new_image, 0, sizeof(*new_image));
104	new_image->loadSegment = 0;	/* default for now */
105
106	/* Decode System */
107	if (strcmp(sysname, "i386") == 0)
108		new_image->system = ET_SYS_X86;
109	else if (strcmp(sysname, "powerpc") == 0)
110		new_image->system = ET_SYS_PPC;
111	else if (strcmp(sysname, "macppc") == 0 ||
112	         strcmp(sysname, "mac68k") == 0)
113		new_image->system = ET_SYS_MAC;
114	else {
115		warnx("boot disk system must be "
116		      "i386, powerpc, macppc, or mac68k");
117		free(temp);
118		free(new_image);
119		return 0;
120	}
121
122
123	if ((new_image->filename = strdup(filename)) == NULL) {
124		warn("%s: strdup", __func__);
125		free(temp);
126		free(new_image);
127		return 0;
128	}
129
130	free(temp);
131
132	/* Get information about the file */
133	if (lstat(new_image->filename, &stbuf) == -1)
134		err(EXIT_FAILURE, "%s: lstat(\"%s\")", __func__,
135		    new_image->filename);
136
137	switch (stbuf.st_size) {
138	case 1440 * 1024:
139		new_image->targetMode = ET_MEDIA_144FDD;
140		mode_msg = "Assigned boot image to 1.44 emulation mode";
141		break;
142	case 1200 * 1024:
143		new_image->targetMode = ET_MEDIA_12FDD;
144		mode_msg = "Assigned boot image to 1.2 emulation mode";
145		break;
146	case 2880 * 1024:
147		new_image->targetMode = ET_MEDIA_288FDD;
148		mode_msg = "Assigned boot image to 2.88 emulation mode";
149		break;
150	default:
151		new_image->targetMode = ET_MEDIA_NOEM;
152		mode_msg = "Assigned boot image to no emulation mode";
153		break;
154	}
155
156	if (diskStructure.verbose_level > 0)
157		printf("%s\n", mode_msg);
158
159	new_image->size = stbuf.st_size;
160	new_image->num_sectors =
161	    howmany(new_image->size, diskStructure.sectorSize) *
162	    howmany(diskStructure.sectorSize, 512);
163	if (diskStructure.verbose_level > 0) {
164		printf("New image has size %d, uses %d 512-byte sectors\n",
165		    new_image->size, new_image->num_sectors);
166	}
167	new_image->sector = -1;
168	/* Bootable by default */
169	new_image->bootable = ET_BOOTABLE;
170	/* Add boot disk */
171
172	/* Group images for the same platform together. */
173	TAILQ_FOREACH(tmp_image, &diskStructure.boot_images, image_list) {
174		if (tmp_image->system != new_image->system)
175			break;
176	}
177
178	if (tmp_image == NULL) {
179		TAILQ_INSERT_HEAD(&diskStructure.boot_images, new_image,
180		    image_list);
181	} else
182		TAILQ_INSERT_BEFORE(tmp_image, new_image, image_list);
183
184	new_image->serialno = diskStructure.image_serialno++;
185
186	/* TODO : Need to do anything about the boot image in the tree? */
187	diskStructure.is_bootable = 1;
188
189	return 1;
190}
191
192int
193cd9660_eltorito_add_boot_option(const char *option_string, const char *value)
194{
195	char *eptr;
196	struct cd9660_boot_image *image;
197
198	assert(option_string != NULL);
199
200	/* Find the last image added */
201	TAILQ_FOREACH(image, &diskStructure.boot_images, image_list) {
202		if (image->serialno + 1 == diskStructure.image_serialno)
203			break;
204	}
205	if (image == NULL)
206		errx(EXIT_FAILURE, "Attempted to add boot option, "
207		    "but no boot images have been specified");
208
209	if (strcmp(option_string, "no-emul-boot") == 0) {
210		image->targetMode = ET_MEDIA_NOEM;
211	} else if (strcmp(option_string, "no-boot") == 0) {
212		image->bootable = ET_NOT_BOOTABLE;
213	} else if (strcmp(option_string, "hard-disk-boot") == 0) {
214		image->targetMode = ET_MEDIA_HDD;
215	} else if (strcmp(option_string, "boot-load-segment") == 0) {
216		image->loadSegment = strtoul(value, &eptr, 16);
217		if (eptr == value || *eptr != '\0' || errno != ERANGE) {
218			warn("%s: strtoul", __func__);
219			return 0;
220		}
221	} else {
222		return 0;
223	}
224	return 1;
225}
226
227static struct boot_catalog_entry *
228cd9660_init_boot_catalog_entry(void)
229{
230	struct boot_catalog_entry *temp;
231
232	if ((temp = malloc(sizeof(*temp))) == NULL)
233		return NULL;
234
235	return memset(temp, 0, sizeof(*temp));
236}
237
238static struct boot_catalog_entry *
239cd9660_boot_setup_validation_entry(char sys)
240{
241	struct boot_catalog_entry *entry;
242	boot_catalog_validation_entry *ve;
243	int16_t checksum;
244	unsigned char *csptr;
245	int i;
246	entry = cd9660_init_boot_catalog_entry();
247
248	if (entry == NULL) {
249		warnx("Error: memory allocation failed in "
250		      "cd9660_boot_setup_validation_entry");
251		return 0;
252	}
253	ve = &entry->entry_data.VE;
254
255	ve->header_id[0] = 1;
256	ve->platform_id[0] = sys;
257	ve->key[0] = 0x55;
258	ve->key[1] = 0xAA;
259
260	/* Calculate checksum */
261	checksum = 0;
262	cd9660_721(0, ve->checksum);
263	csptr = (unsigned char*)ve;
264	for (i = 0; i < sizeof(*ve); i += 2) {
265		checksum += (int16_t)csptr[i];
266		checksum += 256 * (int16_t)csptr[i + 1];
267	}
268	checksum = -checksum;
269	cd9660_721(checksum, ve->checksum);
270
271        ELTORITO_DPRINTF(("%s: header_id %d, platform_id %d, key[0] %d, key[1] %d, "
272	    "checksum %04x\n", __func__, ve->header_id[0], ve->platform_id[0],
273	    ve->key[0], ve->key[1], checksum));
274	return entry;
275}
276
277static struct boot_catalog_entry *
278cd9660_boot_setup_default_entry(struct cd9660_boot_image *disk)
279{
280	struct boot_catalog_entry *default_entry;
281	boot_catalog_initial_entry *ie;
282
283	default_entry = cd9660_init_boot_catalog_entry();
284	if (default_entry == NULL)
285		return NULL;
286
287	ie = &default_entry->entry_data.IE;
288
289	ie->boot_indicator[0] = disk->bootable;
290	ie->media_type[0] = disk->targetMode;
291	cd9660_721(disk->loadSegment, ie->load_segment);
292	ie->system_type[0] = disk->system;
293	cd9660_721(disk->num_sectors, ie->sector_count);
294	cd9660_731(disk->sector, ie->load_rba);
295
296	ELTORITO_DPRINTF(("%s: boot indicator %d, media type %d, "
297	    "load segment %04x, system type %d, sector count %d, "
298	    "load rba %d\n", __func__, ie->boot_indicator[0],
299	    ie->media_type[0], disk->loadSegment, ie->system_type[0],
300	    disk->num_sectors, disk->sector));
301	return default_entry;
302}
303
304static struct boot_catalog_entry *
305cd9660_boot_setup_section_head(char platform)
306{
307	struct boot_catalog_entry *entry;
308	boot_catalog_section_header *sh;
309
310	entry = cd9660_init_boot_catalog_entry();
311	if (entry == NULL)
312		return NULL;
313
314	sh = &entry->entry_data.SH;
315	/* More by default. The last one will manually be set to 0x91 */
316	sh->header_indicator[0] = ET_SECTION_HEADER_MORE;
317	sh->platform_id[0] = platform;
318	sh->num_section_entries[0] = 0;
319	return entry;
320}
321
322static struct boot_catalog_entry *
323cd9660_boot_setup_section_entry(struct cd9660_boot_image *disk)
324{
325	struct boot_catalog_entry *entry;
326	boot_catalog_section_entry *se;
327	if ((entry = cd9660_init_boot_catalog_entry()) == NULL)
328		return NULL;
329
330	se = &entry->entry_data.SE;
331
332	se->boot_indicator[0] = ET_BOOTABLE;
333	se->media_type[0] = disk->targetMode;
334	cd9660_721(disk->loadSegment, se->load_segment);
335	cd9660_721(disk->num_sectors, se->sector_count);
336	cd9660_731(disk->sector, se->load_rba);
337	return entry;
338}
339
340#if 0
341static u_char
342cd9660_boot_get_system_type(struct cd9660_boot_image *disk)
343{
344	/*
345		For hard drive booting, we need to examine the MBR to figure
346		out what the partition type is
347	*/
348	return 0;
349}
350#endif
351
352/*
353 * Set up the BVD, Boot catalog, and the boot entries, but do no writing
354 */
355int
356cd9660_setup_boot(int first_sector)
357{
358	int sector;
359	int used_sectors;
360	int num_entries = 0;
361	int catalog_sectors;
362	struct boot_catalog_entry *x86_head, *mac_head, *ppc_head,
363		*valid_entry, *default_entry, *temp, *head, **headp, *next;
364	struct cd9660_boot_image *tmp_disk;
365
366	headp = NULL;
367	x86_head = mac_head = ppc_head = NULL;
368
369	/* If there are no boot disks, don't bother building boot information */
370	if (TAILQ_EMPTY(&diskStructure.boot_images))
371		return 0;
372
373	/* Point to catalog: For now assume it consumes one sector */
374	ELTORITO_DPRINTF(("Boot catalog will go in sector %d\n", first_sector));
375	diskStructure.boot_catalog_sector = first_sector;
376	cd9660_bothendian_dword(first_sector,
377		diskStructure.boot_descriptor->boot_catalog_pointer);
378
379	/* Step 1: Generate boot catalog */
380	/* Step 1a: Validation entry */
381	valid_entry = cd9660_boot_setup_validation_entry(ET_SYS_X86);
382	if (valid_entry == NULL)
383		return -1;
384
385	/*
386	 * Count how many boot images there are,
387	 * and how many sectors they consume.
388	 */
389	num_entries = 1;
390	used_sectors = 0;
391
392	TAILQ_FOREACH(tmp_disk, &diskStructure.boot_images, image_list) {
393		used_sectors += tmp_disk->num_sectors;
394
395		/* One default entry per image */
396		num_entries++;
397	}
398	catalog_sectors = howmany(num_entries * 0x20, diskStructure.sectorSize);
399	used_sectors += catalog_sectors;
400
401	if (diskStructure.verbose_level > 0) {
402		printf("%s: there will be %i entries consuming %i sectors. "
403		       "Catalog is %i sectors\n", __func__, num_entries,
404		       used_sectors, catalog_sectors);
405	}
406
407	/* Populate sector numbers */
408	sector = first_sector + catalog_sectors;
409	TAILQ_FOREACH(tmp_disk, &diskStructure.boot_images, image_list) {
410		tmp_disk->sector = sector;
411		sector += tmp_disk->num_sectors;
412	}
413
414	LIST_INSERT_HEAD(&diskStructure.boot_entries, valid_entry, ll_struct);
415
416	/* Step 1b: Initial/default entry */
417	/* TODO : PARAM */
418	tmp_disk = TAILQ_FIRST(&diskStructure.boot_images);
419	default_entry = cd9660_boot_setup_default_entry(tmp_disk);
420	if (default_entry == NULL) {
421		warnx("Error: memory allocation failed in cd9660_setup_boot");
422		return -1;
423	}
424
425	LIST_INSERT_AFTER(valid_entry, default_entry, ll_struct);
426
427	/* Todo: multiple default entries? */
428
429	tmp_disk = TAILQ_NEXT(tmp_disk, image_list);
430
431	temp = default_entry;
432
433	/* If multiple boot images are given : */
434	while (tmp_disk != NULL) {
435		/* Step 2: Section header */
436		switch (tmp_disk->system) {
437		case ET_SYS_X86:
438			headp = &x86_head;
439			break;
440		case ET_SYS_PPC:
441			headp = &ppc_head;
442			break;
443		case ET_SYS_MAC:
444			headp = &mac_head;
445			break;
446		default:
447			warnx("%s: internal error: unknown system type",
448			    __func__);
449			return -1;
450		}
451
452		if (*headp == NULL) {
453			head =
454			    cd9660_boot_setup_section_head(tmp_disk->system);
455			if (head == NULL) {
456				warnx("Error: memory allocation failed in "
457				      "cd9660_setup_boot");
458				return -1;
459			}
460			LIST_INSERT_AFTER(default_entry, head, ll_struct);
461			*headp = head;
462		} else
463			head = *headp;
464
465		head->entry_data.SH.num_section_entries[0]++;
466
467		/* Step 2a: Section entry and extensions */
468		temp = cd9660_boot_setup_section_entry(tmp_disk);
469		if (temp == NULL) {
470			warn("%s: cd9660_boot_setup_section_entry", __func__);
471			return -1;
472		}
473
474		while ((next = LIST_NEXT(head, ll_struct)) != NULL &&
475		       next->entry_type == ET_ENTRY_SE)
476			head = next;
477
478		LIST_INSERT_AFTER(head, temp, ll_struct);
479		tmp_disk = TAILQ_NEXT(tmp_disk, image_list);
480	}
481
482	/* TODO: Remaining boot disks when implemented */
483
484	return first_sector + used_sectors;
485}
486
487int
488cd9660_setup_boot_volume_descriptor(volume_descriptor *bvd)
489{
490	boot_volume_descriptor *bvdData =
491	    (boot_volume_descriptor*)bvd->volumeDescriptorData;
492
493	bvdData->boot_record_indicator[0] = ISO_VOLUME_DESCRIPTOR_BOOT;
494	memcpy(bvdData->identifier, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
495	bvdData->version[0] = 1;
496	memcpy(bvdData->boot_system_identifier, ET_ID, 23);
497	memcpy(bvdData->identifier, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
498	diskStructure.boot_descriptor =
499	    (boot_volume_descriptor*) bvd->volumeDescriptorData;
500	return 1;
501}
502
503static int
504cd9660_write_apm_partition_entry(FILE *fd, int index, int total_partitions,
505    off_t sector_start, off_t nsectors, off_t sector_size,
506    const char *part_name, const char *part_type) {
507	uint32_t apm32;
508	uint16_t apm16;
509
510	fseeko(fd, (off_t)(index + 1) * sector_size, SEEK_SET);
511
512	/* Signature */
513	apm16 = htons(0x504d);
514	fwrite(&apm16, sizeof(apm16), 1, fd);
515	apm16 = 0;
516	fwrite(&apm16, sizeof(apm16), 1, fd);
517
518	/* Total number of partitions */
519	apm32 = htonl(total_partitions);
520	fwrite(&apm32, sizeof(apm32), 1, fd);
521	/* Bounds */
522	apm32 = htonl(sector_start);
523	fwrite(&apm32, sizeof(apm32), 1, fd);
524	apm32 = htonl(nsectors);
525	fwrite(&apm32, sizeof(apm32), 1, fd);
526
527	fwrite(part_name, strlen(part_name) + 1, 1, fd);
528	fseek(fd, 32 - strlen(part_name) - 1, SEEK_CUR);
529	fwrite(part_type, strlen(part_type) + 1, 1, fd);
530
531	return 0;
532}
533
534int
535cd9660_write_boot(FILE *fd)
536{
537	struct boot_catalog_entry *e;
538	struct cd9660_boot_image *t;
539	int apm_partitions = 0;
540
541	/* write boot catalog */
542	if (fseeko(fd, (off_t)diskStructure.boot_catalog_sector *
543	    diskStructure.sectorSize, SEEK_SET) == -1)
544		err(1, "fseeko");
545
546	if (diskStructure.verbose_level > 0) {
547		printf("Writing boot catalog to sector %" PRId64 "\n",
548		    diskStructure.boot_catalog_sector);
549	}
550	LIST_FOREACH(e, &diskStructure.boot_entries, ll_struct) {
551		if (diskStructure.verbose_level > 0) {
552			printf("Writing catalog entry of type %d\n",
553			    e->entry_type);
554		}
555		/*
556		 * It doesnt matter which one gets written
557		 * since they are the same size
558		 */
559		fwrite(&(e->entry_data.VE), 1, 32, fd);
560	}
561	if (diskStructure.verbose_level > 0)
562		printf("Finished writing boot catalog\n");
563
564	/* copy boot images */
565	TAILQ_FOREACH(t, &diskStructure.boot_images, image_list) {
566		if (diskStructure.verbose_level > 0) {
567			printf("Writing boot image from %s to sectors %d\n",
568			    t->filename, t->sector);
569		}
570		cd9660_copy_file(fd, t->sector, t->filename);
571
572		if (t->system == ET_SYS_MAC)
573			apm_partitions++;
574	}
575
576	if (apm_partitions > 0) {
577		/* Write DDR and global APM info */
578		uint32_t apm32;
579		uint16_t apm16;
580		int total_parts;
581
582		fseek(fd, 0, SEEK_SET);
583		apm16 = htons(0x4552);
584		fwrite(&apm16, sizeof(apm16), 1, fd);
585		apm16 = htons(diskStructure.sectorSize);
586		fwrite(&apm16, sizeof(apm16), 1, fd);
587		apm32 = htonl(diskStructure.totalSectors);
588		fwrite(&apm32, sizeof(apm32), 1, fd);
589
590		/* Count total needed entries */
591		total_parts = 2 + apm_partitions; /* Self + ISO9660 */
592
593		/* Write self-descriptor */
594		cd9660_write_apm_partition_entry(fd, 0,
595		    total_parts, 1, total_parts, diskStructure.sectorSize,
596		    "Apple", "Apple_partition_map");
597
598		/* Write ISO9660 descriptor, enclosing the whole disk */
599		cd9660_write_apm_partition_entry(fd, 1,
600		    total_parts, 0, diskStructure.totalSectors,
601		    diskStructure.sectorSize, "", "CD_ROM_Mode_1");
602
603		/* Write all partition entries */
604		apm_partitions = 0;
605		TAILQ_FOREACH(t, &diskStructure.boot_images, image_list) {
606			if (t->system != ET_SYS_MAC)
607				continue;
608
609			cd9660_write_apm_partition_entry(fd,
610			    2 + apm_partitions++, total_parts,
611			    t->sector, t->num_sectors, diskStructure.sectorSize,
612			    "CD Boot", "Apple_Bootstrap");
613		}
614	}
615
616	return 0;
617}
618
619