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-NetBSD
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__FBSDID("$FreeBSD$");
42
43#include <util.h>
44
45static int cd9660_write_volume_descriptors(iso9660_disk *, FILE *);
46static int cd9660_write_path_table(iso9660_disk *, FILE *, off_t, int);
47static int cd9660_write_path_tables(iso9660_disk *, FILE *);
48static int cd9660_write_file(iso9660_disk *, FILE *, cd9660node *);
49static int cd9660_write_filedata(iso9660_disk *, FILE *, off_t,
50    const unsigned char *, int);
51#if 0
52static int cd9660_write_buffered(FILE *, off_t, int, const unsigned char *);
53#endif
54static 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 */
62int
63cd9660_write_image(iso9660_disk *diskStructure, const char* image)
64{
65	FILE *fd;
66	int status;
67	unsigned 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
135cleanup_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
144static int
145cd9660_write_volume_descriptors(iso9660_disk *diskStructure, FILE *fd)
146{
147	volume_descriptor *vd_temp = diskStructure->firstVolumeDescriptor;
148
149	while (vd_temp != NULL) {
150		cd9660_write_filedata(diskStructure, fd, vd_temp->sector,
151		    vd_temp->volumeDescriptorData, 1);
152		vd_temp = vd_temp->next;
153	}
154	return 1;
155}
156
157/*
158 * Write out an individual path table
159 * Used just to keep redundant code to a minimum
160 * @param FILE *fd Valid file pointer
161 * @param int Sector to start writing path table to
162 * @param int Endian mode : BIG_ENDIAN or LITTLE_ENDIAN
163 * @returns int 1 on success, 0 on failure
164 */
165static int
166cd9660_write_path_table(iso9660_disk *diskStructure, FILE *fd, off_t sector,
167    int mode)
168{
169	int path_table_sectors = CD9660_BLOCKS(diskStructure->sectorSize,
170	    diskStructure->pathTableLength);
171	unsigned char *buffer;
172	unsigned char *buffer_head;
173	int len, ret;
174	path_table_entry temp_entry;
175	cd9660node *ptcur;
176
177	buffer = ecalloc(path_table_sectors, diskStructure->sectorSize);
178	buffer_head = buffer;
179
180	ptcur = diskStructure->rootNode;
181
182	while (ptcur != NULL) {
183		memset(&temp_entry, 0, sizeof(path_table_entry));
184		temp_entry.length[0] = ptcur->isoDirRecord->name_len[0];
185		temp_entry.extended_attribute_length[0] =
186		    ptcur->isoDirRecord->ext_attr_length[0];
187		memcpy(temp_entry.name, ptcur->isoDirRecord->name,
188		    temp_entry.length[0] + 1);
189
190		/* round up */
191		len = temp_entry.length[0] + 8 + (temp_entry.length[0] & 0x01);
192
193                /* todo: function pointers instead */
194		if (mode == LITTLE_ENDIAN) {
195			cd9660_731(ptcur->fileDataSector,
196			    temp_entry.first_sector);
197			cd9660_721((ptcur->parent == NULL ?
198				1 : ptcur->parent->ptnumber),
199			    temp_entry.parent_number);
200		} else {
201			cd9660_732(ptcur->fileDataSector,
202			    temp_entry.first_sector);
203			cd9660_722((ptcur->parent == NULL ?
204				1 : ptcur->parent->ptnumber),
205			    temp_entry.parent_number);
206		}
207
208
209		memcpy(buffer, &temp_entry, len);
210		buffer += len;
211
212		ptcur = ptcur->ptnext;
213	}
214
215	ret = cd9660_write_filedata(diskStructure, fd, sector, buffer_head,
216	    path_table_sectors);
217	free(buffer_head);
218	return ret;
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 */
236static int
237cd9660_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 */
262static int
263cd9660_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	iso_directory_record_cd9660 temp_record;
271	cd9660node *temp;
272	int rv = 0;
273
274	/* Todo : clean up variables */
275
276	temp_file_name = ecalloc(CD9660MAXPATH + 1, 1);
277	buf = emalloc(diskStructure->sectorSize);
278	if ((writenode->level != 0) &&
279	    !(writenode->node->type & S_IFDIR)) {
280		fsinode *inode = writenode->node->inode;
281		/* Only attempt to write unwritten files that have length. */
282		if ((inode->flags & FI_WRITTEN) != 0) {
283			INODE_WARNX(("%s: skipping written inode %d", __func__,
284			    (int)inode->st.st_ino));
285		} else if (writenode->fileDataLength > 0) {
286			INODE_WARNX(("%s: writing inode %d blocks at %" PRIu32,
287			    __func__, (int)inode->st.st_ino, inode->ino));
288			inode->flags |= FI_WRITTEN;
289			if (writenode->node->contents == NULL)
290				cd9660_compute_full_filename(writenode,
291				    temp_file_name);
292			ret = cd9660_copy_file(diskStructure, fd,
293			    writenode->fileDataSector,
294			    (writenode->node->contents != NULL) ?
295			    writenode->node->contents : temp_file_name);
296			if (ret == 0)
297				goto out;
298		}
299	} else {
300		/*
301		 * Here is a new revelation that ECMA didn't explain
302		 * (at least not well).
303		 * ALL . and .. records store the name "\0" and "\1"
304		 * respectively. So, for each directory, we have to
305		 * make a new node.
306		 *
307		 * This is where it gets kinda messy, since we have to
308		 * be careful of sector boundaries
309		 */
310		cur_sector_offset = 0;
311		working_sector = writenode->fileDataSector;
312		if (fseeko(fd, working_sector * diskStructure->sectorSize,
313		    SEEK_SET) == -1)
314			err(1, "fseeko");
315
316		/*
317		 * Now loop over children, writing out their directory
318		 * records - beware of sector boundaries
319	 	 */
320		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
321			/*
322			 * Copy the temporary record and adjust its size
323			 * if necessary
324			 */
325			memcpy(&temp_record, temp->isoDirRecord,
326			    sizeof(iso_directory_record_cd9660));
327
328			temp_record.length[0] =
329			    cd9660_compute_record_size(diskStructure, temp);
330
331			if (temp_record.length[0] + cur_sector_offset >=
332			    diskStructure->sectorSize) {
333				cur_sector_offset = 0;
334				working_sector++;
335
336				/* Seek to the next sector. */
337				if (fseeko(fd, working_sector *
338				    diskStructure->sectorSize, SEEK_SET) == -1)
339					err(1, "fseeko");
340			}
341			/* Write out the basic ISO directory record */
342			(void)fwrite(&temp_record, 1,
343			    temp->isoDirRecord->length[0], fd);
344			if (diskStructure->rock_ridge_enabled) {
345				cd9660_write_rr(diskStructure, fd, temp,
346				    cur_sector_offset, working_sector);
347			}
348			if (fseeko(fd, working_sector *
349			    diskStructure->sectorSize + cur_sector_offset +
350			    temp_record.length[0] - temp->su_tail_size,
351			    SEEK_SET) == -1)
352				err(1, "fseeko");
353			if (temp->su_tail_size > 0)
354				fwrite(temp->su_tail_data, 1,
355				    temp->su_tail_size, fd);
356			if (ferror(fd)) {
357				warnx("%s: write error", __func__);
358				goto out;
359			}
360			cur_sector_offset += temp_record.length[0];
361
362		}
363
364		/*
365		 * Recurse on children.
366		 */
367		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
368			if ((ret = cd9660_write_file(diskStructure, fd, temp)) == 0)
369				goto out;
370		}
371	}
372	rv = 1;
373out:
374	free(temp_file_name);
375	free(buf);
376	return rv;
377}
378
379/*
380 * Wrapper function to write a buffer (one sector) to disk.
381 * Seeks and writes the buffer.
382 * NOTE: You dont NEED to use this function, but it might make your
383 * life easier if you have to write things that align to a sector
384 * (such as volume descriptors).
385 *
386 * @param int fd Valid file descriptor
387 * @param int sector Sector number to write to
388 * @param const unsigned char* Buffer to write. This should be the
389 *                             size of a sector, and if only a portion
390 *                             is written, the rest should be set to 0.
391 */
392static int
393cd9660_write_filedata(iso9660_disk *diskStructure, FILE *fd, off_t sector,
394    const unsigned char *buf, int numsecs)
395{
396	off_t curpos;
397	size_t success;
398
399	curpos = ftello(fd);
400
401	if (fseeko(fd, sector * diskStructure->sectorSize, SEEK_SET) == -1)
402		err(1, "fseeko");
403
404	success = fwrite(buf, diskStructure->sectorSize * numsecs, 1, fd);
405
406	if (fseeko(fd, curpos, SEEK_SET) == -1)
407		err(1, "fseeko");
408
409	if (success == 1)
410		success = diskStructure->sectorSize * numsecs;
411	return success;
412}
413
414#if 0
415static int
416cd9660_write_buffered(FILE *fd, off_t offset, int buff_len,
417		      const unsigned char* buffer)
418{
419	static int working_sector = -1;
420	static char buf[CD9660_SECTOR_SIZE];
421
422	return 0;
423}
424#endif
425
426int
427cd9660_copy_file(iso9660_disk *diskStructure, FILE *fd, off_t start_sector,
428    const char *filename)
429{
430	FILE *rf;
431	int bytes_read;
432	off_t sector = start_sector;
433	int buf_size = diskStructure->sectorSize;
434	char *buf;
435
436	buf = emalloc(buf_size);
437	if ((rf = fopen(filename, "rb")) == NULL) {
438		warn("%s: cannot open %s", __func__, filename);
439		free(buf);
440		return 0;
441	}
442
443	if (diskStructure->verbose_level > 1)
444		printf("Writing file: %s\n",filename);
445
446	if (fseeko(fd, start_sector * diskStructure->sectorSize, SEEK_SET) == -1)
447		err(1, "fseeko");
448
449	while (!feof(rf)) {
450		bytes_read = fread(buf,1,buf_size,rf);
451		if (ferror(rf)) {
452			warn("%s: fread", __func__);
453			free(buf);
454			(void)fclose(rf);
455			return 0;
456		}
457
458		fwrite(buf,1,bytes_read,fd);
459		if (ferror(fd)) {
460			warn("%s: fwrite", __func__);
461			free(buf);
462			(void)fclose(rf);
463			return 0;
464		}
465		sector++;
466	}
467
468	fclose(rf);
469	free(buf);
470	return 1;
471}
472
473static void
474cd9660_write_rr(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode,
475    off_t offset, off_t sector)
476{
477	int in_ca = 0;
478	struct ISO_SUSP_ATTRIBUTES *myattr;
479
480	offset += writenode->isoDirRecord->length[0];
481	if (fseeko(fd, sector * diskStructure->sectorSize + offset, SEEK_SET) ==
482	    -1)
483		err(1, "fseeko");
484	/* Offset now points at the end of the record */
485	TAILQ_FOREACH(myattr, &writenode->head, rr_ll) {
486		fwrite(&(myattr->attr), CD9660_SUSP_ENTRY_SIZE(myattr), 1, fd);
487
488		if (!in_ca) {
489			offset += CD9660_SUSP_ENTRY_SIZE(myattr);
490			if (myattr->last_in_suf) {
491				/*
492				 * Point the offset to the start of this
493				 * record's CE area
494				 */
495				if (fseeko(fd, ((off_t)diskStructure->
496				    susp_continuation_area_start_sector *
497				    diskStructure->sectorSize)
498				    + writenode->susp_entry_ce_start,
499				    SEEK_SET) == -1)
500					err(1, "fseeko");
501				in_ca = 1;
502			}
503		}
504	}
505
506	/*
507	 * If we had to go to the continuation area, head back to
508	 * where we should be.
509	 */
510	if (in_ca)
511		if (fseeko(fd, sector * diskStructure->sectorSize + offset,
512		    SEEK_SET) == -1)
513			err(1, "fseeko");
514}
515