Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
283 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/SConscript b/SConscript
index 47c63732..e0a149b5 100644
--- a/SConscript
+++ b/SConscript
@@ -1,120 +1,120 @@
import os
import sys
Import('root')
sys.path.append(Dir('.').rel_path(Dir("#%s" % root)))
import scons_rtech1.utils
import scons_rtech1.checks
Import('env')
Import('build_dir_root')
build_type = 'release'
if scons_rtech1.utils.useAndroid():
build_type = 'armeabi-v7a'
if scons_rtech1.utils.useAndroidX64():
build_type = 'android-x64'
config = env.Configure(custom_tests = {'CheckAllegro5': scons_rtech1.checks.checkAllegro5(scons_rtech1.checks.debug()),
'CheckFreetype': scons_rtech1.checks.checkFreetype,
'ConfigChecks': scons_rtech1.checks.configChecks})
if scons_rtech1.utils.useAndroidX64():
env['HAVE_ALLEGRO5'] = True
env.Append(CPPDEFINES = ['USE_ALLEGRO5'])
else:
config.CheckAllegro5()
config.CheckFreetype()
config.ConfigChecks()
env = config.Finish()
if not env['HAVE_ALLEGRO5']:
Exit(1)
if scons_rtech1.checks.debug():
- env.Append(CXXFLAGS = ['-g3','-ggdb', '-Werror'])
+ env.Append(CXXFLAGS = ['-g3','-ggdb'])
build_dir = '%s/%s' % (build_dir_root, build_type if not scons_rtech1.checks.debug() else 'debug')
options = {'networking': False,
'allegro5': True
}
def getLibName():
if scons_rtech1.utils.useAndroid():
return 'lib/r-tech1-arm'
if scons_rtech1.checks.debug():
return 'lib/r-tech1-debug'
return 'lib/r-tech1'
libname = getLibName()
env.Append(CPPPATH = [Dir('include', Dir('.').rel_path(Dir('#' + root)))])
env.VariantDir(build_dir, 'src')
libs = env.SConscript('src/SConscript', variant_dir=build_dir, exports=['env', 'options', 'root'])
rtech1 = env.StaticLibrary(libname, libs)
Alias('rtech1', rtech1)
tests_build_dir = os.path.join(build_dir, 'tests')
unit_tests = []
if not scons_rtech1.utils.useAndroid():
unit_tests = SConscript('tests/SConscript', variant_dir = tests_build_dir, exports = ['env', 'rtech1', 'root'], duplicate=0)
env.Depends(unit_tests, rtech1)
if os.access(env.installPrefix, os.W_OK):
installEnv = env.Clone(tools = ['textfile'])
# Install target and configuration
installEnv.Install('{0}/lib'.format(installEnv.installPrefix), rtech1)
header_prefix = '{0}/include/r-tech1'.format(installEnv.installPrefix)
include_dir = 'include/r-tech1'
for root, dirs, files in os.walk(include_dir):
for file in files:
installEnv.Install(header_prefix + root[len(include_dir):], os.path.join(root, file))
installEnv.Install(os.path.join(header_prefix, 'lz4'), 'src/libs/lz4/lz4.h')
# pkg-config file create
pc_mod, pc_install = scons_rtech1.utils.pc_install(installEnv, build_dir, scons_rtech1.checks.debug())
# Install pkg-config file
installEnv.Alias('install', [installEnv.installPrefix, pc_install])
installEnv.Depends([installEnv.installPrefix, pc_mod], rtech1)
# Uninstall target
installEnv.Command("uninstall", None, Delete(FindInstalledFiles()))
else:
def needsudo(target, source, env):
print 'No write priveleges to {0}, run target [{1}] as sudo'.format(env.installPrefix, target[0])
env.Command('install', None, needsudo)
env.Depends('install', ['rtech1', 'tests'])
env.Command('uninstall', None, needsudo)
env.Depends('uninstall', ['rtech1', 'tests'])
include_dir = 'include/r-tech1'
root_dir = Dir('include/r-tech1', Dir('#%s' % root)).abspath
for myroot, dirs, files in os.walk(root_dir):
for file in files:
source = os.path.join(myroot, file)
dir = myroot[len(root_dir) + 1:]
destination = Dir(dir, Dir('headers/r-tech1', Dir(build_dir))).abspath
env['RTECH1_HEADERS'] = [Dir('include', Dir('.').rel_path(Dir('#%s' % root))).abspath]
# Unit tests
env.Alias('tests', unit_tests)
for test in unit_tests:
orig = str(test).translate(None,'[]\'')
to = orig.replace('{0}/tests/'.format(build_dir), '')
#print orig, to
copy = Command('bin/{0}'.format(to), orig, Copy('$TARGET', '$SOURCE'))
env.Depends(copy, test)
env.AlwaysBuild(copy)
env.Alias('tests', copy, copy[0].abspath)
Return('rtech1')
diff --git a/src/libs/dumb/include/dumb.h b/src/libs/dumb/include/dumb.h
index 2fee9a8f..c4833c79 100644
--- a/src/libs/dumb/include/dumb.h
+++ b/src/libs/dumb/include/dumb.h
@@ -1,687 +1,687 @@
/* _______ ____ __ ___ ___
* \ _ \ \ / \ / \ \ / / ' ' '
* | | \ \ | | || | \/ | . .
* | | | | | | || ||\ /| |
* | | | | | | || || \/ | | ' ' '
* | | | | | | || || | | . .
* | |_/ / \ \__// || | |
* /_______/ynamic \____/niversal /__\ /____\usic /| . . ibliotheque
* / \
* / . \
* dumb.h - The user header file for DUMB. / / \ \
* | < / \_
* Include this file in any of your files in | \/ /\ /
* which you wish to use the DUMB functions \_ / > /
* and variables. | \ / /
* | ' /
* Allegro users, you will probably want aldumb.h. \__/
*/
#ifndef DUMB_H
#define DUMB_H
#include <stdlib.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
#define DUMB_MAJOR_VERSION 0
#define DUMB_MINOR_VERSION 9
#define DUMB_REVISION_VERSION 3
#define DUMB_VERSION (DUMB_MAJOR_VERSION*10000 + DUMB_MINOR_VERSION*100 + DUMB_REVISION_VERSION)
#define DUMB_VERSION_STR "0.9.3"
-#define DUMB_NAME "DUMB v"DUMB_VERSION_STR
+#define DUMB_NAME "DUMB v" DUMB_VERSION_STR
#define DUMB_YEAR 2005
#define DUMB_MONTH 8
#define DUMB_DAY 7
#define DUMB_YEAR_STR2 "05"
#define DUMB_YEAR_STR4 "2005"
#define DUMB_MONTH_STR1 "8"
#define DUMB_DAY_STR1 "7"
#if DUMB_MONTH < 10
-#define DUMB_MONTH_STR2 "0"DUMB_MONTH_STR1
+#define DUMB_MONTH_STR2 "0" DUMB_MONTH_STR1
#else
#define DUMB_MONTH_STR2 DUMB_MONTH_STR1
#endif
#if DUMB_DAY < 10
-#define DUMB_DAY_STR2 "0"DUMB_DAY_STR1
+#define DUMB_DAY_STR2 "0" DUMB_DAY_STR1
#else
#define DUMB_DAY_STR2 DUMB_DAY_STR1
#endif
/* WARNING: The month and day were inadvertently swapped in the v0.8 release.
* Please do not compare this constant against any date in 2002. In
* any case, DUMB_VERSION is probably more useful for this purpose.
*/
#define DUMB_DATE (DUMB_YEAR*10000 + DUMB_MONTH*100 + DUMB_DAY)
-#define DUMB_DATE_STR DUMB_DAY_STR1"."DUMB_MONTH_STR1"."DUMB_YEAR_STR4
+#define DUMB_DATE_STR DUMB_DAY_STR1 "." DUMB_MONTH_STR1 "." DUMB_YEAR_STR4
#undef MIN
#undef MAX
#undef MID
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#define MID(x,y,z) MAX((x), MIN((y), (z)))
#undef ABS
#define ABS(x) (((x) >= 0) ? (x) : (-(x)))
#ifdef DEBUGMODE
#ifndef ASSERT
#include <assert.h>
#define ASSERT(n) assert(n)
#endif
#ifndef TRACE
// it would be nice if this did actually trace ...
#define TRACE 1 ? (void)0 : (void)printf
#endif
#else
#ifndef ASSERT
#define ASSERT(n)
#endif
#ifndef TRACE
#define TRACE 1 ? (void)0 : (void)printf
#endif
#endif
#define DUMB_ID(a,b,c,d) (((unsigned int)(a) << 24) | \
((unsigned int)(b) << 16) | \
((unsigned int)(c) << 8) | \
((unsigned int)(d) ))
#ifndef LONG_LONG
#if defined __GNUC__ || defined __INTEL_COMPILER || defined __MWERKS__
#define LONG_LONG long long
#elif defined _MSC_VER || defined __WATCOMC__
#define LONG_LONG __int64
#elif defined __sgi
#define LONG_LONG long long
#else
#error 64-bit integer type unknown
#endif
#endif
#if __GNUC__ * 100 + __GNUC_MINOR__ >= 301 /* GCC 3.1+ */
#ifndef DUMB_DECLARE_DEPRECATED
#define DUMB_DECLARE_DEPRECATED
#endif
#define DUMB_DEPRECATED __attribute__((__deprecated__))
#else
#define DUMB_DEPRECATED
#endif
/* Basic Sample Type. Normal range is -0x800000 to 0x7FFFFF. */
typedef int sample_t;
/* Library Clean-up Management */
int dumb_atexit(void (*proc)(void));
void dumb_exit(void);
/* File Input Functions */
typedef struct DUMBFILE_SYSTEM
{
void *(*open)(const char *filename);
int (*skip)(void *f, long n);
int (*getc)(void *f);
long (*getnc)(unsigned char *ptr, long n, void *f);
void (*close)(void *f);
}
DUMBFILE_SYSTEM;
typedef struct DUMBFILE DUMBFILE;
void register_dumbfile_system(DUMBFILE_SYSTEM *dfs);
DUMBFILE *dumbfile_open(const char *filename);
DUMBFILE *dumbfile_open_ex(void *file, DUMBFILE_SYSTEM *dfs);
long dumbfile_pos(DUMBFILE *f);
int dumbfile_skip(DUMBFILE *f, long n);
int dumbfile_getc(DUMBFILE *f);
int dumbfile_igetw(DUMBFILE *f);
int dumbfile_mgetw(DUMBFILE *f);
long dumbfile_igetl(DUMBFILE *f);
long dumbfile_mgetl(DUMBFILE *f);
unsigned long dumbfile_cgetul(DUMBFILE *f);
signed long dumbfile_cgetsl(DUMBFILE *f);
long dumbfile_getnc(unsigned char *ptr, long n, DUMBFILE *f);
int dumbfile_error(DUMBFILE *f);
int dumbfile_close(DUMBFILE *f);
/* stdio File Input Module */
void dumb_register_stdfiles(void);
DUMBFILE *dumbfile_open_stdfile(FILE *p);
/* Memory File Input Module */
DUMBFILE *dumbfile_open_memory(const char *data, long size);
/* DUH Management */
typedef struct DUH DUH;
#define DUH_SIGNATURE DUMB_ID('D','U','H','!')
void unload_duh(DUH *duh);
DUH *load_duh(const char *filename);
DUH *read_duh(DUMBFILE *f);
long duh_get_length(DUH *duh);
const char *duh_get_tag(DUH *duh, const char *key);
/* Signal Rendering Functions */
typedef struct DUH_SIGRENDERER DUH_SIGRENDERER;
DUH_SIGRENDERER *duh_start_sigrenderer(DUH *duh, int sig, int n_channels, long pos);
#ifdef DUMB_DECLARE_DEPRECATED
typedef void (*DUH_SIGRENDERER_CALLBACK)(void *data, sample_t **samples, int n_channels, long length);
/* This is deprecated, but is not marked as such because GCC tends to
* complain spuriously when the typedef is used later. See comments below.
*/
void duh_sigrenderer_set_callback(
DUH_SIGRENDERER *sigrenderer,
DUH_SIGRENDERER_CALLBACK callback, void *data
) DUMB_DEPRECATED;
/* The 'callback' argument's type has changed for const-correctness. See the
* DUH_SIGRENDERER_CALLBACK definition just above. Also note that the samples
* in the buffer are now 256 times as large; the normal range is -0x800000 to
* 0x7FFFFF. The function has been renamed partly because its functionality
* has changed slightly and partly so that its name is more meaningful. The
* new one is duh_sigrenderer_set_analyser_callback(), and the typedef for
* the function pointer has also changed, from DUH_SIGRENDERER_CALLBACK to
* DUH_SIGRENDERER_ANALYSER_CALLBACK. (If you wanted to use this callback to
* apply a DSP effect, don't worry; there is a better way of doing this. It
* is undocumented, so contact me and I shall try to help. Contact details
* are in readme.txt.)
*/
typedef void (*DUH_SIGRENDERER_ANALYSER_CALLBACK)(void *data, const sample_t *const *samples, int n_channels, long length);
/* This is deprecated, but is not marked as such because GCC tends to
* complain spuriously when the typedef is used later. See comments below.
*/
void duh_sigrenderer_set_analyser_callback(
DUH_SIGRENDERER *sigrenderer,
DUH_SIGRENDERER_ANALYSER_CALLBACK callback, void *data
) DUMB_DEPRECATED;
/* This is deprecated because the meaning of the 'samples' parameter in the
* callback needed to change. For stereo applications, the array used to be
* indexed with samples[channel][pos]. It is now indexed with
* samples[0][pos*2+channel]. Mono sample data are still indexed with
* samples[0][pos]. The array is still 2D because samples will probably only
* ever be interleaved in twos. In order to fix your code, adapt it to the
* new sample layout and then call
* duh_sigrenderer_set_sample_analyser_callback below instead of this
* function.
*/
#endif
typedef void (*DUH_SIGRENDERER_SAMPLE_ANALYSER_CALLBACK)(void *data, const sample_t *const *samples, int n_channels, long length);
void duh_sigrenderer_set_sample_analyser_callback(
DUH_SIGRENDERER *sigrenderer,
DUH_SIGRENDERER_SAMPLE_ANALYSER_CALLBACK callback, void *data
);
int duh_sigrenderer_get_n_channels(DUH_SIGRENDERER *sigrenderer);
long duh_sigrenderer_get_position(DUH_SIGRENDERER *sigrenderer);
void duh_sigrenderer_set_sigparam(DUH_SIGRENDERER *sigrenderer, unsigned char id, long value);
#ifdef DUMB_DECLARE_DEPRECATED
long duh_sigrenderer_get_samples(
DUH_SIGRENDERER *sigrenderer,
float volume, float delta,
long size, sample_t **samples
) DUMB_DEPRECATED;
/* The sample format has changed, so if you were using this function,
* you should switch to duh_sigrenderer_generate_samples() and change
* how you interpret the samples array. See the comments for
* duh_sigrenderer_set_analyser_callback().
*/
#endif
long duh_sigrenderer_generate_samples(
DUH_SIGRENDERER *sigrenderer,
float volume, float delta,
long size, sample_t **samples
);
void duh_sigrenderer_get_current_sample(DUH_SIGRENDERER *sigrenderer, float volume, sample_t *samples);
void duh_end_sigrenderer(DUH_SIGRENDERER *sigrenderer);
/* DUH Rendering Functions */
long duh_render(
DUH_SIGRENDERER *sigrenderer,
int bits, int unsign,
float volume, float delta,
long size, void *sptr
);
#ifdef DUMB_DECLARE_DEPRECATED
long duh_render_signal(
DUH_SIGRENDERER *sigrenderer,
float volume, float delta,
long size, sample_t **samples
) DUMB_DEPRECATED;
/* Please use duh_sigrenderer_generate_samples(), and see the
* comments for the deprecated duh_sigrenderer_get_samples() too.
*/
typedef DUH_SIGRENDERER DUH_RENDERER DUMB_DEPRECATED;
/* Please use DUH_SIGRENDERER instead of DUH_RENDERER. */
DUH_SIGRENDERER *duh_start_renderer(DUH *duh, int n_channels, long pos) DUMB_DEPRECATED;
/* Please use duh_start_sigrenderer() instead. Pass 0 for 'sig'. */
int duh_renderer_get_n_channels(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
long duh_renderer_get_position(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
/* Please use the duh_sigrenderer_*() equivalents of these two functions. */
void duh_end_renderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
/* Please use duh_end_sigrenderer() instead. */
DUH_SIGRENDERER *duh_renderer_encapsulate_sigrenderer(DUH_SIGRENDERER *sigrenderer) DUMB_DEPRECATED;
DUH_SIGRENDERER *duh_renderer_get_sigrenderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
DUH_SIGRENDERER *duh_renderer_decompose_to_sigrenderer(DUH_SIGRENDERER *dr) DUMB_DEPRECATED;
/* These functions have become no-ops that just return the parameter.
* So, for instance, replace
* duh_renderer_encapsulate_sigrenderer(my_sigrenderer)
* with
* my_sigrenderer
*/
#endif
/* Impulse Tracker Support */
extern int dumb_it_max_to_mix;
typedef struct DUMB_IT_SIGDATA DUMB_IT_SIGDATA;
typedef struct DUMB_IT_SIGRENDERER DUMB_IT_SIGRENDERER;
DUMB_IT_SIGDATA *duh_get_it_sigdata(DUH *duh);
DUH_SIGRENDERER *duh_encapsulate_it_sigrenderer(DUMB_IT_SIGRENDERER *it_sigrenderer, int n_channels, long pos);
DUMB_IT_SIGRENDERER *duh_get_it_sigrenderer(DUH_SIGRENDERER *sigrenderer);
DUH_SIGRENDERER *dumb_it_start_at_order(DUH *duh, int n_channels, int startorder);
void dumb_it_set_loop_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data);
void dumb_it_set_xm_speed_zero_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data), void *data);
void dumb_it_set_midi_callback(DUMB_IT_SIGRENDERER *sigrenderer, int (*callback)(void *data, int channel, unsigned char midi_byte), void *data);
int dumb_it_callback_terminate(void *data);
int dumb_it_callback_midi_block(void *data, int channel, unsigned char midi_byte);
DUH *dumb_load_it(const char *filename);
DUH *dumb_load_xm(const char *filename);
DUH *dumb_load_s3m(const char *filename);
DUH *dumb_load_mod(const char *filename);
DUH *dumb_read_it(DUMBFILE *f);
DUH *dumb_read_xm(DUMBFILE *f);
DUH *dumb_read_s3m(DUMBFILE *f);
DUH *dumb_read_mod(DUMBFILE *f);
DUH *dumb_load_it_quick(const char *filename);
DUH *dumb_load_xm_quick(const char *filename);
DUH *dumb_load_s3m_quick(const char *filename);
DUH *dumb_load_mod_quick(const char *filename);
DUH *dumb_read_it_quick(DUMBFILE *f);
DUH *dumb_read_xm_quick(DUMBFILE *f);
DUH *dumb_read_s3m_quick(DUMBFILE *f);
DUH *dumb_read_mod_quick(DUMBFILE *f);
long dumb_it_build_checkpoints(DUMB_IT_SIGDATA *sigdata);
void dumb_it_do_initial_runthrough(DUH *duh);
const unsigned char *dumb_it_sd_get_song_message(DUMB_IT_SIGDATA *sd);
int dumb_it_sd_get_n_orders(DUMB_IT_SIGDATA *sd);
int dumb_it_sd_get_n_samples(DUMB_IT_SIGDATA *sd);
int dumb_it_sd_get_n_instruments(DUMB_IT_SIGDATA *sd);
const unsigned char *dumb_it_sd_get_sample_name(DUMB_IT_SIGDATA *sd, int i);
const unsigned char *dumb_it_sd_get_sample_filename(DUMB_IT_SIGDATA *sd, int i);
const unsigned char *dumb_it_sd_get_instrument_name(DUMB_IT_SIGDATA *sd, int i);
const unsigned char *dumb_it_sd_get_instrument_filename(DUMB_IT_SIGDATA *sd, int i);
int dumb_it_sd_get_initial_global_volume(DUMB_IT_SIGDATA *sd);
void dumb_it_sd_set_initial_global_volume(DUMB_IT_SIGDATA *sd, int gv);
int dumb_it_sd_get_mixing_volume(DUMB_IT_SIGDATA *sd);
void dumb_it_sd_set_mixing_volume(DUMB_IT_SIGDATA *sd, int mv);
int dumb_it_sd_get_initial_speed(DUMB_IT_SIGDATA *sd);
void dumb_it_sd_set_initial_speed(DUMB_IT_SIGDATA *sd, int speed);
int dumb_it_sd_get_initial_tempo(DUMB_IT_SIGDATA *sd);
void dumb_it_sd_set_initial_tempo(DUMB_IT_SIGDATA *sd, int tempo);
int dumb_it_sd_get_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel);
void dumb_it_sd_set_initial_channel_volume(DUMB_IT_SIGDATA *sd, int channel, int volume);
int dumb_it_sr_get_current_order(DUMB_IT_SIGRENDERER *sr);
int dumb_it_sr_get_current_row(DUMB_IT_SIGRENDERER *sr);
int dumb_it_sr_get_global_volume(DUMB_IT_SIGRENDERER *sr);
void dumb_it_sr_set_global_volume(DUMB_IT_SIGRENDERER *sr, int gv);
int dumb_it_sr_get_tempo(DUMB_IT_SIGRENDERER *sr);
void dumb_it_sr_set_tempo(DUMB_IT_SIGRENDERER *sr, int tempo);
int dumb_it_sr_get_speed(DUMB_IT_SIGRENDERER *sr);
void dumb_it_sr_set_speed(DUMB_IT_SIGRENDERER *sr, int speed);
#define DUMB_IT_N_CHANNELS 64
#define DUMB_IT_N_NNA_CHANNELS 192
#define DUMB_IT_TOTAL_CHANNELS (DUMB_IT_N_CHANNELS + DUMB_IT_N_NNA_CHANNELS)
/* Channels passed to any of these functions are 0-based */
int dumb_it_sr_get_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel);
void dumb_it_sr_set_channel_volume(DUMB_IT_SIGRENDERER *sr, int channel, int volume);
int dumb_it_sr_get_channel_muted(DUMB_IT_SIGRENDERER *sr, int channel);
void dumb_it_sr_set_channel_muted(DUMB_IT_SIGRENDERER *sr, int channel, int muted);
typedef struct DUMB_IT_CHANNEL_STATE DUMB_IT_CHANNEL_STATE;
struct DUMB_IT_CHANNEL_STATE
{
int channel; /* 0-based; meaningful for NNA channels */
int sample; /* 1-based; 0 if nothing playing, then other fields undef */
int freq; /* in Hz */
float volume; /* 1.0 maximum; affected by ALL factors, inc. mixing vol */
unsigned char pan; /* 0-64, 100 for surround */
signed char subpan; /* use (pan + subpan/256.0f) or ((pan<<8)+subpan) */
unsigned char filter_cutoff; /* 0-127 cutoff=127 AND resonance=0 */
unsigned char filter_subcutoff; /* 0-255 -> no filters (subcutoff */
unsigned char filter_resonance; /* 0-127 always 0 in this case) */
/* subcutoff only changes from zero if filter envelopes are in use. The
* calculation (filter_cutoff + filter_subcutoff/256.0f) gives a more
* accurate filter cutoff measurement as a float. It would often be more
* useful to use a scaled int such as ((cutoff<<8) + subcutoff).
*/
};
/* Values of 64 or more will access NNA channels here. */
void dumb_it_sr_get_channel_state(DUMB_IT_SIGRENDERER *sr, int channel, DUMB_IT_CHANNEL_STATE *state);
/* Signal Design Helper Values */
/* Use pow(DUMB_SEMITONE_BASE, n) to get the 'delta' value to transpose up by
* n semitones. To transpose down, use negative n.
*/
#define DUMB_SEMITONE_BASE 1.059463094359295309843105314939748495817
/* Use pow(DUMB_QUARTERTONE_BASE, n) to get the 'delta' value to transpose up
* by n quartertones. To transpose down, use negative n.
*/
#define DUMB_QUARTERTONE_BASE 1.029302236643492074463779317738953977823
/* Use pow(DUMB_PITCH_BASE, n) to get the 'delta' value to transpose up by n
* units. In this case, 256 units represent one semitone; 3072 units
* represent one octave. These units are used by the sequence signal (SEQU).
*/
#define DUMB_PITCH_BASE 1.000225659305069791926712241547647863626
/* Signal Design Function Types */
typedef void sigdata_t;
typedef void sigrenderer_t;
typedef sigdata_t *(*DUH_LOAD_SIGDATA)(DUH *duh, DUMBFILE *file);
typedef sigrenderer_t *(*DUH_START_SIGRENDERER)(
DUH *duh,
sigdata_t *sigdata,
int n_channels,
long pos
);
typedef void (*DUH_SIGRENDERER_SET_SIGPARAM)(
sigrenderer_t *sigrenderer,
unsigned char id, long value
);
typedef long (*DUH_SIGRENDERER_GENERATE_SAMPLES)(
sigrenderer_t *sigrenderer,
float volume, float delta,
long size, sample_t **samples
);
typedef void (*DUH_SIGRENDERER_GET_CURRENT_SAMPLE)(
sigrenderer_t *sigrenderer,
float volume,
sample_t *samples
);
typedef void (*DUH_END_SIGRENDERER)(sigrenderer_t *sigrenderer);
typedef void (*DUH_UNLOAD_SIGDATA)(sigdata_t *sigdata);
/* Signal Design Function Registration */
typedef struct DUH_SIGTYPE_DESC
{
long type;
DUH_LOAD_SIGDATA load_sigdata;
DUH_START_SIGRENDERER start_sigrenderer;
DUH_SIGRENDERER_SET_SIGPARAM sigrenderer_set_sigparam;
DUH_SIGRENDERER_GENERATE_SAMPLES sigrenderer_generate_samples;
DUH_SIGRENDERER_GET_CURRENT_SAMPLE sigrenderer_get_current_sample;
DUH_END_SIGRENDERER end_sigrenderer;
DUH_UNLOAD_SIGDATA unload_sigdata;
}
DUH_SIGTYPE_DESC;
void dumb_register_sigtype(DUH_SIGTYPE_DESC *desc);
// Decide where to put these functions; new heading?
sigdata_t *duh_get_raw_sigdata(DUH *duh, int sig, long type);
DUH_SIGRENDERER *duh_encapsulate_raw_sigrenderer(sigrenderer_t *vsigrenderer, DUH_SIGTYPE_DESC *desc, int n_channels, long pos);
sigrenderer_t *duh_get_raw_sigrenderer(DUH_SIGRENDERER *sigrenderer, long type);
/* Standard Signal Types */
//void dumb_register_sigtype_sample(void);
/* Sample Buffer Allocation Helpers */
#ifdef DUMB_DECLARE_DEPRECATED
sample_t **create_sample_buffer(int n_channels, long length) DUMB_DEPRECATED;
/* DUMB has been changed to interleave stereo samples. Use
* allocate_sample_buffer() instead, and see the comments for
* duh_sigrenderer_set_analyser_callback().
*/
#endif
sample_t **allocate_sample_buffer(int n_channels, long length);
void destroy_sample_buffer(sample_t **samples);
/* Silencing Helper */
void dumb_silence(sample_t *samples, long length);
/* Click Removal Helpers */
typedef struct DUMB_CLICK_REMOVER DUMB_CLICK_REMOVER;
DUMB_CLICK_REMOVER *dumb_create_click_remover(void);
void dumb_record_click(DUMB_CLICK_REMOVER *cr, long pos, sample_t step);
void dumb_remove_clicks(DUMB_CLICK_REMOVER *cr, sample_t *samples, long length, int step, float halflife);
sample_t dumb_click_remover_get_offset(DUMB_CLICK_REMOVER *cr);
void dumb_destroy_click_remover(DUMB_CLICK_REMOVER *cr);
DUMB_CLICK_REMOVER **dumb_create_click_remover_array(int n);
void dumb_record_click_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step);
void dumb_record_click_negative_array(int n, DUMB_CLICK_REMOVER **cr, long pos, sample_t *step);
void dumb_remove_clicks_array(int n, DUMB_CLICK_REMOVER **cr, sample_t **samples, long length, float halflife);
void dumb_click_remover_get_offset_array(int n, DUMB_CLICK_REMOVER **cr, sample_t *offset);
void dumb_destroy_click_remover_array(int n, DUMB_CLICK_REMOVER **cr);
/* Resampling Helpers */
#define DUMB_RQ_ALIASING 0
#define DUMB_RQ_LINEAR 1
#define DUMB_RQ_CUBIC 2
#define DUMB_RQ_N_LEVELS 3
extern int dumb_resampling_quality;
typedef struct DUMB_RESAMPLER DUMB_RESAMPLER;
typedef void (*DUMB_RESAMPLE_PICKUP)(DUMB_RESAMPLER *resampler, void *data);
struct DUMB_RESAMPLER
{
void *src;
long pos;
int subpos;
long start, end;
int dir;
DUMB_RESAMPLE_PICKUP pickup;
void *pickup_data;
int min_quality;
int max_quality;
/* Everything below this point is internal: do not use. */
union {
sample_t x24[3*2];
short x16[3*2];
signed char x8[3*2];
} x;
int overshot;
};
void dumb_reset_resampler(DUMB_RESAMPLER *resampler, sample_t *src, int src_channels, long pos, long start, long end);
DUMB_RESAMPLER *dumb_start_resampler(sample_t *src, int src_channels, long pos, long start, long end);
long dumb_resample_1_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta);
long dumb_resample_1_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_2_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_2_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
void dumb_resample_get_current_sample_1_1(DUMB_RESAMPLER *resampler, float volume, sample_t *dst);
void dumb_resample_get_current_sample_1_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_2_1(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_2_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_end_resampler(DUMB_RESAMPLER *resampler);
void dumb_reset_resampler_16(DUMB_RESAMPLER *resampler, short *src, int src_channels, long pos, long start, long end);
DUMB_RESAMPLER *dumb_start_resampler_16(short *src, int src_channels, long pos, long start, long end);
long dumb_resample_16_1_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta);
long dumb_resample_16_1_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_16_2_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_16_2_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
void dumb_resample_get_current_sample_16_1_1(DUMB_RESAMPLER *resampler, float volume, sample_t *dst);
void dumb_resample_get_current_sample_16_1_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_16_2_1(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_16_2_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_end_resampler_16(DUMB_RESAMPLER *resampler);
void dumb_reset_resampler_8(DUMB_RESAMPLER *resampler, signed char *src, int src_channels, long pos, long start, long end);
DUMB_RESAMPLER *dumb_start_resampler_8(signed char *src, int src_channels, long pos, long start, long end);
long dumb_resample_8_1_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta);
long dumb_resample_8_1_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_8_2_1(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_8_2_2(DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
void dumb_resample_get_current_sample_8_1_1(DUMB_RESAMPLER *resampler, float volume, sample_t *dst);
void dumb_resample_get_current_sample_8_1_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_8_2_1(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_8_2_2(DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_end_resampler_8(DUMB_RESAMPLER *resampler);
void dumb_reset_resampler_n(int n, DUMB_RESAMPLER *resampler, void *src, int src_channels, long pos, long start, long end);
DUMB_RESAMPLER *dumb_start_resampler_n(int n, void *src, int src_channels, long pos, long start, long end);
long dumb_resample_n_1_1(int n, DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume, float delta);
long dumb_resample_n_1_2(int n, DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_n_2_1(int n, DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
long dumb_resample_n_2_2(int n, DUMB_RESAMPLER *resampler, sample_t *dst, long dst_size, float volume_left, float volume_right, float delta);
void dumb_resample_get_current_sample_n_1_1(int n, DUMB_RESAMPLER *resampler, float volume, sample_t *dst);
void dumb_resample_get_current_sample_n_1_2(int n, DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_n_2_1(int n, DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_resample_get_current_sample_n_2_2(int n, DUMB_RESAMPLER *resampler, float volume_left, float volume_right, sample_t *dst);
void dumb_end_resampler_n(int n, DUMB_RESAMPLER *resampler);
/* DUH Construction */
DUH *make_duh(
long length,
int n_tags,
const char *const tag[][2],
int n_signals,
DUH_SIGTYPE_DESC *desc[],
sigdata_t *sigdata[]
);
void duh_set_length(DUH *duh, long length);
#ifdef __cplusplus
}
#endif
#endif /* DUMB_H */
diff --git a/src/libs/dumb/src/it/itread.c b/src/libs/dumb/src/it/itread.c
index 269d57a6..4acdd9e7 100644
--- a/src/libs/dumb/src/it/itread.c
+++ b/src/libs/dumb/src/it/itread.c
@@ -1,1202 +1,1203 @@
/* _______ ____ __ ___ ___
* \ _ \ \ / \ / \ \ / / ' ' '
* | | \ \ | | || | \/ | . .
* | | | | | | || ||\ /| |
* | | | | | | || || \/ | | ' ' '
* | | | | | | || || | | . .
* | |_/ / \ \__// || | |
* /_______/ynamic \____/niversal /__\ /____\usic /| . . ibliotheque
* / \
* / . \
* itread.c - Code to read an Impulse Tracker / / \ \
* module from an open file. | < / \_
* | \/ /\ /
* Based on the loader from an IT player by Bob. \_ / > /
* Adapted for DUMB by entheh. | \ / /
* | ' /
* \__/
*/
#include <stdlib.h>
#include <string.h>//might not be necessary later; required for memset
#include "dumb.h"
#include "internal/it.h"
#define INVESTIGATE_OLD_INSTRUMENTS
static int it_seek(DUMBFILE *f, long offset)
{
long pos = dumbfile_pos(f);
if (pos > offset)
return -1;
if (pos < offset)
if (dumbfile_skip(f, offset - pos))
return -1;
return 0;
}
typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;
static unsigned char *sourcebuf = NULL;
static unsigned char *sourcepos = NULL;
static unsigned char *sourceend;
static int rembits = 0;
static int readblock(DUMBFILE *f)
{
long size;
int c;
size = dumbfile_igetw(f);
if (size < 0)
return size;
sourcebuf = malloc(size);
if (!sourcebuf)
return -1;
c = dumbfile_getnc((unsigned char *)sourcebuf, size, f);
if (c < size) {
free(sourcebuf);
sourcebuf = NULL;
return -1;
}
sourcepos = sourcebuf;
sourceend = sourcebuf + size;
rembits = 8;
return 0;
}
static void freeblock(void)
{
free(sourcebuf);
sourcebuf = NULL;
}
static int readbits(int bitwidth)
{
int val = 0;
int b = 0;
if (sourcepos >= sourceend) return val;
while (bitwidth > rembits) {
val |= *sourcepos++ << b;
if (sourcepos >= sourceend) return val;
b += rembits;
bitwidth -= rembits;
rembits = 8;
}
val |= (*sourcepos & ((1 << bitwidth) - 1)) << b;
*sourcepos >>= bitwidth;
rembits -= bitwidth;
return val;
}
/** WARNING - do we even need to pass `right`? */
/** WARNING - why bother memsetting at all? The whole array is written... */
// if we do memset, dumb_silence() would be neater...
static int decompress8(DUMBFILE *f, signed char *data, int len, int cmwt)
{
int blocklen, blockpos;
byte bitwidth;
word val;
char d1, d2;
memset(data, 0, len * sizeof(*data));
while (len > 0) {
//Read a block of compressed data:
if (readblock(f))
return -1;
//Set up a few variables
blocklen = (len < 0x8000) ? len : 0x8000; //Max block length is 0x8000 bytes
blockpos = 0;
bitwidth = 9;
d1 = d2 = 0;
//Start the decompression:
while (blockpos < blocklen) {
//Read a value:
val = (word)readbits(bitwidth);
//Check for bit width change:
if (bitwidth < 7) { //Method 1:
if (val == (1 << (bitwidth - 1))) {
val = (word)readbits(3) + 1;
bitwidth = (val < bitwidth) ? val : val + 1;
continue;
}
}
else if (bitwidth < 9) { //Method 2
byte border = (0xFF >> (9 - bitwidth)) - 4;
if (val > border && val <= (border + 8)) {
val -= border;
bitwidth = (val < bitwidth) ? val : val + 1;
continue;
}
}
else if (bitwidth == 9) { //Method 3
if (val & 0x100) {
bitwidth = (val + 1) & 0xFF;
continue;
}
}
else { //Illegal width, abort ?
freeblock();
return -1;
}
//Expand the value to signed byte:
{
char v; //The sample value:
if (bitwidth < 8) {
byte shift = 8 - bitwidth;
v = (val << shift);
v >>= shift;
}
else
v = (char)val;
//And integrate the sample value
//(It always has to end with integration doesn't it ? ;-)
d1 += v;
d2 += d1;
}
//Store !
/* Version 2.15 was an unofficial version with hacked compression
* code. Yay, better compression :D
*/
*data++ = cmwt == 0x215 ? d2 : d1;
len--;
blockpos++;
}
freeblock();
}
return 0;
}
static int decompress16(DUMBFILE *f, short *data, int len, int cmwt)
{
int blocklen, blockpos;
byte bitwidth;
long val;
short d1, d2;
memset(data, 0, len * sizeof(*data));
while (len > 0) {
//Read a block of compressed data:
if (readblock(f))
return -1;
//Set up a few variables
blocklen = (len < 0x4000) ? len : 0x4000; // Max block length is 0x4000 bytes
blockpos = 0;
bitwidth = 17;
d1 = d2 = 0;
//Start the decompression:
while (blockpos < blocklen) {
val = readbits(bitwidth);
//Check for bit width change:
if (bitwidth < 7) { //Method 1:
if (val == (1 << (bitwidth - 1))) {
val = readbits(4) + 1;
bitwidth = (val < bitwidth) ? val : val + 1;
continue;
}
}
else if (bitwidth < 17) { //Method 2
word border = (0xFFFF >> (17 - bitwidth)) - 8;
if (val > border && val <= (border + 16)) {
val -= border;
bitwidth = val < bitwidth ? val : val + 1;
continue;
}
}
else if (bitwidth == 17) { //Method 3
if (val & 0x10000) {
bitwidth = (val + 1) & 0xFF;
continue;
}
}
else { //Illegal width, abort ?
freeblock();
return -1;
}
//Expand the value to signed byte:
{
short v; //The sample value:
if (bitwidth < 16) {
byte shift = 16 - bitwidth;
v = (short)(val << shift);
v >>= shift;
}
else
v = (short)val;
//And integrate the sample value
//(It always has to end with integration doesn't it ? ;-)
d1 += v;
d2 += d1;
}
//Store !
/* Version 2.15 was an unofficial version with hacked compression
* code. Yay, better compression :D
*/
*data++ = cmwt == 0x215 ? d2 : d1;
len--;
blockpos++;
}
freeblock();
}
return 0;
}
static int it_read_envelope(IT_ENVELOPE *envelope, DUMBFILE *f)
{
int n;
envelope->flags = dumbfile_getc(f);
envelope->n_nodes = dumbfile_getc(f);
envelope->loop_start = dumbfile_getc(f);
envelope->loop_end = dumbfile_getc(f);
envelope->sus_loop_start = dumbfile_getc(f);
envelope->sus_loop_end = dumbfile_getc(f);
for (n = 0; n < envelope->n_nodes; n++) {
envelope->node_y[n] = dumbfile_getc(f);
envelope->node_t[n] = dumbfile_igetw(f);
}
dumbfile_skip(f, 75 - envelope->n_nodes * 3 + 1);
if (envelope->n_nodes <= 0)
envelope->flags &= ~IT_ENVELOPE_ON;
else {
if (envelope->loop_end >= envelope->n_nodes || envelope->loop_start > envelope->loop_end) envelope->flags &= ~IT_ENVELOPE_LOOP_ON;
if (envelope->sus_loop_end >= envelope->n_nodes || envelope->sus_loop_start > envelope->sus_loop_end) envelope->flags &= ~IT_ENVELOPE_SUSTAIN_LOOP;
}
return dumbfile_error(f);
}
static int it_read_old_instrument(IT_INSTRUMENT *instrument, DUMBFILE *f)
{
int n;
if (dumbfile_mgetl(f) != IT_INSTRUMENT_SIGNATURE)
return -1;
dumbfile_getnc(instrument->filename, 13, f);
instrument->filename[13] = 0;
instrument->volume_envelope.flags = dumbfile_getc(f);
instrument->volume_envelope.loop_start = dumbfile_getc(f);
instrument->volume_envelope.loop_end = dumbfile_getc(f);
instrument->volume_envelope.sus_loop_start = dumbfile_getc(f);
instrument->volume_envelope.sus_loop_end = dumbfile_getc(f);
/* Skip two unused bytes. */
dumbfile_skip(f, 2);
/* In the old instrument format, fadeout ranges from 0 to 64, and is
* subtracted at intervals from a value starting at 512. In the new
* format, all these values are doubled. Therefore we double when loading
* from the old instrument format - that way we don't have to think about
* it later.
*/
instrument->fadeout = dumbfile_igetw(f) << 1;
instrument->new_note_action = dumbfile_getc(f);
instrument->dup_check_type = dumbfile_getc(f);
instrument->dup_check_action = DCA_NOTE_CUT; // This might be wrong!
/** WARNING - what is the duplicate check action for old-style instruments? */
/* Skip Tracker Version and Number of Samples. These are only used in
* separate instrument files. Also skip unused byte.
*/
dumbfile_skip(f, 4);
dumbfile_getnc(instrument->name, 26, f);
instrument->name[26] = 0;
/* Skip unused bytes following the Instrument Name. */
dumbfile_skip(f, 6);
instrument->pp_separation = 0;
instrument->pp_centre = 60;
instrument->global_volume = 128;
/** WARNING - should global_volume be 64 or something? */
instrument->default_pan = 32;
/** WARNING - should default_pan be 128, meaning don`t use? */
instrument->random_volume = 0;
instrument->random_pan = 0;
for (n = 0; n < 120; n++) {
instrument->map_note[n] = dumbfile_getc(f);
instrument->map_sample[n] = dumbfile_getc(f);
}
/* Skip "Volume envelope (200 bytes)". */
// - need to know better what this is for though.
dumbfile_skip(f, 200);
#ifdef INVESTIGATE_OLD_INSTRUMENTS
fprintf(stderr, "Inst %02d Env:", n);
#endif
for (n = 0; n < 25; n++)
{
instrument->volume_envelope.node_t[n] = dumbfile_getc(f);
instrument->volume_envelope.node_y[n] = dumbfile_getc(f);
#ifdef INVESTIGATE_OLD_INSTRUMENTS
fprintf(stderr, " %d,%d",
instrument->volume_envelope.node_t[n],
instrument->volume_envelope.node_y[n]);
#endif
// This loop is unfinished, as we can probably escape from it before
// the end if we want to. Hence the otherwise useless dumbfile_skip()
// call below.
}
dumbfile_skip(f, 50 - (n << 1));
instrument->volume_envelope.n_nodes = n;
#ifdef INVESTIGATE_OLD_INSTRUMENTS
fprintf(stderr, "\n");
#endif
if (dumbfile_error(f))
return -1;
{
IT_ENVELOPE *envelope = &instrument->volume_envelope;
if (envelope->n_nodes <= 0)
envelope->flags &= ~IT_ENVELOPE_ON;
else {
if (envelope->loop_end >= envelope->n_nodes || envelope->loop_start > envelope->loop_end) envelope->flags &= ~IT_ENVELOPE_LOOP_ON;
if (envelope->sus_loop_end >= envelope->n_nodes || envelope->sus_loop_start > envelope->sus_loop_end) envelope->flags &= ~IT_ENVELOPE_SUSTAIN_LOOP;
}
}
instrument->filter_cutoff = 127;
instrument->filter_resonance = 0;
instrument->pan_envelope.flags = 0;
instrument->pitch_envelope.flags = 0;
return 0;
}
static int it_read_instrument(IT_INSTRUMENT *instrument, DUMBFILE *f)
{
int n;
if (dumbfile_mgetl(f) != IT_INSTRUMENT_SIGNATURE)
return -1;
dumbfile_getnc(instrument->filename, 13, f);
instrument->filename[13] = 0;
instrument->new_note_action = dumbfile_getc(f);
instrument->dup_check_type = dumbfile_getc(f);
instrument->dup_check_action = dumbfile_getc(f);
instrument->fadeout = dumbfile_igetw(f);
instrument->pp_separation = dumbfile_getc(f);
instrument->pp_centre = dumbfile_getc(f);
instrument->global_volume = dumbfile_getc(f);
instrument->default_pan = dumbfile_getc(f);
instrument->random_volume = dumbfile_getc(f);
instrument->random_pan = dumbfile_getc(f);
/* Skip Tracker Version and Number of Samples. These are only used in
* separate instrument files. Also skip unused byte.
*/
dumbfile_skip(f, 4);
dumbfile_getnc(instrument->name, 26, f);
instrument->name[26] = 0;
instrument->filter_cutoff = dumbfile_getc(f);
instrument->filter_resonance = dumbfile_getc(f);
/* Skip MIDI Channel, Program and Bank. */
dumbfile_skip(f, 4);
for (n = 0; n < 120; n++) {
instrument->map_note[n] = dumbfile_getc(f);
instrument->map_sample[n] = dumbfile_getc(f);
}
if (dumbfile_error(f))
return -1;
if (it_read_envelope(&instrument->volume_envelope, f)) return -1;
if (it_read_envelope(&instrument->pan_envelope, f)) return -1;
if (it_read_envelope(&instrument->pitch_envelope, f)) return -1;
return 0;
}
static int it_read_sample_header(IT_SAMPLE *sample, unsigned char *convert, long *offset, DUMBFILE *f)
{
if (dumbfile_mgetl(f) != IT_SAMPLE_SIGNATURE)
return -1;
dumbfile_getnc(sample->filename, 13, f);
sample->filename[13] = 0;
sample->global_volume = dumbfile_getc(f);
sample->flags = dumbfile_getc(f);
sample->default_volume = dumbfile_getc(f);
dumbfile_getnc(sample->name, 26, f);
sample->name[26] = 0;
*convert = dumbfile_getc(f);
sample->default_pan = dumbfile_getc(f);
sample->length = dumbfile_igetl(f);
sample->loop_start = dumbfile_igetl(f);
sample->loop_end = dumbfile_igetl(f);
sample->C5_speed = dumbfile_igetl(f);
sample->sus_loop_start = dumbfile_igetl(f);
sample->sus_loop_end = dumbfile_igetl(f);
#ifdef STEREO_SAMPLES_COUNT_AS_TWO
if (sample->flags & IT_SAMPLE_STEREO) {
sample->length >>= 1;
sample->loop_start >>= 1;
sample->loop_end >>= 1;
sample->C5_speed >>= 1;
sample->sus_loop_start >>= 1;
sample->sus_loop_end >>= 1;
}
#endif
if (sample->flags & IT_SAMPLE_EXISTS) {
if (sample->length <= 0)
sample->flags &= ~IT_SAMPLE_EXISTS;
else {
if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
sample->flags &= ~IT_SAMPLE_LOOP;
else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
sample->flags &= ~IT_SAMPLE_LOOP;
if ((unsigned int)sample->sus_loop_end > (unsigned int)sample->length)
sample->flags &= ~IT_SAMPLE_SUS_LOOP;
else if ((unsigned int)sample->sus_loop_start >= (unsigned int)sample->sus_loop_end)
sample->flags &= ~IT_SAMPLE_SUS_LOOP;
/* We may be able to truncate the sample to save memory. */
if (sample->flags & IT_SAMPLE_LOOP) {
if ((sample->flags & IT_SAMPLE_SUS_LOOP) && sample->sus_loop_end >= sample->loop_end)
sample->length = sample->sus_loop_end;
else
sample->length = sample->loop_end;
}
}
}
*offset = dumbfile_igetl(f);
sample->vibrato_speed = dumbfile_getc(f);
sample->vibrato_depth = dumbfile_getc(f);
sample->vibrato_rate = dumbfile_getc(f);
sample->vibrato_waveform = dumbfile_getc(f);
return dumbfile_error(f);
}
static long it_read_sample_data(int cmwt, IT_SAMPLE *sample, unsigned char convert, DUMBFILE *f)
{
long n;
long datasize = sample->length;
if (sample->flags & IT_SAMPLE_STEREO) datasize <<= 1;
sample->data = malloc(datasize * (sample->flags & IT_SAMPLE_16BIT ? 2 : 1));
if (!sample->data)
return -1;
if (sample->flags & 8) {
/* If the sample is packed, then we must unpack it. */
/** WARNING - unresolved business here... test with ModPlug? */
if (sample->flags & IT_SAMPLE_STEREO)
exit(37); // TODO: if this ever happens, maybe sample->length should be doubled below?
/*
//#ifndef STEREO_SAMPLES_COUNT_AS_TWO
ASSERT(!(sample->flags & IT_SAMPLE_STEREO));
//#endif
*/
if (sample->flags & IT_SAMPLE_16BIT)
decompress16(f, sample->data, datasize, cmwt);
else
decompress8(f, sample->data, datasize, cmwt);
} else if (sample->flags & IT_SAMPLE_16BIT) {
if (convert & 2)
for (n = 0; n < datasize; n++)
((short *)sample->data)[n] = dumbfile_mgetw(f);
else
for (n = 0; n < datasize; n++)
((short *)sample->data)[n] = dumbfile_igetw(f);
} else
for (n = 0; n < datasize; n++)
((signed char *)sample->data)[n] = dumbfile_getc(f);
if (dumbfile_error(f))
return -1;
if (!(convert & 1)) {
/* Convert to signed. */
if (sample->flags & IT_SAMPLE_16BIT)
for (n = 0; n < datasize; n++)
((short *)sample->data)[n] ^= 0x8000;
else
for (n = 0; n < datasize; n++)
((signed char *)sample->data)[n] ^= 0x80;
}
/* NOT SUPPORTED:
*
* convert & 4 - Samples stored as delta values
* convert & 16 - Samples stored as TX-Wave 12-bit values
* convert & 32 - Left/Right/All Stereo prompt
*/
return 0;
}
#define DETECT_DUPLICATE_CHANNELS
#ifdef DETECT_DUPLICATE_CHANNELS
#include <stdio.h>
#endif
static int it_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, unsigned char *buffer)
{
unsigned char cmask[DUMB_IT_N_CHANNELS];
unsigned char cnote[DUMB_IT_N_CHANNELS];
unsigned char cinstrument[DUMB_IT_N_CHANNELS];
unsigned char cvolpan[DUMB_IT_N_CHANNELS];
unsigned char ceffect[DUMB_IT_N_CHANNELS];
unsigned char ceffectvalue[DUMB_IT_N_CHANNELS];
#ifdef DETECT_DUPLICATE_CHANNELS
IT_ENTRY *dupentry[DUMB_IT_N_CHANNELS];
#endif
int n_entries = 0;
int buflen;
int bufpos = 0;
IT_ENTRY *entry;
unsigned char channel;
unsigned char mask;
memset(cmask, 0, sizeof(cmask));
memset(cnote, 0, sizeof(cnote));
memset(cinstrument, 0, sizeof(cinstrument));
memset(cvolpan, 0, sizeof(cvolpan));
memset(ceffect, 0, sizeof(ceffect));
memset(ceffectvalue, 0, sizeof(ceffectvalue));
#ifdef DETECT_DUPLICATE_CHANNELS
{
int i;
for (i = 0; i < DUMB_IT_N_CHANNELS; i++) dupentry[i] = NULL;
}
#endif
buflen = dumbfile_igetw(f);
pattern->n_rows = dumbfile_igetw(f);
/* Skip four unused bytes. */
dumbfile_skip(f, 4);
if (dumbfile_error(f))
return -1;
/* Read in the pattern data. */
dumbfile_getnc(buffer, buflen, f);
if (dumbfile_error(f))
return -1;
/* Scan the pattern data, and work out how many entries we need room for. */
while (bufpos < buflen) {
unsigned char b = buffer[bufpos++];
if (b == 0) {
/* End of row */
n_entries++;
continue;
}
channel = (b - 1) & 63;
if (b & 128)
cmask[channel] = mask = buffer[bufpos++];
else
mask = cmask[channel];
{
static const unsigned char used[16] = {0, 1, 1, 2, 1, 2, 2, 3, 2, 3, 3, 4, 3, 4, 4, 5};
n_entries += (mask != 0);
bufpos += used[mask & 15];
}
}
pattern->n_entries = n_entries;
pattern->entry = malloc(n_entries * sizeof(*pattern->entry));
if (!pattern->entry)
return -1;
bufpos = 0;
memset(cmask, 0, sizeof(cmask));
entry = pattern->entry;
while (bufpos < buflen) {
unsigned char b = buffer[bufpos++];
if (b == 0) {
/* End of row */
IT_SET_END_ROW(entry);
entry++;
#ifdef DETECT_DUPLICATE_CHANNELS
{
int i;
for (i = 0; i < DUMB_IT_N_CHANNELS; i++) dupentry[i] = NULL;
}
#endif
continue;
}
channel = (b - 1) & 63;
if (b & 128)
cmask[channel] = mask = buffer[bufpos++];
else
mask = cmask[channel];
if (mask) {
entry->mask = (mask & 15) | (mask >> 4);
entry->channel = channel;
if (mask & IT_ENTRY_NOTE)
cnote[channel] = entry->note = buffer[bufpos++];
else if (mask & (IT_ENTRY_NOTE << 4))
entry->note = cnote[channel];
if (mask & IT_ENTRY_INSTRUMENT)
cinstrument[channel] = entry->instrument = buffer[bufpos++];
else if (mask & (IT_ENTRY_INSTRUMENT << 4))
entry->instrument = cinstrument[channel];
if (mask & IT_ENTRY_VOLPAN)
cvolpan[channel] = entry->volpan = buffer[bufpos++];
else if (mask & (IT_ENTRY_VOLPAN << 4))
entry->volpan = cvolpan[channel];
if (mask & IT_ENTRY_EFFECT) {
ceffect[channel] = entry->effect = buffer[bufpos++];
ceffectvalue[channel] = entry->effectvalue = buffer[bufpos++];
} else {
entry->effect = ceffect[channel];
entry->effectvalue = ceffectvalue[channel];
}
#ifdef DETECT_DUPLICATE_CHANNELS
if (dupentry[channel]) {
FILE *f = fopen("dupentry.txt", "a");
if (!f) abort();
fprintf(f, "Two events on channel %d:", channel);
fprintf(f, " Event #1:");
if (dupentry[channel]->mask & IT_ENTRY_NOTE ) fprintf(f, " %03d", dupentry[channel]->note ); else fprintf(f, " ...");
if (dupentry[channel]->mask & IT_ENTRY_INSTRUMENT) fprintf(f, " %03d", dupentry[channel]->instrument); else fprintf(f, " ...");
if (dupentry[channel]->mask & IT_ENTRY_VOLPAN ) fprintf(f, " %03d", dupentry[channel]->volpan ); else fprintf(f, " ...");
if (dupentry[channel]->mask & IT_ENTRY_EFFECT) fprintf(f, " %c%02X\n", 'A' - 1 + dupentry[channel]->effect, dupentry[channel]->effectvalue); else fprintf(f, " ...\n");
fprintf(f, " Event #2:");
if (entry->mask & IT_ENTRY_NOTE ) fprintf(f, " %03d", entry->note ); else fprintf(f, " ...");
if (entry->mask & IT_ENTRY_INSTRUMENT) fprintf(f, " %03d", entry->instrument); else fprintf(f, " ...");
if (entry->mask & IT_ENTRY_VOLPAN ) fprintf(f, " %03d", entry->volpan ); else fprintf(f, " ...");
if (entry->mask & IT_ENTRY_EFFECT) fprintf(f, " %c%02X\n", 'A' - 1 + entry->effect, entry->effectvalue); else fprintf(f, " ...\n");
fclose(f);
}
dupentry[channel] = entry;
#endif
entry++;
}
}
ASSERT(entry == pattern->entry + n_entries);
return 0;
}
/* Currently we assume the sample data are stored after the sample headers in
* module files. This assumption may be unjustified; let me know if you have
* trouble.
*/
#define IT_COMPONENT_SONG_MESSAGE 1
#define IT_COMPONENT_INSTRUMENT 2
#define IT_COMPONENT_PATTERN 3
#define IT_COMPONENT_SAMPLE 4
typedef struct IT_COMPONENT
{
unsigned char type;
unsigned char n;
long offset;
short sampfirst; /* component[sampfirst] = first sample data after this */
short sampnext; /* sampnext is used to create linked lists of sample data */
}
IT_COMPONENT;
static int it_component_compare(const void *e1, const void *e2)
{
return ((const IT_COMPONENT *)e1)->offset -
((const IT_COMPONENT *)e2)->offset;
}
static sigdata_t *it_load_sigdata(DUMBFILE *f)
{
DUMB_IT_SIGDATA *sigdata;
int cwt, cmwt;
int special;
int message_length, message_offset;
IT_COMPONENT *component;
int n_components = 0;
unsigned char sample_convert[256];
int n;
unsigned char *buffer;
if (dumbfile_mgetl(f) != IT_SIGNATURE)
return NULL;
sigdata = malloc(sizeof(*sigdata));
if (!sigdata)
return NULL;
sigdata->song_message = NULL;
sigdata->order = NULL;
sigdata->instrument = NULL;
sigdata->sample = NULL;
sigdata->pattern = NULL;
sigdata->midi = NULL;
sigdata->checkpoint = NULL;
dumbfile_getnc(sigdata->name, 26, f);
sigdata->name[26] = 0;
/* Skip pattern row highlight info. */
dumbfile_skip(f, 2);
sigdata->n_orders = dumbfile_igetw(f);
sigdata->n_instruments = dumbfile_igetw(f);
sigdata->n_samples = dumbfile_igetw(f);
sigdata->n_patterns = dumbfile_igetw(f);
cwt = dumbfile_igetw(f);
+ cwt = cwt;
cmwt = dumbfile_igetw(f);
sigdata->flags = dumbfile_igetw(f);
special = dumbfile_igetw(f);
sigdata->global_volume = dumbfile_getc(f);
sigdata->mixing_volume = dumbfile_getc(f);
sigdata->speed = dumbfile_getc(f);
if (sigdata->speed == 0) sigdata->speed = 6; // Should we? What about tempo?
sigdata->tempo = dumbfile_getc(f);
sigdata->pan_separation = dumbfile_getc(f); /** WARNING: use this */
/* Skip Pitch Wheel Depth */
dumbfile_skip(f, 1);
message_length = dumbfile_igetw(f);
message_offset = dumbfile_igetl(f);
/* Skip Reserved. */
dumbfile_skip(f, 4);
dumbfile_getnc(sigdata->channel_pan, DUMB_IT_N_CHANNELS, f);
dumbfile_getnc(sigdata->channel_volume, DUMB_IT_N_CHANNELS, f);
if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_instruments > 256 || sigdata->n_samples > 256 || sigdata->n_patterns > 256) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
sigdata->order = malloc(sigdata->n_orders);
if (!sigdata->order) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (sigdata->n_instruments) {
sigdata->instrument = malloc(sigdata->n_instruments * sizeof(*sigdata->instrument));
if (!sigdata->instrument) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
}
if (sigdata->n_samples) {
sigdata->sample = malloc(sigdata->n_samples * sizeof(*sigdata->sample));
if (!sigdata->sample) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < sigdata->n_samples; n++)
sigdata->sample[n].data = NULL;
}
if (sigdata->n_patterns) {
sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
if (!sigdata->pattern) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < sigdata->n_patterns; n++)
sigdata->pattern[n].entry = NULL;
}
dumbfile_getnc(sigdata->order, sigdata->n_orders, f);
sigdata->restart_position = 0;
component = malloc(769 * sizeof(*component));
if (!component) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (special & 1) {
component[n_components].type = IT_COMPONENT_SONG_MESSAGE;
component[n_components].offset = message_offset;
component[n_components].sampfirst = -1;
n_components++;
}
for (n = 0; n < sigdata->n_instruments; n++) {
component[n_components].type = IT_COMPONENT_INSTRUMENT;
component[n_components].n = n;
component[n_components].offset = dumbfile_igetl(f);
component[n_components].sampfirst = -1;
n_components++;
}
for (n = 0; n < sigdata->n_samples; n++) {
component[n_components].type = IT_COMPONENT_SAMPLE;
component[n_components].n = n;
component[n_components].offset = dumbfile_igetl(f);
component[n_components].sampfirst = -1;
n_components++;
}
for (n = 0; n < sigdata->n_patterns; n++) {
long offset = dumbfile_igetl(f);
if (offset) {
component[n_components].type = IT_COMPONENT_PATTERN;
component[n_components].n = n;
component[n_components].offset = offset;
component[n_components].sampfirst = -1;
n_components++;
} else {
/* Empty 64-row pattern */
sigdata->pattern[n].n_rows = 64;
sigdata->pattern[n].n_entries = 0;
}
}
if (dumbfile_error(f)) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (!(sigdata->flags & 128) != !(special & 8)) {
fprintf(stderr, "Flags Bit 7 (\"Request embedded MIDI configuration\"): %s\n", sigdata->flags & 128 ? "=SET=" : "clear");
fprintf(stderr, "Special Bit 3 (\"MIDI configuration embedded\") : %s\n", special & 8 ? "=SET=" : "clear");
fprintf(stderr, "entheh would like to investigate this IT file.\n");
fprintf(stderr, "Please contact him! entheh@users.sf.net\n");
}
if (special & 8) {
/* MIDI configuration is embedded. */
unsigned char mididata[32];
int i;
sigdata->midi = malloc(sizeof(*sigdata->midi));
if (!sigdata->midi) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
// Should we be happy with this outcome in some situations?
}
// What are we skipping?
i = dumbfile_igetw(f);
if (dumbfile_error(f) || dumbfile_skip(f, 8*i)) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
/* Read embedded MIDI configuration */
// What are the first 9 commands for?
if (dumbfile_skip(f, 32*9)) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (i = 0; i < 16; i++) {
unsigned char len = 0;
int j, leftdigit = -1;
if (dumbfile_getnc(mididata, 32, f) < 32) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
sigdata->midi->SFmacroz[i] = 0;
for (j = 0; j < 32; j++) {
if (leftdigit >= 0) {
if (mididata[j] == 0) {
sigdata->midi->SFmacro[i][len++] = leftdigit;
break;
} else if (mididata[j] == ' ')
sigdata->midi->SFmacro[i][len++] = leftdigit;
else if (mididata[j] >= '0' && mididata[j] <= '9')
sigdata->midi->SFmacro[i][len++] = (leftdigit << 4) | (mididata[j] - '0');
else if (mididata[j] >= 'A' && mididata[j] <= 'F')
sigdata->midi->SFmacro[i][len++] = (leftdigit << 4) | (mididata[j] - 'A' + 0xA);
leftdigit = -1;
} else if (mididata[j] == 0)
break;
else if (mididata[j] == 'z')
sigdata->midi->SFmacroz[i] |= 1 << len++;
else if (mididata[j] >= '0' && mididata[j] <= '9')
leftdigit = mididata[j] - '0';
else if (mididata[j] >= 'A' && mididata[j] <= 'F')
leftdigit = mididata[j] - 'A' + 0xA;
}
sigdata->midi->SFmacrolen[i] = len;
}
for (i = 0; i < 128; i++) {
unsigned char len = 0;
int j, leftdigit = -1;
dumbfile_getnc(mididata, 32, f);
for (j = 0; j < 32; j++) {
if (leftdigit >= 0) {
if (mididata[j] == 0) {
sigdata->midi->Zmacro[i][len++] = leftdigit;
break;
} else if (mididata[j] == ' ')
sigdata->midi->Zmacro[i][len++] = leftdigit;
else if (mididata[j] >= '0' && mididata[j] <= '9')
sigdata->midi->Zmacro[i][len++] = (leftdigit << 4) | (mididata[j] - '0');
else if (mididata[j] >= 'A' && mididata[j] <= 'F')
sigdata->midi->Zmacro[i][len++] = (leftdigit << 4) | (mididata[j] - 'A' + 0xA);
leftdigit = -1;
} else if (mididata[j] == 0)
break;
else if (mididata[j] >= '0' && mididata[j] <= '9')
leftdigit = mididata[j] - '0';
else if (mididata[j] >= 'A' && mididata[j] <= 'F')
leftdigit = mididata[j] - 'A' + 0xA;
}
sigdata->midi->Zmacrolen[i] = len;
}
}
sigdata->flags &= IT_REAL_FLAGS;
qsort(component, n_components, sizeof(IT_COMPONENT), &it_component_compare);
buffer = malloc(65536);
if (!buffer) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < n_components; n++) {
long offset;
int m;
if (it_seek(f, component[n].offset)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
switch (component[n].type) {
case IT_COMPONENT_SONG_MESSAGE:
sigdata->song_message = malloc(message_length + 1);
if (sigdata->song_message) {
if (dumbfile_getnc(sigdata->song_message, message_length, f) < message_length) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
sigdata->song_message[message_length] = 0;
}
break;
case IT_COMPONENT_INSTRUMENT:
if (cmwt < 0x200)
m = it_read_old_instrument(&sigdata->instrument[component[n].n], f);
else
m = it_read_instrument(&sigdata->instrument[component[n].n], f);
if (m) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
break;
case IT_COMPONENT_PATTERN:
if (it_read_pattern(&sigdata->pattern[component[n].n], f, buffer)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
break;
case IT_COMPONENT_SAMPLE:
if (it_read_sample_header(&sigdata->sample[component[n].n], &sample_convert[component[n].n], &offset, f)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (sigdata->sample[component[n].n].flags & IT_SAMPLE_EXISTS) {
short *sample;
for (m = n + 1; m < n_components; m++)
if (component[m].offset > offset)
break;
m--;
sample = &component[m].sampfirst;
while (*sample >= 0 && component[*sample].offset <= offset)
sample = &component[*sample].sampnext;
component[n].sampnext = *sample;
*sample = n;
component[n].offset = offset;
}
}
m = component[n].sampfirst;
while (m >= 0) {
if (it_seek(f, component[m].offset)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (it_read_sample_data(cmwt, &sigdata->sample[component[m].n], sample_convert[component[m].n], f)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
m = component[m].sampnext;
}
}
free(buffer);
free(component);
_dumb_it_fix_invalid_orders(sigdata);
return sigdata;
}
DUH *dumb_read_it_quick(DUMBFILE *f)
{
sigdata_t *sigdata;
DUH_SIGTYPE_DESC *descptr = &_dumb_sigtype_it;
sigdata = it_load_sigdata(f);
if (!sigdata)
return NULL;
{
const char *tag[1][2];
tag[0][0] = "TITLE";
tag[0][1] = (const char *) ((DUMB_IT_SIGDATA *)sigdata)->name;
return make_duh(-1, 1, (const char *const (*)[2])tag, 1, &descptr, &sigdata);
}
}
diff --git a/src/libs/dumb/src/it/reads3m.c b/src/libs/dumb/src/it/reads3m.c
index 7a47bccf..98b5cca9 100644
--- a/src/libs/dumb/src/it/reads3m.c
+++ b/src/libs/dumb/src/it/reads3m.c
@@ -1,670 +1,671 @@
/* _______ ____ __ ___ ___
* \ _ \ \ / \ / \ \ / / ' ' '
* | | \ \ | | || | \/ | . .
* | | | | | | || ||\ /| |
* | | | | | | || || \/ | | ' ' '
* | | | | | | || || | | . .
* | |_/ / \ \__// || | |
* /_______/ynamic \____/niversal /__\ /____\usic /| . . ibliotheque
* / \
* / . \
* reads3m.c - Code to read a ScreamTracker 3 / / \ \
* module from an open file. | < / \_
* | \/ /\ /
* By entheh. \_ / > /
* | \ / /
* | ' /
* \__/
*/
// IT_STEREO... :o
#include <stdlib.h>
#include <string.h>
#include "dumb.h"
#include "internal/it.h"
/** WARNING: this is duplicated in itread.c */
static int it_seek(DUMBFILE *f, long offset)
{
long pos = dumbfile_pos(f);
if (pos > offset)
return -1;
if (pos < offset)
if (dumbfile_skip(f, offset - pos))
return -1;
return 0;
}
static int it_s3m_read_sample_header(IT_SAMPLE *sample, long *offset, DUMBFILE *f)
{
unsigned char type;
int flags;
type = dumbfile_getc(f);
if (type > 1) {
/** WARNING: no adlib support */
}
dumbfile_getnc(sample->filename, 13, f);
sample->filename[13] = 0;
*offset = dumbfile_igetw(f) << 4;
sample->length = dumbfile_igetl(f);
sample->loop_start = dumbfile_igetl(f);
sample->loop_end = dumbfile_igetl(f);
sample->default_volume = dumbfile_getc(f);
dumbfile_skip(f, 1);
if (dumbfile_getc(f) != 0)
/* Sample is packed apparently (or error reading from file). We don't
* know how to read packed samples.
*/
return -1;
flags = dumbfile_getc(f);
sample->C5_speed = dumbfile_igetl(f) << 1;
/* Skip four unused bytes and three internal variables. */
dumbfile_skip(f, 4+2+2+4);
dumbfile_getnc(sample->name, 28, f);
sample->name[28] = 0;
if (type == 0) {
/* Looks like no-existy. Anyway, there's for sure no 'SCRS' ... */
sample->flags &= ~IT_SAMPLE_EXISTS;
return dumbfile_error(f);
}
if (dumbfile_mgetl(f) != DUMB_ID('S','C','R','S'))
return -1;
sample->global_volume = 64;
sample->flags = IT_SAMPLE_EXISTS;
if (flags & 1) sample->flags |= IT_SAMPLE_LOOP;
if (flags & 2) sample->flags |= IT_SAMPLE_STEREO;
if (flags & 4) sample->flags |= IT_SAMPLE_16BIT;
sample->default_pan = 0; // 0 = don't use, or 160 = centre?
if (sample->length <= 0)
sample->flags &= ~IT_SAMPLE_EXISTS;
else if (sample->flags & IT_SAMPLE_LOOP) {
if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
sample->flags &= ~IT_SAMPLE_LOOP;
else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
sample->flags &= ~IT_SAMPLE_LOOP;
else
/* ScreamTracker seems not to save what comes after the loop end
* point, but rather to assume it is a duplicate of what comes at
* the loop start point. I am not completely sure of this though.
* It is easy to evade; simply truncate the sample.
*/
sample->length = sample->loop_end;
}
//Do we need to set all these?
sample->vibrato_speed = 0;
sample->vibrato_depth = 0;
sample->vibrato_rate = 0;
sample->vibrato_waveform = IT_VIBRATO_SINE;
return dumbfile_error(f);
}
static int it_s3m_read_sample_data(IT_SAMPLE *sample, int ffi, DUMBFILE *f)
{
long n;
long datasize = sample->length;
if (sample->flags & IT_SAMPLE_STEREO) datasize <<= 1;
sample->data = malloc(datasize * (sample->flags & IT_SAMPLE_16BIT ? 2 : 1));
if (!sample->data)
return -1;
if (sample->flags & IT_SAMPLE_STEREO) {
if (sample->flags & IT_SAMPLE_16BIT) {
for (n = 0; n < datasize; n += 2)
((short *)sample->data)[n] = dumbfile_igetw(f);
for (n = 1; n < datasize; n += 2)
((short *)sample->data)[n] = dumbfile_igetw(f);
} else {
for (n = 0; n < datasize; n += 2)
((signed char *)sample->data)[n] = dumbfile_getc(f);
for (n = 1; n < datasize; n += 2)
((signed char *)sample->data)[n] = dumbfile_getc(f);
}
} else if (sample->flags & IT_SAMPLE_16BIT)
for (n = 0; n < sample->length; n++)
((short *)sample->data)[n] = dumbfile_igetw(f);
else
for (n = 0; n < sample->length; n++)
((signed char *)sample->data)[n] = dumbfile_getc(f);
if (dumbfile_error(f))
return -1;
if (ffi != 1) {
/* Convert to signed. */
if (sample->flags & IT_SAMPLE_16BIT)
for (n = 0; n < datasize; n++)
((short *)sample->data)[n] ^= 0x8000;
else
for (n = 0; n < datasize; n++)
((signed char *)sample->data)[n] ^= 0x80;
}
return 0;
}
static int it_s3m_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, unsigned char *buffer)
{
int buflen = 0;
int bufpos = 0;
IT_ENTRY *entry;
unsigned char channel;
/* Haha, this is hilarious!
*
* Well, after some experimentation, it seems that different S3M writers
* define the format in different ways. The S3M docs say that the first
* two bytes hold the "length of [the] packed pattern", and the packed
* pattern data follow. Judging by the contents of ARMANI.S3M, packaged
* with ScreamTracker itself, the measure of length _includes_ the two
* bytes used to store the length; in other words, we should read
* (length - 2) more bytes. However, aryx.s3m, packaged with ModPlug
* Tracker, excludes these two bytes, so (length) more bytes must be
* read.
*
* Call me crazy, but I just find it insanely funny that the format was
* misunderstood in this way :D
*
* Now we can't just risk reading two extra bytes, because then we
* overshoot, and DUMBFILEs don't support backward seeking (for a good
* reason). Luckily, there is a way. We can read the data little by
* little, and stop when we have 64 rows in memory. Provided we protect
* against buffer overflow, this method should work with all sensibly
* written S3M files. If you find one for which it does not work, please
* let me know at entheh@users.sf.net so I can look at it.
*/
/* Discard the length. */
dumbfile_skip(f, 2);
if (dumbfile_error(f))
return -1;
pattern->n_rows = 0;
pattern->n_entries = 0;
/* Read in the pattern data, little by little, and work out how many
* entries we need room for. Sorry, but this is just so funny...
*/
for (;;) {
unsigned char b = buffer[buflen++] = dumbfile_getc(f);
#if 1
static const unsigned char used[8] = {0, 2, 1, 3, 2, 4, 3, 5};
channel = b & 31;
b >>= 5;
pattern->n_entries++;
if (b) {
if (buflen + used[b] >= 65536) return -1;
dumbfile_getnc(buffer + buflen, used[b], f);
buflen += used[b];
} else {
/* End of row */
if (++pattern->n_rows == 64) break;
if (buflen >= 65536) return -1;
}
#else
if (b == 0) {
/* End of row */
pattern->n_entries++;
if (++pattern->n_rows == 64) break;
if (buflen >= 65536) return -1;
} else {
static const unsigned char used[8] = {0, 2, 1, 3, 2, 4, 3, 5};
channel = b & 31;
b >>= 5;
if (b) {
pattern->n_entries++;
if (buflen + used[b] >= 65536) return -1;
dumbfile_getnc(buffer + buflen, used[b], f);
buflen += used[b];
}
}
#endif
/* We have ensured that buflen < 65536 at this point, so it is safe
* to iterate and read at least one more byte without checking.
* However, now would be a good time to check for errors reading from
* the file.
*/
if (dumbfile_error(f))
return -1;
}
pattern->entry = malloc(pattern->n_entries * sizeof(*pattern->entry));
if (!pattern->entry)
return -1;
entry = pattern->entry;
while (bufpos < buflen) {
unsigned char b = buffer[bufpos++];
#if 1
if (!(b & ~31))
#else
if (b == 0)
#endif
{
/* End of row */
IT_SET_END_ROW(entry);
entry++;
continue;
}
channel = b & 31;
if (b & 224) {
entry->mask = 0;
entry->channel = channel;
if (b & 32) {
unsigned char n = buffer[bufpos++];
if (n != 255) {
if (n == 254)
entry->note = IT_NOTE_CUT;
else
entry->note = (n >> 4) * 12 + (n & 15);
entry->mask |= IT_ENTRY_NOTE;
}
entry->instrument = buffer[bufpos++];
if (entry->instrument)
entry->mask |= IT_ENTRY_INSTRUMENT;
}
if (b & 64) {
entry->volpan = buffer[bufpos++];
if (entry->volpan != 255)
entry->mask |= IT_ENTRY_VOLPAN;
}
if (b & 128) {
entry->effect = buffer[bufpos++];
entry->effectvalue = buffer[bufpos++];
if (entry->effect != 255) {
entry->mask |= IT_ENTRY_EFFECT;
if (entry->effect == IT_BREAK_TO_ROW)
entry->effectvalue -= (entry->effectvalue >> 4) * 6;
}
/** WARNING: ARGH! CONVERT TEH EFFECTS!@~ */
}
entry++;
}
}
ASSERT(entry == pattern->entry + pattern->n_entries);
return 0;
}
/** WARNING: this is duplicated in itread.c - also bad practice to use the same struct name unless they are unified in a header */
/* Currently we assume the sample data are stored after the sample headers in
* module files. This assumption may be unjustified; let me know if you have
* trouble.
*/
#define IT_COMPONENT_INSTRUMENT 1
#define IT_COMPONENT_PATTERN 2
#define IT_COMPONENT_SAMPLE 3
typedef struct IT_COMPONENT
{
unsigned char type;
unsigned char n;
long offset;
short sampfirst; /* component[sampfirst] = first sample data after this */
short sampnext; /* sampnext is used to create linked lists of sample data */
}
IT_COMPONENT;
static int it_component_compare(const void *e1, const void *e2)
{
return ((const IT_COMPONENT *)e1)->offset -
((const IT_COMPONENT *)e2)->offset;
}
static DUMB_IT_SIGDATA *it_s3m_load_sigdata(DUMBFILE *f)
{
DUMB_IT_SIGDATA *sigdata;
int flags, cwtv, ffi;
int default_pan_present;
IT_COMPONENT *component;
int n_components = 0;
int n;
unsigned char *buffer;
sigdata = malloc(sizeof(*sigdata));
if (!sigdata) return NULL;
dumbfile_getnc(sigdata->name, 28, f);
sigdata->name[28] = 0;
if (dumbfile_getc(f) != 0x1A || dumbfile_getc(f) != 16) {
free(sigdata);
return NULL;
}
dumbfile_skip(f, 2);
sigdata->song_message = NULL;
sigdata->order = NULL;
sigdata->instrument = NULL;
sigdata->sample = NULL;
sigdata->pattern = NULL;
sigdata->midi = NULL;
sigdata->checkpoint = NULL;
sigdata->n_orders = dumbfile_igetw(f);
sigdata->n_instruments = 0;
sigdata->n_samples = dumbfile_igetw(f);
sigdata->n_patterns = dumbfile_igetw(f);
if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_samples > 256 || sigdata->n_patterns > 256) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
sigdata->order = malloc(sigdata->n_orders);
if (!sigdata->order) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (sigdata->n_samples) {
sigdata->sample = malloc(sigdata->n_samples * sizeof(*sigdata->sample));
if (!sigdata->sample) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < sigdata->n_samples; n++)
sigdata->sample[n].data = NULL;
}
if (sigdata->n_patterns) {
sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
if (!sigdata->pattern) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < sigdata->n_patterns; n++)
sigdata->pattern[n].entry = NULL;
}
flags = dumbfile_igetw(f);
+ flags = flags;
cwtv = dumbfile_igetw(f);
if (cwtv == 0x1300) {
/** WARNING: volume slides on every frame */
}
ffi = dumbfile_igetw(f);
/** WARNING: which ones? */
sigdata->flags = IT_STEREO | IT_OLD_EFFECTS | IT_COMPATIBLE_GXX;
if (dumbfile_mgetl(f) != DUMB_ID('S','C','R','M')) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
sigdata->global_volume = dumbfile_getc(f) << 1;
sigdata->speed = dumbfile_getc(f);
if (sigdata->speed == 0) sigdata->speed = 6; // Should we? What about tempo?
sigdata->tempo = dumbfile_getc(f);
/*master_volume = */dumbfile_getc(f); // 7 bits; +128 for stereo
//what do we do with master_volume? it's not the same as mixing volume...
sigdata->mixing_volume = 48;
/* Skip GUS Ultra Click Removal byte. */
dumbfile_getc(f);
default_pan_present = dumbfile_getc(f);
dumbfile_skip(f, 8);
/* Skip Special Custom Data Pointer. */
/** WARNING: investigate this? */
dumbfile_igetw(f);
/* Channel settings for 32 channels, 255=unused, +128=disabled */
{
int i;
for (i = 0; i < 32; i++) {
int c = dumbfile_getc(f);
if (!(c & (128 | 16))) { /* +128=disabled, +16=Adlib */
sigdata->channel_volume[i] = 64;
sigdata->channel_pan[i] = c & 8 ? 12 : 3;
/** WARNING: ah, but it should be 7 for mono... */
} else {
/** WARNING: this could be improved if we support channel muting... */
sigdata->channel_volume[i] = 0;
sigdata->channel_pan[i] = 7;
}
}
}
/* Orders, byte each, length = sigdata->n_orders (should be even) */
dumbfile_getnc(sigdata->order, sigdata->n_orders, f);
sigdata->restart_position = 0;
component = malloc(768*sizeof(*component));
if (!component) {
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < sigdata->n_samples; n++) {
component[n_components].type = IT_COMPONENT_SAMPLE;
component[n_components].n = n;
component[n_components].offset = dumbfile_igetw(f) << 4;
component[n_components].sampfirst = -1;
n_components++;
}
for (n = 0; n < sigdata->n_patterns; n++) {
long offset = dumbfile_igetw(f) << 4;
if (offset) {
component[n_components].type = IT_COMPONENT_PATTERN;
component[n_components].n = n;
component[n_components].offset = offset;
component[n_components].sampfirst = -1;
n_components++;
} else {
/** WARNING: Empty 64-row pattern ... ? (this does happen!) */
sigdata->pattern[n].n_rows = 64;
sigdata->pattern[n].n_entries = 0;
}
}
qsort(component, n_components, sizeof(IT_COMPONENT), &it_component_compare);
/* I found a really dumb S3M file that claimed to contain default pan
* data but didn't contain any. Programs would load it by reading part of
* the first instrument header, assuming the data to be default pan
* positions, and then rereading the instrument module. We cannot do this
* without obfuscating the file input model, so we insert an extra check
* here that we won't overrun the start of the first component.
*/
if (default_pan_present == 252 && component[0].offset >= dumbfile_pos(f) + 32) {
/* Channel default pan positions */
int i;
for (i = 0; i < 32; i++) {
int c = dumbfile_getc(f);
if (c & 32)
sigdata->channel_pan[i] = c & 15;
}
}
{
int i;
for (i = 0; i < 32; i++) {
sigdata->channel_pan[i] -= (sigdata->channel_pan[i] & 8) >> 3;
sigdata->channel_pan[i] = ((int)sigdata->channel_pan[i] << 5) / 7;
}
}
sigdata->pan_separation = 128;
if (dumbfile_error(f)) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
buffer = malloc(65536);
if (!buffer) {
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
for (n = 0; n < n_components; n++) {
long offset;
int m;
if (it_seek(f, component[n].offset)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
switch (component[n].type) {
case IT_COMPONENT_PATTERN:
if (it_s3m_read_pattern(&sigdata->pattern[component[n].n], f, buffer)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
break;
case IT_COMPONENT_SAMPLE:
if (it_s3m_read_sample_header(&sigdata->sample[component[n].n], &offset, f)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (sigdata->sample[component[n].n].flags & IT_SAMPLE_EXISTS) {
short *sample;
for (m = n + 1; m < n_components; m++)
if (component[m].offset > offset)
break;
m--;
sample = &component[m].sampfirst;
while (*sample >= 0 && component[*sample].offset <= offset)
sample = &component[*sample].sampnext;
component[n].sampnext = *sample;
*sample = n;
component[n].offset = offset;
}
}
m = component[n].sampfirst;
while (m >= 0) {
if (it_seek(f, component[m].offset)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
if (it_s3m_read_sample_data(&sigdata->sample[component[m].n], ffi, f)) {
free(buffer);
free(component);
_dumb_it_unload_sigdata(sigdata);
return NULL;
}
m = component[m].sampnext;
}
}
free(buffer);
free(component);
_dumb_it_fix_invalid_orders(sigdata);
return sigdata;
}
DUH *dumb_read_s3m_quick(DUMBFILE *f)
{
sigdata_t *sigdata;
DUH_SIGTYPE_DESC *descptr = &_dumb_sigtype_it;
sigdata = it_s3m_load_sigdata(f);
if (!sigdata)
return NULL;
{
const char *tag[1][2];
tag[0][0] = "TITLE";
tag[0][1] = (const char *) ((DUMB_IT_SIGDATA *)sigdata)->name;
return make_duh(-1, 1, (const char *const (*)[2])tag, 1, &descptr, &sigdata);
}
}
diff --git a/src/libs/sfl/sfldir.c b/src/libs/sfl/sfldir.c
index 9659c480..07c5652b 100644
--- a/src/libs/sfl/sfldir.c
+++ b/src/libs/sfl/sfldir.c
@@ -1,1544 +1,1544 @@
/* ----------------------------------------------------------------<Prolog>-
Name: sfldir.c
Title: Directory access functions
Package: Standard Function Library (SFL)
Written: 1996/04/02 iMatix SFL project team <sfl@imatix.com>
Revised: 2000/01/19
Copyright: Copyright (c) 1996-2000 iMatix Corporation
License: This is free software; you can redistribute it and/or modify
it under the terms of the SFL License Agreement as provided
in the file LICENSE.TXT. This software is distributed in
the hope that it will be useful, but without any warranty.
------------------------------------------------------------------</Prolog>-*/
#include "prelude.h" /* Universal header file */
#include "sfldate.h" /* Date handling functions */
#include "sfluid.h" /* Uid/gid functions */
#include "sflstr.h" /* String functions */
#include "sfllist.h" /* Linked-list functions */
#include "sflmem.h" /* Memory allocation functions */
#include "sflnode.h" /* Linked-list functions */
#include "sflfile.h" /* File-access functions */
#include "sflcons.h" /* Console display functions */
#include "sflprint.h" /* snprintf functions */
#include "sfldir.h" /* Prototypes for functions */
/* Static variables used globally in this source file only */
static char
*sort_key;
/* Function prototypes */
static Bool populate_entry (DIRST *dir);
static time_t get_six_months_ago (void);
static char *format_mode (DIRST *dir);
static char *format_name (DIRST *dir, Bool full);
static char *format_time (DIRST *dir);
static Bool compare_dir (LIST *p1, LIST *p2);
static Bool path_delimiter (char delim);
/* ---------------------------------------------------------------------[<]-
Function: open_dir
Synopsis:
Creates a directory stream and returns the first entry in the directory.
The order of entries is arbitrary, and it is undefined whether you will
get entries like '.' and '..' or not. Returns TRUE if something was
found, else FALSE. If TRUE, fills-in the values in the directory stream
block. Use the same directory stream block for the read_dir and
close_dir() functions.
You must supply a DIRST block when calling open_dir(). If you do not
supply a dir_name (i.e. it is NULL or ""), open_dir() assumes you want
to read from the current working directory. You must call close_dir()
after an open_dir(), even if it fails.
The strings in DIRST all point to static areas that may change after a
further call to read_dir. If you need persistent data (i.e. because
you want to collect a set of DIRSTs and then sort them, call fix_dir()
after each call to open_dir and read_dir. You should then call
free_dir() to release each DIRST when you are finished.
---------------------------------------------------------------------[>]-*/
Bool
open_dir (
DIRST *dir,
const char *dir_name)
{
char
*dir_spec, /* Directory to search through */
*dir_spec_end; /* Points to NULL in dir_spec */
ASSERT (dir != NULL);
memset (dir, 0, sizeof (DIRST));
/* Copy and prepare the directory specification */
dir_spec = mem_alloc (NAME_MAX);
if (dir_name == NULL || *dir_name == 0)
strcpy (dir_spec, DEFAULT_DIR);
else
strcpy (dir_spec, dir_name);
#if (defined (MSDOS_FILESYSTEM))
strconvch (dir_spec, '/', '\\');
#endif
/* Remove a trailing slash from the directory name */
dir_spec_end = dir_spec + strlen (dir_spec);
if (dir_spec_end [-1] == PATHEND)
{
dir_spec_end [-1] = '\0';
dir_spec_end--;
}
/* Open directory stream or find first directory entry */
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
if (strnull (dir_spec))
strcpy (dir_spec, "/");
# if (defined (__OS2__))
if (dir_spec_end [-1] == ':') /* Special case d: to d:\ */
strcat (dir_spec, "\\");
# endif
if ((dir-> _dir_handle = opendir (dir_spec)) == NULL)
#elif (defined (WIN32))
strcat (dir_spec, "\\*");
if ((dir-> _dir_handle = FindFirstFile (dir_spec, &dir-> _dir_entry))
== INVALID_HANDLE_VALUE)
#elif (defined (_MSC_VER))
strcat (dir_spec, "\\*.*");
if ((dir-> _dir_handle = _dos_findfirst (dir_spec, _A_NORMAL | _A_SUBDIR,
&dir-> _dir_entry)) != 0)
#elif (defined (__TURBOC__) || defined (__DJGPP__))
strcat (dir_spec, "\\*.*");
if (findfirst (dir_spec, &dir-> _dir_entry, 255 - FA_LABEL) == -1)
#endif
{
mem_free (dir_spec);
return (FALSE); /* Could not open directory */
}
/* Save the directory name in directory stream structure */
#if (defined (__MSDOS__) || defined (__OS2__))
*dir_spec_end = '\0'; /* Kill the \*.* again */
#endif
dir-> dir_name = dir_spec; /* Now owned by DIRST structure */
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
/* Under UNIX & VMS we still need to fetch the first file entry */
return (read_dir (dir));
#elif (defined (WIN32))
/* Under Win32 we have read an entry, so return those values */
return (populate_entry (dir));
#elif (defined (_MSC_VER))
/* Under MSC we have read an entry, so return those values */
return (populate_entry (dir));
#elif (defined (__TURBOC__) || defined (__DJGPP__))
/* Under Borland C we have read an entry, so return those values */
return (populate_entry (dir));
#else
return (FALSE); /* Directory access not supported */
#endif
}
/* -------------------------------------------------------------------------
* populate_entry -- internal
*
* Sets the various public fields in the directory stream from the system-
* specific values in the private fields. Returns TRUE if okay, FALSE if
* there was a problem getting the file status information.
*/
static Bool
populate_entry (DIRST *dir)
{
#if (defined (WIN32))
static char
*default_user = "user";
#else
char
*full_path; /* Full path name of the file */
struct stat
stat_buf; /* File status structure */
int
rc;
#endif
ASSERT (dir != NULL);
if (dir-> _fixed)
free_dir (dir); /* De-allocate old strings if reqd */
/* Get name of file from directory structure */
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
dir-> file_name = dir-> _dir_entry-> d_name;
#elif (defined (WIN32))
dir-> file_name = dir-> _dir_entry.cFileName;
#elif (defined (_MSC_VER))
dir-> file_name = dir-> _dir_entry.name;
#elif (defined (__TURBOC__) || defined (__DJGPP__))
dir-> file_name = dir-> _dir_entry.ff_name;
#endif
#if (defined (__UNIX__) || defined (MSDOS_FILESYSTEM))
/* If the filename is . or .., skip this entry and do the next. We */
/* use a little bit of a recursive call to make this code simple. */
if (dir-> file_name [0] == '.' && (dir-> file_name [1] == '\0'
|| (dir-> file_name [1] == '.' && dir-> file_name [2] == '\0')))
return (read_dir (dir));
#endif
/* Prepare full path and get file status information. Most systems have
* some kind of stat() function; we call this, even if similar info is
* already available in the _dir_entry structures. Except for Win32
* where we use the native Win32 API to support compilers which may not
* have all the C wrapper functions (e.g. RSXNT).
*/
#if (defined (WIN32))
/* Get file info using Win32 calls */
{
unsigned long thi, tlo;
double dthi, dtlo;
double secs_since_1601;
double delta = 11644473600.;
double two_to_32 = 4294967296.;
thi = dir-> _dir_entry.ftLastWriteTime.dwHighDateTime;
tlo = dir-> _dir_entry.ftLastWriteTime.dwLowDateTime;
dthi = (double) thi;
dtlo = (double) tlo;
secs_since_1601 = (dthi * two_to_32 + dtlo) / 1.0e7;
dir-> file_time = (unsigned long) (secs_since_1601 - delta);
dir-> file_size = dir->_dir_entry.nFileSizeLow;
dir-> file_mode = 0;
if (dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
dir-> file_mode |= S_IFDIR;
else
dir-> file_mode |= S_IFREG;
if (!(dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN))
dir-> file_mode |= S_IRUSR;
if (!(dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
dir-> file_mode |= S_IWUSR;
dir-> file_nlink = 1;
dir-> owner = NULL;
dir-> group = NULL;
}
#else
full_path = xstrcpy (NULL, dir-> dir_name, "/", dir-> file_name, NULL);
rc = stat (full_path , &stat_buf);
if (rc == -1){
/* might be a broken symbolic link, in that case just read it. the
* application will fail when it tries to read data from the file.
*/
#if !defined(WII) && !defined(MINPSPW) && !defined(PS3) && !defined(XENON)
rc = lstat(full_path, &stat_buf);
#endif
}
mem_free (full_path);
if (rc == -1)
return (FALSE);
dir-> file_time = stat_buf.st_mtime; /* Modification time */
dir-> file_size = stat_buf.st_size; /* Size in bytes */
dir-> file_mode = stat_buf.st_mode; /* UNIX-ish permissions */
dir-> file_nlink = stat_buf.st_nlink; /* Number of links to file */
#if !defined(WII) && !defined(MINPSPW) && !defined(PS3) && !defined(XENON)
/* Get owner and group names */
dir-> owner = get_uid_name (stat_buf.st_uid);
dir-> group = get_gid_name (stat_buf.st_gid);
#endif
#endif
/* Prepare DOS-ish permission bits */
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
dir-> file_attrs = 0;
if ((stat_buf.st_mode & S_IRUSR) == 0)
dir-> file_attrs |= ATTR_HIDDEN;
if ((stat_buf.st_mode & S_IWUSR) == 0)
dir-> file_attrs |= ATTR_RDONLY;
if ((stat_buf.st_mode & S_IFDIR) != 0)
dir-> file_attrs |= ATTR_SUBDIR;
#elif (defined (WIN32))
dir-> file_attrs = 0;
if (dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
dir-> file_attrs |= ATTR_SUBDIR;
if (dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
dir-> file_attrs |= ATTR_RDONLY;
if (dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
dir-> file_attrs |= ATTR_HIDDEN;
if (dir-> _dir_entry.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
dir-> file_attrs |= ATTR_SYSTEM;
dir-> owner = dir-> group = default_user;
#elif (defined (_MSC_VER))
dir-> file_attrs = (byte) dir-> _dir_entry.attrib & ATTR_MASK;
#elif (defined (__TURBOC__) || defined (__DJGPP__))
dir-> file_attrs = (byte) dir-> _dir_entry.ff_attrib & ATTR_MASK;
#endif
return (TRUE); /* No errors */
}
/* ---------------------------------------------------------------------[<]-
Function: read_dir
Synopsis:
Reads the next entry from the directory stream. Returns TRUE if there
was more data to read; returns FALSE if there was nothing more to read.
Updates the fields in the directory structure when it returns TRUE.
The strings in DIRST all point to static areas that may change after a
further call to read_dir. If you need persistent data (i.e. because
you want to collect a set of DIRSTs and then sort them, call fix_dir()
after each call to open_dir and read_dir. You should then call
free_dir() to release each DIRST when you are finished.
---------------------------------------------------------------------[>]-*/
Bool
read_dir (
DIRST *dir)
{
ASSERT (dir != NULL);
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
if ((dir-> _dir_entry =
(struct Dirent *) readdir (dir-> _dir_handle)) != NULL)
return (populate_entry (dir));
else
#elif (defined (WIN32))
if (FindNextFile (dir-> _dir_handle, &dir-> _dir_entry))
return (populate_entry (dir));
else
#elif (defined (_MSC_VER))
if (_dos_findnext (&dir-> _dir_entry) == 0)
return (populate_entry (dir));
else
#elif (defined (__TURBOC__) || defined (__DJGPP__))
if (findnext (&dir-> _dir_entry) == 0)
return (populate_entry (dir));
else
#endif
return (FALSE);
}
/* ---------------------------------------------------------------------[<]-
Function: close_dir
Synopsis:
Close the directory stream, and free any allocated memory. You should
call this function when you are done reading a directory, or you will
get memory leaks. Returns TRUE if okay, FALSE if there was an error.
---------------------------------------------------------------------[>]-*/
Bool
close_dir (
DIRST *dir)
{
Bool
rc;
ASSERT (dir != NULL);
mem_free (dir-> dir_name); /* Free dynamically-allocated name */
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
ASSERT (dir-> _dir_handle);
rc = (closedir (dir-> _dir_handle) == 0);
#elif (defined (WIN32))
rc = FindClose (dir-> _dir_handle);
#elif (defined (_MSC_VER))
rc = TRUE; /* No function to close a dir */
#elif (defined (__TURBOC__) || defined (__DJGPP__))
rc = TRUE; /* No function to close a dir */
#else
rc = FALSE; /* Directory access not supported */
#endif
return (rc);
}
/* ---------------------------------------------------------------------[<]-
Function: format_dir
Synopsis:
Formats the directory entry information using the same conventions as
the UNIX 'ls -l' command. Returns a static buffer that contains the
the formatted string. If the full argument is TRUE, adds cosmetic
hints to indicate the file type; for instance '/' if the file is a
directory, '*' if it is executable.
---------------------------------------------------------------------[>]-*/
char *
format_dir (
DIRST *dir,
Bool full)
{
static char
buffer [LINE_MAX]; /* Formatted directory entry */
ASSERT (dir != NULL);
snprintf (buffer, sizeof (buffer),
- "%s %3d %-8.8s %-8.8s %8ld %s %s",
+ "%s %3lu %-8.8s %-8.8s %8ld %s %s",
format_mode (dir),
dir-> file_nlink,
dir-> owner,
dir-> group,
(long) dir-> file_size,
format_time (dir),
format_name (dir, full)
);
return (buffer);
}
/* -------------------------------------------------------------------------
* format_mode -- internal
*
* Returns a static string holding the ASCII representation of the UNIX-ish
* permission bits for the directory entry specified.
*/
static char *
format_mode (
DIRST *dir)
{
static char
buffer [11], /* duuugggooo + null */
*bufptr; /* Pointer into buffer */
dbyte
mode = dir-> file_mode; /* File mode bits */
int
field; /* User, group, other */
bufptr = buffer;
*bufptr++ = ((mode & S_IFDIR) ? 'd' : '-');
for (field = 0; field < 3; field++)
{
*bufptr++ = ((mode & (S_IRUSR >> (field * 3))) ? 'r' : '-');
*bufptr++ = ((mode & (S_IWUSR >> (field * 3))) ? 'w' : '-');
*bufptr = ((mode & (S_IXUSR >> (field * 3))) ? 'x' : '-');
#if (defined (S_ISUID))
if (field == 0 && (mode & S_ISUID))
*bufptr = (*bufptr == 'x' ? 's' : 'S');
else
if (field == 1 && (mode & S_ISGID))
*bufptr = (*bufptr == 'x' ? 's' : 'S');
# if (defined (S_ISVTX))
else
if (field == 2 && (mode & S_ISVTX))
*bufptr = (*bufptr == 'x' ? 't' : 'T');
# endif
#endif
++bufptr;
}
*bufptr = '\0';
return (buffer);
}
/* -------------------------------------------------------------------------
* format_name -- internal
*
* Returns a static string holding the cleaned-up filename for the directory
* entry specified. Replaces any control characters by an octal string
* and appends '/' if the entry is a directory, or '*' if it is executable,
* if the full argument is TRUE.
*/
static char *
format_name (DIRST *dir, Bool full)
{
static char
buffer [NAME_MAX + 1],
*fromptr,
*bufptr;
bufptr = buffer;
for (fromptr = dir-> file_name; *fromptr; bufptr++, fromptr++)
{
*bufptr = *fromptr;
if ((byte) *bufptr < ' ')
{
sprintf (bufptr, "\\%03o", (byte) *fromptr);
bufptr += strlen (bufptr) - 1;
}
}
if (full)
{
if (dir-> file_mode & S_IFDIR)
*bufptr++ = '/';
else
if (dir-> file_mode & S_IXUSR)
*bufptr++ = '*';
}
*bufptr = '\0';
return (buffer);
}
/* -------------------------------------------------------------------------
* format_time -- internal
*
* Returns a static string holding the ASCII representation of the date and
* time for the specified directory entry. The format of the date and time
* depends on whether the file is older than 6 months, roughly:
*
* Oct 9 1995 if older than 6 months
* Jan 12 09:55 if not older than 6 months
*/
static char *
format_time (DIRST *dir)
{
static char
buffer [13], /* Returned string */
*months = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
static time_t
six_months_ago = 0;
struct tm
*file_time;
if (six_months_ago == 0)
six_months_ago = get_six_months_ago ();
file_time = safe_localtime (&dir-> file_time);
strncpy (buffer, months + file_time-> tm_mon * 4, 4);
if (dir-> file_time < six_months_ago
|| dir-> file_time > time (NULL))
snprintf (buffer + 3, sizeof (buffer) - 3,
" %2d %4d", file_time-> tm_mday,
file_time-> tm_year + 1900);
else
snprintf (buffer + 3, sizeof (buffer) - 3,
" %2d %02d:%02d", file_time-> tm_mday,
file_time-> tm_hour,
file_time-> tm_min);
return (buffer);
}
/* -------------------------------------------------------------------------
* get_six_months_ago -- internal
*
* Returns system clock 6 months ago.
*/
static time_t
get_six_months_ago ()
{
int
count,
year,
month;
long
days;
time_t
time_val;
struct tm
*time_now;
time_val = time (NULL);
time_now = safe_localtime (&time_val);
month = time_now-> tm_mon + 1;
year = time_now-> tm_year;
days = 0;
for (count = 0; count < 6; count++)
{
if (--month < 1) /* Start with last month */
{
month = 12;
year--;
}
switch (month)
{
case 2: /* Feb */
days += leap_year (year)? 29: 28;
break;
case 1: /* Jan */
case 3: /* Mar */
case 5: /* May */
case 7: /* Jul */
case 8: /* Aug */
case 10: /* Oct */
case 12: /* Dec */
days++;
case 4: /* Apr */
case 6: /* Jun */
case 9: /* Sep */
case 11: /* Nov */
days += 30;
}
}
/* 60 * 60 * 24 = 86400 sec / day */
return (time (NULL) - (long) (86400L * days));
}
/* ---------------------------------------------------------------------[<]-
Function: fix_dir
Synopsis:
Converts all strings in the DIRST into permenant values, by allocating
heap memory for each string. You must call this function if you intend
to keep a set of DIRSTs, for searching or sorting. You do not need to
call fix_dir() if you handle each call to read_dir() independently.
If you use fix_dir(), you must call free_dir() for each DIRST when you
terminate. Returns 0 if okay, -1 if there was insufficient memory or
another fatal error.
---------------------------------------------------------------------[>]-*/
int
fix_dir (DIRST *dir)
{
char
*owner,
*group,
*file_name;
/* Allocate each string */
owner = mem_strdup (dir-> owner);
group = mem_strdup (dir-> group);
file_name = mem_strdup (dir-> file_name);
/* If all okay, assign new strings and indicate everything okay */
if (owner && group && file_name)
{
dir-> owner = owner;
dir-> group = group;
dir-> file_name = file_name;
dir-> _fixed = TRUE;
return (0);
}
else
{
/* Otherwise patch things back the way they were */
if (owner)
mem_free (owner);
if (group)
mem_free (group);
if (file_name)
mem_free (file_name);
return (-1);
}
}
/* ---------------------------------------------------------------------[<]-
Function: free_dir
Synopsis:
Frees all strings used in the DIRST. You should call this function to
free space allocated by fix_dir(). If you try to call free_dir() for a
DIRST that was not fixed, you will get an error feedback, and (if you
compiled with DEBUG defined) an assertion fault. Returns 0 if okay,
-1 if there was an error. After a call to free_dir(), do not try to
access the strings in DIRST; they are all set to point to an empty
string.
---------------------------------------------------------------------[>]-*/
int
free_dir (DIRST *dir)
{
static char
*empty = "";
ASSERT (dir-> _fixed);
if (dir-> _fixed)
{
/* Free allocated strings */
mem_free (dir-> owner);
mem_free (dir-> group);
mem_free (dir-> file_name);
/* Now point the strings to an empty string */
dir-> owner = empty;
dir-> group = empty;
dir-> file_name = empty;
/* And mark the DIRST as no longer 'fixed' */
dir-> _fixed = FALSE;
return (0);
}
else
return (-1);
}
/* ---------------------------------------------------------------------[<]-
Function: load_dir_list
Synopsis:
Loads and sorts the contents of a directory. Returns a NODE pointer to
a linked list containing the directory entries. Each node is a FILEINFO
structure (mapped onto a NODE structure for purposes of manipulating the
linked list). You can ask for the directory list to be sorted in various
ways; in this case subdirectory entries are always sorted first. To
specify the sort order you pass a string consisting of one or more of
these characters, which are then used in order:
<TABLE>
n Sort by ascending name.
N Sort by descending name.
x Sort by ascending extension.
X Sort by descending extension.
t Sort by ascending time and date.
T Sort by descending time and date.
s Sort by ascending size.
S Sort by descending size.
</TABLE>
If the sort string is NULL, no sort is carried out.
---------------------------------------------------------------------[>]-*/
NODE *
load_dir_list (
const char *dir_name,
const char *sort)
{
NODE
*file_list; /* File list head */
DIRST
dir;
Bool
rc;
int
nbr_files = 0;
file_list = mem_alloc (sizeof (NODE));
if (!file_list)
return (NULL);
node_reset (file_list); /* Initialise file list */
/* Load directory */
rc = open_dir (&dir, dir_name);
while (rc)
{
add_dir_list (file_list, &dir);
nbr_files++;
rc = read_dir (&dir);
}
close_dir (&dir);
if (sort && nbr_files > 1)
sort_dir_list (file_list, sort);
return (file_list);
}
/* ---------------------------------------------------------------------[<]-
Function: free_dir_list
Synopsis:
Frees all FILELIST blocks in the specified linked list.
---------------------------------------------------------------------[>]-*/
void
free_dir_list (NODE *file_list)
{
ASSERT (file_list);
while (file_list-> next != file_list)
{
free_dir (&((FILEINFO *) file_list-> next)-> dir);
node_destroy (file_list-> next);
}
mem_free (file_list);
}
/* ---------------------------------------------------------------------[<]-
Function: sort_dir_list
Synopsis: Sorts the directory list as specified. Returns the number of
items in the list. To specify the sort order you pass a string holding
one or more of these characters, which are then used in order:
<TABLE>
n Sort by ascending name.
N Sort by descending name.
x Sort by ascending extension.
X Sort by descending extension.
t Sort by ascending time and date.
T Sort by descending time and date.
s Sort by ascending size.
S Sort by descending size.
</TABLE>
---------------------------------------------------------------------[>]-*/
void
sort_dir_list (NODE *file_list, const char *sort)
{
ASSERT (file_list);
sort_key = (char *) sort;
list_sort (file_list, compare_dir);
}
/* ---------------------------------------------------------------------[<]-
Function: add_dir_list
Synopsis: Adds a node to the specified directory list. Returns the
address of the new node, or NULL if there was insufficient memory.
---------------------------------------------------------------------[>]-*/
FILEINFO *
add_dir_list (NODE *file_list, const DIRST *dir)
{
FILEINFO
*file_info;
file_info = (FILEINFO *) node_create (file_list-> prev, sizeof (FILEINFO));
if (file_info)
{
memcpy (&file_info-> dir, dir, sizeof (DIRST));
fix_dir (&file_info-> dir);
file_info-> directory = (dir-> file_attrs & ATTR_SUBDIR) != 0;
}
return (file_info);
}
/* -------------------------------------------------------------------------
* compare_dir -- internal
*
* Compare two file info structures and return TRUE if SWAP is needed.
* Uses the global variable sort_key to determine sorting method.
*/
static Bool
compare_dir (LIST *p1, LIST *p2)
{
Bool
end = FALSE,
swap = FALSE;
char
*ext1,
*ext2,
*p;
int
comp;
long
date1,
date2,
time1,
time2;
ASSERT (p1);
ASSERT (p2);
if (((FILEINFO *) p1)-> directory != ((FILEINFO *) p2)-> directory)
return (((FILEINFO *) p2)-> directory);
for (p = sort_key;
*p != '\0'
&& end == FALSE
&& swap == FALSE;
p++)
{
switch (*p)
{
case 'n':
case 'N':
comp = lexcmp (((FILEINFO *) p1)-> dir.file_name,
((FILEINFO *) p2)-> dir.file_name);
if ((*p == 'n' && comp > 0)
|| (*p == 'N' && comp < 0))
swap = TRUE;
else
if (comp != 0)
end = TRUE;
break;
case 't':
case 'T':
/* Use date and time and not time_t for compare to minute,
not second */
date1 = timer_to_date (((FILEINFO *) p1)-> dir.file_time);
date2 = timer_to_date (((FILEINFO *) p2)-> dir.file_time);
if ((*p == 't' && date1 > date2)
|| (*p == 'T' && date1 < date2))
swap = TRUE;
else
if (date1 != date2)
end = TRUE;
else
{
time1 = timer_to_time
(((FILEINFO *) p1)-> dir.file_time) / 10000;
time2 = timer_to_time
(((FILEINFO *) p2)-> dir.file_time) / 10000;
if ((*p == 't' && time1 > time2)
|| (*p == 'T' && time1 < time2))
swap = TRUE;
else
if (time1 != time2)
end = TRUE;
}
break;
case 's':
case 'S':
if ((*p == 's' && ((FILEINFO *) p1)-> dir.file_size >
((FILEINFO *) p2)-> dir.file_size)
|| (*p == 'S' && ((FILEINFO *) p1)-> dir.file_size <
((FILEINFO *) p2)-> dir.file_size))
swap = TRUE;
else
if (((FILEINFO *) p1)-> dir.file_size
!= ((FILEINFO *) p2)-> dir.file_size)
end = TRUE;
break;
case 'x':
case 'X':
ext1 = strchr (((FILEINFO *) p1)-> dir.file_name, '.');
ext2 = strchr (((FILEINFO *) p2)-> dir.file_name, '.');
if (ext1 && ext2)
{
comp = lexcmp (ext1, ext2);
if ((*p == 'x' && comp > 0)
|| (*p == 'X' && comp < 0))
swap = TRUE;
else
if (comp != 0)
end = TRUE;
}
break;
}
}
return (swap);
}
/* ---------------------------------------------------------------------[<]-
Function: resolve_path
Synopsis: Accepts a path consisting of zero or more directory names and
optionally a filename plus extension. Removes '.' and '..' if they occur
in the path. '..' is resolved by also removing the preceding directory
name, if any. Returns a freshly-allocated string containing the
resulting path. The caller must free this string using mem_free() when
finished with it. The returned path may be empty. Under OS/2 and DOS,
treats '\' and '/' both as directory separators. A '..' directory at the
start of the path resolves into nothing. If the input path started with
'/', the returned path also does, else it does not. For compatibility
with DOS-based systems, '...' is treated as '../..', '....' as
'../../..', and so on.
---------------------------------------------------------------------[>]-*/
char *
resolve_path (
const char *old_path)
{
#if (defined (__UNIX__) || defined (MSDOS_FILESYSTEM) || defined (__VMS__))
char
*new_path, /* Newly-allocated path */
*new_ptr, /* Pointer into new_path */
last_char = '/'; /* Start of path counts as delim */
int
nbr_dots; /* Size of '..', '...' specifier */
ASSERT (old_path);
new_path = mem_strdup (old_path);
new_ptr = new_path;
while (*old_path)
{
if (path_delimiter (last_char) && *old_path == '.')
{
/* Handle one or more dots followed by a path delimiter */
nbr_dots = 0; /* Count number of dots */
while (old_path [nbr_dots] == '.')
nbr_dots++;
if (path_delimiter (old_path [nbr_dots]))
{
old_path += nbr_dots; /* Skip past dots */
if (*old_path)
old_path++; /* and past / if any */
/* Now backtrack in new path, dropping directories as */
/* many times as needed (0 or more times) */
while (nbr_dots > 1)
{
if (new_ptr > new_path + 1)
{
new_ptr--; /* Drop delimiter */
while (new_ptr > new_path)
{
if (path_delimiter (*(new_ptr - 1)))
break; /* and end after delimiter */
new_ptr--;
}
}
else
break; /* At start of name - finish */
nbr_dots--;
}
}
else
/* Handle '.something' */
last_char = *new_ptr++ = *old_path++;
}
else
last_char = *new_ptr++ = *old_path++;
}
*new_ptr = '\0'; /* Terminate string nicely */
return (new_path);
#else
return (mem_strdup (old_path)); /* Path resolution not supported */
#endif
}
static Bool
path_delimiter (char delim)
{
#if (defined (MSDOS_FILESYSTEM))
if (delim == '\\' || delim == '/' || delim == '\0')
return (TRUE);
else
#elif (defined (__UNIX__) || defined (__VMS__))
if (delim == '/' || delim == '\0')
return (TRUE);
else
#endif
return (FALSE);
}
/* ---------------------------------------------------------------------[<]-
Function: locate_path
Synopsis: Accepts a root directory and a path and locates the path with
respect to the root. If the path looks like an absolute directory,
returns the path after cleaning it up. Otherwise appends the path to
the root, and returns the result. In any case, the resulting directory
does not need to exist. Cleans-up the returned path by appending a '/'
if necessary, and resolving any '..' subpaths. The returned value is
held in a freshly-allocated string which the caller must free using
mem_free() when finished with..
---------------------------------------------------------------------[>]-*/
char *
locate_path (
const char *root,
const char *path)
{
#if (defined (__UNIX__) || defined (MSDOS_FILESYSTEM) || defined (__VMS__))
char
*new_path, /* Returned path value */
*resolved; /* and after .. resolution */
ASSERT (root);
ASSERT (path);
#if (defined (MSDOS_FILESYSTEM))
/* Under MSDOS, OS/2, or Windows we have a full path if we have any of:
* /directory
* D:/directory
* the variations of those with backslashes.
*/
if (path [0] == '\\' || path [0] == '/'
|| (isalpha (path [0]) && path [1] == ':'
&& (path [2] == '\\' || path [2] == '/')))
#else
/* Under UNIX or VMS we have a full path if the path starts with the
* directory marker.
*/
if (path [0] == PATHEND)
#endif
new_path = mem_strdup (path); /* Use path as supplied */
else
{
xstrcpy_debug ();
if (path_delimiter (strlast (root)))
new_path = xstrcpy (NULL, root, path, NULL);
else
new_path = xstrcpy (NULL, root, "/", path, NULL);
}
resolved = resolve_path (new_path);
mem_free (new_path);
/* Append slash if necessary */
if (!path_delimiter (strlast (resolved)))
{
new_path = resolved;
xstrcpy_debug ();
resolved = xstrcpy (NULL, new_path, "/", NULL);
mem_free (new_path);
}
return (resolved);
#else
return (mem_strdup (path)); /* Unknown system */
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: clean_path
Synopsis: Returns a clean directory name; i.e. resolves the path,
removes a trailing slash unless the name consists just of '/'; on a
MS-DOS file system, cleans-up a directory name consisting of a disk
specifier. The cleaned-up directory path is in a static area that is
overwritten by each call.
---------------------------------------------------------------------[>]-*/
char *
clean_path (
const char *path)
{
#if (defined (__UNIX__) || defined (MSDOS_FILESYSTEM) || defined (__VMS__))
static char
new_path [PATH_MAX + 1]; /* Returned path value */
char
*slash;
strncpy (new_path, path, PATH_MAX);
new_path [PATH_MAX] = '\0';
# if (defined (MSDOS_FILESYSTEM))
/* For DOS filesystems, use only back slashes */
strconvch (new_path, '/', '\\');
# endif
slash = strrchr (new_path, PATHEND); /* Find last slash */
# if (defined (MSDOS_FILESYSTEM))
/* If slash is last character in string, maybe squash it */
if (slash && slash [1] == '\0')
{
if (slash > new_path && slash [-1] != ':')
*slash = '\0';
}
else /* Turn X: into X:\ */
if (new_path [1] == ':' && new_path [2] == '\0')
{
new_path [2] = '\\';
new_path [3] = '\0';
}
# else
/* If slash is last character in string, maybe squash it */
if (slash && slash [1] == '\0')
if (slash > new_path)
*slash = '\0';
# endif
return (new_path);
#else
return ((char *) path);
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: get_curdir
Synopsis: Returns a buffer containing the current working directory.
This buffer is allocated using the mem_alloc() function and should be
freed using mem_free() when no longer needed. Returns NULL if there
was insufficient memory to allocate the buffer, or if the system does
not provide the current working directory information. Under Windows,
replaces backslash characters by the UNIX-like slash. Under OpenVMS,
returns directory name in POSIX format. Note that the directory name
always ends in a slash (e.g. 'C:/' or 'C:/subdir/').
---------------------------------------------------------------------[>]-*/
char *
get_curdir (void)
{
char
*curdir; /* String we get from the OS */
curdir = mem_alloc (PATH_MAX + 1);
#if (defined (__UNIX__) || defined (__OS2__))
getcwd (curdir, PATH_MAX);
#elif (defined (__VMS__))
getcwd (curdir, PATH_MAX, 0);
#elif (defined (WIN32))
GetCurrentDirectory (PATH_MAX, curdir);
strconvch (curdir, '\\', '/');
#elif (defined (MSDOS_FILESYSTEM))
getcwd (curdir, PATH_MAX);
strconvch (curdir, '\\', '/');
#else
strclr (curdir);
#endif
/* The directory must always end in a slash */
if (strlast (curdir) != '/')
strcat (curdir, "/");
return (curdir);
}
/* ---------------------------------------------------------------------[<]-
Function: set_curdir
Synopsis: Sets the current working directory as specified. Returns 0
if the directory path was found; -1 if there was an error. Under
Windows, replaces '/' by '\' before changing directory, and switches
to the specified disk if the path starts with a letter and ':'. Does
nothing if the path is NULL or empty.
---------------------------------------------------------------------[>]-*/
int
set_curdir (
const char *path)
{
int
feedback = 0;
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
if (path && *path)
feedback = chdir (path);
#elif (defined (MSDOS_FILESYSTEM))
char
*copy_path = mem_strdup (path);
if (path == NULL || *path == '\0')
return (0); /* Do nothing if path is empty */
/* MS-DOS compilers generally require a two-step process */
strconvch (copy_path, '/', '\\');
# if (defined (WIN32))
/* The drive letter does not need to be changed separately in Win32. */
feedback = !SetCurrentDirectory (copy_path);
# elif (defined (__TURBOC__))
feedback = chdir (copy_path);
if (feedback == 0 && isalpha (path [0]) && path [1] == ':')
setdisk (toupper (path [0]) - 'A');
# elif (defined (__LCC__))
feedback = chdir (copy_path);
if (feedback == 0 && isalpha (path [0]) && path [1] == ':')
chdrive (toupper (path [0]) - 'A' + 1);
# elif (defined (_MSC_VER))
feedback = _chdir (copy_path);
if (feedback == 0 && isalpha (path [0]) && path [1] == ':')
_chdrive (toupper (path [0]) - 'A' + 1);
# endif
mem_strfree (&copy_path);
#else
feedback = -1;
#endif
return (feedback);
}
/* ---------------------------------------------------------------------[<]-
Function: file_matches
Synopsis: Returns TRUE if the filename matches the pattern. The pattern
is a character string that can contain these 'wildcard' characters:
---------------------------------------------------------------------[>]-*/
Bool
file_matches (
const char *filename,
const char *pattern)
{
char
*pattern_ptr, /* Points to pattern */
*filename_ptr; /* Points to filename */
filename_ptr = (char *) filename; /* Start comparing file name */
pattern_ptr = (char *) pattern; /* Start comparing file name */
FOREVER
{
/* If we came to the end of the pattern and the filename, we have */
/* successful match. */
if (*pattern_ptr == '\0' && *filename_ptr == '\0')
return (TRUE); /* Have a match */
/* Otherwise, end of either is a failed match */
if (*pattern_ptr == '\0' || *filename_ptr == '\0')
return (FALSE); /* Match failed */
/* If the pattern character is '?', then we matched a char */
if (*pattern_ptr == '?'
#if (defined (NAMEFOLD))
|| toupper (*pattern_ptr) == toupper (*filename_ptr))
#else
|| *pattern_ptr == *filename_ptr)
#endif
{
pattern_ptr++;
filename_ptr++;
}
else
/* If we have a '*', match as much of the filename as we can */
if (*pattern_ptr == '*')
{
pattern_ptr++; /* Try to match following char */
while (*filename_ptr && *filename_ptr != *pattern_ptr)
filename_ptr++;
}
else
return (FALSE); /* Match failed */
}
}
/* ---------------------------------------------------------------------[<]-
Function: make_dir
Synopsis: Create a new directory. Returns 0 if the directory was created;
-1 if there was an error. Under Windows and OpenVMS, accepts directory
names with '/'. Will create multiple levels of directory if required.
---------------------------------------------------------------------[>]-*/
int
make_dir (
const char *path_to_create)
{
char
*path,
*slash;
int
rc = 0;
path = mem_strdup (path_to_create); /* Working copy */
#if (defined (MSDOS_FILESYSTEM))
strconvch (path, '/', '\\');
/* Handle \\system\drive specially */
if (strprefixed (path, "\\\\")) /* Network drive name? */
{
slash = strchr (path + 2, '\\');
if (slash)
slash = strchr (slash + 1, '\\');
}
else
#endif
slash = strchr (path + 1, PATHEND);
/* Create each component of directory as required */
FOREVER /* Create any parent directories */
{
if (slash)
*slash = '\0'; /* Cut at slash */
if (!file_is_directory (path))
{
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
rc = mkdir (path, 0775); /* User RWE Group RWE World RE */
#elif (defined (WIN32))
if (CreateDirectory (path, NULL))
rc = 0;
else
rc = -1;
#elif (defined (MSDOS_FILESYSTEM))
# if (defined (__DJGPP__))
rc = mkdir (path, 0775); /* User RWE Group RWE World RE */
# else
rc = mkdir (path); /* Protection? What's that? */
# endif
#else
rc = -1; /* Not a known system */
#endif
if (rc) /* End if error */
break;
}
if (slash == NULL) /* End if last directory */
break;
*slash = PATHEND; /* Restore path name */
slash = strchr (slash + 1, PATHEND);
}
mem_strfree (&path);
return (rc);
}
/* ---------------------------------------------------------------------[<]-
Function: remove_dir
Synopsis: remove a directory. Returns 0 if the directory could be
removed; -1 if there was an error. Under MS-DOS and OpenVMS accepts
a directory name in UNIX format, i.e. containing '/' delimiters. The
directory must be empty to be removed.
---------------------------------------------------------------------[>]-*/
int
remove_dir (
const char *path)
{
#if (defined (__UNIX__) || defined (__VMS_XOPEN) || defined (__OS2__))
/* Check that directory exists */
if (!file_is_directory (path))
return (-1);
#ifdef XENON
return -1;
#else
return (rmdir (path));
#endif
#elif (defined (MSDOS_FILESYSTEM))
int
rc = 0;
char
*copy_path;
/* Check that directory exists */
if (!file_is_directory (path))
return (-1);
copy_path = mem_strdup (path);
if (copy_path)
{
strconvch (copy_path, '/', '\\');
# if (defined (WIN32))
if (RemoveDirectory (copy_path))
rc = 0;
else
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
coprintf (lpMsgBuf);
rc = -1;
}
# else
rc = rmdir (copy_path);
# endif
mem_strfree (&copy_path);
}
return (rc);
#else
return (-1);
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: dir_usage
Synopsis: Calculates the amount of disk space used by a directory, and
optionally all directories below that. If the total size is greater
than 4Gb, returns an unspecified value. Returns 0 if there was an error.
---------------------------------------------------------------------[>]-*/
qbyte
dir_usage (const char *path, Bool recurse)
{
DIRST
dir;
qbyte
usage = 0;
char
*full_dir;
if (open_dir (&dir, path))
do
{
if ((dir.file_attrs & ATTR_HIDDEN) != 0)
; /* Do nothing */
else
if (recurse
&& (dir.file_attrs & ATTR_SUBDIR) != 0)
{
full_dir = locate_path (path, dir.file_name);
usage += dir_usage (full_dir, TRUE);
mem_free (full_dir);
}
else
usage += dir.file_size;
}
while (read_dir (&dir));
close_dir (&dir);
return (usage);
}
/* ---------------------------------------------------------------------[<]-
Function: dir_files
Synopsis: Calculates the number of files in a directory and optionally
all directories below that. Excludes directories from the count (thus,
a directory containing only '.' and '..' contains 0 files. Returns 0
if there was an error. Excludes hidden files.
---------------------------------------------------------------------[>]-*/
qbyte
dir_files (const char *path, Bool recurse)
{
DIRST
dir;
qbyte
files = 0;
char
*full_dir;
if (open_dir (&dir, path))
do
{
if ((dir.file_attrs & ATTR_HIDDEN) != 0)
; /* Do nothing */
else
if (recurse
&& (dir.file_attrs & ATTR_SUBDIR) != 0)
{
full_dir = locate_path (path, dir.file_name);
files += dir_files (full_dir, TRUE);
mem_free (full_dir);
}
else
files++;
}
while (read_dir (&dir));
close_dir (&dir);
return (files);
}
diff --git a/src/libs/sfl/sflfile.c b/src/libs/sfl/sflfile.c
index de848b93..9e2c4b7b 100644
--- a/src/libs/sfl/sflfile.c
+++ b/src/libs/sfl/sflfile.c
@@ -1,2531 +1,2531 @@
/* ----------------------------------------------------------------<Prolog>-
Name: sflfile.c
Title: File-access functions
Package: Standard Function Library (SFL)
Written: 1992/10/28 iMatix SFL project team <sfl@imatix.com>
Revised: 2000/01/19
Copyright: Copyright (c) 1996-2000 iMatix Corporation
License: This is free software; you can redistribute it and/or modify
it under the terms of the SFL License Agreement as provided
in the file LICENSE.TXT. This software is distributed in
the hope that it will be useful, but without any warranty.
------------------------------------------------------------------</Prolog>-*/
#include "prelude.h" /* Universal header file */
#include "sflstr.h" /* String handling functions */
#include "sfllist.h" /* Linked-list functions */
#include "sflmem.h" /* Memory allocation functions */
#include "sflnode.h" /* Linked-list functions */
#include "sfldir.h" /* Directory access functions */
#include "sfldate.h" /* Date/time access functions */
#include "sflsymb.h" /* Symbol-table functions */
#include "sfltok.h" /* Token mashing functions */
#include "sflcons.h" /* Console output functions */
#include "sflenv.h" /* Environment access functions */
#include "sflprint.h" /* snprintf functions */
#include "sflfile.h" /* Prototypes for functions */
/* Ensure our buffers will be big enough for dir + name + delimiters */
#if ((LINE_MAX - FILE_NAME_MAX) < (FILE_DIR_MAX + 10))
# error "Cannot compile; FILE_NAME_MAX is too large."
#endif
static char
#if (PATHFOLD == TRUE || defined (MSDOS_FILESYSTEM))
path_name [PATH_MAX + 1], /* Copy of path symbol */
#endif
work_name [LINE_MAX + 1], /* Name plus ext */
full_name [LINE_MAX + 1], /* Dir plus name plus ext */
exec_name [LINE_MAX + 1]; /* Executable file name */
Bool file_crlf = FALSE; /* Initial default */
/* Function prototypes */
#if (defined (MSDOS_FILESYSTEM))
static Bool system_devicename (const char *filename);
#endif
static char *build_next_path (char *dest, const char *path,
const char *name);
static char *build_next_path_ext (char *dest, const char *path,
const char *name,
const char *ext);
static dbyte file_mode (const char *filename);
#if (defined (__WINDOWS__))
static Bool is_exe_file (const char *filename);
#endif
static DESCR *file_load_data (const char *filename, size_t limit);
static Bool fully_specified (const char *filename);
/* ---------------------------------------------------------------------[<]-
Function: file_open
Synopsis: opens a text file for reading or writing. Use in combination
with the file_read() and file_write() functions. These functions handle
end-of-line sequences using a heuristic that works as follows.
... (at this point the author went for a pint of beer and has not been
seen since. We're hoping that the old version - following - is ok.)
Synopsis: Opens the specified file for input or output. If you use
the file_read / file_write functions you must open the file using this
function. This set of functions lets you read files without concern
for the line format (CRLF or LF). Mode should be one of 'r' 'w' 'a'.
Returns a FILE pointer if the file is opened correctly; else NULL.
Sets the global variable file_crlf to FALSE on all systems except MS-DOS
(and Windows by inheritence) where it is set to TRUE by default.
When opening a file in append mode, automatically removes any Ctrl-Z
character under MS-DOS or OS/2.
---------------------------------------------------------------------[>]-*/
FILE *
file_open (
const char *filename, /* Name of file to open */
char mode) /* 'r', 'w', or 'a' */
{
#if (defined (MSDOS_FILESYSTEM))
if (system_devicename (filename))
return (NULL); /* Not allowed on device names */
file_crlf = TRUE;
# if (defined (WIN32))
SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
# endif
# else
ASSERT (filename);
file_crlf = FALSE;
#endif
if (mode == 'r')
return (fopen (filename, FOPEN_READ_BINARY));
else
if (mode == 'w')
return (fopen (filename, FOPEN_WRITE_BINARY));
else
if (mode == 'a'
&& safe_to_extend (filename))
return (fopen (filename, FOPEN_APPEND_BINARY));
else
return (NULL); /* Invalid mode */
}
#if (defined (MSDOS_FILESYSTEM))
/* Under MS-DOS, use of filenames containing 'aux', 'con', 'prn', or
* 'nul' can cause problems, especially for reading. We reject any
* use of these names for directories or filenames.
*/
static Bool
system_devicename (const char *supplied_filename)
{
char
*filename,
*char_ptr,
*token,
**tokens;
int
token_nbr;
Bool
feedback;
filename = mem_strdup (supplied_filename);
strconvch (filename, ' ', '_'); /* Don't break on real spaces */
strconvch (filename, '/', ' ');
strconvch (filename, '\\', ' ');
strlwc (filename); /* All comparisons in lowercase */
/* Skip disk specifier if present */
if (strlen (filename) > 2 && filename [1] == ':')
filename [0] = filename [1] = ' ';
/* Wipe out file extensions */
for (char_ptr = filename; *char_ptr; char_ptr++)
{
if (*char_ptr == '.') /* Wipe over file extensions */
while (*char_ptr && *char_ptr != ' ')
*char_ptr++ = ' ';
if (*char_ptr == '\0')
break;
}
tokens = tok_split (filename);
feedback = FALSE;
for (token_nbr = 0; tokens [token_nbr]; token_nbr++)
{
token = tokens [token_nbr];
#if (defined (WIN32))
/* Ask Windows to check if it's a device */
if (QueryDosDevice (token, NULL, 0) == ERROR_INSUFFICIENT_BUFFER)
#else
if (streq (token, "aux")
|| streq (token, "con")
|| streq (token, "nul")
|| streq (token, "prn")
|| (strprefixed (token, "com") && isdigit (token [3]))
|| (strprefixed (token, "lpt") && isdigit (token [3])))
#endif
{
feedback = TRUE;
break;
}
}
tok_free (tokens);
mem_free (filename);
return (feedback);
}
#endif
/* ---------------------------------------------------------------------[<]-
Function: file_locate
Synopsis: Combines the functions of file_where() and file_open when you
want to read a file. Searches for a file on a specified path, opens the
file if found, and returns a FILE * for the open file. Returns NULL if
the file was not found or could not be opened for reading.
---------------------------------------------------------------------[>]-*/
FILE *
file_locate (
const char *path,
const char *name,
const char *ext)
{
char
*filename;
ASSERT (name);
filename = file_where ('r', path, name, ext);
if (filename)
return (file_open (filename, 'r'));
else
return (NULL);
}
/* ---------------------------------------------------------------------[<]-
Function: file_close
Synopsis: Closes an open file stream. Returns 0 if okay, -1 if there
was an error. For now, equivalent to fclose, and supplied because it
looks nice when you use file_open() and file_close() together.
---------------------------------------------------------------------[>]-*/
int
file_close (
FILE *stream)
{
if (stream)
return (fclose (stream));
else
return (0);
}
/* ---------------------------------------------------------------------[<]-
Function: file_read
Synopsis: Reads a line of text delimited by newline from the stream.
The string must be LINE_MAX + 1 long. Places a null byte in place of
the newline character. Expands tab characters to every 8th column.
Returns TRUE when there is more input waiting; FALSE when the last line
of the file has been read.
Sets the global variable file_crlf to TRUE if CR was found in the file.
This variable is by default FALSE. It is also used by file_write.
---------------------------------------------------------------------[>]-*/
Bool
file_read (
FILE *stream,
char *string)
{
int
ch, /* Character read from file */
cnbr; /* Index into returned string */
ASSERT (stream);
ASSERT (string);
cnbr = 0; /* Start at the beginning... */
memset (string, ' ', LINE_MAX); /* and prepare entire line */
for (;;)
{
ch = fgetc (stream); /* Get next character from file */
if (ch == '\t') /* Jump if tab */
cnbr = ((cnbr >> 3) << 3) + 8;
else
if (ch == '\r') /* Found carriage-return */
file_crlf = TRUE; /* Set flag and ignore CR */
else
if ((ch == '\n') /* Have end of line */
|| (ch == EOF) /* or end of file */
|| (ch == 26)) /* or MS-DOS Ctrl-Z */
{
string [cnbr] = '\0'; /* Terminate string */
return (ch == '\n' || cnbr); /* and return TRUE/FALSE */
}
else
if (cnbr < LINE_MAX)
string [cnbr++] = (char) ch; /* Else add char to string */
if (cnbr >= LINE_MAX) /* Return in any case if line is */
{ /* too long - the line will be */
string [LINE_MAX] = '\0'; /* cut into pieces */
return (TRUE);
}
}
}
/* ---------------------------------------------------------------------[<]-
Function: file_readn
Synopsis: Works as file_read() but with a maximum line-length specified
by the caller. The supplied buffer must be at least as large as the
specified line_max + 1.
---------------------------------------------------------------------[>]-*/
Bool
file_readn (
FILE *stream,
char *string,
int line_max)
{
int
ch, /* Character read from file */
cnbr; /* Index into returned string */
ASSERT (stream);
ASSERT (string);
cnbr = 0; /* Start at the beginning... */
memset (string, ' ', line_max); /* and prepare entire line */
for (;;)
{
ch = fgetc (stream); /* Get next character from file */
if (ch == '\t') /* Jump if tab */
cnbr = ((cnbr >> 3) << 3) + 8;
else
if (ch == '\r') /* Found carriage-return */
file_crlf = TRUE; /* Set flag and ignore CR */
else
if ((ch == '\n') /* Have end of line */
|| (ch == EOF) /* or end of file */
|| (ch == 26)) /* or MS-DOS Ctrl-Z */
{
string [cnbr] = '\0'; /* Terminate string */
return (ch == '\n' || cnbr); /* and return TRUE/FALSE */
}
else
if (cnbr < line_max)
string [cnbr++] = (char) ch; /* Else add char to string */
if (cnbr >= line_max) /* Return in any case if line is */
{ /* too long - the line will be */
string [line_max] = '\0'; /* cut into pieces */
return (TRUE);
}
}
}
/* ---------------------------------------------------------------------[<]-
Function: file_write
Synopsis: Writes a line of text to the specified output stream. If the
variable file_crlf is TRUE, adds a carriage-return to the line being
written to the output stream. This variable is supplied so that you can
either ignore crlf issues (do nothing), or handle them explicitly (play
with file_crlf). Returns the string written, or NULL if no data could
be written to the file.
---------------------------------------------------------------------[>]-*/
char *
file_write (
FILE *stream,
const char *string)
{
ASSERT (stream);
ASSERT (string);
fputs (string, stream);
if (file_crlf)
fputc ('\r', stream);
if (fputc ('\n', stream) == EOF)
return (NULL);
else
return ((char *) string);
}
/* ---------------------------------------------------------------------[<]-
Function: file_copy
Synopsis: Copies a file called src to one called dest. The dest file
may not already exist. If mode is 'b', copies a binary file; if mode is
't', copies a text file. This distinction only applies to MS-DOS file
systems; on other platforms the two modes are equivalent. Returns 0
if no problems occurred, -1 if an error occurred, 1 if the destination
file already exists.
---------------------------------------------------------------------[>]-*/
int
file_copy (
const char *dest,
const char *src,
char mode)
{
FILE *inf, *outf;
char *buffer,
openmode [3] = "??";
size_t chars_read; /* Amount read from stream */
int feedback = 0;
ASSERT (dest);
ASSERT (src);
if (file_exists (dest))
return (1); /* Cancel: dest already exists */
# if (defined (MSDOS_FILESYSTEM))
if (system_devicename (dest) || system_devicename (src))
return (-1); /* Not allowed on device names */
# endif
# if (defined (MSDOS_FILESYSTEM))
openmode [1] = mode;
# else
openmode [1] = 0;
# endif
openmode [0] = 'r';
if ((inf = fopen (src, openmode)) == NULL)
return (-1); /* Input file not found */
if ((buffer = mem_alloc (SHRT_MAX)) == NULL)
feedback = -1; /* Insufficient memory for buffer */
else
{
openmode [0] = 'w';
if ((outf = fopen (dest, openmode)) == NULL)
{
mem_free (buffer);
return (-1); /* Could not create output file */
}
while ((chars_read = fread (buffer, 1, SHRT_MAX, inf)) != 0)
if (fwrite (buffer, 1, chars_read, outf) != chars_read)
{
feedback = -1;
break;
}
fclose (outf);
mem_free (buffer);
}
fclose (inf);
return (feedback);
}
/* ---------------------------------------------------------------------[<]-
Function: file_concat
Synopsis: Copies the contents of src onto dest. If dest does not exist,
it is created. Returns 0 if the concatenation operation succeeded, or
-1 if some error occurred.
---------------------------------------------------------------------[>]-*/
int
file_concat (
const char *src,
const char *dest)
{
FILE *inf, *outf;
char *buffer;
size_t chars_read; /* Amount read from stream */
int feedback = 0;
ASSERT (src);
ASSERT (dest);
# if (defined (MSDOS_FILESYSTEM))
if (system_devicename (dest) || system_devicename (src))
return (-1); /* Not allowed on device names */
# endif
if ((inf = fopen (src, FOPEN_READ_BINARY)) == NULL)
return (-1); /* Input file not found */
if ((buffer = mem_alloc (SHRT_MAX)) == NULL)
feedback = -1; /* Insufficient memory for buffer */
else
{
if ((outf = fopen (dest, FOPEN_APPEND_BINARY)) == NULL)
{
mem_free (buffer);
return (-1); /* Could not create output file */
}
while ((chars_read = fread (buffer, 1, SHRT_MAX, inf)) != 0)
if (fwrite (buffer, 1, chars_read, outf) != chars_read)
{
feedback = -1;
break;
}
fclose (outf);
mem_free (buffer);
}
fclose (inf);
return (feedback);
}
/* ---------------------------------------------------------------------[<]-
Function: file_rename
Synopsis: Renames a file from oldname to newname. Returns 0 if okay,
or -1 if there was an error. Does not overwrite existing files.
---------------------------------------------------------------------[>]-*/
int
file_rename (
const char *oldname,
const char *newname)
{
# if (defined (MSDOS_FILESYSTEM))
char *dos_newname;
int feedback;
ASSERT (oldname);
ASSERT (newname);
if (system_devicename (oldname) || system_devicename (newname))
return (-1); /* Not allowed on device names */
dos_newname = mem_strdup (newname);
strconvch (dos_newname, '/', '\\');
feedback = rename (oldname, dos_newname);
mem_free (dos_newname);
return (feedback);
# else
ASSERT (oldname);
ASSERT (newname);
return (rename (oldname, newname));
# endif
}
/* ---------------------------------------------------------------------[<]-
Function: file_delete
Synopsis: Deletes the specified file. Returns 0 if okay, -1 in case of
an error.
---------------------------------------------------------------------[>]-*/
int
file_delete (
const char *filename)
{
#if (defined (__VMS__))
ASSERT (filename);
return (remove (filename));
#elif (defined (WIN32))
int
rc;
ASSERT (filename);
if (system_devicename (filename))
return (-1); /* Not allowed on device names */
rc = !DeleteFile (filename);
if (rc && errno == EACCES)
{
/* Under WinNT and Win95, a delete of a freshly-created file can
* sometimes fail with a permission error which passes after a
* short delay. Ugly but it seems to work.
*/
Sleep (200);
rc = !DeleteFile (filename);
}
return (rc);
#else
ASSERT (filename);
return (unlink (filename));
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: file_exists
Synopsis: Returns TRUE if the file exists, or FALSE if it does not.
---------------------------------------------------------------------[>]-*/
/* Allegro4 already has this function which works the same way */
#ifndef USE_ALLEGRO
Bool
file_exists (
const char *filename)
{
ASSERT (filename);
return (file_mode (filename) > 0);
}
#endif
/* -------------------------------------------------------------------------
* file_mode -- internal
*
* Returns the file mode for the specified file or directory name; returns
* 0 if the specified file does not exist.
*/
static dbyte
file_mode (const char *filename)
{
#if (defined (WIN32))
DWORD dwfa;
dbyte mode;
ASSERT (filename);
if (system_devicename (filename))
return (0); /* Not allowed on device names */
dwfa = GetFileAttributes (filename);
if (dwfa == 0xffffffff)
return (0);
mode = 0;
if (dwfa & FILE_ATTRIBUTE_DIRECTORY)
mode |= S_IFDIR;
else
mode |= S_IFREG;
if (!(dwfa & FILE_ATTRIBUTE_HIDDEN))
mode |= S_IRUSR;
if (!(dwfa & FILE_ATTRIBUTE_READONLY))
mode |= S_IWUSR;
if (is_exe_file (filename))
mode |= S_IXUSR;
return (mode);
#else
static struct stat
stat_buf;
ASSERT (filename);
# if (defined (MSDOS_FILESYSTEM))
/* Handle simple disk specifiers ourselves, since some compilers cannot
* do a 'stat' on these.
*/
if ( filename [1] == ':'
&& ((filename [2] == '\\' && filename [3] == '\0')
|| (filename [2] == '/' && filename [3] == '\0')
|| (filename [2] == '\0')))
return (S_IFDIR | S_IRUSR | S_IWUSR);
# endif
if (strnull (filename))
return (0);
else
if (stat ((char *) filename, &stat_buf) == 0)
return ((dbyte) stat_buf.st_mode);
else
return (0);
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: file_where
Synopsis: Scans a user-specified path symbol for a specific file, and
returns the fully-specified filename. Also adds an extension if this
is required.
The mode argument can be one of: r, w, a, or s for read, write, append,
or static. The function tries to locate existing files somewhere on the
path. New files are always created in the current directory. Static
files are created in the first directory on the path.
The path argument is only used when more is r, a, or s. If the path is
NULL or empty, it is ignored. Otherwise, the path is translated as an
environment variable, and cut into a list of directory names. The path
is cut up as follows:
<TABLE>
MS-DOS directory names separated by ';'. ;; means current.
OS/2 directory names separated by ';'. ;; means current.
Unix directory names separated by ':'. :: means current.
VMS directory names separated by ','. " ", means current.
Other single directory name.
</TABLE>
When the mode is 'r' or 'a', searches the current directory before
considering the path value. When the path cannot be translated, and is
not null or empty, it is used as a literal value.
The name argument is the filename with or without extension. It will
be prefixed by the path and suffixed by the extension, if required.
The ext argument is a default or mandatory extension. If ext starts
with a dot, it is mandatory and always used. Otherwise it is used only
if the name does not already have an extension. If ext is NULL or empty,
it is ignored.
The total length of a name including path, name, extension, and any
delimiters is FILE_NAME_MAX. Names are truncated if too long. The
maximum size of one directory component is FILE_DIR_MAX chars.
All parameters are case-sensitive; the precise effect of this depends on
the system. On MS-DOS, filenames are always folded to uppercase, but the
path must be supplied in uppercase correctly. On UNIX, all parameters are
case sensitive. On VMS, path and filenames are folded into uppercase.
Returns a pointer to a static character array containing the filename; if
mode is 'r' and the file does not exist, returns NULL. If the mode is
'w', 'a', or 's', always returns a valid filename.
Under VMS, all filenames are handled in POSIX mode, i.e. /disk/path/file
instead of $disk:[path]file.
---------------------------------------------------------------------[>]-*/
char *
file_where (
char mode,
const char *path,
const char *name,
const char *ext)
{
const char
*pathptr; /* End of directory in path */
char
*curdir;
Bool
search_curdir = TRUE; /* Look in current directory? */
ASSERT (name);
if (ext != NULL && *ext) /* Append extension if not null */
{ /* to get name + ext into */
if (ext [0] == '.') /* work_name. */
fixed_extension (work_name, name, ext);
else
default_extension (work_name, name, ext);
}
else
strcpy (work_name, name);
#if (NAMEFOLD == TRUE)
strupc (work_name); /* Fold to uppercase if needed */
#endif
if (path != NULL && *path) /* Get value of path, or NULL */
{
pathptr = getenv (path); /* Translate path symbol */
if (pathptr == NULL)
{
pathptr = path; /* If not found, use literally */
search_curdir = FALSE; /* Path now takes priority */
}
#if (PATHFOLD == TRUE) /* Fold to uppercase if necessary */
if (pathptr)
{
ASSERT (strlen (pathptr) < PATH_MAX);
strcpy (path_name, pathptr);
strupc (path_name);
pathptr = path_name; /* Redirect to uppercase version */
}
#endif
}
else
pathptr = NULL;
#if (defined (MSDOS_FILESYSTEM))
/* Normalise the path value by changing any slashes to backslashes */
if (pathptr)
{
if (pathptr != path_name)
{
strcpy (path_name, pathptr);
pathptr = path_name;
}
strconvch (path_name, '/', '\\');
}
#endif
/* Take care of 'w' and 's' options first */
if (mode == 'w') /* Create output file locally */
return (work_name);
if (mode == 's') /* Get specific directory name */
{
if (fully_specified (work_name))
strncpy (full_name, work_name, sizeof (full_name));
else
if (pathptr && file_is_directory (pathptr))
build_next_path (full_name, pathptr, work_name);
else
#if (defined (MSDOS_FILESYSTEM))
build_next_path (full_name, ".\\", work_name);
#else
build_next_path (full_name, "./", work_name);
#endif
return (full_name);
}
/* If file exists as defined, prefix with current directory if not an */
/* absolute filename, then return the resulting filename */
if (search_curdir && file_exists (work_name))
{
if (fully_specified (work_name))
strncpy (full_name, work_name, sizeof (full_name));
else
{
curdir = get_curdir ();
snprintf (full_name, sizeof (full_name), "%s%s", curdir, work_name);
mem_free (curdir);
}
#if (defined (MSDOS_FILESYSTEM))
strconvch (full_name, '/', '\\');
#endif
return (full_name); /* Then return path + name + ext */
}
if (!pathptr) /* Now we need a path */
return (NULL); /* - if none defined, give up */
for (;;) /* Try each path component */
{
pathptr = build_next_path (full_name, pathptr, work_name);
if (file_exists (full_name))
return (full_name); /* Until we find one, */
if (*pathptr == '\0') /* or we come to the end of */
{ /* the path */
if (mode == 'r')
return (NULL); /* Input file was not found... */
else
return (full_name);
}
}
}
/* ---------------------------------------------------------------------[<]-
Function: file_where_ext
Synopsis: Scans a user-specified path symbol for a specific file, and
returns the fully-specified filename. Can also scan a series of file
extensions while looking for the file in the path. The extensions are
scanned in each directory in the path prior to moving on to the next
directory.
The mode argument can be one of: r, w, a, or s for read, write, append,
or static. The function tries to locate existing files somewhere on the
path. New files are always created in the current directory. Static
files are created in the first directory on the path.
The path argument is only used when mode is r, a, or s. If the path is
NULL or empty, it is ignored. Otherwise, the path is translated as an
environment variable. If the path cannot be translated, it is used as
a literal value. The path is then cut into a list of directory names,
as follows:
<TABLE>
MS-DOS directory names separated by ';'. ;; means current.
OS/2 directory names separated by ';'. ;; means current.
Unix directory names separated by ':'. :: means current.
VMS directory names separated by ','. " ", means current.
Other single directory name.
</TABLE>
When the mode is 'r' or 'a', it searches the current directory before
considering the path value.
The name argument is the filename with or without extension. It will
be prefixed by the path and suffixed by the extension, if required.
The ext argument is an array of default or mandatory extensions.
If the extension starts with a dot, it is mandatory and will override
any existing extension. Otherwise it is used only if the name does
not already have an extension. The filename will be tried as supplied
if ext is NULL, or if it has an extension, and one or more of the
entries is a default extension. The first extension, if any, is
always used in 'w' mode and 's' mode. The last path component and
extension will be used in 'a' mode, if either is supplied.
The total length of a name including path, name, extension, and any
delimiters is FILE_NAME_MAX. Names are truncated if too long. The
maximum size of one directory component is FILE_DIR_MAX chars.
All parameters are case-sensitive; the precise effect of this depends on
the system. On MS-DOS, filenames are always folded to uppercase, but the
path must be supplied in uppercase correctly. On UNIX, all parameters are
case sensitive. On VMS, path and filenames are folded into uppercase.
Returns a pointer to a static character array containing the filename; if
mode is 'r' and the file does not exist, returns NULL. If the mode is
'w', 'a', or 's', always returns a valid filename.
Under VMS, all filenames are handled in POSIX mode, i.e. /disk/path/file
instead of $disk:[path]file.
---------------------------------------------------------------------[>]-*/
char *
file_where_ext (
char mode,
const char *path,
const char *name,
const char **ext)
{
const char
*pathptr; /* End of directory in path */
const char
**extptr; /* Pointer to next extension */
char
*curdir;
Bool
search_curdir = TRUE; /* Look in current directory? */
ASSERT (name);
if (!name)
return NULL;
if (path != NULL && *path) /* Get value of path, or NULL */
{
pathptr = getenv (path); /* Translate path symbol */
if (pathptr == NULL)
{
pathptr = path; /* If not found, use literally */
search_curdir = FALSE; /* Path now takes priority */
}
#if (PATHFOLD == TRUE) /* Fold to uppercase if necessary */
if (pathptr)
{
ASSERT (strlen (pathptr) < PATH_MAX);
strcpy (path_name, pathptr);
strupc (path_name);
pathptr = path_name; /* Redirect to uppercase version */
}
#endif
}
else
pathptr = NULL;
#if (defined (MSDOS_FILESYSTEM))
/* Normalise the path value by changing any slashes to backslashes */
if (pathptr)
{
if (pathptr != path_name)
{
strcpy (path_name, pathptr);
pathptr = path_name;
}
strconvch (path_name, '/', '\\');
}
#endif
/* Take care of 'w' and 's' options first */
if (mode == 'w') /* Create output file locally */
{
if (ext != NULL && ext [0] != NULL)
add_extension (work_name, name, ext [0]);
else
strcpy (work_name, name);
#if (NAMEFOLD == TRUE)
strupc (work_name); /* Fold to uppercase if needed */
#endif
return (work_name);
}
if (mode == 's') /* Get specific directory name */
{
if (ext != NULL && ext [0] != NULL)
add_extension (work_name, name, ext [0]);
else
strcpy (work_name, name);
#if (NAMEFOLD == TRUE)
strupc (work_name); /* Fold to uppercase if needed */
#endif
if (fully_specified (work_name))
strcpy (full_name, work_name);
else
if (pathptr && file_is_directory (pathptr))
build_next_path (full_name, pathptr, work_name);
else
#if (defined (MSDOS_FILESYSTEM))
build_next_path (full_name, ".\\", work_name);
#else
build_next_path (full_name, "./", work_name);
#endif
return (full_name);
}
/* If file exists as defined (with one of the extensions), prefix with */
/* current directory if not an absolute filename, then return the */
/* resulting filename */
if (search_curdir)
{
extptr = ext;
do
{
if (extptr != NULL && *extptr != NULL)
add_extension (work_name, name, *extptr);
else
strcpy (work_name, name);
#if (NAMEFOLD == TRUE)
strupc (work_name); /* Fold to uppercase if needed */
#endif
if (file_exists (work_name))
{
if (fully_specified (work_name))
strcpy (full_name, work_name);
else
{
curdir = get_curdir ();
snprintf (full_name, sizeof (full_name),
"%s%s", curdir, work_name);
mem_free (curdir);
}
#if (defined (MSDOS_FILESYSTEM))
strconvch (full_name, '/', '\\');
#endif
return (full_name); /* Then return path + name + ext */
}
if (extptr)
extptr++;
}
while (extptr != NULL && *extptr != NULL);
}
if (!pathptr) /* We need a path to look further */
return (NULL); /* - if none defined, give up */
for (;;) /* Try each path component */
{ /* - and extension within that */
const char *savedptr = pathptr;
extptr = ext;
do
{
const char *extension = NULL;
if (extptr != NULL && *extptr != NULL)
extension = *extptr;
pathptr = build_next_path_ext (full_name, savedptr,
name, extension);
if (file_exists (full_name))
return (full_name); /* Until we find one that matches */
if (extptr)
extptr++;
}
while (extptr != NULL && *extptr != NULL);
if (*pathptr == '\0') /* or we come to the end of */
{ /* the path */
if (mode == 'r')
return (NULL); /* Input file was not found... */
else
return (full_name);
}
}
}
/* -------------------------------------------------------------------------
* fully_specified -- internal
*
*/
static Bool
fully_specified (const char *filename)
{
#if (defined (MSDOS_FILESYSTEM)) \
/* Under MSDOS we have a full path if we have any of:
* /directory/directory/filename
* D:/directory/directory/filename
* the variations of those with backslashes.
*/
if (filename [0] == '\\' || filename [0] == '/' ||
(isalpha (filename [0]) && filename [1] == ':' &&
(filename [2] == '\\' || filename [2] == '/')))
#else
/* Under UNIX, VMS, or OS/2, we have a full path if the path starts
* with the directory marker
*/
if (filename [0] == PATHEND)
#endif
return (TRUE);
else
return (FALSE);
}
/* -------------------------------------------------------------------------
* build_next_path -- internal
*
*/
static char *
build_next_path (char *dest, const char *path, const char *name)
{
int
length; /* length of directory name */
char
*pathptr = (char *) path;
if (path)
{
length = strcspn (path, PATHSEP);
strncpy (dest, path, length);
pathptr += length; /* Bump past path delimiter */
if (*pathptr) /* unless we are at the end */
pathptr++; /* of the path */
if ((length)
&& (dest [length - 1] != PATHEND))
dest [length++] = PATHEND; /* Add path-to-filename delimiter */
dest [length] = '\0';
strcat (dest, name);
}
else
strcpy (dest, name);
return (pathptr);
}
/* -------------------------------------------------------------------------
* build_next_path_ext -- internal
*
*/
static char *
build_next_path_ext (char *dest, const char *path,
const char *name, const char *ext)
{
int
length; /* length of directory name */
char
*pathptr = (char *) path;
if (path)
{
length = strcspn (path, PATHSEP);
strncpy (dest, path, length);
pathptr += length; /* Bump past path delimiter */
if (*pathptr) /* unless we are at the end */
pathptr++; /* of the path */
if ((length)
&& (dest [length - 1] != PATHEND))
dest [length++] = PATHEND; /* Add path-to-filename delimiter */
dest [length] = '\0';
strcat (dest, name);
add_extension (dest, dest, ext);
}
else
{
if (ext)
add_extension (dest, name, ext);
else
strcpy (dest, name);
}
return (pathptr);
}
/* ---------------------------------------------------------------------[<]-
Function: file_cycle
Synopsis: Cycles the file: if the file already exists, renames the
existing file. This function tries to rename the file using the date
of creation of the file; if this fails because an existing file had the
same name, generates a guaranteed unique file name. Returns TRUE if
the cycle operation succeeded, or FALSE if it failed (e.g. due to a
protection problem). The how argument must be one of:
<TABLE>
CYCLE_ALWAYS Cycle file unconditionally
CYCLE_HOURLY Cycle file if hour has changed
CYCLE_DAILY Cycle file if day has changed
CYCLE_WEEKLY Cycle file if week has changed
CYCLE_MONTHLY Cycle file if month has changed
CYCLE_NEVER Don't cycle the file
</TABLE>
---------------------------------------------------------------------[>]-*/
Bool
file_cycle (
const char *filename,
int how)
{
long
file_date; /* Datestamp of file */
char
*point,
*insert_at; /* Where we start messing name */
int
unique_nbr; /* To generate a unique name */
ASSERT (filename);
/* If no cycling needed, do nothing */
if (!file_cycle_needed (filename, how))
return (TRUE); /* No errors, nothing in fact */
file_date = timer_to_date (get_file_time (filename));
strcpy (full_name, filename);
point = strrchr (full_name, '.');
if (point)
{
strcpy (work_name, point); /* Save extension, if any */
*point = '\0'; /* and truncate original name */
}
else
strclr (work_name);
/* We leave up to 2 original letters of the filename, then stick-in */
/* the 6-digit timestamp. */
insert_at = strrchr (full_name, '/');
#if (defined (MSDOS_FILESYSTEM))
if (!insert_at)
insert_at = strrchr (full_name, '\\');
#endif
if (insert_at)
insert_at++; /* Bump past slash, if found */
else
insert_at = full_name;
if (*insert_at) /* Bump insert_at twice, to leave */
insert_at++; /* up to 2 letters before we */
if (*insert_at) /* stick-in the date stamp */
insert_at++;
/* Format new name for file and make sure it does not already exist */
sprintf (insert_at, "%06d", (int) (file_date % 1000000L));
strcat (insert_at, work_name);
if (file_exists (full_name))
{
point = strrchr (full_name, '.') + 1;
for (unique_nbr = 0; unique_nbr < 1000; unique_nbr++)
{
sprintf (point, "%03d", unique_nbr);
if (!file_exists (full_name))
break;
}
}
if (file_exists (full_name))
return (FALSE); /* We give up! */
if (file_rename (filename, full_name))
return (FALSE); /* No permission */
else
return (TRUE); /* Okay, it worked */
}
/* ---------------------------------------------------------------------[<]-
Function: file_cycle_needed
Synopsis: Checks whether the file should be cycled or not. Returns
TRUE if the file needs to be cycled, FALSE if not. The how argument
must be one of:
<TABLE>
CYCLE_ALWAYS Cycle file unconditionally
CYCLE_HOURLY Cycle file if hour has changed
CYCLE_DAILY Cycle file if day has changed
CYCLE_WEEKLY Cycle file if week has changed
CYCLE_MONTHLY Cycle file if month has changed
CYCLE_NEVER Don't cycle the file
</TABLE>
If the specified file does not exist or is not accessible, returns
FALSE.
---------------------------------------------------------------------[>]-*/
Bool
file_cycle_needed (
const char *filename,
int how)
{
long
curr_time, /* Current time */
curr_date, /* Current date */
file_date, /* Timestamp of file */
file_time; /* Datestamp of file */
Bool
cycle; /* Do we want to cycle the file? */
ASSERT (filename);
if (!file_exists (filename)) /* Not found - nothing more to do */
return (FALSE);
file_time = timer_to_time (get_file_time (filename));
file_date = timer_to_date (get_file_time (filename));
curr_time = time_now ();
curr_date = date_now ();
switch (how)
{
case CYCLE_ALWAYS:
cycle = TRUE;
break;
case CYCLE_HOURLY:
cycle = GET_HOUR (file_time) != GET_HOUR (curr_time);
break;
case CYCLE_DAILY:
cycle = GET_DAY (file_date) != GET_DAY (curr_date);
break;
case CYCLE_WEEKLY:
cycle = week_of_year (file_date) != week_of_year (curr_date);
break;
case CYCLE_MONTHLY:
cycle = GET_MONTH (file_date) != GET_MONTH (curr_date);
break;
case CYCLE_NEVER:
cycle = FALSE;
break;
default:
cycle = FALSE;
}
return (cycle);
}
/* ---------------------------------------------------------------------[<]-
Function: file_has_changed
Synopsis: Returns TRUE if the file has changed since it was last read.
The calling program must supply the date and time of the file as it
was read. If the file is not present or accessible, returns FALSE.
---------------------------------------------------------------------[>]-*/
Bool
file_has_changed (
const char *filename,
long old_date,
long old_time)
{
long
file_date, /* Timestamp of file */
file_time; /* Datestamp of file */
ASSERT (filename);
if (!file_exists (filename)) /* Not found - nothing more to do */
return (FALSE);
file_time = timer_to_time (get_file_time (filename));
file_date = timer_to_date (get_file_time (filename));
if (file_date > old_date
|| (file_date == old_date && file_time > old_time))
return (TRUE);
else
return (FALSE);
}
/* ---------------------------------------------------------------------[<]-
Function: safe_to_extend
Synopsis: Handles system-specific case of extending a file that may not
be in a valid state for such an operation. Returns TRUE if the extend
can go ahead; returns FALSE if the extend cannot be permitted.
Under MS-DOS and Windows, if the last byte in the file is Ctrl-Z (26)
the file is truncated by 1 position to remove this character.
---------------------------------------------------------------------[>]-*/
Bool
safe_to_extend (
const char *filename)
{
#if (defined (MSDOS_FILESYSTEM))
int handle; /* Opened file handle */
char endoffile; /* Last character in file */
ASSERT (filename);
if (system_devicename (filename))
return (FALSE); /* Not allowed on device names */
handle = open (filename, O_RDWR + O_BINARY, S_IRUSR | S_IWUSR);
if (handle) /* If not found, ignore */
{
lseek (handle, -1, SEEK_END);
read (handle, &endoffile, 1);
if (endoffile == 26)
chsize (handle, filelength (handle) - 1);
close (handle);
}
#endif
return (TRUE);
}
/* ---------------------------------------------------------------------[<]-
Function: default_extension
Synopsis: Copies src to dest and adds ext if necessary. Returns dest.
Dest must be large enough for a fully-formatted filename; define it as
char [FILE_NAME_MAX + 1]. The ext argument can start with or without
a dot. If ext is null or empty, does nothing.
---------------------------------------------------------------------[>]-*/
char *
default_extension (
char *dest,
const char *src,
const char *ext)
{
int len, i;
char *ptr;
ASSERT (dest);
ASSERT (src);
if (dest != src) /* Copy src to dest if not same */
strcpy (dest, src);
if (ext != NULL && *ext != 0)
{
len = strlen (dest);
for (i = len - 1, ptr = dest + i; i >= 0; i--, ptr--)
if (*ptr == '\\' || *ptr == '/' || *ptr == '.')
break;
if (i < 0 || *ptr != '.')
{
if (*ext != '.')
{
dest [len++] = '.';
dest [len] = '\0';
}
strcat (dest + len, ext);
}
}
return (dest);
}
/* ---------------------------------------------------------------------[<]-
Function: fixed_extension
Synopsis: Copies src to dest and enforces ext extension. Returns dest.
Dest must be large enough for a fully-formatted filename; define it as
char [FILE_NAME_MAX + 1]. The ext argument can start with or without
a dot. If ext is null or empty, does nothing.
---------------------------------------------------------------------[>]-*/
char *
fixed_extension (
char *dest,
const char *src,
const char *ext)
{
ASSERT (dest);
ASSERT (src);
if (dest != src) /* Copy src to dest if not same */
strcpy (dest, src);
strip_extension (dest);
return (default_extension (dest, dest, ext));
}
/* ---------------------------------------------------------------------[<]-
Function: strip_extension
Synopsis: Removes dot and extension from the name, if any was present.
If the name contained multiple extensions, removes the last one only.
Returns name.
---------------------------------------------------------------------[>]-*/
char *
strip_extension (
char *name)
{
char *dot, *slash;
ASSERT (name);
dot = strrchr (name, '.'); /* Find dot in name, if any */
slash = strrchr (name, '\\'); /* Find last slash (DOS or Unix) */
if (slash == NULL)
slash = strrchr (name, '/');
if (dot > slash)
*dot = 0; /* If we had a dot, truncate name */
return (name);
}
/* ---------------------------------------------------------------------[<]-
Function: add_extension
Synopsis: Copies src to dest and adds ext if necessary. If extension
starts with "." then it will be added, in place of any existing extension.
If extension does not start with "." it will be added only if there is
no existing extension. If ext is null or empty, just copies src into
dest if required.
Dest must be large enough for a fully-formatted filename; define it as
char [FILE_NAME_MAX + 1].
---------------------------------------------------------------------[>]-*/
char *
add_extension (
char *dest,
const char *src,
const char *ext)
{
char
*result;
ASSERT (dest);
ASSERT (src);
if (!src || !dest)
return (NULL);
if (!ext || *ext == '\0')
{
if (dest != src) /* Copy src to dest if not same */
strcpy (dest, src);
result = dest;
}
else
if (*ext == '.')
result = fixed_extension (dest, src, ext);
else
result = default_extension (dest, src, ext);
return (result);
}
/* ---------------------------------------------------------------------[<]-
Function: strip_file_path
Synopsis: Removes the leading path from the filename, if any path was
present. Returns name. The path can be specified using the local
operating system syntax; under MS-DOS, / and \ are interchangeable.
---------------------------------------------------------------------[>]-*/
char
*strip_file_path (
char *name)
{
char *path_end;
ASSERT (name);
path_end = strrchr (name, PATHEND); /* Find end of path, if any */
#if (defined (MSDOS_FILESYSTEM))
if (path_end == NULL)
path_end = strrchr (name, '/');
#endif
if (path_end != NULL)
memmove (name, path_end + 1, strlen (path_end));
return (name);
}
/* ---------------------------------------------------------------------[<]-
Function: strip_file_name
Synopsis: Returns the path for a fully-qualified filename. The path is
cleaned-up and resolved. The returned string is held in a static area
that should be copied directly after calling this function. The returned
path does not end in '/' unless that is the entire path. If the supplied
name contains no path, the returned path is ".".
---------------------------------------------------------------------[>]-*/
char
*strip_file_name (
char *name)
{
char *path_end;
ASSERT (name);
ASSERT (strlen (name) <= LINE_MAX);
strcpy (work_name, name);
path_end = strrchr (work_name, PATHEND);
#if (defined (MSDOS_FILESYSTEM))
if (path_end == NULL)
path_end = strrchr (work_name, '/');
#endif
if (path_end == NULL)
return (".");
else
{
path_end [1] = '\0';
return (clean_path (work_name));
}
}
/* ---------------------------------------------------------------------[<]-
Function: get_new_filename
Synopsis: Appends a numeric suffix (_001, _002,...) to the filename until
it is unique. Returns a freshly-allocated string containing the new
filename.
---------------------------------------------------------------------[>]-*/
char *
get_new_filename (
const char *filename)
{
char
suffix [8],
*new_name;
int
counter;
for (counter = 0; ; counter++)
{
sprintf (suffix, "_%03d", counter);
new_name = xstrcpy (NULL, filename, suffix, NULL);
if (!file_exists (new_name))
return (new_name);
else
mem_free (new_name);
}
return (NULL);
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_readable
Synopsis: Returns TRUE if the current process can read the specified
file or directory. The filename may end in a slash (/ or \) only if
it is a directory.
---------------------------------------------------------------------[>]-*/
Bool
file_is_readable (
const char *filename)
{
ASSERT (filename);
if (file_is_directory (filename))
return ((file_mode (clean_path (filename)) & S_IRUSR) != 0);
else
if (strlast (filename) == '/')
return (FALSE);
else
return ((file_mode (filename) & S_IRUSR) != 0);
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_writeable
Synopsis: Returns TRUE if the current process can write the specified
file or directory. The filename may end in a slash (/ or \) only if
it is a directory.
---------------------------------------------------------------------[>]-*/
Bool
file_is_writeable (
const char *filename)
{
ASSERT (filename);
if (file_is_directory (filename))
return ((file_mode (clean_path (filename)) & S_IWUSR) != 0);
else
if (strlast (filename) == '/')
return (FALSE);
else
return ((file_mode (filename) & S_IRUSR) != 0);
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_executable
Synopsis: Returns TRUE if the current process can execute the specified
file. Directories are _not_ considered to be executable.
Under DOS, Windows, appends ".com", ".exe", and ".bat" to the filename,
in that order, to build a possible executable filename. If this fails,
opens the file (if it exists) and examines the first few bytes of the
file: if these are "#!", or '/'*! or "MZ" then the file is assumed to
be executable. #! is a standard mechanism under Unix for indicating
executable files. Note that process_create() uses a compatible
mechanism to launch the correct interpreter for such 'executable'
scripts. NOTE: '/'*! is provided for REXX. [XXX]
Under OS/2 appends ".exe" and ".cmd" to the filename, in that order,
to be a possible executable filename. If this fails, it opens the
file (if it exists) and examines the first few bytes of the file: if
these are "#!" then the file is assumed to be executable. NOTE:
REXX scripts MUST be in files named script.cmd in order to be found.
BAT files are not considered, nor are COM files, since at present
process_create does not support launching DOS processes.
Under VMS, appends .exe and .com, in that order to build a possible
executable filename.
Does not search the PATH symbol; the filename must be specified with a
path if necessary.
---------------------------------------------------------------------[>]-*/
Bool
file_is_executable (
const char *filename)
{
#if (defined (__UNIX__))
ASSERT (filename);
return ((file_mode (filename) & S_IXUSR) != 0
&& (file_mode (filename) & S_IFDIR) == 0);
#elif (defined (MSDOS_FILESYSTEM))
Bool
executable; /* Return code */
FILE
*stream; /* Opened file stream */
char
input_char = 0, /* First and second bytes of file */
*extension; /* File extension, if any */
ASSERT (filename);
/* Find file extension; if not found, set extension to empty string */
extension = strrchr (filename, '.');
if (extension == NULL
|| strchr (extension, '/') /* If last '.' is part of the path */
|| strchr (extension, '\\')) /* then the filename has no ext. */
extension = "";
/* Windows: If extension is .exe/.com/.bat, the file is an executable */
/* OS/2: If the extension is .exe/.cmd, the file is an executable */
#if (defined ( __OS2__))
if (lexcmp (extension, ".exe") == 0
|| lexcmp (extension, ".cmd") == 0)
#else /* DOS, WINDOWS */
if (lexcmp (extension, ".com") == 0
|| lexcmp (extension, ".exe") == 0
|| lexcmp (extension, ".bat") == 0)
#endif
executable = file_exists (filename);
else
/* Windows: If the extension is empty, try .com, .exe, .bat */
/* OS/2: If the extension is empty, try .exe, .cmd */
if (strnull (extension)
#if (defined( __OS2__))
&& (file_exists (default_extension (work_name, filename, "exe"))
|| file_exists (default_extension (work_name, filename, "cmd"))))
#else /* DOS, WINDOWS */
&& (file_exists (default_extension (work_name, filename, "com"))
|| file_exists (default_extension (work_name, filename, "exe"))
|| file_exists (default_extension (work_name, filename, "bat"))))
#endif
executable = TRUE; /* Executable file found */
else
{
/* Look for magic header at start of file */
stream = file_open (filename, 'r');
if (stream)
{
input_char = fgetc (stream);
executable = ((input_char == '#' && fgetc (stream) == '!')
# if (defined (__WINDOWS__))
|| (input_char == '/' && fgetc (stream) == '*'
&& fgetc (stream) == '!')
|| (input_char == 'M' && fgetc (stream) == 'Z')
# endif
);
file_close (stream);
}
else
executable = FALSE;
}
return (executable);
#elif (defined (__VMS__))
Bool
executable; /* Return code */
char
*extension; /* File extension, if any */
ASSERT (filename);
/* Find file extension, if any */
extension = strrchr (filename, '.');
if ((file_mode (filename) & S_IXUSR) != 0)
executable = TRUE;
else
/* If the extension is empty, try .exe and .com */
if (!extension)
{
default_extension (work_name, filename, "exe");
if ((file_mode (work_name) & S_IXUSR) != 0)
executable = TRUE;
else
{
default_extension (work_name, filename, "com");
if ((file_mode (work_name) & S_IXUSR) != 0)
executable = TRUE;
else
executable = FALSE;
}
}
else
executable = FALSE;
return (executable);
#else
return (FALSE); /* Not supported on this system */
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_program
Synopsis: Returns TRUE if the specified filename is an executable
program on the PATH.
Under DOS, and Windows, appends ".exe", ".com" to the file, in that
order, to build an executable filename, then searches the PATH
definition for the executable filename. Under OS/2, appends ".exe"
to the file to build an executable filename, then searches the PATH
definition for the executable filename. If the filename already has
a path specifier, will not use the PATH definition. Under VMS,
appends "exe" and "com" to the file, in that order, to build an
executable filename. Searches the PATH if necessary.
---------------------------------------------------------------------[>]-*/
Bool
file_is_program (
const char *filename)
{
Bool
executable = FALSE; /* Return code */
#if (defined (__UNIX__))
char
*found_file;
ASSERT (filename);
found_file = file_where ('r', "PATH", filename, "");
if (found_file && (file_mode (found_file) & S_IXUSR))
executable = TRUE; /* Executable file found */
#elif (defined (__VMS__))
char
*found_file;
ASSERT (filename);
found_file = file_where ('r', "PATH", filename, "");
if (!found_file)
found_file = file_where ('r', "PATH", filename, ".exe");
if (!found_file)
found_file = file_where ('r', "PATH", filename, ".com");
if (found_file && (file_mode (found_file) & S_IXUSR))
executable = TRUE; /* Executable file found */
#elif (defined (MSDOS_FILESYSTEM))
char
*path; /* What path do we search? */
ASSERT (filename);
/* If the filename already contains a path, don't look at PATH */
if (strchr (filename, '/') || strchr (filename, '\\'))
path = NULL;
else
path = "PATH";
# if (defined (__WINDOWS__))
if (file_where ('r', path, filename, ".exe")
|| file_where ('r', path, filename, ".com")
|| file_where ('r', path, filename, ".bat"))
executable = TRUE; /* Executable file found */
# else /* OS/2 */
if (file_where ('r', path, filename, ".exe"))
executable = TRUE;
# endif
#endif
return (executable);
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_directory
Synopsis: Returns TRUE if the specified file is a directory. The
filename may end in a slash (/ or \). Under MS-DOS/OS2/Windows, a
directory name may consist solely of a disk-drive specifier. Under
VMS the directory may optionally take the extension '.dir'.
---------------------------------------------------------------------[>]-*/
Bool
file_is_directory (
const char *filename)
{
char
*dir_name;
Bool
rc;
ASSERT (filename);
dir_name = mem_strdup (clean_path (filename));
#if (defined (__VMS__))
if (!file_exists (dir_name))
default_extension (dir_name, dir_name, "dir");
#endif
rc = (file_mode (dir_name) & S_IFDIR) != 0;
mem_free (dir_name);
return (rc);
}
/* ---------------------------------------------------------------------[<]-
Function: file_is_legal
Synopsis: Checks whether the specified file is 'legal', which is a
system-dependent definition. Under 32-bit Windows, a legal file is one
who's name is not a shortened 8.3 version of a long name. This can be
used to bypass filename-based security schemes. On other systems, the
notion of 'illegal' is not defined. Returns TRUE if the file exists
and is legal. Returns FALSE otherwise.
---------------------------------------------------------------------[>]-*/
Bool
file_is_legal (
const char *arg_filename)
{
#if (defined (WIN32))
static WIN32_FIND_DATA
found;
HANDLE
handle;
char
*filename, /* Our copy of arg_filename */
*slash, /* Position of '\' in filename */
*component; /* Component to compare */
Bool
feedback; /* Function feedback */
/* For each path component of the filename, check that the long form
* of the name is the same as the short form. We scan backwards
* from the end of the filename, get the full pathname, and compare
* the last component each time:
*
* aaa\bbb\ccc\name.ext name.ext
* aaa\bbb\ccc ccc
* aaa\bbb bbb
* aaa aaa
*/
if (system_devicename (arg_filename))
return (FALSE); /* Not allowed on device names */
filename = mem_strdup (arg_filename);
feedback = TRUE; /* Assume we match everything */
strconvch (filename, '/', '\\');
if (strlast (filename) == '\\')
strlast (filename) = '\0'; /* Drop any trailing slash */
do
{
slash = strrchr (filename, '\\');
component = slash? slash + 1: filename;
handle = FindFirstFile (filename, &found);
if (handle != INVALID_HANDLE_VALUE
&& lexcmp (component, found.cFileName))
{
feedback = FALSE;
break;
}
FindClose (handle);
if (slash)
{
*slash = '\0'; /* Cut filename at slash */
if (filename [1] == ':'
&& filename [2] == '\0') /* We're at a disk specifier */
break; /* which is okay by now */
}
}
while (slash && *filename);
mem_free (filename);
return (feedback);
#else
return (TRUE); /* On other OSes, all filenames are legal */
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: file_exec_name
Synopsis: If the specified filename is an executable program, formats
a filename including any required extension and returns a static
string with that value. If the specified filename is not an executable
program, returns NULL. Under DOS, and Windows, appends ".com", ".exe",
and ".bat" to the filename, in that order, to build a possible executable
filename. Under OS/2, appends ".exe", and ".cmd" to the filename, in
that order, to build a possible executable filename. If this fails,
returns NULL. Does not search the PATH symbol; the filename must be
specified with a path if necessary. The returned filename (if not NULL)
points to a static string.
---------------------------------------------------------------------[>]-*/
char *
file_exec_name (
const char *filename)
{
#if (defined (__UNIX__) || defined (__VMS__))
ASSERT (filename);
strcpy (exec_name, filename);
if (file_mode (exec_name) & S_IXUSR)
return (exec_name);
else
return (NULL);
#elif (defined (MSDOS_FILESYSTEM))
char
*extension; /* File extension, if any */
ASSERT (filename);
/* Find file extension; if not found, set extension to empty string */
extension = strrchr (filename, '.');
if (extension == NULL
|| strchr (extension, '/') /* If last '.' is part of the path */
|| strchr (extension, '\\')) /* then the filename has no ext. */
extension = "";
/* Windows: If extension is .exe/.com/.bat, the file is an executable */
/* OS/2: If extension is .exe/.cmd, the file is executable */
# if (defined (__OS2__))
if (lexcmp (extension, ".exe") == 0
|| lexcmp (extension, ".cmd") == 0
# else /* DOS, WINDOWS */
if (lexcmp (extension, ".com") == 0
|| lexcmp (extension, ".exe") == 0
|| lexcmp (extension, ".bat") == 0
# if (defined (__WINDOWS__))
|| is_exe_file (filename)
# endif
# endif
)
{
strcpy (exec_name, filename);
return (exec_name);
}
else
/* Windows: If the extension is empty, try .com, .exe, .bat */
/* OS/2: If the extension is empty, try .exe, .cmd */
if (strnull (extension)
# if (defined (__OS2__))
&& (file_exists (default_extension (exec_name, filename, "exe"))
|| file_exists (default_extension (exec_name, filename, "cmd"))))
# else /* DOS, WINDOWS */
&& (file_exists (default_extension (exec_name, filename, "com"))
|| file_exists (default_extension (exec_name, filename, "exe"))
|| file_exists (default_extension (exec_name, filename, "bat"))))
# endif
return (exec_name); /* Executable file found */
else
return (NULL);
#else
return (NULL); /* Not supported on this system */
#endif
}
#if (defined (__WINDOWS__))
/* is_exe_file -- internal
*
* Returns TRUE if the file corresponds to the criteria for an executable
* file under Windows.
*/
static Bool
is_exe_file (const char *filename)
{
Bool
executable; /* Return code */
FILE
*stream; /* Opened file stream */
stream = file_open (filename, 'r');
if (stream)
{
executable = (fgetc (stream) == 'M' && fgetc (stream) == 'Z');
file_close (stream);
}
else
executable = FALSE; /* File not found */
return (executable);
}
#endif
/* ---------------------------------------------------------------------[<]-
Function: get_file_size
Synopsis: Returns the size, in bytes, of the specified file or
directory. The size of a directory is not a portable concept. If there
is an error, returns -1.
---------------------------------------------------------------------[>]-*/
long
get_file_size (
const char *filename)
{
struct stat
stat_buf;
ASSERT (filename);
# if (defined (MSDOS_FILESYSTEM))
if (system_devicename (filename))
return (-1); /* Not allowed on device names */
# endif
if (stat ((char *) filename, &stat_buf) == 0)
return ((long) stat_buf.st_size);
else
return (-1);
}
/* ---------------------------------------------------------------------[<]-
Function: get_file_time
Synopsis: Returns the modification time of the specified file or
directory. The returned time is suitable for feeding to localtime().
---------------------------------------------------------------------[>]-*/
time_t
get_file_time (
const char *filename)
{
#if (defined (WIN32_NOT_IMPLEMENTED))
/* This code has been disactivated because it returns incorrect
values depending on the seasonal clock change.
*/
unsigned long thi,tlo;
double dthi,dtlo;
double secs_since_1601, secs_time_t;
double delta = 11644473600.;
double two_to_32 = 4294967296.;
HANDLE handle;
FILETIME creation, last_access, last_write;
handle = CreateFile (filename, GENERIC_READ, FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, 0);
if (handle == INVALID_HANDLE_VALUE)
return (0);
GetFileTime (handle, &creation, &last_access, &last_write);
CloseHandle (handle);
thi = last_write.dwHighDateTime;
tlo = last_write.dwLowDateTime;
dthi = (double) thi;
dtlo = (double) tlo;
secs_since_1601 = (dthi * two_to_32 + dtlo) / 1.0e7;
secs_time_t = secs_since_1601 - delta;
return ((time_t) secs_time_t);
#else
struct stat
stat_buf;
ASSERT (filename);
# if (defined (MSDOS_FILESYSTEM))
if (system_devicename (filename))
return (0); /* Not allowed on device names */
# endif
if (stat ((char *) filename, &stat_buf) == 0)
return (stat_buf.st_mtime > 0? stat_buf.st_mtime: 0);
else
return (0);
#endif
}
/* ---------------------------------------------------------------------[<]-
Function: get_file_lines
Synopsis: Reads an entire file, and returns the number of lines in the
file. The file should be normal text. Returns 0 if the file cannot be
opened for reading. May be a bit slow on large files.
---------------------------------------------------------------------[>]-*/
long
get_file_lines (
const char *filename)
{
long
file_size;
FILE
*file_stream;
int
ch;
ASSERT (filename);
file_stream = file_open (filename, 'r');
if (file_stream == NULL)
return (0);
file_size = 0;
while ((ch = fgetc (file_stream)) != EOF)
if (ch == '\n')
file_size++;
fclose (file_stream);
return (file_size);
}
/* ---------------------------------------------------------------------[<]-
Function: file_slurp
Synopsis: Reads an entire file, and returns a DESCR containing the file
data. The file is read as binary data. The returned DESCR should be
freed using the mem_free() call. if the file is > 64K long, only the
first 64K bytes are read into memory. This is to stop really silly
things from happening. Returns NULL if the file cannot be found.
Appends a null byte to the data in any case.
---------------------------------------------------------------------[>]-*/
DESCR *
file_slurp (
const char *filename)
{
return (file_load_data (filename, 65535UL));
}
static DESCR *
file_load_data (const char *filename, size_t limit)
{
DESCR
*buffer;
long
file_size;
int
rc;
FILE
*file_stream;
ASSERT (filename);
file_size = get_file_size (filename);
if (file_size == -1)
return (NULL);
else
if (limit && file_size > (long) limit)
file_size = limit;
buffer = mem_descr (NULL, (size_t) file_size + 1);
if (buffer == NULL)
return (NULL);
file_stream = fopen (filename, FOPEN_READ_BINARY);
if (file_stream == NULL)
{
mem_free (buffer);
return (NULL);
}
rc = fread (buffer-> data, (size_t) file_size, 1, file_stream);
fclose (file_stream);
if (rc != 1)
{
mem_free (buffer);
return (NULL);
}
buffer-> data [(size_t) file_size] = '\0';
return (buffer);
}
/* ---------------------------------------------------------------------[<]-
Function: file_slurpl
Synopsis: Reads an entire file, and returns a DESCR containing the file
data. The file is read as binary data. The returned DESCR should be
freed using the mem_free() call. Does not impose any limit on the size
of the file (unlike file_slurp() which stops at 64K bytes). Returns NULL
if the file cannot be found. Appends a null byte to the data in any case.
---------------------------------------------------------------------[>]-*/
DESCR *
file_slurpl (
const char *filename)
{
return (file_load_data (filename, 0));
}
/* ---------------------------------------------------------------------[<]-
Function: file_set_eoln
Synopsis: Formats any end-of-line sequences in the buffer according to
the value of the add_cr argument. If this is TRUE, all end-of-lines
(LF or CRLF or LFCR) are represented by a CRLF sequence. If FALSE, all
end-of-lines are represented by LF by itself. The target buffer must
be large enough to accomodate the resulting line (twice the size of the
source data). Returns the size of the resulting data in the target
buffer not counting the final trailing null byte. The input data does
not need to be null-terminated, but the output data is terminated with
an extra null in any case.
---------------------------------------------------------------------[>]-*/
dbyte
file_set_eoln (char *dst, const char *src, dbyte src_size, Bool add_cr)
{
char
*srcptr, /* Current character in src */
*dstptr, /* Current character in dst */
*last; /* Last character in src */
ASSERT (src);
ASSERT (dst);
srcptr = (char *) src;
dstptr = dst;
last = (char *) src + src_size;
while (*srcptr && srcptr < last)
{
if (*srcptr == '\n')
{
if (add_cr)
*dstptr++ = '\r';
*dstptr++ = '\n';
}
else
if (*srcptr != '\r' && *srcptr != 26)
*dstptr++ = *srcptr;
srcptr++;
}
*dstptr = '\0';
return ((dbyte) (dstptr - dst));
}
/* ---------------------------------------------------------------------[<]-
Function: get_tmp_file_name
Synopsis: Get a temporary file name. The filename is allocated as a
fresh string, which the calling program must free when finished.
---------------------------------------------------------------------[>]-*/
char *
get_tmp_file_name (const char *path, qbyte *index, const char *ext)
{
char
index_str [9], /* Formatted 8-hex digit value */
*filename = NULL;
do
{
mem_strfree (&filename);
- sprintf (index_str, "%08lX", *index);
+ sprintf (index_str, "%08u", *index);
if (path)
filename = xstrcpy (NULL, path, "/", index_str, ".", ext, NULL);
else
filename = xstrcpy (NULL, index_str, ".", ext, NULL);
(*index)++;
}
while (file_exists (filename));
return (filename);
}
/* ---------------------------------------------------------------------[<]-
Function: file_fhredirect
Synopsis: Duplicates the dest file handle to a safe location (saves a
backup copy of it. Then duplicates the source file handle into the dest.
Returns the backup of the original dest, which can be used to undo the
redirection later. Returns -1 if there were errors.
---------------------------------------------------------------------[>]-*/
#if !defined(MINPSPW) && !defined(PS3) && !defined(XENON)
int
file_fhredirect (int source, int dest)
{
int
dupe_file_handle = 0;
dupe_file_handle = dup (dest);
if (dupe_file_handle < 0)
return (-1); /* Cannot acomplish redirection */
/* Let dup2() close dest (if open) if duplication suceeds */
if (dup2 (source, dest) < 0)
{
close (dupe_file_handle); /* Close unneeded duplicate */
return (-1); /* Cannot accomplish redirection */
}
return (dupe_file_handle); /* Return copy of file handle */
}
/* ---------------------------------------------------------------------[<]-
Function: file_fhrestore
Synopsis: Restores a file handle redirection done by file_fhredirect().
Supply the saved file handle (returned by file_fhdirect()) and the same
destination file handle. Ignores a source less than zero (invalid or
not set).
---------------------------------------------------------------------[>]-*/
void
file_fhrestore (int source, int dest)
{
if (source >= 0)
{
dup2 (source, dest);
if (source != dest)
close (source);
}
}
#endif
/* -------------------------------------------------------------------------
This list holds all temporary file references, used by ftmp_close() to
know what file to delete when a temporary file is closed.
------------------------------------------------------------------------ */
typedef struct {
void *next; /* Next item in list */
void *prev; /* Previous item in list */
FILE *stream; /* File pointer */
char *filename; /* File name */
} FTMPITEM;
static FTMPITEM
ftmplist = { &ftmplist, &ftmplist, NULL, NULL };
/* ---------------------------------------------------------------------[<]-
Function: ftmp_open
Synopsis: Creates a temporary file, like the tmpfile() function, but
without the problem under some systems where tmpfile() will try to
create temporary files on read-only drives. If the pathname argument is
not null, allocates a copy of the full filename used for the temporary
file and passes this back in the pathname argument.
---------------------------------------------------------------------[>]-*/
FILE *
ftmp_open (char **pathname)
{
static qbyte
file_number = 0; /* We generate unique file names */
FILE
*tempstream;
char
*tempdir,
*tempfile;
FTMPITEM
*tempitem;
#if (defined (MSDOS_FILESYSTEM))
tempdir = env_get_string ("TEMP", NULL);
if (!tempdir)
tempdir = env_get_string ("TMP", NULL);
if (!tempdir)
tempdir = ".";
#elif (defined (__UNIX__))
tempdir = env_get_string ("TMPDIR", NULL);
if (!tempdir)
tempdir = "/tmp";
#else
tempdir = env_get_string ("TMPDIR", NULL);
if (!tempdir)
tempdir = ".";
#endif
if (file_number == 0)
{
randomize ();
file_number = random (32767);
}
tempfile = get_tmp_file_name (tempdir, &file_number, "tmp");
if (pathname)
*pathname = mem_strdup (tempfile);
tempstream = fopen (tempfile, "wb");
if (tempstream)
{
list_create (tempitem, sizeof (FTMPITEM));
list_relink_before (&ftmplist, tempitem);
tempitem-> stream = tempstream;
tempitem-> filename = tempfile;
}
else
mem_free (tempfile);
return (tempstream);
}
/* ---------------------------------------------------------------------[<]-
Function: ftmp_close
Synopsis: Closes a temporary file created by ftmp_open(). The file
is closed and deleted.
---------------------------------------------------------------------[>]-*/
void
ftmp_close (FILE *tempstream)
{
FTMPITEM
*tempitem;
ASSERT (tempstream);
fclose (tempstream);
/* Find the matching tempitem node and release all resources */
FORLIST (tempitem, ftmplist)
{
if (tempitem-> stream == tempstream)
{
file_delete (tempitem-> filename);
mem_free (tempitem-> filename);
list_unlink (tempitem);
mem_free (tempitem);
break;
}
}
}
diff --git a/src/libs/zip/zip.c b/src/libs/zip/zip.c
index 4286a4ef..ae30763c 100644
--- a/src/libs/zip/zip.c
+++ b/src/libs/zip/zip.c
@@ -1,2004 +1,2004 @@
/* zip.c -- IO on .zip files using zlib
Version 1.1, February 14h, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Changes
Oct-2009 - Mathias Svensson - Remove old C style function prototypes
Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives
Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions.
Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data
It is used when recreting zip archive with RAW when deleting items from a zip.
ZIP64 data is automaticly added to items that needs it, and existing ZIP64 data need to be removed.
Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required)
Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <zlib.h>
#include "zip.h"
#ifdef STDC
# include <stddef.h>
# include <string.h>
# include <stdlib.h>
#endif
#ifdef NO_ERRNO_H
extern int errno;
#else
# include <errno.h>
#endif
#ifndef local
# define local static
#endif
/* compile with -Dlocal if your debugger can't find static symbols */
#ifndef VERSIONMADEBY
# define VERSIONMADEBY (0x0) /* platform depedent */
#endif
#ifndef Z_BUFSIZE
#define Z_BUFSIZE (64*1024) //(16384)
#endif
#ifndef Z_MAXFILENAMEINZIP
#define Z_MAXFILENAMEINZIP (256)
#endif
#ifndef ALLOC
# define ALLOC(size) (malloc(size))
#endif
#ifndef TRYFREE
# define TRYFREE(p) {if (p) free(p);}
#endif
/*
#define SIZECENTRALDIRITEM (0x2e)
#define SIZEZIPLOCALHEADER (0x1e)
*/
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
// NOT sure that this work on ALL platform
#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32))
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#ifndef DEF_MEM_LEVEL
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
#endif
const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
#define SIZEDATA_INDATABLOCK (4096-(4*4))
#define LOCALHEADERMAGIC (0x04034b50)
#define CENTRALHEADERMAGIC (0x02014b50)
#define ENDHEADERMAGIC (0x06054b50)
#define ZIP64ENDHEADERMAGIC (0x6064b50)
#define ZIP64ENDLOCHEADERMAGIC (0x7064b50)
#define FLAG_LOCALHEADER_OFFSET (0x06)
#define CRC_LOCALHEADER_OFFSET (0x0e)
#define SIZECENTRALHEADER (0x2e) /* 46 */
typedef struct linkedlist_datablock_internal_s
{
struct linkedlist_datablock_internal_s* next_datablock;
uLong avail_in_this_block;
uLong filled_in_this_block;
uLong unused; /* for future use and alignement */
unsigned char data[SIZEDATA_INDATABLOCK];
} linkedlist_datablock_internal;
typedef struct linkedlist_data_s
{
linkedlist_datablock_internal* first_block;
linkedlist_datablock_internal* last_block;
} linkedlist_data;
typedef struct
{
z_stream stream; /* zLib stream structure for inflate */
#ifdef HAVE_BZIP2
bz_stream bstream; /* bzLib stream structure for bziped */
#endif
int stream_initialised; /* 1 is stream is initialised */
uInt pos_in_buffered_data; /* last written byte in buffered_data */
ZPOS64_T pos_local_header; /* offset of the local header of the file
currenty writing */
char* central_header; /* central header data for the current file */
uLong size_centralExtra;
uLong size_centralheader; /* size of the central header for cur file */
uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */
uLong flag; /* flag of the file currently writing */
int method; /* compression method of file currenty wr.*/
int raw; /* 1 for directly writing raw data */
Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/
uLong dosDate;
uLong crc32;
int encrypt;
int zip64; /* Add ZIP64 extened information in the extra field */
ZPOS64_T pos_zip64extrainfo;
ZPOS64_T totalCompressedData;
ZPOS64_T totalUncompressedData;
#ifndef NOCRYPT
unsigned long keys[3]; /* keys defining the pseudo-random sequence */
const unsigned long* pcrc_32_tab;
int crypt_header_size;
#endif
} curfile64_info;
typedef struct
{
zlib_filefunc64_32_def z_filefunc;
voidpf filestream; /* io structore of the zipfile */
linkedlist_data central_dir;/* datablock with central dir in construction*/
int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/
curfile64_info ci; /* info on the file curretly writing */
ZPOS64_T begin_pos; /* position of the beginning of the zipfile */
ZPOS64_T add_position_when_writting_offset;
ZPOS64_T number_entry;
#ifndef NO_ADDFILEINEXISTINGZIP
char *globalcomment;
#endif
} zip64_internal;
#ifndef NOCRYPT
#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED
#include "crypt.h"
#endif
local linkedlist_datablock_internal* allocate_new_datablock()
{
linkedlist_datablock_internal* ldi;
ldi = (linkedlist_datablock_internal*)
ALLOC(sizeof(linkedlist_datablock_internal));
if (ldi!=NULL)
{
ldi->next_datablock = NULL ;
ldi->filled_in_this_block = 0 ;
ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ;
}
return ldi;
}
local void free_datablock(linkedlist_datablock_internal* ldi)
{
while (ldi!=NULL)
{
linkedlist_datablock_internal* ldinext = ldi->next_datablock;
TRYFREE(ldi);
ldi = ldinext;
}
}
local void init_linkedlist(linkedlist_data* ll)
{
ll->first_block = ll->last_block = NULL;
}
local void free_linkedlist(linkedlist_data* ll)
{
free_datablock(ll->first_block);
ll->first_block = ll->last_block = NULL;
}
local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len)
{
linkedlist_datablock_internal* ldi;
const unsigned char* from_copy;
if (ll==NULL)
return ZIP_INTERNALERROR;
if (ll->last_block == NULL)
{
ll->first_block = ll->last_block = allocate_new_datablock();
if (ll->first_block == NULL)
return ZIP_INTERNALERROR;
}
ldi = ll->last_block;
from_copy = (unsigned char*)buf;
while (len>0)
{
uInt copy_this;
uInt i;
unsigned char* to_copy;
if (ldi->avail_in_this_block==0)
{
ldi->next_datablock = allocate_new_datablock();
if (ldi->next_datablock == NULL)
return ZIP_INTERNALERROR;
ldi = ldi->next_datablock ;
ll->last_block = ldi;
}
if (ldi->avail_in_this_block < len)
copy_this = (uInt)ldi->avail_in_this_block;
else
copy_this = (uInt)len;
to_copy = &(ldi->data[ldi->filled_in_this_block]);
for (i=0;i<copy_this;i++)
*(to_copy+i)=*(from_copy+i);
ldi->filled_in_this_block += copy_this;
ldi->avail_in_this_block -= copy_this;
from_copy += copy_this ;
len -= copy_this;
}
return ZIP_OK;
}
/****************************************************************************/
#ifndef NO_ADDFILEINEXISTINGZIP
/* ===========================================================================
Inputs a long in LSB order to the given file
nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T)
*/
local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte));
local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)
{
unsigned char buf[8];
int n;
for (n = 0; n < nbByte; n++)
{
buf[n] = (unsigned char)(x & 0xff);
x >>= 8;
}
if (x != 0)
{ /* data overflow - hack for ZIP64 (X Roche) */
for (n = 0; n < nbByte; n++)
{
buf[n] = 0xff;
}
}
if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte)
return ZIP_ERRNO;
else
return ZIP_OK;
}
local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte));
local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte)
{
unsigned char* buf=(unsigned char*)dest;
int n;
for (n = 0; n < nbByte; n++) {
buf[n] = (unsigned char)(x & 0xff);
x >>= 8;
}
if (x != 0)
{ /* data overflow - hack for ZIP64 */
for (n = 0; n < nbByte; n++)
{
buf[n] = 0xff;
}
}
}
/****************************************************************************/
local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm)
{
uLong year = (uLong)ptm->tm_year;
if (year>=1980)
year-=1980;
else if (year>=80)
year-=80;
return
(uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) |
((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour));
}
/****************************************************************************/
local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi));
local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi)
{
unsigned char c;
int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
if (err==1)
{
*pi = (int)c;
return ZIP_OK;
}
else
{
if (ZERROR64(*pzlib_filefunc_def,filestream))
return ZIP_ERRNO;
else
return ZIP_EOF;
}
}
/* ===========================================================================
Reads a long in LSB order from the given gz_stream. Sets
*/
local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
{
uLong x ;
int i = 0;
int err;
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x = (uLong)i;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<8;
if (err==ZIP_OK)
*pX = x;
else
*pX = 0;
return err;
}
local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
{
uLong x ;
int i = 0;
int err;
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x = (uLong)i;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<8;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<16;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<24;
if (err==ZIP_OK)
*pX = x;
else
*pX = 0;
return err;
}
local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX));
local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)
{
ZPOS64_T x;
int i = 0;
int err;
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x = (ZPOS64_T)i;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<8;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<16;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<24;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<32;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<40;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<48;
if (err==ZIP_OK)
err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
x += ((ZPOS64_T)i)<<56;
if (err==ZIP_OK)
*pX = x;
else
*pX = 0;
return err;
}
#ifndef BUFREADCOMMENT
#define BUFREADCOMMENT (0x400)
#endif
/*
Locate the Central directory of a zipfile (at the end, just before
the global comment)
*/
local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
{
unsigned char* buf;
ZPOS64_T uSizeFile;
ZPOS64_T uBackRead;
ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
ZPOS64_T uPosFound=0;
if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
return 0;
uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
if (uMaxBack>uSizeFile)
uMaxBack = uSizeFile;
buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
if (buf==NULL)
return 0;
uBackRead = 4;
while (uBackRead<uMaxBack)
{
uLong uReadSize;
ZPOS64_T uReadPos ;
int i;
if (uBackRead+BUFREADCOMMENT>uMaxBack)
uBackRead = uMaxBack;
else
uBackRead+=BUFREADCOMMENT;
uReadPos = uSizeFile-uBackRead ;
uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
(BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
break;
if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
break;
for (i=(int)uReadSize-3; (i--)>0;)
if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
{
uPosFound = uReadPos+i;
break;
}
if (uPosFound!=0)
break;
}
TRYFREE(buf);
return uPosFound;
}
/*
Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before
the global comment)
*/
local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
{
unsigned char* buf;
ZPOS64_T uSizeFile;
ZPOS64_T uBackRead;
ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
ZPOS64_T uPosFound=0;
uLong uL;
ZPOS64_T relativeOffset;
if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
return 0;
uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
if (uMaxBack>uSizeFile)
uMaxBack = uSizeFile;
buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
if (buf==NULL)
return 0;
uBackRead = 4;
while (uBackRead<uMaxBack)
{
uLong uReadSize;
ZPOS64_T uReadPos;
int i;
if (uBackRead+BUFREADCOMMENT>uMaxBack)
uBackRead = uMaxBack;
else
uBackRead+=BUFREADCOMMENT;
uReadPos = uSizeFile-uBackRead ;
uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
(BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
break;
if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
break;
for (i=(int)uReadSize-3; (i--)>0;)
{
// Signature "0x07064b50" Zip64 end of central directory locater
if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
{
uPosFound = uReadPos+i;
break;
}
}
if (uPosFound!=0)
break;
}
TRYFREE(buf);
if (uPosFound == 0)
return 0;
/* Zip64 end of central directory locator */
if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
return 0;
/* the signature, already checked */
if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
return 0;
/* number of the disk with the start of the zip64 end of central directory */
if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
return 0;
if (uL != 0)
return 0;
/* relative offset of the zip64 end of central directory record */
if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK)
return 0;
/* total number of disks */
if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
return 0;
if (uL != 1)
return 0;
/* Goto Zip64 end of central directory record */
if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
return 0;
/* the signature */
if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
return 0;
if (uL != 0x06064b50) // signature of 'Zip64 end of central directory'
return 0;
return relativeOffset;
}
int LoadCentralDirectoryRecord(zip64_internal* pziinit)
{
int err=ZIP_OK;
ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
ZPOS64_T size_central_dir; /* size of the central directory */
ZPOS64_T offset_central_dir; /* offset of start of central directory */
ZPOS64_T central_pos;
uLong uL;
uLong number_disk; /* number of the current dist, used for
spaning ZIP, unsupported, always 0*/
uLong number_disk_with_CD; /* number the the disk with central dir, used
for spaning ZIP, unsupported, always 0*/
ZPOS64_T number_entry;
ZPOS64_T number_entry_CD; /* total number of entries in
the central dir
(same than number_entry on nospan) */
uLong VersionMadeBy;
uLong VersionNeeded;
uLong size_comment;
int hasZIP64Record = 0;
// check first if we find a ZIP64 record
central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream);
if(central_pos > 0)
{
hasZIP64Record = 1;
}
else if(central_pos == 0)
{
central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream);
}
/* disable to allow appending to empty ZIP archive
if (central_pos==0)
err=ZIP_ERRNO;
*/
if(hasZIP64Record)
{
ZPOS64_T sizeEndOfCentralDirectory;
if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0)
err=ZIP_ERRNO;
/* the signature, already checked */
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
err=ZIP_ERRNO;
/* size of zip64 end of central directory record */
if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK)
err=ZIP_ERRNO;
/* version made by */
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK)
err=ZIP_ERRNO;
/* version needed to extract */
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK)
err=ZIP_ERRNO;
/* number of this disk */
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
err=ZIP_ERRNO;
/* number of the disk with the start of the central directory */
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
err=ZIP_ERRNO;
/* total number of entries in the central directory on this disk */
if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK)
err=ZIP_ERRNO;
/* total number of entries in the central directory */
if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK)
err=ZIP_ERRNO;
if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
err=ZIP_BADZIPFILE;
/* size of the central directory */
if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK)
err=ZIP_ERRNO;
/* offset of start of central directory with respect to the
starting disk number */
if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK)
err=ZIP_ERRNO;
// TODO..
// read the comment from the standard central header.
size_comment = 0;
}
else
{
// Read End of central Directory info
if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
err=ZIP_ERRNO;
/* the signature, already checked */
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
err=ZIP_ERRNO;
/* number of this disk */
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
err=ZIP_ERRNO;
/* number of the disk with the start of the central directory */
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
err=ZIP_ERRNO;
/* total number of entries in the central dir on this disk */
number_entry = 0;
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
err=ZIP_ERRNO;
else
number_entry = uL;
/* total number of entries in the central dir */
number_entry_CD = 0;
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
err=ZIP_ERRNO;
else
number_entry_CD = uL;
if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
err=ZIP_BADZIPFILE;
/* size of the central directory */
size_central_dir = 0;
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
err=ZIP_ERRNO;
else
size_central_dir = uL;
/* offset of start of central directory with respect to the starting disk number */
offset_central_dir = 0;
if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
err=ZIP_ERRNO;
else
offset_central_dir = uL;
/* zipfile global comment length */
if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK)
err=ZIP_ERRNO;
}
if ((central_pos<offset_central_dir+size_central_dir) &&
(err==ZIP_OK))
err=ZIP_BADZIPFILE;
if (err!=ZIP_OK)
{
ZCLOSE64(pziinit->z_filefunc, pziinit->filestream);
return ZIP_ERRNO;
}
if (size_comment>0)
{
pziinit->globalcomment = (char*)ALLOC(size_comment+1);
if (pziinit->globalcomment)
{
size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment);
pziinit->globalcomment[size_comment]=0;
}
}
byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir);
pziinit->add_position_when_writting_offset = byte_before_the_zipfile;
{
ZPOS64_T size_central_dir_to_read = size_central_dir;
size_t buf_size = SIZEDATA_INDATABLOCK;
void* buf_read = (void*)ALLOC(buf_size);
if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0)
err=ZIP_ERRNO;
while ((size_central_dir_to_read>0) && (err==ZIP_OK))
{
ZPOS64_T read_this = SIZEDATA_INDATABLOCK;
if (read_this > size_central_dir_to_read)
read_this = size_central_dir_to_read;
if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this)
err=ZIP_ERRNO;
if (err==ZIP_OK)
err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this);
size_central_dir_to_read-=read_this;
}
TRYFREE(buf_read);
}
pziinit->begin_pos = byte_before_the_zipfile;
pziinit->number_entry = number_entry_CD;
if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0)
err=ZIP_ERRNO;
return err;
}
#endif /* !NO_ADDFILEINEXISTINGZIP*/
/************************************************************/
extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def)
{
zip64_internal ziinit;
zip64_internal* zi;
int err=ZIP_OK;
ziinit.z_filefunc.zseek32_file = NULL;
ziinit.z_filefunc.ztell32_file = NULL;
if (pzlib_filefunc64_32_def==NULL)
fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64);
else
ziinit.z_filefunc = *pzlib_filefunc64_32_def;
ziinit.filestream = ZOPEN64(ziinit.z_filefunc,
pathname,
(append == APPEND_STATUS_CREATE) ?
(ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) :
(ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING));
if (ziinit.filestream == NULL)
return NULL;
if (append == APPEND_STATUS_CREATEAFTER)
ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END);
ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream);
ziinit.in_opened_file_inzip = 0;
ziinit.ci.stream_initialised = 0;
ziinit.number_entry = 0;
ziinit.add_position_when_writting_offset = 0;
init_linkedlist(&(ziinit.central_dir));
zi = (zip64_internal*)ALLOC(sizeof(zip64_internal));
if (zi==NULL)
{
ZCLOSE64(ziinit.z_filefunc,ziinit.filestream);
return NULL;
}
/* now we add file in a zipfile */
# ifndef NO_ADDFILEINEXISTINGZIP
ziinit.globalcomment = NULL;
if (append == APPEND_STATUS_ADDINZIP)
{
// Read and Cache Central Directory Records
err = LoadCentralDirectoryRecord(&ziinit);
}
if (globalcomment)
{
*globalcomment = ziinit.globalcomment;
}
# endif /* !NO_ADDFILEINEXISTINGZIP*/
if (err != ZIP_OK)
{
# ifndef NO_ADDFILEINEXISTINGZIP
TRYFREE(ziinit.globalcomment);
# endif /* !NO_ADDFILEINEXISTINGZIP*/
TRYFREE(zi);
return NULL;
}
else
{
*zi = ziinit;
return (zipFile)zi;
}
}
extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def)
{
if (pzlib_filefunc32_def != NULL)
{
zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
}
else
return zipOpen3(pathname, append, globalcomment, NULL);
}
extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def)
{
if (pzlib_filefunc_def != NULL)
{
zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
zlib_filefunc64_32_def_fill.ztell32_file = NULL;
zlib_filefunc64_32_def_fill.zseek32_file = NULL;
return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
}
else
return zipOpen3(pathname, append, globalcomment, NULL);
}
extern zipFile ZEXPORT zipOpen (const char* pathname, int append)
{
return zipOpen3((const void*)pathname,append,NULL,NULL);
}
extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append)
{
return zipOpen3(pathname,append,NULL,NULL);
}
int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local)
{
/* write the local header */
int err;
uInt size_filename = (uInt)strlen(filename);
uInt size_extrafield = size_extrafield_local;
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4);
if (err==ZIP_OK)
{
if(zi->ci.zip64)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */
}
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2);
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2);
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4);
// CRC / Compressed size / Uncompressed size will be filled in later and rewritten later
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */
if (err==ZIP_OK)
{
if(zi->ci.zip64)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */
}
if (err==ZIP_OK)
{
if(zi->ci.zip64)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */
}
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2);
if(zi->ci.zip64)
{
size_extrafield += 20;
}
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2);
if ((err==ZIP_OK) && (size_filename > 0))
{
if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename)
err = ZIP_ERRNO;
}
if ((err==ZIP_OK) && (size_extrafield_local > 0))
{
if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local)
err = ZIP_ERRNO;
}
if ((err==ZIP_OK) && (zi->ci.zip64))
{
// write the Zip64 extended info
short HeaderID = 1;
short DataSize = 16;
ZPOS64_T CompressedSize = 0;
ZPOS64_T UncompressedSize = 0;
// Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file)
zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream);
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2);
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2);
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8);
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8);
}
return err;
}
/*
NOTE.
When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped
before calling this function it can be done with zipRemoveExtraInfoBlock
It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize
unnecessary allocations.
*/
extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw,
int windowBits,int memLevel, int strategy,
const char* password, uLong crcForCrypting,
uLong versionMadeBy, uLong flagBase, int zip64)
{
zip64_internal* zi;
uInt size_filename;
uInt size_comment;
uInt i;
int err = ZIP_OK;
# ifdef NOCRYPT
if (password != NULL)
return ZIP_PARAMERROR;
# endif
if (file == NULL)
return ZIP_PARAMERROR;
#ifdef HAVE_BZIP2
if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED))
return ZIP_PARAMERROR;
#else
if ((method!=0) && (method!=Z_DEFLATED))
return ZIP_PARAMERROR;
#endif
zi = (zip64_internal*)file;
if (zi->in_opened_file_inzip == 1)
{
err = zipCloseFileInZip (file);
if (err != ZIP_OK)
return err;
}
if (filename==NULL)
filename="-";
if (comment==NULL)
size_comment = 0;
else
size_comment = (uInt)strlen(comment);
size_filename = (uInt)strlen(filename);
if (zipfi == NULL)
zi->ci.dosDate = 0;
else
{
if (zipfi->dosDate != 0)
zi->ci.dosDate = zipfi->dosDate;
else
zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date);
}
zi->ci.flag = flagBase;
if ((level==8) || (level==9))
zi->ci.flag |= 2;
if (level==2)
zi->ci.flag |= 4;
if (level==1)
zi->ci.flag |= 6;
if (password != NULL)
zi->ci.flag |= 1;
zi->ci.crc32 = 0;
zi->ci.method = method;
zi->ci.encrypt = 0;
zi->ci.stream_initialised = 0;
zi->ci.pos_in_buffered_data = 0;
zi->ci.raw = raw;
zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream);
zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment;
zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data
zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree);
zi->ci.size_centralExtra = size_extrafield_global;
zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
/* version info */
zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2);
zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/
if (zipfi==NULL)
zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
else
zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);
if (zipfi==NULL)
zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
else
zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);
if(zi->ci.pos_local_header >= 0xffffffff)
zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4);
else
zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writting_offset,4);
for (i=0;i<size_filename;i++)
*(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);
for (i=0;i<size_extrafield_global;i++)
*(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
*(((const char*)extrafield_global)+i);
for (i=0;i<size_comment;i++)
*(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
size_extrafield_global+i) = *(comment+i);
if (zi->ci.central_header == NULL)
return ZIP_INTERNALERROR;
zi->ci.zip64 = zip64;
zi->ci.totalCompressedData = 0;
zi->ci.totalUncompressedData = 0;
zi->ci.pos_zip64extrainfo = 0;
err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local);
#ifdef HAVE_BZIP2
zi->ci.bstream.avail_in = (uInt)0;
zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
zi->ci.bstream.total_in_hi32 = 0;
zi->ci.bstream.total_in_lo32 = 0;
zi->ci.bstream.total_out_hi32 = 0;
zi->ci.bstream.total_out_lo32 = 0;
#endif
zi->ci.stream.avail_in = (uInt)0;
zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.stream.next_out = zi->ci.buffered_data;
zi->ci.stream.total_in = 0;
zi->ci.stream.total_out = 0;
zi->ci.stream.data_type = Z_BINARY;
#ifdef HAVE_BZIP2
if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
#else
if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
#endif
{
if(zi->ci.method == Z_DEFLATED)
{
zi->ci.stream.zalloc = (alloc_func)0;
zi->ci.stream.zfree = (free_func)0;
zi->ci.stream.opaque = (voidpf)0;
if (windowBits>0)
windowBits = -windowBits;
err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy);
if (err==Z_OK)
zi->ci.stream_initialised = Z_DEFLATED;
}
else if(zi->ci.method == Z_BZIP2ED)
{
#ifdef HAVE_BZIP2
// Init BZip stuff here
zi->ci.bstream.bzalloc = 0;
zi->ci.bstream.bzfree = 0;
zi->ci.bstream.opaque = (voidpf)0;
err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35);
if(err == BZ_OK)
zi->ci.stream_initialised = Z_BZIP2ED;
#endif
}
}
# ifndef NOCRYPT
zi->ci.crypt_header_size = 0;
if ((err==Z_OK) && (password != NULL))
{
unsigned char bufHead[RAND_HEAD_LEN];
unsigned int sizeHead;
zi->ci.encrypt = 1;
- zi->ci.pcrc_32_tab = get_crc_table();
+ zi->ci.pcrc_32_tab = (const unsigned long*) get_crc_table();
/*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/
sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting);
zi->ci.crypt_header_size = sizeHead;
if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead)
err = ZIP_ERRNO;
}
# endif
if (err==Z_OK)
zi->in_opened_file_inzip = 1;
return err;
}
extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw,
int windowBits,int memLevel, int strategy,
const char* password, uLong crcForCrypting,
uLong versionMadeBy, uLong flagBase)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, raw,
windowBits, memLevel, strategy,
password, crcForCrypting, versionMadeBy, flagBase, 0);
}
extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw,
int windowBits,int memLevel, int strategy,
const char* password, uLong crcForCrypting)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, raw,
windowBits, memLevel, strategy,
password, crcForCrypting, VERSIONMADEBY, 0, 0);
}
extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw,
int windowBits,int memLevel, int strategy,
const char* password, uLong crcForCrypting, int zip64)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, raw,
windowBits, memLevel, strategy,
password, crcForCrypting, VERSIONMADEBY, 0, zip64);
}
extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, raw,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
NULL, 0, VERSIONMADEBY, 0, 0);
}
extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int raw, int zip64)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, raw,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
NULL, 0, VERSIONMADEBY, 0, zip64);
}
extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void*extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level, int zip64)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, 0,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
NULL, 0, VERSIONMADEBY, 0, zip64);
}
extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi,
const void* extrafield_local, uInt size_extrafield_local,
const void*extrafield_global, uInt size_extrafield_global,
const char* comment, int method, int level)
{
return zipOpenNewFileInZip4_64 (file, filename, zipfi,
extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global,
comment, method, level, 0,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
NULL, 0, VERSIONMADEBY, 0, 0);
}
local int zip64FlushWriteBuffer(zip64_internal* zi)
{
int err=ZIP_OK;
if (zi->ci.encrypt != 0)
{
#ifndef NOCRYPT
uInt i;
int t;
for (i=0;i<zi->ci.pos_in_buffered_data;i++)
zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t);
#endif
}
if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data)
err = ZIP_ERRNO;
zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data;
#ifdef HAVE_BZIP2
if(zi->ci.method == Z_BZIP2ED)
{
zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32;
zi->ci.bstream.total_in_lo32 = 0;
zi->ci.bstream.total_in_hi32 = 0;
}
else
#endif
{
zi->ci.totalUncompressedData += zi->ci.stream.total_in;
zi->ci.stream.total_in = 0;
}
zi->ci.pos_in_buffered_data = 0;
return err;
}
extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len)
{
zip64_internal* zi;
int err=ZIP_OK;
if (file == NULL)
return ZIP_PARAMERROR;
zi = (zip64_internal*)file;
if (zi->in_opened_file_inzip == 0)
return ZIP_PARAMERROR;
zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len);
#ifdef HAVE_BZIP2
if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw))
{
zi->ci.bstream.next_in = (void*)buf;
zi->ci.bstream.avail_in = len;
err = BZ_RUN_OK;
while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0))
{
if (zi->ci.bstream.avail_out == 0)
{
if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
err = ZIP_ERRNO;
zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
}
if(err != BZ_RUN_OK)
break;
if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
{
uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32;
// uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32;
err=BZ2_bzCompress(&zi->ci.bstream, BZ_RUN);
zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ;
}
}
if(err == BZ_RUN_OK)
err = ZIP_OK;
}
else
#endif
{
zi->ci.stream.next_in = (Bytef*)buf;
zi->ci.stream.avail_in = len;
while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0))
{
if (zi->ci.stream.avail_out == 0)
{
if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
err = ZIP_ERRNO;
zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.stream.next_out = zi->ci.buffered_data;
}
if(err != ZIP_OK)
break;
if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
{
uLong uTotalOutBefore = zi->ci.stream.total_out;
err=deflate(&zi->ci.stream, Z_NO_FLUSH);
if(uTotalOutBefore > zi->ci.stream.total_out)
{
int bBreak = 0;
bBreak++;
}
zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
}
else
{
uInt copy_this,i;
if (zi->ci.stream.avail_in < zi->ci.stream.avail_out)
copy_this = zi->ci.stream.avail_in;
else
copy_this = zi->ci.stream.avail_out;
for (i = 0; i < copy_this; i++)
*(((char*)zi->ci.stream.next_out)+i) =
*(((const char*)zi->ci.stream.next_in)+i);
{
zi->ci.stream.avail_in -= copy_this;
zi->ci.stream.avail_out-= copy_this;
zi->ci.stream.next_in+= copy_this;
zi->ci.stream.next_out+= copy_this;
zi->ci.stream.total_in+= copy_this;
zi->ci.stream.total_out+= copy_this;
zi->ci.pos_in_buffered_data += copy_this;
}
}
}// while(...)
}
return err;
}
extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32)
{
return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32);
}
extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32)
{
zip64_internal* zi;
ZPOS64_T compressed_size;
uLong invalidValue = 0xffffffff;
short datasize = 0;
int err=ZIP_OK;
if (file == NULL)
return ZIP_PARAMERROR;
zi = (zip64_internal*)file;
if (zi->in_opened_file_inzip == 0)
return ZIP_PARAMERROR;
zi->ci.stream.avail_in = 0;
if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
{
while (err==ZIP_OK)
{
uLong uTotalOutBefore;
if (zi->ci.stream.avail_out == 0)
{
if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
err = ZIP_ERRNO;
zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.stream.next_out = zi->ci.buffered_data;
}
uTotalOutBefore = zi->ci.stream.total_out;
err=deflate(&zi->ci.stream, Z_FINISH);
zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
}
}
else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
{
#ifdef HAVE_BZIP2
err = BZ_FINISH_OK;
while (err==BZ_FINISH_OK)
{
uLong uTotalOutBefore;
if (zi->ci.bstream.avail_out == 0)
{
if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
err = ZIP_ERRNO;
zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
}
uTotalOutBefore = zi->ci.bstream.total_out_lo32;
err=BZ2_bzCompress(&zi->ci.bstream, BZ_FINISH);
if(err == BZ_STREAM_END)
err = Z_STREAM_END;
zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore);
}
if(err == BZ_FINISH_OK)
err = ZIP_OK;
#endif
}
if (err==Z_STREAM_END)
err=ZIP_OK; /* this is normal */
if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK))
{
if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO)
err = ZIP_ERRNO;
}
if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
{
int tmp_err = deflateEnd(&zi->ci.stream);
if (err == ZIP_OK)
err = tmp_err;
zi->ci.stream_initialised = 0;
}
#ifdef HAVE_BZIP2
else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
{
int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream);
if (err==ZIP_OK)
err = tmperr;
zi->ci.stream_initialised = 0;
}
#endif
if (!zi->ci.raw)
{
crc32 = (uLong)zi->ci.crc32;
uncompressed_size = zi->ci.totalUncompressedData;
}
compressed_size = zi->ci.totalCompressedData;
# ifndef NOCRYPT
compressed_size += zi->ci.crypt_header_size;
# endif
// update Current Item crc and sizes,
if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff)
{
/*version Made by*/
zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2);
/*version needed*/
zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2);
}
zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/
if(compressed_size >= 0xffffffff)
zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/
else
zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/
/// set internal file attributes field
if (zi->ci.stream.data_type == Z_ASCII)
zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2);
if(uncompressed_size >= 0xffffffff)
zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/
else
zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/
// Add ZIP64 extra info field for uncompressed size
if(uncompressed_size >= 0xffffffff)
datasize += 8;
// Add ZIP64 extra info field for compressed size
if(compressed_size >= 0xffffffff)
datasize += 8;
// Add ZIP64 extra info field for relative offset to local file header of current file
if(zi->ci.pos_local_header >= 0xffffffff)
datasize += 8;
if(datasize > 0)
{
char* p = NULL;
if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree)
{
// we can not write more data to the buffer that we have room for.
return ZIP_BADZIPFILE;
}
p = zi->ci.central_header + zi->ci.size_centralheader;
// Add Extra Information Header for 'ZIP64 information'
zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID
p += 2;
zip64local_putValue_inmemory(p, datasize, 2); // DataSize
p += 2;
if(uncompressed_size >= 0xffffffff)
{
zip64local_putValue_inmemory(p, uncompressed_size, 8);
p += 8;
}
if(compressed_size >= 0xffffffff)
{
zip64local_putValue_inmemory(p, compressed_size, 8);
p += 8;
}
if(zi->ci.pos_local_header >= 0xffffffff)
{
zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8);
p += 8;
}
// Update how much extra free space we got in the memory buffer
// and increase the centralheader size so the new ZIP64 fields are included
// ( 4 below is the size of HeaderID and DataSize field )
zi->ci.size_centralExtraFree -= datasize + 4;
zi->ci.size_centralheader += datasize + 4;
// Update the extra info size field
zi->ci.size_centralExtra += datasize + 4;
zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2);
}
if (err==ZIP_OK)
err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader);
free(zi->ci.central_header);
if (err==ZIP_OK)
{
// Update the LocalFileHeader with the new values.
ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0)
err = ZIP_ERRNO;
if (err==ZIP_OK)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */
if(uncompressed_size >= 0xffffffff)
{
if(zi->ci.pos_zip64extrainfo > 0)
{
// Update the size in the ZIP64 extended field.
if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0)
err = ZIP_ERRNO;
if (err==ZIP_OK) /* compressed size, unknown */
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8);
if (err==ZIP_OK) /* uncompressed size, unknown */
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8);
}
}
else
{
if (err==ZIP_OK) /* compressed size, unknown */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4);
if (err==ZIP_OK) /* uncompressed size, unknown */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4);
}
if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0)
err = ZIP_ERRNO;
}
zi->number_entry ++;
zi->in_opened_file_inzip = 0;
return err;
}
extern int ZEXPORT zipCloseFileInZip (zipFile file)
{
return zipCloseFileInZipRaw (file,0,0);
}
int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip)
{
int err = ZIP_OK;
ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writting_offset;
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4);
/*num disks*/
if (err==ZIP_OK) /* number of the disk with the start of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
/*relative offset*/
if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8);
/*total disks*/ /* Do not support spawning of disk so always say 1 here*/
if (err==ZIP_OK) /* number of the disk with the start of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4);
return err;
}
int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
{
int err = ZIP_OK;
uLong Zip64DataSize = 44;
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4);
if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ?
if (err==ZIP_OK) /* version made by */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
if (err==ZIP_OK) /* version needed */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
if (err==ZIP_OK) /* number of this disk */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
if (err==ZIP_OK) /* number of the disk with the start of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
if (err==ZIP_OK) /* total number of entries in the central dir */
err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
if (err==ZIP_OK) /* size of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8);
if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
{
ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8);
}
return err;
}
int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
{
int err = ZIP_OK;
/*signature*/
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4);
if (err==ZIP_OK) /* number of this disk */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
if (err==ZIP_OK) /* number of the disk with the start of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
{
{
if(zi->number_entry >= 0xFFFF)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
}
}
if (err==ZIP_OK) /* total number of entries in the central dir */
{
if(zi->number_entry >= 0xFFFF)
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
}
if (err==ZIP_OK) /* size of the central directory */
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4);
if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
{
ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
if(pos >= 0xffffffff)
{
err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4);
}
else
err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4);
}
return err;
}
int Write_GlobalComment(zip64_internal* zi, const char* global_comment)
{
int err = ZIP_OK;
uInt size_global_comment = 0;
if(global_comment != NULL)
size_global_comment = (uInt)strlen(global_comment);
err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2);
if (err == ZIP_OK && size_global_comment > 0)
{
if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment)
err = ZIP_ERRNO;
}
return err;
}
extern int ZEXPORT zipClose (zipFile file, const char* global_comment)
{
zip64_internal* zi;
int err = 0;
uLong size_centraldir = 0;
ZPOS64_T centraldir_pos_inzip;
ZPOS64_T pos;
if (file == NULL)
return ZIP_PARAMERROR;
zi = (zip64_internal*)file;
if (zi->in_opened_file_inzip == 1)
{
err = zipCloseFileInZip (file);
}
#ifndef NO_ADDFILEINEXISTINGZIP
if (global_comment==NULL)
global_comment = zi->globalcomment;
#endif
centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
if (err==ZIP_OK)
{
linkedlist_datablock_internal* ldi = zi->central_dir.first_block;
while (ldi!=NULL)
{
if ((err==ZIP_OK) && (ldi->filled_in_this_block>0))
{
if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block)
err = ZIP_ERRNO;
}
size_centraldir += ldi->filled_in_this_block;
ldi = ldi->next_datablock;
}
}
free_linkedlist(&(zi->central_dir));
pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
if(pos >= 0xffffffff)
{
ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream);
Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos);
}
if (err==ZIP_OK)
err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
if(err == ZIP_OK)
err = Write_GlobalComment(zi, global_comment);
if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0)
if (err == ZIP_OK)
err = ZIP_ERRNO;
#ifndef NO_ADDFILEINEXISTINGZIP
TRYFREE(zi->globalcomment);
#endif
TRYFREE(zi);
return err;
}
extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader)
{
char* p = pData;
int size = 0;
char* pNewHeader;
char* pTmp;
short header;
short dataSize;
int retVal = ZIP_OK;
if(pData == NULL || *dataLen < 4)
return ZIP_PARAMERROR;
pNewHeader = (char*)ALLOC(*dataLen);
pTmp = pNewHeader;
while(p < (pData + *dataLen))
{
header = *(short*)p;
dataSize = *(((short*)p)+1);
if( header == sHeader ) // Header found.
{
p += dataSize + 4; // skip it. do not copy to temp buffer
}
else
{
// Extra Info block should not be removed, So copy it to the temp buffer.
memcpy(pTmp, p, dataSize + 4);
p += dataSize + 4;
size += dataSize + 4;
}
}
if(size < *dataLen)
{
// clean old extra info block.
memset(pData,0, *dataLen);
// copy the new extra info block over the old
if(size > 0)
memcpy(pData, pNewHeader, size);
// set the new extra info size
*dataLen = size;
retVal = ZIP_OK;
}
else
retVal = ZIP_ERRNO;
TRYFREE(pNewHeader);
return retVal;
}
diff --git a/tests/init/main.cpp b/tests/init/main.cpp
index f72ab52d..6b75a9a0 100644
--- a/tests/init/main.cpp
+++ b/tests/init/main.cpp
@@ -1,26 +1,28 @@
#include <r-tech1/init.h>
#include <r-tech1/debug.h>
#include <r-tech1/file-system.h>
+#include <r-tech1/graphics/bitmap.h>
Filesystem::AbsolutePath Filesystem::configFile(){
return Filesystem::AbsolutePath("config");
}
Filesystem::AbsolutePath Filesystem::userDirectory(){
return Filesystem::AbsolutePath("/tmp");
}
int main(int argc, char ** argv){
Global::InitConditions conditions;
Global::debug(0) << "Starting up r-tech1..." << std::endl;
Global::init(conditions);
Global::debug(0) << "Done! Exiting..." << std::endl;
+ Graphics::Bitmap::shutdown();
Global::close();
return 0;
}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Jun 15, 11:34 PM (2 w, 2 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
72179
Default Alt Text
(283 KB)

Event Timeline