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