fix one too small
[RRG-proxmark3.git] / client / src / comms.c
blob091f51d8684af935160413db8ecc7aaa8c918a6a
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // Code for communicating with the proxmark3 hardware.
17 //-----------------------------------------------------------------------------
19 #include "comms.h"
21 #include <inttypes.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
26 #include "uart/uart.h"
27 #include "ui.h"
28 #include "crc16.h"
29 #include "util.h" // g_pendingPrompt
30 #include "util_posix.h" // msclock
31 #include "util_darwin.h" // en/dis-ableNapp();
32 #include "usart_defs.h"
34 // #define COMMS_DEBUG
35 // #define COMMS_DEBUG_RAW
37 // Serial port that we are communicating with the PM3 on.
38 static serial_port sp = NULL;
40 communication_arg_t g_conn;
41 capabilities_t g_pm3_capabilities;
43 static pthread_t communication_thread;
44 static pthread_t reconnect_thread;
46 static bool reconnect_ok = false;
48 static bool comm_thread_dead = false;
49 static bool comm_raw_mode = false;
50 static uint8_t *comm_raw_data = NULL;
51 static size_t comm_raw_len = 0;
52 static size_t comm_raw_pos = 0;
54 // Transmit buffer.
55 static PacketCommandOLD txBuffer;
56 static PacketCommandNGRaw txBufferNG;
57 static size_t txBufferNGLen;
58 static bool txBuffer_pending = false;
59 static pthread_mutex_t txBufferMutex = PTHREAD_MUTEX_INITIALIZER;
60 static pthread_cond_t txBufferSig = PTHREAD_COND_INITIALIZER;
62 // Used by PacketResponseReceived as a ring buffer for messages that are yet to be
63 // processed by a command handler (WaitForResponse{,Timeout})
64 static PacketResponseNG rxBuffer[CMD_BUFFER_SIZE];
66 // Points to the next empty position to write to
67 static int cmd_head = 0;
69 // Points to the position of the last unread command
70 static int cmd_tail = 0;
72 // to lock rxBuffer operations from different threads
73 static pthread_mutex_t rxBufferMutex = PTHREAD_MUTEX_INITIALIZER;
75 // Global start time for WaitForResponseTimeout & dl_it, so we can reset timeout when we get packets
76 // as sending lot of these packets can slow down things wuite a lot on slow links (e.g. hw status or lf read at 9600)
77 static uint64_t timeout_start_time;
79 static uint64_t last_packet_time;
81 static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd);
83 // Simple alias to track usages linked to the Bootloader, these commands must not be migrated.
84 // - commands sent to enter bootloader mode as we might have to talk to old firmwares
85 // - commands sent to the bootloader as it only supports OLD frames (which will always be the case for old BL)
86 void SendCommandBL(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *data, size_t len) {
87 SendCommandOLD(cmd, arg0, arg1, arg2, data, len);
90 void SendCommandOLD(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const void *data, size_t len) {
91 PacketCommandOLD c = {CMD_UNKNOWN, {0, 0, 0}, {{0}}};
92 c.cmd = cmd;
93 c.arg[0] = arg0;
94 c.arg[1] = arg1;
95 c.arg[2] = arg2;
96 if (len && data)
97 memcpy(&c.d, data, len);
99 #ifdef COMMS_DEBUG
100 PrintAndLogEx(NORMAL, "Sending %s", "OLD");
101 #endif
102 #ifdef COMMS_DEBUG_RAW
103 print_hex_break((uint8_t *)&c.cmd, sizeof(c.cmd), 32);
104 print_hex_break((uint8_t *)&c.arg, sizeof(c.arg), 32);
105 print_hex_break((uint8_t *)&c.d, sizeof(c.d), 32);
106 #endif
108 if (!g_session.pm3_present) {
109 PrintAndLogEx(WARNING, "Sending bytes to Proxmark3 failed ( " _RED_("offline") " )");
110 return;
113 pthread_mutex_lock(&txBufferMutex);
115 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
116 but comm thread just spins here. Not good.../holiman
118 while (txBuffer_pending) {
119 // wait for communication thread to complete sending a previous command
120 pthread_cond_wait(&txBufferSig, &txBufferMutex);
123 txBuffer = c;
124 txBuffer_pending = true;
126 // tell communication thread that a new command can be send
127 pthread_cond_signal(&txBufferSig);
129 pthread_mutex_unlock(&txBufferMutex);
131 //__atomic_test_and_set(&txcmd_pending, __ATOMIC_SEQ_CST);
134 static void SendCommandNG_internal(uint16_t cmd, uint8_t *data, size_t len, bool ng) {
135 #ifdef COMMS_DEBUG
136 PrintAndLogEx(INFO, "Sending %s", ng ? "NG" : "MIX");
137 #endif
139 if (!g_session.pm3_present) {
140 PrintAndLogEx(INFO, "Sending bytes to proxmark failed - offline");
141 return;
143 if (len > PM3_CMD_DATA_SIZE) {
144 PrintAndLogEx(WARNING, "Sending %zu bytes of payload is too much, abort", len);
145 return;
148 PacketCommandNGPostamble *tx_post = (PacketCommandNGPostamble *)((uint8_t *)&txBufferNG + sizeof(PacketCommandNGPreamble) + len);
150 pthread_mutex_lock(&txBufferMutex);
152 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
153 but comm thread just spins here. Not good.../holiman
155 while (txBuffer_pending) {
156 // wait for communication thread to complete sending a previous command
157 pthread_cond_wait(&txBufferSig, &txBufferMutex);
160 txBufferNG.pre.magic = COMMANDNG_PREAMBLE_MAGIC;
161 txBufferNG.pre.ng = ng;
162 txBufferNG.pre.length = len;
163 txBufferNG.pre.cmd = cmd;
164 if (len > 0 && data) {
165 memcpy(&txBufferNG.data, data, len);
168 if ((g_conn.send_via_fpc_usart && g_conn.send_with_crc_on_fpc) || ((!g_conn.send_via_fpc_usart) && g_conn.send_with_crc_on_usb)) {
169 uint8_t first = 0, second = 0;
170 compute_crc(CRC_14443_A, (uint8_t *)&txBufferNG, sizeof(PacketCommandNGPreamble) + len, &first, &second);
171 tx_post->crc = (first << 8) + second;
172 } else {
173 tx_post->crc = COMMANDNG_POSTAMBLE_MAGIC;
176 txBufferNGLen = sizeof(PacketCommandNGPreamble) + len + sizeof(PacketCommandNGPostamble);
178 #ifdef COMMS_DEBUG_RAW
179 print_hex_break((uint8_t *)&txBufferNG.pre, sizeof(PacketCommandNGPreamble), 32);
180 if (ng) {
181 print_hex_break((uint8_t *)&txBufferNG.data, len, 32);
182 } else {
183 print_hex_break((uint8_t *)&txBufferNG.data, 3 * sizeof(uint64_t), 32);
184 print_hex_break((uint8_t *)&txBufferNG.data + 3 * sizeof(uint64_t), len - 3 * sizeof(uint64_t), 32);
186 print_hex_break((uint8_t *)tx_post, sizeof(PacketCommandNGPostamble), 32);
187 #endif
188 txBuffer_pending = true;
190 // tell communication thread that a new command can be send
191 pthread_cond_signal(&txBufferSig);
193 pthread_mutex_unlock(&txBufferMutex);
195 //__atomic_test_and_set(&txcmd_pending, __ATOMIC_SEQ_CST);
198 void SendCommandNG(uint16_t cmd, uint8_t *data, size_t len) {
199 SendCommandNG_internal(cmd, data, len, true);
202 void SendCommandMIX(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, const void *data, size_t len) {
203 uint64_t arg[3] = {arg0, arg1, arg2};
204 if (len > PM3_CMD_DATA_SIZE_MIX) {
205 PrintAndLogEx(WARNING, "Sending %zu bytes of payload is too much for MIX frames, abort", len);
206 return;
208 uint8_t cmddata[PM3_CMD_DATA_SIZE];
209 memcpy(cmddata, arg, sizeof(arg));
210 if (len && data)
211 memcpy(cmddata + sizeof(arg), data, len);
212 SendCommandNG_internal(cmd, cmddata, len + sizeof(arg), false);
217 * @brief This method should be called when sending a new command to the pm3. In case any old
218 * responses from previous commands are stored in the buffer, a call to this method should clear them.
219 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
220 * operation. Right now we'll just have to live with this.
222 void clearCommandBuffer(void) {
223 //This is a very simple operation
224 pthread_mutex_lock(&rxBufferMutex);
225 cmd_tail = cmd_head;
226 pthread_mutex_unlock(&rxBufferMutex);
229 * @brief storeCommand stores a USB command in a circular buffer
230 * @param UC
232 static void storeReply(const PacketResponseNG *packet) {
233 pthread_mutex_lock(&rxBufferMutex);
234 if ((cmd_head + 1) % CMD_BUFFER_SIZE == cmd_tail) {
235 //If these two are equal, we're about to overwrite in the
236 // circular buffer.
237 PrintAndLogEx(FAILED, "WARNING: Command buffer about to overwrite command! This needs to be fixed!");
238 fflush(stdout);
240 //Store the command at the 'head' location
241 PacketResponseNG *destination = &rxBuffer[cmd_head];
242 memcpy(destination, packet, sizeof(PacketResponseNG));
244 //increment head and wrap
245 cmd_head = (cmd_head + 1) % CMD_BUFFER_SIZE;
246 pthread_mutex_unlock(&rxBufferMutex);
249 * @brief getCommand gets a command from an internal circular buffer.
250 * @param response location to write command
251 * @return 1 if response was returned, 0 if nothing has been received
253 static int getReply(PacketResponseNG *packet) {
254 pthread_mutex_lock(&rxBufferMutex);
255 //If head == tail, there's nothing to read, or if we just got initialized
256 if (cmd_head == cmd_tail) {
257 pthread_mutex_unlock(&rxBufferMutex);
258 return 0;
261 //Pick out the next unread command
262 memcpy(packet, &rxBuffer[cmd_tail], sizeof(PacketResponseNG));
264 //Increment tail - this is a circular buffer, so modulo buffer size
265 cmd_tail = (cmd_tail + 1) % CMD_BUFFER_SIZE;
267 pthread_mutex_unlock(&rxBufferMutex);
268 return 1;
271 //-----------------------------------------------------------------------------
272 // Entry point into our code: called whenever we received a packet over USB
273 // that we weren't necessarily expecting, for example a debug print.
274 //-----------------------------------------------------------------------------
275 static void PacketResponseReceived(PacketResponseNG *packet) {
277 // we got a packet, reset WaitForResponseTimeout timeout
278 uint64_t prev_clk = __atomic_load_n(&last_packet_time, __ATOMIC_SEQ_CST);
279 uint64_t clk = msclock();
280 __atomic_store_n(&timeout_start_time, clk, __ATOMIC_SEQ_CST);
281 __atomic_store_n(&last_packet_time, clk, __ATOMIC_SEQ_CST);
282 (void) prev_clk;
283 // PrintAndLogEx(NORMAL, "[%07"PRIu64"] RECV %s magic %08x length %04x status %04x crc %04x cmd %04x",
284 // clk - prev_clk, packet->ng ? "NG" : "OLD", packet->magic, packet->length, packet->status, packet->crc, packet->cmd);
286 switch (packet->cmd) {
287 // First check if we are handling a debug message
288 case CMD_DEBUG_PRINT_STRING: {
290 char s[PM3_CMD_DATA_SIZE + 1];
291 memset(s, 0x00, sizeof(s));
293 size_t len;
294 uint16_t flag;
295 if (packet->ng) {
296 struct d {
297 uint16_t flag;
298 uint8_t buf[PM3_CMD_DATA_SIZE - sizeof(uint16_t)];
299 } PACKED;
300 const struct d *data = (struct d *)&packet->data.asBytes;
301 len = packet->length - sizeof(data->flag);
302 flag = data->flag;
303 memcpy(s, data->buf, len);
304 } else {
305 len = MIN(packet->oldarg[0], PM3_CMD_DATA_SIZE);
306 flag = packet->oldarg[1];
307 memcpy(s, packet->data.asBytes, len);
310 if (flag & FLAG_LOG) {
311 if (g_pendingPrompt) {
312 PrintAndLogEx(NORMAL, "");
313 g_pendingPrompt = false;
315 //PrintAndLogEx(NORMAL, "[" _MAGENTA_("pm3") "] ["_BLUE_("#")"] " "%s", s);
316 PrintAndLogEx(NORMAL, "[" _BLUE_("#") "] %s", s);
317 } else {
318 if (flag & FLAG_INPLACE) {
319 PrintAndLogEx(NORMAL, "\r" NOLF);
322 PrintAndLogEx(NORMAL, "%s" NOLF, s);
324 if (flag & FLAG_NEWLINE) {
325 PrintAndLogEx(NORMAL, "");
328 break;
330 case CMD_DEBUG_PRINT_INTEGERS: {
331 if (packet->ng == false) {
332 PrintAndLogEx(NORMAL, "[" _MAGENTA_("pm3") "] ["_BLUE_("#")"] " "%" PRIx64 ", %" PRIx64 ", %" PRIx64 ""
333 , packet->oldarg[0]
334 , packet->oldarg[1]
335 , packet->oldarg[2]
338 break;
340 // iceman: hw status - down the path on device, runs printusbspeed which starts sending a lot of
341 // CMD_DOWNLOAD_BIGBUF packages which is not dealt with. I wonder if simply ignoring them will
342 // work. lets try it.
343 default: {
344 storeReply(packet);
345 break;
350 // The reconnect device thread.
351 // When communication thread is dead, start up and try to start it again
352 void *uart_reconnect(void *targ) {
354 const communication_arg_t *connection = (communication_arg_t *)targ;
356 #if defined(__MACH__) && defined(__APPLE__)
357 disableAppNap("Proxmark3 polling UART");
358 #endif
360 uint32_t speed = USART_BAUD_RATE;
361 if (connection->uart_speed) {
362 speed = connection->uart_speed;
365 while (1) {
366 // throttle
367 msleep(200);
368 if (OpenProxmarkSilent(&g_session.current_device, connection->serial_port_name, speed) == false) {
369 continue;
372 if (g_session.pm3_present && (TestProxmark(g_session.current_device) != PM3_SUCCESS)) {
373 CloseProxmark(g_session.current_device);
374 } else {
375 break;
380 #if defined(__MACH__) && defined(__APPLE__)
381 enableAppNap();
382 #endif
384 __atomic_test_and_set(&reconnect_ok, __ATOMIC_SEQ_CST);
386 pthread_exit(NULL);
387 return NULL;
390 void StartReconnectProxmark(void) {
391 pthread_create(&reconnect_thread, NULL, &uart_reconnect, &g_conn);
394 bool IsReconnectedOk(void) {
395 bool ret = __atomic_load_n(&reconnect_ok, __ATOMIC_SEQ_CST);
396 return ret;
399 // The communications thread.
400 // signals to main thread when a response is ready to process.
402 static void
403 #ifdef __has_attribute
404 #if __has_attribute(force_align_arg_pointer)
405 __attribute__((force_align_arg_pointer))
406 #endif
407 #endif
408 *uart_communication(void *targ) {
409 const communication_arg_t *connection = (communication_arg_t *)targ;
410 uint32_t rxlen;
411 bool commfailed = false;
412 PacketResponseNG rx;
413 PacketResponseNGRaw rx_raw;
414 // Stash the last state of is_receiving_raw, to detect if state changed
415 bool is_receiving_raw_last = false;
417 #if defined(__MACH__) && defined(__APPLE__)
418 disableAppNap("Proxmark3 polling UART");
419 #endif
421 // is this connection->run a cross thread call?
422 while (connection->run) {
423 rxlen = 0;
424 bool ACK_received = false;
425 bool error = false;
426 int res;
428 // Signal to main thread that communications seems off.
429 // main thread will kill and restart this thread.
430 if (commfailed) {
431 if (g_conn.last_command != CMD_HARDWARE_RESET) {
432 PrintAndLogEx(WARNING, "\nCommunicating with Proxmark3 device " _RED_("failed"));
434 __atomic_test_and_set(&comm_thread_dead, __ATOMIC_SEQ_CST);
435 break;
438 bool is_receiving_raw = __atomic_load_n(&comm_raw_mode, __ATOMIC_SEQ_CST);
440 if (is_receiving_raw) {
441 uint8_t *bufferData = __atomic_load_n(&comm_raw_data, __ATOMIC_SEQ_CST); // read only
442 size_t bufferLen = __atomic_load_n(&comm_raw_len, __ATOMIC_SEQ_CST); // read only
443 size_t bufferPos = __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST); // read and write
444 if (bufferPos < bufferLen) {
445 size_t rxMaxLen = bufferLen - bufferPos;
447 rxMaxLen = MIN(COMM_RAW_RECEIVE_LEN, rxMaxLen);
449 res = uart_receive(sp, bufferData + bufferPos, rxMaxLen, &rxlen);
450 if (res == PM3_SUCCESS) {
451 uint64_t clk = msclock();
452 __atomic_store_n(&timeout_start_time, clk, __ATOMIC_SEQ_CST);
453 __atomic_store_n(&comm_raw_pos, bufferPos + rxlen, __ATOMIC_SEQ_CST);
454 } else if (res != PM3_ENODATA) {
455 PrintAndLogEx(WARNING, "Error when reading raw data: %zu/%zu, %d", bufferPos, bufferLen, res);
456 error = true;
457 if (res == PM3_ENOTTY) {
458 commfailed = true;
461 } else {
462 // Ignore data when bufferPos >= bufferLen and is_receiving_raw has not been set to false
463 uint8_t dummyData[64];
464 uint32_t dummyLen;
465 uart_receive(sp, dummyData, sizeof(dummyData), &dummyLen);
467 } else {
468 if (is_receiving_raw_last) {
469 // is_receiving_raw changed from true to false
471 // Set the buffer as undefined
472 // comm_raw_data == NULL is used in SetCommunicationReceiveMode()
473 __atomic_store_n(&comm_raw_data, NULL, __ATOMIC_SEQ_CST);
475 res = uart_receive(sp, (uint8_t *)&rx_raw.pre, sizeof(PacketResponseNGPreamble), &rxlen);
477 if ((res == PM3_SUCCESS) && (rxlen == sizeof(PacketResponseNGPreamble))) {
479 rx.magic = rx_raw.pre.magic;
480 uint16_t length = rx_raw.pre.length;
481 rx.ng = rx_raw.pre.ng;
482 rx.status = rx_raw.pre.status;
483 rx.cmd = rx_raw.pre.cmd;
485 if (rx.magic == RESPONSENG_PREAMBLE_MAGIC) { // New style NG reply
487 if (length > PM3_CMD_DATA_SIZE) {
488 PrintAndLogEx(WARNING, "Received packet frame with incompatible length: 0x%04x", length);
489 error = true;
492 if ((!error) && (length > 0)) { // Get the variable length payload
494 res = uart_receive(sp, (uint8_t *)&rx_raw.data, length, &rxlen);
496 if ((res != PM3_SUCCESS) || (rxlen != length)) {
498 PrintAndLogEx(WARNING, "Received packet frame with variable part too short? %d/%d", rxlen, length);
499 error = true;
501 } else {
503 if (rx.ng) { // Received a valid NG frame
505 memcpy(&rx.data, &rx_raw.data, length);
506 rx.length = length;
507 if ((rx.cmd == g_conn.last_command) && (rx.status == PM3_SUCCESS)) {
508 ACK_received = true;
511 } else {
512 uint64_t arg[3];
513 if (length < sizeof(arg)) {
514 PrintAndLogEx(WARNING, "Received MIX packet frame with incompatible length: 0x%04x", length);
515 error = true;
518 if (!error) { // Received a valid MIX frame
520 memcpy(arg, &rx_raw.data, sizeof(arg));
521 rx.oldarg[0] = arg[0];
522 rx.oldarg[1] = arg[1];
523 rx.oldarg[2] = arg[2];
524 memcpy(&rx.data, ((uint8_t *)&rx_raw.data) + sizeof(arg), length - sizeof(arg));
525 rx.length = length - sizeof(arg);
527 if (rx.cmd == CMD_ACK) {
528 ACK_received = true;
533 } else if ((!error) && (length == 0)) { // we received an empty frame
535 if (rx.ng) {
536 rx.length = 0; // set received length to 0
537 } else { // old frames can't be empty
538 PrintAndLogEx(WARNING, "Received empty MIX packet frame (length: 0x00)");
539 error = true;
544 if (!error) { // Get the postamble
545 res = uart_receive(sp, (uint8_t *)&rx_raw.foopost, sizeof(PacketResponseNGPostamble), &rxlen);
546 if ((res != PM3_SUCCESS) || (rxlen != sizeof(PacketResponseNGPostamble))) {
547 PrintAndLogEx(WARNING, "Received packet frame without postamble");
548 error = true;
552 if (!error) { // Check CRC, accept MAGIC as placeholder
553 rx.crc = rx_raw.foopost.crc;
555 if (rx.crc != RESPONSENG_POSTAMBLE_MAGIC) {
557 uint8_t first, second;
558 compute_crc(CRC_14443_A, (uint8_t *)&rx_raw, sizeof(PacketResponseNGPreamble) + length, &first, &second);
560 if ((first << 8) + second != rx.crc) {
561 PrintAndLogEx(WARNING, "Received packet frame with invalid CRC %02X%02X <> %04X", first, second, rx.crc);
562 error = true;
566 if (!error) { // Received a valid OLD frame
567 #ifdef COMMS_DEBUG
568 PrintAndLogEx(NORMAL, "Receiving %s:", rx.ng ? "NG" : "MIX");
569 #endif
570 #ifdef COMMS_DEBUG_RAW
571 print_hex_break((uint8_t *)&rx_raw.pre, sizeof(PacketResponseNGPreamble), 32);
572 print_hex_break((uint8_t *)&rx_raw.data, rx_raw.pre.length, 32);
573 print_hex_break((uint8_t *)&rx_raw.foopost, sizeof(PacketResponseNGPostamble), 32);
574 #endif
575 PacketResponseReceived(&rx);
577 } else { // Old style reply
578 PacketResponseOLD rx_old;
579 memcpy(&rx_old, &rx_raw.pre, sizeof(PacketResponseNGPreamble));
581 res = uart_receive(sp, ((uint8_t *)&rx_old) + sizeof(PacketResponseNGPreamble), sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble), &rxlen);
582 if ((res != PM3_SUCCESS) || (rxlen != sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble))) {
583 PrintAndLogEx(WARNING, "Received packet OLD frame with payload too short? %d/%zu", rxlen, sizeof(PacketResponseOLD) - sizeof(PacketResponseNGPreamble));
584 error = true;
586 if (!error) {
587 #ifdef COMMS_DEBUG
588 PrintAndLogEx(NORMAL, "Receiving OLD:");
589 #endif
590 #ifdef COMMS_DEBUG_RAW
591 print_hex_break((uint8_t *)&rx_old.cmd, sizeof(rx_old.cmd), 32);
592 print_hex_break((uint8_t *)&rx_old.arg, sizeof(rx_old.arg), 32);
593 print_hex_break((uint8_t *)&rx_old.d, sizeof(rx_old.d), 32);
594 #endif
595 rx.ng = false;
596 rx.magic = 0;
597 rx.status = 0;
598 rx.crc = 0;
599 rx.cmd = rx_old.cmd;
600 rx.oldarg[0] = rx_old.arg[0];
601 rx.oldarg[1] = rx_old.arg[1];
602 rx.oldarg[2] = rx_old.arg[2];
603 rx.length = PM3_CMD_DATA_SIZE;
604 memcpy(&rx.data, &rx_old.d, rx.length);
605 PacketResponseReceived(&rx);
606 if (rx.cmd == CMD_ACK) {
607 ACK_received = true;
611 } else {
612 if (rxlen > 0) {
613 PrintAndLogEx(WARNING, "Received packet frame preamble too short: %d/%zu", rxlen, sizeof(PacketResponseNGPreamble));
614 error = true;
616 if (res == PM3_ENOTTY) {
617 commfailed = true;
622 is_receiving_raw_last = is_receiving_raw;
623 // TODO if error, shall we resync ?
625 pthread_mutex_lock(&txBufferMutex);
627 if (connection->block_after_ACK) {
628 // if we just received an ACK, wait here until a new command is to be transmitted
629 // This is only working on OLD frames, and only used by flasher and flashmem
630 if (ACK_received) {
631 #ifdef COMMS_DEBUG
632 PrintAndLogEx(NORMAL, "Received ACK, fast TX mode: ignoring other RX till TX");
633 #endif
634 while (!txBuffer_pending) {
635 pthread_cond_wait(&txBufferSig, &txBufferMutex);
640 if (txBuffer_pending) {
642 if (txBufferNGLen) { // NG packet
643 res = uart_send(sp, (uint8_t *) &txBufferNG, txBufferNGLen);
644 if (res == PM3_EIO) {
645 commfailed = true;
647 g_conn.last_command = txBufferNG.pre.cmd;
648 txBufferNGLen = 0;
649 } else {
650 res = uart_send(sp, (uint8_t *) &txBuffer, sizeof(PacketCommandOLD));
651 if (res == PM3_EIO) {
652 commfailed = true;
654 g_conn.last_command = txBuffer.cmd;
657 txBuffer_pending = false;
659 // main thread doesn't know send failed...
661 // tell main thread that txBuffer is empty
662 pthread_cond_signal(&txBufferSig);
665 pthread_mutex_unlock(&txBufferMutex);
668 // when thread dies, we close the serial port.
669 uart_close(sp);
670 sp = NULL;
672 #if defined(__MACH__) && defined(__APPLE__)
673 enableAppNap();
674 #endif
676 pthread_exit(NULL);
677 return NULL;
680 bool IsCommunicationThreadDead(void) {
681 bool ret = __atomic_load_n(&comm_thread_dead, __ATOMIC_SEQ_CST);
682 return ret;
687 // To start raw receive mode:
688 // 1. Call SetCommunicationRawReceiveBuffer(...)
689 // 2. Call SetCommunicationReceiveMode(true)
691 // To stop raw receive mode:
692 // Call SetCommunicationReceiveMode(false)
694 // Note:
695 // 1. The receiving thread won't accept any normal packets after calling
696 // SetCommunicationReceiveMode(true). You need to call
697 // SetCommunicationReceiveMode(false) to stop the raw receiving process.
698 // 2. If the received size >= len used in SetCommunicationRawReceiveBuffer(),
699 // The receiving thread will ignore the incoming data to prevent overflow.
700 // 3. Normally you only need WaitForRawDataTimeout() rather than the
701 // low level functions like SetCommunicationReceiveMode(),
702 // SetCommunicationRawReceiveBuffer() and GetCommunicationRawReceiveNum()
704 bool SetCommunicationReceiveMode(bool isRawMode) {
705 if (isRawMode) {
706 const uint8_t *buffer = __atomic_load_n(&comm_raw_data, __ATOMIC_SEQ_CST);
707 if (buffer == NULL) {
708 PrintAndLogEx(ERR, "Buffer for raw data is not set");
709 return false;
712 __atomic_store_n(&comm_raw_mode, isRawMode, __ATOMIC_SEQ_CST);
713 return true;
716 void SetCommunicationRawReceiveBuffer(uint8_t *buffer, size_t len) {
717 __atomic_store_n(&comm_raw_data, buffer, __ATOMIC_SEQ_CST);
718 __atomic_store_n(&comm_raw_len, len, __ATOMIC_SEQ_CST);
719 __atomic_store_n(&comm_raw_pos, 0, __ATOMIC_SEQ_CST);
722 size_t GetCommunicationRawReceiveNum(void) {
723 return __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST);
726 bool OpenProxmarkSilent(pm3_device_t **dev, const char *port, uint32_t speed) {
728 sp = uart_open(port, speed, true);
730 // check result of uart opening
731 if (sp == INVALID_SERIAL_PORT) {
732 sp = NULL;
733 return false;
734 } else if (sp == CLAIMED_SERIAL_PORT) {
735 sp = NULL;
736 return false;
737 } else {
738 // start the communication thread
739 if (port != g_conn.serial_port_name) {
740 uint16_t len = MIN(strlen(port), FILE_PATH_SIZE - 1);
741 memset(g_conn.serial_port_name, 0, FILE_PATH_SIZE);
742 memcpy(g_conn.serial_port_name, port, len);
744 g_conn.run = true;
745 g_conn.block_after_ACK = false;
746 // Flags to tell where to add CRC on sent replies
747 g_conn.send_with_crc_on_usb = false;
748 g_conn.send_with_crc_on_fpc = true;
749 // "Session" flag, to tell via which interface next msgs should be sent: USB or FPC USART
750 g_conn.send_via_fpc_usart = false;
752 pthread_create(&communication_thread, NULL, &uart_communication, &g_conn);
753 __atomic_clear(&comm_thread_dead, __ATOMIC_SEQ_CST);
754 __atomic_clear(&reconnect_ok, __ATOMIC_SEQ_CST);
756 g_session.pm3_present = true; // TODO support for multiple devices
758 fflush(stdout);
759 if (*dev == NULL) {
760 *dev = calloc(sizeof(pm3_device_t), sizeof(uint8_t));
762 (*dev)->g_conn = &g_conn; // TODO g_conn shouldn't be global
763 return true;
767 bool OpenProxmark(pm3_device_t **dev, const char *port, bool wait_for_port, int timeout, bool flash_mode, uint32_t speed) {
769 if (wait_for_port == false) {
770 PrintAndLogEx(SUCCESS, "Using UART port " _GREEN_("%s"), port);
771 sp = uart_open(port, speed, false);
772 } else {
773 PrintAndLogEx(SUCCESS, "Waiting for Proxmark3 to appear on " _YELLOW_("%s"), port);
774 fflush(stdout);
775 int openCount = 0;
776 PrintAndLogEx(INPLACE, "% 3i", timeout);
777 do {
778 sp = uart_open(port, speed, false);
779 msleep(500);
780 PrintAndLogEx(INPLACE, "% 3i", timeout - openCount - 1);
782 } while (++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
785 // check result of uart opening
786 if (sp == INVALID_SERIAL_PORT) {
787 PrintAndLogEx(WARNING, "\n" _RED_("ERROR:") " invalid serial port " _YELLOW_("%s"), port);
788 PrintAndLogEx(HINT, "Try the shell script " _YELLOW_("`./pm3 --list`") " to get a list of possible serial ports");
789 sp = NULL;
790 return false;
791 } else if (sp == CLAIMED_SERIAL_PORT) {
792 PrintAndLogEx(WARNING, "\n" _RED_("ERROR:") " serial port " _YELLOW_("%s") " is claimed by another process", port);
793 PrintAndLogEx(HINT, "Try the shell script " _YELLOW_("`./pm3 --list`") " to get a list of possible serial ports");
795 sp = NULL;
796 return false;
797 } else {
798 // start the communication thread
799 if (port != g_conn.serial_port_name) {
800 uint16_t len = MIN(strlen(port), FILE_PATH_SIZE - 1);
801 memset(g_conn.serial_port_name, 0, FILE_PATH_SIZE);
802 memcpy(g_conn.serial_port_name, port, len);
804 g_conn.run = true;
805 g_conn.block_after_ACK = flash_mode;
806 // Flags to tell where to add CRC on sent replies
807 g_conn.send_with_crc_on_usb = false;
808 g_conn.send_with_crc_on_fpc = true;
809 // "Session" flag, to tell via which interface next msgs should be sent: USB or FPC USART
810 g_conn.send_via_fpc_usart = false;
812 pthread_create(&communication_thread, NULL, &uart_communication, &g_conn);
813 __atomic_clear(&comm_thread_dead, __ATOMIC_SEQ_CST);
814 g_session.pm3_present = true; // TODO support for multiple devices
816 fflush(stdout);
817 if (*dev == NULL) {
818 *dev = calloc(sizeof(pm3_device_t), sizeof(uint8_t));
820 (*dev)->g_conn = &g_conn; // TODO g_conn shouldn't be global
821 return true;
825 // check if we can communicate with Pm3
826 int TestProxmark(pm3_device_t *dev) {
828 uint16_t len = 32;
829 uint8_t data[len];
830 for (uint16_t i = 0; i < len; i++) {
831 data[i] = i & 0xFF;
834 __atomic_store_n(&last_packet_time, msclock(), __ATOMIC_SEQ_CST);
835 clearCommandBuffer();
836 SendCommandNG(CMD_PING, data, len);
838 uint32_t timeout;
840 #ifdef USART_SLOW_LINK
841 // 10s timeout for slow FPC, e.g. over BT
842 // as this is the very first command sent to the pm3
843 // that initiates the BT connection
844 timeout = 10000;
845 #else
846 timeout = 1000;
847 #endif
849 PacketResponseNG resp;
850 if (WaitForResponseTimeoutW(CMD_PING, &resp, timeout, false) == 0) {
851 return PM3_ETIMEOUT;
854 bool error = memcmp(data, resp.data.asBytes, len) != 0;
855 if (error) {
856 return PM3_EIO;
859 SendCommandNG(CMD_CAPABILITIES, NULL, 0);
860 if (WaitForResponseTimeoutW(CMD_CAPABILITIES, &resp, 1000, false) == 0) {
861 return PM3_ETIMEOUT;
864 if ((resp.length != sizeof(g_pm3_capabilities)) || (resp.data.asBytes[0] != CAPABILITIES_VERSION)) {
865 PrintAndLogEx(ERR, _RED_("Capabilities structure version sent by Proxmark3 is not the same as the one used by the client!"));
866 PrintAndLogEx(ERR, _RED_("Please flash the Proxmark3 with the same version as the client."));
867 return PM3_EDEVNOTSUPP;
870 memcpy(&g_pm3_capabilities, resp.data.asBytes, sizeof(capabilities_t));
871 g_conn.send_via_fpc_usart = g_pm3_capabilities.via_fpc;
872 g_conn.uart_speed = g_pm3_capabilities.baudrate;
874 bool is_tcp_conn = (g_conn.send_via_ip == PM3_TCPv4 || g_conn.send_via_ip == PM3_TCPv6);
875 bool is_bt_conn = (memcmp(g_conn.serial_port_name, "bt:", 3) == 0);
876 bool is_udp_conn = (g_conn.send_via_ip == PM3_UDPv4 || g_conn.send_via_ip == PM3_UDPv6);
878 PrintAndLogEx(SUCCESS, "Communicating with PM3 over %s%s%s%s",
879 (g_conn.send_via_fpc_usart) ? _GREEN_("FPC UART") : _GREEN_("USB-CDC"),
880 (is_tcp_conn) ? " over " _GREEN_("TCP") : "",
881 (is_bt_conn) ? " over " _GREEN_("BT") : "",
882 (is_udp_conn) ? " over " _GREEN_("UDP") : ""
884 if (g_conn.send_via_fpc_usart) {
885 PrintAndLogEx(SUCCESS, "PM3 UART serial baudrate: " _GREEN_("%u") "\n", g_conn.uart_speed);
886 } else {
887 int res;
888 if (g_conn.send_via_local_ip) {
889 // (g_conn.send_via_local_ip == true) -> ((is_tcp_conn || is_udp_conn) == true)
890 res = uart_reconfigure_timeouts(is_tcp_conn ? UART_TCP_LOCAL_CLIENT_RX_TIMEOUT_MS : UART_UDP_LOCAL_CLIENT_RX_TIMEOUT_MS);
891 } else if (is_tcp_conn || is_udp_conn) {
892 res = uart_reconfigure_timeouts(UART_NET_CLIENT_RX_TIMEOUT_MS);
893 } else {
894 res = uart_reconfigure_timeouts(UART_USB_CLIENT_RX_TIMEOUT_MS);
896 if (res != PM3_SUCCESS) {
897 return res;
900 return PM3_SUCCESS;
903 void CloseProxmark(pm3_device_t *dev) {
904 dev->g_conn->run = false;
906 #ifdef __BIONIC__
907 if (communication_thread != 0) {
908 pthread_join(communication_thread, NULL);
910 #else
911 pthread_join(communication_thread, NULL);
912 #endif
914 if (sp) {
915 uart_close(sp);
918 // Clean up our state
919 sp = NULL;
920 #ifdef __BIONIC__
921 if (communication_thread != 0) {
922 memset(&communication_thread, 0, sizeof(pthread_t));
924 #else
925 memset(&communication_thread, 0, sizeof(pthread_t));
926 #endif
928 g_session.pm3_present = false;
931 // Gives a rough estimate of the communication delay based on channel & baudrate
932 // Max communication delay is when sending largest frame and receiving largest frame
933 // Empirical measures on FTDI with physical cable:
934 // "hw pingng 512"
935 // usb -> 6..32ms
936 // 460800 -> 40..70ms
937 // 9600 -> 1100..1150ms
938 // ~ = 12000000 / USART_BAUD_RATE
939 // Let's take 2x (maybe we need more for BT link?)
940 static size_t communication_delay(void) {
941 // needed also for Windows USB USART??
942 if (g_conn.send_via_fpc_usart) {
943 return 2 * (12000000 / g_conn.uart_speed);
945 return 0;
950 * @brief Wait for receiving a specified amount of bytes
952 * @param buffer The receive buffer
953 * @param len The maximum receive byte size
954 * @param ms_timeout the maximum timeout
955 * @param show_process print how many bytes are received
956 * @return the number of received bytes
958 size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, bool show_process) {
959 uint8_t print_counter = 0;
960 size_t last_pos = 0;
962 // Add delay depending on the communication channel & speed
963 if (ms_timeout != (size_t) - 1) {
964 ms_timeout += communication_delay();
966 __atomic_store_n(&timeout_start_time, msclock(), __ATOMIC_SEQ_CST);
968 SetCommunicationRawReceiveBuffer(buffer, len);
969 SetCommunicationReceiveMode(true);
971 size_t pos = 0;
972 while (pos < len) {
974 if (kbd_enter_pressed()) {
975 // Send anything to stop the transfer
976 PrintAndLogEx(INFO, "Stopping");
977 SendCommandNG(CMD_BREAK_LOOP, NULL, 0);
979 // For ms_timeout == -1, pos < len might always be true
980 // so user need a spectial way to break this loop
981 if (ms_timeout == (size_t) - 1) {
982 break;
986 pos = __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST);
988 // Check the timeout if pos is not updated
989 if (last_pos == pos) {
990 uint64_t tmp_clk = __atomic_load_n(&timeout_start_time, __ATOMIC_SEQ_CST);
991 // If ms_timeout == -1, the loop can only be breaked by pressing Enter or receiving enough data
992 if ((ms_timeout != (size_t) - 1) && (msclock() - tmp_clk > ms_timeout)) {
993 break;
995 } else {
996 // Print process when (print_counter % 64) == 0
997 if (show_process && (print_counter & 0x3F) == 0) {
998 PrintAndLogEx(INFO, "[%zu/%zu]", pos, len);
1002 print_counter++;
1003 last_pos = pos;
1004 msleep(10);
1006 if (pos == len && (ms_timeout != (size_t) - 1)) {
1007 // If ms_timeout != -1, when the desired data is received, tell the arm side
1008 // to stop the current process, and wait for some time to make sure the process
1009 // has been stopped.
1010 // If ms_timeout == -1, the user might not want to break the existing process
1011 // on the arm side.
1012 SendCommandNG(CMD_BREAK_LOOP, NULL, 0);
1013 msleep(ms_timeout);
1015 SetCommunicationReceiveMode(false);
1016 pos = __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST);
1017 return pos;
1021 * @brief Waits for a certain response type. This method waits for a maximum of
1022 * ms_timeout milliseconds for a specified response command.
1024 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
1025 * @param response struct to copy received command into.
1026 * @param ms_timeout display message after 3 seconds
1027 * @param show_warning display message after 3 seconds
1028 * @return true if command was returned, otherwise false
1030 bool WaitForResponseTimeoutW(uint32_t cmd, PacketResponseNG *response, size_t ms_timeout, bool show_warning) {
1032 PacketResponseNG resp;
1033 // init to ZERO
1034 resp.cmd = 0,
1035 resp.length = 0,
1036 resp.magic = 0,
1037 resp.status = 0,
1038 resp.crc = 0,
1039 resp.ng = false,
1040 resp.oldarg[0] = 0;
1041 resp.oldarg[1] = 0;
1042 resp.oldarg[2] = 0;
1043 memset(resp.data.asBytes, 0, PM3_CMD_DATA_SIZE);
1045 if (response == NULL) {
1046 response = &resp;
1049 // Add delay depending on the communication channel & speed
1050 if (ms_timeout != (size_t) - 1)
1051 ms_timeout += communication_delay();
1053 __atomic_store_n(&timeout_start_time, msclock(), __ATOMIC_SEQ_CST);
1055 // Wait until the command is received
1056 while (true) {
1058 // if device gets disconnected or resets, break out of this loop
1059 if (IsCommunicationThreadDead()) {
1060 break;
1063 while (getReply(response)) {
1064 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
1065 return true;
1068 if (response->cmd == CMD_WTX && response->length == sizeof(uint16_t)) {
1069 uint16_t wtx = response->data.asDwords[0] & 0xFFFF;
1070 PrintAndLogEx(DEBUG, "Got Waiting Time eXtension request %i ms", wtx);
1071 if (ms_timeout != (size_t) - 1) {
1072 ms_timeout += wtx;
1077 uint64_t tmp_clk = __atomic_load_n(&timeout_start_time, __ATOMIC_SEQ_CST);
1078 if ((ms_timeout != (size_t) - 1) && (msclock() - tmp_clk > ms_timeout)) {
1079 break;
1082 if (msclock() - tmp_clk > 3000 && show_warning) {
1083 // 3 seconds elapsed (but this doesn't mean the timeout was exceeded)
1084 PrintAndLogEx(INFO, "You can cancel this operation by pressing the pm3 button");
1085 show_warning = false;
1087 // just to avoid CPU busy loop:
1088 msleep(1);
1090 return false;
1093 bool WaitForResponseTimeout(uint32_t cmd, PacketResponseNG *response, size_t ms_timeout) {
1094 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
1097 bool WaitForResponse(uint32_t cmd, PacketResponseNG *response) {
1098 return WaitForResponseTimeoutW(cmd, response, -1, true);
1102 * Data transfer from Proxmark to client. This method times out after
1103 * ms_timeout milliseconds.
1104 * @brief GetFromDevice
1105 * @param memtype Type of memory to download from proxmark
1106 * @param dest Destination address for transfer
1107 * @param bytes number of bytes to be transferred
1108 * @param start_index offset into Proxmark3 BigBuf[]
1109 * @param data used by SPIFFS to provide filename
1110 * @param datalen used by SPIFFS to provide filename length
1111 * @param response struct to copy last command (CMD_ACK) into
1112 * @param ms_timeout timeout in milliseconds
1113 * @param show_warning display message after 2 seconds
1114 * @return true if command was returned, otherwise false
1116 bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, uint8_t *data, uint32_t datalen, PacketResponseNG *response, size_t ms_timeout, bool show_warning) {
1118 if (dest == NULL) return false;
1120 PacketResponseNG resp;
1121 if (response == NULL) {
1122 response = &resp;
1125 // init to ZERO
1126 resp.cmd = 0,
1127 resp.length = 0,
1128 resp.magic = 0,
1129 resp.status = 0,
1130 resp.crc = 0,
1131 resp.ng = false,
1132 resp.oldarg[0] = 0;
1133 resp.oldarg[1] = 0;
1134 resp.oldarg[2] = 0;
1135 memset(resp.data.asBytes, 0, PM3_CMD_DATA_SIZE);
1137 if (bytes == 0) return true;
1140 // clear
1141 clearCommandBuffer();
1143 switch (memtype) {
1144 case BIG_BUF: {
1145 SendCommandMIX(CMD_DOWNLOAD_BIGBUF, start_index, bytes, 0, NULL, 0);
1146 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_BIGBUF);
1148 case BIG_BUF_EML: {
1149 SendCommandMIX(CMD_DOWNLOAD_EML_BIGBUF, start_index, bytes, 0, NULL, 0);
1150 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_EML_BIGBUF);
1152 case SPIFFS: {
1153 SendCommandMIX(CMD_SPIFFS_DOWNLOAD, start_index, bytes, 0, data, datalen);
1154 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_SPIFFS_DOWNLOADED);
1156 case FLASH_MEM: {
1157 SendCommandMIX(CMD_FLASHMEM_DOWNLOAD, start_index, bytes, 0, NULL, 0);
1158 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_FLASHMEM_DOWNLOADED);
1160 case SIM_MEM: {
1161 //SendCommandMIX(CMD_DOWNLOAD_SIM_MEM, start_index, bytes, 0, NULL, 0);
1162 //return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_DOWNLOADED_SIMMEM);
1163 return false;
1165 case FPGA_MEM: {
1166 SendCommandNG(CMD_FPGAMEM_DOWNLOAD, NULL, 0);
1167 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_FPGAMEM_DOWNLOADED);
1169 case MCU_FLASH:
1170 case MCU_MEM: {
1171 uint32_t flags = (memtype == MCU_MEM) ? READ_MEM_DOWNLOAD_FLAG_RAW : 0;
1172 SendCommandBL(CMD_READ_MEM_DOWNLOAD, start_index, bytes, flags, NULL, 0);
1173 return dl_it(dest, bytes, response, ms_timeout, show_warning, CMD_READ_MEM_DOWNLOADED);
1176 return false;
1179 static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd) {
1181 uint32_t bytes_completed = 0;
1182 __atomic_store_n(&timeout_start_time, msclock(), __ATOMIC_SEQ_CST);
1184 // Add delay depending on the communication channel & speed
1185 if (ms_timeout != (size_t) - 1)
1186 ms_timeout += communication_delay();
1188 while (true) {
1190 if (getReply(response)) {
1192 if (response->cmd == CMD_ACK)
1193 return true;
1194 if (response->cmd == CMD_SPIFFS_DOWNLOAD && response->status == PM3_EMALLOC)
1195 return false;
1196 // Spiffs // fpgamem-plot download is converted to NG,
1197 if (response->cmd == CMD_SPIFFS_DOWNLOAD || response->cmd == CMD_FPGAMEM_DOWNLOAD)
1198 return true;
1200 // sample_buf is a array pointer, located in data.c
1201 // arg0 = offset in transfer. Startindex of this chunk
1202 // arg1 = length bytes to transfer
1203 // arg2 = bigbuff tracelength (?)
1204 if (response->cmd == rec_cmd) {
1206 uint32_t offset = response->oldarg[0];
1207 uint32_t copy_bytes = MIN(bytes - bytes_completed, response->oldarg[1]);
1208 //uint32_t tracelen = response->oldarg[2];
1210 // extended bounds check1. upper limit is PM3_CMD_DATA_SIZE
1211 // shouldn't happen
1212 copy_bytes = MIN(copy_bytes, PM3_CMD_DATA_SIZE);
1214 // extended bounds check2.
1215 if (offset + copy_bytes > bytes) {
1216 PrintAndLogEx(FAILED, "ERROR: Out of bounds when downloading from device, offset %u | len %u | total len %u > buf_size %u", offset, copy_bytes, offset + copy_bytes, bytes);
1217 break;
1220 memcpy(dest + offset, response->data.asBytes, copy_bytes);
1221 bytes_completed += copy_bytes;
1222 } else if (response->cmd == CMD_WTX && response->length == sizeof(uint16_t)) {
1223 uint16_t wtx = response->data.asDwords[0] & 0xFFFF;
1224 PrintAndLogEx(DEBUG, "Got Waiting Time eXtension request %i ms", wtx);
1225 if (ms_timeout != (size_t) - 1)
1226 ms_timeout += wtx;
1230 uint64_t tmp_clk = __atomic_load_n(&timeout_start_time, __ATOMIC_SEQ_CST);
1231 if (msclock() - tmp_clk > ms_timeout) {
1232 PrintAndLogEx(FAILED, "Timed out while trying to download data from device");
1233 break;
1236 if (msclock() - tmp_clk > 3000 && show_warning) {
1237 // 3 seconds elapsed (but this doesn't mean the timeout was exceeded)
1238 PrintAndLogEx(INFO, "Waiting for a response from the Proxmark3...");
1239 PrintAndLogEx(INFO, "You can cancel this operation by pressing the pm3 button");
1240 show_warning = false;
1243 return false;