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