summer restructuring:

* .h include only the strict minimum for their own parsing
  * this forces all files to include explicitment their needs and not count on far streched dependencies
  * this helps Makefile to rebuild only the minimum
  * according to this rule, most standalone .h are now gone
  * big app.h is gone
  * remove seldom __cplusplus, if c++ happens, everything will have to be done properly anyway
* all unrequired include were removed
* split common/ into common/ (client+arm) and common_arm/ (os+bootloader)
  * bring zlib to common/
  * bring stuff not really/not yet used in common back to armsrc/ or client/
  * bring liblua into client/
  * bring uart into client/
  * move some portions of code around (dbprint, protocols,...)
* rename unused files into *_disabled.[ch] to make it explicit
* rename soft Uarts between 14a, 14b and iclass, so a standalone could use several without clash
* remove PrintAndLogDevice
* move deprecated-hid-flasher from client to tools
* Makefiles
  * treat deps in armsrc/ as in client/
  * client: stop on warning (-Werror), same as for armsrc/

Tested on:

* all standalone modes
* Linux
This commit is contained in:
Philippe Teuwen 2019-08-08 16:57:33 +02:00
commit d19754567d
447 changed files with 2553 additions and 2599 deletions

View file

@ -1,121 +0,0 @@
#-----------------------------------------------------------------------------
# This code is licensed to you under the terms of the GNU GPL, version 2 or,
# at your option, any later version. See the LICENSE.txt file for the text of
# the license.
#-----------------------------------------------------------------------------
# Common makefile functions for all platforms
#-----------------------------------------------------------------------------
# This new makefile replaces the previous Makefile/Makefile.linux
# with as much common code for both environments as possible.
# Following is a short OS detection to set up variables, all the
# remaining Makefile should be portable and only depend on these
# variables
#
ifneq ($(V),1)
Q?=@
endif
# To see full command lines, use make V=1
# Make sure that all is the default target
# (The including Makefile still needs to define what 'all' is)
platform = $(shell uname)
all:
CROSS ?= arm-none-eabi-
CC = $(CROSS)gcc
AS = $(CROSS)as
LD = $(CROSS)ld
OBJCOPY = $(CROSS)objcopy
GZIP=gzip
OBJDIR = obj
INCLUDE = -I../include -I../common -I.
TAR=tar
TARFLAGS = -C .. -rvf
# Windows' echo echos its input verbatim, on Posix there is some
# amount of shell command line parsing going on. echo "" on
# Windows yields literal "", on Linux yields an empty line
ifeq ($(shell echo ""),)
DELETE=rm -rf
MOVE=mv
COPY=cp
PATHSEP=/
FLASH_TOOL=client/flasher
# This is probably a proper system, so we can use uname
DETECTED_OS=$(platform)
else
# Assume that we are running on Windows.
DELETE=del /q
MOVE=ren
COPY=copy
PATHSEP=\\#
FLASH_TOOL=client\\flasher.exe
DETECTED_OS=Windows
endif
# Also search prerequisites in the common directory (for usb.c), the fpga directory (for fpga.bit), and the zlib directory
VPATH = . ../common ../common/crapto1 ../common/mbedtls ../fpga ../zlib ../armsrc/Standalone ../uart
INCLUDES = ../include/proxmark3.h ../include/at91sam7s512.h ../include/config_gpio.h ../include/pm3_cmd.h $(APP_INCLUDES)
CFLAGS = -c $(INCLUDE) -Wall -Werror -pedantic -Wunused -std=c99 $(APP_CFLAGS) -Os
LDFLAGS = -nostartfiles -nodefaultlibs -Wl,-gc-sections -n
LIBS = -lgcc
THUMBOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(THUMBSRC)))
ARMOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(ARMSRC)))
ASMOBJ = $(patsubst %.s,$(OBJDIR)/%.o,$(notdir $(ASMSRC)))
VERSIONOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(VERSIONSRC)))
$(THUMBOBJ): $(OBJDIR)/%.o: %.c $(INCLUDES)
$(info [-] CC $<)
$(Q)$(CC) $(CFLAGS) -mthumb -mthumb-interwork -o $@ $<
$(ARMOBJ): $(OBJDIR)/%.o: %.c $(INCLUDES)
$(info [-] CC $<)
$(Q)$(CC) $(CFLAGS) -mthumb-interwork -o $@ $<
$(ASMOBJ): $(OBJDIR)/%.o: %.s
$(info [-] CC $<)
$(Q)$(CC) $(CFLAGS) -mthumb-interwork -o $@ $<
$(VERSIONOBJ): $(OBJDIR)/%.o: %.c $(INCLUDES)
$(info [-] CC $<)
$(Q)$(CC) $(CFLAGS) -mthumb -mthumb-interwork -o $@ $<
# This objcopy call translates physical flash addresses to logical addresses
# without touching start address or RAM addresses (.bss and .data sections)
# See ldscript.common. -- Henryk Plötz <henryk@ploetzli.ch> 2009-08-27
OBJCOPY_TRANSLATIONS = --no-change-warnings \
--change-addresses -0x100000 --change-start 0 \
--change-section-address .bss+0 --change-section-address .data-0x100000 \
--change-section-address .commonarea+0
$(OBJDIR)/%.s19: $(OBJDIR)/%.elf
$(info [=] GEN $@)
$(Q)$(OBJCOPY) -Osrec --srec-forceS3 --strip-debug $(OBJCOPY_TRANSLATIONS) $^ $@
# easy printing of MAKE VARIABLES
print-%: ; @echo $* = $($*)
# Automatic dependency generation
DEPENDENCY_FILES = $(patsubst %.c,$(OBJDIR)/%.d,$(notdir $(THUMBSRC))) \
$(patsubst %.c,$(OBJDIR)/%.d,$(notdir $(ARMSRC))) \
$(patsubst %.s,$(OBJDIR)/%.d,$(notdir $(ASMSRC)))
$(DEPENDENCY_FILES): Makefile ../common/Makefile.common
$(patsubst %.o,%.d,$(THUMBOBJ) $(ARMOBJ)): $(OBJDIR)/%.d: %.c
@$(CC) -MM -MT "$(@) $(@:.d=.o)" $(CFLAGS) $< > $@
$(patsubst %.o,%.d,$(ASMOBJ)):$(OBJDIR)/%.d: %.s
@$(CC) -MM -MT "$(@) $(@:.d=.o)" $(CFLAGS) $< > $@
-include $(DEPENDENCY_FILES)

View file

@ -1,183 +0,0 @@
# Default platform if no platform specified
PLATFORM?=PM3RDV4
# Standalone Mode info (path depends if make is called at top or from armsrc)
# Guard Makefile.hal against implicit rules: (with % to avoid being first goal)
%/Makefile.hal: ;
-include armsrc/Standalone/Makefile.hal
-include Standalone/Makefile.hal
ifndef DEFAULT_STANDALONE
$(error Could not find armsrc/Standalone/Makefile.hal)
endif
define KNOWN_PLATFORM_DEFINITIONS
Known definitions:
+==========================================================+
| PLATFORM | DESCRIPTION |
+==========================================================+
| PM3RDV4 (def) | Proxmark3 rdv4 with AT91SAM7S512 |
+----------------------------------------------------------+
| PM3EVO | Proxmark3 EVO with AT91SAM7S512 |
+----------------------------------------------------------+
| PM3EASY | Proxmark3 rdv3 Easy with AT91SAM7S256 |
+----------------------------------------------------------+
| PM3RDV2 | Proxmark3 rdv2 with AT91SAM7S512 |
+----------------------------------------------------------+
| PM3OLD256 | Proxmark3 V1 with AT91SAM7S256 |
+----------------------------------------------------------+
| PM3OLD512 | Proxmark3 V1 with AT91SAM7S512 |
+----------------------------------------------------------+
+==========================================================+
| PLATFORM_EXTRAS | DESCRIPTION |
+==========================================================+
| BTADDON | Proxmark3 rdv4 BT add-on |
+----------------------------------------------------------+
endef
define HELP_DEFINITIONS
Options to define platform, platform extras and/or standalone mode:
(1) Run make with PLATFORM, PLATFORM_EXTRAS and/or STANDALONE as follows:
make PLATFORM=PM3EASY STANDALONE=$(HELP_EXAMPLE_STANDALONE)
(2) Save a file called Makefile.platform with contents:
PLATFORM=PM3EASY
or if you have a Proxmark 3 RDV4 with the BT add-on:
PLATFORM=PM3RDV4
PLATFORM_EXTRAS=BTADDON
Default standalone mode is $(DEFAULT_STANDALONE).
To disable standalone modes, set explicitly an empty STANDALONE:
STANDALONE=
endef
define KNOWN_DEFINITIONS
$(KNOWN_PLATFORM_DEFINITIONS)
$(KNOWN_STANDALONE_DEFINITIONS)
$(HELP_DEFINITIONS)
endef
PLTNAME = Unknown Platform
ifeq ($(PLATFORM),PM3RDV4)
MCU = AT91SAM7S512
PLATFORM_DEFS = -DWITH_SMARTCARD -DWITH_FLASH
PLTNAME = Proxmark3 rdv4
else ifeq ($(PLATFORM),PM3EVO)
MCU = AT91SAM7S512
PLTNAME = Proxmark3 EVO
else ifeq ($(PLATFORM),PM3EASY)
MCU = AT91SAM7S256
PLTNAME = Proxmark3 rdv3 Easy
else ifeq ($(PLATFORM),PM3RDV2)
MCU = AT91SAM7S512
PLTNAME = Proxmark3 rdv2
else ifeq ($(PLATFORM),PM3OLD256)
MCU = AT91SAM7S256
PLTNAME = Proxmark3 V1 with AT91SAM7S256
else ifeq ($(PLATFORM),PM3OLD512)
MCU = AT91SAM7S512
PLTNAME = Proxmark3 V1 with AT91SAM7S512
else
$(error Invalid or empty PLATFORM: $(PLATFORM). $(KNOWN_DEFINITIONS))
endif
# parsing additional PLATFORM_EXTRAS tokens
PLATFORM_EXTRAS_TMP:=$(PLATFORM_EXTRAS)
ifneq (,$(findstring BTADDON,$(PLATFORM_EXTRAS_TMP)))
PLATFORM_DEFS += -DWITH_FPC_USART_HOST
PLATFORM_EXTRAS_TMP := $(strip $(filter-out BTADDON,$(PLATFORM_EXTRAS_TMP)))
endif
ifneq (,$(findstring FPC_USART_DEV,$(PLATFORM_EXTRAS_TMP)))
PLATFORM_DEFS += -DWITH_FPC_USART_DEV
PLATFORM_EXTRAS_TMP := $(strip $(filter-out FPC_USART_DEV,$(PLATFORM_EXTRAS_TMP)))
endif
ifneq (,$(PLATFORM_EXTRAS_TMP))
$(error Unknown PLATFORM_EXTRAS token(s): $(PLATFORM_EXTRAS_TMP))
endif
# common LF support
PLATFORM_DEFS += \
-DWITH_LF \
-DWITH_HITAG
# common HF support
PLATFORM_DEFS += \
-DWITH_ISO15693 \
-DWITH_LEGICRF \
-DWITH_ISO14443b \
-DWITH_ISO14443a \
-DWITH_ICLASS \
-DWITH_FELICA \
-DWITH_NFCBARCODE \
-DWITH_HFSNIFF
# Standalone mode
ifneq ($(strip $(filter $(PLATFORM_DEFS),$(STANDALONE_REQ_DEFS))),$(strip $(STANDALONE_REQ_DEFS)))
$(error Chosen Standalone mode $(STANDALONE) requires $(strip $(STANDALONE_REQ_DEFS)), unsupported by $(PLTNAME))
endif
PLATFORM_DEFS+=$(STANDALONE_PLATFORM_DEFS)
$(info $(findstring WITH_STANDALONE_*,$(PLATFORM_DEFS)))
# Misc
#PLATFORM_DEFS += -DWITH_LCD
# Add flags dependencies :
# WITH_FPC_USART_* needs WITH_FPC_USART :
ifneq (,$(findstring WITH_FPC_USART_,$(PLATFORM_DEFS)))
PLATFORM_DEFS += -DWITH_FPC_USART
endif
PLATFORM_DEFS_INFO = $(strip $(filter-out STANDALONE%, $(subst -DWITH_,,$(PLATFORM_DEFS))))
PLATFORM_DEFS_INFO_STANDALONE = $(strip $(subst STANDALONE_,, $(filter STANDALONE%, $(subst -DWITH_,,$(PLATFORM_DEFS)))))
# Check that only one Standalone mode has been chosen
ifneq (,$(word 2, $(PLATFORM_DEFS_INFO_STANDALONE)))
$(error You must choose only one Standalone mode!: $(PLATFORM_DEFS_INFO_STANDALONE))
endif
PLATFORM_EXTRAS_INFO = $(PLATFORM_EXTRAS)
# info when no extra
ifeq (,$(PLATFORM_EXTRAS_INFO))
PLATFORM_EXTRAS_INFO = No extra selected
endif
# info when no standalone mode
ifeq (,$(PLATFORM_DEFS_INFO_STANDALONE))
PLATFORM_DEFS_INFO_STANDALONE = No standalone mode selected
endif
PLATFORM_CHANGED=false
ifneq ($(PLATFORM), $(CACHED_PLATFORM))
PLATFORM_CHANGED=true
else ifneq ($(PLATFORM_EXTRAS), $(CACHED_PLATFORM_EXTRAS))
PLATFORM_CHANGED=true
else ifneq ($(PLATFORM_DEFS), $(CACHED_PLATFORM_DEFS))
PLATFORM_CHANGED=true
endif
export PLATFORM
export PLATFORM_EXTRAS
export PLATFORM_EXTRAS_INFO
export PLTNAME
export MCU
export PLATFORM_DEFS
export PLATFORM_DEFS_INFO
export PLATFORM_DEFS_INFO_STANDALONE
export PLATFORM_CHANGED
$(info ===================================================================)
$(info Platform name: $(PLTNAME))
$(info PLATFORM: $(PLATFORM))
$(info Platform extras: $(PLATFORM_EXTRAS_INFO))
$(info Included options: $(PLATFORM_DEFS_INFO))
$(info Standalone mode: $(PLATFORM_DEFS_INFO_STANDALONE))
$(info ===================================================================)

View file

@ -1,8 +1,7 @@
#ifndef BUCKETSORT_H__
#define BUCKETSORT_H__
#include <stdint.h>
#include <stdlib.h>
#include "common.h"
typedef struct bucket {
uint32_t *head;
@ -21,4 +20,5 @@ typedef struct bucket_info {
void bucket_sort_intersect(uint32_t *const estart, uint32_t *const estop,
uint32_t *const ostart, uint32_t *const ostop,
bucket_info_t *bucket_info, bucket_array_t bucket);
#endif

View file

@ -1,244 +0,0 @@
/*
* Proxmark send and receive commands
*
* Copyright (c) 2012, Roel Verdult
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file cmd.c
* @brief
*/
#include "cmd.h"
#include "crc16.h"
// Flags to tell where to add CRC on sent replies
bool reply_with_crc_on_usb = false;
bool reply_with_crc_on_fpc = true;
// "Session" flag, to tell via which interface next msgs should be sent: USB or FPC USART
bool reply_via_fpc = false;
bool reply_via_usb = false;
int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) {
PacketResponseOLD txcmd;
for (size_t i = 0; i < sizeof(PacketResponseOLD); i++)
((uint8_t *)&txcmd)[i] = 0x00;
// Compose the outgoing command frame
txcmd.cmd = cmd;
txcmd.arg[0] = arg0;
txcmd.arg[1] = arg1;
txcmd.arg[2] = arg2;
// Add the (optional) content to the frame, with a maximum size of PM3_CMD_DATA_SIZE
if (data && len) {
len = MIN(len, PM3_CMD_DATA_SIZE);
for (size_t i = 0; i < len; i++) {
txcmd.d.asBytes[i] = ((uint8_t *)data)[i];
}
}
int resultfpc = PM3_EUNDEF;
int resultusb = PM3_EUNDEF;
// Send frame and make sure all bytes are transmitted
if (reply_via_usb) {
resultusb = usb_write((uint8_t *)&txcmd, sizeof(PacketResponseOLD));
}
if (reply_via_fpc) {
#ifdef WITH_FPC_USART_HOST
resultfpc = usart_writebuffer_sync((uint8_t *)&txcmd, sizeof(PacketResponseOLD));
#else
return PM3_EDEVNOTSUPP;
#endif
}
// we got two results, let's prioritize the faulty one and USB over FPC.
if (reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb;
if (reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc;
return PM3_SUCCESS;
}
static int reply_ng_internal(uint16_t cmd, int16_t status, uint8_t *data, size_t len, bool ng) {
PacketResponseNGRaw txBufferNG;
size_t txBufferNGLen;
// Compose the outgoing command frame
txBufferNG.pre.magic = RESPONSENG_PREAMBLE_MAGIC;
txBufferNG.pre.cmd = cmd;
txBufferNG.pre.status = status;
txBufferNG.pre.ng = ng;
if (len > PM3_CMD_DATA_SIZE) {
len = PM3_CMD_DATA_SIZE;
// overwrite status
txBufferNG.pre.status = PM3_EOVFLOW;
}
txBufferNG.pre.length = len;
// Add the (optional) content to the frame, with a maximum size of PM3_CMD_DATA_SIZE
if (data && len) {
for (size_t i = 0; i < len; i++) {
txBufferNG.data[i] = data[i];
}
}
PacketResponseNGPostamble *tx_post = (PacketResponseNGPostamble *)((uint8_t *)&txBufferNG + sizeof(PacketResponseNGPreamble) + len);
// Note: if we send to both FPC & USB, we'll set CRC for both if any of them require CRC
if ((reply_via_fpc && reply_with_crc_on_fpc) || ((reply_via_usb) && reply_with_crc_on_usb)) {
uint8_t first, second;
compute_crc(CRC_14443_A, (uint8_t *)&txBufferNG, sizeof(PacketResponseNGPreamble) + len, &first, &second);
tx_post->crc = (first << 8) + second;
} else {
tx_post->crc = RESPONSENG_POSTAMBLE_MAGIC;
}
txBufferNGLen = sizeof(PacketResponseNGPreamble) + len + sizeof(PacketResponseNGPostamble);
int resultfpc = PM3_EUNDEF;
int resultusb = PM3_EUNDEF;
// Send frame and make sure all bytes are transmitted
if (reply_via_usb) {
resultusb = usb_write((uint8_t *)&txBufferNG, txBufferNGLen);
}
if (reply_via_fpc) {
#ifdef WITH_FPC_USART_HOST
resultfpc = usart_writebuffer_sync((uint8_t *)&txBufferNG, txBufferNGLen);
#else
return PM3_EDEVNOTSUPP;
#endif
}
// we got two results, let's prioritize the faulty one and USB over FPC.
if (reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb;
if (reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc;
return PM3_SUCCESS;
}
int reply_ng(uint16_t cmd, int16_t status, uint8_t *data, size_t len) {
return reply_ng_internal(cmd, status, data, len, true);
}
int reply_mix(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) {
uint16_t status = PM3_SUCCESS;
uint64_t arg[3] = {arg0, arg1, arg2};
if (len > PM3_CMD_DATA_SIZE - sizeof(arg)) {
len = PM3_CMD_DATA_SIZE - sizeof(arg);
status = PM3_EOVFLOW;
}
uint8_t cmddata[PM3_CMD_DATA_SIZE];
memcpy(cmddata, arg, sizeof(arg));
if (len && data)
memcpy(cmddata + sizeof(arg), data, len);
return reply_ng_internal(cmd, status, cmddata, len + sizeof(arg), false);
}
static int receive_ng_internal(PacketCommandNG *rx, uint32_t read_ng(uint8_t *data, size_t len), bool usb, bool fpc) {
PacketCommandNGRaw rx_raw;
size_t bytes = read_ng((uint8_t *)&rx_raw.pre, sizeof(PacketCommandNGPreamble));
if (bytes == 0)
return PM3_ENODATA;
if (bytes != sizeof(PacketCommandNGPreamble))
return PM3_EIO;
rx->magic = rx_raw.pre.magic;
rx->ng = rx_raw.pre.ng;
uint16_t length = rx_raw.pre.length;
rx->cmd = rx_raw.pre.cmd;
if (rx->magic == COMMANDNG_PREAMBLE_MAGIC) { // New style NG command
if (length > PM3_CMD_DATA_SIZE)
return PM3_EOVFLOW;
// Get the core and variable length payload
bytes = read_ng((uint8_t *)&rx_raw.data, length);
if (bytes != length)
return PM3_EIO;
if (rx->ng) {
memcpy(rx->data.asBytes, rx_raw.data, length);
rx->length = length;
} else {
uint64_t arg[3];
if (length < sizeof(arg))
return PM3_EIO;
memcpy(arg, rx_raw.data, sizeof(arg));
rx->oldarg[0] = arg[0];
rx->oldarg[1] = arg[1];
rx->oldarg[2] = arg[2];
memcpy(rx->data.asBytes, rx_raw.data + sizeof(arg), length - sizeof(arg));
rx->length = length - sizeof(arg);
}
// Get the postamble
bytes = read_ng((uint8_t *)&rx_raw.foopost, sizeof(PacketCommandNGPostamble));
if (bytes != sizeof(PacketCommandNGPostamble))
return PM3_EIO;
// Check CRC, accept MAGIC as placeholder
rx->crc = rx_raw.foopost.crc;
if (rx->crc != COMMANDNG_POSTAMBLE_MAGIC) {
uint8_t first, second;
compute_crc(CRC_14443_A, (uint8_t *)&rx_raw, sizeof(PacketCommandNGPreamble) + length, &first, &second);
if ((first << 8) + second != rx->crc)
return PM3_EIO;
}
reply_via_usb = usb;
reply_via_fpc = fpc;
} else { // Old style command
PacketCommandOLD rx_old;
memcpy(&rx_old, &rx_raw.pre, sizeof(PacketCommandNGPreamble));
bytes = read_ng(((uint8_t *)&rx_old) + sizeof(PacketCommandNGPreamble), sizeof(PacketCommandOLD) - sizeof(PacketCommandNGPreamble));
if (bytes != sizeof(PacketCommandOLD) - sizeof(PacketCommandNGPreamble))
return PM3_EIO;
reply_via_usb = usb;
reply_via_fpc = fpc;
rx->ng = false;
rx->magic = 0;
rx->crc = 0;
rx->cmd = rx_old.cmd;
rx->oldarg[0] = rx_old.arg[0];
rx->oldarg[1] = rx_old.arg[1];
rx->oldarg[2] = rx_old.arg[2];
rx->length = PM3_CMD_DATA_SIZE;
memcpy(&rx->data, &rx_old.d.asBytes, rx->length);
}
return PM3_SUCCESS;
}
int receive_ng(PacketCommandNG *rx) {
// Check if there is a packet available
if (usb_poll_validate_length())
return receive_ng_internal(rx, usb_read_ng, true, false);
#ifdef WITH_FPC_USART_HOST
// Check if there is a FPC packet available
if (usart_rxdata_available() > 0)
return receive_ng_internal(rx, usart_read_ng, false, true);
#endif
return PM3_ENODATA;
}

View file

@ -1,83 +0,0 @@
/*
* Proxmark send and receive commands
*
* Copyright (c) 2010, Roel Verdult
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file cmd.h
* @brief
*/
#ifndef _PROXMARK_CMD_H_
#define _PROXMARK_CMD_H_
#include "common.h"
#include "pm3_cmd.h"
#include "usb_cdc.h"
#include "usart.h"
#include "proxmark3.h"
int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len);
int reply_ng(uint16_t cmd, int16_t status, uint8_t *data, size_t len);
int reply_mix(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len);
int receive_ng(PacketCommandNG *rx);
// Flags to tell where to add CRC on sent replies
extern bool reply_with_crc_on_usb;
extern bool reply_with_crc_on_fpc;
// "Session" flag, to tell via which interface next msgs should be sent: USB and/or FPC USART
extern bool reply_via_fpc;
extern bool reply_via_usb;
extern void Dbprintf(const char *fmt, ...);
#define Dbprintf_usb(...) {\
bool tmpfpc = reply_via_fpc;\
bool tmpusb = reply_via_usb;\
reply_via_fpc = false;\
reply_via_usb = true;\
Dbprintf(__VA_ARGS__);\
reply_via_fpc = tmpfpc;\
reply_via_usb = tmpusb;}
#define Dbprintf_fpc(...) {\
bool tmpfpc = reply_via_fpc;\
bool tmpusb = reply_via_usb;\
reply_via_fpc = true;\
reply_via_usb = false;\
Dbprintf(__VA_ARGS__);\
reply_via_fpc = tmpfpc;\
reply_via_usb = tmpusb;}
#define Dbprintf_all(...) {\
bool tmpfpc = reply_via_fpc;\
bool tmpusb = reply_via_usb;\
reply_via_fpc = true;\
reply_via_usb = true;\
Dbprintf(__VA_ARGS__);\
reply_via_fpc = tmpfpc;\
reply_via_usb = tmpusb;}
#endif // _PROXMARK_CMD_H_

View file

@ -11,8 +11,8 @@
#ifndef __COMMONUTIL_H
#define __COMMONUTIL_H
#include <stddef.h>
#include <inttypes.h>
#include "common.h"
// endian change for 16bit
#ifdef __GNUC__
#ifndef BSWAP_16
@ -53,11 +53,4 @@ void lsl(uint8_t *data, size_t len);
int32_t le24toh(uint8_t data[3]);
void htole24(uint32_t val, uint8_t data[3]);
# define _BLUE_(s) "\x1b[34m" s "\x1b[0m "
# define _RED_(s) "\x1b[31m" s "\x1b[0m "
# define _GREEN_(s) "\x1b[32m" s "\x1b[0m "
# define _YELLOW_(s) "\x1b[33m" s "\x1b[0m "
# define _MAGENTA_(s) "\x1b[35m" s "\x1b[0m "
# define _CYAN_(s) "\x1b[36m" s "\x1b[0m "
#endif

View file

@ -19,6 +19,8 @@
*/
#include "crapto1.h"
#include "bucketsort.h"
#include <stdlib.h>
#include "parity.h"

View file

@ -19,13 +19,10 @@
*/
#ifndef CRAPTO1_INCLUDED
#define CRAPTO1_INCLUDED
#include <stdint.h>
#include <stdbool.h>
#include "bucketsort.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
struct Crypto1State {uint32_t odd, even;};
#if defined(__arm__) && !defined(__linux__) && !defined(_WIN32) && !defined(__APPLE__) // bare metal ARM Proxmark lacks malloc()/free()
@ -77,7 +74,4 @@ static inline int filter(uint32_t const x) {
f |= 0x0d938 >> (x >> 16 & 0xf) & 1;
return BIT(0xEC57E80A, f);
}
#ifdef __cplusplus
}
#endif
#endif

View file

@ -17,9 +17,9 @@
Copyright (C) 2008-2008 bla <blapost@gmail.com>
*/
#include "crapto1.h"
#include <stdlib.h>
#include "crapto1.h"
#include "parity.h"
#define SWAPENDIAN(x)\

View file

@ -9,6 +9,8 @@
//
#include "crc.h"
#include "commonutil.h"
void crc_init_ref(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor, bool refin, bool refout) {
crc_init(crc, order, polynom, initial_value, final_xor);
crc->refin = refin;

View file

@ -9,8 +9,7 @@
#ifndef __CRC_H
#define __CRC_H
#include "common.h" //stdint, stddef, stdbool
#include "commonutil.h" // reflect, bswap_16
#include "common.h"
typedef struct crc_ctx {
uint32_t state;
@ -24,6 +23,18 @@ typedef struct crc_ctx {
bool refout; /* Parameter: Reflect output CRC? */
} crc_t;
/* Static initialization of a crc structure */
#define CRC_INITIALIZER(_order, _polynom, _initial_value, _final_xor) { \
.state = ((_initial_value) & ((1L<<(_order))-1)), \
.order = (_order), \
.polynom = (_polynom), \
.initial_value = (_initial_value), \
.final_xor = (_final_xor), \
.mask = ((1L<<(_order))-1) \
.refin = false, \
.refout = false \
}
/* Initialize a crc structure. order is the order of the polynom, e.g. 32 for a CRC-32
* polynom is the CRC polynom. initial_value is the initial value of a clean state.
* final_xor is XORed onto the state before returning it from crc_result().
@ -62,16 +73,4 @@ uint32_t CRC4Legic(uint8_t *buff, size_t size);
// Calculate CRC-8/Legic checksum
uint32_t CRC8Legic(uint8_t *buff, size_t size);
/* Static initialization of a crc structure */
#define CRC_INITIALIZER(_order, _polynom, _initial_value, _final_xor) { \
.state = ((_initial_value) & ((1L<<(_order))-1)), \
.order = (_order), \
.polynom = (_polynom), \
.initial_value = (_initial_value), \
.final_xor = (_final_xor), \
.mask = ((1L<<(_order))-1) \
.refin = false, \
.refout = false \
}
#endif /* __CRC_H */

View file

@ -7,6 +7,9 @@
//-----------------------------------------------------------------------------
#include "crc16.h"
#include <string.h>
#include "commonutil.h"
static uint16_t crc_table[256];
static bool crc_table_init = false;
static CrcType_t current_crc_type = CRC_NONE;

View file

@ -8,11 +8,7 @@
#ifndef __CRC16_H
#define __CRC16_H
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "commonutil.h"
#include "common.h"
#define CRC16_POLY_CCITT 0x1021
#define CRC16_POLY_LEGIC 0xc6c6 //0x6363

View file

@ -9,18 +9,9 @@
#ifndef __CRC32_H
#define __CRC32_H
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "common.h"
void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc);
void crc32_append(uint8_t *data, const size_t len);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -1,5 +1,3 @@
#include <stdint.h>
#include <stddef.h>
#include "crc64.h"
#define CRC64_ISO_PRESET 0xFFFFFFFFFFFFFFFF

View file

@ -9,6 +9,8 @@
#ifndef __CRC64_H
#define __CRC64_H
#include "common.h"
void crc64(const uint8_t *data, const size_t len, uint64_t *crc) ;
#endif

View file

@ -1,9 +0,0 @@
#include "proxmark3.h"
/* This is the default version.c file that Makefile.common falls back to if perl is not available */
const struct version_information __attribute__((section(".version_information"))) version_information = {
VERSION_INFORMATION_MAGIC,
1, /* version 1 */
0, /* version information not present */
2, /* cleanliness couldn't be determined */
/* Remaining fields: zero */
};

View file

@ -1,173 +0,0 @@
#ifndef __DESFIRE_H
#define __DESFIRE_H
#include <string.h>
#include <stdarg.h>
#include "mbedtls/aes.h"
#include "mifare.h"
#define MAX_CRYPTO_BLOCK_SIZE 16
/* Mifare DESFire EV1 Application crypto operations */
#define APPLICATION_CRYPTO_DES 0x00
#define APPLICATION_CRYPTO_3K3DES 0x40
#define APPLICATION_CRYPTO_AES 0x80
#define MAC_LENGTH 4
#define CMAC_LENGTH 8
typedef enum {
MCD_SEND,
MCD_RECEIVE
} MifareCryptoDirection;
typedef enum {
MCO_ENCYPHER,
MCO_DECYPHER
} MifareCryptoOperation;
#define MDCM_MASK 0x000F
#define CMAC_NONE 0
// Data send to the PICC is used to update the CMAC
#define CMAC_COMMAND 0x010
// Data received from the PICC is used to update the CMAC
#define CMAC_VERIFY 0x020
// MAC the command (when MDCM_MACED)
#define MAC_COMMAND 0x100
// The command returns a MAC to verify (when MDCM_MACED)
#define MAC_VERIFY 0x200
#define ENC_COMMAND 0x1000
#define NO_CRC 0x2000
#define MAC_MASK 0x0F0
#define CMAC_MACK 0xF00
/* Communication mode */
#define MDCM_PLAIN 0x00
#define MDCM_MACED 0x01
#define MDCM_ENCIPHERED 0x03
/* Error code managed by the library */
#define CRYPTO_ERROR 0x01
enum DESFIRE_AUTH_SCHEME {
AS_LEGACY,
AS_NEW
};
enum DESFIRE_CRYPTOALGO {
T_DES = 0x00,
T_3DES = 0x01,
T_3K3DES = 0x02,
T_AES = 0x03
};
#define DESFIRE_KEY(key) ((struct desfire_key *) key)
struct desfire_key {
enum DESFIRE_CRYPTOALGO type;
uint8_t data[24];
uint8_t cmac_sk1[24];
uint8_t cmac_sk2[24];
uint8_t aes_version;
};
typedef struct desfire_key *desfirekey_t;
#define DESFIRE(tag) ((struct desfire_tag *) tag)
struct desfire_tag {
iso14a_card_select_t info;
int active;
uint8_t last_picc_error;
uint8_t last_internal_error;
uint8_t last_pcd_error;
desfirekey_t session_key;
enum DESFIRE_AUTH_SCHEME authentication_scheme;
uint8_t authenticated_key_no;
uint8_t ivect[MAX_CRYPTO_BLOCK_SIZE];
uint8_t cmac[16];
uint8_t *crypto_buffer;
size_t crypto_buffer_size;
uint32_t selected_application;
};
typedef struct desfire_tag *desfiretag_t;
/* File types */
enum DESFIRE_FILE_TYPES {
MDFT_STANDARD_DATA_FILE = 0x00,
MDFT_BACKUP_DATA_FILE = 0x01,
MDFT_VALUE_FILE_WITH_BACKUP = 0x02,
MDFT_LINEAR_RECORD_FILE_WITH_BACKUP = 0x03,
MDFT_CYCLIC_RECORD_FILE_WITH_BACKUP = 0x04
};
enum DESFIRE_STATUS {
OPERATION_OK = 0x00,
NO_CHANGES = 0x0c,
OUT_OF_EEPROM_ERROR = 0x0e,
ILLEGAL_COMMAND_CODE = 0x1c,
INTEGRITY_ERROR = 0x1e,
NO_SUCH_KEY = 0x40,
LENGTH_ERROR = 0x7e,
PERMISSION_DENIED = 0x9d,
PARAMETER_ERROR = 0x9e,
APPLICATION_NOT_FOUND = 0xa0,
APPL_INTEGRITY_ERROR = 0xa1,
AUTHENTICATION_ERROR = 0xae,
ADDITIONAL_FRAME = 0xaf,
BOUNDARY_ERROR = 0xbe,
PICC_INTEGRITY_ERROR = 0xc1,
COMMAND_ABORTED = 0xca,
PICC_DISABLED_ERROR = 0xcd,
COUNT_ERROR = 0xce,
DUPLICATE_ERROR = 0xde,
EEPROM_ERROR = 0xee,
FILE_NOT_FOUND = 0xf0,
FILE_INTEGRITY_ERROR = 0xf1
};
enum DESFIRE_CMD {
CREATE_APPLICATION = 0xca,
DELETE_APPLICATION = 0xda,
GET_APPLICATION_IDS = 0x6a,
SELECT_APPLICATION = 0x5a,
FORMAT_PICC = 0xfc,
GET_VERSION = 0x60,
READ_DATA = 0xbd,
WRITE_DATA = 0x3d,
GET_VALUE = 0x6c,
CREDIT = 0x0c,
DEBIT = 0xdc,
LIMITED_CREDIT = 0x1c,
WRITE_RECORD = 0x3b,
READ_RECORDS = 0xbb,
CLEAR_RECORD_FILE = 0xeb,
COMMIT_TRANSACTION = 0xc7,
ABORT_TRANSACTION = 0xa7,
GET_FREE_MEMORY = 0x6e,
GET_FILE_IDS = 0x6f,
GET_FILE_SETTINGS = 0xf5,
CHANGE_FILE_SETTINGS = 0x5f,
CREATE_STD_DATA_FILE = 0xcd,
CREATE_BACKUP_DATA_FILE = 0xcb,
CREATE_VALUE_FILE = 0xcc,
CREATE_LINEAR_RECORD_FILE = 0xc1,
CREATE_CYCLIC_RECORD_FILE = 0xc0,
DELETE_FILE = 0xdf,
AUTHENTICATE = 0x0a, // AUTHENTICATE_NATIVE
AUTHENTICATE_ISO = 0x1a, // AUTHENTICATE_STANDARD
AUTHENTICATE_AES = 0xaa,
CHANGE_KEY_SETTINGS = 0x54,
GET_KEY_SETTINGS = 0x45,
CHANGE_KEY = 0xc4,
GET_KEY_VERSION = 0x64,
AUTHENTICATION_FRAME = 0xAF
};
#endif

View file

@ -1,249 +0,0 @@
//-----------------------------------------------------------------------------
// Peter Fillmore 2014
// code derived off merloks mifare code
//
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// structure to hold EMV card and terminal parameters
//-----------------------------------------------------------------------------
#ifndef __EMVCARD_H
#define __EMVCARD_H
#include <stdint.h>
#include <stddef.h>
//structure to hold received/set tag values
//variable data inputs have length specifiers
typedef struct {
//ISO14443-A card stuff
uint8_t ATQA[2]; //Answer to Request
uint8_t UID_len;
uint8_t UID[10];
uint8_t SAK1; //SAK for UID 1
uint8_t SAK2; //SAK for UID 2
uint8_t ATS_len; //Answer to select
uint8_t ATS[256];
//ATS
uint8_t TL;
uint8_t T0;
uint8_t TA1;
uint8_t TB1;
uint8_t TC1;
uint8_t *historicalbytes;
//PPS response
uint8_t PPSS;
//SFI 2 record 1
uint8_t tag_4F_len; //length of AID
uint8_t tag_4F[16]; //Application Identifier (AID)
uint8_t tag_50_len; //length of application label
uint8_t tag_50[16]; //Application Label
uint8_t tag_56_len; //track1 length
uint8_t tag_56[76]; //Track 1 Data
uint8_t tag_57_len; //track2 equiv len
uint8_t tag_57[19]; //Track 2 Equivalent Data
uint8_t tag_5A_len; //PAN length
uint8_t tag_5A[10]; //Application Primary Account Number (PAN)
//uint8_t tag_6F[]; //File Control Information (FCI) Template
//uint8_t tag_70[255]; //Record Template
//uint8_t tag_77[]; //Response Message Template Format 2
//uint8_t tag_80[]; //Response Message Template Format 1
uint8_t tag_82[2]; //Application Interchange Profile AIP
//uint8_t tag_83[]; //Command Template
uint8_t tag_84_len;
uint8_t tag_84[16]; //DF Name
uint8_t tag_86_len;
uint8_t tag_86[261]; //Issuer Script Command
uint8_t tag_87[1]; //Application Priority Indicator
uint8_t tag_88[1]; //Short File Identifier
uint8_t tag_8A[2]; //Authorisation Response Code
uint8_t tag_8C_len;
uint8_t tag_8C[252]; //CDOL1
uint8_t tag_8D_len;
uint8_t tag_8D[252]; //CDOL2
uint8_t tag_8E_len;
uint8_t tag_8E[252]; //Cardholder Verification Method (CVM) List
uint8_t tag_8F[1]; //Certification Authority Public Key Index
uint8_t tag_90_len;
uint8_t tag_90[255]; //ssuer Public Key Certificate
uint8_t tag_92_len;
uint8_t tag_92[255]; //Issuer Public Key Remainder
uint8_t tag_93_len;
uint8_t tag_93[255]; //Signed Static Application Data
uint8_t tag_94_len;
uint8_t tag_94[252]; //Application File Locator AFL
uint8_t tag_95[5]; //Terminal Verification Results
uint8_t tag_97_len;
uint8_t tag_97[252]; //Transaction Certificate Data Object List (TDOL)
uint8_t tag_98[20]; //Transaction Certificate (TC) Hash Value
//assume 20 bytes, change after testing
uint8_t tag_99_len;
uint8_t tag_99[20]; //Transaction Personal Identification Number (PIN) Data
uint8_t tag_9A[3]; //Transaction Date
uint8_t tag_9B[2]; //Transaction Status Information
uint8_t tag_9C[1]; //Transaction Type
uint8_t tag_9D_len;
uint8_t tag_9D[16]; //Directory Definition File
uint8_t tag_CD[3]; //Card Issuer Action Codes Paypass
uint8_t tag_CE[3];
uint8_t tag_CF[3];
uint8_t tag_D7[3]; //Application Control (PayPass)
uint8_t tag_D8[2]; //Application Interchange Profile (PayPass)
uint8_t tag_D9_len; //Application File Locator (PayPass)
uint8_t tag_D9[16];
uint8_t tag_DA[2]; //Static CVC3track1
uint8_t tag_DB[2]; //Static CVC3track2
uint8_t tag_DC[2]; //IVCVC3 CVC3track1
uint8_t tag_DD[2]; //IVCVC3 CVC3track2
uint8_t tag_AF_len;
uint8_t tag_AF[255]; //Proprietary Information
uint8_t tag_5F20_len;
uint8_t tag_5F20[26]; //Cardholder Name
uint8_t tag_5F24[3]; //Application Expiry Date
uint8_t tag_5F25[3]; //Application Effective Date YYMMDD
uint8_t tag_5F28[2]; //Issuer Country Code
uint8_t tag_5F2A[2]; //Transaction Currency Code
uint8_t tag_5F2D_len;
uint8_t tag_5F2D[8]; //Language Preference
uint8_t tag_5F30[2]; //Service Code
uint8_t tag_5F34[1]; //Application Primary Account Number (PAN) Sequence Number
uint8_t tag_5F36[2]; //ATC
uint8_t tag_5F50_len;
uint8_t tag_5F50[255]; //Issuer URL
uint8_t tag_5F54_len;
uint8_t tag_5F54[11]; //Bank Identifier Code (BIC)
uint8_t tag_9F01[6]; //Acquirer Identifier
uint8_t tag_9F02[6]; // Amount, Authorised (Numeric)
uint8_t tag_9F03[6]; //Amount, Other (Numeric)
uint8_t tag_9F04[4]; //Amount, Other (Binary)
uint8_t tag_9F05_len;
uint8_t tag_9F05[32]; //Application Discretionary Data
uint8_t tag_9F06_len;
uint8_t tag_9F06[16]; //AID terminal
uint8_t tag_9F07[2]; //Application Usage Control
uint8_t tag_9F08[2]; //Application Version Number
uint8_t tag_9F09[2]; //Application Version Number
//uint8_t tag_9F0A[2]
uint8_t tag_9F0B_len;
uint8_t tag_9F0B[45]; //Cardholder Name Extended
uint8_t tag_9F0D[5]; //Issuer Action Code - Default
uint8_t tag_9F0E[5]; //Issuer Action Code - Denial
uint8_t tag_9F0F[5]; //Issuer Action Code - Online
uint8_t tag_9F10_len; //Issuer Application Data
uint8_t tag_9F10[32];
uint8_t tag_9F11[1]; //Issuer Code Table Index
uint8_t tag_9F12_len;
uint8_t tag_9F12[255]; //Application Preferred Name
uint8_t tag_9F13[2]; //Last Online Application Transaction Counter (ATC) Registerjk
uint8_t tag_9F14[1]; //Lower Consecutive Offline Limit
uint8_t tag_9F15[2]; //Merchant Category Code
uint8_t tag_9F16[15]; //Merchant Identifier
uint8_t tag_9F17[1]; //Personal Identification Number (PIN) Try Counter
uint8_t tag_9F18[4]; //Issuer Script Identifier
//uint8_t tag_9F19[]
uint8_t tag_9F1A[2]; //Terminal Country Code
uint8_t tag_9F1B[4]; //Terminal Floor Limit
uint8_t tag_9F1C[8]; //Terminal Identification
uint8_t tag_9F1D_len;
uint8_t tag_9F1D[8]; //Terminal Risk Management Data
uint8_t tag_9F1E[8]; //Interface Device (IFD) Serial Number
uint8_t tag_9F1F_len;
uint8_t tag_9F1F[255]; //Track 1 Discretionary Data
uint8_t tag_9F20_len;
uint8_t tag_9F20[255]; //Track 2 DD
uint8_t tag_9F21[3]; //Transaction Time
uint8_t tag_9F22[1]; //Certification Authority Public Key Index
uint8_t tag_9F23[1]; //Upper Consecutive Offline Limit
//uint8_t tag_9F24
//uint8_t tag_9F25
uint8_t tag_9F26[8]; //Application Cryptogram
uint8_t tag_9F27[1]; //Cryptogram Information Data
//uint8_t tag_9F28
//uint8_t tag_9F29
//uint8_t tag_9F2A
//uint8_t tag_9F2B
//uint8_t tag_9F2C
uint8_t tag_9F2D_len;
uint8_t tag_9F2D[255]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Certificate
uint8_t tag_9F2E[3]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Exponent
uint8_t tag_9F2F_len;
uint8_t tag_9F2F[255]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Remainder
//uint8_t tag_9F30
//uint8_t tag_9F31
uint8_t tag_9F32_len;
uint8_t tag_9F32[3]; //Issuer Public Key Exponent
uint8_t tag_9F33[3]; //Terminal Capabilities
uint8_t tag_9F34[3]; //Cardholder Verification Method (CVM) Results
uint8_t tag_9F35[1]; //Terminal Type
uint8_t tag_9F36[2]; //Application Transaction Counter (ATC)
uint8_t tag_9F37[8]; //Unpredictable Number
uint8_t tag_9F38_len;
uint8_t tag_9F38[255]; //PDOL
uint8_t tag_9F39[1]; //Point-of-Service (POS) Entry Mode
uint8_t tag_9F40[5]; //Additional Terminal Capabilities
uint8_t tag_9F41[4]; //Transaction Sequence Counter
uint8_t tag_9F42[2]; //Application Currency Code
uint8_t tag_9F43[4]; //Application Reference Currency Exponent
uint8_t tag_9F44[1]; //Application Currency Exponent
uint8_t tag_9F45[2]; //Data Authentication Code
uint8_t tag_9F46_len;
uint8_t tag_9F46[255]; //ICC Public Key Certificate
uint8_t tag_9F47_len;
uint8_t tag_9F47[3]; //ICC Public Key Exponent
uint8_t tag_9F48_len;
uint8_t tag_9F48[255]; //ICC Public Key Remainder
uint8_t tag_9F49_len;
uint8_t tag_9F49[252];
uint8_t tag_9F4A[1]; //SDA Tag list
uint8_t tag_9F4B_len;
uint8_t tag_9F4B[255]; //Signed Dynamic Application Data
uint8_t tag_9F4C[8]; //ICC Dynamic Number
uint8_t tag_9F4D[2]; //Log Entry
uint8_t tag_9F4E[255]; //Merchant Name and Location
//9F50-9F7F are payment system specific
uint8_t tag_9F60[2]; //CVC3 track1
uint8_t tag_9F61[2]; //CVC3 track2
uint8_t tag_9F62[6]; //Track 1 Bit Map for CVC3 (PCVC3TRACK1)
uint8_t tag_9F63[6]; //Track 1 Bit Map for UN and ATC (PUNATCTRACK1)
uint8_t tag_9F64[1]; //Track 1 Number of ATC Digits (NATCTRACK1)
uint8_t tag_9F65[2]; //rack 2 Bit Map for CVC3 (PCVC3TRACK2)
uint8_t tag_9F66[4]; //Track 2 Bit Map for UN and ATC (PUNATCTRACK2), or VISA card type
uint8_t tag_9F67[1]; //Track 2 Number of ATC Digits (NATCTRACK2)
uint8_t tag_9F68_len;
uint8_t tag_9F68[252]; //Mag Stripe CVM List
uint8_t tag_9F69_len;
uint8_t tag_9F69[255]; //Unpredictable Number Data Object List (UDOL)
uint8_t tag_9F6A[8]; //Unpredictable Number (Numeric)
uint8_t tag_9F6B_len;
uint8_t tag_9F6B[19]; //track 2 data
uint8_t tag_9F6C[2]; //Mag Stripe Application Version Number(Card)
//template holders
uint8_t tag_61_len;
uint8_t tag_61[255]; //Application template
uint8_t tag_6F_len;
uint8_t tag_6F[255]; //6F template
uint8_t tag_A5_len;
uint8_t tag_A5[255]; //A5 template
uint8_t tag_DFNAME_len;
uint8_t tag_DFNAME[255]; //A5 template
uint8_t tag_70_len;
uint8_t tag_70[255]; //70 template
uint8_t tag_77_len;
uint8_t tag_77[255]; //77 template
uint8_t tag_80_len;
uint8_t tag_80[255]; //80 template
uint8_t tag_91_len; //Issuer Authentication Data
uint8_t tag_91[16];
uint8_t tag_BF0C_len;
uint8_t tag_BF0C[222]; //File Control Information (FCI) Issuer Discretionary Data
uint8_t tag_DFName[16];
uint8_t tag_DFName_len;
} emvtags;
#endif //__EMVCARD_H

View file

@ -7,6 +7,8 @@
#ifndef __FPGA_H
#define __FPGA_H
#include "common.h"
#define FPGA_BITSTREAM_FIXED_HEADER_SIZE sizeof(bitparse_fixed_header)
#define FPGA_INTERLEAVE_SIZE 288
#define FPGA_CONFIG_SIZE 42336L // our current fpga_[lh]f.bit files are 42175 bytes. Rounded up to next multiple of FPGA_INTERLEAVE_SIZE

View file

@ -1,834 +0,0 @@
//-----------------------------------------------------------------------------
// Willok, June 2018
// Edits by Iceman, July 2018
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// The main i2c code, for communications with smart card module
//-----------------------------------------------------------------------------
#include "i2c.h"
#define GPIO_RST AT91C_PIO_PA1
#define GPIO_SCL AT91C_PIO_PA5
#define GPIO_SDA AT91C_PIO_PA7
#define SCL_H HIGH(GPIO_SCL)
#define SCL_L LOW(GPIO_SCL)
#define SDA_H HIGH(GPIO_SDA)
#define SDA_L LOW(GPIO_SDA)
#define SCL_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SCL)
#define SDA_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SDA)
#define I2C_ERROR "I2C_WaitAck Error"
volatile unsigned long c;
// Direct use the loop to delay. 6 instructions loop, Masterclock 48MHz,
// delay=1 is about 200kbps
// timer.
// I2CSpinDelayClk(4) = 12.31us
// I2CSpinDelayClk(1) = 3.07us
void __attribute__((optimize("O0"))) I2CSpinDelayClk(uint16_t delay) {
for (c = delay * 2; c; c--) {};
}
#define I2C_DELAY_1CLK I2CSpinDelayClk(1)
#define I2C_DELAY_2CLK I2CSpinDelayClk(2)
#define I2C_DELAY_XCLK(x) I2CSpinDelayClk((x))
#define ISO7618_MAX_FRAME 255
// try i2c bus recovery at 100kHz = 5us high, 5us low
void I2C_recovery(void) {
DbpString("Performing i2c bus recovery");
// reset I2C
SDA_H;
SCL_H;
//9nth cycle acts as NACK
for (int i = 0; i < 10; i++) {
SCL_H;
WaitUS(5);
SCL_L;
WaitUS(5);
}
//a STOP signal (SDA from low to high while CLK is high)
SDA_L;
WaitUS(5);
SCL_H;
WaitUS(2);
SDA_H;
WaitUS(2);
bool isok = (SCL_read && SDA_read);
if (!SDA_read)
DbpString("I2C bus recovery error: SDA still LOW");
if (!SCL_read)
DbpString("I2C bus recovery error: SCL still LOW");
if (isok)
DbpString("I2C bus recovery complete");
}
void I2C_init(void) {
// Configure reset pin, close up pull up, push-pull output, default high
AT91C_BASE_PIOA->PIO_PPUDR = GPIO_RST;
AT91C_BASE_PIOA->PIO_MDDR = GPIO_RST;
// Configure I2C pin, open up, open leakage
AT91C_BASE_PIOA->PIO_PPUER |= (GPIO_SCL | GPIO_SDA);
AT91C_BASE_PIOA->PIO_MDER |= (GPIO_SCL | GPIO_SDA);
// default three lines all pull up
AT91C_BASE_PIOA->PIO_SODR |= (GPIO_SCL | GPIO_SDA | GPIO_RST);
AT91C_BASE_PIOA->PIO_OER |= (GPIO_SCL | GPIO_SDA | GPIO_RST);
AT91C_BASE_PIOA->PIO_PER |= (GPIO_SCL | GPIO_SDA | GPIO_RST);
bool isok = (SCL_read && SDA_read);
if (!isok)
I2C_recovery();
}
// set the reset state
void I2C_SetResetStatus(uint8_t LineRST, uint8_t LineSCK, uint8_t LineSDA) {
if (LineRST)
HIGH(GPIO_RST);
else
LOW(GPIO_RST);
if (LineSCK)
HIGH(GPIO_SCL);
else
LOW(GPIO_SCL);
if (LineSDA)
HIGH(GPIO_SDA);
else
LOW(GPIO_SDA);
}
// Reset the SIM_Adapter, then enter the main program
// Note: the SIM_Adapter will not enter the main program after power up. Please run this function before use SIM_Adapter.
void I2C_Reset_EnterMainProgram(void) {
StartTicks();
I2C_init();
I2C_SetResetStatus(0, 0, 0);
WaitMS(30);
I2C_SetResetStatus(1, 0, 0);
WaitMS(30);
I2C_SetResetStatus(1, 1, 1);
WaitMS(10);
}
// Reset the SIM_Adapter, then enter the bootloader program
// Reserve for firmware update.
void I2C_Reset_EnterBootloader(void) {
StartTicks();
I2C_init();
I2C_SetResetStatus(0, 1, 1);
WaitMS(100);
I2C_SetResetStatus(1, 1, 1);
WaitMS(10);
}
// Wait for the clock to go High.
bool WaitSCL_H_delay(uint32_t delay) {
while (delay--) {
if (SCL_read) {
return true;
}
I2C_DELAY_1CLK;
}
return false;
}
// 5000 * 3.07us = 15350us. 15.35ms
// 15000 * 3.07us = 46050us. 46.05ms
bool WaitSCL_H(void) {
return WaitSCL_H_delay(15000);
}
bool WaitSCL_L_delay(uint32_t delay) {
while (delay--) {
if (!SCL_read) {
return true;
}
I2C_DELAY_1CLK;
}
return false;
}
// 5000 * 3.07us = 15350us. 15.35ms
bool WaitSCL_L(void) {
return WaitSCL_L_delay(15000);
}
// Wait max 1800ms or until SCL goes LOW.
// It timeout reading response from card
// Which ever comes first
bool WaitSCL_L_timeout(void) {
volatile uint16_t delay = 1800;
while (delay--) {
// exit on SCL LOW
if (!SCL_read)
return true;
WaitMS(1);
}
return (delay == 0);
}
bool I2C_Start(void) {
I2C_DELAY_XCLK(4);
SDA_H;
I2C_DELAY_1CLK;
SCL_H;
if (!WaitSCL_H()) return false;
I2C_DELAY_2CLK;
if (!SCL_read) return false;
if (!SDA_read) return false;
SDA_L;
I2C_DELAY_2CLK;
return true;
}
bool I2C_WaitForSim() {
// wait for data from card
if (!WaitSCL_L_timeout())
return false;
// 8051 speaks with smart card.
// 1000*50*3.07 = 153.5ms
// 1byte transfer == 1ms with max frame being 256bytes
if (!WaitSCL_H_delay(10 * 1000 * 50))
return false;
return true;
}
// send i2c STOP
void I2C_Stop(void) {
SCL_L;
I2C_DELAY_2CLK;
SDA_L;
I2C_DELAY_2CLK;
SCL_H;
I2C_DELAY_2CLK;
if (!WaitSCL_H()) return;
SDA_H;
I2C_DELAY_XCLK(8);
}
// Send i2c ACK
void I2C_Ack(void) {
SCL_L;
I2C_DELAY_2CLK;
SDA_L;
I2C_DELAY_2CLK;
SCL_H;
I2C_DELAY_2CLK;
if (!WaitSCL_H()) return;
SCL_L;
I2C_DELAY_2CLK;
}
// Send i2c NACK
void I2C_NoAck(void) {
SCL_L;
I2C_DELAY_2CLK;
SDA_H;
I2C_DELAY_2CLK;
SCL_H;
I2C_DELAY_2CLK;
if (!WaitSCL_H()) return;
SCL_L;
I2C_DELAY_2CLK;
}
bool I2C_WaitAck(void) {
SCL_L;
I2C_DELAY_1CLK;
SDA_H;
I2C_DELAY_1CLK;
SCL_H;
if (!WaitSCL_H())
return false;
I2C_DELAY_2CLK;
I2C_DELAY_2CLK;
if (SDA_read) {
SCL_L;
return false;
}
SCL_L;
return true;
}
void I2C_SendByte(uint8_t data) {
uint8_t bits = 8;
while (bits--) {
SCL_L;
I2C_DELAY_1CLK;
if (data & 0x80)
SDA_H;
else
SDA_L;
data <<= 1;
I2C_DELAY_1CLK;
SCL_H;
if (!WaitSCL_H())
return;
I2C_DELAY_2CLK;
}
SCL_L;
}
int16_t I2C_ReadByte(void) {
uint8_t bits = 8, b = 0;
SDA_H;
while (bits--) {
b <<= 1;
SCL_L;
if (!WaitSCL_L()) return -2;
I2C_DELAY_1CLK;
SCL_H;
if (!WaitSCL_H()) return -1;
I2C_DELAY_1CLK;
if (SDA_read)
b |= 0x01;
}
SCL_L;
return b;
}
// Sends one byte ( command to be written, SlaveDevice address)
bool I2C_WriteCmd(uint8_t device_cmd, uint8_t device_address) {
bool bBreak = true;
do {
if (!I2C_Start())
return false;
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(device_cmd);
if (!I2C_WaitAck())
break;
bBreak = false;
} while (false);
I2C_Stop();
if (bBreak) {
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return false;
}
return true;
}
// Sends 1 byte data (Data to be written, command to be written , SlaveDevice address ).
bool I2C_WriteByte(uint8_t data, uint8_t device_cmd, uint8_t device_address) {
bool bBreak = true;
do {
if (!I2C_Start())
return false;
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(device_cmd);
if (!I2C_WaitAck())
break;
I2C_SendByte(data);
if (!I2C_WaitAck())
break;
bBreak = false;
} while (false);
I2C_Stop();
if (bBreak) {
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return false;
}
return true;
}
//Sends array of data (Array, length, command to be written , SlaveDevice address ).
// len = uint8 (max buffer to write 256bytes)
bool I2C_BufferWrite(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t device_address) {
bool bBreak = true;
do {
if (!I2C_Start())
return false;
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(device_cmd);
if (!I2C_WaitAck())
break;
while (len) {
I2C_SendByte(*data);
if (!I2C_WaitAck())
break;
len--;
data++;
}
if (len == 0)
bBreak = false;
} while (false);
I2C_Stop();
if (bBreak) {
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return false;
}
return true;
}
// read one array of data (Data array, Readout length, command to be written , SlaveDevice address ).
// len = uint8 (max buffer to read 256bytes)
int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t device_address) {
if (!data || len == 0)
return 0;
// extra wait 500us (514us measured)
// 200us (xx measured)
WaitUS(600);
bool bBreak = true;
uint16_t readcount = 0;
do {
if (!I2C_Start())
return 0;
// 0xB0 / 0xC0 == i2c write
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(device_cmd);
if (!I2C_WaitAck())
break;
// 0xB1 / 0xC1 == i2c read
I2C_Start();
I2C_SendByte(device_address | 1);
if (!I2C_WaitAck())
break;
bBreak = false;
} while (false);
if (bBreak) {
I2C_Stop();
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return 0;
}
while (len) {
int16_t tmp = I2C_ReadByte();
if (tmp < 0)
return tmp;
*data = (uint8_t)tmp & 0xFF;
len--;
// 读取的第一个字节为后续长度
// The first byte in response is the message length
if (!readcount && (len > *data)) {
len = *data;
} else {
data++;
}
readcount++;
// acknowledgements. After last byte send NACK.
if (len == 0)
I2C_NoAck();
else
I2C_Ack();
}
I2C_Stop();
// return bytecount - first byte (which is length byte)
return --readcount;
}
int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address) {
//START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP
bool bBreak = true;
uint8_t readcount = 0;
// sending
do {
if (!I2C_Start())
return 0;
// 0xB0 / 0xC0 i2c write
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(msb);
if (!I2C_WaitAck())
break;
I2C_SendByte(lsb);
if (!I2C_WaitAck())
break;
// 0xB1 / 0xC1 i2c read
I2C_Start();
I2C_SendByte(device_address | 1);
if (!I2C_WaitAck())
break;
bBreak = false;
} while (false);
if (bBreak) {
I2C_Stop();
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return 0;
}
// reading
while (len) {
int16_t tmp = I2C_ReadByte();
if (tmp < 0)
return tmp;
*data = (uint8_t)tmp & 0xFF;
data++;
readcount++;
len--;
// acknowledgements. After last byte send NACK.
if (len == 0)
I2C_NoAck();
else
I2C_Ack();
}
I2C_Stop();
return readcount;
}
bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address) {
//START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP
bool bBreak = true;
do {
if (!I2C_Start())
return false;
// 0xB0 == i2c write
I2C_SendByte(device_address & 0xFE);
if (!I2C_WaitAck())
break;
I2C_SendByte(msb);
if (!I2C_WaitAck())
break;
I2C_SendByte(lsb);
if (!I2C_WaitAck())
break;
while (len) {
I2C_SendByte(*data);
if (!I2C_WaitAck())
break;
len--;
data++;
}
if (len == 0)
bBreak = false;
} while (false);
I2C_Stop();
if (bBreak) {
if (DBGLEVEL > 3) DbpString(I2C_ERROR);
return false;
}
return true;
}
void I2C_print_status(void) {
DbpString(_BLUE_("Smart card module (ISO 7816)"));
uint8_t maj, min;
if (I2C_get_version(&maj, &min) == PM3_SUCCESS)
Dbprintf(" version................." _YELLOW_("v%x.%02d"), maj, min);
else
DbpString(" version................." _RED_("FAILED"));
}
int I2C_get_version(uint8_t *maj, uint8_t *min) {
uint8_t resp[] = {0, 0, 0, 0};
I2C_Reset_EnterMainProgram();
uint8_t len = I2C_BufferRead(resp, sizeof(resp), I2C_DEVICE_CMD_GETVERSION, I2C_DEVICE_ADDRESS_MAIN);
if (len > 0) {
*maj = resp[0];
*min = resp[1];
return PM3_SUCCESS;
} else {
return PM3_EDEVNOTSUPP;
}
}
// Will read response from smart card module, retries 3 times to get the data.
bool sc_rx_bytes(uint8_t *dest, uint8_t *destlen) {
uint8_t i = 3;
int16_t len = 0;
while (i--) {
I2C_WaitForSim();
len = I2C_BufferRead(dest, *destlen, I2C_DEVICE_CMD_READ, I2C_DEVICE_ADDRESS_MAIN);
if (len > 1) {
break;
} else if (len == 1) {
continue;
} else if (len <= 0) {
return false;
}
}
// after three
if (len <= 1)
return false;
*destlen = (uint8_t)len & 0xFF;
return true;
}
bool GetATR(smart_card_atr_t *card_ptr) {
if (!card_ptr)
return false;
card_ptr->atr_len = 0;
memset(card_ptr->atr, 0, sizeof(card_ptr->atr));
// Send ATR
// start [C0 01] stop start C1 len aa bb cc stop]
I2C_WriteCmd(I2C_DEVICE_CMD_GENERATE_ATR, I2C_DEVICE_ADDRESS_MAIN);
//wait for sim card to answer.
// 1byte = 1ms , max frame 256bytes. SHould wait 256ms atleast just in case.
if (!I2C_WaitForSim())
return false;
// read bytes from module
uint8_t len = sizeof(card_ptr->atr);
if (!sc_rx_bytes(card_ptr->atr, &len))
return false;
uint8_t pos_td = 1;
if ((card_ptr->atr[1] & 0x10) == 0x10) pos_td++;
if ((card_ptr->atr[1] & 0x20) == 0x20) pos_td++;
if ((card_ptr->atr[1] & 0x40) == 0x40) pos_td++;
// T0 indicate presence T=0 vs T=1. T=1 has checksum TCK
if ((card_ptr->atr[1] & 0x80) == 0x80) {
pos_td++;
// 1 == T1 , presence of checksum TCK
if ((card_ptr->atr[pos_td] & 0x01) == 0x01) {
uint8_t chksum = 0;
// xor property. will be zero when xored with chksum.
for (uint8_t i = 1; i < len; ++i)
chksum ^= card_ptr->atr[i];
if (chksum) {
if (DBGLEVEL > 2) DbpString("Wrong ATR checksum");
}
}
}
card_ptr->atr_len = len;
LogTrace(card_ptr->atr, card_ptr->atr_len, 0, 0, NULL, false);
return true;
}
void SmartCardAtr(void) {
smart_card_atr_t card;
LED_D_ON();
clear_trace();
set_tracing(true);
I2C_Reset_EnterMainProgram();
bool isOK = GetATR(&card);
reply_old(CMD_ACK, isOK, sizeof(smart_card_atr_t), 0, &card, sizeof(smart_card_atr_t));
set_tracing(false);
LEDsoff();
}
void SmartCardRaw(uint64_t arg0, uint64_t arg1, uint8_t *data) {
LED_D_ON();
uint8_t len = 0;
uint8_t *resp = BigBuf_malloc(ISO7618_MAX_FRAME);
smartcard_command_t flags = arg0;
if ((flags & SC_CONNECT))
clear_trace();
set_tracing(true);
if ((flags & SC_CONNECT)) {
I2C_Reset_EnterMainProgram();
if ((flags & SC_SELECT)) {
smart_card_atr_t card;
bool gotATR = GetATR(&card);
//reply_old(CMD_ACK, gotATR, sizeof(smart_card_atr_t), 0, &card, sizeof(smart_card_atr_t));
if (!gotATR)
goto OUT;
}
}
if ((flags & SC_RAW) || (flags & SC_RAW_T0)) {
LogTrace(data, arg1, 0, 0, NULL, true);
// Send raw bytes
// asBytes = A0 A4 00 00 02
// arg1 = len 5
bool res = I2C_BufferWrite(data, arg1, ((flags & SC_RAW_T0) ? I2C_DEVICE_CMD_SEND_T0 : I2C_DEVICE_CMD_SEND), I2C_DEVICE_ADDRESS_MAIN);
if (!res && DBGLEVEL > 3) DbpString(I2C_ERROR);
// read bytes from module
len = ISO7618_MAX_FRAME;
res = sc_rx_bytes(resp, &len);
if (res) {
LogTrace(resp, len, 0, 0, NULL, false);
} else {
len = 0;
}
}
OUT:
reply_old(CMD_ACK, len, 0, 0, resp, len);
BigBuf_free();
set_tracing(false);
LEDsoff();
}
void SmartCardUpgrade(uint64_t arg0) {
LED_C_ON();
#define I2C_BLOCK_SIZE 128
// write. Sector0, with 11,22,33,44
// erase is 128bytes, and takes 50ms to execute
I2C_Reset_EnterBootloader();
bool isOK = true;
uint16_t length = arg0, pos = 0;
uint8_t *fwdata = BigBuf_get_addr();
uint8_t *verfiydata = BigBuf_malloc(I2C_BLOCK_SIZE);
while (length) {
uint8_t msb = (pos >> 8) & 0xFF;
uint8_t lsb = pos & 0xFF;
Dbprintf("FW %02X%02X", msb, lsb);
size_t size = MIN(I2C_BLOCK_SIZE, length);
// write
int16_t res = I2C_WriteFW(fwdata + pos, size, msb, lsb, I2C_DEVICE_ADDRESS_BOOT);
if (!res) {
DbpString("Writing failed");
isOK = false;
break;
}
// writing takes time.
WaitMS(50);
// read
res = I2C_ReadFW(verfiydata, size, msb, lsb, I2C_DEVICE_ADDRESS_BOOT);
if (res <= 0) {
DbpString("Reading back failed");
isOK = false;
break;
}
// cmp
if (0 != memcmp(fwdata + pos, verfiydata, size)) {
DbpString("not equal data");
isOK = false;
break;
}
length -= size;
pos += size;
}
reply_mix(CMD_ACK, isOK, pos, 0, 0, 0);
LED_C_OFF();
BigBuf_free();
}
void SmartCardSetBaud(uint64_t arg0) {
}
void SmartCardSetClock(uint64_t arg0) {
LED_D_ON();
set_tracing(true);
I2C_Reset_EnterMainProgram();
// Send SIM CLC
// start [C0 05 xx] stop
I2C_WriteByte(arg0, I2C_DEVICE_CMD_SIM_CLC, I2C_DEVICE_ADDRESS_MAIN);
reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
set_tracing(false);
LEDsoff();
}

View file

@ -1,51 +0,0 @@
#ifndef __I2C_H
#define __I2C_H
#include <stddef.h>
#include "proxmark3.h"
#include "apps.h"
#include "BigBuf.h"
#include "mifare.h"
#define I2C_DEVICE_ADDRESS_BOOT 0xB0
#define I2C_DEVICE_ADDRESS_MAIN 0xC0
#define I2C_DEVICE_CMD_GENERATE_ATR 0x01
#define I2C_DEVICE_CMD_SEND 0x02
#define I2C_DEVICE_CMD_READ 0x03
#define I2C_DEVICE_CMD_SETBAUD 0x04
#define I2C_DEVICE_CMD_SIM_CLC 0x05
#define I2C_DEVICE_CMD_GETVERSION 0x06
#define I2C_DEVICE_CMD_SEND_T0 0x07
void I2C_recovery(void);
void I2C_init(void);
void I2C_Reset(void);
void I2C_SetResetStatus(uint8_t LineRST, uint8_t LineSCK, uint8_t LineSDA);
void I2C_Reset_EnterMainProgram(void);
void I2C_Reset_EnterBootloader(void);
bool I2C_WriteCmd(uint8_t device_cmd, uint8_t device_address);
bool I2C_WriteByte(uint8_t data, uint8_t device_cmd, uint8_t device_address);
bool I2C_BufferWrite(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t device_address);
int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t device_address);
// for firmware
int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address);
bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address);
//
bool GetATR(smart_card_atr_t *card_ptr);
// generice functions
void SmartCardAtr(void);
void SmartCardRaw(uint64_t arg0, uint64_t arg1, uint8_t *data);
void SmartCardUpgrade(uint64_t arg0);
void SmartCardSetBaud(uint64_t arg0);
void SmartCardSetClock(uint64_t arg0);
void I2C_print_status(void);
int I2C_get_version(uint8_t *maj, uint8_t *min);
#endif

View file

@ -7,6 +7,8 @@
//-----------------------------------------------------------------------------
#include "iso15693tools.h"
#include <stdio.h>
// returns a string representation of the UID
// UID is transmitted and stored LSB first, displayed MSB first
// target char* buffer, where to put the UID, if NULL a static buffer is returned

View file

@ -11,10 +11,7 @@
#ifndef ISO15693_H__
#define ISO15693_H__
#include "proxmark3.h"
#include <stdint.h>
#include <stdlib.h>
#include "crc16.h"
#include "common.h"
// REQUEST FLAGS
#define ISO15_REQ_SUBCARRIER_SINGLE 0x00 // Tag should respond using one subcarrier (ASK)
@ -70,8 +67,6 @@
#define ISO15_CMD_SYSINFO 0x2B
#define ISO15_CMD_SECSTATUS 0x2C
char *Iso15693sprintUID(char *target, uint8_t *uid);
//-----------------------------------------------------------------------------
// Map a sequence of octets (~layer 2 command) into the set of bits to feed
// to the FPGA, to transmit that command to the tag.
@ -123,4 +118,6 @@ static const int Iso15693FrameEOF[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
char *Iso15693sprintUID(char *target, uint8_t *uid);
#endif

View file

@ -1,32 +0,0 @@
/*
-----------------------------------------------------------------------------
This code is licensed to you under the ter
ms of the GNU GPL, version 2 or,
at your option, any later version. See the LICENSE.txt file for the text of
the license.
-----------------------------------------------------------------------------
Common linker script
-----------------------------------------------------------------------------
*/
/* AT91SAM7S256 has 256k Flash and 64k RAM */
/* AT91SAM7S512 has 512k Flash and 64k RAM */
/* boot space = 8192bytes (0x2000) */
/* osimage space = (512k - 0x2000 == 524288 - 8192 == 516096bytes == 0x7E000 ) */
MEMORY
{
bootphase1 : ORIGIN = 0x00100000, LENGTH = 0x200 /* Phase 1 bootloader: Copies real bootloader to RAM */
bootphase2 : ORIGIN = 0x00100200, LENGTH = 0x2000 - 0x200 /* Main bootloader code, stored in Flash, executed from RAM */
osimage : ORIGIN = 0x00102000, LENGTH = 512K - 0x2000 /* Place where the main OS will end up */
ram : ORIGIN = 0x00200000, LENGTH = 64K - 0x20 /* RAM, minus small common area */
commonarea : ORIGIN = 0x00200000 + 64K - 0x20, LENGTH = 0x20 /* Communication between bootloader and main OS */
}
/* Export some information that can be used from within the firmware */
_bootphase1_version_pointer = ORIGIN(bootphase1) + LENGTH(bootphase1) - 0x4;
_osimage_entry = ORIGIN(osimage);
_bootrom_start = ORIGIN(bootphase1);
_bootrom_end = ORIGIN(bootphase2) + LENGTH(bootphase2);
_flash_start = ORIGIN(bootphase1);
_flash_end = ORIGIN(osimage) + LENGTH(osimage);
_stack_end = ORIGIN(ram) + LENGTH(ram) - 8;

View file

@ -3,16 +3,18 @@
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Generic TEA crypto code.
// ref: http://143.53.36.235:8080/source.htm#ansi
// LEFIC's obfuscation function
//-----------------------------------------------------------------------------
#ifndef __TEA_H
#define __TEA_H
#ifndef __LEGIC_PRNG_H
#define __LEGIC_PRNG_H
#include "common.h"
void legic_prng_init(uint8_t iv);
void legic_prng_forward(int count);
uint8_t legic_prng_get_bit(void);
uint32_t legic_prng_get_bits(uint8_t len);
#endif
#include "commonutil.h"
#include <stdint.h>
#include <stddef.h>
void tea_encrypt(uint8_t *v, uint8_t *key);
void tea_decrypt(uint8_t *v, uint8_t *key);
#endif /* __TEA_H */

View file

@ -36,12 +36,9 @@
// marshmellow
//-----------------------------------------------------------------------------
#include <string.h> // for memset, memcmp and size_t
#include "lfdemod.h"
#include <stdint.h> // for uint_32+
#include <stdbool.h> // for bool
#include <string.h> // for memset, memcmp and size_t
#include "parity.h" // for parity test
#include "commonutil.h" // colors
#include "pm3_cmd.h" // error codes
//**********************************************************************************************
//---------------------------------Utilities Section--------------------------------------------
@ -51,15 +48,12 @@
//to allow debug print calls when used not on dev
//void dummy(char *fmt, ...){}
void Dbprintf(const char *fmt, ...);
#ifndef ON_DEVICE
#include "ui.h"
# include "cmdparser.h"
# include "cmddata.h"
# define prnt(args...) PrintAndLogEx(DEBUG, ## args );
#else
# include "dbprint.h"
uint8_t g_debugMode = 0;
# define prnt Dbprintf
#endif

View file

@ -13,12 +13,8 @@
#ifndef LFDEMOD_H__
#define LFDEMOD_H__
#include <stdint.h> // for uint_32+
#include <stdbool.h> // for bool
#include <string.h> // for strcmp, memset, memcmp and size_t
#include <stdlib.h> // for
#include <stdbool.h> // for bool
#include "parity.h" // for parity test
#include "common.h"
//might not be high enough for noisy environments
#define NOISE_AMPLITUDE_THRESHOLD 8
@ -83,4 +79,5 @@ int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, u
int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx);
int detectIdteck(uint8_t *dest, size_t *size);
int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx);
#endif

View file

@ -6,7 +6,6 @@
// parity functions (all defined in parity.h)
//-----------------------------------------------------------------------------
#include <parity.h>
#include <stdint.h>
const uint8_t OddByteParity[256] = {
1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,

View file

@ -11,12 +11,7 @@
#ifndef __PARITY_H
#define __PARITY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include "common.h"
extern const uint8_t OddByteParity[256];
@ -52,8 +47,4 @@ static inline bool oddparity32(uint32_t x) {
#endif
}
#ifdef __cplusplus
}
#endif
#endif /* __PARITY_H */

View file

@ -1,39 +0,0 @@
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Burtle Prng - Modified. 42iterations instead of 20.
// ref: http://burtleburtle.net/bob/rand/smallprng.html
//-----------------------------------------------------------------------------
#include "prng.h"
#define rot(x,k) (((x)<<(k))|((x)>>(32-(k))))
uint32_t burtle_get_mod(prng_ctx *x) {
uint32_t e = x->a - rot(x->b, 21);
x->a = x->b ^ rot(x->c, 19);
x->b = x->c + rot(x->d, 6);
x->c = x->d + e;
x->d = e + x->a;
return x->d;
}
void burtle_init_mod(prng_ctx *x, uint32_t seed) {
x->a = 0xf1ea5eed;
x->b = x->c = x->d = seed;
for (uint8_t i = 0; i < 42; ++i) {
(void)burtle_get_mod(x);
}
}
void burtle_init(prng_ctx *x, uint32_t seed) {
uint32_t i;
x->a = 0xf1ea5eed, x->b = x->c = x->d = seed;
for (i = 0; i < 20; ++i) {
(void)burtle_get_mod(x);
}
}
uint32_t GetSimplePrng(uint32_t seed) {
seed *= 0x19660D;
seed += 0x3C6EF35F;
return seed;
}

View file

@ -1,24 +0,0 @@
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Burtle Prng - Modified. 42iterations instead of 20.
// ref: http://burtleburtle.net/bob/rand/smallprng.html
//-----------------------------------------------------------------------------
#ifndef __PRNG_H
#define __PRNG_H
#include <stdint.h>
#include <stddef.h>
typedef struct prng_ctx {
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
} prng_ctx;
//uint32_t burtle_get( prng_ctx *x );
uint32_t burtle_get_mod(prng_ctx *x);
void burtle_init_mod(prng_ctx *x, uint32_t seed);
void burtle_init(prng_ctx *x, uint32_t seed);
uint32_t GetSimplePrng(uint32_t seed);
#endif /* __PRNG_H */

View file

@ -1,150 +0,0 @@
#include "protocols.h"
// ATA55xx shared presets & routines
uint32_t GetT55xxClockBit(uint32_t clock) {
switch (clock) {
case 128:
return T55x7_BITRATE_RF_128;
case 100:
return T55x7_BITRATE_RF_100;
case 64:
return T55x7_BITRATE_RF_64;
case 50:
return T55x7_BITRATE_RF_50;
case 40:
return T55x7_BITRATE_RF_40;
case 32:
return T55x7_BITRATE_RF_32;
case 16:
return T55x7_BITRATE_RF_16;
case 8:
return T55x7_BITRATE_RF_8;
default :
return 0;
}
}
#ifndef ON_DEVICE
#include "ui.h"
#define PrintAndLogDevice(level, format, args...) PrintAndLogEx(level, format , ## args)
static uint8_t isset(uint8_t val, uint8_t mask) {
return (val & mask);
}
static uint8_t notset(uint8_t val, uint8_t mask) {
return !(val & mask);
}
static void fuse_config(const picopass_hdr *hdr) {
uint8_t fuses = hdr->conf.fuses;
if (isset(fuses, FUSE_FPERS))
PrintAndLogDevice(SUCCESS, "\tMode: Personalization [Programmable]");
else
PrintAndLogDevice(NORMAL, "\tMode: Application [Locked]");
if (isset(fuses, FUSE_CODING1)) {
PrintAndLogDevice(NORMAL, "\tCoding: RFU");
} else {
if (isset(fuses, FUSE_CODING0))
PrintAndLogDevice(NORMAL, "\tCoding: ISO 14443-2 B/ISO 15693");
else
PrintAndLogDevice(NORMAL, "\tCoding: ISO 14443B only");
}
// 1 1
if (isset(fuses, FUSE_CRYPT1) && isset(fuses, FUSE_CRYPT0)) PrintAndLogDevice(SUCCESS, "\tCrypt: Secured page, keys not locked");
// 1 0
if (isset(fuses, FUSE_CRYPT1) && notset(fuses, FUSE_CRYPT0)) PrintAndLogDevice(NORMAL, "\tCrypt: Secured page, keys locked");
// 0 1
if (notset(fuses, FUSE_CRYPT1) && isset(fuses, FUSE_CRYPT0)) PrintAndLogDevice(SUCCESS, "\tCrypt: Non secured page");
// 0 0
if (notset(fuses, FUSE_CRYPT1) && notset(fuses, FUSE_CRYPT0)) PrintAndLogDevice(NORMAL, "\tCrypt: No auth possible. Read only if RA is enabled");
if (isset(fuses, FUSE_RA))
PrintAndLogDevice(NORMAL, "\tRA: Read access enabled");
else
PrintAndLogDevice(WARNING, "\tRA: Read access not enabled");
}
void getMemConfig(uint8_t mem_cfg, uint8_t chip_cfg, uint8_t *max_blk, uint8_t *app_areas, uint8_t *kb) {
// mem-bit 5, mem-bit 7, chip-bit 4: defines chip type
uint8_t k16 = isset(mem_cfg, 0x80);
//uint8_t k2 = isset(mem_cfg, 0x08);
uint8_t book = isset(mem_cfg, 0x20);
if (isset(chip_cfg, 0x10) && !k16 && !book) {
*kb = 2;
*app_areas = 2;
*max_blk = 31;
} else if (isset(chip_cfg, 0x10) && k16 && !book) {
*kb = 16;
*app_areas = 2;
*max_blk = 255; //16kb
} else if (notset(chip_cfg, 0x10) && !k16 && !book) {
*kb = 16;
*app_areas = 16;
*max_blk = 255; //16kb
} else if (isset(chip_cfg, 0x10) && k16 && book) {
*kb = 32;
*app_areas = 3;
*max_blk = 255; //16kb
} else if (notset(chip_cfg, 0x10) && !k16 && book) {
*kb = 32;
*app_areas = 17;
*max_blk = 255; //16kb
} else {
*kb = 32;
*app_areas = 2;
*max_blk = 255;
}
}
static void mem_app_config(const picopass_hdr *hdr) {
uint8_t mem = hdr->conf.mem_config;
uint8_t chip = hdr->conf.chip_config;
uint8_t applimit = hdr->conf.app_limit;
uint8_t kb = 2;
uint8_t app_areas = 2;
uint8_t max_blk = 31;
getMemConfig(mem, chip, &max_blk, &app_areas, &kb);
if (applimit < 6) applimit = 26;
if (kb == 2 && (applimit > 0x1f)) applimit = 26;
PrintAndLogDevice(NORMAL, " Mem: %u KBits/%u App Areas (%u * 8 bytes) [%02X]", kb, app_areas, max_blk, mem);
PrintAndLogDevice(NORMAL, "\tAA1: blocks 06-%02X", applimit);
PrintAndLogDevice(NORMAL, "\tAA2: blocks %02X-%02X", applimit + 1, max_blk);
PrintAndLogDevice(NORMAL, "\tOTP: 0x%02X%02X", hdr->conf.otp[1], hdr->conf.otp[0]);
PrintAndLogDevice(NORMAL, "\nKeyAccess:");
uint8_t book = isset(mem, 0x20);
if (book) {
PrintAndLogDevice(NORMAL, "\tRead A - Kd");
PrintAndLogDevice(NORMAL, "\tRead B - Kc");
PrintAndLogDevice(NORMAL, "\tWrite A - Kd");
PrintAndLogDevice(NORMAL, "\tWrite B - Kc");
PrintAndLogDevice(NORMAL, "\tDebit - Kd or Kc");
PrintAndLogDevice(NORMAL, "\tCredit - Kc");
} else {
PrintAndLogDevice(NORMAL, "\tRead A - Kd or Kc");
PrintAndLogDevice(NORMAL, "\tRead B - Kd or Kc");
PrintAndLogDevice(NORMAL, "\tWrite A - Kc");
PrintAndLogDevice(NORMAL, "\tWrite B - Kc");
PrintAndLogDevice(NORMAL, "\tDebit - Kd or Kc");
PrintAndLogDevice(NORMAL, "\tCredit - Kc");
}
}
static void print_picopass_info(const picopass_hdr *hdr) {
fuse_config(hdr);
mem_app_config(hdr);
}
void printIclassDumpInfo(uint8_t *iclass_dump) {
print_picopass_info((picopass_hdr *) iclass_dump);
}
#else
#define PrintAndLogDevice(level, format, ...) { }
#endif
//ON_DEVICE

View file

@ -1,577 +0,0 @@
#ifndef PROTOCOLS_H
#define PROTOCOLS_H
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
//The following data is taken from http://www.proxmark.org/forum/viewtopic.php?pid=13501#p13501
/*
ISO14443A (usually NFC tags)
26 (7bits) = REQA
30 = Read (usage: 30+1byte block number+2bytes ISO14443A-CRC - answer: 16bytes)
A2 = Write (usage: A2+1byte block number+4bytes data+2bytes ISO14443A-CRC - answer: 0A [ACK] or 00 [NAK])
52 (7bits) = WUPA (usage: 52(7bits) - answer: 2bytes ATQA)
93 20 = Anticollision (usage: 9320 - answer: 4bytes UID+1byte UID-bytes-xor)
93 70 = Select (usage: 9370+5bytes 9320 answer - answer: 1byte SAK)
95 20 = Anticollision of cascade level2
95 70 = Select of cascade level2
50 00 = Halt (usage: 5000+2bytes ISO14443A-CRC - no answer from card)
Mifare
60 = Authenticate with KeyA
61 = Authenticate with KeyB
40 (7bits) = Used to put Chinese Changeable UID cards in special mode (must be followed by 43 (8bits) - answer: 0A)
C0 = Decrement
C1 = Increment
C2 = Restore
B0 = Transfer
Ultralight C
A0 = Compatibility Write (to accomodate MIFARE commands)
1A = Step1 Authenticate
AF = Step2 Authenticate
ISO14443B
05 = REQB
1D = ATTRIB
50 = HALT
BA = PING (reader -> tag)
AB = PONG (tag -> reader)
SRIX4K (tag does not respond to 05)
06 00 = INITIATE
0E xx = SELECT ID (xx = Chip-ID)
0B = Get UID
08 yy = Read Block (yy = block number)
09 yy dd dd dd dd = Write Block (yy = block number; dd dd dd dd = data to be written)
0C = Reset to Inventory
0F = Completion
0A 11 22 33 44 55 66 = Authenticate (11 22 33 44 55 66 = data to authenticate)
ISO15693
MANDATORY COMMANDS (all ISO15693 tags must support those)
01 = Inventory (usage: 260100+2bytes ISO15693-CRC - answer: 12bytes)
02 = Stay Quiet
OPTIONAL COMMANDS (not all tags support them)
20 = Read Block (usage: 0220+1byte block number+2bytes ISO15693-CRC - answer: 4bytes)
21 = Write Block (usage: 0221+1byte block number+4bytes data+2bytes ISO15693-CRC - answer: 4bytes)
22 = Lock Block
23 = Read Multiple Blocks (usage: 0223+1byte 1st block to read+1byte last block to read+2bytes ISO15693-CRC)
25 = Select
26 = Reset to Ready
27 = Write AFI
28 = Lock AFI
29 = Write DSFID
2A = Lock DSFID
2B = Get_System_Info (usage: 022B+2bytes ISO15693-CRC - answer: 14 or more bytes)
2C = Read Multiple Block Security Status (usage: 022C+1byte 1st block security to read+1byte last block security to read+2bytes ISO15693-CRC)
EM Microelectronic CUSTOM COMMANDS
A5 = Active EAS (followed by 1byte IC Manufacturer code+1byte EAS type)
A7 = Write EAS ID (followed by 1byte IC Manufacturer code+2bytes EAS value)
B8 = Get Protection Status for a specific block (followed by 1byte IC Manufacturer code+1byte block number+1byte of how many blocks after the previous is needed the info)
E4 = Login (followed by 1byte IC Manufacturer code+4bytes password)
NXP/Philips CUSTOM COMMANDS
A0 = Inventory Read
A1 = Fast Inventory Read
A2 = Set EAS
A3 = Reset EAS
A4 = Lock EAS
A5 = EAS Alarm
A6 = Password Protect EAS
A7 = Write EAS ID
A8 = Read EPC
B0 = Inventory Page Read
B1 = Fast Inventory Page Read
B2 = Get Random Number
B3 = Set Password
B4 = Write Password
B5 = Lock Password
B6 = Bit Password Protection
B7 = Lock Page Protection Condition
B8 = Get Multiple Block Protection Status
B9 = Destroy SLI
BA = Enable Privacy
BB = 64bit Password Protection
40 = Long Range CMD (Standard ISO/TR7003:1990)
ISO 7816-4 Basic interindustry commands. For command APDU's.
B0 = READ BINARY
D0 = WRITE BINARY
D6 = UPDATE BINARY
0E = ERASE BINARY
B2 = READ RECORDS
D2 = WRITE RECORDS
E2 = APPEND RECORD
DC = UPDATE RECORD
CA = GET DATA
DA = PUT DATA
A4 = SELECT FILE
20 = VERIFY
88 = INTERNAL AUTHENTICATION
82 = EXTERNAL AUTHENTICATION
B4 = GET CHALLENGE
70 = MANAGE CHANNEL
For response APDU's
90 00 = OK
6x xx = ERROR
*/
// these cmds are adjusted to ISO15693 and Manchester encoding requests.
// for instance ICLASS_CMD_SELECT 0x81 tells if ISO14443b/BPSK coding/106 kbits/s
// for instance ICLASS_CMD_SELECT 0x41 tells if ISO14443b/BPSK coding/423 kbits/s
//
#define ICLASS_CMD_HALT 0x00
#define ICLASS_CMD_SELECT_15 0x01
#define ICLASS_CMD_ACTALL 0x0A
#define ICLASS_CMD_DETECT 0x0F
#define ICLASS_CMD_CHECK 0x05
#define ICLASS_CMD_READ4 0x06
#define ICLASS_CMD_READ_OR_IDENTIFY 0x0C
#define ICLASS_CMD_SELECT 0x81
#define ICLASS_CMD_PAGESEL 0x84
#define ICLASS_CMD_UPDATE 0x87
#define ICLASS_CMD_READCHECK_KC 0x18
#define ICLASS_CMD_READCHECK_KD 0x88
#define ICLASS_CMD_ACT 0x8E
#define ISO14443A_CMD_REQA 0x26
#define ISO14443A_CMD_READBLOCK 0x30
#define ISO14443A_CMD_WUPA 0x52
#define ISO14443A_CMD_OPTS 0x35
#define ISO14443A_CMD_ANTICOLL_OR_SELECT 0x93
#define ISO14443A_CMD_ANTICOLL_OR_SELECT_2 0x95
#define ISO14443A_CMD_ANTICOLL_OR_SELECT_3 0x97
#define ISO14443A_CMD_WRITEBLOCK 0xA0
#define ISO14443A_CMD_HALT 0x50
#define ISO14443A_CMD_RATS 0xE0
#define ISO14443A_CMD_NXP_DESELECT 0xC2
#define MIFARE_SELECT_CT 0x88
#define MIFARE_AUTH_KEYA 0x60
#define MIFARE_AUTH_KEYB 0x61
#define MIFARE_MAGICWUPC1 0x40
#define MIFARE_MAGICWUPC2 0x43
#define MIFARE_MAGICWIPEC 0x41
#define MIFARE_CMD_INC 0xC0
#define MIFARE_CMD_DEC 0xC1
#define MIFARE_CMD_RESTORE 0xC2
#define MIFARE_CMD_TRANSFER 0xB0
#define MIFARE_EV1_PERSONAL_UID 0x40
#define MIFARE_EV1_SETMODE 0x43
#define MIFARE_ULC_WRITE 0xA2
#define MIFARE_ULC_COMP_WRITE 0xA0
#define MIFARE_ULC_AUTH_1 0x1A
#define MIFARE_ULC_AUTH_2 0xAF
#define MIFARE_ULEV1_AUTH 0x1B
#define MIFARE_ULEV1_VERSION 0x60
#define MIFARE_ULEV1_FASTREAD 0x3A
#define MIFARE_ULEV1_READ_CNT 0x39
#define MIFARE_ULEV1_INCR_CNT 0xA5
#define MIFARE_ULEV1_READSIG 0x3C
#define MIFARE_ULEV1_CHECKTEAR 0x3E
#define MIFARE_ULEV1_VCSL 0x4B
// New Mifare UL Nano commands. Ref:: (https://www.nxp.com/docs/en/data-sheet/MF0UN_H_00.pdf)
#define MIFARE_ULNANO_WRITESIG 0xA9
#define MIFARE_ULNANO_LOCKSIF 0xAC
// mifare 4bit card answers
#define CARD_ACK 0x0A // 1010 - ACK
#define CARD_NACK_IV 0x00 // 0000 - NACK, invalid argument (invalid page address)
#define CARD_NACK_PA 0x01 // 0001 - NACK, parity / crc error
#define CARD_NACK_NA 0x04 // 0100 - NACK, not allowed (command not allowed)
#define CARD_NACK_TR 0x05 // 0101 - NACK, transmission error
#define CARD_NACK_EE 0x07 // 0111 - NACK, EEPROM write error
// Magic Generation 1, parameter "work flags"
// bit 0 - need get UID
// bit 1 - send wupC (wakeup chinese)
// bit 2 - send HALT cmd after sequence
// bit 3 - turn on FPGA
// bit 4 - turn off FPGA
// bit 5 - set datain instead of issuing USB reply (called via ARM for StandAloneMode14a)
#define MAGIC_UID 0x01
#define MAGIC_WUPC 0x02
#define MAGIC_HALT 0x04
#define MAGIC_INIT 0x08
#define MAGIC_OFF 0x10
#define MAGIC_DATAIN 0x20
#define MAGIC_WIPE 0x40
#define MAGIC_SINGLE (MAGIC_WUPC | MAGIC_HALT | MAGIC_INIT | MAGIC_OFF) //0x1E
/**
06 00 = INITIATE
0E xx = SELECT ID (xx = Chip-ID)
0B = Get UID
08 yy = Read Block (yy = block number)
09 yy dd dd dd dd = Write Block (yy = block number; dd dd dd dd = data to be written)
0C = Reset to Inventory
0F = Completion
0A 11 22 33 44 55 66 = Authenticate (11 22 33 44 55 66 = data to authenticate)
**/
#define ISO14443B_REQB 0x05
#define ISO14443B_ATTRIB 0x1D
#define ISO14443B_HALT 0x50
#define ISO14443B_INITIATE 0x06
#define ISO14443B_SELECT 0x0E
#define ISO14443B_GET_UID 0x0B
#define ISO14443B_READ_BLK 0x08
#define ISO14443B_WRITE_BLK 0x09
#define ISO14443B_RESET 0x0C
#define ISO14443B_COMPLETION 0x0F
#define ISO14443B_AUTHENTICATE 0x0A
#define ISO14443B_PING 0xBA
#define ISO14443B_PONG 0xAB
//First byte is 26
#define ISO15693_INVENTORY 0x01
#define ISO15693_STAYQUIET 0x02
//First byte is 02
#define ISO15693_READBLOCK 0x20
#define ISO15693_WRITEBLOCK 0x21
#define ISO15693_LOCKBLOCK 0x22
#define ISO15693_READ_MULTI_BLOCK 0x23
#define ISO15693_SELECT 0x25
#define ISO15693_RESET_TO_READY 0x26
#define ISO15693_WRITE_AFI 0x27
#define ISO15693_LOCK_AFI 0x28
#define ISO15693_WRITE_DSFID 0x29
#define ISO15693_LOCK_DSFID 0x2A
#define ISO15693_GET_SYSTEM_INFO 0x2B
#define ISO15693_READ_MULTI_SECSTATUS 0x2C
// Topaz command set:
#define TOPAZ_REQA 0x26 // Request
#define TOPAZ_WUPA 0x52 // WakeUp
#define TOPAZ_RID 0x78 // Read ID
#define TOPAZ_RALL 0x00 // Read All (all bytes)
#define TOPAZ_READ 0x01 // Read (a single byte)
#define TOPAZ_WRITE_E 0x53 // Write-with-erase (a single byte)
#define TOPAZ_WRITE_NE 0x1a // Write-no-erase (a single byte)
// additional commands for Dynamic Memory Model
#define TOPAZ_RSEG 0x10 // Read segment
#define TOPAZ_READ8 0x02 // Read (eight bytes)
#define TOPAZ_WRITE_E8 0x54 // Write-with-erase (eight bytes)
#define TOPAZ_WRITE_NE8 0x1B // Write-no-erase (eight bytes)
// Definitions of which protocol annotations there are available
#define ISO_14443A 0
#define ICLASS 1
#define ISO_14443B 2
#define TOPAZ 3
#define ISO_7816_4 4
#define MFDES 5
#define LEGIC 6
#define ISO_15693 7
#define FELICA 8
#define PROTO_MIFARE 9
#define PROTO_HITAG 10
#define THINFILM 11
//-- Picopass fuses
#define FUSE_FPERS 0x80
#define FUSE_CODING1 0x40
#define FUSE_CODING0 0x20
#define FUSE_CRYPT1 0x10
#define FUSE_CRYPT0 0x08
#define FUSE_FPROD1 0x04
#define FUSE_FPROD0 0x02
#define FUSE_RA 0x01
// ISO 7816-4 Basic interindustry commands. For command APDU's.
#define ISO7816_READ_BINARY 0xB0
#define ISO7816_WRITE_BINARY 0xD0
#define ISO7816_UPDATE_BINARY 0xD6
#define ISO7816_ERASE_BINARY 0x0E
#define ISO7816_READ_RECORDS 0xB2
#define ISO7816_WRITE_RECORDS 0xD2
#define ISO7816_APPEND_RECORD 0xE2
#define ISO7816_UPDATE_RECORD 0xDC
#define ISO7816_GET_DATA 0xCA
#define ISO7816_PUT_DATA 0xDA
#define ISO7816_SELECT_FILE 0xA4
#define ISO7816_VERIFY 0x20
#define ISO7816_INTERNAL_AUTHENTICATION 0x88
#define ISO7816_EXTERNAL_AUTHENTICATION 0x82
#define ISO7816_GET_CHALLENGE 0x84
#define ISO7816_MANAGE_CHANNEL 0x70
#define ISO7816_GET_RESPONSE 0xC0
// ISO7816-4 For response APDU's
#define ISO7816_OK 0x9000
// 6x xx = ERROR
// MIFARE DESFire command set:
#define MFDES_CREATE_APPLICATION 0xca
#define MFDES_DELETE_APPLICATION 0xda
#define MFDES_GET_APPLICATION_IDS 0x6a
#define MFDES_SELECT_APPLICATION 0x5a
#define MFDES_FORMAT_PICC 0xfc
#define MFDES_GET_VERSION 0x60
#define MFDES_READ_DATA 0xbd
#define MFDES_WRITE_DATA 0x3d
#define MFDES_GET_VALUE 0x6c
#define MFDES_CREDIT 0x0c
#define MFDES_DEBIT 0xdc
#define MFDES_LIMITED_CREDIT 0x1c
#define MFDES_WRITE_RECORD 0x3b
#define MFDES_READ_RECORDS 0xbb
#define MFDES_CLEAR_RECORD_FILE 0xeb
#define MFDES_COMMIT_TRANSACTION 0xc7
#define MFDES_ABORT_TRANSACTION 0xa7
#define MFDES_GET_FREE_MEMORY 0x6e
#define MFDES_GET_FILE_IDS 0x6f
#define MFDES_GET_ISOFILE_IDS 0x61
#define MFDES_GET_FILE_SETTINGS 0xf5
#define MFDES_CHANGE_FILE_SETTINGS 0x5f
#define MFDES_CREATE_STD_DATA_FILE 0xcd
#define MFDES_CREATE_BACKUP_DATA_FILE 0xcb
#define MFDES_CREATE_VALUE_FILE 0xcc
#define MFDES_CREATE_LINEAR_RECORD_FILE 0xc1
#define MFDES_CREATE_CYCLIC_RECORD_FILE 0xc0
#define MFDES_DELETE_FILE 0xdf
#define MFDES_AUTHENTICATE 0x0a // AUTHENTICATE_NATIVE
#define MFDES_AUTHENTICATE_ISO 0x1a // AUTHENTICATE_STANDARD
#define MFDES_AUTHENTICATE_AES 0xaa
#define MFDES_CHANGE_KEY_SETTINGS 0x54
#define MFDES_GET_KEY_SETTINGS 0x45
#define MFDES_CHANGE_KEY 0xc4
#define MFDES_GET_KEY_VERSION 0x64
#define MFDES_AUTHENTICATION_FRAME 0xAF
// LEGIC Commands
#define LEGIC_MIM_22 0x0D
#define LEGIC_MIM_256 0x1D
#define LEGIC_MIM_1024 0x3D
#define LEGIC_ACK_22 0x19
#define LEGIC_ACK_256 0x39
#define LEGIC_READ 0x01
#define LEGIC_WRITE 0x00
void printIclassDumpInfo(uint8_t *iclass_dump);
void getMemConfig(uint8_t mem_cfg, uint8_t chip_cfg, uint8_t *max_blk, uint8_t *app_areas, uint8_t *kb);
/* T55x7 configuration register definitions */
#define T55x7_POR_DELAY 0x00000001
#define T55x7_ST_TERMINATOR 0x00000008
#define T55x7_PWD 0x00000010
#define T55x7_MAXBLOCK_SHIFT 5
#define T55x7_AOR 0x00000200
#define T55x7_PSKCF_RF_2 0
#define T55x7_PSKCF_RF_4 0x00000400
#define T55x7_PSKCF_RF_8 0x00000800
#define T55x7_MODULATION_DIRECT 0
#define T55x7_MODULATION_PSK1 0x00001000
#define T55x7_MODULATION_PSK2 0x00002000
#define T55x7_MODULATION_PSK3 0x00003000
#define T55x7_MODULATION_FSK1 0x00004000
#define T55x7_MODULATION_FSK2 0x00005000
#define T55x7_MODULATION_FSK1a 0x00006000
#define T55x7_MODULATION_FSK2a 0x00007000
#define T55x7_MODULATION_MANCHESTER 0x00008000
#define T55x7_MODULATION_BIPHASE 0x00010000
#define T55x7_MODULATION_DIPHASE 0x00018000
#define T55x7_X_MODE 0x00020000
#define T55x7_BITRATE_RF_8 0
#define T55x7_BITRATE_RF_16 0x00040000
#define T55x7_BITRATE_RF_32 0x00080000
#define T55x7_BITRATE_RF_40 0x000C0000
#define T55x7_BITRATE_RF_50 0x00100000
#define T55x7_BITRATE_RF_64 0x00140000
#define T55x7_BITRATE_RF_100 0x00180000
#define T55x7_BITRATE_RF_128 0x001C0000
#define T55x7_TESTMODE_DISABLED 0x60000000
/* T5555 (Q5) configuration register definitions */
#define T5555_ST_TERMINATOR 0x00000001
#define T5555_MAXBLOCK_SHIFT 0x00000001
#define T5555_MODULATION_MANCHESTER 0
#define T5555_MODULATION_PSK1 0x00000010
#define T5555_MODULATION_PSK2 0x00000020
#define T5555_MODULATION_PSK3 0x00000030
#define T5555_MODULATION_FSK1 0x00000040
#define T5555_MODULATION_FSK2 0x00000050
#define T5555_MODULATION_BIPHASE 0x00000060
#define T5555_MODULATION_DIRECT 0x00000070
#define T5555_INVERT_OUTPUT 0x00000080
#define T5555_PSK_RF_2 0
#define T5555_PSK_RF_4 0x00000100
#define T5555_PSK_RF_8 0x00000200
#define T5555_USE_PWD 0x00000400
#define T5555_USE_AOR 0x00000800
#define T5555_SET_BITRATE(x) (((x-2)/2)<<12)
#define T5555_GET_BITRATE(x) ((((x >> 12) & 0x3F)*2)+2)
#define T5555_BITRATE_SHIFT 12 //(RF=2n+2) ie 64=2*0x1F+2 or n = (RF-2)/2
#define T5555_FAST_WRITE 0x00004000
#define T5555_PAGE_SELECT 0x00008000
#define T55XX_WRITE_TIMEOUT 1500
uint32_t GetT55xxClockBit(uint32_t clock);
// em4x05 & em4x69 chip configuration register definitions
#define EM4x05_GET_BITRATE(x) (((x & 0x3F)*2)+2)
#define EM4x05_SET_BITRATE(x) ((x-2)/2)
#define EM4x05_MODULATION_NRZ 0x00000000
#define EM4x05_MODULATION_MANCHESTER 0x00000040
#define EM4x05_MODULATION_BIPHASE 0x00000080
#define EM4x05_MODULATION_MILLER 0x000000C0 //not supported by all 4x05/4x69 chips
#define EM4x05_MODULATION_PSK1 0x00000100 //not supported by all 4x05/4x69 chips
#define EM4x05_MODULATION_PSK2 0x00000140 //not supported by all 4x05/4x69 chips
#define EM4x05_MODULATION_PSK3 0x00000180 //not supported by all 4x05/4x69 chips
#define EM4x05_MODULATION_FSK1 0x00000200 //not supported by all 4x05/4x69 chips
#define EM4x05_MODULATION_FSK2 0x00000240 //not supported by all 4x05/4x69 chips
#define EM4x05_PSK_RF_2 0
#define EM4x05_PSK_RF_4 0x00000400
#define EM4x05_PSK_RF_8 0x00000800
#define EM4x05_MAXBLOCK_SHIFT 14
#define EM4x05_FIRST_USER_BLOCK 5
#define EM4x05_SET_NUM_BLOCKS(x) ((x+5-1)<<14) //# of blocks sent during default read mode
#define EM4x05_GET_NUM_BLOCKS(x) (((x>>14) & 0xF)-5+1)
#define EM4x05_READ_LOGIN_REQ 1<<18
#define EM4x05_READ_HK_LOGIN_REQ 1<<19
#define EM4x05_WRITE_LOGIN_REQ 1<<20
#define EM4x05_WRITE_HK_LOGIN_REQ 1<<21
#define EM4x05_READ_AFTER_WRITE 1<<22
#define EM4x05_DISABLE_ALLOWED 1<<23
#define EM4x05_READER_TALK_FIRST 1<<24
// FeliCa protocol
#define FELICA_POLL_REQ 0x00
#define FELICA_POLL_ACK 0x01
#define FELICA_REQSRV_REQ 0x02
#define FELICA_REQSRV_ACK 0x03
#define FELICA_REQRESP_REQ 0x04
#define FELICA_REQRESP_ACK 0x05
#define FELICA_RDBLK_REQ 0x06
#define FELICA_RDBLK_ACK 0x07
#define FELICA_WRTBLK_REQ 0x08
#define FELICA_WRTBLK_ACK 0x09
#define FELICA_SRCHSYSCODE_REQ 0x0a
#define FELICA_SRCHSYSCODE_ACK 0x0b
#define FELICA_REQSYSCODE_REQ 0x0c
#define FELICA_REQSYSCODE_ACK 0x0d
#define FELICA_AUTH1_REQ 0x10
#define FELICA_AUTH1_ACK 0x11
#define FELICA_AUTH2_REQ 0x12
#define FELICA_AUTH2_ACK 0x13
#define FELICA_RDSEC_REQ 0x14
#define FELICA_RDSEC_ACK 0x15
#define FELICA_WRTSEC_REQ 0x16
#define FELICA_WRTSEC_ACK 0x17
#define FELICA_REQSRV2_REQ 0x32
#define FELICA_REQSRV2_ACK 0x33
#define FELICA_GETSTATUS_REQ 0x38
#define FELICA_GETSTATUS_ACK 0x39
#define FELICA_OSVER_REQ 0x3c
#define FELICA_OSVER_ACK 0x3d
#define FELICA_RESET_MODE_REQ 0x3e
#define FELICA_RESET_MODE_ACK 0x3f
#define FELICA_AUTH1V2_REQ 0x40
#define FELICA_AUTH1V2_ACK 0x41
#define FELICA_AUTH2V2_REQ 0x42
#define FELICA_AUTH2V2_ACK 0x43
#define FELICA_RDSECV2_REQ 0x44
#define FELICA_RDSECV2_ACK 0x45
#define FELICA_WRTSECV2_REQ 0x46
#define FELICA_WRTSECV2_ACK 0x47
#define FELICA_UPDATE_RNDID_REQ 0x4C
#define FELICA_UPDATE_RNDID_ACK 0x4D
// FeliCa SYSTEM list
#define SYSTEMCODE_ANY 0xffff // ANY
#define SYSTEMCODE_FELICA_LITE 0x88b4 // FeliCa Lite
#define SYSTEMCODE_COMMON 0xfe00 // Common
#define SYSTEMCODE_EDY 0xfe00 // Edy
#define SYSTEMCODE_CYBERNE 0x0003 // Cyberne
#define SYSTEMCODE_SUICA 0x0003 // Suica
#define SYSTEMCODE_PASMO 0x0003 // Pasmo
//FeliCa Service list Suica/pasmo (little endian)
#define SERVICE_SUICA_INOUT 0x108f // SUICA/PASMO
#define SERVICE_SUICA_HISTORY 0x090f // SUICA/PASMO
#define SERVICE_FELICA_LITE_READONLY 0x0b00 // FeliCa Lite RO
#define SERVICE_FELICA_LITE_READWRITE 0x0900 // FeliCa Lite RW
// Calypso protocol
#define CALYPSO_GET_RESPONSE 0xC0
#define CALYPSO_SELECT 0xA4
#define CALYPSO_INVALIDATE 0x04
#define CALYPSO_REHABILITATE 0x44
#define CALYPSO_APPEND_RECORD 0xE2
#define CALYPSO_DECREASE 0x30
#define CALYPSO_INCREASE 0x32
#define CALYPSO_READ_BINARY 0xB0
#define CALYPSO_READ_RECORD 0xB2
#define CALYPSO_UPDATE_BINARY 0xD6
#define CALYPSO_UPDATE_RECORD 0xDC
#define CALYPSO_WRITE_RECORD 0xD2
#define CALYPSO_OPEN_SESSION 0x8A
#define CALYPSO_CLOSE_SESSION 0x8E
#define CALYPSO_GET_CHALLENGE 0x84
#define CALYPSO_CHANGE_PIN 0xD8
#define CALYPSO_VERIFY_PIN 0x20
#define CALYPSO_SV_GET 0x7C
#define CALYPSO_SV_DEBIT 0xBA
#define CALYPSO_SV_RELOAD 0xB8
#define CALYPSO_SV_UN_DEBIT 0xBC
#define CALYPSO_SAM_SV_DEBIT 0x54
#define CALYPSO_SAM_SV_RELOAD 0x56
// iclass / picopass chip config structures and shared routines
typedef struct {
uint8_t app_limit; //[8]
uint8_t otp[2]; //[9-10]
uint8_t block_writelock;//[11]
uint8_t chip_config; //[12]
uint8_t mem_config; //[13]
uint8_t eas; //[14]
uint8_t fuses; //[15]
} picopass_conf_block;
typedef struct {
uint8_t csn[8];
picopass_conf_block conf;
uint8_t epurse[8];
uint8_t key_d[8];
uint8_t key_c[8];
uint8_t app_issuer_area[8];
} picopass_hdr;
#endif
// PROTOCOLS_H

View file

@ -1,99 +0,0 @@
#include "radixsort.h"
uint64_t *radixSort(uint64_t *array, uint32_t size) {
rscounts_t counts;
memset(&counts, 0, 256 * 8 * sizeof(uint32_t));
uint64_t *cpy = (uint64_t *)calloc(size * sizeof(uint64_t), sizeof(uint8_t));
uint32_t o8 = 0, o7 = 0, o6 = 0, o5 = 0, o4 = 0, o3 = 0, o2 = 0, o1 = 0;
uint32_t t8, t7, t6, t5, t4, t3, t2, t1;
uint32_t x;
// calculate counts
for (x = 0; x < size; ++x) {
t8 = array[x] & 0xff;
t7 = (array[x] >> 8) & 0xff;
t6 = (array[x] >> 16) & 0xff;
t5 = (array[x] >> 24) & 0xff;
t4 = (array[x] >> 32) & 0xff;
t3 = (array[x] >> 40) & 0xff;
t2 = (array[x] >> 48) & 0xff;
t1 = (array[x] >> 56) & 0xff;
counts.c8[t8]++;
counts.c7[t7]++;
counts.c6[t6]++;
counts.c5[t5]++;
counts.c4[t4]++;
counts.c3[t3]++;
counts.c2[t2]++;
counts.c1[t1]++;
}
// convert counts to offsets
for (x = 0; x < 256; ++x) {
t8 = o8 + counts.c8[x];
t7 = o7 + counts.c7[x];
t6 = o6 + counts.c6[x];
t5 = o5 + counts.c5[x];
t4 = o4 + counts.c4[x];
t3 = o3 + counts.c3[x];
t2 = o2 + counts.c2[x];
t1 = o1 + counts.c1[x];
counts.c8[x] = o8;
counts.c7[x] = o7;
counts.c6[x] = o6;
counts.c5[x] = o5;
counts.c4[x] = o4;
counts.c3[x] = o3;
counts.c2[x] = o2;
counts.c1[x] = o1;
o8 = t8;
o7 = t7;
o6 = t6;
o5 = t5;
o4 = t4;
o3 = t3;
o2 = t2;
o1 = t1;
}
// radix
for (x = 0; x < size; ++x) {
t8 = array[x] & 0xff;
cpy[counts.c8[t8]] = array[x];
counts.c8[t8]++;
}
for (x = 0; x < size; ++x) {
t7 = (cpy[x] >> 8) & 0xff;
array[counts.c7[t7]] = cpy[x];
counts.c7[t7]++;
}
for (x = 0; x < size; ++x) {
t6 = (array[x] >> 16) & 0xff;
cpy[counts.c6[t6]] = array[x];
counts.c6[t6]++;
}
for (x = 0; x < size; ++x) {
t5 = (cpy[x] >> 24) & 0xff;
array[counts.c5[t5]] = cpy[x];
counts.c5[t5]++;
}
for (x = 0; x < size; ++x) {
t4 = (array[x] >> 32) & 0xff;
cpy[counts.c4[t4]] = array[x];
counts.c4[t4]++;
}
for (x = 0; x < size; ++x) {
t3 = (cpy[x] >> 40) & 0xff;
array[counts.c3[t3]] = cpy[x];
counts.c3[t3]++;
}
for (x = 0; x < size; ++x) {
t2 = (array[x] >> 48) & 0xff;
cpy[counts.c2[t2]] = array[x];
counts.c2[t2]++;
}
for (x = 0; x < size; ++x) {
t1 = (cpy[x] >> 56) & 0xff;
array[counts.c1[t1]] = cpy[x];
counts.c1[t1]++;
}
free(cpy);
return array;
}

View file

@ -1,23 +0,0 @@
#ifndef RADIXSORT_H__
#define RADIXSORT_H__
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
typedef union {
struct {
uint32_t c8[256];
uint32_t c7[256];
uint32_t c6[256];
uint32_t c5[256];
uint32_t c4[256];
uint32_t c3[256];
uint32_t c2[256];
uint32_t c1[256];
};
uint32_t counts[256 * 8];
} rscounts_t;
uint64_t *radixSort(uint64_t *array, uint32_t size);
#endif // RADIXSORT_H__

View file

@ -1,64 +0,0 @@
//-----------------------------------------------------------------------------
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Generic TEA crypto code.
// ref: http://143.53.36.235:8080/source.htm#ansi
//-----------------------------------------------------------------------------
#include "tea.h"
#define ROUNDS 32
#define DELTA 0x9E3779B9
#define SUM 0xC6EF3720
void tea_encrypt(uint8_t *v, uint8_t *key) {
uint32_t a = 0, b = 0, c = 0, d = 0, y = 0, z = 0;
uint32_t sum = 0;
uint8_t n = ROUNDS;
//key
a = bytes_to_num(key, 4);
b = bytes_to_num(key + 4, 4);
c = bytes_to_num(key + 8, 4);
d = bytes_to_num(key + 12, 4);
//input
y = bytes_to_num(v, 4);
z = bytes_to_num(v + 4, 4);
while (n-- > 0) {
sum += DELTA;
y += ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
z += ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
}
num_to_bytes(y, 4, v);
num_to_bytes(z, 4, v + 4);
}
void tea_decrypt(uint8_t *v, uint8_t *key) {
uint32_t a = 0, b = 0, c = 0, d = 0, y = 0, z = 0;
uint32_t sum = SUM;
uint8_t n = ROUNDS;
//key
a = bytes_to_num(key, 4);
b = bytes_to_num(key + 4, 4);
c = bytes_to_num(key + 8, 4);
d = bytes_to_num(key + 12, 4);
//input
y = bytes_to_num(v, 4);
z = bytes_to_num(v + 4, 4);
/* sum = delta<<5, in general sum = delta * n */
while (n-- > 0) {
z -= ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
y -= ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
sum -= DELTA;
}
num_to_bytes(y, 4, v);
num_to_bytes(z, 4, v + 4);
}

View file

@ -1,265 +0,0 @@
//-----------------------------------------------------------------------------
// Iceman, July 2018
// edits by - Anticat, August 2018
//
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// The main USART code, for serial communications over FPC connector
//-----------------------------------------------------------------------------
#include "cmd.h"
#include "usart.h"
#include "string.h"
#include "../armsrc/ticks.h" // startcountus
volatile AT91PS_USART pUS1 = AT91C_BASE_US1;
volatile AT91PS_PIO pPIO = AT91C_BASE_PIOA;
volatile AT91PS_PDC pPDC = AT91C_BASE_PDC_US1;
uint32_t usart_baudrate = 0;
uint8_t usart_parity = 0;
/*
void usart_close(void) {
// Reset the USART mode
pUS1->US_MR = 0;
// Reset the baud rate divisor register
pUS1->US_BRGR = 0;
// Reset the Timeguard Register
pUS1->US_TTGR = 0;
// Disable all interrupts
pUS1->US_IDR = 0xFFFFFFFF;
// Abort the Peripheral Data Transfers
pUS1->US_PTCR = AT91C_PDC_RXTDIS | AT91C_PDC_TXTDIS;
// Disable receiver and transmitter and stop any activity immediately
pUS1->US_CR = AT91C_US_TXDIS | AT91C_US_RXDIS | AT91C_US_RSTTX | AT91C_US_RSTRX;
}
*/
static uint8_t us_inbuf1[USART_BUFFLEN];
static uint8_t us_inbuf2[USART_BUFFLEN];
uint8_t *usart_cur_inbuf = NULL;
uint16_t usart_cur_inbuf_off = 0;
static uint8_t us_rxfifo[USART_FIFOLEN];
static size_t us_rxfifo_low = 0;
static size_t us_rxfifo_high = 0;
static void usart_fill_rxfifo(void) {
uint16_t rxfifo_free = 0;
if (pUS1->US_RNCR == 0) { // One buffer got filled, backup buffer being used
if (us_rxfifo_low > us_rxfifo_high)
rxfifo_free = us_rxfifo_low - us_rxfifo_high;
else
rxfifo_free = sizeof(us_rxfifo) - us_rxfifo_high + us_rxfifo_low;
uint16_t available = USART_BUFFLEN - usart_cur_inbuf_off;
if (available <= rxfifo_free) {
for (uint16_t i = 0; i < available; i++) {
us_rxfifo[us_rxfifo_high++] = usart_cur_inbuf[usart_cur_inbuf_off + i];
if (us_rxfifo_high == sizeof(us_rxfifo))
us_rxfifo_high = 0;
}
// Give next buffer
pUS1->US_RNPR = (uint32_t)usart_cur_inbuf;
pUS1->US_RNCR = USART_BUFFLEN;
// Swap current buff
if (usart_cur_inbuf == us_inbuf1)
usart_cur_inbuf = us_inbuf2;
else
usart_cur_inbuf = us_inbuf1;
usart_cur_inbuf_off = 0;
} else {
// Take only what we have room for
available = rxfifo_free;
for (uint16_t i = 0; i < available; i++) {
us_rxfifo[us_rxfifo_high++] = usart_cur_inbuf[usart_cur_inbuf_off + i];
if (us_rxfifo_high == sizeof(us_rxfifo))
us_rxfifo_high = 0;
}
usart_cur_inbuf_off += available;
return;
}
}
if (pUS1->US_RCR < USART_BUFFLEN - usart_cur_inbuf_off) { // Current buffer partially filled
if (us_rxfifo_low > us_rxfifo_high)
rxfifo_free = us_rxfifo_low - us_rxfifo_high;
else
rxfifo_free = sizeof(us_rxfifo) - us_rxfifo_high + us_rxfifo_low;
uint16_t available = USART_BUFFLEN - pUS1->US_RCR - usart_cur_inbuf_off;
if (available > rxfifo_free)
available = rxfifo_free;
for (uint16_t i = 0; i < available; i++) {
us_rxfifo[us_rxfifo_high++] = usart_cur_inbuf[usart_cur_inbuf_off + i];
if (us_rxfifo_high == sizeof(us_rxfifo))
us_rxfifo_high = 0;
}
usart_cur_inbuf_off += available;
}
}
uint16_t usart_rxdata_available(void) {
usart_fill_rxfifo();
if (us_rxfifo_low <= us_rxfifo_high)
return us_rxfifo_high - us_rxfifo_low;
else
return sizeof(us_rxfifo) - us_rxfifo_low + us_rxfifo_high;
}
uint32_t usart_read_ng(uint8_t *data, size_t len) {
if (len == 0) return 0;
uint32_t nbBytesRcv = 0;
uint32_t try = 0;
// uint32_t highest_observed_try = 0;
// Empirical max try observed: 3000000 / USART_BAUD_RATE
// Let's take 10x
uint32_t tryconstant = 0;
#ifdef USART_SLOW_LINK
// Experienced up to 13200 tries on BT link even at 460800
tryconstant = 50000;
#endif
uint32_t maxtry = 10 * (3000000 / USART_BAUD_RATE) + tryconstant;
while (len) {
uint32_t available = usart_rxdata_available();
uint32_t packetSize = MIN(available, len);
if (available > 0) {
// Dbprintf_usb("Dbg USART ask %d bytes, available %d bytes, packetsize %d bytes", len, available, packetSize);
// highest_observed_try = MAX(highest_observed_try, try);
try = 0;
}
len -= packetSize;
while (packetSize--) {
data[nbBytesRcv++] = us_rxfifo[us_rxfifo_low++];
if (us_rxfifo_low == sizeof(us_rxfifo))
us_rxfifo_low = 0;
}
if (try++ == maxtry) {
// Dbprintf_usb("Dbg USART TIMEOUT");
break;
}
}
// highest_observed_try = MAX(highest_observed_try, try);
// Dbprintf_usb("Dbg USART max observed try %i", highest_observed_try);
return nbBytesRcv;
}
// transfer from device to client
inline int usart_writebuffer_sync(uint8_t *data, size_t len) {
// Wait for current PDC bank to be free
// (and check next bank too, in case there will be a usart_writebuffer_async)
while (pUS1->US_TNCR || pUS1->US_TCR) {};
pUS1->US_TPR = (uint32_t)data;
pUS1->US_TCR = len;
// Wait until finishing all transfers to make sure "data" buffer can be discarded
// (if we don't wait here, bulk send as e.g. "hw status" will fail)
while (pUS1->US_TNCR || pUS1->US_TCR) {};
return PM3_SUCCESS;
}
void usart_init(uint32_t baudrate, uint8_t parity) {
if (baudrate != 0)
usart_baudrate = baudrate;
if ((parity == 'N') || (parity == 'O') || (parity == 'E'))
usart_parity = parity;
// For a nice detailed sample, interrupt driven but still relevant.
// See https://www.sparkfun.com/datasheets/DevTools/SAM7/at91sam7%20serial%20communications.pdf
// disable & reset receiver / transmitter for configuration
pUS1->US_CR = (AT91C_US_RSTRX | AT91C_US_RSTTX | AT91C_US_RXDIS | AT91C_US_TXDIS);
//enable the USART1 Peripheral clock
AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US1);
// disable PIO control of receive / transmit pins
pPIO->PIO_PDR |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1);
// enable peripheral mode A on receive / transmit pins
pPIO->PIO_ASR |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1);
pPIO->PIO_BSR = 0;
// enable pull-up on receive / transmit pins (see 31.5.1 I/O Lines)
pPIO->PIO_PPUER |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1);
// set mode
uint32_t mode = AT91C_US_USMODE_NORMAL | // normal mode
AT91C_US_CLKS_CLOCK | // MCK (48MHz)
AT91C_US_OVER | // oversampling
AT91C_US_CHRL_8_BITS | // 8 bits
AT91C_US_NBSTOP_1_BIT | // 1 stop bit
AT91C_US_CHMODE_NORMAL; // channel mode: normal
switch (usart_parity) {
case 'N':
mode |= AT91C_US_PAR_NONE; // parity: none
break;
case 'O':
mode |= AT91C_US_PAR_ODD; // parity: odd
break;
case 'E':
mode |= AT91C_US_PAR_EVEN; // parity: even
break;
}
pUS1->US_MR = mode;
// all interrupts disabled
pUS1->US_IDR = 0xFFFF;
// http://ww1.microchip.com/downloads/en/DeviceDoc/doc6175.pdf
// note that for very large baudrates, error is not neglectible:
// b921600 => 8.6%
// b1382400 => 8.6%
// FP, Fractional Part (Datasheet p402, Supported in AT91SAM512 / 256) (31.6.1.3)
// FP = 0 disabled;
// FP = 1-7 Baudrate resolution,
// CD, Clock divider,
// sync == 0 , (async?)
// OVER = 0, -no
// baudrate == selected clock/16/CD
// OVER = 1, -yes we are oversampling
// baudrate == selected clock/8/CD --> this is ours
//
uint32_t brgr = MCK / (usart_baudrate << 3);
// doing fp = round((mck / (usart_baudrate << 3) - brgr) * 8) with integers:
uint32_t fp = ((16 * MCK / (usart_baudrate << 3) - 16 * brgr) + 1) / 2;
pUS1->US_BRGR = (fp << 16) | brgr;
// Write the Timeguard Register
pUS1->US_TTGR = 0;
pUS1->US_RTOR = 0;
pUS1->US_FIDI = 0;
pUS1->US_IF = 0;
// Initialize DMA buffers
pUS1->US_TPR = (uint32_t)0;
pUS1->US_TCR = 0;
pUS1->US_TNPR = (uint32_t)0;
pUS1->US_TNCR = 0;
pUS1->US_RPR = (uint32_t)us_inbuf1;
pUS1->US_RCR = USART_BUFFLEN;
usart_cur_inbuf = us_inbuf1;
usart_cur_inbuf_off = 0;
pUS1->US_RNPR = (uint32_t)us_inbuf2;
pUS1->US_RNCR = USART_BUFFLEN;
// Initialize our fifo
us_rxfifo_low = 0;
us_rxfifo_high = 0;
// re-enable receiver / transmitter
pUS1->US_CR = (AT91C_US_RXEN | AT91C_US_TXEN);
// ready to receive and transmit
pUS1->US_PTCR = AT91C_PDC_RXTEN | AT91C_PDC_TXTEN;
}

View file

@ -1,28 +0,0 @@
#ifndef __USART_H
#define __USART_H
#include <stddef.h>
#include "proxmark3.h"
//#define USART_BAUD_RATE 9600
#define USART_BAUD_RATE 115200
// BT HC-06 physical layer runs at 128kbps
// so it's possible to gain a little bit by using 230400
// with some risk to overflow its internal buffers:
//#define USART_BAUD_RATE 230400
// Higher baudrates are pointless, only increasing overflow risk
extern uint32_t usart_baudrate;
#define USART_PARITY 'N'
extern uint8_t usart_parity;
void usart_init(uint32_t baudrate, uint8_t parity);
int usart_writebuffer_sync(uint8_t *data, size_t len);
uint32_t usart_read_ng(uint8_t *data, size_t len);
uint16_t usart_rxdata_available(void);
#define USART_BUFFLEN 512
#define USART_FIFOLEN (2*USART_BUFFLEN)
#endif

File diff suppressed because it is too large Load diff

View file

@ -1,65 +0,0 @@
/*
* at91sam7s USB CDC device implementation
*
* Copyright (c) 2012, Roel Verdult
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* based on the "Basic USB Example" from ATMEL (doc6123.pdf)
*
* @file usb_cdc.c
* @brief
*/
#ifndef _USB_CDC_H_
#define _USB_CDC_H_
#include <wchar.h>
#include "at91sam7s512.h"
#include "usart.h"
#include "config_gpio.h"
#include "proxmark3.h" // USB_CONNECT()
#include "common.h"
void usb_disable(void);
void usb_enable(void);
bool usb_check(void);
bool usb_poll(void);
bool usb_poll_validate_length(void);
uint32_t usb_read(uint8_t *data, size_t len);
int usb_write(const uint8_t *data, const size_t len);
uint32_t usb_read_ng(uint8_t *data, size_t len);
void SetUSBreconnect(int value);
int GetUSBreconnect(void);
void SetUSBconfigured(int value);
int GetUSBconfigured(void);
void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length);
void AT91F_USB_SendZlp(AT91PS_UDP pUdp);
void AT91F_USB_SendStall(AT91PS_UDP pUdp);
void AT91F_CDC_Enumerate(void);
#endif // _USB_CDC_H_

View file

@ -1,239 +0,0 @@
//-----------------------------------------------------------------------------
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Wiegand functions
//-----------------------------------------------------------------------------
#include "wiegand.h"
/*
* @brief getParity
* @param bits pointer to the source bitstream of binary values 0|1
* @param len how long shall parity be calculated
* @param type use the defined values EVEN|ODD
* @return parity bit required to match type
*/
uint8_t getParity(uint8_t *bits, uint8_t len, uint8_t type) {
uint8_t x = 0;
for (; len > 0; --len)
x += bits[len - 1];
return (x & 1) ^ type;
}
// by marshmellow
/* pass bits to be tested in bits, length bits passed in bitLen, and parity type EVEN|ODD in type
* @brief checkParity
* @param bits pointer to the source bitstream of binary values 0|1
* @param len number of bits to be checked
* @param type use the defined values EVEN|ODD
* @return 1 if passed
*/
uint8_t checkParity(uint32_t bits, uint8_t len, uint8_t type);
// by marshmellow
// takes a array of binary values, start position, length of bits per parity (includes parity bit),
// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run)
size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) {
uint32_t parityWd = 0;
size_t j = 0, bitcount = 0;
for (int word = 0; word < (bLen); word += pLen) {
for (int bit = 0; bit < pLen; ++bit) {
parityWd = (parityWd << 1) | bits[startIdx + word + bit];
bits[j++] = (bits[startIdx + word + bit]);
}
j--; // overwrite parity with next data
// if parity fails then return 0
switch (pType) {
case 3:
if (bits[j] == 1) return 0;
break; //should be 0 spacer bit
case 2:
if (bits[j] == 0) return 0;
break; //should be 1 spacer bit
default: //test parity
if (parityTest(parityWd, pLen, pType) == 0) return 0;
break;
}
bitcount += (pLen - 1);
parityWd = 0;
}
// if we got here then all the parities passed
//return ID start index and size
return bitcount;
}
// by marshmellow
// takes a array of binary values, length of bits per parity (includes parity bit),
// Parity Type (1 for odd; 0 for even; 2 Always 1's; 3 Always 0's), and binary Length (length to run)
// Make sure *dest is long enough to store original sourceLen + #_of_parities_to_be_added
/*
* @brief addParity
* @param src pointer to the source bitstream of binary values
* @param dest pointer to the destination where parities together with bits are added.
* @param sourceLen number of
* @param pLen length bits to be checked
* @param pType EVEN|ODD|2 (always 1's)|3 (always 0's)
* @return
*/
size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) {
uint32_t parityWd = 0;
size_t j = 0, bitCnt = 0;
for (int word = 0; word < sourceLen; word += pLen - 1) {
for (int bit = 0; bit < pLen - 1; ++bit) {
parityWd = (parityWd << 1) | src[word + bit];
dest[j++] = (src[word + bit]);
}
// if parity fails then return 0
switch (pType) {
case 3:
dest[j++] = 0;
break; // marker bit which should be a 0
case 2:
dest[j++] = 1;
break; // marker bit which should be a 1
default:
dest[j++] = parityTest(parityWd, pLen - 1, pType) ^ 1;
break;
}
bitCnt += pLen;
parityWd = 0;
}
// if we got here then all the parities passed
//return ID start index and size
return bitCnt;
}
// by marshmellow
/*
* add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
* @brief wiegand_add_parity
* @param source pointer to source of binary data
* @param dest pointer to the destination where wiegandparity has been appended
* @param len number of bits which wiegand parity shall be calculated over. This number is without parities, so a wiegand 26 has 24 bits of data
*/
void wiegand_add_parity(uint8_t *source, uint8_t *dest, uint8_t len) {
// Copy to destination, shifted one step to make room for EVEN parity
memcpy(dest + 1, source, length);
// half length, Even and Odd is calculated to the middle.
uint8_t len_h2 = length >> 1;
// add EVEN parity at the beginning
*(dest) = GetParity(source, EVEN, len_h2);
dest += length + 1;
// add ODD parity at the very end
*(dest) = GetParity(source + len_h2, ODD, len_h2);
}
//uint32_t bytebits_to_byte(uint8_t* src, size_t numbits);
#define MAX_BITS_TXX55 6*4*8
#define MAX_BYTES_TXX55 6*4
/*
* @brief num_to_wiegand_bytes
* @param oem Sometimes call FF Fixfield, SiteCode. Used in a few formats
* @param fc Facility code
* @param cn Card number
* @param dest pointer to the destination where wiegand bytes will be stored
* @param formatlen
*/
void num_to_wiegand_bytes(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen) {
uint8_t data[MAX_BITS_TXX55] = {0};
memset(data, 0, sizeof(data));
num_to_wiegand_bits(oem, fc, cn, data, formatlen);
// loop
// (formatlen / 32 ) + 1
// (formatlen >> 5) + 1
for (int i = 0; i < formatlen ; ++i) {
uint32_t value = bytebits_to_byte(data + (i * 32), 32);
num_to_bytes(value, 32, dest + (i * 4));
}
}
/*
* @brief num_to_wiegand_bits
* @param oem Sometimes call FF Fixfield, SiteCode. Used in a few formats
* @param fc Facility code
* @param cn Card number
* @param dest pointer to the destination where wiegand bits will be stored
* @param formatlen
*/
void num_to_wiegand_bits(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen) {
uint8_t bits[MAX_BITS_TXX55] = {0};
memset(bits, 0, sizeof(bits));
uint8_t *temp = bits;
uint64_t value = 0;
switch (formatlen) {
case 26 : // 26bit HID H10301
fc &= 0xFF; // 8bits
cn &= 0xFFFF; // 16bits
value = fc << 16 | cn;
num_to_bytebits(value, 24, temp);
wiegand_add_parity(temp, dest, 24);
break;
case 261: // 26bit Indala
fc &= 0xFFF; // 12bits
cn &= 0xFFF; // 12bits
value = fc << 12 | cn;
num_to_bytebits(value, 24, temp);
wiegand_add_parity(temp, dest, 24);
break;
case 34 : // 34bits HID
fc &= 0xFFFF; // 16bits
cn &= 0xFFFF; // 16bits
value = fc << 16 | cn;
num_to_bytebits(value, 32, temp);
wiegand_add_parity(temp, dest, 32);
break;
case 35 : // 35bits HID
fc &= 0xFFF; // 12bits
cn &= 0xFFFFFF; // 20bits
value = fc << 20 | cn;
num_to_bytebits(value, 32, temp);
wiegand_add_parity(temp, dest, 32);
break;
case 37 : // H10304
fc &= 0xFFFF; // 16bits
cn &= 0x7FFFF; // 19bits
value = fc << 19 | cn;
num_to_bytebits(value, 35, temp);
wiegand_add_parity(temp, dest, 35);
break;
case 39 : // 39bit KERI System Pyramid
fc &= 0x1FFFF; // 17bits
cn &= 0xFFFFFFFF; // 20bits
value = fc << 20 | cn;
num_to_bytebits(value, 37, temp);
wiegand_add_parity(temp, dest, 37);
break;
case 44 : // 44bit KERI system Pyramid
oem &= 0xFF; // 8bits
fc &= 0xFFF; // 12bits
cn &= 0xFFFFFFFF; // 21bits
value = oem << 20 | fc << 12 | cn;
num_to_bytebits(value, 42, temp);
wiegand_add_parity(temp, dest, 42);
break;
case 50 : // AWID 50 RBH
fc &= 0xFFFF; // 16bits
cn &= 0xFFFFFFFF; // 32bits
value = fc << 32 | cn;
num_to_bytebits(value, 48, temp);
wiegand_add_parity(temp, dest, 48); // verify!
break;
default:
break;
}
}

View file

@ -1,20 +0,0 @@
//-----------------------------------------------------------------------------
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Generic Wiegand Calculation code
//-----------------------------------------------------------------------------
#ifndef __WIEGAND_H
#define __WIEGAND_H
#include "common.h"
uint8_t getParity(uint8_t *bits, uint8_t len, uint8_t type);
uint8_t checkParity(uint32_t bits, uint8_t len, uint8_t type);
void num_to_wiegand_bytes(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen);
void num_to_wiegand_bits(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen);
#endif /* __WIEGAND_H */

1481
common/zlib/ChangeLog Normal file

File diff suppressed because it is too large Load diff

368
common/zlib/FAQ Normal file
View file

@ -0,0 +1,368 @@
Frequently Asked Questions about zlib
If your question is not there, please check the zlib home page
http://zlib.net/ which may have more recent information.
The lastest zlib FAQ is at http://zlib.net/zlib_faq.html
1. Is zlib Y2K-compliant?
Yes. zlib doesn't handle dates.
2. Where can I get a Windows DLL version?
The zlib sources can be compiled without change to produce a DLL. See the
file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the
precompiled DLL are found in the zlib web site at http://zlib.net/ .
3. Where can I get a Visual Basic interface to zlib?
See
* http://marknelson.us/1997/01/01/zlib-engine/
* win32/DLL_FAQ.txt in the zlib distribution
4. compress() returns Z_BUF_ERROR.
Make sure that before the call of compress(), the length of the compressed
buffer is equal to the available size of the compressed buffer and not
zero. For Visual Basic, check that this parameter is passed by reference
("as any"), not by value ("as long").
5. deflate() or inflate() returns Z_BUF_ERROR.
Before making the call, make sure that avail_in and avail_out are not zero.
When setting the parameter flush equal to Z_FINISH, also make sure that
avail_out is big enough to allow processing all pending input. Note that a
Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be
made with more input or output space. A Z_BUF_ERROR may in fact be
unavoidable depending on how the functions are used, since it is not
possible to tell whether or not there is more output pending when
strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a
heavily annotated example.
6. Where's the zlib documentation (man pages, etc.)?
It's in zlib.h . Examples of zlib usage are in the files test/example.c
and test/minigzip.c, with more in examples/ .
7. Why don't you use GNU autoconf or libtool or ...?
Because we would like to keep zlib as a very small and simple package.
zlib is rather portable and doesn't need much configuration.
8. I found a bug in zlib.
Most of the time, such problems are due to an incorrect usage of zlib.
Please try to reproduce the problem with a small program and send the
corresponding source to us at zlib@gzip.org . Do not send multi-megabyte
data files without prior agreement.
9. Why do I get "undefined reference to gzputc"?
If "make test" produces something like
example.o(.text+0x154): undefined reference to `gzputc'
check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
/usr/X11R6/lib. Remove any old versions, then do "make install".
10. I need a Delphi interface to zlib.
See the contrib/delphi directory in the zlib distribution.
11. Can zlib handle .zip archives?
Not by itself, no. See the directory contrib/minizip in the zlib
distribution.
12. Can zlib handle .Z files?
No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
the code of uncompress on your own.
13. How can I make a Unix shared library?
By default a shared (and a static) library is built for Unix. So:
make distclean
./configure
make
14. How do I install a shared zlib library on Unix?
After the above, then:
make install
However, many flavors of Unix come with a shared zlib already installed.
Before going to the trouble of compiling a shared version of zlib and
trying to install it, you may want to check if it's already there! If you
can #include <zlib.h>, it's there. The -lz option will probably link to
it. You can check the version at the top of zlib.h or with the
ZLIB_VERSION symbol defined in zlib.h .
15. I have a question about OttoPDF.
We are not the authors of OttoPDF. The real author is on the OttoPDF web
site: Joel Hainley, jhainley@myndkryme.com.
16. Can zlib decode Flate data in an Adobe PDF file?
Yes. See http://www.pdflib.com/ . To modify PDF forms, see
http://sourceforge.net/projects/acroformtool/ .
17. Why am I getting this "register_frame_info not found" error on Solaris?
After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
generates an error such as:
ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
symbol __register_frame_info: referenced symbol not found
The symbol __register_frame_info is not part of zlib, it is generated by
the C compiler (cc or gcc). You must recompile applications using zlib
which have this problem. This problem is specific to Solaris. See
http://www.sunfreeware.com for Solaris versions of zlib and applications
using zlib.
18. Why does gzip give an error on a file I make with compress/deflate?
The compress and deflate functions produce data in the zlib format, which
is different and incompatible with the gzip format. The gz* functions in
zlib on the other hand use the gzip format. Both the zlib and gzip formats
use the same compressed data format internally, but have different headers
and trailers around the compressed data.
19. Ok, so why are there two different formats?
The gzip format was designed to retain the directory information about a
single file, such as the name and last modification date. The zlib format
on the other hand was designed for in-memory and communication channel
applications, and has a much more compact header and trailer and uses a
faster integrity check than gzip.
20. Well that's nice, but how do I make a gzip file in memory?
You can request that deflate write the gzip format instead of the zlib
format using deflateInit2(). You can also request that inflate decode the
gzip format using inflateInit2(). Read zlib.h for more details.
21. Is zlib thread-safe?
Yes. However any library routines that zlib uses and any application-
provided memory allocation routines must also be thread-safe. zlib's gz*
functions use stdio library routines, and most of zlib's functions use the
library memory allocation routines by default. zlib's *Init* functions
allow for the application to provide custom memory allocation routines.
Of course, you should only operate on any given zlib or gzip stream from a
single thread at a time.
22. Can I use zlib in my commercial application?
Yes. Please read the license in zlib.h.
23. Is zlib under the GNU license?
No. Please read the license in zlib.h.
24. The license says that altered source versions must be "plainly marked". So
what exactly do I need to do to meet that requirement?
You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
particular, the final version number needs to be changed to "f", and an
identification string should be appended to ZLIB_VERSION. Version numbers
x.x.x.f are reserved for modifications to zlib by others than the zlib
maintainers. For example, if the version of the base zlib you are altering
is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
update the version strings in deflate.c and inftrees.c.
For altered source distributions, you should also note the origin and
nature of the changes in zlib.h, as well as in ChangeLog and README, along
with the dates of the alterations. The origin should include at least your
name (or your company's name), and an email address to contact for help or
issues with the library.
Note that distributing a compiled zlib library along with zlib.h and
zconf.h is also a source distribution, and so you should change
ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
in zlib.h as you would for a full source distribution.
25. Will zlib work on a big-endian or little-endian architecture, and can I
exchange compressed data between them?
Yes and yes.
26. Will zlib work on a 64-bit machine?
Yes. It has been tested on 64-bit machines, and has no dependence on any
data types being limited to 32-bits in length. If you have any
difficulties, please provide a complete problem report to zlib@gzip.org
27. Will zlib decompress data from the PKWare Data Compression Library?
No. The PKWare DCL uses a completely different compressed data format than
does PKZIP and zlib. However, you can look in zlib's contrib/blast
directory for a possible solution to your problem.
28. Can I access data randomly in a compressed stream?
No, not without some preparation. If when compressing you periodically use
Z_FULL_FLUSH, carefully write all the pending data at those points, and
keep an index of those locations, then you can start decompression at those
points. You have to be careful to not use Z_FULL_FLUSH too often, since it
can significantly degrade compression. Alternatively, you can scan a
deflate stream once to generate an index, and then use that index for
random access. See examples/zran.c .
29. Does zlib work on MVS, OS/390, CICS, etc.?
It has in the past, but we have not heard of any recent evidence. There
were working ports of zlib 1.1.4 to MVS, but those links no longer work.
If you know of recent, successful applications of zlib on these operating
systems, please let us know. Thanks.
30. Is there some simpler, easier to read version of inflate I can look at to
understand the deflate format?
First off, you should read RFC 1951. Second, yes. Look in zlib's
contrib/puff directory.
31. Does zlib infringe on any patents?
As far as we know, no. In fact, that was originally the whole point behind
zlib. Look here for some more information:
http://www.gzip.org/#faq11
32. Can zlib work with greater than 4 GB of data?
Yes. inflate() and deflate() will process any amount of data correctly.
Each call of inflate() or deflate() is limited to input and output chunks
of the maximum value that can be stored in the compiler's "unsigned int"
type, but there is no limit to the number of chunks. Note however that the
strm.total_in and strm_total_out counters may be limited to 4 GB. These
counters are provided as a convenience and are not used internally by
inflate() or deflate(). The application can easily set up its own counters
updated after each call of inflate() or deflate() to count beyond 4 GB.
compress() and uncompress() may be limited to 4 GB, since they operate in a
single call. gzseek() and gztell() may be limited to 4 GB depending on how
zlib is compiled. See the zlibCompileFlags() function in zlib.h.
The word "may" appears several times above since there is a 4 GB limit only
if the compiler's "long" type is 32 bits. If the compiler's "long" type is
64 bits, then the limit is 16 exabytes.
33. Does zlib have any security vulnerabilities?
The only one that we are aware of is potentially in gzprintf(). If zlib is
compiled to use sprintf() or vsprintf(), then there is no protection
against a buffer overflow of an 8K string space (or other value as set by
gzbuffer()), other than the caller of gzprintf() assuring that the output
will not exceed 8K. On the other hand, if zlib is compiled to use
snprintf() or vsnprintf(), which should normally be the case, then there is
no vulnerability. The ./configure script will display warnings if an
insecure variation of sprintf() will be used by gzprintf(). Also the
zlibCompileFlags() function will return information on what variant of
sprintf() is used by gzprintf().
If you don't have snprintf() or vsnprintf() and would like one, you can
find a portable implementation here:
http://www.ijs.si/software/snprintf/
Note that you should be using the most recent version of zlib. Versions
1.1.3 and before were subject to a double-free vulnerability, and versions
1.2.1 and 1.2.2 were subject to an access exception when decompressing
invalid compressed data.
34. Is there a Java version of zlib?
Probably what you want is to use zlib in Java. zlib is already included
as part of the Java SDK in the java.util.zip package. If you really want
a version of zlib written in the Java language, look on the zlib home
page for links: http://zlib.net/ .
35. I get this or that compiler or source-code scanner warning when I crank it
up to maximally-pedantic. Can't you guys write proper code?
Many years ago, we gave up attempting to avoid warnings on every compiler
in the universe. It just got to be a waste of time, and some compilers
were downright silly as well as contradicted each other. So now, we simply
make sure that the code always works.
36. Valgrind (or some similar memory access checker) says that deflate is
performing a conditional jump that depends on an uninitialized value.
Isn't that a bug?
No. That is intentional for performance reasons, and the output of deflate
is not affected. This only started showing up recently since zlib 1.2.x
uses malloc() by default for allocations, whereas earlier versions used
calloc(), which zeros out the allocated memory. Even though the code was
correct, versions 1.2.4 and later was changed to not stimulate these
checkers.
37. Will zlib read the (insert any ancient or arcane format here) compressed
data format?
Probably not. Look in the comp.compression FAQ for pointers to various
formats and associated software.
38. How can I encrypt/decrypt zip files with zlib?
zlib doesn't support encryption. The original PKZIP encryption is very
weak and can be broken with freely available programs. To get strong
encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib
compression. For PKZIP compatible "encryption", look at
http://www.info-zip.org/
39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
"gzip" is the gzip format, and "deflate" is the zlib format. They should
probably have called the second one "zlib" instead to avoid confusion with
the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
correctly points to the zlib specification in RFC 1950 for the "deflate"
transfer encoding, there have been reports of servers and browsers that
incorrectly produce or expect raw deflate data per the deflate
specification in RFC 1951, most notably Microsoft. So even though the
"deflate" transfer encoding using the zlib format would be the more
efficient approach (and in fact exactly what the zlib format was designed
for), using the "gzip" transfer encoding is probably more reliable due to
an unfortunate choice of name on the part of the HTTP 1.1 authors.
Bottom line: use the gzip format for HTTP 1.1 encoding.
40. Does zlib support the new "Deflate64" format introduced by PKWare?
No. PKWare has apparently decided to keep that format proprietary, since
they have not documented it as they have previous compression formats. In
any case, the compression improvements are so modest compared to other more
modern approaches, that it's not worth the effort to implement.
41. I'm having a problem with the zip functions in zlib, can you help?
There are no zip functions in zlib. You are probably using minizip by
Giles Vollant, which is found in the contrib directory of zlib. It is not
part of zlib. In fact none of the stuff in contrib is part of zlib. The
files in there are not supported by the zlib authors. You need to contact
the authors of the respective contribution for help.
42. The match.asm code in contrib is under the GNU General Public License.
Since it's part of zlib, doesn't that mean that all of zlib falls under the
GNU GPL?
No. The files in contrib are not part of zlib. They were contributed by
other authors and are provided as a convenience to the user within the zlib
distribution. Each item in contrib has its own license.
43. Is zlib subject to export controls? What is its ECCN?
zlib is not subject to export controls, and so is classified as EAR99.
44. Can you please sign these lengthy legal documents and fax them back to us
so that we can use your software in our product?
No. Go away. Shoo.

124
common/zlib/README Normal file
View file

@ -0,0 +1,124 @@
//-----------------------------------------------------------------------------
// This version of zlib is modified for use within the Proxmark3 project.
// Files from the original distribution which are not required for this
// purpose are not included. All modifications can easily be found
// by searching for #ifdef ZLIB_PM3_TUNED and #ifndef ZLIB_PM3_TUNED.
//
// The rest of this file consists of the original README content
//-----------------------------------------------------------------------------
ZLIB DATA COMPRESSION LIBRARY
zlib 1.2.8 is a general purpose data compression library. All the code is
thread safe. The data format used by the zlib library is described by RFCs
(Request for Comments) 1950 to 1952 in the files
http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
rfc1952 (gzip format).
All functions of the compression library are documented in the file zlib.h
(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
of the library is given in the file test/example.c which also tests that
the library is working correctly. Another example is given in the file
test/minigzip.c. The compression library itself is composed of all source
files in the root directory.
To compile all files and run the test program, follow the instructions given at
the top of Makefile.in. In short "./configure; make test", and if that goes
well, "make install" should work for most flavors of Unix. For Windows, use
one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use
make_vms.com.
Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
<info@winimage.com> for the Windows DLL version. The zlib home page is
http://zlib.net/ . Before reporting a problem, please check this site to
verify that you have the latest version of zlib; otherwise get the latest
version and check whether the problem still exists or not.
PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
issue of Dr. Dobb's Journal; a copy of the article is available at
http://marknelson.us/1997/01/01/zlib-engine/ .
The changes made in version 1.2.8 are documented in the file ChangeLog.
Unsupported third party contributions are provided in directory contrib/ .
zlib is available in Java using the java.util.zip package, documented at
http://java.sun.com/developer/technicalArticles/Programming/compression/ .
A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
at CPAN (Comprehensive Perl Archive Network) sites, including
http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
available in Python 1.5 and later versions, see
http://docs.python.org/library/zlib.html .
zlib is built into tcl: http://wiki.tcl.tk/4610 .
An experimental package to read and write files in .zip format, written on top
of zlib by Gilles Vollant <info@winimage.com>, is available in the
contrib/minizip directory of zlib.
Notes for some targets:
- For Windows DLL versions, please see win32/DLL_FAQ.txt
- For 64-bit Irix, deflate.c must be compiled without any optimization. With
-O, one libpng test fails. The test works in 32 bit mode (with the -n32
compiler flag). The compiler bug has been reported to SGI.
- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
when compiled with cc.
- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
necessary to get gzprintf working correctly. This is done by configure.
- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
other compilers. Use "make test" to check your compiler.
- gzdopen is not supported on RISCOS or BEOS.
- For PalmOs, see http://palmzlib.sourceforge.net/
Acknowledgments:
The deflate format used by zlib was defined by Phil Katz. The deflate and
zlib specifications were written by L. Peter Deutsch. Thanks to all the
people who reported problems and suggested various improvements in zlib; they
are too numerous to cite here.
Copyright notice:
(C) 1995-2013 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
If you use the zlib library in a product, we would appreciate *not* receiving
lengthy legal documents to sign. The sources are provided for free but without
warranty of any kind. The library has been entirely written by Jean-loup
Gailly and Mark Adler; it does not include third-party code.
If you redistribute modified sources, we would appreciate that you include in
the file ChangeLog history information documenting your changes. Please read
the FAQ for more information on the distribution of modified source versions.

179
common/zlib/adler32.c Normal file
View file

@ -0,0 +1,179 @@
/* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2011 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "zutil.h"
#define local static
local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
#define BASE 65521 /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
/* use NO_DIVIDE if your processor does not do division in hardware --
try it both ways to see which is faster */
#ifdef NO_DIVIDE
/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
(thank you to John Reiser for pointing this out) */
# define CHOP(a) \
do { \
unsigned long tmp = a >> 16; \
a &= 0xffffUL; \
a += (tmp << 4) - tmp; \
} while (0)
# define MOD28(a) \
do { \
CHOP(a); \
if (a >= BASE) a -= BASE; \
} while (0)
# define MOD(a) \
do { \
CHOP(a); \
MOD28(a); \
} while (0)
# define MOD63(a) \
do { /* this assumes a is not negative */ \
z_off64_t tmp = a >> 32; \
a &= 0xffffffffL; \
a += (tmp << 8) - (tmp << 5) + tmp; \
tmp = a >> 16; \
a &= 0xffffL; \
a += (tmp << 4) - tmp; \
tmp = a >> 16; \
a &= 0xffffL; \
a += (tmp << 4) - tmp; \
if (a >= BASE) a -= BASE; \
} while (0)
#else
# define MOD(a) a %= BASE
# define MOD28(a) a %= BASE
# define MOD63(a) a %= BASE
#endif
/* ========================================================================= */
uLong ZEXPORT adler32(adler, buf, len)
uLong adler;
const Bytef *buf;
uInt len;
{
unsigned long sum2;
unsigned n;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == Z_NULL)
return 1L;
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD28(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf);
buf += 16;
}
while (len--) {
adler += *buf++;
sum2 += adler;
}
MOD(adler);
MOD(sum2);
}
/* return recombined sums */
return adler | (sum2 << 16);
}
/* ========================================================================= */
local uLong adler32_combine_(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off64_t len2;
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* for negative len, return invalid adler32 as a clue for debugging */
if (len2 < 0)
return 0xffffffffUL;
/* the derivation of this formula is left as an exercise for the reader */
MOD63(len2); /* assumes len2 >= 0 */
rem = (unsigned)len2;
sum1 = adler1 & 0xffff;
sum2 = rem * sum1;
MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}
uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off64_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}

2056
common/zlib/deflate.c Normal file

File diff suppressed because it is too large Load diff

346
common/zlib/deflate.h Normal file
View file

@ -0,0 +1,346 @@
/* deflate.h -- internal compression state
* Copyright (C) 1995-2012 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef DEFLATE_H
#define DEFLATE_H
#include "zutil.h"
/* define NO_GZIP when compiling if you want to disable gzip header and
trailer creation by deflate(). NO_GZIP would be used to avoid linking in
the crc code when it is not needed. For shared libraries, gzip encoding
should be left enabled. */
#ifndef NO_GZIP
# define GZIP
#endif
/* ===========================================================================
* Internal compression state.
*/
#define LENGTH_CODES 29
/* number of length codes, not counting the special END_BLOCK code */
#define LITERALS 256
/* number of literal bytes 0..255 */
#define L_CODES (LITERALS+1+LENGTH_CODES)
/* number of Literal or Length codes, including the END_BLOCK code */
#define D_CODES 30
/* number of distance codes */
#define BL_CODES 19
/* number of codes used to transfer the bit lengths */
#define HEAP_SIZE (2*L_CODES+1)
/* maximum heap size */
#define MAX_BITS 15
/* All codes must not exceed MAX_BITS bits */
#define Buf_size 16
/* size of bit buffer in bi_buf */
#define INIT_STATE 42
#define EXTRA_STATE 69
#define NAME_STATE 73
#define COMMENT_STATE 91
#define HCRC_STATE 103
#define BUSY_STATE 113
#define FINISH_STATE 666
/* Stream status */
/* Data structure describing a single value and its code string. */
typedef struct ct_data_s {
union {
ush freq; /* frequency count */
ush code; /* bit string */
} fc;
union {
ush dad; /* father node in Huffman tree */
ush len; /* length of bit string */
} dl;
} FAR ct_data;
#define Freq fc.freq
#define Code fc.code
#define Dad dl.dad
#define Len dl.len
typedef struct static_tree_desc_s static_tree_desc;
typedef struct tree_desc_s {
ct_data *dyn_tree; /* the dynamic tree */
int max_code; /* largest code with non zero frequency */
static_tree_desc *stat_desc; /* the corresponding static tree */
} FAR tree_desc;
typedef ush Pos;
typedef Pos FAR Posf;
typedef unsigned IPos;
/* A Pos is an index in the character window. We use short instead of int to
* save space in the various tables. IPos is used only for parameter passing.
*/
typedef struct internal_state {
z_streamp strm; /* pointer back to this zlib stream */
int status; /* as the name implies */
Bytef *pending_buf; /* output still pending */
ulg pending_buf_size; /* size of pending_buf */
Bytef *pending_out; /* next pending byte to output to the stream */
uInt pending; /* nb of bytes in the pending buffer */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
gz_headerp gzhead; /* gzip header information to write */
uInt gzindex; /* where in extra, name, or comment */
Byte method; /* can only be DEFLATED */
int last_flush; /* value of flush param for previous deflate call */
/* used by deflate.c: */
uInt w_size; /* LZ77 window size (32K by default) */
uInt w_bits; /* log2(w_size) (8..16) */
uInt w_mask; /* w_size - 1 */
Bytef *window;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size. Also, it limits
* the window size to 64K, which is quite useful on MSDOS.
* To do: use the user input buffer as sliding window.
*/
ulg window_size;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
Posf *prev;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
Posf *head; /* Heads of the hash chains or NIL. */
uInt ins_h; /* hash index of string to be inserted */
uInt hash_size; /* number of elements in hash table */
uInt hash_bits; /* log2(hash_size) */
uInt hash_mask; /* hash_size-1 */
uInt hash_shift;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
long block_start;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
uInt match_length; /* length of best match */
IPos prev_match; /* previous match */
int match_available; /* set if previous match exists */
uInt strstart; /* start of string to insert */
uInt match_start; /* start of matching string */
uInt lookahead; /* number of valid bytes ahead in window */
uInt prev_length;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
uInt max_chain_length;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
uInt max_lazy_match;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
# define max_insert_length max_lazy_match
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
int level; /* compression level (1..9) */
int strategy; /* favor or force Huffman coding*/
uInt good_match;
/* Use a faster search when the previous match is longer than this */
int nice_match; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
struct ct_data_s dyn_dtree[2 * D_CODES + 1]; /* distance tree */
struct ct_data_s bl_tree[2 * BL_CODES + 1]; /* Huffman tree for bit lengths */
struct tree_desc_s l_desc; /* desc. for literal tree */
struct tree_desc_s d_desc; /* desc. for distance tree */
struct tree_desc_s bl_desc; /* desc. for bit length tree */
ush bl_count[MAX_BITS + 1];
/* number of codes at each bit length for an optimal tree */
int heap[2 * L_CODES + 1]; /* heap used to build the Huffman trees */
int heap_len; /* number of elements in the heap */
int heap_max; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
uch depth[2 * L_CODES + 1];
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
uchf *l_buf; /* buffer for literals or lengths */
uInt lit_bufsize;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
uInt last_lit; /* running index in l_buf */
ushf *d_buf;
/* Buffer for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
ulg opt_len; /* bit length of current block with optimal trees */
ulg static_len; /* bit length of current block with static trees */
uInt matches; /* number of string matches in current block */
uInt insert; /* bytes at end of window left to insert */
#ifdef DEBUG
ulg compressed_len; /* total bit length of compressed file mod 2^32 */
ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
#endif
ush bi_buf;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
int bi_valid;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
ulg high_water;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
} FAR deflate_state;
/* Output a byte on the stream.
* IN assertion: there is enough room in pending_buf.
*/
#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
/* Minimum amount of lookahead, except at the end of the input file.
* See deflate.c for comments about the MIN_MATCH+1.
*/
#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
/* In order to simplify the code, particularly on 16 bit machines, match
* distances are limited to MAX_DIST instead of WSIZE.
*/
#define WIN_INIT MAX_MATCH
/* Number of bytes after end of data in window to initialize in order to avoid
memory checker errors from longest match routines */
/* in trees.c */
void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
ulg stored_len, int last));
void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
ulg stored_len, int last));
#define d_code(dist) \
((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. _dist_code[256] and _dist_code[257] are never
* used.
*/
#ifndef DEBUG
/* Inline versions of _tr_tally for speed: */
#if defined(GEN_TREES_H) || !defined(STDC)
extern uch ZLIB_INTERNAL _length_code[];
extern uch ZLIB_INTERNAL _dist_code[];
#else
extern const uch ZLIB_INTERNAL _length_code[];
extern const uch ZLIB_INTERNAL _dist_code[];
#endif
# define _tr_tally_lit(s, c, flush) \
{ uch cc = (c); \
s->d_buf[s->last_lit] = 0; \
s->l_buf[s->last_lit++] = cc; \
s->dyn_ltree[cc].Freq++; \
flush = (s->last_lit == s->lit_bufsize-1); \
}
# define _tr_tally_dist(s, distance, length, flush) \
{ uch len = (length); \
ush dist = (distance); \
s->d_buf[s->last_lit] = dist; \
s->l_buf[s->last_lit++] = len; \
dist--; \
s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
s->dyn_dtree[d_code(dist)].Freq++; \
flush = (s->last_lit == s->lit_bufsize-1); \
}
#else
# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
# define _tr_tally_dist(s, distance, length, flush) \
flush = _tr_tally(s, distance, length)
#endif
#endif /* DEFLATE_H */

331
common/zlib/inffast.c Normal file
View file

@ -0,0 +1,331 @@
/* inffast.c -- fast decoding
* Copyright (C) 1995-2008, 2010, 2013 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "inftrees.h"
#include "inflate.h"
#include "inffast.h"
#ifndef ASMINF
/* Allow machine dependent optimization for post-increment or pre-increment.
Based on testing to date,
Pre-increment preferred for:
- PowerPC G3 (Adler)
- MIPS R5000 (Randers-Pehrson)
Post-increment preferred for:
- none
No measurable difference:
- Pentium III (Anderson)
- M68060 (Nikl)
*/
#ifdef POSTINC
# define OFF 0
# define PUP(a) *(a)++
#else
# define OFF 1
# define PUP(a) *++(a)
#endif
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state->mode == LEN
strm->avail_in >= 6
strm->avail_out >= 258
start >= strm->avail_out
state->bits < 8
On return, state->mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm->avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm->avail_out >= 258 for each loop to avoid checking for
output space.
*/
void ZLIB_INTERNAL inflate_fast(strm, start)
z_streamp strm;
unsigned start; /* inflate()'s starting value for strm->avail_out */
{
struct inflate_state FAR *state;
z_const unsigned char FAR *in; /* local strm->next_in */
z_const unsigned char FAR *last; /* have enough input while in < last */
unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */
code const FAR *lcode; /* local strm->lencode */
code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */
code here; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */
unsigned dist; /* match distance */
unsigned char FAR *from; /* where to copy match from */
/* copy state to local variables */
state = (struct inflate_state FAR *)strm->state;
in = strm->next_in - OFF;
last = in + (strm->avail_in - 5);
out = strm->next_out - OFF;
beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize;
whave = state->whave;
wnext = state->wnext;
window = state->window;
hold = state->hold;
bits = state->bits;
lcode = state->lencode;
dcode = state->distcode;
lmask = (1U << state->lenbits) - 1;
dmask = (1U << state->distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
do {
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op == 0) { /* literal */
Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", here.val));
PUP(out) = (unsigned char)(here.val);
} else if (op & 16) { /* length base */
len = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
len += (unsigned)hold & ((1U << op) - 1);
hold >>= op;
bits -= op;
}
Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
op = (unsigned)(here.bits);
hold >>= op;
bits -= op;
op = (unsigned)(here.op);
if (op & 16) { /* distance base */
dist = (unsigned)(here.val);
op &= 15; /* number of extra bits */
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits;
bits += 8;
}
}
dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op;
bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist));
op = (unsigned)(out - beg); /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state->sane) {
strm->msg =
(char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (len <= op - whave) {
do {
PUP(out) = 0;
} while (--len);
continue;
}
len -= op - whave;
do {
PUP(out) = 0;
} while (--op > whave);
if (op == 0) {
from = out - dist;
do {
PUP(out) = PUP(from);
} while (--len);
continue;
}
#endif
}
from = window - OFF;
if (wnext == 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
} else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = window - OFF;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
} else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
PUP(out) = PUP(from);
} while (--op);
from = out - dist; /* rest from output */
}
}
while (len > 2) {
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
}
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
} else {
from = out - dist; /* copy direct from output */
do { /* minimum length is three */
PUP(out) = PUP(from);
PUP(out) = PUP(from);
PUP(out) = PUP(from);
len -= 3;
} while (len > 2);
if (len) {
PUP(out) = PUP(from);
if (len > 1)
PUP(out) = PUP(from);
}
}
} else if ((op & 64) == 0) { /* 2nd level distance code */
here = dcode[here.val + (hold & ((1U << op) - 1))];
goto dodist;
} else {
strm->msg = (char *)"invalid distance code";
state->mode = BAD;
break;
}
} else if ((op & 64) == 0) { /* 2nd level length code */
here = lcode[here.val + (hold & ((1U << op) - 1))];
goto dolen;
} else if (op & 32) { /* end-of-block */
Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE;
break;
} else {
strm->msg = (char *)"invalid literal/length code";
state->mode = BAD;
break;
}
} while (in < last && out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
in -= len;
bits -= len << 3;
hold &= (1U << bits) - 1;
/* update state and return */
strm->next_in = in + OFF;
strm->next_out = out + OFF;
strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
strm->avail_out = (unsigned)(out < end ?
257 + (end - out) : 257 - (out - end));
state->hold = hold;
state->bits = bits;
return;
}
/*
inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
- Using bit fields for code structure
- Different op definition to avoid & for extra bits (do & for table bits)
- Three separate decoding do-loops for direct, window, and wnext == 0
- Special case for distance > 1 copies to do overlapped load and store copy
- Explicit branch predictions (based on measured branch probabilities)
- Deferring match copy and interspersed it with decoding subsequent codes
- Swapping literal/length else
- Swapping window/direct else
- Larger unrolled copy loops (three is about right)
- Moving len -= 3 statement into middle of loop
*/
#endif /* !ASMINF */

11
common/zlib/inffast.h Normal file
View file

@ -0,0 +1,11 @@
/* inffast.h -- header to use inffast.c
* Copyright (C) 1995-2003, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));

94
common/zlib/inffixed.h Normal file
View file

@ -0,0 +1,94 @@
/* inffixed.h -- table for decoding fixed codes
* Generated automatically by makefixed().
*/
/* WARNING: this file should *not* be used by applications.
It is part of the implementation of this library and is
subject to change. Applications should only use zlib.h.
*/
static const code lenfix[512] = {
{96, 7, 0}, {0, 8, 80}, {0, 8, 16}, {20, 8, 115}, {18, 7, 31}, {0, 8, 112}, {0, 8, 48},
{0, 9, 192}, {16, 7, 10}, {0, 8, 96}, {0, 8, 32}, {0, 9, 160}, {0, 8, 0}, {0, 8, 128},
{0, 8, 64}, {0, 9, 224}, {16, 7, 6}, {0, 8, 88}, {0, 8, 24}, {0, 9, 144}, {19, 7, 59},
{0, 8, 120}, {0, 8, 56}, {0, 9, 208}, {17, 7, 17}, {0, 8, 104}, {0, 8, 40}, {0, 9, 176},
{0, 8, 8}, {0, 8, 136}, {0, 8, 72}, {0, 9, 240}, {16, 7, 4}, {0, 8, 84}, {0, 8, 20},
{21, 8, 227}, {19, 7, 43}, {0, 8, 116}, {0, 8, 52}, {0, 9, 200}, {17, 7, 13}, {0, 8, 100},
{0, 8, 36}, {0, 9, 168}, {0, 8, 4}, {0, 8, 132}, {0, 8, 68}, {0, 9, 232}, {16, 7, 8},
{0, 8, 92}, {0, 8, 28}, {0, 9, 152}, {20, 7, 83}, {0, 8, 124}, {0, 8, 60}, {0, 9, 216},
{18, 7, 23}, {0, 8, 108}, {0, 8, 44}, {0, 9, 184}, {0, 8, 12}, {0, 8, 140}, {0, 8, 76},
{0, 9, 248}, {16, 7, 3}, {0, 8, 82}, {0, 8, 18}, {21, 8, 163}, {19, 7, 35}, {0, 8, 114},
{0, 8, 50}, {0, 9, 196}, {17, 7, 11}, {0, 8, 98}, {0, 8, 34}, {0, 9, 164}, {0, 8, 2},
{0, 8, 130}, {0, 8, 66}, {0, 9, 228}, {16, 7, 7}, {0, 8, 90}, {0, 8, 26}, {0, 9, 148},
{20, 7, 67}, {0, 8, 122}, {0, 8, 58}, {0, 9, 212}, {18, 7, 19}, {0, 8, 106}, {0, 8, 42},
{0, 9, 180}, {0, 8, 10}, {0, 8, 138}, {0, 8, 74}, {0, 9, 244}, {16, 7, 5}, {0, 8, 86},
{0, 8, 22}, {64, 8, 0}, {19, 7, 51}, {0, 8, 118}, {0, 8, 54}, {0, 9, 204}, {17, 7, 15},
{0, 8, 102}, {0, 8, 38}, {0, 9, 172}, {0, 8, 6}, {0, 8, 134}, {0, 8, 70}, {0, 9, 236},
{16, 7, 9}, {0, 8, 94}, {0, 8, 30}, {0, 9, 156}, {20, 7, 99}, {0, 8, 126}, {0, 8, 62},
{0, 9, 220}, {18, 7, 27}, {0, 8, 110}, {0, 8, 46}, {0, 9, 188}, {0, 8, 14}, {0, 8, 142},
{0, 8, 78}, {0, 9, 252}, {96, 7, 0}, {0, 8, 81}, {0, 8, 17}, {21, 8, 131}, {18, 7, 31},
{0, 8, 113}, {0, 8, 49}, {0, 9, 194}, {16, 7, 10}, {0, 8, 97}, {0, 8, 33}, {0, 9, 162},
{0, 8, 1}, {0, 8, 129}, {0, 8, 65}, {0, 9, 226}, {16, 7, 6}, {0, 8, 89}, {0, 8, 25},
{0, 9, 146}, {19, 7, 59}, {0, 8, 121}, {0, 8, 57}, {0, 9, 210}, {17, 7, 17}, {0, 8, 105},
{0, 8, 41}, {0, 9, 178}, {0, 8, 9}, {0, 8, 137}, {0, 8, 73}, {0, 9, 242}, {16, 7, 4},
{0, 8, 85}, {0, 8, 21}, {16, 8, 258}, {19, 7, 43}, {0, 8, 117}, {0, 8, 53}, {0, 9, 202},
{17, 7, 13}, {0, 8, 101}, {0, 8, 37}, {0, 9, 170}, {0, 8, 5}, {0, 8, 133}, {0, 8, 69},
{0, 9, 234}, {16, 7, 8}, {0, 8, 93}, {0, 8, 29}, {0, 9, 154}, {20, 7, 83}, {0, 8, 125},
{0, 8, 61}, {0, 9, 218}, {18, 7, 23}, {0, 8, 109}, {0, 8, 45}, {0, 9, 186}, {0, 8, 13},
{0, 8, 141}, {0, 8, 77}, {0, 9, 250}, {16, 7, 3}, {0, 8, 83}, {0, 8, 19}, {21, 8, 195},
{19, 7, 35}, {0, 8, 115}, {0, 8, 51}, {0, 9, 198}, {17, 7, 11}, {0, 8, 99}, {0, 8, 35},
{0, 9, 166}, {0, 8, 3}, {0, 8, 131}, {0, 8, 67}, {0, 9, 230}, {16, 7, 7}, {0, 8, 91},
{0, 8, 27}, {0, 9, 150}, {20, 7, 67}, {0, 8, 123}, {0, 8, 59}, {0, 9, 214}, {18, 7, 19},
{0, 8, 107}, {0, 8, 43}, {0, 9, 182}, {0, 8, 11}, {0, 8, 139}, {0, 8, 75}, {0, 9, 246},
{16, 7, 5}, {0, 8, 87}, {0, 8, 23}, {64, 8, 0}, {19, 7, 51}, {0, 8, 119}, {0, 8, 55},
{0, 9, 206}, {17, 7, 15}, {0, 8, 103}, {0, 8, 39}, {0, 9, 174}, {0, 8, 7}, {0, 8, 135},
{0, 8, 71}, {0, 9, 238}, {16, 7, 9}, {0, 8, 95}, {0, 8, 31}, {0, 9, 158}, {20, 7, 99},
{0, 8, 127}, {0, 8, 63}, {0, 9, 222}, {18, 7, 27}, {0, 8, 111}, {0, 8, 47}, {0, 9, 190},
{0, 8, 15}, {0, 8, 143}, {0, 8, 79}, {0, 9, 254}, {96, 7, 0}, {0, 8, 80}, {0, 8, 16},
{20, 8, 115}, {18, 7, 31}, {0, 8, 112}, {0, 8, 48}, {0, 9, 193}, {16, 7, 10}, {0, 8, 96},
{0, 8, 32}, {0, 9, 161}, {0, 8, 0}, {0, 8, 128}, {0, 8, 64}, {0, 9, 225}, {16, 7, 6},
{0, 8, 88}, {0, 8, 24}, {0, 9, 145}, {19, 7, 59}, {0, 8, 120}, {0, 8, 56}, {0, 9, 209},
{17, 7, 17}, {0, 8, 104}, {0, 8, 40}, {0, 9, 177}, {0, 8, 8}, {0, 8, 136}, {0, 8, 72},
{0, 9, 241}, {16, 7, 4}, {0, 8, 84}, {0, 8, 20}, {21, 8, 227}, {19, 7, 43}, {0, 8, 116},
{0, 8, 52}, {0, 9, 201}, {17, 7, 13}, {0, 8, 100}, {0, 8, 36}, {0, 9, 169}, {0, 8, 4},
{0, 8, 132}, {0, 8, 68}, {0, 9, 233}, {16, 7, 8}, {0, 8, 92}, {0, 8, 28}, {0, 9, 153},
{20, 7, 83}, {0, 8, 124}, {0, 8, 60}, {0, 9, 217}, {18, 7, 23}, {0, 8, 108}, {0, 8, 44},
{0, 9, 185}, {0, 8, 12}, {0, 8, 140}, {0, 8, 76}, {0, 9, 249}, {16, 7, 3}, {0, 8, 82},
{0, 8, 18}, {21, 8, 163}, {19, 7, 35}, {0, 8, 114}, {0, 8, 50}, {0, 9, 197}, {17, 7, 11},
{0, 8, 98}, {0, 8, 34}, {0, 9, 165}, {0, 8, 2}, {0, 8, 130}, {0, 8, 66}, {0, 9, 229},
{16, 7, 7}, {0, 8, 90}, {0, 8, 26}, {0, 9, 149}, {20, 7, 67}, {0, 8, 122}, {0, 8, 58},
{0, 9, 213}, {18, 7, 19}, {0, 8, 106}, {0, 8, 42}, {0, 9, 181}, {0, 8, 10}, {0, 8, 138},
{0, 8, 74}, {0, 9, 245}, {16, 7, 5}, {0, 8, 86}, {0, 8, 22}, {64, 8, 0}, {19, 7, 51},
{0, 8, 118}, {0, 8, 54}, {0, 9, 205}, {17, 7, 15}, {0, 8, 102}, {0, 8, 38}, {0, 9, 173},
{0, 8, 6}, {0, 8, 134}, {0, 8, 70}, {0, 9, 237}, {16, 7, 9}, {0, 8, 94}, {0, 8, 30},
{0, 9, 157}, {20, 7, 99}, {0, 8, 126}, {0, 8, 62}, {0, 9, 221}, {18, 7, 27}, {0, 8, 110},
{0, 8, 46}, {0, 9, 189}, {0, 8, 14}, {0, 8, 142}, {0, 8, 78}, {0, 9, 253}, {96, 7, 0},
{0, 8, 81}, {0, 8, 17}, {21, 8, 131}, {18, 7, 31}, {0, 8, 113}, {0, 8, 49}, {0, 9, 195},
{16, 7, 10}, {0, 8, 97}, {0, 8, 33}, {0, 9, 163}, {0, 8, 1}, {0, 8, 129}, {0, 8, 65},
{0, 9, 227}, {16, 7, 6}, {0, 8, 89}, {0, 8, 25}, {0, 9, 147}, {19, 7, 59}, {0, 8, 121},
{0, 8, 57}, {0, 9, 211}, {17, 7, 17}, {0, 8, 105}, {0, 8, 41}, {0, 9, 179}, {0, 8, 9},
{0, 8, 137}, {0, 8, 73}, {0, 9, 243}, {16, 7, 4}, {0, 8, 85}, {0, 8, 21}, {16, 8, 258},
{19, 7, 43}, {0, 8, 117}, {0, 8, 53}, {0, 9, 203}, {17, 7, 13}, {0, 8, 101}, {0, 8, 37},
{0, 9, 171}, {0, 8, 5}, {0, 8, 133}, {0, 8, 69}, {0, 9, 235}, {16, 7, 8}, {0, 8, 93},
{0, 8, 29}, {0, 9, 155}, {20, 7, 83}, {0, 8, 125}, {0, 8, 61}, {0, 9, 219}, {18, 7, 23},
{0, 8, 109}, {0, 8, 45}, {0, 9, 187}, {0, 8, 13}, {0, 8, 141}, {0, 8, 77}, {0, 9, 251},
{16, 7, 3}, {0, 8, 83}, {0, 8, 19}, {21, 8, 195}, {19, 7, 35}, {0, 8, 115}, {0, 8, 51},
{0, 9, 199}, {17, 7, 11}, {0, 8, 99}, {0, 8, 35}, {0, 9, 167}, {0, 8, 3}, {0, 8, 131},
{0, 8, 67}, {0, 9, 231}, {16, 7, 7}, {0, 8, 91}, {0, 8, 27}, {0, 9, 151}, {20, 7, 67},
{0, 8, 123}, {0, 8, 59}, {0, 9, 215}, {18, 7, 19}, {0, 8, 107}, {0, 8, 43}, {0, 9, 183},
{0, 8, 11}, {0, 8, 139}, {0, 8, 75}, {0, 9, 247}, {16, 7, 5}, {0, 8, 87}, {0, 8, 23},
{64, 8, 0}, {19, 7, 51}, {0, 8, 119}, {0, 8, 55}, {0, 9, 207}, {17, 7, 15}, {0, 8, 103},
{0, 8, 39}, {0, 9, 175}, {0, 8, 7}, {0, 8, 135}, {0, 8, 71}, {0, 9, 239}, {16, 7, 9},
{0, 8, 95}, {0, 8, 31}, {0, 9, 159}, {20, 7, 99}, {0, 8, 127}, {0, 8, 63}, {0, 9, 223},
{18, 7, 27}, {0, 8, 111}, {0, 8, 47}, {0, 9, 191}, {0, 8, 15}, {0, 8, 143}, {0, 8, 79},
{0, 9, 255}
};
static const code distfix[32] = {
{16, 5, 1}, {23, 5, 257}, {19, 5, 17}, {27, 5, 4097}, {17, 5, 5}, {25, 5, 1025},
{21, 5, 65}, {29, 5, 16385}, {16, 5, 3}, {24, 5, 513}, {20, 5, 33}, {28, 5, 8193},
{18, 5, 9}, {26, 5, 2049}, {22, 5, 129}, {64, 5, 0}, {16, 5, 2}, {23, 5, 385},
{19, 5, 25}, {27, 5, 6145}, {17, 5, 7}, {25, 5, 1537}, {21, 5, 97}, {29, 5, 24577},
{16, 5, 4}, {24, 5, 769}, {20, 5, 49}, {28, 5, 12289}, {18, 5, 13}, {26, 5, 3073},
{22, 5, 193}, {64, 5, 0}
};

1522
common/zlib/inflate.c Normal file

File diff suppressed because it is too large Load diff

122
common/zlib/inflate.h Normal file
View file

@ -0,0 +1,122 @@
/* inflate.h -- internal inflate state definition
* Copyright (C) 1995-2009 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* define NO_GZIP when compiling if you want to disable gzip header and
trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
the crc code when it is not needed. For shared libraries, gzip decoding
should be left enabled. */
#ifndef NO_GZIP
# define GUNZIP
#endif
/* Possible inflate modes between inflate() calls */
typedef enum {
HEAD, /* i: waiting for magic header */
FLAGS, /* i: waiting for method and flags (gzip) */
TIME, /* i: waiting for modification time (gzip) */
OS, /* i: waiting for extra flags and operating system (gzip) */
EXLEN, /* i: waiting for extra length (gzip) */
EXTRA, /* i: waiting for extra bytes (gzip) */
NAME, /* i: waiting for end of file name (gzip) */
COMMENT, /* i: waiting for end of comment (gzip) */
HCRC, /* i: waiting for header crc (gzip) */
DICTID, /* i: waiting for dictionary check value */
DICT, /* waiting for inflateSetDictionary() call */
TYPE, /* i: waiting for type bits, including last-flag bit */
TYPEDO, /* i: same, but skip check to exit inflate on new block */
STORED, /* i: waiting for stored size (length and complement) */
COPY_, /* i/o: same as COPY below, but only first time in */
COPY, /* i/o: waiting for input or output to copy stored block */
TABLE, /* i: waiting for dynamic block table lengths */
LENLENS, /* i: waiting for code length code lengths */
CODELENS, /* i: waiting for length/lit and distance code lengths */
LEN_, /* i: same as LEN below, but only first time in */
LEN, /* i: waiting for length/lit/eob code */
LENEXT, /* i: waiting for length extra bits */
DIST, /* i: waiting for distance code */
DISTEXT, /* i: waiting for distance extra bits */
MATCH, /* o: waiting for output space to copy string */
LIT, /* o: waiting for output space to write literal */
CHECK, /* i: waiting for 32-bit check value */
LENGTH, /* i: waiting for 32-bit length (gzip) */
DONE, /* finished check, done -- remain here until reset */
BAD, /* got a data error -- remain here until reset */
MEM, /* got an inflate() memory error -- remain here until reset */
SYNC /* looking for synchronization bytes to restart inflate() */
} inflate_mode;
/*
State transitions between above modes -
(most modes can go to BAD or MEM on error -- not shown for clarity)
Process header:
HEAD -> (gzip) or (zlib) or (raw)
(gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
HCRC -> TYPE
(zlib) -> DICTID or TYPE
DICTID -> DICT -> TYPE
(raw) -> TYPEDO
Read deflate blocks:
TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
STORED -> COPY_ -> COPY -> TYPE
TABLE -> LENLENS -> CODELENS -> LEN_
LEN_ -> LEN
Read deflate codes in fixed or dynamic block:
LEN -> LENEXT or LIT or TYPE
LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
LIT -> LEN
Process trailer:
CHECK -> LENGTH -> DONE
*/
/* state maintained between inflate() calls. Approximately 10K bytes. */
struct inflate_state {
inflate_mode mode; /* current inflate mode */
int last; /* true if processing last block */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
int havedict; /* true if dictionary provided */
int flags; /* gzip header method and flags (0 if zlib) */
unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
unsigned long check; /* protected copy of check value */
unsigned long total; /* protected copy of output count */
gz_headerp head; /* where to save gzip header information */
/* sliding window */
unsigned wbits; /* log base 2 of requested window size */
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if needed */
/* bit accumulator */
unsigned long hold; /* input bit accumulator */
unsigned bits; /* number of bits in "in" */
/* for string and stored block copying */
unsigned length; /* literal or length of data to copy */
unsigned offset; /* distance back to copy string from */
/* for table and code decoding */
unsigned extra; /* extra bits needed */
/* fixed and dynamic code tables */
code const FAR *lencode; /* starting table for length/literal codes */
code const FAR *distcode; /* starting table for distance codes */
unsigned lenbits; /* index bits for lencode */
unsigned distbits; /* index bits for distcode */
/* dynamic table building */
unsigned ncode; /* number of code length code lengths */
unsigned nlen; /* number of length code lengths */
unsigned ndist; /* number of distance code lengths */
unsigned have; /* number of code lengths in lens[] */
code FAR *next; /* next available space in codes[] */
unsigned short lens[320]; /* temporary storage for code lengths */
unsigned short work[288]; /* work area for code table building */
code codes[ENOUGH]; /* space for code tables */
int sane; /* if false, allow invalid distance too far */
int back; /* bits back of last unprocessed length/lit */
unsigned was; /* initial length of match */
};

302
common/zlib/inftrees.c Normal file
View file

@ -0,0 +1,302 @@
/* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2013 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "inftrees.h"
#define MAXBITS 15
const char inflate_copyright[] =
" inflate 1.2.8.f-Proxmark3 Copyright 1995-2013 Mark Adler ";
/*
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/*
Build a set of tables to decode the provided canonical Huffman code.
The code lengths are lens[0..codes-1]. The result starts at *table,
whose indices are 0..2^bits-1. work is a writable array of at least
lens shorts, which is used as a work area. type is the type of code
to be generated, CODES, LENS, or DISTS. On return, zero is success,
-1 is an invalid code, and +1 means that ENOUGH isn't enough. table
on return points to the next available entry's address. bits is the
requested root table index bits, and on return it is the actual root
table index bits. It will differ if the request is greater than the
longest code or if it is less than the shortest code.
*/
int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
unsigned codes, code FAR *FAR *table,
unsigned FAR *bits, unsigned short FAR *work) {
unsigned len; /* a code's length in bits */
unsigned sym; /* index of code symbols */
unsigned min, max; /* minimum and maximum code lengths */
unsigned root; /* number of index bits for root table */
unsigned curr; /* number of index bits for current table */
unsigned drop; /* code bits to drop for sub-table */
int left; /* number of prefix codes available */
unsigned used; /* code entries in table used */
unsigned huff; /* Huffman code */
unsigned incr; /* for incrementing code, index */
unsigned fill; /* index for replicating entries */
unsigned low; /* low bits for current root entry */
unsigned mask; /* mask for low root bits */
code here; /* table entry for duplication */
code FAR *next; /* next available space in table */
const unsigned short FAR *base; /* base value table to use */
const unsigned short FAR *extra; /* extra bits table to use */
int end; /* use base and extra for symbol > end */
unsigned short count[MAXBITS + 1]; /* number of codes of each length */
unsigned short offs[MAXBITS + 1]; /* offsets in table for each length */
static const unsigned short lbase[31] = { /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
static const unsigned short lext[31] = { /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
};
static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
};
static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
};
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++)
count[len] = 0;
for (sym = 0; sym < codes; sym++)
count[lens[sym]]++;
/* bound code lengths, force root to be within code lengths */
root = *bits;
for (max = MAXBITS; max >= 1; max--)
if (count[max] != 0) break;
if (root > max) root = max;
if (max == 0) { /* no symbols to code at all */
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)1;
here.val = (unsigned short)0;
*(*table)++ = here; /* make a table to force an error */
*(*table)++ = here;
*bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++)
if (count[min] != 0) break;
if (root < min) root = min;
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) return -1; /* over-subscribed */
}
if (left > 0 && (type == CODES || max != 1))
return -1; /* incomplete set */
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++)
offs[len + 1] = offs[len] + count[len];
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++)
if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
switch (type) {
case CODES:
base = extra = work; /* dummy value--not used */
end = 19;
break;
case LENS:
base = lbase;
base -= 257;
extra = lext;
extra -= 257;
end = 256;
break;
default: /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize state for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = *table; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = (unsigned)(-1); /* trigger new sub-table when len > root */
used = 1U << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type == LENS && used > ENOUGH_LENS) ||
(type == DISTS && used > ENOUGH_DISTS))
return 1;
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here.bits = (unsigned char)(len - drop);
if ((int)(work[sym]) < end) {
here.op = (unsigned char)0;
here.val = work[sym];
} else if ((int)(work[sym]) > end) {
here.op = (unsigned char)(extra[work[sym]]);
here.val = base[work[sym]];
} else {
here.op = (unsigned char)(32 + 64); /* end of block */
here.val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1U << (len - drop);
fill = 1U << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
next[(huff >> drop) + fill] = here;
} while (fill != 0);
/* backwards increment the len-bit code huff */
incr = 1U << (len - 1);
while (huff & incr)
incr >>= 1;
if (incr != 0) {
huff &= incr - 1;
huff += incr;
} else
huff = 0;
/* go to next symbol, update count, len */
sym++;
if (--(count[len]) == 0) {
if (len == max) break;
len = lens[work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) != low) {
/* if first time, transition to sub-tables */
if (drop == 0)
drop = root;
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = (int)(1 << curr);
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) break;
curr++;
left <<= 1;
}
/* check for enough space */
used += 1U << curr;
if ((type == LENS && used > ENOUGH_LENS) ||
(type == DISTS && used > ENOUGH_DISTS))
return 1;
/* point entry in root table to sub-table */
low = huff & mask;
(*table)[low].op = (unsigned char)curr;
(*table)[low].bits = (unsigned char)root;
(*table)[low].val = (unsigned short)(next - *table);
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff != 0) {
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)(len - drop);
here.val = (unsigned short)0;
next[huff] = here;
}
/* set return parameters */
*table += used;
*bits = root;
return 0;
}

62
common/zlib/inftrees.h Normal file
View file

@ -0,0 +1,62 @@
/* inftrees.h -- header to use inftrees.c
* Copyright (C) 1995-2005, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* Structure for decoding tables. Each entry provides either the
information needed to do the operation requested by the code that
indexed that table entry, or it provides a pointer to another
table that indexes more bits of the code. op indicates whether
the entry is a pointer to another table, a literal, a length or
distance, an end-of-block, or an invalid code. For a table
pointer, the low four bits of op is the number of index bits of
that table. For a length or distance, the low four bits of op
is the number of extra bits to get after the code. bits is
the number of bits in this code or part of the code to drop off
of the bit buffer. val is the actual byte to output in the case
of a literal, the base length or distance, or the offset from
the current table to the next table. Each entry is four bytes. */
typedef struct {
unsigned char op; /* operation, extra bits, table bits */
unsigned char bits; /* bits in this part of the code */
unsigned short val; /* offset in table or code value */
} code;
/* op values as set by inflate_table():
00000000 - literal
0000tttt - table link, tttt != 0 is the number of table index bits
0001eeee - length or distance, eeee is the number of extra bits
01100000 - end of block
01000000 - invalid code
*/
/* Maximum size of the dynamic table. The maximum number of code structures is
1444, which is the sum of 852 for literal/length codes and 592 for distance
codes. These values were found by exhaustive searches using the program
examples/enough.c found in the zlib distribtution. The arguments to that
program are the number of symbols, the initial root table size, and the
maximum bit length of a code. "enough 286 9 15" for literal/length codes
returns returns 852, and "enough 30 6 15" for distance codes returns 592.
The initial root table size (9 or 6) is found in the fifth argument of the
inflate_table() calls in inflate.c and infback.c. If the root table size is
changed, then these maximum sizes would be need to be recalculated and
updated. */
#define ENOUGH_LENS 852
#define ENOUGH_DISTS 592
#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
/* Type of code to build for inflate_table() */
typedef enum {
CODES,
LENS,
DISTS
} codetype;
int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
unsigned codes, code FAR *FAR *table,
unsigned FAR *bits, unsigned short FAR *work));

1247
common/zlib/trees.c Normal file

File diff suppressed because it is too large Load diff

128
common/zlib/trees.h Normal file
View file

@ -0,0 +1,128 @@
/* header created automatically with -DGEN_TREES_H */
local const ct_data static_ltree[L_CODES + 2] = {
{{ 12}, { 8}}, {{140}, { 8}}, {{ 76}, { 8}}, {{204}, { 8}}, {{ 44}, { 8}},
{{172}, { 8}}, {{108}, { 8}}, {{236}, { 8}}, {{ 28}, { 8}}, {{156}, { 8}},
{{ 92}, { 8}}, {{220}, { 8}}, {{ 60}, { 8}}, {{188}, { 8}}, {{124}, { 8}},
{{252}, { 8}}, {{ 2}, { 8}}, {{130}, { 8}}, {{ 66}, { 8}}, {{194}, { 8}},
{{ 34}, { 8}}, {{162}, { 8}}, {{ 98}, { 8}}, {{226}, { 8}}, {{ 18}, { 8}},
{{146}, { 8}}, {{ 82}, { 8}}, {{210}, { 8}}, {{ 50}, { 8}}, {{178}, { 8}},
{{114}, { 8}}, {{242}, { 8}}, {{ 10}, { 8}}, {{138}, { 8}}, {{ 74}, { 8}},
{{202}, { 8}}, {{ 42}, { 8}}, {{170}, { 8}}, {{106}, { 8}}, {{234}, { 8}},
{{ 26}, { 8}}, {{154}, { 8}}, {{ 90}, { 8}}, {{218}, { 8}}, {{ 58}, { 8}},
{{186}, { 8}}, {{122}, { 8}}, {{250}, { 8}}, {{ 6}, { 8}}, {{134}, { 8}},
{{ 70}, { 8}}, {{198}, { 8}}, {{ 38}, { 8}}, {{166}, { 8}}, {{102}, { 8}},
{{230}, { 8}}, {{ 22}, { 8}}, {{150}, { 8}}, {{ 86}, { 8}}, {{214}, { 8}},
{{ 54}, { 8}}, {{182}, { 8}}, {{118}, { 8}}, {{246}, { 8}}, {{ 14}, { 8}},
{{142}, { 8}}, {{ 78}, { 8}}, {{206}, { 8}}, {{ 46}, { 8}}, {{174}, { 8}},
{{110}, { 8}}, {{238}, { 8}}, {{ 30}, { 8}}, {{158}, { 8}}, {{ 94}, { 8}},
{{222}, { 8}}, {{ 62}, { 8}}, {{190}, { 8}}, {{126}, { 8}}, {{254}, { 8}},
{{ 1}, { 8}}, {{129}, { 8}}, {{ 65}, { 8}}, {{193}, { 8}}, {{ 33}, { 8}},
{{161}, { 8}}, {{ 97}, { 8}}, {{225}, { 8}}, {{ 17}, { 8}}, {{145}, { 8}},
{{ 81}, { 8}}, {{209}, { 8}}, {{ 49}, { 8}}, {{177}, { 8}}, {{113}, { 8}},
{{241}, { 8}}, {{ 9}, { 8}}, {{137}, { 8}}, {{ 73}, { 8}}, {{201}, { 8}},
{{ 41}, { 8}}, {{169}, { 8}}, {{105}, { 8}}, {{233}, { 8}}, {{ 25}, { 8}},
{{153}, { 8}}, {{ 89}, { 8}}, {{217}, { 8}}, {{ 57}, { 8}}, {{185}, { 8}},
{{121}, { 8}}, {{249}, { 8}}, {{ 5}, { 8}}, {{133}, { 8}}, {{ 69}, { 8}},
{{197}, { 8}}, {{ 37}, { 8}}, {{165}, { 8}}, {{101}, { 8}}, {{229}, { 8}},
{{ 21}, { 8}}, {{149}, { 8}}, {{ 85}, { 8}}, {{213}, { 8}}, {{ 53}, { 8}},
{{181}, { 8}}, {{117}, { 8}}, {{245}, { 8}}, {{ 13}, { 8}}, {{141}, { 8}},
{{ 77}, { 8}}, {{205}, { 8}}, {{ 45}, { 8}}, {{173}, { 8}}, {{109}, { 8}},
{{237}, { 8}}, {{ 29}, { 8}}, {{157}, { 8}}, {{ 93}, { 8}}, {{221}, { 8}},
{{ 61}, { 8}}, {{189}, { 8}}, {{125}, { 8}}, {{253}, { 8}}, {{ 19}, { 9}},
{{275}, { 9}}, {{147}, { 9}}, {{403}, { 9}}, {{ 83}, { 9}}, {{339}, { 9}},
{{211}, { 9}}, {{467}, { 9}}, {{ 51}, { 9}}, {{307}, { 9}}, {{179}, { 9}},
{{435}, { 9}}, {{115}, { 9}}, {{371}, { 9}}, {{243}, { 9}}, {{499}, { 9}},
{{ 11}, { 9}}, {{267}, { 9}}, {{139}, { 9}}, {{395}, { 9}}, {{ 75}, { 9}},
{{331}, { 9}}, {{203}, { 9}}, {{459}, { 9}}, {{ 43}, { 9}}, {{299}, { 9}},
{{171}, { 9}}, {{427}, { 9}}, {{107}, { 9}}, {{363}, { 9}}, {{235}, { 9}},
{{491}, { 9}}, {{ 27}, { 9}}, {{283}, { 9}}, {{155}, { 9}}, {{411}, { 9}},
{{ 91}, { 9}}, {{347}, { 9}}, {{219}, { 9}}, {{475}, { 9}}, {{ 59}, { 9}},
{{315}, { 9}}, {{187}, { 9}}, {{443}, { 9}}, {{123}, { 9}}, {{379}, { 9}},
{{251}, { 9}}, {{507}, { 9}}, {{ 7}, { 9}}, {{263}, { 9}}, {{135}, { 9}},
{{391}, { 9}}, {{ 71}, { 9}}, {{327}, { 9}}, {{199}, { 9}}, {{455}, { 9}},
{{ 39}, { 9}}, {{295}, { 9}}, {{167}, { 9}}, {{423}, { 9}}, {{103}, { 9}},
{{359}, { 9}}, {{231}, { 9}}, {{487}, { 9}}, {{ 23}, { 9}}, {{279}, { 9}},
{{151}, { 9}}, {{407}, { 9}}, {{ 87}, { 9}}, {{343}, { 9}}, {{215}, { 9}},
{{471}, { 9}}, {{ 55}, { 9}}, {{311}, { 9}}, {{183}, { 9}}, {{439}, { 9}},
{{119}, { 9}}, {{375}, { 9}}, {{247}, { 9}}, {{503}, { 9}}, {{ 15}, { 9}},
{{271}, { 9}}, {{143}, { 9}}, {{399}, { 9}}, {{ 79}, { 9}}, {{335}, { 9}},
{{207}, { 9}}, {{463}, { 9}}, {{ 47}, { 9}}, {{303}, { 9}}, {{175}, { 9}},
{{431}, { 9}}, {{111}, { 9}}, {{367}, { 9}}, {{239}, { 9}}, {{495}, { 9}},
{{ 31}, { 9}}, {{287}, { 9}}, {{159}, { 9}}, {{415}, { 9}}, {{ 95}, { 9}},
{{351}, { 9}}, {{223}, { 9}}, {{479}, { 9}}, {{ 63}, { 9}}, {{319}, { 9}},
{{191}, { 9}}, {{447}, { 9}}, {{127}, { 9}}, {{383}, { 9}}, {{255}, { 9}},
{{511}, { 9}}, {{ 0}, { 7}}, {{ 64}, { 7}}, {{ 32}, { 7}}, {{ 96}, { 7}},
{{ 16}, { 7}}, {{ 80}, { 7}}, {{ 48}, { 7}}, {{112}, { 7}}, {{ 8}, { 7}},
{{ 72}, { 7}}, {{ 40}, { 7}}, {{104}, { 7}}, {{ 24}, { 7}}, {{ 88}, { 7}},
{{ 56}, { 7}}, {{120}, { 7}}, {{ 4}, { 7}}, {{ 68}, { 7}}, {{ 36}, { 7}},
{{100}, { 7}}, {{ 20}, { 7}}, {{ 84}, { 7}}, {{ 52}, { 7}}, {{116}, { 7}},
{{ 3}, { 8}}, {{131}, { 8}}, {{ 67}, { 8}}, {{195}, { 8}}, {{ 35}, { 8}},
{{163}, { 8}}, {{ 99}, { 8}}, {{227}, { 8}}
};
local const ct_data static_dtree[D_CODES] = {
{{ 0}, { 5}}, {{16}, { 5}}, {{ 8}, { 5}}, {{24}, { 5}}, {{ 4}, { 5}},
{{20}, { 5}}, {{12}, { 5}}, {{28}, { 5}}, {{ 2}, { 5}}, {{18}, { 5}},
{{10}, { 5}}, {{26}, { 5}}, {{ 6}, { 5}}, {{22}, { 5}}, {{14}, { 5}},
{{30}, { 5}}, {{ 1}, { 5}}, {{17}, { 5}}, {{ 9}, { 5}}, {{25}, { 5}},
{{ 5}, { 5}}, {{21}, { 5}}, {{13}, { 5}}, {{29}, { 5}}, {{ 3}, { 5}},
{{19}, { 5}}, {{11}, { 5}}, {{27}, { 5}}, {{ 7}, { 5}}, {{23}, { 5}}
};
const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
const uch ZLIB_INTERNAL _length_code[MAX_MATCH - MIN_MATCH + 1] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
local const int base_length[LENGTH_CODES] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
local const int base_dist[D_CODES] = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};

511
common/zlib/zconf.h Normal file
View file

@ -0,0 +1,511 @@
/* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2013 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#ifndef ZCONF_H
#define ZCONF_H
/*
* If you *really* need a unique prefix for all types and library functions,
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
* Even better than compiling with -DZ_PREFIX would be to use configure to set
* this permanently in zconf.h using "./configure --zprefix".
*/
#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */
# define Z_PREFIX_SET
/* all linked symbols */
# define _dist_code z__dist_code
# define _length_code z__length_code
# define _tr_align z__tr_align
# define _tr_flush_bits z__tr_flush_bits
# define _tr_flush_block z__tr_flush_block
# define _tr_init z__tr_init
# define _tr_stored_block z__tr_stored_block
# define _tr_tally z__tr_tally
# define adler32 z_adler32
# define adler32_combine z_adler32_combine
# define adler32_combine64 z_adler32_combine64
# ifndef Z_SOLO
# define compress z_compress
# define compress2 z_compress2
# define compressBound z_compressBound
# endif
# define crc32 z_crc32
# define crc32_combine z_crc32_combine
# define crc32_combine64 z_crc32_combine64
# define deflate z_deflate
# define deflateBound z_deflateBound
# define deflateCopy z_deflateCopy
# define deflateEnd z_deflateEnd
# define deflateInit2_ z_deflateInit2_
# define deflateInit_ z_deflateInit_
# define deflateParams z_deflateParams
# define deflatePending z_deflatePending
# define deflatePrime z_deflatePrime
# define deflateReset z_deflateReset
# define deflateResetKeep z_deflateResetKeep
# define deflateSetDictionary z_deflateSetDictionary
# define deflateSetHeader z_deflateSetHeader
# define deflateTune z_deflateTune
# define deflate_copyright z_deflate_copyright
# define get_crc_table z_get_crc_table
# ifndef Z_SOLO
# define gz_error z_gz_error
# define gz_intmax z_gz_intmax
# define gz_strwinerror z_gz_strwinerror
# define gzbuffer z_gzbuffer
# define gzclearerr z_gzclearerr
# define gzclose z_gzclose
# define gzclose_r z_gzclose_r
# define gzclose_w z_gzclose_w
# define gzdirect z_gzdirect
# define gzdopen z_gzdopen
# define gzeof z_gzeof
# define gzerror z_gzerror
# define gzflush z_gzflush
# define gzgetc z_gzgetc
# define gzgetc_ z_gzgetc_
# define gzgets z_gzgets
# define gzoffset z_gzoffset
# define gzoffset64 z_gzoffset64
# define gzopen z_gzopen
# define gzopen64 z_gzopen64
# ifdef _WIN32
# define gzopen_w z_gzopen_w
# endif
# define gzprintf z_gzprintf
# define gzvprintf z_gzvprintf
# define gzputc z_gzputc
# define gzputs z_gzputs
# define gzread z_gzread
# define gzrewind z_gzrewind
# define gzseek z_gzseek
# define gzseek64 z_gzseek64
# define gzsetparams z_gzsetparams
# define gztell z_gztell
# define gztell64 z_gztell64
# define gzungetc z_gzungetc
# define gzwrite z_gzwrite
# endif
# define inflate z_inflate
# define inflateBack z_inflateBack
# define inflateBackEnd z_inflateBackEnd
# define inflateBackInit_ z_inflateBackInit_
# define inflateCopy z_inflateCopy
# define inflateEnd z_inflateEnd
# define inflateGetHeader z_inflateGetHeader
# define inflateInit2_ z_inflateInit2_
# define inflateInit_ z_inflateInit_
# define inflateMark z_inflateMark
# define inflatePrime z_inflatePrime
# define inflateReset z_inflateReset
# define inflateReset2 z_inflateReset2
# define inflateSetDictionary z_inflateSetDictionary
# define inflateGetDictionary z_inflateGetDictionary
# define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint
# define inflateUndermine z_inflateUndermine
# define inflateResetKeep z_inflateResetKeep
# define inflate_copyright z_inflate_copyright
# define inflate_fast z_inflate_fast
# define inflate_table z_inflate_table
# ifndef Z_SOLO
# define uncompress z_uncompress
# endif
# define zError z_zError
# ifndef Z_SOLO
# define zcalloc z_zcalloc
# define zcfree z_zcfree
# endif
# define zlibCompileFlags z_zlibCompileFlags
# define zlibVersion z_zlibVersion
/* all zlib typedefs in zlib.h and zconf.h */
# define Byte z_Byte
# define Bytef z_Bytef
# define alloc_func z_alloc_func
# define charf z_charf
# define free_func z_free_func
# ifndef Z_SOLO
# define gzFile z_gzFile
# endif
# define gz_header z_gz_header
# define gz_headerp z_gz_headerp
# define in_func z_in_func
# define intf z_intf
# define out_func z_out_func
# define uInt z_uInt
# define uIntf z_uIntf
# define uLong z_uLong
# define uLongf z_uLongf
# define voidp z_voidp
# define voidpc z_voidpc
# define voidpf z_voidpf
/* all zlib structs in zlib.h and zconf.h */
# define gz_header_s z_gz_header_s
# define internal_state z_internal_state
#endif
#if defined(__MSDOS__) && !defined(MSDOS)
# define MSDOS
#endif
#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
# define OS2
#endif
#if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS
#endif
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
# ifndef WIN32
# define WIN32
# endif
#endif
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
# ifndef SYS16BIT
# define SYS16BIT
# endif
# endif
#endif
/*
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
* than 64k bytes at a time (needed on systems with 16-bit int).
*/
#ifdef SYS16BIT
# define MAXSEG_64K
#endif
#ifdef MSDOS
# define UNALIGNED_OK
#endif
#ifdef __STDC_VERSION__
# ifndef STDC
# define STDC
# endif
# if __STDC_VERSION__ >= 199901L
# ifndef STDC99
# define STDC99
# endif
# endif
#endif
#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
# define STDC
#endif
#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
# define STDC
#endif
#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
# define STDC
#endif
#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
# define STDC
#endif
#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
# define STDC
#endif
#ifndef STDC
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
# define const /* note: need a more gentle solution here */
# endif
#endif
#if defined(ZLIB_CONST) && !defined(z_const)
# define z_const const
#else
# define z_const
#endif
/* Some Mac compilers merge all .h files incorrectly: */
#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
# define NO_DUMMY_DECL
#endif
/* Maximum value for memLevel in deflateInit2 */
#ifndef MAX_MEM_LEVEL
# ifdef MAXSEG_64K
# define MAX_MEM_LEVEL 8
# else
# define MAX_MEM_LEVEL 9
# endif
#endif
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
* created by gzip. (Files created by minigzip can still be extracted by
* gzip.)
*/
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
/* The memory requirements for deflate are (in bytes):
(1 << (windowBits+2)) + (1 << (memLevel+9))
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes) 1 << windowBits
that is, 32K for windowBits=15 (default value) plus a few kilobytes
for small objects.
*/
/* Type declarations */
#ifndef OF /* function prototypes */
# ifdef STDC
# define OF(args) args
# else
# define OF(args) ()
# endif
#endif
#ifndef Z_ARG /* function prototypes for stdarg */
# if defined(STDC) || defined(Z_HAVE_STDARG_H)
# define Z_ARG(args) args
# else
# define Z_ARG(args) ()
# endif
#endif
/* The following definitions for FAR are needed only for MSDOS mixed
* model programming (small or medium model with some far allocations).
* This was tested only with MSC; for other MSDOS compilers you may have
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
* just define FAR to be empty.
*/
#ifdef SYS16BIT
# if defined(M_I86SM) || defined(M_I86MM)
/* MSC small or medium model */
# define SMALL_MEDIUM
# ifdef _MSC_VER
# define FAR _far
# else
# define FAR far
# endif
# endif
# if (defined(__SMALL__) || defined(__MEDIUM__))
/* Turbo C small or medium model */
# define SMALL_MEDIUM
# ifdef __BORLANDC__
# define FAR _far
# else
# define FAR far
# endif
# endif
#endif
#if defined(WINDOWS) || defined(WIN32)
/* If building or using zlib as a DLL, define ZLIB_DLL.
* This is not mandatory, but it offers a little performance increase.
*/
# ifdef ZLIB_DLL
# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
# ifdef ZLIB_INTERNAL
# define ZEXTERN extern __declspec(dllexport)
# else
# define ZEXTERN extern __declspec(dllimport)
# endif
# endif
# endif /* ZLIB_DLL */
/* If building or using zlib with the WINAPI/WINAPIV calling convention,
* define ZLIB_WINAPI.
* Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
*/
# ifdef ZLIB_WINAPI
# ifdef FAR
# undef FAR
# endif
# include <windows.h>
/* No need for _export, use ZLIB.DEF instead. */
/* For complete Windows compatibility, use WINAPI, not __stdcall. */
# define ZEXPORT WINAPI
# ifdef WIN32
# define ZEXPORTVA WINAPIV
# else
# define ZEXPORTVA FAR CDECL
# endif
# endif
#endif
#if defined (__BEOS__)
# ifdef ZLIB_DLL
# ifdef ZLIB_INTERNAL
# define ZEXPORT __declspec(dllexport)
# define ZEXPORTVA __declspec(dllexport)
# else
# define ZEXPORT __declspec(dllimport)
# define ZEXPORTVA __declspec(dllimport)
# endif
# endif
#endif
#ifndef ZEXTERN
# define ZEXTERN extern
#endif
#ifndef ZEXPORT
# define ZEXPORT
#endif
#ifndef ZEXPORTVA
# define ZEXPORTVA
#endif
#ifndef FAR
# define FAR
#endif
#if !defined(__MACTYPES__)
typedef unsigned char Byte; /* 8 bits */
#endif
typedef unsigned int uInt; /* 16 bits or more */
typedef unsigned long uLong; /* 32 bits or more */
#ifdef SMALL_MEDIUM
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
# define Bytef Byte FAR
#else
typedef Byte FAR Bytef;
#endif
typedef char FAR charf;
typedef int FAR intf;
typedef uInt FAR uIntf;
typedef uLong FAR uLongf;
#ifdef STDC
typedef void const *voidpc;
typedef void FAR *voidpf;
typedef void *voidp;
#else
typedef Byte const *voidpc;
typedef Byte FAR *voidpf;
typedef Byte *voidp;
#endif
#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
# include <limits.h>
# if (UINT_MAX == 0xffffffffUL)
# define Z_U4 unsigned
# elif (ULONG_MAX == 0xffffffffUL)
# define Z_U4 unsigned long
# elif (USHRT_MAX == 0xffffffffUL)
# define Z_U4 unsigned short
# endif
#endif
#ifdef Z_U4
typedef Z_U4 z_crc_t;
#else
typedef unsigned long z_crc_t;
#endif
#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */
# define Z_HAVE_UNISTD_H
#endif
#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */
# define Z_HAVE_STDARG_H
#endif
#ifdef STDC
# ifndef Z_SOLO
# include <sys/types.h> /* for off_t */
# endif
#endif
#if defined(STDC) || defined(Z_HAVE_STDARG_H)
# ifndef Z_SOLO
# include <stdarg.h> /* for va_list */
# endif
#endif
#ifdef _WIN32
# ifndef Z_SOLO
# include <stddef.h> /* for wchar_t */
# endif
#endif
/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
* "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
* though the former does not conform to the LFS document), but considering
* both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
* equivalently requesting no 64-bit operations
*/
#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
# undef _LARGEFILE64_SOURCE
#endif
#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
# define Z_HAVE_UNISTD_H
#endif
#ifndef Z_SOLO
# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
# include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
# ifdef VMS
# include <unixio.h> /* for off_t */
# endif
# ifndef z_off_t
# define z_off_t off_t
# endif
# endif
#endif
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
# define Z_LFS64
#endif
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
# define Z_LARGE64
#endif
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
# define Z_WANT64
#endif
#if !defined(SEEK_SET) && !defined(Z_SOLO)
# define SEEK_SET 0 /* Seek from beginning of file. */
# define SEEK_CUR 1 /* Seek from current position. */
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif
#ifndef z_off_t
# define z_off_t long
#endif
#if !defined(_WIN32) && defined(Z_LARGE64)
# define z_off64_t off64_t
#else
# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
# define z_off64_t __int64
# else
# define z_off64_t z_off_t
# endif
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
#pragma map(deflateInit_,"DEIN")
#pragma map(deflateInit2_,"DEIN2")
#pragma map(deflateEnd,"DEEND")
#pragma map(deflateBound,"DEBND")
#pragma map(inflateInit_,"ININ")
#pragma map(inflateInit2_,"ININ2")
#pragma map(inflateEnd,"INEND")
#pragma map(inflateSync,"INSY")
#pragma map(inflateSetDictionary,"INSEDI")
#pragma map(compressBound,"CMBND")
#pragma map(inflate_table,"INTABL")
#pragma map(inflate_fast,"INFA")
#pragma map(inflate_copyright,"INCOPY")
#endif
#endif /* ZCONF_H */

1786
common/zlib/zlib.h Normal file

File diff suppressed because it is too large Load diff

343
common/zlib/zutil.c Normal file
View file

@ -0,0 +1,343 @@
/* zutil.c -- target dependent utility functions for the compression library
* Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "zutil.h"
#ifndef Z_SOLO
# include "gzguts.h"
#endif
#ifndef NO_DUMMY_DECL
struct internal_state {int dummy;}; /* for buggy compilers */
#endif
z_const char *const z_errmsg[10] = {
"need dictionary", /* Z_NEED_DICT 2 */
"stream end", /* Z_STREAM_END 1 */
"", /* Z_OK 0 */
"file error", /* Z_ERRNO (-1) */
"stream error", /* Z_STREAM_ERROR (-2) */
"data error", /* Z_DATA_ERROR (-3) */
"insufficient memory", /* Z_MEM_ERROR (-4) */
"buffer error", /* Z_BUF_ERROR (-5) */
"incompatible version",/* Z_VERSION_ERROR (-6) */
""
};
const char *ZEXPORT zlibVersion() {
return ZLIB_VERSION;
}
uLong ZEXPORT zlibCompileFlags() {
uLong flags;
flags = 0;
switch ((int)(sizeof(uInt))) {
case 2:
break;
case 4:
flags += 1;
break;
case 8:
flags += 2;
break;
default:
flags += 3;
}
switch ((int)(sizeof(uLong))) {
case 2:
break;
case 4:
flags += 1 << 2;
break;
case 8:
flags += 2 << 2;
break;
default:
flags += 3 << 2;
}
switch ((int)(sizeof(voidpf))) {
case 2:
break;
case 4:
flags += 1 << 4;
break;
case 8:
flags += 2 << 4;
break;
default:
flags += 3 << 4;
}
switch ((int)(sizeof(z_off_t))) {
case 2:
break;
case 4:
flags += 1 << 6;
break;
case 8:
flags += 2 << 6;
break;
default:
flags += 3 << 6;
}
#ifdef DEBUG
flags += 1 << 8;
#endif
#if defined(ASMV) || defined(ASMINF)
flags += 1 << 9;
#endif
#ifdef ZLIB_WINAPI
flags += 1 << 10;
#endif
#ifdef BUILDFIXED
flags += 1 << 12;
#endif
#ifdef DYNAMIC_CRC_TABLE
flags += 1 << 13;
#endif
#ifdef NO_GZCOMPRESS
flags += 1L << 16;
#endif
#ifdef NO_GZIP
flags += 1L << 17;
#endif
#ifdef PKZIP_BUG_WORKAROUND
flags += 1L << 20;
#endif
#ifdef FASTEST
flags += 1L << 21;
#endif
#if defined(STDC) || defined(Z_HAVE_STDARG_H)
# ifdef NO_vsnprintf
flags += 1L << 25;
# ifdef HAS_vsprintf_void
flags += 1L << 26;
# endif
# else
# ifdef HAS_vsnprintf_void
flags += 1L << 26;
# endif
# endif
#else
flags += 1L << 24;
# ifdef NO_snprintf
flags += 1L << 25;
# ifdef HAS_sprintf_void
flags += 1L << 26;
# endif
# else
# ifdef HAS_snprintf_void
flags += 1L << 26;
# endif
# endif
#endif
return flags;
}
#ifdef DEBUG
# ifndef verbose
# define verbose 0
# endif
int ZLIB_INTERNAL z_verbose = verbose;
void ZLIB_INTERNAL z_error(m)
char *m;
{
fprintf(stderr, "%s\n", m);
exit(1);
}
#endif
/* exported to allow conversion of error code to string for compress() and
* uncompress()
*/
const char *ZEXPORT zError(err)
int err;
{
return ERR_MSG(err);
}
#if defined(_WIN32_WCE)
/* The Microsoft C Run-Time Library for Windows CE doesn't have
* errno. We define it as a global variable to simplify porting.
* Its value is always 0 and should not be used.
*/
int errno = 0;
#endif
#ifndef HAVE_MEMCPY
void ZLIB_INTERNAL zmemcpy(dest, source, len)
Bytef *dest;
const Bytef *source;
uInt len;
{
if (len == 0) return;
do {
*dest++ = *source++; /* ??? to be unrolled */
} while (--len != 0);
}
int ZLIB_INTERNAL zmemcmp(s1, s2, len)
const Bytef *s1;
const Bytef *s2;
uInt len;
{
uInt j;
for (j = 0; j < len; j++) {
if (s1[j] != s2[j]) return 2 * (s1[j] > s2[j]) - 1;
}
return 0;
}
void ZLIB_INTERNAL zmemzero(dest, len)
Bytef *dest;
uInt len;
{
if (len == 0) return;
do {
*dest++ = 0; /* ??? to be unrolled */
} while (--len != 0);
}
#endif
#ifndef Z_SOLO
#ifdef SYS16BIT
#ifdef __TURBOC__
/* Turbo C in 16-bit mode */
# define MY_ZCALLOC
/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
* and farmalloc(64K) returns a pointer with an offset of 8, so we
* must fix the pointer. Warning: the pointer must be put back to its
* original form in order to free it, use zcfree().
*/
#define MAX_PTR 10
/* 10*64K = 640K */
local int next_ptr = 0;
typedef struct ptr_table_s {
voidpf org_ptr;
voidpf new_ptr;
} ptr_table;
local ptr_table table[MAX_PTR];
/* This table is used to remember the original form of pointers
* to large buffers (64K). Such pointers are normalized with a zero offset.
* Since MSDOS is not a preemptive multitasking OS, this table is not
* protected from concurrent access. This hack doesn't work anyway on
* a protected system like OS/2. Use Microsoft C instead.
*/
voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) {
voidpf buf = opaque; /* just to make some compilers happy */
ulg bsize = (ulg)items * size;
/* If we allocate less than 65520 bytes, we assume that farmalloc
* will return a usable pointer which doesn't have to be normalized.
*/
if (bsize < 65520L) {
buf = farmalloc(bsize);
if (*(ush *)&buf != 0) return buf;
} else {
buf = farmalloc(bsize + 16L);
}
if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
table[next_ptr].org_ptr = buf;
/* Normalize the pointer to seg:0 */
*((ush *)&buf + 1) += ((ush)((uch *)buf - 0) + 15) >> 4;
*(ush *)&buf = 0;
table[next_ptr++].new_ptr = buf;
return buf;
}
void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) {
int n;
if (*(ush *)&ptr != 0) { /* object < 64K */
farfree(ptr);
return;
}
/* Find the original pointer */
for (n = 0; n < next_ptr; n++) {
if (ptr != table[n].new_ptr) continue;
farfree(table[n].org_ptr);
while (++n < next_ptr) {
table[n - 1] = table[n];
}
next_ptr--;
return;
}
ptr = opaque; /* just to make some compilers happy */
Assert(0, "zcfree: ptr not found");
}
#endif /* __TURBOC__ */
#ifdef M_I86
/* Microsoft C in 16-bit mode */
# define MY_ZCALLOC
#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
# define _halloc halloc
# define _hfree hfree
#endif
voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) {
if (opaque) opaque = 0; /* to make compiler happy */
return _halloc((long)items, size);
}
void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) {
if (opaque) opaque = 0; /* to make compiler happy */
_hfree(ptr);
}
#endif /* M_I86 */
#endif /* SYS16BIT */
#ifndef MY_ZCALLOC /* Any system without a special alloc function */
#ifndef STDC
extern voidp malloc OF((uInt size));
extern voidp calloc OF((uInt items, uInt size));
extern void free OF((voidpf ptr));
#endif
voidpf ZLIB_INTERNAL zcalloc(opaque, items, size)
voidpf opaque;
unsigned items;
unsigned size;
{
if (opaque) items += size - size; /* make compiler happy */
return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
(voidpf)calloc(items, size);
}
void ZLIB_INTERNAL zcfree(opaque, ptr)
voidpf opaque;
voidpf ptr;
{
free(ptr);
if (opaque) return; /* make compiler happy */
}
#endif /* MY_ZCALLOC */
#endif /* !Z_SOLO */

253
common/zlib/zutil.h Normal file
View file

@ -0,0 +1,253 @@
/* zutil.h -- internal interface and configuration of the compression library
* Copyright (C) 1995-2013 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef ZUTIL_H
#define ZUTIL_H
#ifdef HAVE_HIDDEN
# define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
#else
# define ZLIB_INTERNAL
#endif
#include "zlib.h"
#if defined(STDC) && !defined(Z_SOLO)
# if !(defined(_WIN32_WCE) && defined(_MSC_VER))
# include <stddef.h>
# endif
# include <string.h>
# include <stdlib.h>
#endif
#ifdef Z_SOLO
typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */
#endif
#ifndef local
# define local static
#endif
/* compile with -Dlocal if your debugger can't find static symbols */
typedef unsigned char uch;
typedef uch FAR uchf;
typedef unsigned short ush;
typedef ush FAR ushf;
typedef unsigned long ulg;
extern z_const char *const z_errmsg[10]; /* indexed by 2-zlib_error */
/* (size given to avoid silly warnings with Visual C++) */
#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
#define ERR_RETURN(strm,err) \
return (strm->msg = ERR_MSG(err), (err))
/* To be used only when the state is known to be valid */
/* common constants */
#ifndef DEF_WBITS
# define DEF_WBITS MAX_WBITS
#endif
/* default windowBits for decompression. MAX_WBITS is for compression only */
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
/* default memLevel */
#define STORED_BLOCK 0
#define STATIC_TREES 1
#define DYN_TREES 2
/* The three kinds of block type */
#define MIN_MATCH 3
#define MAX_MATCH 258
/* The minimum and maximum match lengths */
#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
/* target dependencies */
#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
# define OS_CODE 0x00
# ifndef Z_SOLO
# if defined(__TURBOC__) || defined(__BORLANDC__)
# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
/* Allow compilation with ANSI keywords only enabled */
void _Cdecl farfree(void *block);
void *_Cdecl farmalloc(unsigned long nbytes);
# else
# include <alloc.h>
# endif
# else /* MSC or DJGPP */
# include <malloc.h>
# endif
# endif
#endif
#ifdef AMIGA
# define OS_CODE 0x01
#endif
#if defined(VAXC) || defined(VMS)
# define OS_CODE 0x02
# define F_OPEN(name, mode) \
fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
#endif
#if defined(ATARI) || defined(atarist)
# define OS_CODE 0x05
#endif
#ifdef OS2
# define OS_CODE 0x06
# if defined(M_I86) && !defined(Z_SOLO)
# include <malloc.h>
# endif
#endif
#if defined(MACOS) || defined(TARGET_OS_MAC)
# define OS_CODE 0x07
# ifndef Z_SOLO
# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
# include <unix.h> /* for fdopen */
# else
# ifndef fdopen
# define fdopen(fd,mode) NULL /* No fdopen() */
# endif
# endif
# endif
#endif
#ifdef TOPS20
# define OS_CODE 0x0a
#endif
#ifdef WIN32
# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
# define OS_CODE 0x0b
# endif
#endif
#ifdef __50SERIES /* Prime/PRIMOS */
# define OS_CODE 0x0f
#endif
#if defined(_BEOS_) || defined(RISCOS)
# define fdopen(fd,mode) NULL /* No fdopen() */
#endif
#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
# if defined(_WIN32_WCE)
# define fdopen(fd,mode) NULL /* No fdopen() */
# ifndef _PTRDIFF_T_DEFINED
typedef int ptrdiff_t;
# define _PTRDIFF_T_DEFINED
# endif
# else
# define fdopen(fd,type) _fdopen(fd,type)
# endif
#endif
#if defined(__BORLANDC__) && !defined(MSDOS)
#pragma warn -8004
#pragma warn -8008
#pragma warn -8066
#endif
/* provide prototypes for these when building zlib without LFS */
#if !defined(_WIN32) && \
(!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
#endif
/* common defaults */
#ifndef OS_CODE
# define OS_CODE 0x03 /* assume Unix */
#endif
#ifndef F_OPEN
# define F_OPEN(name, mode) fopen((name), (mode))
#endif
/* functions */
#if defined(pyr) || defined(Z_SOLO)
# define NO_MEMCPY
#endif
#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
/* Use our own functions for small and medium model with MSC <= 5.0.
* You may have to use the same strategy for Borland C (untested).
* The __SC__ check is for Symantec.
*/
# define NO_MEMCPY
#endif
#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
# define HAVE_MEMCPY
#endif
#ifdef HAVE_MEMCPY
# ifdef SMALL_MEDIUM /* MSDOS small or medium model */
# define zmemcpy _fmemcpy
# define zmemcmp _fmemcmp
# define zmemzero(dest, len) _fmemset(dest, 0, len)
# else
# define zmemcpy memcpy
# define zmemcmp memcmp
# define zmemzero(dest, len) memset(dest, 0, len)
# endif
#else
void ZLIB_INTERNAL zmemcpy OF((Bytef *dest, const Bytef *source, uInt len));
int ZLIB_INTERNAL zmemcmp OF((const Bytef *s1, const Bytef *s2, uInt len));
void ZLIB_INTERNAL zmemzero OF((Bytef *dest, uInt len));
#endif
/* Diagnostic functions */
#ifdef DEBUG
# include <stdio.h>
extern int ZLIB_INTERNAL z_verbose;
extern void ZLIB_INTERNAL z_error OF((char *m));
# define Assert(cond,msg) {if(!(cond)) z_error(msg);}
# define Trace(x) {if (z_verbose>=0) fprintf x ;}
# define Tracev(x) {if (z_verbose>0) fprintf x ;}
# define Tracevv(x) {if (z_verbose>1) fprintf x ;}
# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
#else
# define Assert(cond,msg)
# define Trace(x)
# define Tracev(x)
# define Tracevv(x)
# define Tracec(c,x)
# define Tracecv(c,x)
#endif
#ifndef Z_SOLO
voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
unsigned size));
void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr));
#endif
#define ZALLOC(strm, items, size) \
(*((strm)->zalloc))((strm)->opaque, (items), (size))
#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
/* Reverse the bytes in a 32-bit value */
#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
(((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
#endif /* ZUTIL_H */