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