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 //-----------------------------------------------------------------------------
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 } communication_arg_t
;
38 static communication_arg_t conn
;
39 static pthread_t USB_communication_thread
;
42 static UsbCommand txBuffer
;
43 static bool txBuffer_pending
= false;
44 static pthread_mutex_t txBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
45 static pthread_cond_t txBufferSig
= PTHREAD_COND_INITIALIZER
;
47 // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
48 // processed by a command handler (WaitForResponse{,Timeout})
49 #define CMD_BUFFER_SIZE 50
50 static UsbCommand rxBuffer
[CMD_BUFFER_SIZE
];
52 // Points to the next empty position to write to
53 static int cmd_head
= 0;
55 // Points to the position of the last unread command
56 static int cmd_tail
= 0;
58 // to lock rxBuffer operations from different threads
59 static pthread_mutex_t rxBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
61 // These wrappers are required because it is not possible to access a static
62 // global variable outside of the context of a single file.
64 void SetOffline(bool new_offline
) {
65 offline
= new_offline
;
72 void SendCommand(UsbCommand
*c
) {
74 printf("Sending %04" PRIx64
" cmd\n", c
->cmd
);
78 PrintAndLog("Sending bytes to proxmark failed - offline");
82 pthread_mutex_lock(&txBufferMutex
);
84 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
85 but comm thread just spins here. Not good.../holiman
87 while (txBuffer_pending
) {
88 pthread_cond_wait(&txBufferSig
, &txBufferMutex
); // wait for communication thread to complete sending a previous commmand
92 txBuffer_pending
= true;
93 pthread_cond_signal(&txBufferSig
); // tell communication thread that a new command can be send
95 pthread_mutex_unlock(&txBufferMutex
);
101 * @brief This method should be called when sending a new command to the pm3. In case any old
102 * responses from previous commands are stored in the buffer, a call to this method should clear them.
103 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
104 * operation. Right now we'll just have to live with this.
106 void clearCommandBuffer() {
107 //This is a very simple operation
108 pthread_mutex_lock(&rxBufferMutex
);
110 pthread_mutex_unlock(&rxBufferMutex
);
114 * @brief storeCommand stores a USB command in a circular buffer
117 static void storeCommand(UsbCommand
*command
) {
118 pthread_mutex_lock(&rxBufferMutex
);
119 if ((cmd_head
+ 1) % CMD_BUFFER_SIZE
== cmd_tail
) {
120 // If these two are equal, we're about to overwrite in the
122 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
125 // Store the command at the 'head' location
126 UsbCommand
* destination
= &rxBuffer
[cmd_head
];
127 memcpy(destination
, command
, sizeof(UsbCommand
));
129 cmd_head
= (cmd_head
+ 1) % CMD_BUFFER_SIZE
; //increment head and wrap
130 pthread_mutex_unlock(&rxBufferMutex
);
135 * @brief getCommand gets a command from an internal circular buffer.
136 * @param response location to write command
137 * @return 1 if response was returned, 0 if nothing has been received
139 static int getCommand(UsbCommand
* response
) {
140 pthread_mutex_lock(&rxBufferMutex
);
141 // If head == tail, there's nothing to read
142 if (cmd_head
== cmd_tail
) {
143 pthread_mutex_unlock(&rxBufferMutex
);
147 // Pick out the next unread command
148 UsbCommand
* last_unread
= &rxBuffer
[cmd_tail
];
149 memcpy(response
, last_unread
, sizeof(UsbCommand
));
150 // Increment tail - this is a circular buffer, so modulo buffer size
151 cmd_tail
= (cmd_tail
+ 1) % CMD_BUFFER_SIZE
;
153 pthread_mutex_unlock(&rxBufferMutex
);
158 //----------------------------------------------------------------------------------
159 // Entry point into our code: called whenever we received a packet over USB.
160 // Handle debug commands directly, store all other commands in circular buffer.
161 //----------------------------------------------------------------------------------
162 static void UsbCommandReceived(UsbCommand
*UC
) {
164 // First check if we are handling a debug message
165 case CMD_DEBUG_PRINT_STRING
: {
166 char s
[USB_CMD_DATA_SIZE
+1];
167 memset(s
, 0x00, sizeof(s
));
168 size_t len
= MIN(UC
->arg
[0], USB_CMD_DATA_SIZE
);
169 memcpy(s
, UC
->d
.asBytes
,len
);
170 PrintAndLog("#db# %s", s
);
174 case CMD_DEBUG_PRINT_INTEGERS
: {
175 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC
->arg
[0], UC
->arg
[1], UC
->arg
[2]);
187 static bool receive_from_serial(serial_port sp
, uint8_t *rx_buf
, size_t len
, size_t *received_len
) {
188 size_t bytes_read
= 0;
190 // we eventually need to call uart_receive several times if it times out in the middle of a transfer
191 while (uart_receive(sp
, rx_buf
+ *received_len
, len
- *received_len
, &bytes_read
) && bytes_read
&& *received_len
< len
) {
193 if (bytes_read
!= len
- *received_len
) {
194 printf("uart_receive() returned true but not enough bytes could be received. received: %zd, wanted to receive: %zd, already received before: %zd\n",
195 bytes_read
, len
- *received_len
, *received_len
);
198 *received_len
+= bytes_read
;
201 return (*received_len
== len
);
206 #ifdef __has_attribute
207 #if __has_attribute(force_align_arg_pointer)
208 __attribute__((force_align_arg_pointer
))
211 *uart_communication(void *targ
) {
212 communication_arg_t
*conn
= (communication_arg_t
*)targ
;
213 uint8_t rx
[sizeof(UsbCommand
)];
216 UsbCommand
*command
= (UsbCommand
*)rx
;
217 UsbResponse
*response
= (UsbResponse
*)rx
;
219 #if defined(__MACH__) && defined(__APPLE__)
220 disableAppNap("Proxmark3 polling UART");
224 bool ACK_received
= false;
226 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)
227 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
229 if (response
->cmd
& CMD_VARIABLE_SIZE_FLAG
) { // new style response with variable size
231 PrintAndLog("received new style response %04" PRIx16
", datalen = %zd, arg[0] = %08" PRIx32
", arg[1] = %08" PRIx32
", arg[2] = %08" PRIx32
,
232 response
->cmd
, response
->datalen
, response
->arg
[0], response
->arg
[1], response
->arg
[2]);
234 bytes_to_read
= response
->datalen
;
235 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
237 resp
.cmd
= response
->cmd
& ~CMD_VARIABLE_SIZE_FLAG
; // remove the flag
238 resp
.arg
[0] = response
->arg
[0];
239 resp
.arg
[1] = response
->arg
[1];
240 resp
.arg
[2] = response
->arg
[2];
241 memcpy(&resp
.d
.asBytes
, &response
->d
.asBytes
, response
->datalen
);
242 UsbCommandReceived(&resp
);
243 if (resp
.cmd
== CMD_ACK
) {
247 } else { // old style response uses same data structure as commands. Fixed size.
249 PrintAndLog("received old style response %016" PRIx64
", arg[0] = %016" PRIx64
, 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
);
262 // if we received an ACK the PM has done its job and waits for another command.
263 // We therefore can wait here as well until a new command is to be transmitted.
264 // The advantage is that the next command will be transmitted immediately without the need to wait for a receive timeout
266 while (!txBuffer_pending
) {
267 pthread_cond_wait(&txBufferSig
, &txBufferMutex
);
270 if (txBuffer_pending
) {
271 if (!uart_send(sp
, (uint8_t*) &txBuffer
, sizeof(UsbCommand
))) {
272 PrintAndLog("Sending bytes to proxmark failed");
274 txBuffer_pending
= false;
276 pthread_cond_signal(&txBufferSig
); // tell main thread that txBuffer is empty
277 pthread_mutex_unlock(&txBufferMutex
);
280 #if defined(__MACH__) && defined(__APPLE__)
290 * Data transfer from Proxmark to client. This method times out after
291 * ms_timeout milliseconds.
292 * @brief GetFromBigBuf
293 * @param dest Destination address for transfer
294 * @param bytes number of bytes to be transferred
295 * @param start_index offset into Proxmark3 BigBuf[]
296 * @param response struct to copy last command (CMD_ACK) into
297 * @param ms_timeout timeout in milliseconds
298 * @param show_warning display message after 2 seconds
299 * @return true if command was returned, otherwise false
301 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
) {
302 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
305 uint64_t start_time
= msclock();
308 if (response
== NULL
) {
312 int bytes_completed
= 0;
314 if (getCommand(response
)) {
315 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
316 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
317 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
318 bytes_completed
+= copy_bytes
;
319 } else if (response
->cmd
== CMD_ACK
) {
324 if (msclock() - start_time
> ms_timeout
) {
328 if (msclock() - start_time
> 2000 && show_warning
) {
329 PrintAndLog("Waiting for a response from the proxmark...");
330 PrintAndLog("You can cancel this operation by pressing the pm3 button");
331 show_warning
= false;
339 bool GetFromFpgaRAM(uint8_t *dest
, int bytes
) {
340 UsbCommand c
= {CMD_HF_PLOT
, {0, 0, 0}};
343 uint64_t start_time
= msclock();
347 int bytes_completed
= 0;
348 bool show_warning
= true;
350 if (getCommand(&response
)) {
351 if (response
.cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
352 int copy_bytes
= MIN(bytes
- bytes_completed
, response
.arg
[1]);
353 memcpy(dest
+ response
.arg
[0], response
.d
.asBytes
, copy_bytes
);
354 bytes_completed
+= copy_bytes
;
355 } else if (response
.cmd
== CMD_ACK
) {
360 if (msclock() - start_time
> 2000 && show_warning
) {
361 PrintAndLog("Waiting for a response from the proxmark...");
362 PrintAndLog("You can cancel this operation by pressing the pm3 button");
363 show_warning
= false;
371 bool OpenProxmark(void *port
, bool wait_for_port
, int timeout
) {
372 char *portname
= (char *)port
;
373 if (!wait_for_port
) {
374 sp
= uart_open(portname
);
376 printf("Waiting for Proxmark to appear on %s ", portname
);
380 sp
= uart_open(portname
);
384 } while (++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
388 // check result of uart opening
389 if (sp
== INVALID_SERIAL_PORT
) {
390 printf("ERROR: invalid serial port\n");
392 serial_port_name
= NULL
;
394 } else if (sp
== CLAIMED_SERIAL_PORT
) {
395 printf("ERROR: serial port is claimed by another process\n");
397 serial_port_name
= NULL
;
400 // start the USB communication thread
401 serial_port_name
= portname
;
403 pthread_create(&USB_communication_thread
, NULL
, &uart_communication
, &conn
);
409 void CloseProxmark(void) {
413 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
414 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
416 // In Bionic libc, pthread_t is an integer.
418 if (USB_communication_thread
!= 0) {
419 pthread_join(USB_communication_thread
, NULL
);
422 // pthread_t is a struct on other libc, treat as an opaque memory reference
423 pthread_join(USB_communication_thread
, NULL
);
430 // Clean up our state
432 serial_port_name
= NULL
;
434 memset(&USB_communication_thread
, 0, sizeof(pthread_t
));
440 * Waits for a certain response type. This method waits for a maximum of
441 * ms_timeout milliseconds for a specified response command.
442 *@brief WaitForResponseTimeout
443 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
444 * @param response struct to copy received command into.
446 * @param show_warning display message after 2 seconds
447 * @return true if command was returned, otherwise false
449 bool WaitForResponseTimeoutW(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
, bool show_warning
) {
454 printf("Waiting for %04x cmd\n", cmd
);
457 if (response
== NULL
) {
461 uint64_t start_time
= msclock();
463 // Wait until the command is received
465 while (getCommand(response
)) {
466 if (cmd
== CMD_UNKNOWN
|| response
->cmd
== cmd
) {
471 if (msclock() - start_time
> ms_timeout
) {
475 if (msclock() - start_time
> 2000 && show_warning
) {
476 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
477 PrintAndLog("Waiting for a response from the proxmark...");
478 PrintAndLog("You can cancel this operation by pressing the pm3 button");
479 show_warning
= false;
487 bool WaitForResponseTimeout(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
) {
488 return WaitForResponseTimeoutW(cmd
, response
, ms_timeout
, true);
491 bool WaitForResponse(uint32_t cmd
, UsbCommand
* response
) {
492 return WaitForResponseTimeoutW(cmd
, response
, -1, true);