1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2001-2009  Josh Coalson
3  * Copyright (C) 2011-2013  Xiph.Org Foundation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * - Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the Xiph.org Foundation nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #ifdef HAVE_CONFIG_H
34 #  include <config.h>
35 #endif
36 
37 #include <errno.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdarg.h>
42 
43 #include <sys/stat.h> /* for stat(), maybe chmod() */
44 
45 #include "private/metadata.h"
46 
47 #include "FLAC/assert.h"
48 #include "FLAC/stream_decoder.h"
49 #include "share/alloc.h"
50 #include "share/compat.h"
51 #include "share/macros.h"
52 #include "share/safe_str.h"
53 #include "private/macros.h"
54 #include "private/memory.h"
55 
56 #include <retro_miscellaneous.h>
57 
58 /* Alias the first (in share/alloc.h) to the second (in src/libFLAC/memory.c). */
59 #define safe_malloc_mul_2op_ safe_malloc_mul_2op_p
60 
61 /****************************************************************************
62  *
63  * Local function declarations
64  *
65  ***************************************************************************/
66 
67 static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
68 static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
69 static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes);
70 static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes);
71 static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes);
72 static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes);
73 
74 static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator);
75 static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block);
76 static FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length);
77 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block);
78 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block);
79 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length);
80 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length);
81 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length);
82 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry);
83 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block);
84 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track);
85 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block);
86 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block);
87 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length);
88 
89 static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
90 static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
91 static FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
92 static FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
93 static FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block);
94 static FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length);
95 static FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length);
96 static FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block);
97 static FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block);
98 static FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block);
99 static FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block);
100 static FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length);
101 
102 static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block);
103 static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last);
104 static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append);
105 
106 static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator);
107 static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator);
108 
109 static unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb);
110 static unsigned seek_to_first_metadata_block_(FILE *f);
111 
112 static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append);
113 static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, FLAC__off_t fixup_is_last_flag_offset, FLAC__bool backup);
114 
115 static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
116 static FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
117 static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status);
118 static FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status);
119 
120 static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
121 static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
122 static void cleanup_tempfile_(FILE **tempfile, char **tempfilename);
123 
124 static FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats);
125 static void set_file_stats_(const char *filename, struct flac_stat_s *stats);
126 
127 static int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence);
128 static FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle);
129 
130 static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status);
131 
132 
133 #ifdef FLAC__VALGRIND_TESTING
local__fwrite(const void * ptr,size_t size,size_t nmemb,FILE * stream)134 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
135 {
136 	size_t ret = fwrite(ptr, size, nmemb, stream);
137 	if(!ferror(stream))
138 		fflush(stream);
139 	return ret;
140 }
141 #else
142 #define local__fwrite fwrite
143 #endif
144 
145 /****************************************************************************
146  *
147  * Level 0 implementation
148  *
149  ***************************************************************************/
150 
151 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
152 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
153 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
154 
155 typedef struct {
156 	FLAC__bool got_error;
157 	FLAC__StreamMetadata *object;
158 } level0_client_data;
159 
get_one_metadata_block_(const char * filename,FLAC__MetadataType type)160 static FLAC__StreamMetadata *get_one_metadata_block_(const char *filename, FLAC__MetadataType type)
161 {
162 	level0_client_data cd;
163 	FLAC__StreamDecoder *decoder;
164 
165 	FLAC__ASSERT(0 != filename);
166 
167 	cd.got_error = false;
168 	cd.object = 0;
169 
170 	decoder = FLAC__stream_decoder_new();
171 
172 	if(0 == decoder)
173 		return 0;
174 
175 	FLAC__stream_decoder_set_md5_checking(decoder, false);
176 	FLAC__stream_decoder_set_metadata_ignore_all(decoder);
177 	FLAC__stream_decoder_set_metadata_respond(decoder, type);
178 
179 	if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &cd) != FLAC__STREAM_DECODER_INIT_STATUS_OK || cd.got_error) {
180 		(void)FLAC__stream_decoder_finish(decoder);
181 		FLAC__stream_decoder_delete(decoder);
182 		return 0;
183 	}
184 
185 	if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || cd.got_error) {
186 		(void)FLAC__stream_decoder_finish(decoder);
187 		FLAC__stream_decoder_delete(decoder);
188 		if(0 != cd.object)
189 			FLAC__metadata_object_delete(cd.object);
190 		return 0;
191 	}
192 
193 	(void)FLAC__stream_decoder_finish(decoder);
194 	FLAC__stream_decoder_delete(decoder);
195 
196 	return cd.object;
197 }
198 
FLAC__metadata_get_streaminfo(const char * filename,FLAC__StreamMetadata * streaminfo)199 FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo)
200 {
201 	FLAC__StreamMetadata *object;
202 
203 	FLAC__ASSERT(0 != filename);
204 	FLAC__ASSERT(0 != streaminfo);
205 
206 	object = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_STREAMINFO);
207 
208 	if (object) {
209 		/* can just copy the contents since STREAMINFO has no internal structure */
210 		*streaminfo = *object;
211 		FLAC__metadata_object_delete(object);
212 		return true;
213 	}
214 	else {
215 		return false;
216 	}
217 }
218 
FLAC__metadata_get_tags(const char * filename,FLAC__StreamMetadata ** tags)219 FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags)
220 {
221 	FLAC__ASSERT(0 != filename);
222 	FLAC__ASSERT(0 != tags);
223 
224 	*tags = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_VORBIS_COMMENT);
225 
226 	return 0 != *tags;
227 }
228 
FLAC__metadata_get_cuesheet(const char * filename,FLAC__StreamMetadata ** cuesheet)229 FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet)
230 {
231 	FLAC__ASSERT(0 != filename);
232 	FLAC__ASSERT(0 != cuesheet);
233 
234 	*cuesheet = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_CUESHEET);
235 
236 	return 0 != *cuesheet;
237 }
238 
write_callback_(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)239 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
240 {
241 	(void)decoder, (void)frame, (void)buffer, (void)client_data;
242 
243 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
244 }
245 
metadata_callback_(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)246 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
247 {
248 	level0_client_data *cd = (level0_client_data *)client_data;
249 	(void)decoder;
250 
251 	/*
252 	 * we assume we only get here when the one metadata block we were
253 	 * looking for was passed to us
254 	 */
255 	if(!cd->got_error && 0 == cd->object) {
256 		if(0 == (cd->object = FLAC__metadata_object_clone(metadata)))
257 			cd->got_error = true;
258 	}
259 }
260 
error_callback_(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)261 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
262 {
263 	level0_client_data *cd = (level0_client_data *)client_data;
264 	(void)decoder;
265 
266 	if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
267 		cd->got_error = true;
268 }
269 
FLAC__metadata_get_picture(const char * filename,FLAC__StreamMetadata ** picture,FLAC__StreamMetadata_Picture_Type type,const char * mime_type,const FLAC__byte * description,unsigned max_width,unsigned max_height,unsigned max_depth,unsigned max_colors)270 FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors)
271 {
272 	FLAC__Metadata_SimpleIterator *it;
273 	FLAC__uint64 max_area_seen = 0;
274 	FLAC__uint64 max_depth_seen = 0;
275 
276 	FLAC__ASSERT(0 != filename);
277 	FLAC__ASSERT(0 != picture);
278 
279 	*picture = 0;
280 
281 	it = FLAC__metadata_simple_iterator_new();
282 	if(0 == it)
283 		return false;
284 	if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) {
285 		FLAC__metadata_simple_iterator_delete(it);
286 		return false;
287 	}
288 	do {
289 		if(FLAC__metadata_simple_iterator_get_block_type(it) == FLAC__METADATA_TYPE_PICTURE) {
290 			FLAC__StreamMetadata *obj = FLAC__metadata_simple_iterator_get_block(it);
291 			FLAC__uint64 area = (FLAC__uint64)obj->data.picture.width * (FLAC__uint64)obj->data.picture.height;
292 			/* check constraints */
293 			if(
294 				(type == (FLAC__StreamMetadata_Picture_Type)(-1) || type == obj->data.picture.type) &&
295 				(mime_type == 0 || !strcmp(mime_type, obj->data.picture.mime_type)) &&
296 				(description == 0 || !strcmp((const char *)description, (const char *)obj->data.picture.description)) &&
297 				obj->data.picture.width <= max_width &&
298 				obj->data.picture.height <= max_height &&
299 				obj->data.picture.depth <= max_depth &&
300 				obj->data.picture.colors <= max_colors &&
301 				(area > max_area_seen || (area == max_area_seen && obj->data.picture.depth > max_depth_seen))
302 			) {
303 				if(*picture)
304 					FLAC__metadata_object_delete(*picture);
305 				*picture = obj;
306 				max_area_seen = area;
307 				max_depth_seen = obj->data.picture.depth;
308 			}
309 			else {
310 				FLAC__metadata_object_delete(obj);
311 			}
312 		}
313 	} while(FLAC__metadata_simple_iterator_next(it));
314 
315 	FLAC__metadata_simple_iterator_delete(it);
316 
317 	return (0 != *picture);
318 }
319 
320 
321 /****************************************************************************
322  *
323  * Level 1 implementation
324  *
325  ***************************************************************************/
326 
327 #define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4)
328 /* 1 for initial offset, +4 for our own personal use */
329 
330 struct FLAC__Metadata_SimpleIterator {
331 	FILE *file;
332 	char *filename, *tempfile_path_prefix;
333 	struct flac_stat_s stats;
334 	FLAC__bool has_stats;
335 	FLAC__bool is_writable;
336 	FLAC__Metadata_SimpleIteratorStatus status;
337 	FLAC__off_t offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH];
338 	FLAC__off_t first_offset; /* this is the offset to the STREAMINFO block */
339 	unsigned depth;
340 	/* this is the metadata block header of the current block we are pointing to: */
341 	FLAC__bool is_last;
342 	FLAC__MetadataType type;
343 	unsigned length;
344 };
345 
346 FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = {
347 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK",
348 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT",
349 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE",
350 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE",
351 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE",
352 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA",
353 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR",
354 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR",
355 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR",
356 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR",
357 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR",
358 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR",
359 	"FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR"
360 };
361 
362 
FLAC__metadata_simple_iterator_new(void)363 FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void)
364 {
365 	FLAC__Metadata_SimpleIterator *iterator = calloc(1, sizeof(FLAC__Metadata_SimpleIterator));
366 
367 	if(0 != iterator) {
368 		iterator->file = 0;
369 		iterator->filename = 0;
370 		iterator->tempfile_path_prefix = 0;
371 		iterator->has_stats = false;
372 		iterator->is_writable = false;
373 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
374 		iterator->first_offset = iterator->offset[0] = -1;
375 		iterator->depth = 0;
376 	}
377 
378 	return iterator;
379 }
380 
simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator * iterator)381 static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator)
382 {
383 	FLAC__ASSERT(0 != iterator);
384 
385 	if(0 != iterator->file) {
386 		fclose(iterator->file);
387 		iterator->file = 0;
388 		if(iterator->has_stats)
389 			set_file_stats_(iterator->filename, &iterator->stats);
390 	}
391 	if(0 != iterator->filename) {
392 		free(iterator->filename);
393 		iterator->filename = 0;
394 	}
395 	if(0 != iterator->tempfile_path_prefix) {
396 		free(iterator->tempfile_path_prefix);
397 		iterator->tempfile_path_prefix = 0;
398 	}
399 }
400 
FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator * iterator)401 FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator)
402 {
403 	FLAC__ASSERT(0 != iterator);
404 
405 	simple_iterator_free_guts_(iterator);
406 	free(iterator);
407 }
408 
FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator * iterator)409 FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator)
410 {
411 	FLAC__Metadata_SimpleIteratorStatus status;
412 
413 	FLAC__ASSERT(0 != iterator);
414 
415 	status = iterator->status;
416 	iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
417 	return status;
418 }
419 
simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator * iterator,FLAC__bool read_only)420 static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only)
421 {
422 	unsigned ret;
423 
424 	FLAC__ASSERT(0 != iterator);
425 
426 	if(read_only || 0 == (iterator->file = flac_fopen(iterator->filename, "r+b"))) {
427 		iterator->is_writable = false;
428 		if(read_only || errno == EACCES) {
429 			if(0 == (iterator->file = flac_fopen(iterator->filename, "rb"))) {
430 				iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
431 				return false;
432 			}
433 		}
434 		else {
435 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
436 			return false;
437 		}
438 	}
439 	else {
440 		iterator->is_writable = true;
441 	}
442 
443 	ret = seek_to_first_metadata_block_(iterator->file);
444 	switch(ret) {
445 		case 0:
446 			iterator->depth = 0;
447 			iterator->first_offset = iterator->offset[iterator->depth] = ftello(iterator->file);
448 			return read_metadata_block_header_(iterator);
449 		case 1:
450 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
451 			return false;
452 		case 2:
453 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
454 			return false;
455 		case 3:
456 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE;
457 			return false;
458 		default:
459 			FLAC__ASSERT(0);
460 			return false;
461 	}
462 }
463 
FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator * iterator,const char * filename,FLAC__bool read_only,FLAC__bool preserve_file_stats)464 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats)
465 {
466 	const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'flac_rename(...)' for what it will take to finish implementing this */
467 
468 	FLAC__ASSERT(0 != iterator);
469 	FLAC__ASSERT(0 != filename);
470 
471 	simple_iterator_free_guts_(iterator);
472 
473 	if(!read_only && preserve_file_stats)
474 		iterator->has_stats = get_file_stats_(filename, &iterator->stats);
475 
476 	if(0 == (iterator->filename = strdup(filename))) {
477 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
478 		return false;
479 	}
480 	if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) {
481 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
482 		return false;
483 	}
484 
485 	return simple_iterator_prime_input_(iterator, read_only);
486 }
487 
FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator * iterator)488 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator)
489 {
490 	FLAC__ASSERT(0 != iterator);
491 	FLAC__ASSERT(0 != iterator->file);
492 
493 	return iterator->is_writable;
494 }
495 
FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator * iterator)496 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator)
497 {
498 	FLAC__ASSERT(0 != iterator);
499 	FLAC__ASSERT(0 != iterator->file);
500 
501 	if(iterator->is_last)
502 		return false;
503 
504 	if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
505 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
506 		return false;
507 	}
508 
509 	iterator->offset[iterator->depth] = ftello(iterator->file);
510 
511 	return read_metadata_block_header_(iterator);
512 }
513 
FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator * iterator)514 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator)
515 {
516 	FLAC__off_t this_offset;
517 
518 	FLAC__ASSERT(0 != iterator);
519 	FLAC__ASSERT(0 != iterator->file);
520 
521 	if(iterator->offset[iterator->depth] == iterator->first_offset)
522 		return false;
523 
524 	if(0 != fseeko(iterator->file, iterator->first_offset, SEEK_SET)) {
525 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
526 		return false;
527 	}
528 	this_offset = iterator->first_offset;
529 	if(!read_metadata_block_header_(iterator))
530 		return false;
531 
532 	/* we ignore any error from ftello() and catch it in fseeko() */
533 	while(ftello(iterator->file) + (FLAC__off_t)iterator->length < iterator->offset[iterator->depth]) {
534 		if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
535 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
536 			return false;
537 		}
538 		this_offset = ftello(iterator->file);
539 		if(!read_metadata_block_header_(iterator))
540 			return false;
541 	}
542 
543 	iterator->offset[iterator->depth] = this_offset;
544 
545 	return true;
546 }
547 
548 /*@@@@add to tests*/
FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator * iterator)549 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator)
550 {
551 	FLAC__ASSERT(0 != iterator);
552 	FLAC__ASSERT(0 != iterator->file);
553 
554 	return iterator->is_last;
555 }
556 
557 /*@@@@add to tests*/
FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator * iterator)558 FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator)
559 {
560 	FLAC__ASSERT(0 != iterator);
561 	FLAC__ASSERT(0 != iterator->file);
562 
563 	return iterator->offset[iterator->depth];
564 }
565 
FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator * iterator)566 FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator)
567 {
568 	FLAC__ASSERT(0 != iterator);
569 	FLAC__ASSERT(0 != iterator->file);
570 
571 	return iterator->type;
572 }
573 
574 /*@@@@add to tests*/
FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator * iterator)575 FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator)
576 {
577 	FLAC__ASSERT(0 != iterator);
578 	FLAC__ASSERT(0 != iterator->file);
579 
580 	return iterator->length;
581 }
582 
583 /*@@@@add to tests*/
FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator * iterator,FLAC__byte * id)584 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id)
585 {
586 	const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
587 
588 	FLAC__ASSERT(0 != iterator);
589 	FLAC__ASSERT(0 != iterator->file);
590 	FLAC__ASSERT(0 != id);
591 
592 	if(iterator->type != FLAC__METADATA_TYPE_APPLICATION) {
593 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
594 		return false;
595 	}
596 
597 	if(fread(id, 1, id_bytes, iterator->file) != id_bytes) {
598 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
599 		return false;
600 	}
601 
602 	/* back up */
603 	if(0 != fseeko(iterator->file, -((int)id_bytes), SEEK_CUR)) {
604 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
605 		return false;
606 	}
607 
608 	return true;
609 }
610 
FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator * iterator)611 FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator)
612 {
613 	FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type);
614 
615 	FLAC__ASSERT(0 != iterator);
616 	FLAC__ASSERT(0 != iterator->file);
617 
618 	if(0 != block) {
619 		block->is_last = iterator->is_last;
620 		block->length = iterator->length;
621 
622 		if(!read_metadata_block_data_(iterator, block)) {
623 			FLAC__metadata_object_delete(block);
624 			return 0;
625 		}
626 
627 		/* back up to the beginning of the block data to stay consistent */
628 		if(0 != fseeko(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) {
629 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
630 			FLAC__metadata_object_delete(block);
631 			return 0;
632 		}
633 	}
634 	else
635 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
636 
637 	return block;
638 }
639 
FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator * iterator,FLAC__StreamMetadata * block,FLAC__bool use_padding)640 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
641 {
642 	FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth];)
643 	FLAC__bool ret;
644 
645 	FLAC__ASSERT(0 != iterator);
646 	FLAC__ASSERT(0 != iterator->file);
647 	FLAC__ASSERT(0 != block);
648 
649 	if(!iterator->is_writable) {
650 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
651 		return false;
652 	}
653 
654 	if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) {
655 		if(iterator->type != block->type) {
656 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
657 			return false;
658 		}
659 	}
660 
661 	block->is_last = iterator->is_last;
662 
663 	if(iterator->length == block->length)
664 		return write_metadata_block_stationary_(iterator, block);
665 	else if(iterator->length > block->length) {
666 		if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) {
667 			ret = write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last);
668 			FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
669 			FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
670 			return ret;
671 		}
672 		else {
673 			ret = rewrite_whole_file_(iterator, block, /*append=*/false);
674 			FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
675 			FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
676 			return ret;
677 		}
678 	}
679 	else /* iterator->length < block->length */ {
680 		unsigned padding_leftover = 0;
681 		FLAC__bool padding_is_last = false;
682 		if(use_padding) {
683 			/* first see if we can even use padding */
684 			if(iterator->is_last) {
685 				use_padding = false;
686 			}
687 			else {
688 				const unsigned extra_padding_bytes_required = block->length - iterator->length;
689 				simple_iterator_push_(iterator);
690 				if(!FLAC__metadata_simple_iterator_next(iterator)) {
691 					(void)simple_iterator_pop_(iterator);
692 					return false;
693 				}
694 				if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
695 					use_padding = false;
696 				}
697 				else {
698 					if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) {
699 						padding_leftover = 0;
700 						block->is_last = iterator->is_last;
701 					}
702 					else if(iterator->length < extra_padding_bytes_required)
703 						use_padding = false;
704 					else {
705 						padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required;
706 						padding_is_last = iterator->is_last;
707 						block->is_last = false;
708 					}
709 				}
710 				if(!simple_iterator_pop_(iterator))
711 					return false;
712 			}
713 		}
714 		if(use_padding) {
715 			if(padding_leftover == 0) {
716 				ret = write_metadata_block_stationary_(iterator, block);
717 				FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
718 				FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
719 				return ret;
720 			}
721 			else {
722 				FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
723 				ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
724 				FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
725 				FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
726 				return ret;
727 			}
728 		}
729 		else {
730 			ret = rewrite_whole_file_(iterator, block, /*append=*/false);
731 			FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
732 			FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
733 			return ret;
734 		}
735 	}
736 }
737 
FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator * iterator,FLAC__StreamMetadata * block,FLAC__bool use_padding)738 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
739 {
740 	unsigned padding_leftover = 0;
741 	FLAC__bool padding_is_last = false;
742 
743 	FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;)
744 	FLAC__bool ret;
745 
746 	FLAC__ASSERT(0 != iterator);
747 	FLAC__ASSERT(0 != iterator->file);
748 	FLAC__ASSERT(0 != block);
749 
750 	if(!iterator->is_writable)
751 		return false;
752 
753 	if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
754 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
755 		return false;
756 	}
757 
758 	block->is_last = iterator->is_last;
759 
760 	if(use_padding) {
761 		/* first see if we can even use padding */
762 		if(iterator->is_last) {
763 			use_padding = false;
764 		}
765 		else {
766 			simple_iterator_push_(iterator);
767 			if(!FLAC__metadata_simple_iterator_next(iterator)) {
768 				(void)simple_iterator_pop_(iterator);
769 				return false;
770 			}
771 			if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
772 				use_padding = false;
773 			}
774 			else {
775 				if(iterator->length == block->length) {
776 					padding_leftover = 0;
777 					block->is_last = iterator->is_last;
778 				}
779 				else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length)
780 					use_padding = false;
781 				else {
782 					padding_leftover = iterator->length - block->length;
783 					padding_is_last = iterator->is_last;
784 					block->is_last = false;
785 				}
786 			}
787 			if(!simple_iterator_pop_(iterator))
788 				return false;
789 		}
790 	}
791 	if(use_padding) {
792 		/* move to the next block, which is suitable padding */
793 		if(!FLAC__metadata_simple_iterator_next(iterator))
794 			return false;
795 		if(padding_leftover == 0) {
796 			ret = write_metadata_block_stationary_(iterator, block);
797 			FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
798 			FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
799 			return ret;
800 		}
801 		else {
802 			FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
803 			ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
804 			FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
805 			FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
806 			return ret;
807 		}
808 	}
809 	else {
810 		ret = rewrite_whole_file_(iterator, block, /*append=*/true);
811 		FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
812 		FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
813 		return ret;
814 	}
815 }
816 
FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator * iterator,FLAC__bool use_padding)817 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding)
818 {
819 	FLAC__ASSERT_DECLARATION(FLAC__off_t debug_target_offset = iterator->offset[iterator->depth];)
820 	FLAC__bool ret;
821 
822 	if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) {
823 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
824 		return false;
825 	}
826 
827 	if(use_padding) {
828 		FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
829 		if(0 == padding) {
830 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
831 			return false;
832 		}
833 		padding->length = iterator->length;
834 		if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) {
835 			FLAC__metadata_object_delete(padding);
836 			return false;
837 		}
838 		FLAC__metadata_object_delete(padding);
839 		if(!FLAC__metadata_simple_iterator_prev(iterator))
840 			return false;
841 		FLAC__ASSERT(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length == debug_target_offset);
842 		FLAC__ASSERT(ftello(iterator->file) + (FLAC__off_t)iterator->length == debug_target_offset);
843 		return true;
844 	}
845 	else {
846 		ret = rewrite_whole_file_(iterator, 0, /*append=*/false);
847 		FLAC__ASSERT(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length == debug_target_offset);
848 		FLAC__ASSERT(ftello(iterator->file) + (FLAC__off_t)iterator->length == debug_target_offset);
849 		return ret;
850 	}
851 }
852 
853 
854 
855 /****************************************************************************
856  *
857  * Level 2 implementation
858  *
859  ***************************************************************************/
860 
861 
862 typedef struct FLAC__Metadata_Node {
863 	FLAC__StreamMetadata *data;
864 	struct FLAC__Metadata_Node *prev, *next;
865 } FLAC__Metadata_Node;
866 
867 struct FLAC__Metadata_Chain {
868 	char *filename; /* will be NULL if using callbacks */
869 	FLAC__bool is_ogg;
870 	FLAC__Metadata_Node *head;
871 	FLAC__Metadata_Node *tail;
872 	unsigned nodes;
873 	FLAC__Metadata_ChainStatus status;
874 	FLAC__off_t first_offset, last_offset;
875 	/*
876 	 * This is the length of the chain initially read from the FLAC file.
877 	 * it is used to compare against the current length to decide whether
878 	 * or not the whole file has to be rewritten.
879 	 */
880 	FLAC__off_t initial_length;
881 	/* @@@ hacky, these are currently only needed by ogg reader */
882 	FLAC__IOHandle handle;
883 	FLAC__IOCallback_Read read_cb;
884 };
885 
886 struct FLAC__Metadata_Iterator {
887 	FLAC__Metadata_Chain *chain;
888 	FLAC__Metadata_Node *current;
889 };
890 
891 FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = {
892 	"FLAC__METADATA_CHAIN_STATUS_OK",
893 	"FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT",
894 	"FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE",
895 	"FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE",
896 	"FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE",
897 	"FLAC__METADATA_CHAIN_STATUS_BAD_METADATA",
898 	"FLAC__METADATA_CHAIN_STATUS_READ_ERROR",
899 	"FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR",
900 	"FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR",
901 	"FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR",
902 	"FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR",
903 	"FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR",
904 	"FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR",
905 	"FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS",
906 	"FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH",
907 	"FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL"
908 };
909 
910 
node_new_(void)911 static FLAC__Metadata_Node *node_new_(void)
912 {
913 	return calloc(1, sizeof(FLAC__Metadata_Node));
914 }
915 
node_delete_(FLAC__Metadata_Node * node)916 static void node_delete_(FLAC__Metadata_Node *node)
917 {
918 	FLAC__ASSERT(0 != node);
919 	if(0 != node->data)
920 		FLAC__metadata_object_delete(node->data);
921 	free(node);
922 }
923 
chain_init_(FLAC__Metadata_Chain * chain)924 static void chain_init_(FLAC__Metadata_Chain *chain)
925 {
926 	FLAC__ASSERT(0 != chain);
927 
928 	chain->filename = 0;
929 	chain->is_ogg = false;
930 	chain->head = chain->tail = 0;
931 	chain->nodes = 0;
932 	chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
933 	chain->initial_length = 0;
934 	chain->read_cb = 0;
935 }
936 
chain_clear_(FLAC__Metadata_Chain * chain)937 static void chain_clear_(FLAC__Metadata_Chain *chain)
938 {
939 	FLAC__Metadata_Node *node, *next;
940 
941 	FLAC__ASSERT(0 != chain);
942 
943 	for(node = chain->head; node; ) {
944 		next = node->next;
945 		node_delete_(node);
946 		node = next;
947 	}
948 
949 	if(0 != chain->filename)
950 		free(chain->filename);
951 
952 	chain_init_(chain);
953 }
954 
chain_append_node_(FLAC__Metadata_Chain * chain,FLAC__Metadata_Node * node)955 static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
956 {
957 	FLAC__ASSERT(0 != chain);
958 	FLAC__ASSERT(0 != node);
959 	FLAC__ASSERT(0 != node->data);
960 
961 	node->next = node->prev = 0;
962 	node->data->is_last = true;
963 	if(0 != chain->tail)
964 		chain->tail->data->is_last = false;
965 
966 	if(0 == chain->head)
967 		chain->head = node;
968 	else {
969 		FLAC__ASSERT(0 != chain->tail);
970 		chain->tail->next = node;
971 		node->prev = chain->tail;
972 	}
973 	chain->tail = node;
974 	chain->nodes++;
975 }
976 
chain_remove_node_(FLAC__Metadata_Chain * chain,FLAC__Metadata_Node * node)977 static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
978 {
979 	FLAC__ASSERT(0 != chain);
980 	FLAC__ASSERT(0 != node);
981 
982 	if(node == chain->head)
983 		chain->head = node->next;
984 	else
985 		node->prev->next = node->next;
986 
987 	if(node == chain->tail)
988 		chain->tail = node->prev;
989 	else
990 		node->next->prev = node->prev;
991 
992 	if(0 != chain->tail)
993 		chain->tail->data->is_last = true;
994 
995 	chain->nodes--;
996 }
997 
chain_delete_node_(FLAC__Metadata_Chain * chain,FLAC__Metadata_Node * node)998 static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
999 {
1000 	chain_remove_node_(chain, node);
1001 	node_delete_(node);
1002 }
1003 
chain_calculate_length_(FLAC__Metadata_Chain * chain)1004 static FLAC__off_t chain_calculate_length_(FLAC__Metadata_Chain *chain)
1005 {
1006 	const FLAC__Metadata_Node *node;
1007 	FLAC__off_t length = 0;
1008 	for(node = chain->head; node; node = node->next)
1009 		length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1010 	return length;
1011 }
1012 
iterator_insert_node_(FLAC__Metadata_Iterator * iterator,FLAC__Metadata_Node * node)1013 static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1014 {
1015 	FLAC__ASSERT(0 != node);
1016 	FLAC__ASSERT(0 != node->data);
1017 	FLAC__ASSERT(0 != iterator);
1018 	FLAC__ASSERT(0 != iterator->current);
1019 	FLAC__ASSERT(0 != iterator->chain);
1020 	FLAC__ASSERT(0 != iterator->chain->head);
1021 	FLAC__ASSERT(0 != iterator->chain->tail);
1022 
1023 	node->data->is_last = false;
1024 
1025 	node->prev = iterator->current->prev;
1026 	node->next = iterator->current;
1027 
1028 	if(0 == node->prev)
1029 		iterator->chain->head = node;
1030 	else
1031 		node->prev->next = node;
1032 
1033 	iterator->current->prev = node;
1034 
1035 	iterator->chain->nodes++;
1036 }
1037 
iterator_insert_node_after_(FLAC__Metadata_Iterator * iterator,FLAC__Metadata_Node * node)1038 static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1039 {
1040 	FLAC__ASSERT(0 != node);
1041 	FLAC__ASSERT(0 != node->data);
1042 	FLAC__ASSERT(0 != iterator);
1043 	FLAC__ASSERT(0 != iterator->current);
1044 	FLAC__ASSERT(0 != iterator->chain);
1045 	FLAC__ASSERT(0 != iterator->chain->head);
1046 	FLAC__ASSERT(0 != iterator->chain->tail);
1047 
1048 	iterator->current->data->is_last = false;
1049 
1050 	node->prev = iterator->current;
1051 	node->next = iterator->current->next;
1052 
1053 	if(0 == node->next)
1054 		iterator->chain->tail = node;
1055 	else
1056 		node->next->prev = node;
1057 
1058 	node->prev->next = node;
1059 
1060 	iterator->chain->tail->data->is_last = true;
1061 
1062 	iterator->chain->nodes++;
1063 }
1064 
1065 /* return true iff node and node->next are both padding */
chain_merge_adjacent_padding_(FLAC__Metadata_Chain * chain,FLAC__Metadata_Node * node)1066 static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1067 {
1068 	if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
1069 		const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
1070 		node->data->length += growth;
1071 
1072 		chain_delete_node_(chain, node->next);
1073 		return true;
1074 	}
1075 	else
1076 		return false;
1077 }
1078 
1079 /* Returns the new length of the chain, or 0 if there was an error. */
1080 /* WATCHOUT: This can get called multiple times before a write, so
1081  * it should still work when this happens.
1082  */
1083 /* WATCHOUT: Make sure to also update the logic in
1084  * FLAC__metadata_chain_check_if_tempfile_needed() if the logic here changes.
1085  */
chain_prepare_for_write_(FLAC__Metadata_Chain * chain,FLAC__bool use_padding)1086 static FLAC__off_t chain_prepare_for_write_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1087 {
1088 	FLAC__off_t current_length = chain_calculate_length_(chain);
1089 
1090 	if(use_padding) {
1091 		/* if the metadata shrank and the last block is padding, we just extend the last padding block */
1092 		if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1093 			const FLAC__off_t delta = chain->initial_length - current_length;
1094 			chain->tail->data->length += delta;
1095 			current_length += delta;
1096 			FLAC__ASSERT(current_length == chain->initial_length);
1097 		}
1098 		/* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1099 		else if(current_length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
1100 			FLAC__StreamMetadata *padding;
1101 			FLAC__Metadata_Node *node;
1102 			if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
1103 				chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1104 				return 0;
1105 			}
1106 			padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
1107 			if(0 == (node = node_new_())) {
1108 				FLAC__metadata_object_delete(padding);
1109 				chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1110 				return 0;
1111 			}
1112 			node->data = padding;
1113 			chain_append_node_(chain, node);
1114 			current_length = chain_calculate_length_(chain);
1115 			FLAC__ASSERT(current_length == chain->initial_length);
1116 		}
1117 		/* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1118 		else if(current_length > chain->initial_length) {
1119 			const FLAC__off_t delta = current_length - chain->initial_length;
1120 			if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1121 				/* if the delta is exactly the size of the last padding block, remove the padding block */
1122 				if((FLAC__off_t)chain->tail->data->length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
1123 					chain_delete_node_(chain, chain->tail);
1124 					current_length = chain_calculate_length_(chain);
1125 					FLAC__ASSERT(current_length == chain->initial_length);
1126 				}
1127 				/* if there is at least 'delta' bytes of padding, trim the padding down */
1128 				else if((FLAC__off_t)chain->tail->data->length >= delta) {
1129 					chain->tail->data->length -= delta;
1130 					current_length -= delta;
1131 					FLAC__ASSERT(current_length == chain->initial_length);
1132 				}
1133 			}
1134 		}
1135 	}
1136 
1137 	return current_length;
1138 }
1139 
chain_read_cb_(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOCallback_Seek seek_cb,FLAC__IOCallback_Tell tell_cb)1140 static FLAC__bool chain_read_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Tell tell_cb)
1141 {
1142 	FLAC__Metadata_Node *node;
1143 
1144 	FLAC__ASSERT(0 != chain);
1145 
1146 	/* we assume we're already at the beginning of the file */
1147 
1148 	switch(seek_to_first_metadata_block_cb_(handle, read_cb, seek_cb)) {
1149 		case 0:
1150 			break;
1151 		case 1:
1152 			chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1153 			return false;
1154 		case 2:
1155 			chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1156 			return false;
1157 		case 3:
1158 			chain->status = FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
1159 			return false;
1160 		default:
1161 			FLAC__ASSERT(0);
1162 			return false;
1163 	}
1164 
1165 	{
1166 		FLAC__int64 pos = tell_cb(handle);
1167 		if(pos < 0) {
1168 			chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1169 			return false;
1170 		}
1171 		chain->first_offset = (FLAC__off_t)pos;
1172 	}
1173 
1174 	{
1175 		FLAC__bool is_last;
1176 		FLAC__MetadataType type;
1177 		unsigned length;
1178 
1179 		do {
1180 			node = node_new_();
1181 			if(0 == node) {
1182 				chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1183 				return false;
1184 			}
1185 
1186 			if(!read_metadata_block_header_cb_(handle, read_cb, &is_last, &type, &length)) {
1187 				node_delete_(node);
1188 				chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1189 				return false;
1190 			}
1191 
1192 			node->data = FLAC__metadata_object_new(type);
1193 			if(0 == node->data) {
1194 				node_delete_(node);
1195 				chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1196 				return false;
1197 			}
1198 
1199 			node->data->is_last = is_last;
1200 			node->data->length = length;
1201 
1202 			chain->status = get_equivalent_status_(read_metadata_block_data_cb_(handle, read_cb, seek_cb, node->data));
1203 			if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1204 				node_delete_(node);
1205 				return false;
1206 			}
1207 			chain_append_node_(chain, node);
1208 		} while(!is_last);
1209 	}
1210 
1211 	{
1212 		FLAC__int64 pos = tell_cb(handle);
1213 		if(pos < 0) {
1214 			chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1215 			return false;
1216 		}
1217 		chain->last_offset = (FLAC__off_t)pos;
1218 	}
1219 
1220 	chain->initial_length = chain_calculate_length_(chain);
1221 
1222 	return true;
1223 }
1224 
chain_read_ogg_read_cb_(const FLAC__StreamDecoder * decoder,FLAC__byte buffer[],size_t * bytes,void * client_data)1225 static FLAC__StreamDecoderReadStatus chain_read_ogg_read_cb_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
1226 {
1227 	FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1228 	(void)decoder;
1229 	if(*bytes > 0 && chain->status == FLAC__METADATA_CHAIN_STATUS_OK) {
1230 		*bytes = chain->read_cb(buffer, sizeof(FLAC__byte), *bytes, chain->handle);
1231 		if(*bytes == 0)
1232 			return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
1233 		else
1234 			return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
1235 	}
1236 	else
1237 		return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
1238 }
1239 
chain_read_ogg_write_cb_(const FLAC__StreamDecoder * decoder,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)1240 static FLAC__StreamDecoderWriteStatus chain_read_ogg_write_cb_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1241 {
1242 	(void)decoder, (void)frame, (void)buffer, (void)client_data;
1243 	return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1244 }
1245 
chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder * decoder,const FLAC__StreamMetadata * metadata,void * client_data)1246 static void chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1247 {
1248 	FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1249 	FLAC__Metadata_Node *node;
1250 
1251 	(void)decoder;
1252 
1253 	node = node_new_();
1254 	if(0 == node) {
1255 		chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1256 		return;
1257 	}
1258 
1259 	node->data = FLAC__metadata_object_clone(metadata);
1260 	if(0 == node->data) {
1261 		node_delete_(node);
1262 		chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1263 		return;
1264 	}
1265 
1266 	chain_append_node_(chain, node);
1267 }
1268 
chain_read_ogg_error_cb_(const FLAC__StreamDecoder * decoder,FLAC__StreamDecoderErrorStatus status,void * client_data)1269 static void chain_read_ogg_error_cb_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1270 {
1271 	FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1272 	(void)decoder, (void)status;
1273 	chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1274 }
1275 
chain_read_ogg_cb_(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb)1276 static FLAC__bool chain_read_ogg_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb)
1277 {
1278 	FLAC__StreamDecoder *decoder;
1279 
1280 	FLAC__ASSERT(0 != chain);
1281 
1282 	/* we assume we're already at the beginning of the file */
1283 
1284 	chain->handle = handle;
1285 	chain->read_cb = read_cb;
1286 	if(0 == (decoder = FLAC__stream_decoder_new())) {
1287 		chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1288 		return false;
1289 	}
1290 	FLAC__stream_decoder_set_metadata_respond_all(decoder);
1291 	if(FLAC__stream_decoder_init_ogg_stream(decoder, chain_read_ogg_read_cb_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, chain_read_ogg_write_cb_, chain_read_ogg_metadata_cb_, chain_read_ogg_error_cb_, chain) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1292 		FLAC__stream_decoder_delete(decoder);
1293 		chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1294 		return false;
1295 	}
1296 
1297 	chain->first_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1298 
1299 	if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
1300 		chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1301 	if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1302 		FLAC__stream_decoder_delete(decoder);
1303 		return false;
1304 	}
1305 
1306 	FLAC__stream_decoder_delete(decoder);
1307 
1308 	chain->last_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1309 
1310 	chain->initial_length = chain_calculate_length_(chain);
1311 
1312 	return true;
1313 }
1314 
chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,FLAC__IOCallback_Seek seek_cb)1315 static FLAC__bool chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, FLAC__IOCallback_Seek seek_cb)
1316 {
1317 	FLAC__Metadata_Node *node;
1318 
1319 	FLAC__ASSERT(0 != chain);
1320 	FLAC__ASSERT(0 != chain->head);
1321 
1322 	if(0 != seek_cb(handle, chain->first_offset, SEEK_SET)) {
1323 		chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1324 		return false;
1325 	}
1326 
1327 	for(node = chain->head; node; node = node->next) {
1328 		if(!write_metadata_block_header_cb_(handle, write_cb, node->data)) {
1329 			chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1330 			return false;
1331 		}
1332 		if(!write_metadata_block_data_cb_(handle, write_cb, node->data)) {
1333 			chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1334 			return false;
1335 		}
1336 	}
1337 
1338 	/*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1339 
1340 	chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1341 	return true;
1342 }
1343 
chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain * chain)1344 static FLAC__bool chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain *chain)
1345 {
1346 	FILE *file;
1347 	FLAC__bool ret;
1348 
1349 	FLAC__ASSERT(0 != chain->filename);
1350 
1351 	if(0 == (file = flac_fopen(chain->filename, "r+b"))) {
1352 		chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1353 		return false;
1354 	}
1355 
1356 	/* chain_rewrite_metadata_in_place_cb_() sets chain->status for us */
1357 	ret = chain_rewrite_metadata_in_place_cb_(chain, (FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, fseek_wrapper_);
1358 
1359 	fclose(file);
1360 
1361 	return ret;
1362 }
1363 
chain_rewrite_file_(FLAC__Metadata_Chain * chain,const char * tempfile_path_prefix)1364 static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
1365 {
1366 	FILE *f, *tempfile = NULL;
1367 	char *tempfilename;
1368 	FLAC__Metadata_SimpleIteratorStatus status;
1369 	const FLAC__Metadata_Node *node;
1370 
1371 	FLAC__ASSERT(0 != chain);
1372 	FLAC__ASSERT(0 != chain->filename);
1373 	FLAC__ASSERT(0 != chain->head);
1374 
1375 	/* copy the file prefix (data up to first metadata block */
1376 	if(0 == (f = flac_fopen(chain->filename, "rb"))) {
1377 		chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1378 		return false;
1379 	}
1380 	if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
1381 		chain->status = get_equivalent_status_(status);
1382 		goto err;
1383 	}
1384 	if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
1385 		chain->status = get_equivalent_status_(status);
1386 		goto err;
1387 	}
1388 
1389 	/* write the metadata */
1390 	for(node = chain->head; node; node = node->next) {
1391 		if(!write_metadata_block_header_(tempfile, &status, node->data)) {
1392 			chain->status = get_equivalent_status_(status);
1393 			goto err;
1394 		}
1395 		if(!write_metadata_block_data_(tempfile, &status, node->data)) {
1396 			chain->status = get_equivalent_status_(status);
1397 			goto err;
1398 		}
1399 	}
1400 	/*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1401 
1402 	/* copy the file postfix (everything after the metadata) */
1403 	if(0 != fseeko(f, chain->last_offset, SEEK_SET)) {
1404 		chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1405 		goto err;
1406 	}
1407 	if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
1408 		chain->status = get_equivalent_status_(status);
1409 		goto err;
1410 	}
1411 
1412 	/* move the tempfile on top of the original */
1413 	(void)fclose(f);
1414 	if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
1415 		return false;
1416 
1417 	return true;
1418 
1419 err:
1420 	(void)fclose(f);
1421 	cleanup_tempfile_(&tempfile, &tempfilename);
1422 	return false;
1423 }
1424 
1425 /* assumes 'handle' is already at beginning of file */
chain_rewrite_file_cb_(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOCallback_Seek seek_cb,FLAC__IOCallback_Eof eof_cb,FLAC__IOHandle temp_handle,FLAC__IOCallback_Write temp_write_cb)1426 static FLAC__bool chain_rewrite_file_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb)
1427 {
1428 	FLAC__Metadata_SimpleIteratorStatus status;
1429 	const FLAC__Metadata_Node *node;
1430 
1431 	FLAC__ASSERT(0 != chain);
1432 	FLAC__ASSERT(0 == chain->filename);
1433 	FLAC__ASSERT(0 != chain->head);
1434 
1435 	/* copy the file prefix (data up to first metadata block */
1436 	if(!copy_n_bytes_from_file_cb_(handle, read_cb, temp_handle, temp_write_cb, chain->first_offset, &status)) {
1437 		chain->status = get_equivalent_status_(status);
1438 		return false;
1439 	}
1440 
1441 	/* write the metadata */
1442 	for(node = chain->head; node; node = node->next) {
1443 		if(!write_metadata_block_header_cb_(temp_handle, temp_write_cb, node->data)) {
1444 			chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1445 			return false;
1446 		}
1447 		if(!write_metadata_block_data_cb_(temp_handle, temp_write_cb, node->data)) {
1448 			chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1449 			return false;
1450 		}
1451 	}
1452 	/*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1453 
1454 	/* copy the file postfix (everything after the metadata) */
1455 	if(0 != seek_cb(handle, chain->last_offset, SEEK_SET)) {
1456 		chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1457 		return false;
1458 	}
1459 	if(!copy_remaining_bytes_from_file_cb_(handle, read_cb, eof_cb, temp_handle, temp_write_cb, &status)) {
1460 		chain->status = get_equivalent_status_(status);
1461 		return false;
1462 	}
1463 
1464 	return true;
1465 }
1466 
FLAC__metadata_chain_new(void)1467 FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void)
1468 {
1469 	FLAC__Metadata_Chain *chain = calloc(1, sizeof(FLAC__Metadata_Chain));
1470 
1471 	if(0 != chain)
1472 		chain_init_(chain);
1473 
1474 	return chain;
1475 }
1476 
FLAC__metadata_chain_delete(FLAC__Metadata_Chain * chain)1477 FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
1478 {
1479 	FLAC__ASSERT(0 != chain);
1480 
1481 	chain_clear_(chain);
1482 
1483 	free(chain);
1484 }
1485 
FLAC__metadata_chain_status(FLAC__Metadata_Chain * chain)1486 FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
1487 {
1488 	FLAC__Metadata_ChainStatus status;
1489 
1490 	FLAC__ASSERT(0 != chain);
1491 
1492 	status = chain->status;
1493 	chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1494 	return status;
1495 }
1496 
chain_read_(FLAC__Metadata_Chain * chain,const char * filename,FLAC__bool is_ogg)1497 static FLAC__bool chain_read_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool is_ogg)
1498 {
1499 	FILE *file;
1500 	FLAC__bool ret;
1501 
1502 	FLAC__ASSERT(0 != chain);
1503 	FLAC__ASSERT(0 != filename);
1504 
1505 	chain_clear_(chain);
1506 
1507 	if(0 == (chain->filename = strdup(filename))) {
1508 		chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1509 		return false;
1510 	}
1511 
1512 	chain->is_ogg = is_ogg;
1513 
1514 	if(0 == (file = flac_fopen(filename, "rb"))) {
1515 		chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1516 		return false;
1517 	}
1518 
1519 	/* the function also sets chain->status for us */
1520 	ret = is_ogg?
1521 		chain_read_ogg_cb_(chain, file, (FLAC__IOCallback_Read)fread) :
1522 		chain_read_cb_(chain, file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, ftell_wrapper_)
1523 	;
1524 
1525 	fclose(file);
1526 
1527 	return ret;
1528 }
1529 
FLAC__metadata_chain_read(FLAC__Metadata_Chain * chain,const char * filename)1530 FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
1531 {
1532 	return chain_read_(chain, filename, /*is_ogg=*/false);
1533 }
1534 
1535 /*@@@@add to tests*/
FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain * chain,const char * filename)1536 FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename)
1537 {
1538 	return chain_read_(chain, filename, /*is_ogg=*/true);
1539 }
1540 
chain_read_with_callbacks_(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallbacks callbacks,FLAC__bool is_ogg)1541 static FLAC__bool chain_read_with_callbacks_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__bool is_ogg)
1542 {
1543 	FLAC__bool ret;
1544 
1545 	FLAC__ASSERT(0 != chain);
1546 
1547 	chain_clear_(chain);
1548 
1549 	if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.tell) {
1550 		chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1551 		return false;
1552 	}
1553 
1554 	chain->is_ogg = is_ogg;
1555 
1556 	/* rewind */
1557 	if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1558 		chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1559 		return false;
1560 	}
1561 
1562 	/* the function also sets chain->status for us */
1563 	ret = is_ogg?
1564 		chain_read_ogg_cb_(chain, handle, callbacks.read) :
1565 		chain_read_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.tell)
1566 	;
1567 
1568 	return ret;
1569 }
1570 
FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallbacks callbacks)1571 FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1572 {
1573 	return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/false);
1574 }
1575 
1576 /*@@@@add to tests*/
FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain * chain,FLAC__IOHandle handle,FLAC__IOCallbacks callbacks)1577 FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1578 {
1579 	return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/true);
1580 }
1581 
FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain * chain,FLAC__bool use_padding)1582 FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1583 {
1584 	/* This does all the same checks that are in chain_prepare_for_write_()
1585 	 * but doesn't actually alter the chain.  Make sure to update the logic
1586 	 * here if chain_prepare_for_write_() changes.
1587 	 */
1588 	const FLAC__off_t current_length = chain_calculate_length_(chain);
1589 
1590 	FLAC__ASSERT(0 != chain);
1591 
1592 	if(use_padding) {
1593 		/* if the metadata shrank and the last block is padding, we just extend the last padding block */
1594 		if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING)
1595 			return false;
1596 		/* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1597 		else if(current_length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length)
1598 			return false;
1599 		/* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1600 		else if(current_length > chain->initial_length) {
1601 			const FLAC__off_t delta = current_length - chain->initial_length;
1602 			if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1603 				/* if the delta is exactly the size of the last padding block, remove the padding block */
1604 				if((FLAC__off_t)chain->tail->data->length + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta)
1605 					return false;
1606 				/* if there is at least 'delta' bytes of padding, trim the padding down */
1607 				else if((FLAC__off_t)chain->tail->data->length >= delta)
1608 					return false;
1609 			}
1610 		}
1611 	}
1612 
1613 	return (current_length != chain->initial_length);
1614 }
1615 
FLAC__metadata_chain_write(FLAC__Metadata_Chain * chain,FLAC__bool use_padding,FLAC__bool preserve_file_stats)1616 FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
1617 {
1618 	struct flac_stat_s stats;
1619 	const char *tempfile_path_prefix = 0;
1620 	FLAC__off_t current_length;
1621 
1622 	FLAC__ASSERT(0 != chain);
1623 
1624 	if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1625 		chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1626 		return false;
1627 	}
1628 
1629 	if (0 == chain->filename) {
1630 		chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1631 		return false;
1632 	}
1633 
1634 	current_length = chain_prepare_for_write_(chain, use_padding);
1635 
1636 	/* a return value of 0 means there was an error; chain->status is already set */
1637 	if (0 == current_length)
1638 		return false;
1639 
1640 	if(preserve_file_stats)
1641 		get_file_stats_(chain->filename, &stats);
1642 
1643 	if(current_length == chain->initial_length) {
1644 		if(!chain_rewrite_metadata_in_place_(chain))
1645 			return false;
1646 	}
1647 	else {
1648 		if(!chain_rewrite_file_(chain, tempfile_path_prefix))
1649 			return false;
1650 
1651 		/* recompute lengths and offsets */
1652 		{
1653 			const FLAC__Metadata_Node *node;
1654 			chain->initial_length = current_length;
1655 			chain->last_offset = chain->first_offset;
1656 			for(node = chain->head; node; node = node->next)
1657 				chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1658 		}
1659 	}
1660 
1661 	if(preserve_file_stats)
1662 		set_file_stats_(chain->filename, &stats);
1663 
1664 	return true;
1665 }
1666 
FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain * chain,FLAC__bool use_padding,FLAC__IOHandle handle,FLAC__IOCallbacks callbacks)1667 FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1668 {
1669 	FLAC__off_t current_length;
1670 
1671 	FLAC__ASSERT(0 != chain);
1672 
1673 	if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1674 		chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1675 		return false;
1676 	}
1677 
1678 	if (0 != chain->filename) {
1679 		chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1680 		return false;
1681 	}
1682 
1683 	if (0 == callbacks.write || 0 == callbacks.seek) {
1684 		chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1685 		return false;
1686 	}
1687 
1688 	if (FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1689 		chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1690 		return false;
1691 	}
1692 
1693 	current_length = chain_prepare_for_write_(chain, use_padding);
1694 
1695 	/* a return value of 0 means there was an error; chain->status is already set */
1696 	if (0 == current_length)
1697 		return false;
1698 
1699 	FLAC__ASSERT(current_length == chain->initial_length);
1700 
1701 	return chain_rewrite_metadata_in_place_cb_(chain, handle, callbacks.write, callbacks.seek);
1702 }
1703 
FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain * chain,FLAC__bool use_padding,FLAC__IOHandle handle,FLAC__IOCallbacks callbacks,FLAC__IOHandle temp_handle,FLAC__IOCallbacks temp_callbacks)1704 FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks)
1705 {
1706 	FLAC__off_t current_length;
1707 
1708 	FLAC__ASSERT(0 != chain);
1709 
1710 	if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1711 		chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1712 		return false;
1713 	}
1714 
1715 	if (0 != chain->filename) {
1716 		chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1717 		return false;
1718 	}
1719 
1720 	if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.eof) {
1721 		chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1722 		return false;
1723 	}
1724 	if (0 == temp_callbacks.write) {
1725 		chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1726 		return false;
1727 	}
1728 
1729 	if (!FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1730 		chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1731 		return false;
1732 	}
1733 
1734 	current_length = chain_prepare_for_write_(chain, use_padding);
1735 
1736 	/* a return value of 0 means there was an error; chain->status is already set */
1737 	if (0 == current_length)
1738 		return false;
1739 
1740 	FLAC__ASSERT(current_length != chain->initial_length);
1741 
1742 	/* rewind */
1743 	if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1744 		chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1745 		return false;
1746 	}
1747 
1748 	if(!chain_rewrite_file_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.eof, temp_handle, temp_callbacks.write))
1749 		return false;
1750 
1751 	/* recompute lengths and offsets */
1752 	{
1753 		const FLAC__Metadata_Node *node;
1754 		chain->initial_length = current_length;
1755 		chain->last_offset = chain->first_offset;
1756 		for(node = chain->head; node; node = node->next)
1757 			chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1758 	}
1759 
1760 	return true;
1761 }
1762 
FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain * chain)1763 FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
1764 {
1765 	FLAC__Metadata_Node *node;
1766 
1767 	FLAC__ASSERT(0 != chain);
1768 
1769 	for(node = chain->head; node; ) {
1770 		if(!chain_merge_adjacent_padding_(chain, node))
1771 			node = node->next;
1772 	}
1773 }
1774 
FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain * chain)1775 FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
1776 {
1777 	FLAC__Metadata_Node *node, *save;
1778 	unsigned i;
1779 
1780 	FLAC__ASSERT(0 != chain);
1781 
1782 	/*
1783 	 * Don't try and be too smart... this simple algo is good enough for
1784 	 * the small number of nodes that we deal with.
1785 	 */
1786 	for(i = 0, node = chain->head; i < chain->nodes; i++) {
1787 		if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
1788 			save = node->next;
1789 			chain_remove_node_(chain, node);
1790 			chain_append_node_(chain, node);
1791 			node = save;
1792 		}
1793 		else {
1794 			node = node->next;
1795 		}
1796 	}
1797 
1798 	FLAC__metadata_chain_merge_padding(chain);
1799 }
1800 
1801 
FLAC__metadata_iterator_new(void)1802 FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void)
1803 {
1804 	FLAC__Metadata_Iterator *iterator = calloc(1, sizeof(FLAC__Metadata_Iterator));
1805 
1806 	/* calloc() implies:
1807 		iterator->current = 0;
1808 		iterator->chain = 0;
1809 	*/
1810 
1811 	return iterator;
1812 }
1813 
FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator * iterator)1814 FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
1815 {
1816 	FLAC__ASSERT(0 != iterator);
1817 
1818 	free(iterator);
1819 }
1820 
FLAC__metadata_iterator_init(FLAC__Metadata_Iterator * iterator,FLAC__Metadata_Chain * chain)1821 FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
1822 {
1823 	FLAC__ASSERT(0 != iterator);
1824 	FLAC__ASSERT(0 != chain);
1825 	FLAC__ASSERT(0 != chain->head);
1826 
1827 	iterator->chain = chain;
1828 	iterator->current = chain->head;
1829 }
1830 
FLAC__metadata_iterator_next(FLAC__Metadata_Iterator * iterator)1831 FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
1832 {
1833 	FLAC__ASSERT(0 != iterator);
1834 
1835 	if(0 == iterator->current || 0 == iterator->current->next)
1836 		return false;
1837 
1838 	iterator->current = iterator->current->next;
1839 	return true;
1840 }
1841 
FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator * iterator)1842 FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
1843 {
1844 	FLAC__ASSERT(0 != iterator);
1845 
1846 	if(0 == iterator->current || 0 == iterator->current->prev)
1847 		return false;
1848 
1849 	iterator->current = iterator->current->prev;
1850 	return true;
1851 }
1852 
FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator * iterator)1853 FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
1854 {
1855 	FLAC__ASSERT(0 != iterator);
1856 	FLAC__ASSERT(0 != iterator->current);
1857 	FLAC__ASSERT(0 != iterator->current->data);
1858 
1859 	return iterator->current->data->type;
1860 }
1861 
FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator * iterator)1862 FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
1863 {
1864 	FLAC__ASSERT(0 != iterator);
1865 	FLAC__ASSERT(0 != iterator->current);
1866 
1867 	return iterator->current->data;
1868 }
1869 
FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator * iterator,FLAC__StreamMetadata * block)1870 FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1871 {
1872 	FLAC__ASSERT(0 != iterator);
1873 	FLAC__ASSERT(0 != block);
1874 	return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
1875 }
1876 
FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator * iterator,FLAC__bool replace_with_padding)1877 FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
1878 {
1879 	FLAC__Metadata_Node *save;
1880 
1881 	FLAC__ASSERT(0 != iterator);
1882 	FLAC__ASSERT(0 != iterator->current);
1883 
1884 	if(0 == iterator->current->prev) {
1885 		FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1886 		return false;
1887 	}
1888 
1889 	save = iterator->current->prev;
1890 
1891 	if(replace_with_padding) {
1892 		FLAC__metadata_object_delete_data(iterator->current->data);
1893 		iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
1894 	}
1895 	else {
1896 		chain_delete_node_(iterator->chain, iterator->current);
1897 	}
1898 
1899 	iterator->current = save;
1900 	return true;
1901 }
1902 
FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator * iterator,FLAC__StreamMetadata * block)1903 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1904 {
1905 	FLAC__Metadata_Node *node;
1906 
1907 	FLAC__ASSERT(0 != iterator);
1908 	FLAC__ASSERT(0 != iterator->current);
1909 	FLAC__ASSERT(0 != block);
1910 
1911 	if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1912 		return false;
1913 
1914 	if(0 == iterator->current->prev) {
1915 		FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1916 		return false;
1917 	}
1918 
1919 	if(0 == (node = node_new_()))
1920 		return false;
1921 
1922 	node->data = block;
1923 	iterator_insert_node_(iterator, node);
1924 	iterator->current = node;
1925 	return true;
1926 }
1927 
FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator * iterator,FLAC__StreamMetadata * block)1928 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1929 {
1930 	FLAC__Metadata_Node *node;
1931 
1932 	FLAC__ASSERT(0 != iterator);
1933 	FLAC__ASSERT(0 != iterator->current);
1934 	FLAC__ASSERT(0 != block);
1935 
1936 	if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1937 		return false;
1938 
1939 	if(0 == (node = node_new_()))
1940 		return false;
1941 
1942 	node->data = block;
1943 	iterator_insert_node_after_(iterator, node);
1944 	iterator->current = node;
1945 	return true;
1946 }
1947 
1948 
1949 /****************************************************************************
1950  *
1951  * Local function definitions
1952  *
1953  ***************************************************************************/
1954 
pack_uint32_(FLAC__uint32 val,FLAC__byte * b,unsigned bytes)1955 void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1956 {
1957 	unsigned i;
1958 
1959 	b += bytes;
1960 
1961 	for(i = 0; i < bytes; i++) {
1962 		*(--b) = (FLAC__byte)(val & 0xff);
1963 		val >>= 8;
1964 	}
1965 }
1966 
pack_uint32_little_endian_(FLAC__uint32 val,FLAC__byte * b,unsigned bytes)1967 void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1968 {
1969 	unsigned i;
1970 
1971 	for(i = 0; i < bytes; i++) {
1972 		*(b++) = (FLAC__byte)(val & 0xff);
1973 		val >>= 8;
1974 	}
1975 }
1976 
pack_uint64_(FLAC__uint64 val,FLAC__byte * b,unsigned bytes)1977 void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
1978 {
1979 	unsigned i;
1980 
1981 	b += bytes;
1982 
1983 	for(i = 0; i < bytes; i++) {
1984 		*(--b) = (FLAC__byte)(val & 0xff);
1985 		val >>= 8;
1986 	}
1987 }
1988 
unpack_uint32_(FLAC__byte * b,unsigned bytes)1989 FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
1990 {
1991 	FLAC__uint32 ret = 0;
1992 	unsigned i;
1993 
1994 	for(i = 0; i < bytes; i++)
1995 		ret = (ret << 8) | (FLAC__uint32)(*b++);
1996 
1997 	return ret;
1998 }
1999 
unpack_uint32_little_endian_(FLAC__byte * b,unsigned bytes)2000 FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
2001 {
2002 	FLAC__uint32 ret = 0;
2003 	unsigned i;
2004 
2005 	b += bytes;
2006 
2007 	for(i = 0; i < bytes; i++)
2008 		ret = (ret << 8) | (FLAC__uint32)(*--b);
2009 
2010 	return ret;
2011 }
2012 
unpack_uint64_(FLAC__byte * b,unsigned bytes)2013 FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
2014 {
2015 	FLAC__uint64 ret = 0;
2016 	unsigned i;
2017 
2018 	for(i = 0; i < bytes; i++)
2019 		ret = (ret << 8) | (FLAC__uint64)(*b++);
2020 
2021 	return ret;
2022 }
2023 
read_metadata_block_header_(FLAC__Metadata_SimpleIterator * iterator)2024 FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
2025 {
2026 	FLAC__ASSERT(0 != iterator);
2027 	FLAC__ASSERT(0 != iterator->file);
2028 
2029 	if(!read_metadata_block_header_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, &iterator->is_last, &iterator->type, &iterator->length)) {
2030 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2031 		return false;
2032 	}
2033 
2034 	return true;
2035 }
2036 
read_metadata_block_data_(FLAC__Metadata_SimpleIterator * iterator,FLAC__StreamMetadata * block)2037 FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
2038 {
2039 	FLAC__ASSERT(0 != iterator);
2040 	FLAC__ASSERT(0 != iterator->file);
2041 
2042 	iterator->status = read_metadata_block_data_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, block);
2043 
2044 	return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
2045 }
2046 
read_metadata_block_header_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__bool * is_last,FLAC__MetadataType * type,unsigned * length)2047 FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length)
2048 {
2049 	FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
2050 
2051 	if(read_cb(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2052 		return false;
2053 
2054 	*is_last = raw_header[0] & 0x80? true : false;
2055 	*type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
2056 	*length = unpack_uint32_(raw_header + 1, 3);
2057 
2058 	/* Note that we don't check:
2059 	 *    if(iterator->type >= FLAC__METADATA_TYPE_UNDEFINED)
2060 	 * we just will read in an opaque block
2061 	 */
2062 
2063 	return true;
2064 }
2065 
read_metadata_block_data_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOCallback_Seek seek_cb,FLAC__StreamMetadata * block)2066 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block)
2067 {
2068 	switch(block->type) {
2069 		case FLAC__METADATA_TYPE_STREAMINFO:
2070 			return read_metadata_block_data_streaminfo_cb_(handle, read_cb, &block->data.stream_info);
2071 		case FLAC__METADATA_TYPE_PADDING:
2072 			return read_metadata_block_data_padding_cb_(handle, seek_cb, &block->data.padding, block->length);
2073 		case FLAC__METADATA_TYPE_APPLICATION:
2074 			return read_metadata_block_data_application_cb_(handle, read_cb, &block->data.application, block->length);
2075 		case FLAC__METADATA_TYPE_SEEKTABLE:
2076 			return read_metadata_block_data_seektable_cb_(handle, read_cb, &block->data.seek_table, block->length);
2077 		case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2078 			return read_metadata_block_data_vorbis_comment_cb_(handle, read_cb, &block->data.vorbis_comment);
2079 		case FLAC__METADATA_TYPE_CUESHEET:
2080 			return read_metadata_block_data_cuesheet_cb_(handle, read_cb, &block->data.cue_sheet);
2081 		case FLAC__METADATA_TYPE_PICTURE:
2082 			return read_metadata_block_data_picture_cb_(handle, read_cb, &block->data.picture);
2083 		default:
2084 			return read_metadata_block_data_unknown_cb_(handle, read_cb, &block->data.unknown, block->length);
2085 	}
2086 }
2087 
read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_StreamInfo * block)2088 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block)
2089 {
2090 	FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
2091 
2092 	if(read_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2093 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2094 
2095 	b = buffer;
2096 
2097 	/* we are using hardcoded numbers for simplicity but we should
2098 	 * probably eventually write a bit-level unpacker and use the
2099 	 * _STREAMINFO_ constants.
2100 	 */
2101 	block->min_blocksize = unpack_uint32_(b, 2); b += 2;
2102 	block->max_blocksize = unpack_uint32_(b, 2); b += 2;
2103 	block->min_framesize = unpack_uint32_(b, 3); b += 3;
2104 	block->max_framesize = unpack_uint32_(b, 3); b += 3;
2105 	block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
2106 	block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
2107 	block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
2108 	block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
2109 	memcpy(block->md5sum, b+8, 16);
2110 
2111 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2112 }
2113 
read_metadata_block_data_padding_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Seek seek_cb,FLAC__StreamMetadata_Padding * block,unsigned block_length)2114 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length)
2115 {
2116 	(void)block; /* nothing to do; we don't care about reading the padding bytes */
2117 
2118 	if(0 != seek_cb(handle, block_length, SEEK_CUR))
2119 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2120 
2121 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2122 }
2123 
read_metadata_block_data_application_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_Application * block,unsigned block_length)2124 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length)
2125 {
2126 	const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2127 
2128 	if(read_cb(block->id, 1, id_bytes, handle) != id_bytes)
2129 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2130 
2131 	if(block_length < id_bytes)
2132 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2133 
2134 	block_length -= id_bytes;
2135 
2136 	if(block_length == 0) {
2137 		block->data = 0;
2138 	}
2139 	else {
2140 		if(0 == (block->data = malloc(block_length)))
2141 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2142 
2143 		if(read_cb(block->data, 1, block_length, handle) != block_length)
2144 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2145 	}
2146 
2147 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2148 }
2149 
read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_SeekTable * block,unsigned block_length)2150 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
2151 {
2152 	unsigned i;
2153 	FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2154 
2155 	FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
2156 
2157 	block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
2158 
2159 	if(block->num_points == 0)
2160 		block->points = 0;
2161 	else if(0 == (block->points = safe_malloc_mul_2op_p(block->num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint))))
2162 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2163 
2164 	for(i = 0; i < block->num_points; i++) {
2165 		if(read_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2166 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2167 		/* some MAGIC NUMBERs here */
2168 		block->points[i].sample_number = unpack_uint64_(buffer, 8);
2169 		block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
2170 		block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
2171 	}
2172 
2173 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2174 }
2175 
read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_VorbisComment_Entry * entry)2176 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry)
2177 {
2178 	const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2179 	FLAC__byte buffer[4]; /* magic number is asserted below */
2180 
2181 	FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == sizeof(buffer));
2182 
2183 	if(read_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2184 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2185 	entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
2186 
2187 	if(0 != entry->entry)
2188 		free(entry->entry);
2189 
2190 	if(entry->length == 0) {
2191 		entry->entry = 0;
2192 	}
2193 	else {
2194 		if(0 == (entry->entry = safe_malloc_add_2op_(entry->length, /*+*/1)))
2195 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2196 
2197 		if(read_cb(entry->entry, 1, entry->length, handle) != entry->length)
2198 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2199 
2200 		entry->entry[entry->length] = '\0';
2201 	}
2202 
2203 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2204 }
2205 
read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_VorbisComment * block)2206 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block)
2207 {
2208 	unsigned i;
2209 	FLAC__Metadata_SimpleIteratorStatus status;
2210 	const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2211 	FLAC__byte buffer[4]; /* magic number is asserted below */
2212 
2213 	FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == sizeof(buffer));
2214 
2215 	if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, &(block->vendor_string))))
2216 		return status;
2217 
2218 	if(read_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2219 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2220 	block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
2221 
2222 	if(block->num_comments == 0) {
2223 		block->comments = 0;
2224 	}
2225 	else if(0 == (block->comments = calloc(block->num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry))))
2226 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2227 
2228 	for(i = 0; i < block->num_comments; i++) {
2229 		if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, block->comments + i)))
2230 			return status;
2231 	}
2232 
2233 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2234 }
2235 
read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_CueSheet_Track * track)2236 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track)
2237 {
2238 	unsigned i, len;
2239 	FLAC__byte buffer[32]; /* asserted below that this is big enough */
2240 
2241 	FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2242 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2243 	FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8);
2244 
2245 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2246 	len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2247 	if(read_cb(buffer, 1, len, handle) != len)
2248 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2249 	track->offset = unpack_uint64_(buffer, len);
2250 
2251 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2252 	len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2253 	if(read_cb(buffer, 1, len, handle) != len)
2254 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2255 	track->number = (FLAC__byte)unpack_uint32_(buffer, len);
2256 
2257 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2258 	len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2259 	if(read_cb(track->isrc, 1, len, handle) != len)
2260 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2261 
2262 	FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2263 	len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2264 	if(read_cb(buffer, 1, len, handle) != len)
2265 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2266 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN == 1);
2267 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN == 1);
2268 	track->type = buffer[0] >> 7;
2269 	track->pre_emphasis = (buffer[0] >> 6) & 1;
2270 
2271 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2272 	len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2273 	if(read_cb(buffer, 1, len, handle) != len)
2274 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2275 	track->num_indices = (FLAC__byte)unpack_uint32_(buffer, len);
2276 
2277 	if(track->num_indices == 0) {
2278 		track->indices = 0;
2279 	}
2280 	else if(0 == (track->indices = calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index))))
2281 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2282 
2283 	for(i = 0; i < track->num_indices; i++) {
2284 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2285 		len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2286 		if(read_cb(buffer, 1, len, handle) != len)
2287 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2288 		track->indices[i].offset = unpack_uint64_(buffer, len);
2289 
2290 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2291 		len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2292 		if(read_cb(buffer, 1, len, handle) != len)
2293 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2294 		track->indices[i].number = (FLAC__byte)unpack_uint32_(buffer, len);
2295 
2296 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2297 		len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2298 		if(read_cb(buffer, 1, len, handle) != len)
2299 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2300 	}
2301 
2302 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2303 }
2304 
read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_CueSheet * block)2305 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block)
2306 {
2307 	unsigned i, len;
2308 	FLAC__Metadata_SimpleIteratorStatus status;
2309 	FLAC__byte buffer[1024]; /* MSVC needs a constant expression so we put a magic number and assert */
2310 
2311 	FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)/8 <= sizeof(buffer));
2312 	FLAC__ASSERT(sizeof(FLAC__uint64) <= sizeof(buffer));
2313 
2314 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2315 	len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2316 	if(read_cb(block->media_catalog_number, 1, len, handle) != len)
2317 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2318 
2319 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2320 	len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2321 	if(read_cb(buffer, 1, len, handle) != len)
2322 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2323 	block->lead_in = unpack_uint64_(buffer, len);
2324 
2325 	FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2326 	len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2327 	if(read_cb(buffer, 1, len, handle) != len)
2328 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2329 	block->is_cd = buffer[0]&0x80? true : false;
2330 
2331 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2332 	len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2333 	if(read_cb(buffer, 1, len, handle) != len)
2334 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2335 	block->num_tracks = unpack_uint32_(buffer, len);
2336 
2337 	if(block->num_tracks == 0) {
2338 		block->tracks = 0;
2339 	}
2340 	else if(0 == (block->tracks = calloc(block->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track))))
2341 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2342 
2343 	for(i = 0; i < block->num_tracks; i++) {
2344 		if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_cuesheet_track_cb_(handle, read_cb, block->tracks + i)))
2345 			return status;
2346 	}
2347 
2348 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2349 }
2350 
read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__byte ** data,FLAC__uint32 * length,FLAC__uint32 length_len)2351 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__byte **data, FLAC__uint32 *length, FLAC__uint32 length_len)
2352 {
2353 	FLAC__byte buffer[sizeof(FLAC__uint32)];
2354 
2355 	FLAC__ASSERT(0 != data);
2356 	FLAC__ASSERT(length_len%8 == 0);
2357 
2358 	length_len /= 8; /* convert to bytes */
2359 
2360 	FLAC__ASSERT(sizeof(buffer) >= length_len);
2361 
2362 	if(read_cb(buffer, 1, length_len, handle) != length_len)
2363 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2364 	*length = unpack_uint32_(buffer, length_len);
2365 
2366 	if(0 != *data)
2367 		free(*data);
2368 
2369 	if(0 == (*data = safe_malloc_add_2op_(*length, /*+*/1)))
2370 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2371 
2372 	if(*length > 0) {
2373 		if(read_cb(*data, 1, *length, handle) != *length)
2374 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2375 	}
2376 
2377 	(*data)[*length] = '\0';
2378 
2379 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2380 }
2381 
read_metadata_block_data_picture_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_Picture * block)2382 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block)
2383 {
2384 	FLAC__Metadata_SimpleIteratorStatus status;
2385 	FLAC__byte buffer[4]; /* asserted below that this is big enough */
2386 	FLAC__uint32 len;
2387 
2388 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2389 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2390 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2391 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2392 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2393 
2394 	FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_TYPE_LEN % 8 == 0);
2395 	len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN / 8;
2396 	if(read_cb(buffer, 1, len, handle) != len)
2397 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2398 	block->type = (FLAC__StreamMetadata_Picture_Type)unpack_uint32_(buffer, len);
2399 
2400 	if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, (FLAC__byte**)(&(block->mime_type)), &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2401 		return status;
2402 
2403 	if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->description), &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2404 		return status;
2405 
2406 	FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN % 8 == 0);
2407 	len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN / 8;
2408 	if(read_cb(buffer, 1, len, handle) != len)
2409 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2410 	block->width = unpack_uint32_(buffer, len);
2411 
2412 	FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN % 8 == 0);
2413 	len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN / 8;
2414 	if(read_cb(buffer, 1, len, handle) != len)
2415 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2416 	block->height = unpack_uint32_(buffer, len);
2417 
2418 	FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN % 8 == 0);
2419 	len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN / 8;
2420 	if(read_cb(buffer, 1, len, handle) != len)
2421 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2422 	block->depth = unpack_uint32_(buffer, len);
2423 
2424 	FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_COLORS_LEN % 8 == 0);
2425 	len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN / 8;
2426 	if(read_cb(buffer, 1, len, handle) != len)
2427 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2428 	block->colors = unpack_uint32_(buffer, len);
2429 
2430 	/* for convenience we use read_metadata_block_data_picture_cstring_cb_() even though it adds an extra terminating NUL we don't use */
2431 	if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->data), &(block->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2432 		return status;
2433 
2434 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2435 }
2436 
read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__StreamMetadata_Unknown * block,unsigned block_length)2437 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2438 {
2439 	if(block_length == 0) {
2440 		block->data = 0;
2441 	}
2442 	else {
2443 		if(0 == (block->data = malloc(block_length)))
2444 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2445 
2446 		if(read_cb(block->data, 1, block_length, handle) != block_length)
2447 			return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2448 	}
2449 
2450 	return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2451 }
2452 
write_metadata_block_header_(FILE * file,FLAC__Metadata_SimpleIteratorStatus * status,const FLAC__StreamMetadata * block)2453 FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2454 {
2455 	FLAC__ASSERT(0 != file);
2456 	FLAC__ASSERT(0 != status);
2457 
2458 	if(!write_metadata_block_header_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2459 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2460 		return false;
2461 	}
2462 
2463 	return true;
2464 }
2465 
write_metadata_block_data_(FILE * file,FLAC__Metadata_SimpleIteratorStatus * status,const FLAC__StreamMetadata * block)2466 FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2467 {
2468 	FLAC__ASSERT(0 != file);
2469 	FLAC__ASSERT(0 != status);
2470 
2471 	if (write_metadata_block_data_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2472 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2473 		return true;
2474 	}
2475 	else {
2476 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2477 		return false;
2478 	}
2479 }
2480 
write_metadata_block_header_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata * block)2481 FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2482 {
2483 	FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
2484 
2485 	FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
2486 
2487 	buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
2488 	pack_uint32_(block->length, buffer + 1, 3);
2489 
2490 	if(write_cb(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2491 		return false;
2492 
2493 	return true;
2494 }
2495 
write_metadata_block_data_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata * block)2496 FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2497 {
2498 	FLAC__ASSERT(0 != block);
2499 
2500 	switch(block->type) {
2501 		case FLAC__METADATA_TYPE_STREAMINFO:
2502 			return write_metadata_block_data_streaminfo_cb_(handle, write_cb, &block->data.stream_info);
2503 		case FLAC__METADATA_TYPE_PADDING:
2504 			return write_metadata_block_data_padding_cb_(handle, write_cb, &block->data.padding, block->length);
2505 		case FLAC__METADATA_TYPE_APPLICATION:
2506 			return write_metadata_block_data_application_cb_(handle, write_cb, &block->data.application, block->length);
2507 		case FLAC__METADATA_TYPE_SEEKTABLE:
2508 			return write_metadata_block_data_seektable_cb_(handle, write_cb, &block->data.seek_table);
2509 		case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2510 			return write_metadata_block_data_vorbis_comment_cb_(handle, write_cb, &block->data.vorbis_comment);
2511 		case FLAC__METADATA_TYPE_CUESHEET:
2512 			return write_metadata_block_data_cuesheet_cb_(handle, write_cb, &block->data.cue_sheet);
2513 		case FLAC__METADATA_TYPE_PICTURE:
2514 			return write_metadata_block_data_picture_cb_(handle, write_cb, &block->data.picture);
2515 		default:
2516 			return write_metadata_block_data_unknown_cb_(handle, write_cb, &block->data.unknown, block->length);
2517 	}
2518 }
2519 
write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_StreamInfo * block)2520 FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block)
2521 {
2522 	FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
2523 	const unsigned channels1 = block->channels - 1;
2524 	const unsigned bps1 = block->bits_per_sample - 1;
2525 
2526 	/* we are using hardcoded numbers for simplicity but we should
2527 	 * probably eventually write a bit-level packer and use the
2528 	 * _STREAMINFO_ constants.
2529 	 */
2530 	pack_uint32_(block->min_blocksize, buffer, 2);
2531 	pack_uint32_(block->max_blocksize, buffer+2, 2);
2532 	pack_uint32_(block->min_framesize, buffer+4, 3);
2533 	pack_uint32_(block->max_framesize, buffer+7, 3);
2534 	buffer[10] = (block->sample_rate >> 12) & 0xff;
2535 	buffer[11] = (block->sample_rate >> 4) & 0xff;
2536 	buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
2537 	buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
2538 	pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
2539 	memcpy(buffer+18, block->md5sum, 16);
2540 
2541 	if(write_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2542 		return false;
2543 
2544 	return true;
2545 }
2546 
write_metadata_block_data_padding_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_Padding * block,unsigned block_length)2547 FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
2548 {
2549 	unsigned i, n = block_length;
2550 	FLAC__byte buffer[1024];
2551 
2552 	(void)block;
2553 
2554 	memset(buffer, 0, 1024);
2555 
2556 	for(i = 0; i < n/1024; i++)
2557 		if(write_cb(buffer, 1, 1024, handle) != 1024)
2558 			return false;
2559 
2560 	n %= 1024;
2561 
2562 	if(write_cb(buffer, 1, n, handle) != n)
2563 		return false;
2564 
2565 	return true;
2566 }
2567 
write_metadata_block_data_application_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_Application * block,unsigned block_length)2568 FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length)
2569 {
2570 	const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2571 
2572 	if(write_cb(block->id, 1, id_bytes, handle) != id_bytes)
2573 		return false;
2574 
2575 	block_length -= id_bytes;
2576 
2577 	if(write_cb(block->data, 1, block_length, handle) != block_length)
2578 		return false;
2579 
2580 	return true;
2581 }
2582 
write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_SeekTable * block)2583 FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block)
2584 {
2585 	unsigned i;
2586 	FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2587 
2588 	for(i = 0; i < block->num_points; i++) {
2589 		/* some MAGIC NUMBERs here */
2590 		pack_uint64_(block->points[i].sample_number, buffer, 8);
2591 		pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
2592 		pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
2593 		if(write_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2594 			return false;
2595 	}
2596 
2597 	return true;
2598 }
2599 
write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_VorbisComment * block)2600 FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block)
2601 {
2602 	unsigned i;
2603 	const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2604 	const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2605 	FLAC__byte buffer[4]; /* magic number is asserted below */
2606 
2607 	FLAC__ASSERT(MAX(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == sizeof(buffer));
2608 
2609 	pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
2610 	if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2611 		return false;
2612 	if(write_cb(block->vendor_string.entry, 1, block->vendor_string.length, handle) != block->vendor_string.length)
2613 		return false;
2614 
2615 	pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
2616 	if(write_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2617 		return false;
2618 
2619 	for(i = 0; i < block->num_comments; i++) {
2620 		pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
2621 		if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2622 			return false;
2623 		if(write_cb(block->comments[i].entry, 1, block->comments[i].length, handle) != block->comments[i].length)
2624 			return false;
2625 	}
2626 
2627 	return true;
2628 }
2629 
write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_CueSheet * block)2630 FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block)
2631 {
2632 	unsigned i, j, len;
2633 	FLAC__byte buffer[1024]; /* asserted below that this is big enough */
2634 
2635 	FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2636 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN/8);
2637 	FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)/8);
2638 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2639 
2640 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2641 	len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2642 	if(write_cb(block->media_catalog_number, 1, len, handle) != len)
2643 		return false;
2644 
2645 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2646 	len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2647 	pack_uint64_(block->lead_in, buffer, len);
2648 	if(write_cb(buffer, 1, len, handle) != len)
2649 		return false;
2650 
2651 	FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2652 	len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2653 	memset(buffer, 0, len);
2654 	if(block->is_cd)
2655 		buffer[0] |= 0x80;
2656 	if(write_cb(buffer, 1, len, handle) != len)
2657 		return false;
2658 
2659 	FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2660 	len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2661 	pack_uint32_(block->num_tracks, buffer, len);
2662 	if(write_cb(buffer, 1, len, handle) != len)
2663 		return false;
2664 
2665 	for(i = 0; i < block->num_tracks; i++) {
2666 		FLAC__StreamMetadata_CueSheet_Track *track = block->tracks + i;
2667 
2668 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2669 		len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2670 		pack_uint64_(track->offset, buffer, len);
2671 		if(write_cb(buffer, 1, len, handle) != len)
2672 			return false;
2673 
2674 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2675 		len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2676 		pack_uint32_(track->number, buffer, len);
2677 		if(write_cb(buffer, 1, len, handle) != len)
2678 			return false;
2679 
2680 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2681 		len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2682 		if(write_cb(track->isrc, 1, len, handle) != len)
2683 			return false;
2684 
2685 		FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2686 		len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2687 		memset(buffer, 0, len);
2688 		buffer[0] = (track->type << 7) | (track->pre_emphasis << 6);
2689 		if(write_cb(buffer, 1, len, handle) != len)
2690 			return false;
2691 
2692 		FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2693 		len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2694 		pack_uint32_(track->num_indices, buffer, len);
2695 		if(write_cb(buffer, 1, len, handle) != len)
2696 			return false;
2697 
2698 		for(j = 0; j < track->num_indices; j++) {
2699 			FLAC__StreamMetadata_CueSheet_Index *indx = track->indices + j;
2700 
2701 			FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2702 			len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2703 			pack_uint64_(indx->offset, buffer, len);
2704 			if(write_cb(buffer, 1, len, handle) != len)
2705 				return false;
2706 
2707 			FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2708 			len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2709 			pack_uint32_(indx->number, buffer, len);
2710 			if(write_cb(buffer, 1, len, handle) != len)
2711 				return false;
2712 
2713 			FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2714 			len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2715 			memset(buffer, 0, len);
2716 			if(write_cb(buffer, 1, len, handle) != len)
2717 				return false;
2718 		}
2719 	}
2720 
2721 	return true;
2722 }
2723 
write_metadata_block_data_picture_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_Picture * block)2724 FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block)
2725 {
2726 	unsigned len;
2727 	size_t slen;
2728 	FLAC__byte buffer[4]; /* magic number is asserted below */
2729 
2730 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_TYPE_LEN%8);
2731 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN%8);
2732 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN%8);
2733 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN%8);
2734 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN%8);
2735 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN%8);
2736 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_COLORS_LEN%8);
2737 	FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN%8);
2738 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2739 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8);
2740 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8);
2741 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2742 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2743 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2744 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2745 	FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8);
2746 
2747 	len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8;
2748 	pack_uint32_(block->type, buffer, len);
2749 	if(write_cb(buffer, 1, len, handle) != len)
2750 		return false;
2751 
2752 	len = FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8;
2753 	slen = strlen(block->mime_type);
2754 	pack_uint32_(slen, buffer, len);
2755 	if(write_cb(buffer, 1, len, handle) != len)
2756 		return false;
2757 	if(write_cb(block->mime_type, 1, slen, handle) != slen)
2758 		return false;
2759 
2760 	len = FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8;
2761 	slen = strlen((const char *)block->description);
2762 	pack_uint32_(slen, buffer, len);
2763 	if(write_cb(buffer, 1, len, handle) != len)
2764 		return false;
2765 	if(write_cb(block->description, 1, slen, handle) != slen)
2766 		return false;
2767 
2768 	len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8;
2769 	pack_uint32_(block->width, buffer, len);
2770 	if(write_cb(buffer, 1, len, handle) != len)
2771 		return false;
2772 
2773 	len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8;
2774 	pack_uint32_(block->height, buffer, len);
2775 	if(write_cb(buffer, 1, len, handle) != len)
2776 		return false;
2777 
2778 	len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8;
2779 	pack_uint32_(block->depth, buffer, len);
2780 	if(write_cb(buffer, 1, len, handle) != len)
2781 		return false;
2782 
2783 	len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8;
2784 	pack_uint32_(block->colors, buffer, len);
2785 	if(write_cb(buffer, 1, len, handle) != len)
2786 		return false;
2787 
2788 	len = FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8;
2789 	pack_uint32_(block->data_length, buffer, len);
2790 	if(write_cb(buffer, 1, len, handle) != len)
2791 		return false;
2792 	if(write_cb(block->data, 1, block->data_length, handle) != block->data_length)
2793 		return false;
2794 
2795 	return true;
2796 }
2797 
write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Write write_cb,const FLAC__StreamMetadata_Unknown * block,unsigned block_length)2798 FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2799 {
2800 	if(write_cb(block->data, 1, block_length, handle) != block_length)
2801 		return false;
2802 
2803 	return true;
2804 }
2805 
write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator * iterator,const FLAC__StreamMetadata * block)2806 FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
2807 {
2808 	if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2809 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2810 		return false;
2811 	}
2812 
2813 	if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2814 		return false;
2815 
2816 	if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2817 		return false;
2818 
2819 	if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2820 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2821 		return false;
2822 	}
2823 
2824 	return read_metadata_block_header_(iterator);
2825 }
2826 
write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator * iterator,FLAC__StreamMetadata * block,unsigned padding_length,FLAC__bool padding_is_last)2827 FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
2828 {
2829 	FLAC__StreamMetadata *padding;
2830 
2831 	if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2832 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2833 		return false;
2834 	}
2835 
2836 	block->is_last = false;
2837 
2838 	if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2839 		return false;
2840 
2841 	if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2842 		return false;
2843 
2844 	if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
2845 		return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2846 
2847 	padding->is_last = padding_is_last;
2848 	padding->length = padding_length;
2849 
2850 	if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
2851 		FLAC__metadata_object_delete(padding);
2852 		return false;
2853 	}
2854 
2855 	if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
2856 		FLAC__metadata_object_delete(padding);
2857 		return false;
2858 	}
2859 
2860 	FLAC__metadata_object_delete(padding);
2861 
2862 	if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2863 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2864 		return false;
2865 	}
2866 
2867 	return read_metadata_block_header_(iterator);
2868 }
2869 
rewrite_whole_file_(FLAC__Metadata_SimpleIterator * iterator,FLAC__StreamMetadata * block,FLAC__bool append)2870 FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
2871 {
2872 	FILE *tempfile = NULL;
2873 	char *tempfilename = NULL;
2874 	int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
2875 	FLAC__off_t fixup_is_last_flag_offset = -1;
2876 
2877 	FLAC__ASSERT(0 != block || append == false);
2878 
2879 	if(iterator->is_last) {
2880 		if(append) {
2881 			fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
2882 			fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2883 		}
2884 		else if(0 == block) {
2885 			simple_iterator_push_(iterator);
2886 			if(!FLAC__metadata_simple_iterator_prev(iterator)) {
2887 				(void)simple_iterator_pop_(iterator);
2888 				return false;
2889 			}
2890 			fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
2891 			fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2892 			if(!simple_iterator_pop_(iterator))
2893 				return false;
2894 		}
2895 	}
2896 
2897 	if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
2898 		return false;
2899 
2900 	if(0 != block) {
2901 		if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
2902 			cleanup_tempfile_(&tempfile, &tempfilename);
2903 			return false;
2904 		}
2905 
2906 		if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
2907 			cleanup_tempfile_(&tempfile, &tempfilename);
2908 			return false;
2909 		}
2910 	}
2911 
2912 	if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
2913 		return false;
2914 
2915 	if(append)
2916 		return FLAC__metadata_simple_iterator_next(iterator);
2917 
2918 	return true;
2919 }
2920 
simple_iterator_push_(FLAC__Metadata_SimpleIterator * iterator)2921 void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
2922 {
2923 	FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
2924 	iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
2925 	iterator->depth++;
2926 }
2927 
simple_iterator_pop_(FLAC__Metadata_SimpleIterator * iterator)2928 FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
2929 {
2930 	FLAC__ASSERT(iterator->depth > 0);
2931 	iterator->depth--;
2932 	if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2933 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2934 		return false;
2935 	}
2936 
2937 	return read_metadata_block_header_(iterator);
2938 }
2939 
2940 /* return meanings:
2941  * 0: ok
2942  * 1: read error
2943  * 2: seek error
2944  * 3: not a FLAC file
2945  */
seek_to_first_metadata_block_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOCallback_Seek seek_cb)2946 unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb)
2947 {
2948 	FLAC__byte buffer[4];
2949 	size_t n;
2950 	unsigned i;
2951 
2952 	FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == sizeof(buffer));
2953 
2954 	/* skip any id3v2 tag */
2955 	errno = 0;
2956 	n = read_cb(buffer, 1, 4, handle);
2957 	if(errno)
2958 		return 1;
2959 	else if(n != 4)
2960 		return 3;
2961 	else if(0 == memcmp(buffer, "ID3", 3)) {
2962 		unsigned tag_length = 0;
2963 
2964 		/* skip to the tag length */
2965 		if(seek_cb(handle, 2, SEEK_CUR) < 0)
2966 			return 2;
2967 
2968 		/* read the length */
2969 		for(i = 0; i < 4; i++) {
2970 			if(read_cb(buffer, 1, 1, handle) < 1 || buffer[0] & 0x80)
2971 				return 1;
2972 			tag_length <<= 7;
2973 			tag_length |= (buffer[0] & 0x7f);
2974 		}
2975 
2976 		/* skip the rest of the tag */
2977 		if(seek_cb(handle, tag_length, SEEK_CUR) < 0)
2978 			return 2;
2979 
2980 		/* read the stream sync code */
2981 		errno = 0;
2982 		n = read_cb(buffer, 1, 4, handle);
2983 		if(errno)
2984 			return 1;
2985 		else if(n != 4)
2986 			return 3;
2987 	}
2988 
2989 	/* check for the fLaC signature */
2990 	if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
2991 		return 0;
2992 	else
2993 		return 3;
2994 }
2995 
seek_to_first_metadata_block_(FILE * f)2996 unsigned seek_to_first_metadata_block_(FILE *f)
2997 {
2998 	return seek_to_first_metadata_block_cb_((FLAC__IOHandle)f, (FLAC__IOCallback_Read)fread, fseek_wrapper_);
2999 }
3000 
simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator * iterator,FILE ** tempfile,char ** tempfilename,FLAC__bool append)3001 FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
3002 {
3003 	const FLAC__off_t offset_end = append? iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length : iterator->offset[iterator->depth];
3004 
3005 	if(0 != fseeko(iterator->file, 0, SEEK_SET)) {
3006 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3007 		return false;
3008 	}
3009 	if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
3010 		cleanup_tempfile_(tempfile, tempfilename);
3011 		return false;
3012 	}
3013 	if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
3014 		cleanup_tempfile_(tempfile, tempfilename);
3015 		return false;
3016 	}
3017 
3018 	return true;
3019 }
3020 
simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator * iterator,FILE ** tempfile,char ** tempfilename,int fixup_is_last_code,FLAC__off_t fixup_is_last_flag_offset,FLAC__bool backup)3021 FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, FLAC__off_t fixup_is_last_flag_offset, FLAC__bool backup)
3022 {
3023 	FLAC__off_t save_offset = iterator->offset[iterator->depth];
3024 	FLAC__ASSERT(0 != *tempfile);
3025 
3026 	if(0 != fseeko(iterator->file, save_offset + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length, SEEK_SET)) {
3027 		cleanup_tempfile_(tempfile, tempfilename);
3028 		iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3029 		return false;
3030 	}
3031 	if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
3032 		cleanup_tempfile_(tempfile, tempfilename);
3033 		return false;
3034 	}
3035 
3036 	if(fixup_is_last_code != 0) {
3037 		/*
3038 		 * if code == 1, it means a block was appended to the end so
3039 		 *   we have to clear the is_last flag of the previous block
3040 		 * if code == -1, it means the last block was deleted so
3041 		 *   we have to set the is_last flag of the previous block
3042 		 */
3043 		/* MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
3044 		FLAC__byte x;
3045 		if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3046 			cleanup_tempfile_(tempfile, tempfilename);
3047 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3048 			return false;
3049 		}
3050 		if(fread(&x, 1, 1, *tempfile) != 1) {
3051 			cleanup_tempfile_(tempfile, tempfilename);
3052 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3053 			return false;
3054 		}
3055 		if(fixup_is_last_code > 0) {
3056 			FLAC__ASSERT(x & 0x80);
3057 			x &= 0x7f;
3058 		}
3059 		else {
3060 			FLAC__ASSERT(!(x & 0x80));
3061 			x |= 0x80;
3062 		}
3063 		if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3064 			cleanup_tempfile_(tempfile, tempfilename);
3065 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3066 			return false;
3067 		}
3068 		if(local__fwrite(&x, 1, 1, *tempfile) != 1) {
3069 			cleanup_tempfile_(tempfile, tempfilename);
3070 			iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3071 			return false;
3072 		}
3073 	}
3074 
3075 	(void)fclose(iterator->file);
3076 
3077 	if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
3078 		return false;
3079 
3080 	if(iterator->has_stats)
3081 		set_file_stats_(iterator->filename, &iterator->stats);
3082 
3083 	if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
3084 		return false;
3085 	if(backup) {
3086 		while(iterator->offset[iterator->depth] + (FLAC__off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (FLAC__off_t)iterator->length < save_offset)
3087 			if(!FLAC__metadata_simple_iterator_next(iterator))
3088 				return false;
3089 		return true;
3090 	}
3091 	else {
3092 		/* move the iterator to it's original block faster by faking a push, then doing a pop_ */
3093 		FLAC__ASSERT(iterator->depth == 0);
3094 		iterator->offset[0] = save_offset;
3095 		iterator->depth++;
3096 		return simple_iterator_pop_(iterator);
3097 	}
3098 }
3099 
copy_n_bytes_from_file_(FILE * file,FILE * tempfile,FLAC__off_t bytes,FLAC__Metadata_SimpleIteratorStatus * status)3100 FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3101 {
3102 	FLAC__byte buffer[8192];
3103 	size_t n;
3104 
3105 	FLAC__ASSERT(bytes >= 0);
3106 	while(bytes > 0) {
3107 		n = MIN(sizeof(buffer), (size_t)bytes);
3108 		if(fread(buffer, 1, n, file) != n) {
3109 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3110 			return false;
3111 		}
3112 		if(local__fwrite(buffer, 1, n, tempfile) != n) {
3113 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3114 			return false;
3115 		}
3116 		bytes -= n;
3117 	}
3118 
3119 	return true;
3120 }
3121 
copy_n_bytes_from_file_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOHandle temp_handle,FLAC__IOCallback_Write temp_write_cb,FLAC__off_t bytes,FLAC__Metadata_SimpleIteratorStatus * status)3122 FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3123 {
3124 	FLAC__byte buffer[8192];
3125 	size_t n;
3126 
3127 	FLAC__ASSERT(bytes >= 0);
3128 	while(bytes > 0) {
3129 		n = MIN(sizeof(buffer), (size_t)bytes);
3130 		if(read_cb(buffer, 1, n, handle) != n) {
3131 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3132 			return false;
3133 		}
3134 		if(temp_write_cb(buffer, 1, n, temp_handle) != n) {
3135 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3136 			return false;
3137 		}
3138 		bytes -= n;
3139 	}
3140 
3141 	return true;
3142 }
3143 
copy_remaining_bytes_from_file_(FILE * file,FILE * tempfile,FLAC__Metadata_SimpleIteratorStatus * status)3144 FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
3145 {
3146 	FLAC__byte buffer[8192];
3147 	size_t n;
3148 
3149 	while(!feof(file)) {
3150 		n = fread(buffer, 1, sizeof(buffer), file);
3151 		if(n == 0 && !feof(file)) {
3152 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3153 			return false;
3154 		}
3155 		if(n > 0 && local__fwrite(buffer, 1, n, tempfile) != n) {
3156 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3157 			return false;
3158 		}
3159 	}
3160 
3161 	return true;
3162 }
3163 
copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle,FLAC__IOCallback_Read read_cb,FLAC__IOCallback_Eof eof_cb,FLAC__IOHandle temp_handle,FLAC__IOCallback_Write temp_write_cb,FLAC__Metadata_SimpleIteratorStatus * status)3164 FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status)
3165 {
3166 	FLAC__byte buffer[8192];
3167 	size_t n;
3168 
3169 	while(!eof_cb(handle)) {
3170 		n = read_cb(buffer, 1, sizeof(buffer), handle);
3171 		if(n == 0 && !eof_cb(handle)) {
3172 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3173 			return false;
3174 		}
3175 		if(n > 0 && temp_write_cb(buffer, 1, n, temp_handle) != n) {
3176 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3177 			return false;
3178 		}
3179 	}
3180 
3181 	return true;
3182 }
3183 
3184 static int
local_snprintf(char * str,size_t size,const char * fmt,...)3185 local_snprintf(char *str, size_t size, const char *fmt, ...)
3186 {
3187 	va_list va;
3188 	int rc ;
3189 
3190 	va_start (va, fmt);
3191 
3192 #ifdef _MSC_VER
3193 	rc = vsnprintf_s (str, size, _TRUNCATE, fmt, va);
3194 	rc = (rc > 0) ? rc : (size == 0 ? 1024 : size * 2);
3195 #else
3196 	rc = vsnprintf (str, size, fmt, va);
3197 #endif
3198 	va_end (va);
3199 
3200 	return rc;
3201 }
3202 
open_tempfile_(const char * filename,const char * tempfile_path_prefix,FILE ** tempfile,char ** tempfilename,FLAC__Metadata_SimpleIteratorStatus * status)3203 FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3204 {
3205 	static const char *tempfile_suffix = ".metadata_edit";
3206 	if(0 == tempfile_path_prefix) {
3207 		size_t dest_len = strlen(filename) + strlen(tempfile_suffix) + 1;
3208 		if(0 == (*tempfilename = safe_malloc_(dest_len))) {
3209 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3210 			return false;
3211 		}
3212 		local_snprintf(*tempfilename, dest_len, "%s%s", filename, tempfile_suffix);
3213 	}
3214 	else {
3215 		const char *p = strrchr(filename, '/');
3216 		size_t dest_len;
3217 		if(0 == p)
3218 			p = filename;
3219 		else
3220 			p++;
3221 
3222 		dest_len = strlen(tempfile_path_prefix) + strlen(p) + strlen(tempfile_suffix) + 2;
3223 
3224 		if(0 == (*tempfilename = safe_malloc_(dest_len))) {
3225 			*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3226 			return false;
3227 		}
3228 		local_snprintf(*tempfilename, dest_len, "%s/%s%s", tempfile_path_prefix, p, tempfile_suffix);
3229 	}
3230 
3231 	if(0 == (*tempfile = flac_fopen(*tempfilename, "w+b"))) {
3232 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
3233 		return false;
3234 	}
3235 
3236 	return true;
3237 }
3238 
transport_tempfile_(const char * filename,FILE ** tempfile,char ** tempfilename,FLAC__Metadata_SimpleIteratorStatus * status)3239 FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3240 {
3241 	FLAC__ASSERT(0 != filename);
3242 	FLAC__ASSERT(0 != tempfile);
3243 	FLAC__ASSERT(0 != *tempfile);
3244 	FLAC__ASSERT(0 != tempfilename);
3245 	FLAC__ASSERT(0 != *tempfilename);
3246 	FLAC__ASSERT(0 != status);
3247 
3248 	(void)fclose(*tempfile);
3249 	*tempfile = 0;
3250 
3251 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__
3252 	/* on some flavors of windows, flac_rename() will fail if the destination already exists */
3253 	if(flac_unlink(filename) < 0) {
3254 		cleanup_tempfile_(tempfile, tempfilename);
3255 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
3256 		return false;
3257 	}
3258 #endif
3259 
3260 	/*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just flac_rename(): */
3261 	if(0 != flac_rename(*tempfilename, filename)) {
3262 		cleanup_tempfile_(tempfile, tempfilename);
3263 		*status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
3264 		return false;
3265 	}
3266 
3267 	cleanup_tempfile_(tempfile, tempfilename);
3268 
3269 	return true;
3270 }
3271 
cleanup_tempfile_(FILE ** tempfile,char ** tempfilename)3272 void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
3273 {
3274 	if(0 != *tempfile) {
3275 		(void)fclose(*tempfile);
3276 		*tempfile = 0;
3277 	}
3278 
3279 	if(0 != *tempfilename) {
3280 		(void)flac_unlink(*tempfilename);
3281 		free(*tempfilename);
3282 		*tempfilename = 0;
3283 	}
3284 }
3285 
get_file_stats_(const char * filename,struct flac_stat_s * stats)3286 FLAC__bool get_file_stats_(const char *filename, struct flac_stat_s *stats)
3287 {
3288 	FLAC__ASSERT(0 != filename);
3289 	FLAC__ASSERT(0 != stats);
3290 	return (0 == flac_stat(filename, stats));
3291 }
3292 
set_file_stats_(const char * filename,struct flac_stat_s * stats)3293 void set_file_stats_(const char *filename, struct flac_stat_s *stats)
3294 {
3295 	struct utimbuf srctime;
3296 
3297 	FLAC__ASSERT(0 != filename);
3298 	FLAC__ASSERT(0 != stats);
3299 
3300 	srctime.actime = stats->st_atime;
3301 	srctime.modtime = stats->st_mtime;
3302 	(void)flac_chmod(filename, stats->st_mode);
3303 	(void)flac_utime(filename, &srctime);
3304 #if !defined _MSC_VER && !defined __BORLANDC__ && !defined __MINGW32__
3305 	FLAC_CHECK_RETURN(chown(filename, stats->st_uid, -1));
3306 	FLAC_CHECK_RETURN(chown(filename, -1, stats->st_gid));
3307 #endif
3308 }
3309 
fseek_wrapper_(FLAC__IOHandle handle,FLAC__int64 offset,int whence)3310 int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence)
3311 {
3312 	return fseeko((FILE*)handle, (FLAC__off_t)offset, whence);
3313 }
3314 
ftell_wrapper_(FLAC__IOHandle handle)3315 FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle)
3316 {
3317 	return ftello((FILE*)handle);
3318 }
3319 
get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)3320 FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
3321 {
3322 	switch(status) {
3323 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
3324 			return FLAC__METADATA_CHAIN_STATUS_OK;
3325 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
3326 			return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
3327 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
3328 			return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
3329 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
3330 			return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
3331 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
3332 			return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
3333 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
3334 			return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
3335 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
3336 			return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
3337 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
3338 			return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
3339 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
3340 			return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
3341 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
3342 			return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
3343 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
3344 			return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
3345 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
3346 			return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
3347 		case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
3348 		default:
3349 			return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
3350 	}
3351 }
3352