1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2009 Michael Gernoth <michael at gernoth.net>
3 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
8 //-----------------------------------------------------------------------------
9 // Code for communicating with the proxmark3 hardware.
10 //-----------------------------------------------------------------------------
17 #if defined(__linux__) && !defined(NO_UNLINK)
18 #include <unistd.h> // for unlink()
23 #include "util_darwin.h"
24 #include "util_posix.h"
27 // Serial port that we are communicating with the PM3 on.
28 static serial_port sp
= NULL
;
29 static char *serial_port_name
= NULL
;
31 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
35 bool run
; // If TRUE, continue running the uart_communication thread
36 bool block_after_ACK
; // if true, block after receiving an ACK package
37 } communication_arg_t
;
39 static communication_arg_t conn
;
40 static pthread_t USB_communication_thread
;
43 static UsbCommand txBuffer
;
44 static bool txBuffer_pending
= false;
45 static pthread_mutex_t txBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
46 static pthread_cond_t txBufferSig
= PTHREAD_COND_INITIALIZER
;
48 // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
49 // processed by a command handler (WaitForResponse{,Timeout})
50 #define CMD_BUFFER_SIZE 50
51 static UsbCommand rxBuffer
[CMD_BUFFER_SIZE
];
53 // Points to the next empty position to write to
54 static int cmd_head
= 0;
56 // Points to the position of the last unread command
57 static int cmd_tail
= 0;
59 // to lock rxBuffer operations from different threads
60 static pthread_mutex_t rxBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
62 // These wrappers are required because it is not possible to access a static
63 // global variable outside of the context of a single file.
65 void SetOffline(bool new_offline
) {
66 offline
= new_offline
;
73 void SendCommand(UsbCommand
*c
) {
75 printf("Sending %04x cmd\n", c
->cmd
);
79 PrintAndLog("Sending bytes to proxmark failed - offline");
83 pthread_mutex_lock(&txBufferMutex
);
85 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
86 but comm thread just spins here. Not good.../holiman
88 while (txBuffer_pending
) {
89 pthread_cond_wait(&txBufferSig
, &txBufferMutex
); // wait for communication thread to complete sending a previous commmand
93 txBuffer_pending
= true;
94 pthread_cond_signal(&txBufferSig
); // tell communication thread that a new command can be send
96 pthread_mutex_unlock(&txBufferMutex
);
102 * @brief This method should be called when sending a new command to the pm3. In case any old
103 * responses from previous commands are stored in the buffer, a call to this method should clear them.
104 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
105 * operation. Right now we'll just have to live with this.
107 void clearCommandBuffer()
109 //This is a very simple operation
110 pthread_mutex_lock(&rxBufferMutex
);
112 pthread_mutex_unlock(&rxBufferMutex
);
116 * @brief storeCommand stores a USB command in a circular buffer
119 static void storeCommand(UsbCommand
*command
)
121 pthread_mutex_lock(&rxBufferMutex
);
122 if( (cmd_head
+1) % CMD_BUFFER_SIZE
== cmd_tail
)
124 // If these two are equal, we're about to overwrite in the
126 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
129 // Store the command at the 'head' location
130 UsbCommand
* destination
= &rxBuffer
[cmd_head
];
131 memcpy(destination
, command
, sizeof(UsbCommand
));
133 cmd_head
= (cmd_head
+1) % CMD_BUFFER_SIZE
; //increment head and wrap
134 pthread_mutex_unlock(&rxBufferMutex
);
139 * @brief getCommand gets a command from an internal circular buffer.
140 * @param response location to write command
141 * @return 1 if response was returned, 0 if nothing has been received
143 static int getCommand(UsbCommand
* response
)
145 pthread_mutex_lock(&rxBufferMutex
);
146 //If head == tail, there's nothing to read, or if we just got initialized
147 if (cmd_head
== cmd_tail
){
148 pthread_mutex_unlock(&rxBufferMutex
);
152 //Pick out the next unread command
153 UsbCommand
* last_unread
= &rxBuffer
[cmd_tail
];
154 memcpy(response
, last_unread
, sizeof(UsbCommand
));
155 //Increment tail - this is a circular buffer, so modulo buffer size
156 cmd_tail
= (cmd_tail
+ 1) % CMD_BUFFER_SIZE
;
158 pthread_mutex_unlock(&rxBufferMutex
);
163 //----------------------------------------------------------------------------------
164 // Entry point into our code: called whenever we received a packet over USB.
165 // Handle debug commands directly, store all other commands in circular buffer.
166 //----------------------------------------------------------------------------------
167 static void UsbCommandReceived(UsbCommand
*UC
)
170 // First check if we are handling a debug message
171 case CMD_DEBUG_PRINT_STRING
: {
172 char s
[USB_CMD_DATA_SIZE
+1];
173 memset(s
, 0x00, sizeof(s
));
174 size_t len
= MIN(UC
->arg
[0],USB_CMD_DATA_SIZE
);
175 memcpy(s
,UC
->d
.asBytes
,len
);
176 PrintAndLog("#db# %s", s
);
180 case CMD_DEBUG_PRINT_INTEGERS
: {
181 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC
->arg
[0], UC
->arg
[1], UC
->arg
[2]);
193 static bool receive_from_serial(serial_port sp
, uint8_t *rx_buf
, size_t len
, size_t *received_len
) {
194 size_t bytes_read
= 0;
196 // we eventually need to call uart_receive several times if it times out in the middle of a transfer
197 while (uart_receive(sp
, rx_buf
+ *received_len
, len
- *received_len
, &bytes_read
) && bytes_read
&& *received_len
< len
) {
198 if (bytes_read
!= len
- *received_len
) {
199 printf("uart_receive() returned true but not enough bytes could be received. received: %d, wanted to receive: %d, already received before: %d\n",
200 bytes_read
, len
- *received_len
, *received_len
);
202 *received_len
+= bytes_read
;
205 return (*received_len
== len
);
210 #ifdef __has_attribute
211 #if __has_attribute(force_align_arg_pointer)
212 __attribute__((force_align_arg_pointer
))
215 *uart_communication(void *targ
) {
216 communication_arg_t
*conn
= (communication_arg_t
*)targ
;
217 uint8_t rx
[sizeof(UsbCommand
)];
220 UsbCommand
*command
= (UsbCommand
*)rx
;
221 UsbResponse
*response
= (UsbResponse
*)rx
;
223 #if defined(__MACH__) && defined(__APPLE__)
224 disableAppNap("Proxmark3 polling UART");
228 bool ACK_received
= false;
230 size_t bytes_to_read
= offsetof(UsbResponse
, d
); // the fixed part of a new style UsbResponse. Otherwise this will be cmd and arg[0] (64 bit each)
231 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
233 if (response
->cmd
& CMD_VARIABLE_SIZE_FLAG
) { // new style response with variable size
234 // printf("received new style response %04" PRIx16 ", datalen = %d, arg[0] = %08" PRIx32 ", arg[1] = %08" PRIx32 ", arg[2] = %08" PRIx32 "\n",
235 // response->cmd, response->datalen, response->arg[0], response->arg[1], response->arg[2]);
236 bytes_to_read
= response
->datalen
;
237 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
239 resp
.cmd
= response
->cmd
& ~CMD_VARIABLE_SIZE_FLAG
;
240 resp
.arg
[0] = response
->arg
[0];
241 resp
.arg
[1] = response
->arg
[1];
242 resp
.arg
[2] = response
->arg
[2];
243 memcpy(&resp
.d
.asBytes
, &response
->d
.asBytes
, response
->datalen
);
244 UsbCommandReceived(&resp
);
245 if (resp
.cmd
== CMD_ACK
) {
249 } else { // old style response uses same data structure as commands. Fixed size.
250 // printf("received old style response %016" PRIx64 ", arg[0] = %016" PRIx64 "\n", command->cmd, command->arg[0]);
251 bytes_to_read
= sizeof(UsbCommand
) - bytes_to_read
;
252 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
253 UsbCommandReceived(command
);
254 if (command
->cmd
== CMD_ACK
) {
261 pthread_mutex_lock(&txBufferMutex
);
263 if (conn
->block_after_ACK
) {
264 // if we just received an ACK, wait here until a new command is to be transmitted
266 while (!txBuffer_pending
) {
267 pthread_cond_wait(&txBufferSig
, &txBufferMutex
);
272 if(txBuffer_pending
) {
273 if (!uart_send(sp
, (uint8_t*) &txBuffer
, sizeof(UsbCommand
))) {
274 PrintAndLog("Sending bytes to proxmark failed");
276 txBuffer_pending
= false;
277 pthread_cond_signal(&txBufferSig
); // tell main thread that txBuffer is empty
280 pthread_mutex_unlock(&txBufferMutex
);
283 #if defined(__MACH__) && defined(__APPLE__)
293 * Data transfer from Proxmark to client. This method times out after
294 * ms_timeout milliseconds.
295 * @brief GetFromBigBuf
296 * @param dest Destination address for transfer
297 * @param bytes number of bytes to be transferred
298 * @param start_index offset into Proxmark3 BigBuf[]
299 * @param response struct to copy last command (CMD_ACK) into
300 * @param ms_timeout timeout in milliseconds
301 * @param show_warning display message after 2 seconds
302 * @return true if command was returned, otherwise false
304 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
)
306 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
309 uint64_t start_time
= msclock();
312 if (response
== NULL
) {
316 int bytes_completed
= 0;
318 if (getCommand(response
)) {
319 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
320 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
321 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
322 bytes_completed
+= copy_bytes
;
323 } else if (response
->cmd
== CMD_ACK
) {
328 if (msclock() - start_time
> ms_timeout
) {
332 if (msclock() - start_time
> 2000 && show_warning
) {
333 PrintAndLog("Waiting for a response from the proxmark...");
334 PrintAndLog("You can cancel this operation by pressing the pm3 button");
335 show_warning
= false;
343 bool GetFromFpgaRAM(uint8_t *dest
, int bytes
)
345 UsbCommand c
= {CMD_HF_PLOT
, {0, 0, 0}};
348 uint64_t start_time
= msclock();
352 int bytes_completed
= 0;
353 bool show_warning
= true;
355 if (getCommand(&response
)) {
356 if (response
.cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
357 int copy_bytes
= MIN(bytes
- bytes_completed
, response
.arg
[1]);
358 memcpy(dest
+ response
.arg
[0], response
.d
.asBytes
, copy_bytes
);
359 bytes_completed
+= copy_bytes
;
360 } else if (response
.cmd
== CMD_ACK
) {
365 if (msclock() - start_time
> 2000 && show_warning
) {
366 PrintAndLog("Waiting for a response from the proxmark...");
367 PrintAndLog("You can cancel this operation by pressing the pm3 button");
368 show_warning
= false;
376 bool OpenProxmark(void *port
, bool wait_for_port
, int timeout
, bool flash_mode
) {
377 char *portname
= (char *)port
;
378 if (!wait_for_port
) {
379 sp
= uart_open(portname
);
381 printf("Waiting for Proxmark to appear on %s ", portname
);
385 sp
= uart_open(portname
);
389 } while(++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
393 // check result of uart opening
394 if (sp
== INVALID_SERIAL_PORT
) {
395 printf("ERROR: invalid serial port\n");
397 serial_port_name
= NULL
;
399 } else if (sp
== CLAIMED_SERIAL_PORT
) {
400 printf("ERROR: serial port is claimed by another process\n");
402 serial_port_name
= NULL
;
405 // start the USB communication thread
406 serial_port_name
= portname
;
408 conn
.block_after_ACK
= flash_mode
;
409 pthread_create(&USB_communication_thread
, NULL
, &uart_communication
, &conn
);
415 void CloseProxmark(void) {
419 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
420 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
422 // In Bionic libc, pthread_t is an integer.
424 if (USB_communication_thread
!= 0) {
425 pthread_join(USB_communication_thread
, NULL
);
428 // pthread_t is a struct on other libc, treat as an opaque memory reference
429 pthread_join(USB_communication_thread
, NULL
);
436 #if defined(__linux__) && !defined(NO_UNLINK)
437 // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
439 // This may be disabled at compile-time with -DNO_UNLINK (used for a JNI-based serial port on Android).
440 if (serial_port_name
) {
441 unlink(serial_port_name
);
445 // Clean up our state
447 serial_port_name
= NULL
;
449 memset(&USB_communication_thread
, 0, sizeof(pthread_t
));
455 * Waits for a certain response type. This method waits for a maximum of
456 * ms_timeout milliseconds for a specified response command.
457 *@brief WaitForResponseTimeout
458 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
459 * @param response struct to copy received command into.
461 * @param show_warning display message after 2 seconds
462 * @return true if command was returned, otherwise false
464 bool WaitForResponseTimeoutW(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
, bool show_warning
) {
469 printf("Waiting for %04x cmd\n", cmd
);
472 if (response
== NULL
) {
476 uint64_t start_time
= msclock();
478 // Wait until the command is received
480 while(getCommand(response
)) {
481 if (cmd
== CMD_UNKNOWN
|| response
->cmd
== cmd
) {
486 if (msclock() - start_time
> ms_timeout
) {
490 if (msclock() - start_time
> 2000 && show_warning
) {
491 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
492 PrintAndLog("Waiting for a response from the proxmark...");
493 PrintAndLog("You can cancel this operation by pressing the pm3 button");
494 show_warning
= false;
501 bool WaitForResponseTimeout(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
) {
502 return WaitForResponseTimeoutW(cmd
, response
, ms_timeout
, true);
505 bool WaitForResponse(uint32_t cmd
, UsbCommand
* response
) {
506 return WaitForResponseTimeoutW(cmd
, response
, -1, true);