diff --git a/Makefile.am b/Makefile.am index 6af6516c..9d39bdc5 100644 --- a/Makefile.am +++ b/Makefile.am @@ -22,6 +22,7 @@ libreadstat_la_SOURCES = \ src/sas/readstat_sas7bdat_write.c \ src/sas/readstat_sas_rle.c \ src/sas/readstat_sas_rdc.c \ + src/sas/readstat_cport_read.c \ src/sas/readstat_xport.c \ src/sas/readstat_xport_read.c \ src/sas/readstat_xport_write.c \ @@ -96,6 +97,9 @@ EXTRA_DIST = \ resources/compression_type_0x0d.sas7bdat \ resources/format_with_default_32bit.sas7bcat \ resources/format_with_default_64bit.sas7bcat \ + resources/cport_basic_win94.xpt \ + resources/cport_basic_viya_nocompress.xpt \ + resources/cport_encoding_viya.xpt \ resources/sav_missing_continuations.sav include_HEADERS = src/readstat.h @@ -113,6 +117,7 @@ noinst_HEADERS = \ src/sas/readstat_sas.h \ src/sas/readstat_sas_rle.h \ src/sas/readstat_sas_rdc.h \ + src/sas/readstat_cport.h \ src/sas/readstat_xport.h \ src/sas/readstat_xport_parse_format.h \ src/spss/readstat_por.h \ diff --git a/README.md b/README.md index cf545ba1..326949b6 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Originally developed for [Wizard](https://www.wizardmac.com/), ReadStat is a command-line tool and MIT-licensed C library for reading files from popular stats packages. Supported data formats include: -* SAS: SAS7BDAT (binary file) and XPORT (transport file) +* SAS: SAS7BDAT (binary file), XPORT (transport file) and CPORT (transport file, read only) * Stata: DTA (binary file) versions 104-119 * SPSS: POR (portable file), SAV (binary file), and ZSAV (compressed binary) @@ -131,7 +131,7 @@ Standard usage: Where: -* `` ends with `.dta`, `.por`, `.sav`, `.sas7bdat`, or `.xpt`and +* `` ends with `.dta`, `.por`, `.sav`, `.sas7bdat`, `.xpt`, `.cpt` or `.cport`, and * `` ends with `.dta`, `.por`, `.sav`, `.sas7bdat`, `.xpt` or `.csv` If [libxlsxwriter](http://libxlsxwriter.github.io) is found at compile-time, an diff --git a/VS17/ReadStat.vcxproj b/VS17/ReadStat.vcxproj index 74a783fb..c4f767c0 100644 --- a/VS17/ReadStat.vcxproj +++ b/VS17/ReadStat.vcxproj @@ -200,6 +200,7 @@ + @@ -245,6 +246,7 @@ + diff --git a/VS17/ReadStat.vcxproj.filters b/VS17/ReadStat.vcxproj.filters index 3f645fa8..3b5f6d9f 100644 --- a/VS17/ReadStat.vcxproj.filters +++ b/VS17/ReadStat.vcxproj.filters @@ -84,6 +84,9 @@ Source Files\sas + + Source Files\sas + Source Files\sas @@ -212,6 +215,9 @@ Header Files + + Header Files + Header Files diff --git a/man/readstat.man b/man/readstat.man index b0708239..7d52db9b 100644 --- a/man/readstat.man +++ b/man/readstat.man @@ -29,7 +29,11 @@ should be a file with one of the following extensions: SAS binary file, created with SAS version 7 or newer .TP .IR xpt -SAS portable file, version 5 or version 8, created with the SAS XPORT command +SAS portable file, version 5 or version 8, created with the SAS XPORT command, +or SAS transport file created with PROC CPORT (read only) +.TP +.IR cpt ", " cport +SAS transport file created with PROC CPORT (read only) .TP .IR sav SPSS uncompressed binary file diff --git a/resources/cport_basic_viya_nocompress.xpt b/resources/cport_basic_viya_nocompress.xpt new file mode 100644 index 00000000..7b12a2d7 Binary files /dev/null and b/resources/cport_basic_viya_nocompress.xpt differ diff --git a/resources/cport_basic_win94.xpt b/resources/cport_basic_win94.xpt new file mode 100644 index 00000000..f207927f Binary files /dev/null and b/resources/cport_basic_win94.xpt differ diff --git a/resources/cport_encoding_viya.xpt b/resources/cport_encoding_viya.xpt new file mode 100644 index 00000000..c5e9b3ae Binary files /dev/null and b/resources/cport_encoding_viya.xpt differ diff --git a/src/bin/readstat.c b/src/bin/readstat.c index e3fbbd19..9a02caf5 100644 --- a/src/bin/readstat.c +++ b/src/bin/readstat.c @@ -159,15 +159,18 @@ static void print_version(void) { } #if HAVE_ZLIB -#define INPUT_FORMATS "dta|por|sav|sas7bdat|xpt|zsav" +#define READ_WRITE_FORMATS "dta|por|sav|sas7bdat|xpt|zsav" #else -#define INPUT_FORMATS "dta|por|sav|sas7bdat|xpt" +#define READ_WRITE_FORMATS "dta|por|sav|sas7bdat|xpt" #endif +/* SAS CPORT files can be read, but not written */ +#define INPUT_FORMATS READ_WRITE_FORMATS "|cpt|cport" + #if HAVE_XLSXWRITER -#define OUTPUT_FORMATS INPUT_FORMATS "|csv|xlsx" +#define OUTPUT_FORMATS READ_WRITE_FORMATS "|csv|xlsx" #else -#define OUTPUT_FORMATS INPUT_FORMATS "|csv" +#define OUTPUT_FORMATS READ_WRITE_FORMATS "|csv" #endif static void print_usage(const char *cmd) { diff --git a/src/bin/util/file_format.c b/src/bin/util/file_format.c index eaaaea8f..4d1455b8 100644 --- a/src/bin/util/file_format.c +++ b/src/bin/util/file_format.c @@ -43,6 +43,10 @@ rs_format_e readstat_format(const char *filename) { if (strncasecmp(filename + len - 4, ".xpt", 4) == 0) return RS_FORMAT_XPORT; + /* SAS CPORT files are read through the XPORT reader */ + if (strncasecmp(filename + len - 4, ".cpt", 4) == 0) + return RS_FORMAT_XPORT; + if (len < sizeof(".json")-1) return RS_FORMAT_UNKNOWN; @@ -52,6 +56,12 @@ rs_format_e readstat_format(const char *filename) { if (strncasecmp(filename + len - 5, ".zsav", 5) == 0) return RS_FORMAT_ZSAV; + if (len < sizeof(".cport")-1) + return RS_FORMAT_UNKNOWN; + + if (strncasecmp(filename + len - 6, ".cport", 6) == 0) + return RS_FORMAT_XPORT; + if (len < sizeof(".sas7bdat")-1) return RS_FORMAT_UNKNOWN; diff --git a/src/sas/readstat_cport.h b/src/sas/readstat_cport.h new file mode 100644 index 00000000..de70f87b --- /dev/null +++ b/src/sas/readstat_cport.h @@ -0,0 +1,8 @@ + +/* SAS CPORT transport files (PROC CPORT), often named .xpt like XPORT + * files. They are read through readstat_parse_xport(). */ + +#define CPORT_RECORD_LEN 80 + +int cport_has_signature(const char *record, size_t record_len); +readstat_error_t cport_parse(readstat_parser_t *parser, size_t file_size, void *user_ctx); diff --git a/src/sas/readstat_cport_read.c b/src/sas/readstat_cport_read.c new file mode 100644 index 00000000..ec821f28 --- /dev/null +++ b/src/sas/readstat_cport_read.c @@ -0,0 +1,771 @@ +/* Reader for SAS CPORT transport files (PROC CPORT). + * + * The format is undocumented. A file is a stream of 80-byte records, + * optionally compressed (see cport_read_record): + * + * LIB CONTROL ... library record + * per member (datasets D01, catalogs C01): + * D01VC RC RL + * header record 2 (label length at offset 17, encoding at offset 64) + * 2 blank records, ceil(label length / 80) label records + * SPAN CONTROL ... records, each followed by + * payload records: -1 per variable, 0 per observation, + * others (indexes, sort information) are skipped + * End of Data + * + * Observations use the XPORT layout: IBM floating point numbers and blank + * padded strings, at the offsets given by the variable descriptors. Only + * the first dataset member is read; catalogs are skipped. + */ + +#include +#include +#include +#include +#include +#include + +#include "../readstat.h" +#include "../readstat_iconv.h" +#include "../readstat_convert.h" +#include "../readstat_malloc.h" +#include "readstat_sas.h" +#include "readstat_xport.h" +#include "readstat_cport.h" +#include "ieee.h" + +#define CPORT_COMPRESSED_SIGNATURE "**COMPRESSED** **COMPRESSED** " +#define CPORT_LIBRARY_SIGNATURE "LIB CONTROL " +#define CPORT_SPAN_SIGNATURE "SPAN CONTROL " +#define CPORT_END_OF_DATA "End of Data" + +#define CPORT_ESCAPE 0xBC +#define CPORT_BUFFER_SIZE 4096 + +#define CPORT_SPAN_VARIABLE -1 +#define CPORT_SPAN_OBSERVATION 0 + +/* Fixed part of a variable descriptor (SPAN -1) before the name */ +#define CPORT_VARIABLE_HEADER_LEN 72 + +typedef struct cport_span_s { + int type; + size_t length; + size_t records; +} cport_span_t; + +typedef struct cport_charset_entry_s { + const char *sas_name; + const char *iconv_name; +} cport_charset_entry_t; + +/* SAS short encoding names as found in header record 2. Only names seen + * in real files are listed; others need an explicit input encoding. */ +static cport_charset_entry_t _cport_charset_table[] = { + { .sas_name = "utf8", .iconv_name = "UTF-8" }, + { .sas_name = "wlt1", .iconv_name = "WINDOWS-1252" } +}; + +typedef struct cport_ctx_s { + readstat_callbacks_t handle; + size_t file_size; + void *user_ctx; + const char *input_encoding; + const char *output_encoding; + iconv_t converter; + + readstat_io_t *io; + + int compressed; + unsigned char buffer[CPORT_BUFFER_SIZE]; + size_t buffer_len; + size_t buffer_pos; + size_t run_len; + char run_byte; + + char *span_data; + size_t span_data_len; + + long obs_count; + int var_count; + int var_parsed_count; + size_t row_length; + long row_limit; + long row_offset; + long parsed_row_count; + char file_label[256*4+1]; + char table_name[32*4+1]; + char encoding[9]; + char error_buf[2048]; + + readstat_variable_t **variables; +} cport_ctx_t; + +int cport_has_signature(const char *record, size_t record_len) { + return ((record_len >= sizeof(CPORT_COMPRESSED_SIGNATURE)-1 && + memcmp(record, CPORT_COMPRESSED_SIGNATURE, sizeof(CPORT_COMPRESSED_SIGNATURE)-1) == 0) || + (record_len >= sizeof(CPORT_LIBRARY_SIGNATURE)-1 && + memcmp(record, CPORT_LIBRARY_SIGNATURE, sizeof(CPORT_LIBRARY_SIGNATURE)-1) == 0)); +} + +static uint16_t cport_read2(const char *data) { + const unsigned char *bytes = (const unsigned char *)data; + return (bytes[0] << 8) | bytes[1]; +} + +static uint32_t cport_read4(const char *data) { + const unsigned char *bytes = (const unsigned char *)data; + return ((uint32_t)bytes[0] << 24) | ((uint32_t)bytes[1] << 16) | (bytes[2] << 8) | bytes[3]; +} + +static cport_ctx_t *cport_ctx_init(void) { + cport_ctx_t *ctx = calloc(1, sizeof(cport_ctx_t)); + return ctx; +} + +static void cport_ctx_free(cport_ctx_t *ctx) { + if (ctx->variables) { + int i; + for (i=0; ivar_count; i++) { + if (ctx->variables[i]) + free(ctx->variables[i]); + } + free(ctx->variables); + } + if (ctx->converter) { + iconv_close(ctx->converter); + } + free(ctx->span_data); + + free(ctx); +} + +static readstat_error_t cport_update_progress(cport_ctx_t *ctx) { + readstat_io_t *io = ctx->io; + return io->update(ctx->file_size, ctx->handle.progress, ctx->user_ctx, io->io_ctx); +} + +static readstat_error_t cport_read_byte(cport_ctx_t *ctx, unsigned char *byte) { + if (ctx->buffer_pos == ctx->buffer_len) { + readstat_io_t *io = ctx->io; + ssize_t bytes_read = io->read(ctx->buffer, sizeof(ctx->buffer), io->io_ctx); + if (bytes_read <= 0) + return READSTAT_ERROR_READ; + + ctx->buffer_len = bytes_read; + ctx->buffer_pos = 0; + } + *byte = ctx->buffer[ctx->buffer_pos++]; + return READSTAT_OK; +} + +/* Compressed files start with an 80-byte banner, then the records are + * compressed as a byte stream: + * BC 00 a literal 0xBC byte + * BC n n+2 NUL bytes (n = 01-7F) + * BC 80+n n+2 blanks + * Runs may continue into the next record. */ +static readstat_error_t cport_read_record(cport_ctx_t *ctx, char *record) { + readstat_error_t retval = READSTAT_OK; + size_t len = 0; + unsigned char byte = 0; + + while (len < CPORT_RECORD_LEN) { + if (ctx->run_len) { + size_t run_len = ctx->run_len; + if (run_len > CPORT_RECORD_LEN - len) + run_len = CPORT_RECORD_LEN - len; + + memset(&record[len], ctx->run_byte, run_len); + len += run_len; + ctx->run_len -= run_len; + continue; + } + + if ((retval = cport_read_byte(ctx, &byte)) != READSTAT_OK) + goto cleanup; + + if (!ctx->compressed || byte != CPORT_ESCAPE) { + record[len++] = byte; + continue; + } + + if ((retval = cport_read_byte(ctx, &byte)) != READSTAT_OK) + goto cleanup; + + if (byte == 0x00) { + record[len++] = (char)CPORT_ESCAPE; + } else { + ctx->run_byte = (byte & 0x80) ? ' ' : '\0'; + ctx->run_len = (byte & 0x7F) + 2; + } + } + +cleanup: + return retval; +} + +static int cport_record_starts_with(const char *record, const char *prefix) { + return strncmp(record, prefix, strlen(prefix)) == 0; +} + +static int cport_is_member_record(const char *record, char member_type) { + return (record[0] == member_type && record[1] >= '0' && record[1] <= '9' && + record[2] == '0' && record[3] == '1'); +} + +static readstat_error_t cport_parse_span_record(const char *record, cport_span_t *span) { + char line[CPORT_RECORD_LEN+1]; + long length = 0, records = 0, last_record_length = 0; + int type = 0; + + memcpy(line, record, CPORT_RECORD_LEN); + line[CPORT_RECORD_LEN] = '\0'; + + if (sscanf(&line[sizeof(CPORT_SPAN_SIGNATURE)-1], "%d %ld %ld %ld", + &type, &length, &records, &last_record_length) != 4) + return READSTAT_ERROR_PARSE; + + if (length < 0 || length > INT32_MAX || + records != (length + CPORT_RECORD_LEN - 1) / CPORT_RECORD_LEN) + return READSTAT_ERROR_PARSE; + + span->type = type; + span->length = length; + span->records = records; + + return READSTAT_OK; +} + +static readstat_error_t cport_read_span_data(cport_ctx_t *ctx, cport_span_t *span) { + readstat_error_t retval = READSTAT_OK; + size_t data_len = span->records * CPORT_RECORD_LEN; + size_t i; + + if (data_len > ctx->span_data_len) { + if ((ctx->span_data = readstat_realloc(ctx->span_data, data_len)) == NULL) { + ctx->span_data_len = 0; + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + ctx->span_data_len = data_len; + } + + for (i=0; irecords; i++) { + if ((retval = cport_read_record(ctx, &ctx->span_data[i * CPORT_RECORD_LEN])) != READSTAT_OK) + goto cleanup; + } + +cleanup: + return retval; +} + +static readstat_error_t cport_skip_span_data(cport_ctx_t *ctx, cport_span_t *span) { + readstat_error_t retval = READSTAT_OK; + char record[CPORT_RECORD_LEN]; + size_t i; + + for (i=0; irecords; i++) { + if ((retval = cport_read_record(ctx, record)) != READSTAT_OK) + break; + } + + return retval; +} + +static readstat_error_t cport_construct_format(char *dst, size_t dst_len, + const char *src, size_t src_len, int width, int decimals) { + readstat_error_t retval = READSTAT_OK; + char name[32*4+1]; + + if ((retval = readstat_convert(name, sizeof(name), src, src_len, NULL)) != READSTAT_OK) + return retval; + + if (width && decimals) { + snprintf(dst, dst_len, "%s%d.%d", name, width, decimals); + } else if (width) { + snprintf(dst, dst_len, "%s%d.", name, width); + } else if (decimals) { + snprintf(dst, dst_len, "%s.%d", name, decimals); + } else { + snprintf(dst, dst_len, "%s", name); + } + + return retval; +} + +/* Variable descriptor (SPAN -1), big-endian: + * 20 u16 format width 22 u16 format decimals + * 24 u16 informat width 26 u16 informat decimals + * 40 u32 offset in row 44 u32 length + * 52 u16 name length 54 u16 label length + * 56 u8 type (1 numeric, 2 character) + * 72 name, then label + * then, at s = 72 + name length + label length: + * s u32 variable number (1-based) + * s+32 u16 format name length, format name + * then u16 informat name length, informat name + * Unused bytes may hold stale data and are ignored. */ +static readstat_error_t cport_read_variable(cport_ctx_t *ctx, const char *data, size_t data_len) { + readstat_error_t retval = READSTAT_OK; + readstat_variable_t *variable = NULL; + + if (data_len < CPORT_VARIABLE_HEADER_LEN) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + size_t name_len = cport_read2(&data[52]); + size_t label_len = cport_read2(&data[54]); + size_t end = CPORT_VARIABLE_HEADER_LEN + name_len + label_len; + if (end + 36 > data_len) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + size_t format_len = cport_read2(&data[end+32]); + if (end + 36 + format_len > data_len) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + size_t informat_len = cport_read2(&data[end+34+format_len]); + if (end + 36 + format_len + informat_len > data_len) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + uint32_t var_number = cport_read4(&data[end]); + if (var_number < 1 || var_number > (uint32_t)ctx->var_count || ctx->variables[var_number-1]) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + uint32_t offset = cport_read4(&data[40]); + uint32_t storage_width = cport_read4(&data[44]); + if (storage_width == 0 || offset > ctx->row_length || storage_width > ctx->row_length - offset) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + if (data[56] != SAS_COLUMN_TYPE_NUM && data[56] != SAS_COLUMN_TYPE_CHR) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + if ((variable = calloc(1, sizeof(readstat_variable_t))) == NULL) { + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + + variable->index = var_number - 1; + variable->type = data[56] == SAS_COLUMN_TYPE_CHR ? READSTAT_TYPE_STRING : READSTAT_TYPE_DOUBLE; + variable->offset = offset; + variable->storage_width = storage_width; + variable->display_width = cport_read2(&data[20]); + variable->decimals = cport_read2(&data[22]); + + retval = readstat_convert(variable->name, sizeof(variable->name), + &data[CPORT_VARIABLE_HEADER_LEN], name_len, ctx->converter); + if (retval != READSTAT_OK) + goto cleanup; + + retval = readstat_convert(variable->label, sizeof(variable->label), + &data[CPORT_VARIABLE_HEADER_LEN+name_len], label_len, ctx->converter); + if (retval != READSTAT_OK) + goto cleanup; + + retval = cport_construct_format(variable->format, sizeof(variable->format), + &data[end+34], format_len, cport_read2(&data[20]), cport_read2(&data[22])); + if (retval != READSTAT_OK) + goto cleanup; + + retval = cport_construct_format(variable->informat, sizeof(variable->informat), + &data[end+36+format_len], informat_len, cport_read2(&data[24]), cport_read2(&data[26])); + if (retval != READSTAT_OK) + goto cleanup; + + ctx->variables[var_number-1] = variable; + variable = NULL; + ctx->var_parsed_count++; + +cleanup: + free(variable); + return retval; +} + +static readstat_error_t cport_handle_variables(cport_ctx_t *ctx) { + readstat_error_t retval = READSTAT_OK; + int index_after_skipping = 0; + int i; + + if (ctx->var_parsed_count != ctx->var_count) { + retval = READSTAT_ERROR_COLUMN_COUNT_MISMATCH; + goto cleanup; + } + + for (i=0; ivar_count; i++) { + readstat_variable_t *variable = ctx->variables[i]; + variable->index_after_skipping = index_after_skipping; + + int cb_retval = READSTAT_HANDLER_OK; + if (ctx->handle.variable) { + cb_retval = ctx->handle.variable(i, variable, variable->format, ctx->user_ctx); + } + if (cb_retval == READSTAT_HANDLER_ABORT) { + retval = READSTAT_ERROR_USER_ABORT; + goto cleanup; + } + if (cb_retval == READSTAT_HANDLER_SKIP_VARIABLE) { + variable->skip = 1; + } else { + index_after_skipping++; + } + } + +cleanup: + return retval; +} + +static readstat_error_t cport_process_row(cport_ctx_t *ctx, const char *row) { + readstat_error_t retval = READSTAT_OK; + char *string = NULL; + int i; + + if (ctx->row_offset) { + ctx->row_offset--; + goto cleanup; + } + + for (i=0; ivar_count; i++) { + readstat_variable_t *variable = ctx->variables[i]; + readstat_value_t value = { .type = variable->type }; + const char *field = &row[variable->offset]; + + if (variable->skip) + continue; + + if (variable->type == READSTAT_TYPE_STRING) { + string = readstat_realloc(string, 4*variable->storage_width+1); + if (string == NULL) { + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + retval = readstat_convert(string, 4*variable->storage_width+1, + field, variable->storage_width, ctx->converter); + if (retval != READSTAT_OK) + goto cleanup; + + value.v.string_value = string; + } else { + double dval = NAN; + if (variable->storage_width <= XPORT_MAX_DOUBLE_SIZE && + variable->storage_width >= XPORT_MIN_DOUBLE_SIZE) { + char full_value[8] = { 0 }; + if (memcmp(&full_value[1], &field[1], variable->storage_width - 1) == 0 && + (field[0] == '.' || sas_validate_tag(field[0]) == READSTAT_OK)) { + if (field[0] == '.') { + value.is_system_missing = 1; + } else { + value.tag = field[0]; + value.is_tagged_missing = 1; + } + } else { + memcpy(full_value, field, variable->storage_width); + int rc = cnxptiee(full_value, CN_TYPE_XPORT, &dval, CN_TYPE_NATIVE); + if (rc != 0) { + retval = READSTAT_ERROR_CONVERT; + goto cleanup; + } + } + } + + value.v.double_value = dval; + } + + if (ctx->handle.value(ctx->parsed_row_count, variable, value, ctx->user_ctx) != READSTAT_HANDLER_OK) { + retval = READSTAT_ERROR_USER_ABORT; + goto cleanup; + } + } + ctx->parsed_row_count++; + +cleanup: + free(string); + return retval; +} + +static readstat_error_t cport_open_converter(cport_ctx_t *ctx) { + readstat_error_t retval = READSTAT_OK; + const char *input_encoding = ctx->input_encoding; + size_t i; + + if (input_encoding == NULL) { + if (ctx->encoding[0] == '\0') { + input_encoding = SAS_DEFAULT_STRING_ENCODING; + } else { + for (i=0; iencoding, _cport_charset_table[i].sas_name) == 0) { + input_encoding = _cport_charset_table[i].iconv_name; + break; + } + } + } + if (input_encoding == NULL) { + retval = READSTAT_ERROR_UNSUPPORTED_CHARSET; + if (ctx->handle.error) { + snprintf(ctx->error_buf, sizeof(ctx->error_buf), + "Unsupported character set: %s", ctx->encoding); + ctx->handle.error(ctx->error_buf, ctx->user_ctx); + } + goto cleanup; + } + ctx->input_encoding = input_encoding; + } + + if (ctx->output_encoding && strcmp(input_encoding, ctx->output_encoding) != 0) { + iconv_t converter = iconv_open(ctx->output_encoding, input_encoding); + if (converter == (iconv_t)-1) { + retval = READSTAT_ERROR_UNSUPPORTED_CHARSET; + goto cleanup; + } + ctx->converter = converter; + } + +cleanup: + return retval; +} + +/* Header records of a dataset member, up to the first SPAN record */ +static readstat_error_t cport_read_member_header(cport_ctx_t *ctx, const char *member_record) { + readstat_error_t retval = READSTAT_OK; + char line[CPORT_RECORD_LEN+1]; + char *label = NULL; + long var_count = 0, obs_count = 0, row_length = 0; + size_t label_len = 0; + size_t i; + + memcpy(line, member_record, CPORT_RECORD_LEN); + line[CPORT_RECORD_LEN] = '\0'; + if (sscanf(&line[44], "VC%ld RC%ld RL%ld", &var_count, &obs_count, &row_length) != 3 || + var_count < 0 || var_count > INT32_MAX || obs_count < 0 || row_length < 0) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + ctx->var_count = var_count; + ctx->obs_count = obs_count; + ctx->row_length = row_length; + + if ((retval = cport_read_record(ctx, line)) != READSTAT_OK) + goto cleanup; + + for (i=17; i<20 && line[i] >= '0' && line[i] <= '9'; i++) { + label_len = 10 * label_len + (line[i] - '0'); + } + retval = readstat_convert(ctx->encoding, sizeof(ctx->encoding), &line[64], 8, NULL); + if (retval != READSTAT_OK) + goto cleanup; + + if ((retval = cport_open_converter(ctx)) != READSTAT_OK) + goto cleanup; + + retval = readstat_convert(ctx->table_name, sizeof(ctx->table_name), + &member_record[12], 32, ctx->converter); + if (retval != READSTAT_OK) + goto cleanup; + + /* two blank records */ + for (i=0; i<2; i++) { + if ((retval = cport_read_record(ctx, line)) != READSTAT_OK) + goto cleanup; + } + + if (label_len) { + size_t records = (label_len + CPORT_RECORD_LEN - 1) / CPORT_RECORD_LEN; + if ((label = readstat_malloc(records * CPORT_RECORD_LEN)) == NULL) { + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + for (i=0; ifile_label, sizeof(ctx->file_label), + label, label_len, ctx->converter); + if (retval != READSTAT_OK) + goto cleanup; + } + + if (ctx->var_count) { + if ((ctx->variables = readstat_calloc(ctx->var_count, sizeof(readstat_variable_t *))) == NULL) { + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + } + + if (ctx->obs_count > ctx->row_offset) { + ctx->obs_count -= ctx->row_offset; + } else { + ctx->row_offset = ctx->obs_count; + ctx->obs_count = 0; + } + if (ctx->row_limit > 0 && ctx->row_limit < ctx->obs_count) + ctx->obs_count = ctx->row_limit; + + if (ctx->handle.metadata) { + readstat_metadata_t metadata = { + .row_count = ctx->obs_count, + .var_count = ctx->var_count, + .file_label = ctx->file_label, + .table_name = ctx->table_name, + .file_encoding = ctx->input_encoding, + .compression = ctx->compressed ? READSTAT_COMPRESS_ROWS : READSTAT_COMPRESS_NONE + }; + if (ctx->handle.metadata(&metadata, ctx->user_ctx) != READSTAT_HANDLER_OK) { + retval = READSTAT_ERROR_USER_ABORT; + goto cleanup; + } + } + +cleanup: + free(label); + return retval; +} + +static readstat_error_t cport_read_member(cport_ctx_t *ctx, const char *member_record) { + readstat_error_t retval = READSTAT_OK; + char record[CPORT_RECORD_LEN]; + int variables_handled = 0; + + if ((retval = cport_read_member_header(ctx, member_record)) != READSTAT_OK) + goto cleanup; + + while (1) { + cport_span_t span = { 0 }; + + if ((retval = cport_read_record(ctx, record)) != READSTAT_OK) + goto cleanup; + + if (cport_record_starts_with(record, CPORT_END_OF_DATA)) + break; + + if (!cport_record_starts_with(record, CPORT_SPAN_SIGNATURE)) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + if ((retval = cport_parse_span_record(record, &span)) != READSTAT_OK) + goto cleanup; + + if (span.type == CPORT_SPAN_VARIABLE && !variables_handled) { + if ((retval = cport_read_span_data(ctx, &span)) != READSTAT_OK) + goto cleanup; + + if ((retval = cport_read_variable(ctx, ctx->span_data, span.length)) != READSTAT_OK) + goto cleanup; + } else if (span.type == CPORT_SPAN_OBSERVATION) { + if (!variables_handled) { + if ((retval = cport_handle_variables(ctx)) != READSTAT_OK) + goto cleanup; + variables_handled = 1; + if (!ctx->handle.value) + goto cleanup; + } + if (span.length != ctx->row_length) { + retval = READSTAT_ERROR_ROW_WIDTH_MISMATCH; + goto cleanup; + } + if ((retval = cport_read_span_data(ctx, &span)) != READSTAT_OK) + goto cleanup; + + if ((retval = cport_process_row(ctx, ctx->span_data)) != READSTAT_OK) + goto cleanup; + + if (ctx->row_limit > 0 && ctx->parsed_row_count == ctx->row_limit) + goto cleanup; + + if ((retval = cport_update_progress(ctx)) != READSTAT_OK) + goto cleanup; + } else { + if ((retval = cport_skip_span_data(ctx, &span)) != READSTAT_OK) + goto cleanup; + } + } + + if (!variables_handled) { + if ((retval = cport_handle_variables(ctx)) != READSTAT_OK) + goto cleanup; + } + + if (ctx->parsed_row_count != ctx->obs_count) { + retval = READSTAT_ERROR_ROW_COUNT_MISMATCH; + goto cleanup; + } + +cleanup: + return retval; +} + +readstat_error_t cport_parse(readstat_parser_t *parser, size_t file_size, void *user_ctx) { + readstat_error_t retval = READSTAT_OK; + char record[CPORT_RECORD_LEN]; + cport_ctx_t *ctx = NULL; + + if ((ctx = cport_ctx_init()) == NULL) { + retval = READSTAT_ERROR_MALLOC; + goto cleanup; + } + + ctx->handle = parser->handlers; + ctx->input_encoding = parser->input_encoding; + ctx->output_encoding = parser->output_encoding; + ctx->user_ctx = user_ctx; + ctx->io = parser->io; + ctx->file_size = file_size; + ctx->row_limit = parser->row_limit; + if (parser->row_offset > 0) + ctx->row_offset = parser->row_offset; + + if ((retval = cport_read_record(ctx, record)) != READSTAT_OK) + goto cleanup; + + if (memcmp(record, CPORT_COMPRESSED_SIGNATURE, sizeof(CPORT_COMPRESSED_SIGNATURE)-1) == 0) { + ctx->compressed = 1; + if ((retval = cport_read_record(ctx, record)) != READSTAT_OK) + goto cleanup; + } + + if (!cport_record_starts_with(record, CPORT_LIBRARY_SIGNATURE)) { + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + /* Skip catalog members up to the first dataset member */ + while (1) { + if ((retval = cport_read_record(ctx, record)) != READSTAT_OK) { + /* a file without a dataset member ends here */ + if (retval == READSTAT_ERROR_READ) + retval = READSTAT_ERROR_PARSE; + goto cleanup; + } + + if (cport_is_member_record(record, 'D')) { + retval = cport_read_member(ctx, record); + goto cleanup; + } + + if (cport_record_starts_with(record, CPORT_SPAN_SIGNATURE)) { + cport_span_t span = { 0 }; + if ((retval = cport_parse_span_record(record, &span)) != READSTAT_OK) + goto cleanup; + if ((retval = cport_skip_span_data(ctx, &span)) != READSTAT_OK) + goto cleanup; + } + } + +cleanup: + if (ctx) + cport_ctx_free(ctx); + + return retval; +} diff --git a/src/sas/readstat_xport_read.c b/src/sas/readstat_xport_read.c index d3959619..c8bca879 100644 --- a/src/sas/readstat_xport_read.c +++ b/src/sas/readstat_xport_read.c @@ -11,6 +11,7 @@ #include "../readstat_malloc.h" #include "readstat_sas.h" #include "readstat_xport.h" +#include "readstat_cport.h" #include "ieee.h" #define LINE_LEN 80 @@ -195,6 +196,24 @@ static readstat_error_t xport_read_file_label_record(xport_ctx_t *ctx) { return retval; } +/* SAS CPORT files are often named .xpt; tell them apart by the first record */ +static readstat_error_t xport_is_cport(xport_ctx_t *ctx, int *is_cport) { + char line[LINE_LEN]; + readstat_io_t *io = ctx->io; + readstat_error_t retval = READSTAT_OK; + + ssize_t bytes_read = read_bytes(ctx, line, LINE_LEN); + *is_cport = (bytes_read == LINE_LEN && cport_has_signature(line, LINE_LEN)); + + if (io->seek(0, READSTAT_SEEK_SET, io->io_ctx) == -1) { + retval = READSTAT_ERROR_SEEK; + goto cleanup; + } + +cleanup: + return retval; +} + static readstat_error_t xport_read_library_record(xport_ctx_t *ctx) { xport_header_record_t xrecord; readstat_error_t retval = xport_read_header_record(ctx, &xrecord); @@ -785,6 +804,16 @@ readstat_error_t readstat_parse_xport(readstat_parser_t *parser, const char *pat goto cleanup; } + int is_cport = 0; + retval = xport_is_cport(ctx, &is_cport); + if (retval != READSTAT_OK) + goto cleanup; + + if (is_cport) { + retval = cport_parse(parser, ctx->file_size, user_ctx); + goto cleanup; + } + if (ctx->input_encoding && ctx->output_encoding && strcmp(ctx->input_encoding, ctx->output_encoding) != 0) { iconv_t converter = iconv_open(ctx->output_encoding, ctx->input_encoding); if (converter == (iconv_t)-1) { diff --git a/src/test/test_readstat.c b/src/test/test_readstat.c index 1b25cd50..467d9f84 100644 --- a/src/test/test_readstat.c +++ b/src/test/test_readstat.c @@ -325,6 +325,9 @@ int main(int argc, char *argv[]) { if (test_sas7bcat_large_label_sets() != 0) return 1; + if (test_xport_cport() != 0) + return 1; + if (test_txt_schema_bounds() != 0) return 1; diff --git a/src/test/test_sas.c b/src/test/test_sas.c index b2e3ab8e..3360cd06 100644 --- a/src/test/test_sas.c +++ b/src/test/test_sas.c @@ -1,8 +1,10 @@ #include #include #include +#include #include "../readstat.h" +#include "../sas/ieee.h" #include "test_buffer.h" #include "test_buffer_io.h" @@ -195,3 +197,632 @@ int test_sas7bcat_large_label_sets(void) { buffer_free(buffer); return failed; } + +/* SAS CPORT files, read through readstat_parse_xport(). Real files from SAS + * live in resources/; more cases are built in memory following the layout + * described in src/sas/readstat_cport_read.c */ + +#define RT_CPORT_MAX_COLUMNS 9 +#define RT_CPORT_MAX_ROWS 10 +#define RT_CPORT_RECORD_LEN 80 +#define RT_CPORT_MAX_ERRORS 10 + +typedef struct rt_cport_value_s { + char missing; /* 0 for a value, '.' when system missing, else the tag */ + double d; + const char *s; /* expected string (UTF-8) */ + const char *raw; /* bytes in a built file, if they differ from s */ +} rt_cport_value_t; + +typedef struct rt_cport_column_s { + const char *name; + const char *label; + readstat_type_t type; + size_t width; + const char *format; + const char *informat; + rt_cport_value_t values[RT_CPORT_MAX_ROWS]; +} rt_cport_column_t; + +typedef struct rt_cport_file_s { + const char *table_name; + const char *label; + const char *encoding; /* reported encoding */ + const char *sas_encoding; /* encoding name written into built files */ + readstat_compress_t compression; + long rows; + int columns_count; + const rt_cport_column_t *columns; +} rt_cport_file_t; + +typedef struct rt_cport_build_s { + int compress; /* 0 none, 1 runs end with each record (as SAS does), 2 runs cross records */ + int catalog_first; + int catalog_only; + int extra_spans; /* index and sort information */ + int bad_name_length; +} rt_cport_build_t; + +typedef struct rt_cport_ctx_s { + const rt_cport_file_t *file; /* NULL: don't check anything */ + const char *test_name; + long row_offset; + long rows; + long values_count; + int errors_count; +} rt_cport_ctx_t; + +#define RT_CPORT_D(x) { .d = (x) } +#define RT_CPORT_MISSING { .missing = '.' } +#define RT_CPORT_TAG(t) { .missing = (t) } +#define RT_CPORT_S(x) { .s = (x) } + +/* The "basic" dataset written by SAS 9.4 (Windows) and SAS Viya 4 */ +static const rt_cport_column_t _cport_basic_columns[] = { + { .name = "id", .label = "Row id", .type = READSTAT_TYPE_DOUBLE, .width = 8, .format = "8.", + .values = { RT_CPORT_D(1.0), RT_CPORT_D(2.0), RT_CPORT_D(3.0), RT_CPORT_D(4.0), RT_CPORT_D(5.0), + RT_CPORT_D(6.0), RT_CPORT_D(7.0), RT_CPORT_D(8.0), RT_CPORT_D(9.0), RT_CPORT_D(10.0) } }, + { .name = "name", .label = "First name", .type = READSTAT_TYPE_STRING, .width = 12, .informat = "$CHAR12.", + .values = { RT_CPORT_S("Alice"), RT_CPORT_S("Bob"), RT_CPORT_S(""), RT_CPORT_S("Dora"), RT_CPORT_S("Eve"), + RT_CPORT_S("Frank"), RT_CPORT_S("Grace"), RT_CPORT_S("Heidi"), RT_CPORT_S("Ivan"), RT_CPORT_S("Judy") } }, + { .name = "amount", .label = "Amount", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .format = "DOLLAR12.2", .informat = "COMMA12.2", + .values = { RT_CPORT_D(1234.5), RT_CPORT_D(-0.01), RT_CPORT_MISSING, RT_CPORT_D(0.0), RT_CPORT_D(99999999.99), + RT_CPORT_D(1.0), RT_CPORT_D(2.5), RT_CPORT_D(1000000.0), RT_CPORT_D(-42.0), RT_CPORT_D(0.125) } }, + { .name = "visitdt", .label = "Visit date", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .format = "DATE9.", .informat = "ANYDTDTE10.", + .values = { RT_CPORT_D(23435.0), RT_CPORT_D(0.0), RT_CPORT_D(-1.0), RT_CPORT_MISSING, RT_CPORT_D(-137774.0), + RT_CPORT_D(2936549.0), RT_CPORT_D(14610.0), RT_CPORT_D(14609.0), RT_CPORT_D(28508.0), RT_CPORT_D(3653.0) } }, + { .name = "visitts", .label = "Visit timestamp", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .format = "DATETIME22.1", + .values = { RT_CPORT_D(2024833530.0), RT_CPORT_D(0.0), RT_CPORT_D(-1.0), RT_CPORT_MISSING, + RT_CPORT_D(315619200.0), RT_CPORT_D(2463102848.0), RT_CPORT_D(1262390399.0), + RT_CPORT_D(-1893326400.0), RT_CPORT_D(2051222401.0), RT_CPORT_D(2065595400.5) } }, + { .name = "visittm", .label = "Visit time", .type = READSTAT_TYPE_DOUBLE, .width = 8, .format = "TIME8.", + .values = { RT_CPORT_D(0.0), RT_CPORT_D(86399.0), RT_CPORT_D(43200.0), RT_CPORT_MISSING, RT_CPORT_D(3723.0), + RT_CPORT_D(23400.0), RT_CPORT_D(65745.0), RT_CPORT_D(1.0), RT_CPORT_D(32949.0), RT_CPORT_D(80542.0) } }, + { .name = "flag", .label = "Yes/No flag", .type = READSTAT_TYPE_STRING, .width = 1, .format = "$YN", + .values = { RT_CPORT_S("Y"), RT_CPORT_S("N"), RT_CPORT_S("Y"), RT_CPORT_S(""), RT_CPORT_S("N"), + RT_CPORT_S("Y"), RT_CPORT_S("N"), RT_CPORT_S("Y"), RT_CPORT_S("N"), RT_CPORT_S("Y") } }, + { .name = "age", .label = "Age in years", .type = READSTAT_TYPE_DOUBLE, .width = 8, .format = "AGEGRP", + .values = { RT_CPORT_D(5.0), RT_CPORT_D(17.0), RT_CPORT_D(18.0), RT_CPORT_D(64.0), RT_CPORT_D(65.0), + RT_CPORT_D(99.0), RT_CPORT_MISSING, RT_CPORT_D(30.0), RT_CPORT_D(0.0), RT_CPORT_D(120.0) } }, + { .name = "score", .label = "Score with special missings", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .values = { RT_CPORT_D(1.5), RT_CPORT_MISSING, RT_CPORT_TAG('A'), RT_CPORT_TAG('B'), RT_CPORT_TAG('Z'), + RT_CPORT_D(2.0), RT_CPORT_TAG('_'), RT_CPORT_D(3.25), RT_CPORT_TAG('C'), RT_CPORT_D(4.0) } } +}; + +/* Latin-1 text; the UTF-8 bytes C3 BC of u-umlaut need the escape for a literal 0xBC */ +static const rt_cport_column_t _cport_encoding_columns[] = { + { .name = "row", .label = "Row", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .values = { RT_CPORT_D(1.0), RT_CPORT_D(2.0), RT_CPORT_D(3.0), RT_CPORT_D(4.0), RT_CPORT_D(5.0), + RT_CPORT_D(6.0), RT_CPORT_D(7.0), RT_CPORT_D(8.0), RT_CPORT_D(9.0) } }, + { .name = "text", .label = "Accented text", .type = READSTAT_TYPE_STRING, .width = 40, + .values = { RT_CPORT_S("caf\xc3\xa9"), RT_CPORT_S("M\xc3\xbc" "ller"), RT_CPORT_S("Stra\xc3\x9f" "e"), + RT_CPORT_S("na\xc3\xaf" "ve"), RT_CPORT_S("\xc3\x85" "ngstr\xc3\xb6" "m"), + RT_CPORT_S("\xc2\xa9\xc2\xae\xc2\xb1\xc2\xb5"), + RT_CPORT_S("\xc3\xa0\xc3\xa1\xc3\xa2\xc3\xa3\xc3\xa4\xc3\xa5\xc3\xa6\xc3\xa7\xc3\xa8\xc3\xa9\xc3\xaa\xc3\xab"), + RT_CPORT_S("plain ascii"), RT_CPORT_S("") } } +}; + +#define RT_CPORT_A10 "AAAAAAAAAA" + +/* Built in memory: short numerics, a string spanning several records and, + * with WLATIN1, a literal 0xBC byte (one quarter sign) */ +static const rt_cport_column_t _cport_built_columns[] = { + { .name = "x", .label = "Amount", .type = READSTAT_TYPE_DOUBLE, .width = 8, + .format = "DOLLAR12.2", .informat = "COMMA12.2", + .values = { RT_CPORT_D(1.5), RT_CPORT_MISSING, RT_CPORT_D(-2.0), RT_CPORT_D(0.0) } }, + { .name = "short", .label = "", .type = READSTAT_TYPE_DOUBLE, .width = 3, + .values = { RT_CPORT_D(42.0), RT_CPORT_TAG('A'), RT_CPORT_TAG('_'), RT_CPORT_D(0.0) } }, + { .name = "a_variable_name_of_32_characters", .label = "Name", .type = READSTAT_TYPE_STRING, .width = 200, + .format = "$CHAR20.", + .values = { RT_CPORT_S(" Alice"), RT_CPORT_S(""), { .s = "Gr\xc2\xbc", .raw = "Gr\xbc" }, + RT_CPORT_S(RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 + RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 + RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10 RT_CPORT_A10) } } +}; + +static const rt_cport_file_t _cport_basic_win94 = { + .table_name = "BASIC", .label = "Basic SAS types", .encoding = "WINDOWS-1252", + .compression = READSTAT_COMPRESS_ROWS, .rows = 10, .columns_count = 9, .columns = _cport_basic_columns +}; + +static const rt_cport_file_t _cport_basic_viya = { + .table_name = "BASIC", .label = "Basic SAS types", .encoding = "UTF-8", + .compression = READSTAT_COMPRESS_NONE, .rows = 10, .columns_count = 9, .columns = _cport_basic_columns +}; + +static const rt_cport_file_t _cport_encoding_viya = { + .table_name = "ENCODING", .label = "Non-ASCII text (Latin-1 range)", .encoding = "UTF-8", + .compression = READSTAT_COMPRESS_ROWS, .rows = 9, .columns_count = 2, .columns = _cport_encoding_columns +}; + +static const rt_cport_file_t _cport_built = { + .table_name = "BUILT", + .label = "A dataset label longer than one record of eighty bytes, so that it continues on a second record", + .encoding = "WINDOWS-1252", .sas_encoding = "wlt1", + .compression = READSTAT_COMPRESS_NONE, .rows = 4, .columns_count = 3, .columns = _cport_built_columns +}; + +static void rt_cport_error(rt_cport_ctx_t *ctx, const char *fmt, ...) { + if (ctx->errors_count++ < RT_CPORT_MAX_ERRORS) { + va_list args; + va_start(args, fmt); + printf("CPORT test %s: ", ctx->test_name); + vprintf(fmt, args); + printf("\n"); + va_end(args); + } +} + +static void rt_cport_check_string(rt_cport_ctx_t *ctx, const char *what, + const char *expected, const char *received) { + if (strcmp(expected ? expected : "", received ? received : "") != 0) + rt_cport_error(ctx, "%s: expected \"%s\", got \"%s\"", what, expected ? expected : "", received ? received : ""); +} + +static int rt_cport_handle_metadata(readstat_metadata_t *metadata, void *ctx_) { + rt_cport_ctx_t *ctx = (rt_cport_ctx_t *)ctx_; + const rt_cport_file_t *file = ctx->file; + if (file == NULL) + return READSTAT_HANDLER_OK; + + if (readstat_get_row_count(metadata) != ctx->rows) + rt_cport_error(ctx, "row count %d, expected %ld", readstat_get_row_count(metadata), ctx->rows); + if (readstat_get_var_count(metadata) != file->columns_count) + rt_cport_error(ctx, "variable count %d, expected %d", readstat_get_var_count(metadata), file->columns_count); + if (readstat_get_compression(metadata) != file->compression) + rt_cport_error(ctx, "compression %d, expected %d", readstat_get_compression(metadata), file->compression); + rt_cport_check_string(ctx, "table name", file->table_name, readstat_get_table_name(metadata)); + rt_cport_check_string(ctx, "file label", file->label, readstat_get_file_label(metadata)); + rt_cport_check_string(ctx, "file encoding", file->encoding, readstat_get_file_encoding(metadata)); + + return READSTAT_HANDLER_OK; +} + +static int rt_cport_handle_variable(int index, readstat_variable_t *variable, + const char *val_labels, void *ctx_) { + rt_cport_ctx_t *ctx = (rt_cport_ctx_t *)ctx_; + if (ctx->file == NULL) + return READSTAT_HANDLER_OK; + + if (index >= ctx->file->columns_count) { + rt_cport_error(ctx, "unexpected variable %d", index); + return READSTAT_HANDLER_ABORT; + } + const rt_cport_column_t *column = &ctx->file->columns[index]; + + rt_cport_check_string(ctx, "variable name", column->name, readstat_variable_get_name(variable)); + rt_cport_check_string(ctx, "variable label", column->label, readstat_variable_get_label(variable)); + rt_cport_check_string(ctx, "variable format", column->format, readstat_variable_get_format(variable)); + rt_cport_check_string(ctx, "variable informat", column->informat, readstat_variable_get_informat(variable)); + if (readstat_variable_get_type(variable) != column->type) + rt_cport_error(ctx, "variable %s: type %d, expected %d", column->name, + readstat_variable_get_type(variable), column->type); + if (readstat_variable_get_storage_width(variable) != column->width) + rt_cport_error(ctx, "variable %s: width %zu, expected %zu", column->name, + readstat_variable_get_storage_width(variable), column->width); + + return READSTAT_HANDLER_OK; +} + +static int rt_cport_handle_value(int obs_index, readstat_variable_t *variable, + readstat_value_t value, void *ctx_) { + rt_cport_ctx_t *ctx = (rt_cport_ctx_t *)ctx_; + if (ctx->file == NULL) + return READSTAT_HANDLER_OK; + + const rt_cport_column_t *column = &ctx->file->columns[readstat_variable_get_index(variable)]; + ctx->values_count++; + + if (obs_index >= ctx->rows) { + rt_cport_error(ctx, "unexpected row %d", obs_index); + return READSTAT_HANDLER_ABORT; + } + const rt_cport_value_t *expected = &column->values[obs_index + ctx->row_offset]; + + if (column->type == READSTAT_TYPE_STRING) { + rt_cport_check_string(ctx, column->name, expected->s, readstat_string_value(value)); + } else if (expected->missing == '.') { + if (!readstat_value_is_system_missing(value)) + rt_cport_error(ctx, "%s row %d: expected a system missing value", column->name, obs_index); + } else if (expected->missing) { + if (!readstat_value_is_tagged_missing(value) || readstat_value_tag(value) != expected->missing) + rt_cport_error(ctx, "%s row %d: expected .%c", column->name, obs_index, expected->missing); + } else if (readstat_value_is_missing(value, variable) || readstat_double_value(value) != expected->d) { + rt_cport_error(ctx, "%s row %d: expected %.17g, got %.17g", column->name, obs_index, + expected->d, readstat_double_value(value)); + } + + return READSTAT_HANDLER_OK; +} + +static readstat_error_t rt_cport_parse(rt_buffer_t *buffer, rt_cport_ctx_t *ctx, + long row_offset, long row_limit) { + rt_buffer_ctx_t buffer_ctx = { .buffer = buffer }; + readstat_error_t error = READSTAT_OK; + + ctx->row_offset = row_offset; + if (ctx->file) { + ctx->rows = ctx->file->rows > row_offset ? ctx->file->rows - row_offset : 0; + if (row_limit && row_limit < ctx->rows) + ctx->rows = row_limit; + } + + readstat_parser_t *parser = readstat_parser_init(); + readstat_set_open_handler(parser, rt_open_handler); + readstat_set_close_handler(parser, rt_close_handler); + readstat_set_seek_handler(parser, rt_seek_handler); + readstat_set_read_handler(parser, rt_read_handler); + readstat_set_update_handler(parser, rt_update_handler); + readstat_set_io_ctx(parser, &buffer_ctx); + readstat_set_metadata_handler(parser, &rt_cport_handle_metadata); + readstat_set_variable_handler(parser, &rt_cport_handle_variable); + readstat_set_value_handler(parser, &rt_cport_handle_value); + readstat_set_row_offset(parser, row_offset); + readstat_set_row_limit(parser, row_limit); + + error = readstat_parse_xport(parser, NULL, ctx); + + readstat_parser_free(parser); + return error; +} + +static int rt_cport_check(rt_buffer_t *buffer, const rt_cport_file_t *file, const char *test_name, + long row_offset, long row_limit) { + rt_cport_ctx_t ctx = { .file = file, .test_name = test_name }; + + readstat_error_t error = rt_cport_parse(buffer, &ctx, row_offset, row_limit); + if (error != READSTAT_OK) { + rt_cport_error(&ctx, "%s (row offset %ld, row limit %ld)", readstat_error_message(error), + row_offset, row_limit); + } else if (ctx.values_count != ctx.rows * file->columns_count) { + rt_cport_error(&ctx, "%ld values, expected %ld (row offset %ld, row limit %ld)", ctx.values_count, + ctx.rows * file->columns_count, row_offset, row_limit); + } + return ctx.errors_count != 0; +} + +static int rt_cport_expect_error(rt_buffer_t *buffer, const char *test_name, readstat_error_t expected) { + rt_cport_ctx_t ctx = { .test_name = test_name }; + + readstat_error_t error = rt_cport_parse(buffer, &ctx, 0, 0); + if (error != expected) { + rt_cport_error(&ctx, "expected \"%s\", got \"%s\"", readstat_error_message(expected), + readstat_error_message(error)); + } + return ctx.errors_count != 0; +} + +static void rt_cport_append(rt_buffer_t *buffer, const void *bytes, size_t len) { + buffer_grow(buffer, len); + memcpy(buffer->bytes + buffer->used, bytes, len); + buffer->used += len; +} + +static void rt_cport_append_record(rt_buffer_t *buffer, const char *data, size_t len, char pad) { + char record[RT_CPORT_RECORD_LEN]; + memset(record, pad, sizeof(record)); + memcpy(record, data, len < sizeof(record) ? len : sizeof(record)); + rt_cport_append(buffer, record, sizeof(record)); +} + +static void rt_cport_append_text(rt_buffer_t *buffer, const char *text) { + rt_cport_append_record(buffer, text, strlen(text), ' '); +} + +static void rt_cport_append_span(rt_buffer_t *buffer, int type, const char *data, size_t len) { + char header[RT_CPORT_RECORD_LEN+1]; + size_t records = (len + RT_CPORT_RECORD_LEN - 1) / RT_CPORT_RECORD_LEN; + size_t i; + + snprintf(header, sizeof(header), "SPAN CONTROL %-5d%-9lu%-9lu%-9luL %lu", type, (unsigned long)len, + (unsigned long)records, (unsigned long)(len - (records - 1) * RT_CPORT_RECORD_LEN), (unsigned long)len); + rt_cport_append_text(buffer, header); + for (i=0; i> 8) & 0xFF; + dst[1] = value & 0xFF; +} + +static void rt_cport_put4(char *dst, unsigned long value) { + rt_cport_put2(&dst[0], (value >> 16) & 0xFFFF); + rt_cport_put2(&dst[2], value & 0xFFFF); +} + +/* "DOLLAR12.2" -> "DOLLAR", 12, 2 */ +static void rt_cport_split_format(const char *format, char *name, size_t name_len, int *width, int *decimals) { + size_t len = 0; + const char *dot = NULL; + if (format == NULL) + format = ""; + while (format[len] && !(format[len] >= '0' && format[len] <= '9') && format[len] != '.') + len++; + snprintf(name, name_len, "%.*s", (int)len, format); + *width = atoi(&format[len]); + dot = strchr(&format[len], '.'); + *decimals = dot ? atoi(dot + 1) : 0; +} + +static size_t rt_cport_variable(char *dst, const rt_cport_column_t *column, int var_number, + size_t offset, int bad_name_length) { + char format[32], informat[32]; + int format_width, format_decimals, informat_width, informat_decimals; + + rt_cport_split_format(column->format, format, sizeof(format), &format_width, &format_decimals); + rt_cport_split_format(column->informat, informat, sizeof(informat), &informat_width, &informat_decimals); + + size_t name_len = strlen(column->name), label_len = strlen(column->label); + size_t format_len = strlen(format), informat_len = strlen(informat); + size_t end = 72 + name_len + label_len; + size_t len = end + 36 + format_len + informat_len + 6; + + memset(dst, 0, len); + memcpy(dst, "NAME", 4); + rt_cport_put2(&dst[20], format_width); + rt_cport_put2(&dst[22], format_decimals); + rt_cport_put2(&dst[24], informat_width); + rt_cport_put2(&dst[26], informat_decimals); + dst[36] = 0x21; + dst[37] = (char)0xC0; + rt_cport_put4(&dst[40], offset); + rt_cport_put4(&dst[44], column->width); + rt_cport_put4(&dst[48], column->width); + rt_cport_put2(&dst[52], bad_name_length ? 1000 : name_len); + rt_cport_put2(&dst[54], label_len); + dst[56] = column->type == READSTAT_TYPE_STRING ? 2 : 1; + dst[71] = 2; + memcpy(&dst[72], column->name, name_len); + memcpy(&dst[72 + name_len], column->label, label_len); + rt_cport_put4(&dst[end], var_number); + dst[end + 31] = dst[56]; + rt_cport_put2(&dst[end + 32], format_len); + memcpy(&dst[end + 34], format, format_len); + rt_cport_put2(&dst[end + 34 + format_len], informat_len); + memcpy(&dst[end + 36 + format_len], informat, informat_len); + + return len; +} + +/* Compressed: banner, then runs of 3+ NULs or blanks as BC n / BC 80+n + * (n+2 bytes), a literal 0xBC as BC 00, padded to 80 bytes with blanks */ +static void rt_cport_compress(rt_buffer_t *dst, const rt_buffer_t *src, int runs_cross_records) { + const char banner[] = "**COMPRESSED** **COMPRESSED** **COMPRESSED** **COMPRESSED** **COMPRESSED********"; + size_t i = 0; + + rt_cport_append(dst, banner, RT_CPORT_RECORD_LEN); + while (i < src->used) { + unsigned char byte = src->bytes[i]; + size_t limit = runs_cross_records ? src->used : (i / RT_CPORT_RECORD_LEN + 1) * RT_CPORT_RECORD_LEN; + size_t run = 1; + if (byte == ' ' || byte == '\0') { + while (i + run < limit && run < 129 && (unsigned char)src->bytes[i + run] == byte) + run++; + } + if (run >= 3) { + char code[2] = { (char)0xBC, (char)((byte == ' ' ? 0x80 : 0x00) | (run - 2)) }; + rt_cport_append(dst, code, sizeof(code)); + i += run; + } else if (byte == 0xBC) { + char code[2] = { (char)0xBC, 0x00 }; + rt_cport_append(dst, code, sizeof(code)); + i++; + } else { + rt_cport_append(dst, &src->bytes[i], 1); + i++; + } + } + while (dst->used % RT_CPORT_RECORD_LEN) + rt_cport_append(dst, " ", 1); +} + +static void rt_cport_build(rt_buffer_t *buffer, const rt_cport_file_t *file, const rt_cport_build_t *build) { + rt_buffer_t *plain = buffer_init(); + char record[RT_CPORT_RECORD_LEN+1]; + char data[1024]; + size_t offsets[RT_CPORT_MAX_COLUMNS]; + size_t row_length = 0; + size_t len, i; + int j; + + memset(record, ' ', RT_CPORT_RECORD_LEN); + memcpy(record, "LIB CONTROL X64_SRV1", 20); + memset(&record[20], '\0', 8); + memcpy(&record[28], " SAS9.4 I", 13); + rt_cport_append(plain, record, RT_CPORT_RECORD_LEN); + + if (build->catalog_first || build->catalog_only) { + rt_cport_append_text(plain, "C901SMP FORMATS OC0 2 MAX LRECL =152"); + rt_cport_append_text(plain, "OBJECT CONTROL AGEGRP FORMAT 1"); + /* looks like a dataset member, but is the payload of a span */ + memset(data, ' ', 120); + memcpy(data, "D901SMP FAKE", 16); + rt_cport_append_span(plain, 3, data, 120); + rt_cport_append_text(plain, "End of Object"); + } + + if (!build->catalog_only) { + /* numerics first, then strings, as SAS stores them */ + for (j=0; jcolumns_count; j++) { + if (file->columns[j].type != READSTAT_TYPE_STRING) { + offsets[j] = row_length; + row_length += file->columns[j].width; + } + } + for (j=0; jcolumns_count; j++) { + if (file->columns[j].type == READSTAT_TYPE_STRING) { + offsets[j] = row_length; + row_length += file->columns[j].width; + } + } + row_length = (row_length + 7) / 8 * 8; + + char member[256]; + snprintf(member, sizeof(member), "D901SMP %-32sVC%-5dRC%-12ldRL%-12lu1", + file->table_name, file->columns_count, file->rows, (unsigned long)row_length); + rt_cport_append_text(plain, member); + + size_t label_len = strlen(file->label); + char label_len_text[32]; + snprintf(label_len_text, sizeof(label_len_text), "%-3lu", (unsigned long)label_len); + memset(record, ' ', RT_CPORT_RECORD_LEN); + record[9] = 'S'; + record[11] = '0'; + record[14] = '0'; + memcpy(&record[17], label_len_text, 3); + memcpy(&record[20], "NO", 2); + record[28] = '0'; + record[40] = '1'; + memcpy(&record[64], file->sas_encoding, strlen(file->sas_encoding)); + memset(&record[72], '\0', 4); + rt_cport_append(plain, record, RT_CPORT_RECORD_LEN); + rt_cport_append_text(plain, ""); + rt_cport_append_text(plain, ""); + for (i=0; ilabel[i], + label_len - i < RT_CPORT_RECORD_LEN ? label_len - i : RT_CPORT_RECORD_LEN, ' '); + } + + memset(data, '\0', 40); + rt_cport_append_span(plain, -7, data, 40); + if (build->extra_spans) { + memset(data, '\0', 46); + memcpy(data, "\0\002id", 4); + rt_cport_append_span(plain, -2, data, 46); + } + for (j=0; jcolumns_count; j++) { + len = rt_cport_variable(data, &file->columns[j], j + 1, offsets[j], build->bad_name_length && j == 0); + rt_cport_append_span(plain, -1, data, len); + } + if (build->extra_spans) { + memset(data, ' ', 8); + memset(&data[8], '\0', 20); + rt_cport_append_span(plain, -3, data, 28); + } else { + memset(data, '\0', 20); + rt_cport_append_span(plain, -3, data, 20); + } + + for (i=0; irows; i++) { + memset(data, 'Z', row_length); /* padding bytes hold stale data in real files */ + for (j=0; jcolumns_count; j++) { + const rt_cport_column_t *column = &file->columns[j]; + const rt_cport_value_t *value = &column->values[i]; + char *field = &data[offsets[j]]; + if (column->type == READSTAT_TYPE_STRING) { + const char *bytes = value->raw ? value->raw : value->s; + memset(field, ' ', column->width); + memcpy(field, bytes, strlen(bytes)); + } else if (value->missing) { + memset(field, '\0', column->width); + field[0] = value->missing; + } else { + char ibm[8]; + cnxptiee(&value->d, CN_TYPE_NATIVE, ibm, CN_TYPE_XPORT); + memcpy(field, ibm, column->width); + } + } + rt_cport_append_span(plain, 0, data, row_length); + } + rt_cport_append_text(plain, "End of Data"); + } + + buffer_reset(buffer); + if (build->compress) { + rt_cport_compress(buffer, plain, build->compress == 2); + } else { + rt_cport_append(buffer, plain->bytes, plain->used); + } + buffer_free(plain); +} + +int test_xport_cport(void) { + rt_buffer_t *buffer = buffer_init(); + long limits[][2] = { { 0, 0 }, { 1, 1 }, { 3, 4 }, { 20, 0 } }; + struct { + const char *resource_name; + const rt_cport_file_t *file; + } resources[] = { + { "cport_basic_win94.xpt", &_cport_basic_win94 }, + { "cport_basic_viya_nocompress.xpt", &_cport_basic_viya }, + { "cport_encoding_viya.xpt", &_cport_encoding_viya } + }; + rt_cport_build_t builds[] = { + { .compress = 0 }, + { .compress = 1 }, + { .compress = 2 }, + { .compress = 1, .catalog_first = 1 }, + { .compress = 0, .extra_spans = 1 }, + { .compress = 2, .catalog_first = 1, .extra_spans = 1 } + }; + rt_cport_file_t unknown_encoding = _cport_built; + unknown_encoding.sas_encoding = "xyz1"; + char test_name[128]; + int failed = 0; + size_t i, j, cut; + + /* Files written by SAS */ + for (i=0; iused; + size_t end = i ? used - RT_CPORT_RECORD_LEN : used; + for (cut=0; cutused = cut; + if (rt_cport_parse(buffer, &ctx, 0, 0) == READSTAT_OK) { + printf("CPORT test truncated: no error for a %s file cut after %lu of %lu bytes\n", + i ? "compressed" : "plain", (unsigned long)cut, (unsigned long)used); + failed = 1; + break; + } + } + } + + buffer_free(buffer); + return failed; +} diff --git a/src/test/test_sas.h b/src/test/test_sas.h index 6741cdc1..ad2a8c66 100644 --- a/src/test/test_sas.h +++ b/src/test/test_sas.h @@ -1,3 +1,4 @@ long sas_file_format_version(long format_code); int test_sas7bcat_large_label_sets(void); +int test_xport_cport(void);