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 //-----------------------------------------------------------------------------
18 #if defined(__linux__) && !defined(NO_UNLINK)
19 #include <unistd.h> // for unlink()
24 #include "util_darwin.h"
25 #include "util_posix.h"
28 // Serial port that we are communicating with the PM3 on.
29 static serial_port sp
= NULL
;
30 static char *serial_port_name
= NULL
;
32 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
36 bool run
; // If TRUE, continue running the uart_communication thread
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
) {
199 if (bytes_read
!= len
- *received_len
) {
200 printf("uart_receive() returned true but not enough bytes could be received. received: %d, wanted to receive: %d, already received before: %d\n",
201 bytes_read
, len
- *received_len
, *received_len
);
204 *received_len
+= bytes_read
;
207 return (*received_len
== len
);
212 #ifdef __has_attribute
213 #if __has_attribute(force_align_arg_pointer)
214 __attribute__((force_align_arg_pointer
))
217 *uart_communication(void *targ
) {
218 communication_arg_t
*conn
= (communication_arg_t
*)targ
;
219 uint8_t rx
[sizeof(UsbCommand
)];
222 UsbCommand
*command
= (UsbCommand
*)rx
;
223 UsbResponse
*response
= (UsbResponse
*)rx
;
225 #if defined(__MACH__) && defined(__APPLE__)
226 disableAppNap("Proxmark3 polling UART");
230 bool ACK_received
= false;
232 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)
233 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
235 if (response
->cmd
& CMD_VARIABLE_SIZE_FLAG
) { // new style response with variable size
236 // PrintAndLog("received new style response %04" PRIx16 ", datalen = %d, arg[0] = %08" PRIx32 ", arg[1] = %08" PRIx32 ", arg[2] = %08" PRIx32 "\n",
237 // response->cmd, response->datalen, response->arg[0], response->arg[1], response->arg[2]);
238 bytes_to_read
= response
->datalen
;
239 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
241 resp
.cmd
= response
->cmd
& ~CMD_VARIABLE_SIZE_FLAG
; // remove the flag
242 resp
.arg
[0] = response
->arg
[0];
243 resp
.arg
[1] = response
->arg
[1];
244 resp
.arg
[2] = response
->arg
[2];
245 memcpy(&resp
.d
.asBytes
, &response
->d
.asBytes
, response
->datalen
);
246 UsbCommandReceived(&resp
);
247 if (resp
.cmd
== CMD_ACK
) {
251 } else { // old style response uses same data structure as commands. Fixed size.
252 // PrintAndLog("received old style response %016" PRIx64 ", arg[0] = %016" PRIx64 "\n", command->cmd, command->arg[0]);
253 bytes_to_read
= sizeof(UsbCommand
) - bytes_to_read
;
254 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
255 UsbCommandReceived(command
);
256 if (command
->cmd
== CMD_ACK
) {
263 pthread_mutex_lock(&txBufferMutex
);
264 // if we received an ACK the PM has done its job and waits for another command.
265 // We therefore can wait here as well until a new command is to be transmitted.
266 // The advantage is that the next command will be transmitted immediately without the need to wait for a receive timeout
268 while (!txBuffer_pending
) {
269 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;
278 pthread_cond_signal(&txBufferSig
); // tell main thread that txBuffer is empty
279 pthread_mutex_unlock(&txBufferMutex
);
282 #if defined(__MACH__) && defined(__APPLE__)
292 * Data transfer from Proxmark to client. This method times out after
293 * ms_timeout milliseconds.
294 * @brief GetFromBigBuf
295 * @param dest Destination address for transfer
296 * @param bytes number of bytes to be transferred
297 * @param start_index offset into Proxmark3 BigBuf[]
298 * @param response struct to copy last command (CMD_ACK) into
299 * @param ms_timeout timeout in milliseconds
300 * @param show_warning display message after 2 seconds
301 * @return true if command was returned, otherwise false
303 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
)
305 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
308 uint64_t start_time
= msclock();
311 if (response
== NULL
) {
315 int bytes_completed
= 0;
317 if (getCommand(response
)) {
318 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
319 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
320 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
321 bytes_completed
+= copy_bytes
;
322 } else if (response
->cmd
== CMD_ACK
) {
327 if (msclock() - start_time
> ms_timeout
) {
331 if (msclock() - start_time
> 2000 && show_warning
) {
332 PrintAndLog("Waiting for a response from the proxmark...");
333 PrintAndLog("You can cancel this operation by pressing the pm3 button");
334 show_warning
= false;
342 bool GetFromFpgaRAM(uint8_t *dest
, int bytes
)
344 UsbCommand c
= {CMD_HF_PLOT
, {0, 0, 0}};
347 uint64_t start_time
= msclock();
351 int bytes_completed
= 0;
352 bool show_warning
= true;
354 if (getCommand(&response
)) {
355 if (response
.cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
356 int copy_bytes
= MIN(bytes
- bytes_completed
, response
.arg
[1]);
357 memcpy(dest
+ response
.arg
[0], response
.d
.asBytes
, copy_bytes
);
358 bytes_completed
+= copy_bytes
;
359 } else if (response
.cmd
== CMD_ACK
) {
364 if (msclock() - start_time
> 2000 && show_warning
) {
365 PrintAndLog("Waiting for a response from the proxmark...");
366 PrintAndLog("You can cancel this operation by pressing the pm3 button");
367 show_warning
= false;
375 bool OpenProxmark(void *port
, bool wait_for_port
, int timeout
) {
376 char *portname
= (char *)port
;
377 if (!wait_for_port
) {
378 sp
= uart_open(portname
);
380 printf("Waiting for Proxmark to appear on %s ", portname
);
384 sp
= uart_open(portname
);
388 } while(++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
392 // check result of uart opening
393 if (sp
== INVALID_SERIAL_PORT
) {
394 printf("ERROR: invalid serial port\n");
396 serial_port_name
= NULL
;
398 } else if (sp
== CLAIMED_SERIAL_PORT
) {
399 printf("ERROR: serial port is claimed by another process\n");
401 serial_port_name
= NULL
;
404 // start the USB communication thread
405 serial_port_name
= portname
;
407 pthread_create(&USB_communication_thread
, NULL
, &uart_communication
, &conn
);
413 void CloseProxmark(void) {
417 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
418 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
420 // In Bionic libc, pthread_t is an integer.
422 if (USB_communication_thread
!= 0) {
423 pthread_join(USB_communication_thread
, NULL
);
426 // pthread_t is a struct on other libc, treat as an opaque memory reference
427 pthread_join(USB_communication_thread
, NULL
);
434 #if defined(__linux__) && !defined(NO_UNLINK)
435 // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
437 // This may be disabled at compile-time with -DNO_UNLINK (used for a JNI-based serial port on Android).
438 if (serial_port_name
) {
439 unlink(serial_port_name
);
443 // Clean up our state
445 serial_port_name
= NULL
;
447 memset(&USB_communication_thread
, 0, sizeof(pthread_t
));
453 * Waits for a certain response type. This method waits for a maximum of
454 * ms_timeout milliseconds for a specified response command.
455 *@brief WaitForResponseTimeout
456 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
457 * @param response struct to copy received command into.
459 * @param show_warning display message after 2 seconds
460 * @return true if command was returned, otherwise false
462 bool WaitForResponseTimeoutW(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
, bool show_warning
) {
467 printf("Waiting for %04x cmd\n", cmd
);
470 if (response
== NULL
) {
474 uint64_t start_time
= msclock();
476 // Wait until the command is received
478 while (getCommand(response
)) {
479 if (cmd
== CMD_UNKNOWN
|| response
->cmd
== cmd
) {
484 if (msclock() - start_time
> ms_timeout
) {
488 if (msclock() - start_time
> 2000 && show_warning
) {
489 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
490 PrintAndLog("Waiting for a response from the proxmark...");
491 PrintAndLog("You can cancel this operation by pressing the pm3 button");
492 show_warning
= false;
499 bool WaitForResponseTimeout(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
) {
500 return WaitForResponseTimeoutW(cmd
, response
, ms_timeout
, true);
503 bool WaitForResponse(uint32_t cmd
, UsbCommand
* response
) {
504 return WaitForResponseTimeoutW(cmd
, response
, -1, true);