1/*	$NetBSD: cd9660_write.c,v 1.14 2011/01/04 09:48:21 wiz Exp $	*/
2
3/*-
4 * SPDX-License-Identifier: BSD-2-Clause
5 *
6 * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
7 * Perez-Rathke and Ram Vedam.  All rights reserved.
8 *
9 * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
10 * Alan Perez-Rathke and Ram Vedam.
11 *
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
14 * conditions are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above
18 *    copyright notice, this list of conditions and the following
19 *    disclaimer in the documentation and/or other materials provided
20 *    with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN
23 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED.  IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN
27 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30 * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
34 * OF SUCH DAMAGE.
35 */
36
37#include "cd9660.h"
38#include "iso9660_rrip.h"
39
40#include <sys/cdefs.h>
41#include <util.h>
42
43static int cd9660_write_volume_descriptors(iso9660_disk *, FILE *);
44static int cd9660_write_path_table(iso9660_disk *, FILE *, off_t, int);
45static int cd9660_write_path_tables(iso9660_disk *, FILE *);
46static int cd9660_write_file(iso9660_disk *, FILE *, cd9660node *);
47static int cd9660_write_filedata(iso9660_disk *, FILE *, off_t,
48    const unsigned char *, int);
49#if 0
50static int cd9660_write_buffered(FILE *, off_t, int, const unsigned char *);
51#endif
52static 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 */
60int
61cd9660_write_image(iso9660_disk *diskStructure, const char* image)
62{
63	FILE *fd;
64	int status;
65	unsigned 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 concerned 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
133cleanup_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
142static int
143cd9660_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 */
163static int
164cd9660_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 */
234static int
235cd9660_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 */
260static int
261cd9660_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(PATH_MAX, 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;
371out:
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 */
390static int
391cd9660_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
413static int
414cd9660_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
424int
425cd9660_copy_file(iso9660_disk *diskStructure, FILE *fd, off_t start_sector,
426    const char *filename)
427{
428	FILE *rf;
429	int bytes_read;
430	int buf_size = diskStructure->sectorSize;
431	char *buf;
432
433	buf = emalloc(buf_size);
434	if ((rf = fopen(filename, "rb")) == NULL) {
435		warn("%s: cannot open %s", __func__, filename);
436		free(buf);
437		return 0;
438	}
439
440	if (diskStructure->verbose_level > 1)
441		printf("Writing file: %s\n",filename);
442
443	if (fseeko(fd, start_sector * diskStructure->sectorSize, SEEK_SET) == -1)
444		err(1, "fseeko");
445
446	while (!feof(rf)) {
447		bytes_read = fread(buf,1,buf_size,rf);
448		if (ferror(rf)) {
449			warn("%s: fread", __func__);
450			free(buf);
451			(void)fclose(rf);
452			return 0;
453		}
454
455		fwrite(buf,1,bytes_read,fd);
456		if (ferror(fd)) {
457			warn("%s: fwrite", __func__);
458			free(buf);
459			(void)fclose(rf);
460			return 0;
461		}
462	}
463
464	fclose(rf);
465	free(buf);
466	return 1;
467}
468
469static void
470cd9660_write_rr(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode,
471    off_t offset, off_t sector)
472{
473	int in_ca = 0;
474	struct ISO_SUSP_ATTRIBUTES *myattr;
475
476	offset += writenode->isoDirRecord->length[0];
477	if (fseeko(fd, sector * diskStructure->sectorSize + offset, SEEK_SET) ==
478	    -1)
479		err(1, "fseeko");
480	/* Offset now points at the end of the record */
481	TAILQ_FOREACH(myattr, &writenode->head, rr_ll) {
482		fwrite(&(myattr->attr), CD9660_SUSP_ENTRY_SIZE(myattr), 1, fd);
483
484		if (!in_ca) {
485			offset += CD9660_SUSP_ENTRY_SIZE(myattr);
486			if (myattr->last_in_suf) {
487				/*
488				 * Point the offset to the start of this
489				 * record's CE area
490				 */
491				if (fseeko(fd, ((off_t)diskStructure->
492				    susp_continuation_area_start_sector *
493				    diskStructure->sectorSize)
494				    + writenode->susp_entry_ce_start,
495				    SEEK_SET) == -1)
496					err(1, "fseeko");
497				in_ca = 1;
498			}
499		}
500	}
501
502	/*
503	 * If we had to go to the continuation area, head back to
504	 * where we should be.
505	 */
506	if (in_ca)
507		if (fseeko(fd, sector * diskStructure->sectorSize + offset,
508		    SEEK_SET) == -1)
509			err(1, "fseeko");
510}
511