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: stable/11/usr.sbin/makefs/cd9660/cd9660_write.c 332981 2018-04-25 01:48:15Z benno $");
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	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	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 */
167static int
168cd9660_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, ret;
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	ret = cd9660_write_filedata(diskStructure, fd, sector, buffer_head,
218	    path_table_sectors);
219	free(buffer_head);
220	return ret;
221}
222
223
224/*
225 * Write out the path tables to disk
226 * Each file descriptor should be pointed to by the PVD, so we know which
227 * sector to copy them to. One thing to watch out for: the only path tables
228 * stored are in the endian mode that the application is compiled for. So,
229 * the first thing to do is write out that path table, then to write the one
230 * in the other endian mode requires to convert the endianness of each entry
231 * in the table. The best way to do this would be to create a temporary
232 * path_table_entry structure, then for each path table entry, copy it to
233 * the temporary entry, translate, then copy that to disk.
234 *
235 * @param FILE* Valid file descriptor
236 * @returns int 0 on failure, 1 on success
237 */
238static int
239cd9660_write_path_tables(iso9660_disk *diskStructure, FILE *fd)
240{
241	if (cd9660_write_path_table(diskStructure, fd,
242	    diskStructure->primaryLittleEndianTableSector, LITTLE_ENDIAN) == 0)
243		return 0;
244
245	if (cd9660_write_path_table(diskStructure, fd,
246	    diskStructure->primaryBigEndianTableSector, BIG_ENDIAN) == 0)
247		return 0;
248
249	/* @TODO: handle remaining two path tables */
250	return 1;
251}
252
253/*
254 * Write a file to disk
255 * Writes a file, its directory record, and its data to disk
256 * This file is designed to be called RECURSIVELY, so initially call it
257 * with the root node. All of the records should store what sector the
258 * file goes in, so no computation should be  necessary.
259 *
260 * @param int fd Valid file descriptor
261 * @param struct cd9660node* writenode Pointer to the file to be written
262 * @returns int 0 on failure, 1 on success
263 */
264static int
265cd9660_write_file(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode)
266{
267	char *buf;
268	char *temp_file_name;
269	int ret;
270	off_t working_sector;
271	int cur_sector_offset;
272	int written;
273	iso_directory_record_cd9660 temp_record;
274	cd9660node *temp;
275	int rv = 0;
276
277	/* Todo : clean up variables */
278
279	temp_file_name = ecalloc(CD9660MAXPATH + 1, 1);
280	buf = emalloc(diskStructure->sectorSize);
281	if ((writenode->level != 0) &&
282	    !(writenode->node->type & S_IFDIR)) {
283		fsinode *inode = writenode->node->inode;
284		/* Only attempt to write unwritten files that have length. */
285		if ((inode->flags & FI_WRITTEN) != 0) {
286			INODE_WARNX(("%s: skipping written inode %d", __func__,
287			    (int)inode->st.st_ino));
288		} else if (writenode->fileDataLength > 0) {
289			INODE_WARNX(("%s: writing inode %d blocks at %" PRIu32,
290			    __func__, (int)inode->st.st_ino, inode->ino));
291			inode->flags |= FI_WRITTEN;
292			if (writenode->node->contents == NULL)
293				cd9660_compute_full_filename(writenode,
294				    temp_file_name);
295			ret = cd9660_copy_file(diskStructure, fd,
296			    writenode->fileDataSector,
297			    (writenode->node->contents != NULL) ?
298			    writenode->node->contents : temp_file_name);
299			if (ret == 0)
300				goto out;
301		}
302	} else {
303		/*
304		 * Here is a new revelation that ECMA didn't explain
305		 * (at least not well).
306		 * ALL . and .. records store the name "\0" and "\1"
307		 * respectively. So, for each directory, we have to
308		 * make a new node.
309		 *
310		 * This is where it gets kinda messy, since we have to
311		 * be careful of sector boundaries
312		 */
313		cur_sector_offset = 0;
314		working_sector = writenode->fileDataSector;
315		if (fseeko(fd, working_sector * diskStructure->sectorSize,
316		    SEEK_SET) == -1)
317			err(1, "fseeko");
318
319		/*
320		 * Now loop over children, writing out their directory
321		 * records - beware of sector boundaries
322	 	 */
323		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
324			/*
325			 * Copy the temporary record and adjust its size
326			 * if necessary
327			 */
328			memcpy(&temp_record, temp->isoDirRecord,
329			    sizeof(iso_directory_record_cd9660));
330
331			temp_record.length[0] =
332			    cd9660_compute_record_size(diskStructure, temp);
333
334			if (temp_record.length[0] + cur_sector_offset >=
335			    diskStructure->sectorSize) {
336				cur_sector_offset = 0;
337				working_sector++;
338
339				/* Seek to the next sector. */
340				if (fseeko(fd, working_sector *
341				    diskStructure->sectorSize, SEEK_SET) == -1)
342					err(1, "fseeko");
343			}
344			/* Write out the basic ISO directory record */
345			written = fwrite(&temp_record, 1,
346			    temp->isoDirRecord->length[0], fd);
347			if (diskStructure->rock_ridge_enabled) {
348				cd9660_write_rr(diskStructure, fd, temp,
349				    cur_sector_offset, working_sector);
350			}
351			if (fseeko(fd, working_sector *
352			    diskStructure->sectorSize + cur_sector_offset +
353			    temp_record.length[0] - temp->su_tail_size,
354			    SEEK_SET) == -1)
355				err(1, "fseeko");
356			if (temp->su_tail_size > 0)
357				fwrite(temp->su_tail_data, 1,
358				    temp->su_tail_size, fd);
359			if (ferror(fd)) {
360				warnx("%s: write error", __func__);
361				goto out;
362			}
363			cur_sector_offset += temp_record.length[0];
364
365		}
366
367		/*
368		 * Recurse on children.
369		 */
370		TAILQ_FOREACH(temp, &writenode->cn_children, cn_next_child) {
371			if ((ret = cd9660_write_file(diskStructure, fd, temp)) == 0)
372				goto out;
373		}
374	}
375	rv = 1;
376out:
377	free(temp_file_name);
378	free(buf);
379	return rv;
380}
381
382/*
383 * Wrapper function to write a buffer (one sector) to disk.
384 * Seeks and writes the buffer.
385 * NOTE: You dont NEED to use this function, but it might make your
386 * life easier if you have to write things that align to a sector
387 * (such as volume descriptors).
388 *
389 * @param int fd Valid file descriptor
390 * @param int sector Sector number to write to
391 * @param const unsigned char* Buffer to write. This should be the
392 *                             size of a sector, and if only a portion
393 *                             is written, the rest should be set to 0.
394 */
395static int
396cd9660_write_filedata(iso9660_disk *diskStructure, FILE *fd, off_t sector,
397    const unsigned char *buf, int numsecs)
398{
399	off_t curpos;
400	size_t success;
401
402	curpos = ftello(fd);
403
404	if (fseeko(fd, sector * diskStructure->sectorSize, SEEK_SET) == -1)
405		err(1, "fseeko");
406
407	success = fwrite(buf, diskStructure->sectorSize * numsecs, 1, fd);
408
409	if (fseeko(fd, curpos, SEEK_SET) == -1)
410		err(1, "fseeko");
411
412	if (success == 1)
413		success = diskStructure->sectorSize * numsecs;
414	return success;
415}
416
417#if 0
418static int
419cd9660_write_buffered(FILE *fd, off_t offset, int buff_len,
420		      const unsigned char* buffer)
421{
422	static int working_sector = -1;
423	static char buf[CD9660_SECTOR_SIZE];
424
425	return 0;
426}
427#endif
428
429int
430cd9660_copy_file(iso9660_disk *diskStructure, FILE *fd, off_t start_sector,
431    const char *filename)
432{
433	FILE *rf;
434	int bytes_read;
435	off_t sector = start_sector;
436	int buf_size = diskStructure->sectorSize;
437	char *buf;
438
439	buf = emalloc(buf_size);
440	if ((rf = fopen(filename, "rb")) == NULL) {
441		warn("%s: cannot open %s", __func__, filename);
442		free(buf);
443		return 0;
444	}
445
446	if (diskStructure->verbose_level > 1)
447		printf("Writing file: %s\n",filename);
448
449	if (fseeko(fd, start_sector * diskStructure->sectorSize, SEEK_SET) == -1)
450		err(1, "fseeko");
451
452	while (!feof(rf)) {
453		bytes_read = fread(buf,1,buf_size,rf);
454		if (ferror(rf)) {
455			warn("%s: fread", __func__);
456			free(buf);
457			(void)fclose(rf);
458			return 0;
459		}
460
461		fwrite(buf,1,bytes_read,fd);
462		if (ferror(fd)) {
463			warn("%s: fwrite", __func__);
464			free(buf);
465			(void)fclose(rf);
466			return 0;
467		}
468		sector++;
469	}
470
471	fclose(rf);
472	free(buf);
473	return 1;
474}
475
476static void
477cd9660_write_rr(iso9660_disk *diskStructure, FILE *fd, cd9660node *writenode,
478    off_t offset, off_t sector)
479{
480	int in_ca = 0;
481	struct ISO_SUSP_ATTRIBUTES *myattr;
482
483	offset += writenode->isoDirRecord->length[0];
484	if (fseeko(fd, sector * diskStructure->sectorSize + offset, SEEK_SET) ==
485	    -1)
486		err(1, "fseeko");
487	/* Offset now points at the end of the record */
488	TAILQ_FOREACH(myattr, &writenode->head, rr_ll) {
489		fwrite(&(myattr->attr), CD9660_SUSP_ENTRY_SIZE(myattr), 1, fd);
490
491		if (!in_ca) {
492			offset += CD9660_SUSP_ENTRY_SIZE(myattr);
493			if (myattr->last_in_suf) {
494				/*
495				 * Point the offset to the start of this
496				 * record's CE area
497				 */
498				if (fseeko(fd, ((off_t)diskStructure->
499				    susp_continuation_area_start_sector *
500				    diskStructure->sectorSize)
501				    + writenode->susp_entry_ce_start,
502				    SEEK_SET) == -1)
503					err(1, "fseeko");
504				in_ca = 1;
505			}
506		}
507	}
508
509	/*
510	 * If we had to go to the continuation area, head back to
511	 * where we should be.
512	 */
513	if (in_ca)
514		if (fseeko(fd, sector * diskStructure->sectorSize + offset,
515		    SEEK_SET) == -1)
516			err(1, "fseeko");
517}
518