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