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 //-----------------------------------------------------------------------------
20 #if defined(__linux__) && !defined(NO_UNLINK)
21 #include <unistd.h> // for unlink()
26 #include "util_darwin.h"
27 #include "util_posix.h"
30 // Serial port that we are communicating with the PM3 on.
31 static serial_port sp
= NULL
;
32 static char *serial_port_name
= NULL
;
34 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
38 bool run
; // If TRUE, continue running the uart_communication thread
39 } communication_arg_t
;
41 static communication_arg_t conn
;
42 static pthread_t USB_communication_thread
;
45 static UsbCommand txBuffer
;
46 static bool txBuffer_pending
= false;
47 static pthread_mutex_t txBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
48 static pthread_cond_t txBufferSig
= PTHREAD_COND_INITIALIZER
;
50 // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
51 // processed by a command handler (WaitForResponse{,Timeout})
52 #define CMD_BUFFER_SIZE 50
53 static UsbCommand rxBuffer
[CMD_BUFFER_SIZE
];
55 // Points to the next empty position to write to
56 static int cmd_head
= 0;
58 // Points to the position of the last unread command
59 static int cmd_tail
= 0;
61 // to lock rxBuffer operations from different threads
62 static pthread_mutex_t rxBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
64 // These wrappers are required because it is not possible to access a static
65 // global variable outside of the context of a single file.
67 void SetOffline(bool new_offline
) {
68 offline
= new_offline
;
75 void SendCommand(UsbCommand
*c
) {
77 printf("Sending %04x cmd\n", c
->cmd
);
81 PrintAndLog("Sending bytes to proxmark failed - offline");
85 pthread_mutex_lock(&txBufferMutex
);
87 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
88 but comm thread just spins here. Not good.../holiman
90 while (txBuffer_pending
) {
91 pthread_cond_wait(&txBufferSig
, &txBufferMutex
); // wait for communication thread to complete sending a previous commmand
95 txBuffer_pending
= true;
96 pthread_cond_signal(&txBufferSig
); // tell communication thread that a new command can be send
98 pthread_mutex_unlock(&txBufferMutex
);
104 * @brief This method should be called when sending a new command to the pm3. In case any old
105 * responses from previous commands are stored in the buffer, a call to this method should clear them.
106 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
107 * operation. Right now we'll just have to live with this.
109 void clearCommandBuffer()
111 //This is a very simple operation
112 pthread_mutex_lock(&rxBufferMutex
);
114 pthread_mutex_unlock(&rxBufferMutex
);
118 * @brief storeCommand stores a USB command in a circular buffer
121 static void storeCommand(UsbCommand
*command
)
123 pthread_mutex_lock(&rxBufferMutex
);
124 if( (cmd_head
+1) % CMD_BUFFER_SIZE
== cmd_tail
)
126 // If these two are equal, we're about to overwrite in the
128 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
131 // Store the command at the 'head' location
132 UsbCommand
* destination
= &rxBuffer
[cmd_head
];
133 memcpy(destination
, command
, sizeof(UsbCommand
));
135 cmd_head
= (cmd_head
+1) % CMD_BUFFER_SIZE
; //increment head and wrap
136 pthread_mutex_unlock(&rxBufferMutex
);
141 * @brief getCommand gets a command from an internal circular buffer.
142 * @param response location to write command
143 * @return 1 if response was returned, 0 if nothing has been received
145 static int getCommand(UsbCommand
* response
)
147 pthread_mutex_lock(&rxBufferMutex
);
148 //If head == tail, there's nothing to read, or if we just got initialized
149 if (cmd_head
== cmd_tail
){
150 pthread_mutex_unlock(&rxBufferMutex
);
154 //Pick out the next unread command
155 UsbCommand
* last_unread
= &rxBuffer
[cmd_tail
];
156 memcpy(response
, last_unread
, sizeof(UsbCommand
));
157 //Increment tail - this is a circular buffer, so modulo buffer size
158 cmd_tail
= (cmd_tail
+ 1) % CMD_BUFFER_SIZE
;
160 pthread_mutex_unlock(&rxBufferMutex
);
165 //----------------------------------------------------------------------------------
166 // Entry point into our code: called whenever we received a packet over USB.
167 // Handle debug commands directly, store all other commands in circular buffer.
168 //----------------------------------------------------------------------------------
169 static void UsbCommandReceived(UsbCommand
*UC
)
172 // First check if we are handling a debug message
173 case CMD_DEBUG_PRINT_STRING
: {
174 char s
[USB_CMD_DATA_SIZE
+1];
175 memset(s
, 0x00, sizeof(s
));
176 size_t len
= MIN(UC
->arg
[0],USB_CMD_DATA_SIZE
);
177 memcpy(s
,UC
->d
.asBytes
,len
);
178 PrintAndLog("#db# %s", s
);
182 case CMD_DEBUG_PRINT_INTEGERS
: {
183 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC
->arg
[0], UC
->arg
[1], UC
->arg
[2]);
195 static bool receive_from_serial(serial_port sp
, uint8_t *rx_buf
, size_t len
, size_t *received_len
) {
196 size_t bytes_read
= 0;
198 // we eventually need to call uart_receive several times if it times out in the middle of a transfer
199 while (uart_receive(sp
, rx_buf
+ *received_len
, len
- *received_len
, &bytes_read
) && bytes_read
&& *received_len
< len
) {
201 if (bytes_read
!= len
- *received_len
) {
202 printf("uart_receive() returned true but not enough bytes could be received. received: %d, wanted to receive: %d, already received before: %d\n",
203 bytes_read
, len
- *received_len
, *received_len
);
206 *received_len
+= bytes_read
;
209 return (*received_len
== len
);
214 #ifdef __has_attribute
215 #if __has_attribute(force_align_arg_pointer)
216 __attribute__((force_align_arg_pointer
))
219 *uart_communication(void *targ
) {
220 communication_arg_t
*conn
= (communication_arg_t
*)targ
;
221 uint8_t rx
[sizeof(UsbCommand
)];
224 UsbCommand
*command
= (UsbCommand
*)rx
;
225 UsbResponse
*response
= (UsbResponse
*)rx
;
227 #if defined(__MACH__) && defined(__APPLE__)
228 disableAppNap("Proxmark3 polling UART");
232 bool ACK_received
= false;
234 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)
235 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
237 if (response
->cmd
& CMD_VARIABLE_SIZE_FLAG
) { // new style response with variable size
238 // PrintAndLog("received new style response %04" PRIx16 ", datalen = %d, arg[0] = %08" PRIx32 ", arg[1] = %08" PRIx32 ", arg[2] = %08" PRIx32 "\n",
239 // response->cmd, response->datalen, response->arg[0], response->arg[1], response->arg[2]);
240 bytes_to_read
= response
->datalen
;
241 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
243 resp
.cmd
= response
->cmd
& ~CMD_VARIABLE_SIZE_FLAG
; // remove the flag
244 resp
.arg
[0] = response
->arg
[0];
245 resp
.arg
[1] = response
->arg
[1];
246 resp
.arg
[2] = response
->arg
[2];
247 memcpy(&resp
.d
.asBytes
, &response
->d
.asBytes
, response
->datalen
);
248 UsbCommandReceived(&resp
);
249 if (resp
.cmd
== CMD_ACK
) {
253 } else { // old style response uses same data structure as commands. Fixed size.
254 // PrintAndLog("received old style response %016" PRIx64 ", arg[0] = %016" PRIx64 "\n", command->cmd, command->arg[0]);
255 bytes_to_read
= sizeof(UsbCommand
) - bytes_to_read
;
256 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
257 UsbCommandReceived(command
);
258 if (command
->cmd
== CMD_ACK
) {
265 pthread_mutex_lock(&txBufferMutex
);
266 // if we received an ACK the PM has done its job and waits for another command.
267 // We therefore can wait here as well until a new command is to be transmitted.
268 // The advantage is that the next command will be transmitted immediately without the need to wait for a receive timeout
270 while (!txBuffer_pending
) {
271 pthread_cond_wait(&txBufferSig
, &txBufferMutex
);
274 if (txBuffer_pending
) {
275 if (!uart_send(sp
, (uint8_t*) &txBuffer
, sizeof(UsbCommand
))) {
276 PrintAndLog("Sending bytes to proxmark failed");
278 txBuffer_pending
= false;
280 pthread_cond_signal(&txBufferSig
); // tell main thread that txBuffer is empty
281 pthread_mutex_unlock(&txBufferMutex
);
284 #if defined(__MACH__) && defined(__APPLE__)
294 * Data transfer from Proxmark to client. This method times out after
295 * ms_timeout milliseconds.
296 * @brief GetFromBigBuf
297 * @param dest Destination address for transfer
298 * @param bytes number of bytes to be transferred
299 * @param start_index offset into Proxmark3 BigBuf[]
300 * @param response struct to copy last command (CMD_ACK) into
301 * @param ms_timeout timeout in milliseconds
302 * @param show_warning display message after 2 seconds
303 * @return true if command was returned, otherwise false
305 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
)
307 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
310 uint64_t start_time
= msclock();
313 if (response
== NULL
) {
317 int bytes_completed
= 0;
319 if (getCommand(response
)) {
320 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
321 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
322 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
323 bytes_completed
+= copy_bytes
;
324 } else if (response
->cmd
== CMD_ACK
) {
329 if (msclock() - start_time
> ms_timeout
) {
333 if (msclock() - start_time
> 2000 && show_warning
) {
334 PrintAndLog("Waiting for a response from the proxmark...");
335 PrintAndLog("You can cancel this operation by pressing the pm3 button");
336 show_warning
= false;
344 bool GetFromFpgaRAM(uint8_t *dest
, int bytes
)
346 UsbCommand c
= {CMD_HF_PLOT
, {0, 0, 0}};
349 uint64_t start_time
= msclock();
353 int bytes_completed
= 0;
354 bool show_warning
= true;
356 if (getCommand(&response
)) {
357 if (response
.cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
358 int copy_bytes
= MIN(bytes
- bytes_completed
, response
.arg
[1]);
359 memcpy(dest
+ response
.arg
[0], response
.d
.asBytes
, copy_bytes
);
360 bytes_completed
+= copy_bytes
;
361 } else if (response
.cmd
== CMD_ACK
) {
366 if (msclock() - start_time
> 2000 && show_warning
) {
367 PrintAndLog("Waiting for a response from the proxmark...");
368 PrintAndLog("You can cancel this operation by pressing the pm3 button");
369 show_warning
= false;
377 bool OpenProxmark(void *port
, bool wait_for_port
, int timeout
) {
378 char *portname
= (char *)port
;
379 if (!wait_for_port
) {
380 sp
= uart_open(portname
);
382 printf("Waiting for Proxmark to appear on %s ", portname
);
386 sp
= uart_open(portname
);
390 } while(++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
394 // check result of uart opening
395 if (sp
== INVALID_SERIAL_PORT
) {
396 printf("ERROR: invalid serial port\n");
398 serial_port_name
= NULL
;
400 } else if (sp
== CLAIMED_SERIAL_PORT
) {
401 printf("ERROR: serial port is claimed by another process\n");
403 serial_port_name
= NULL
;
406 // start the USB communication thread
407 serial_port_name
= portname
;
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);