xref: /netbsd-src/usr.sbin/makefs/cd9660/cd9660_write.c (revision a4ddc2c8fb9af816efe3b1c375a5530aef0e89e9)
1 /*	$NetBSD: cd9660_write.c,v 1.16 2013/01/28 21:03:28 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 "cd9660.h"
36 #include "iso9660_rrip.h"
37 
38 #include <sys/cdefs.h>
39 #if defined(__RCSID) && !defined(__lint)
40 __RCSID("$NetBSD: cd9660_write.c,v 1.16 2013/01/28 21:03:28 christos Exp $");
41 #endif  /* !__lint */
42 
43 #include <util.h>
44 
45 static int cd9660_write_volume_descriptors(iso9660_disk *, FILE *);
46 static int cd9660_write_path_table(iso9660_disk *, FILE *, off_t, int);
47 static int cd9660_write_path_tables(iso9660_disk *, FILE *);
48 static int cd9660_write_file(iso9660_disk *, FILE *, cd9660node *);
49 static int cd9660_write_filedata(iso9660_disk *, FILE *, off_t,
50     const unsigned char *, int);
51 #if 0
52 static int cd9660_write_buffered(FILE *, off_t, int, const unsigned char *);
53 #endif
54 static void cd9660_write_rr(iso9660_disk *, FILE *, cd9660node *, off_t, off_t);
55 
56 /*
57  * Write the image
58  * Writes the entire image
59  * @param const char* The filename for the image
60  * @returns int 1 on success, 0 on failure
61  */
62 int
63 cd9660_write_image(iso9660_disk *diskStructure, const char* image)
64 {
65 	FILE *fd;
66 	int status;
67 	char buf[CD9660_SECTOR_SIZE];
68 
69 	if ((fd = fopen(image, "w+")) == NULL) {
70 		err(EXIT_FAILURE, "%s: Can't open `%s' for writing", __func__,
71 		    image);
72 	}
73 
74 	if (diskStructure->verbose_level > 0)
75 		printf("Writing image\n");
76 
77 	if (diskStructure->has_generic_bootimage) {
78 		status = cd9660_copy_file(diskStructure, fd, 0,
79 		    diskStructure->generic_bootimage);
80 		if (status == 0) {
81 			warnx("%s: Error writing generic boot image",
82 			    __func__);
83 			goto cleanup_bad_image;
84 		}
85 	}
86 
87 	/* Write the volume descriptors */
88 	status = cd9660_write_volume_descriptors(diskStructure, fd);
89 	if (status == 0) {
90 		warnx("%s: Error writing volume descriptors to image",
91 		    __func__);
92 		goto cleanup_bad_image;
93 	}
94 
95 	if (diskStructure->verbose_level > 0)
96 		printf("Volume descriptors written\n");
97 
98 	/*
99 	 * Write the path tables: there are actually four, but right
100 	 * now we are only concearned with two.
101 	 */
102 	status = cd9660_write_path_tables(diskStructure, fd);
103 	if (status == 0) {
104 		warnx("%s: Error writing path tables to image", __func__);
105 		goto cleanup_bad_image;
106 	}
107 
108 	if (diskStructure->verbose_level > 0)
109 		printf("Path tables written\n");
110 
111 	/* Write the directories and files */
112 	status = cd9660_write_file(diskStructure, fd, diskStructure->rootNode);
113 	if (status == 0) {
114 		warnx("%s: Error writing files to image", __func__);
115 		goto cleanup_bad_image;
116 	}
117 
118 	if (diskStructure->is_bootable) {
119 		cd9660_write_boot(diskStructure, fd);
120 	}
121 
122 	/* Write padding bits. This is temporary */
123 	memset(buf, 0, CD9660_SECTOR_SIZE);
124 	cd9660_write_filedata(diskStructure, fd,
125 	    diskStructure->totalSectors - 1, buf, 1);
126 
127 	if (diskStructure->verbose_level > 0)
128 		printf("Files written\n");
129 	fclose(fd);
130 
131 	if (diskStructure->verbose_level > 0)
132 		printf("Image closed\n");
133 	return 1;
134 
135 cleanup_bad_image:
136 	fclose(fd);
137 	if (!diskStructure->keep_bad_images)
138 		unlink(image);
139 	if (diskStructure->verbose_level > 0)
140 		printf("Bad image cleaned up\n");
141 	return 0;
142 }
143 
144 static int
145 cd9660_write_volume_descriptors(iso9660_disk *diskStructure, FILE *fd)
146 {
147 	volume_descriptor *vd_temp = diskStructure->firstVolumeDescriptor;
148 	int pos;
149 
150 	while (vd_temp != NULL) {
151 		pos = vd_temp->sector * diskStructure->sectorSize;
152 		cd9660_write_filedata(diskStructure, fd, vd_temp->sector,
153 		    vd_temp->volumeDescriptorData, 1);
154 		vd_temp = vd_temp->next;
155 	}
156 	return 1;
157 }
158 
159 /*
160  * Write out an individual path table
161  * Used just to keep redundant code to a minimum
162  * @param FILE *fd Valid file pointer
163  * @param int Sector to start writing path table to
164  * @param int Endian mode : BIG_ENDIAN or LITTLE_ENDIAN
165  * @returns int 1 on success, 0 on failure
166  */
167 static int
168 cd9660_write_path_table(iso9660_disk *diskStructure, FILE *fd, off_t sector,
169     int mode)
170 {
171 	int path_table_sectors = CD9660_BLOCKS(diskStructure->sectorSize,
172 	    diskStructure->pathTableLength);
173 	unsigned char *buffer;
174 	unsigned char *buffer_head;
175 	int len;
176 	path_table_entry temp_entry;
177 	cd9660node *ptcur;
178 
179 	buffer = ecalloc(path_table_sectors, diskStructure->sectorSize);
180 	buffer_head = buffer;
181 
182 	ptcur = diskStructure->rootNode;
183 
184 	while (ptcur != NULL) {
185 		memset(&temp_entry, 0, sizeof(path_table_entry));
186 		temp_entry.length[0] = ptcur->isoDirRecord->name_len[0];
187 		temp_entry.extended_attribute_length[0] =
188 		    ptcur->isoDirRecord->ext_attr_length[0];
189 		memcpy(temp_entry.name, ptcur->isoDirRecord->name,
190 		    temp_entry.length[0] + 1);
191 
192 		/* round up */
193 		len = temp_entry.length[0] + 8 + (temp_entry.length[0] & 0x01);
194 
195                 /* todo: function pointers instead */
196 		if (mode == LITTLE_ENDIAN) {
197 			cd9660_731(ptcur->fileDataSector,
198 			    temp_entry.first_sector);
199 			cd9660_721((ptcur->parent == NULL ?
200 				1 : ptcur->parent->ptnumber),
201 			    temp_entry.parent_number);
202 		} else {
203 			cd9660_732(ptcur->fileDataSector,
204 			    temp_entry.first_sector);
205 			cd9660_722((ptcur->parent == NULL ?
206 				1 : ptcur->parent->ptnumber),
207 			    temp_entry.parent_number);
208 		}
209 
210 
211 		memcpy(buffer, &temp_entry, len);
212 		buffer += len;
213 
214 		ptcur = ptcur->ptnext;
215 	}
216 
217 	return cd9660_write_filedata(diskStructure, fd, sector, buffer_head,
218 	    path_table_sectors);
219 }
220 
221 
222 /*
223  * Write out the path tables to disk
224  * Each file descriptor should be pointed to by the PVD, so we know which
225  * sector to copy them to. One thing to watch out for: the only path tables
226  * stored are in the endian mode that the application is compiled for. So,
227  * the first thing to do is write out that path table, then to write the one
228  * in the other endian mode requires to convert the endianness of each entry
229  * in the table. The best way to do this would be to create a temporary
230  * path_table_entry structure, then for each path table entry, copy it to
231  * the temporary entry, translate, then copy that to disk.
232  *
233  * @param FILE* Valid file descriptor
234  * @returns int 0 on failure, 1 on success
235  */
236 static int
237 cd9660_write_path_tables(iso9660_disk *diskStructure, FILE *fd)
238 {
239 	if (cd9660_write_path_table(diskStructure, fd,
240 	    diskStructure->primaryLittleEndianTableSector, LITTLE_ENDIAN) == 0)
241 		return 0;
242 
243 	if (cd9660_write_path_table(diskStructure, fd,
244 	    diskStructure->primaryBigEndianTableSector, BIG_ENDIAN) == 0)
245 		return 0;
246 
247 	/* @TODO: handle remaining two path tables */
248 	return 1;
249 }
250 
251 /*
252  * Write a file to disk
253  * Writes a file, its directory record, and its data to disk
254  * This file is designed to be called RECURSIVELY, so initially call it
255  * with the root node. All of the records should store what sector the
256  * file goes in, so no computation should be  necessary.
257  *
258  * @param int fd Valid file descriptor
259  * @param struct cd9660node* writenode Pointer to the file to be written
260  * @returns int 0 on failure, 1 on success
261  */
262 static int
263 cd9660_write_file(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode)
264 {
265 	char *buf;
266 	char *temp_file_name;
267 	int ret;
268 	off_t working_sector;
269 	int cur_sector_offset;
270 	int written;
271 	iso_directory_record_cd9660 temp_record;
272 	cd9660node *temp;
273 	int rv = 0;
274 
275 	/* Todo : clean up variables */
276 
277 	temp_file_name = ecalloc(CD9660MAXPATH + 1, 1);
278 	buf = emalloc(diskStructure->sectorSize);
279 	if ((writenode->level != 0) &&
280 	    !(writenode->node->type & S_IFDIR)) {
281 		fsinode *inode = writenode->node->inode;
282 		/* Only attempt to write unwritten files that have length. */
283 		if ((inode->flags & FI_WRITTEN) != 0) {
284 			INODE_WARNX(("%s: skipping written inode %d", __func__,
285 			    (int)inode->st.st_ino));
286 		} else if (writenode->fileDataLength > 0) {
287 			INODE_WARNX(("%s: writing inode %d blocks at %" PRIu32,
288 			    __func__, (int)inode->st.st_ino, inode->ino));
289 			inode->flags |= FI_WRITTEN;
290 			cd9660_compute_full_filename(writenode,
291 			    temp_file_name);
292 			ret = cd9660_copy_file(diskStructure, fd,
293 			    writenode->fileDataSector, temp_file_name);
294 			if (ret == 0)
295 				goto out;
296 		}
297 	} else {
298 		/*
299 		 * Here is a new revelation that ECMA didnt explain
300 		 * (at least not well).
301 		 * ALL . and .. records store the name "\0" and "\1"
302 		 * resepctively. So, for each directory, we have to
303 		 * make a new node.
304 		 *
305 		 * This is where it gets kinda messy, since we have to
306 		 * be careful of sector boundaries
307 		 */
308 		cur_sector_offset = 0;
309 		working_sector = writenode->fileDataSector;
310 		if (fseeko(fd, working_sector * diskStructure->sectorSize,
311 		    SEEK_SET) == -1)
312 			err(1, "fseeko");
313 
314 		/*
315 		 * Now loop over children, writing out their directory
316 		 * records - beware of sector boundaries
317 	 	 */
318 		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
319 			/*
320 			 * Copy the temporary record and adjust its size
321 			 * if necessary
322 			 */
323 			memcpy(&temp_record, temp->isoDirRecord,
324 			    sizeof(iso_directory_record_cd9660));
325 
326 			temp_record.length[0] =
327 			    cd9660_compute_record_size(diskStructure, temp);
328 
329 			if (temp_record.length[0] + cur_sector_offset >=
330 			    diskStructure->sectorSize) {
331 				cur_sector_offset = 0;
332 				working_sector++;
333 
334 				/* Seek to the next sector. */
335 				if (fseeko(fd, working_sector *
336 				    diskStructure->sectorSize, SEEK_SET) == -1)
337 					err(1, "fseeko");
338 			}
339 			/* Write out the basic ISO directory record */
340 			written = fwrite(&temp_record, 1,
341 			    temp->isoDirRecord->length[0], fd);
342 			if (diskStructure->rock_ridge_enabled) {
343 				cd9660_write_rr(diskStructure, fd, temp,
344 				    cur_sector_offset, working_sector);
345 			}
346 			if (fseeko(fd, working_sector *
347 			    diskStructure->sectorSize + cur_sector_offset +
348 			    temp_record.length[0] - temp->su_tail_size,
349 			    SEEK_SET) == -1)
350 				err(1, "fseeko");
351 			if (temp->su_tail_size > 0)
352 				fwrite(temp->su_tail_data, 1,
353 				    temp->su_tail_size, fd);
354 			if (ferror(fd)) {
355 				warnx("%s: write error", __func__);
356 				goto out;
357 			}
358 			cur_sector_offset += temp_record.length[0];
359 
360 		}
361 
362 		/*
363 		 * Recurse on children.
364 		 */
365 		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
366 			if ((ret = cd9660_write_file(diskStructure, fd, temp))
367 			    == 0)
368 				goto out;
369 		}
370 	}
371 	rv = 1;
372 out:
373 	free(temp_file_name);
374 	free(buf);
375 	return rv;
376 }
377 
378 /*
379  * Wrapper function to write a buffer (one sector) to disk.
380  * Seeks and writes the buffer.
381  * NOTE: You dont NEED to use this function, but it might make your
382  * life easier if you have to write things that align to a sector
383  * (such as volume descriptors).
384  *
385  * @param int fd Valid file descriptor
386  * @param int sector Sector number to write to
387  * @param const unsigned char* Buffer to write. This should be the
388  *                             size of a sector, and if only a portion
389  *                             is written, the rest should be set to 0.
390  */
391 static int
392 cd9660_write_filedata(iso9660_disk *diskStructure, FILE *fd, off_t sector,
393     const unsigned char *buf, int numsecs)
394 {
395 	off_t curpos;
396 	size_t success;
397 
398 	curpos = ftello(fd);
399 
400 	if (fseeko(fd, sector * diskStructure->sectorSize, SEEK_SET) == -1)
401 		err(1, "fseeko");
402 
403 	success = fwrite(buf, diskStructure->sectorSize * numsecs, 1, fd);
404 
405 	if (fseeko(fd, curpos, SEEK_SET) == -1)
406 		err(1, "fseeko");
407 
408 	if (success == 1)
409 		success = diskStructure->sectorSize * numsecs;
410 	return success;
411 }
412 
413 #if 0
414 static int
415 cd9660_write_buffered(FILE *fd, off_t offset, int buff_len,
416 		      const unsigned char* buffer)
417 {
418 	static int working_sector = -1;
419 	static char buf[CD9660_SECTOR_SIZE];
420 
421 	return 0;
422 }
423 #endif
424 
425 int
426 cd9660_copy_file(iso9660_disk *diskStructure, FILE *fd, off_t start_sector,
427     const char *filename)
428 {
429 	FILE *rf;
430 	int bytes_read;
431 	off_t sector = start_sector;
432 	int buf_size = diskStructure->sectorSize;
433 	char *buf;
434 
435 	buf = emalloc(buf_size);
436 	if ((rf = fopen(filename, "rb")) == NULL) {
437 		warn("%s: cannot open %s", __func__, filename);
438 		free(buf);
439 		return 0;
440 	}
441 
442 	if (diskStructure->verbose_level > 1)
443 		printf("Writing file: %s\n",filename);
444 
445 	if (fseeko(fd, start_sector * diskStructure->sectorSize, SEEK_SET) == -1)
446 		err(1, "fseeko");
447 
448 	while (!feof(rf)) {
449 		bytes_read = fread(buf,1,buf_size,rf);
450 		if (ferror(rf)) {
451 			warn("%s: fread", __func__);
452 			free(buf);
453 			(void)fclose(rf);
454 			return 0;
455 		}
456 
457 		fwrite(buf,1,bytes_read,fd);
458 		if (ferror(fd)) {
459 			warn("%s: fwrite", __func__);
460 			free(buf);
461 			(void)fclose(rf);
462 			return 0;
463 		}
464 		sector++;
465 	}
466 
467 	fclose(rf);
468 	free(buf);
469 	return 1;
470 }
471 
472 static void
473 cd9660_write_rr(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode,
474     off_t offset, off_t sector)
475 {
476 	int in_ca = 0;
477 	struct ISO_SUSP_ATTRIBUTES *myattr;
478 
479 	offset += writenode->isoDirRecord->length[0];
480 	if (fseeko(fd, sector * diskStructure->sectorSize + offset, SEEK_SET) ==
481 	    -1)
482 		err(1, "fseeko");
483 	/* Offset now points at the end of the record */
484 	TAILQ_FOREACH(myattr, &writenode->head, rr_ll) {
485 		fwrite(&(myattr->attr), CD9660_SUSP_ENTRY_SIZE(myattr), 1, fd);
486 
487 		if (!in_ca) {
488 			offset += CD9660_SUSP_ENTRY_SIZE(myattr);
489 			if (myattr->last_in_suf) {
490 				/*
491 				 * Point the offset to the start of this
492 				 * record's CE area
493 				 */
494 				if (fseeko(fd, ((off_t)diskStructure->
495 				    susp_continuation_area_start_sector *
496 				    diskStructure->sectorSize)
497 				    + writenode->susp_entry_ce_start,
498 				    SEEK_SET) == -1)
499 					err(1, "fseeko");
500 				in_ca = 1;
501 			}
502 		}
503 	}
504 
505 	/*
506 	 * If we had to go to the continuation area, head back to
507 	 * where we should be.
508 	 */
509 	if (in_ca)
510 		if (fseeko(fd, sector * diskStructure->sectorSize + offset,
511 		    SEEK_SET) == -1)
512 			err(1, "fseeko");
513 }
514