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 //-----------------------------------------------------------------------------
12 #define _POSIX_C_SOURCE 199309L // need clock_gettime()
27 #include "util_darwin.h"
28 #include "util_posix.h"
31 // Serial port that we are communicating with the PM3 on.
32 static serial_port sp
= NULL
;
33 static char *serial_port_name
= NULL
;
35 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
39 bool run
; // If TRUE, continue running the uart_communication thread
40 } communication_arg_t
;
42 static communication_arg_t conn
;
43 static pthread_t USB_communication_thread
;
46 static UsbCommand txBuffer
;
47 static bool txBuffer_pending
= false;
48 static pthread_mutex_t txBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
49 static pthread_cond_t txBufferSig
= PTHREAD_COND_INITIALIZER
;
51 // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
52 // processed by a command handler (WaitForResponse{,Timeout})
53 #define CMD_BUFFER_SIZE 50
54 #define CMD_BUFFER_CHECK_TIME 10 // maximum time (in ms) to wait in getCommand()
56 static UsbCommand rxBuffer
[CMD_BUFFER_SIZE
];
58 // Points to the next empty position to write to
59 static int cmd_head
= 0;
61 // Points to the position of the last unread command
62 static int cmd_tail
= 0;
64 // to lock rxBuffer operations from different threads
65 static pthread_mutex_t rxBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
66 static pthread_cond_t rxBufferSig
= PTHREAD_COND_INITIALIZER
;
68 // These wrappers are required because it is not possible to access a static
69 // global variable outside of the context of a single file.
71 void SetOffline(bool new_offline
) {
72 offline
= new_offline
;
79 void SendCommand(UsbCommand
*c
) {
81 printf("Sending %04" PRIx64
" cmd\n", c
->cmd
);
85 PrintAndLog("Sending bytes to proxmark failed - offline");
89 pthread_mutex_lock(&txBufferMutex
);
91 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
92 but comm thread just spins here. Not good.../holiman
94 while (txBuffer_pending
) {
95 pthread_cond_wait(&txBufferSig
, &txBufferMutex
); // wait for communication thread to complete sending a previous commmand
99 txBuffer_pending
= true;
100 pthread_cond_signal(&txBufferSig
); // tell communication thread that a new command can be send
102 pthread_mutex_unlock(&txBufferMutex
);
108 * @brief This method should be called when sending a new command to the pm3. In case any old
109 * responses from previous commands are stored in the buffer, a call to this method should clear them.
110 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
111 * operation. Right now we'll just have to live with this.
113 void clearCommandBuffer() {
114 //This is a very simple operation
115 pthread_mutex_lock(&rxBufferMutex
);
117 pthread_mutex_unlock(&rxBufferMutex
);
121 * @brief storeCommand stores a USB command in a circular buffer
124 static void storeCommand(UsbCommand
*command
) {
125 pthread_mutex_lock(&rxBufferMutex
);
126 if ((cmd_head
+ 1) % CMD_BUFFER_SIZE
== cmd_tail
) {
127 // If these two are equal, we're about to overwrite in the
129 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
132 // Store the command at the 'head' location
133 UsbCommand
* destination
= &rxBuffer
[cmd_head
];
134 memcpy(destination
, command
, sizeof(UsbCommand
));
136 cmd_head
= (cmd_head
+ 1) % CMD_BUFFER_SIZE
; //increment head and wrap
137 pthread_cond_signal(&rxBufferSig
); // tell main thread that a new command can be retreived
138 pthread_mutex_unlock(&rxBufferMutex
);
143 * @brief getCommand gets a command from an internal circular buffer.
144 * @param response location to write command
145 * @return 1 if response was returned, 0 if nothing has been received in time
147 static int getCommand(UsbCommand
* response
, uint32_t ms_timeout
) {
149 struct timespec end_time
;
150 clock_gettime(CLOCK_REALTIME
, &end_time
);
151 end_time
.tv_sec
+= ms_timeout
/ 1000;
152 end_time
.tv_nsec
+= (ms_timeout
% 1000) * 1000000;
153 if (end_time
.tv_nsec
> 1000000000) {
154 end_time
.tv_nsec
-= 1000000000;
155 end_time
.tv_sec
+= 1;
157 pthread_mutex_lock(&rxBufferMutex
);
159 while (cmd_head
== cmd_tail
&& !res
) {
160 res
= pthread_cond_timedwait(&rxBufferSig
, &rxBufferMutex
, &end_time
);
162 if (res
) { // timeout
163 pthread_mutex_unlock(&rxBufferMutex
);
167 // Pick out the next unread command
168 UsbCommand
* last_unread
= &rxBuffer
[cmd_tail
];
169 memcpy(response
, last_unread
, sizeof(UsbCommand
));
170 // Increment tail - this is a circular buffer, so modulo buffer size
171 cmd_tail
= (cmd_tail
+ 1) % CMD_BUFFER_SIZE
;
173 pthread_mutex_unlock(&rxBufferMutex
);
178 //----------------------------------------------------------------------------------
179 // Entry point into our code: called whenever we received a packet over USB.
180 // Handle debug commands directly, store all other commands in circular buffer.
181 //----------------------------------------------------------------------------------
182 static void UsbCommandReceived(UsbCommand
*UC
) {
184 // First check if we are handling a debug message
185 case CMD_DEBUG_PRINT_STRING
: {
186 char s
[USB_CMD_DATA_SIZE
+1];
187 memset(s
, 0x00, sizeof(s
));
188 size_t len
= MIN(UC
->arg
[0], USB_CMD_DATA_SIZE
);
189 memcpy(s
, UC
->d
.asBytes
,len
);
190 PrintAndLog("#db# %s", s
);
194 case CMD_DEBUG_PRINT_INTEGERS
: {
195 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC
->arg
[0], UC
->arg
[1], UC
->arg
[2]);
207 static bool receive_from_serial(serial_port sp
, uint8_t *rx_buf
, size_t len
, size_t *received_len
) {
208 size_t bytes_read
= 0;
210 // we eventually need to call uart_receive several times because it may timeout in the middle of a transfer
211 while (uart_receive(sp
, rx_buf
+ *received_len
, len
- *received_len
, &bytes_read
) && bytes_read
&& *received_len
< len
) {
213 if (bytes_read
!= len
- *received_len
) {
214 printf("uart_receive() returned true but not enough bytes could be received. received: %zd, wanted to receive: %zd, already received before: %zd\n",
215 bytes_read
, len
- *received_len
, *received_len
);
218 *received_len
+= bytes_read
;
221 return (*received_len
== len
);
226 #ifdef __has_attribute
227 #if __has_attribute(force_align_arg_pointer)
228 __attribute__((force_align_arg_pointer
))
231 *uart_communication(void *targ
) {
232 communication_arg_t
*conn
= (communication_arg_t
*)targ
;
233 uint8_t rx
[sizeof(UsbCommand
)];
236 UsbCommand
*command
= (UsbCommand
*)rx
;
237 UsbResponse
*response
= (UsbResponse
*)rx
;
239 #if defined(__MACH__) && defined(__APPLE__)
240 disableAppNap("Proxmark3 polling UART");
244 bool ACK_received
= false;
246 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)
247 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
249 if (response
->cmd
& CMD_VARIABLE_SIZE_FLAG
) { // new style response with variable size
251 PrintAndLog("received new style response %04" PRIx16
", datalen = %zd, arg[0] = %08" PRIx32
", arg[1] = %08" PRIx32
", arg[2] = %08" PRIx32
,
252 response
->cmd
, response
->datalen
, response
->arg
[0], response
->arg
[1], response
->arg
[2]);
254 bytes_to_read
= response
->datalen
;
255 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
257 resp
.cmd
= response
->cmd
& ~CMD_VARIABLE_SIZE_FLAG
; // remove the flag
258 resp
.arg
[0] = response
->arg
[0];
259 resp
.arg
[1] = response
->arg
[1];
260 resp
.arg
[2] = response
->arg
[2];
261 memcpy(&resp
.d
.asBytes
, &response
->d
.asBytes
, response
->datalen
);
262 UsbCommandReceived(&resp
);
263 if (resp
.cmd
== CMD_ACK
) {
267 } else { // old style response uses same data structure as commands. Fixed size.
269 PrintAndLog("received old style response %016" PRIx64
", arg[0] = %016" PRIx64
, command
->cmd
, command
->arg
[0]);
271 bytes_to_read
= sizeof(UsbCommand
) - bytes_to_read
;
272 if (receive_from_serial(sp
, prx
, bytes_to_read
, &rxlen
)) {
273 UsbCommandReceived(command
);
274 if (command
->cmd
== CMD_ACK
) {
281 pthread_mutex_lock(&txBufferMutex
);
282 // if we received an ACK the PM has done its job and waits for another command.
283 // We therefore can wait here as well until a new command is to be transmitted.
284 // The advantage is that the next command will be transmitted immediately without the need to wait for a receive timeout
286 while (!txBuffer_pending
) {
287 pthread_cond_wait(&txBufferSig
, &txBufferMutex
);
290 if (txBuffer_pending
) {
291 if (!uart_send(sp
, (uint8_t*) &txBuffer
, sizeof(UsbCommand
))) {
292 PrintAndLog("Sending bytes to proxmark failed");
294 txBuffer_pending
= false;
296 pthread_cond_signal(&txBufferSig
); // tell main thread that txBuffer is empty
297 pthread_mutex_unlock(&txBufferMutex
);
300 #if defined(__MACH__) && defined(__APPLE__)
310 * Data transfer from Proxmark to client. This method times out after
311 * ms_timeout milliseconds.
312 * @brief GetFromBigBuf
313 * @param dest Destination address for transfer
314 * @param bytes number of bytes to be transferred
315 * @param start_index offset into Proxmark3 BigBuf[]
316 * @param response struct to copy last command (CMD_ACK) into
317 * @param ms_timeout timeout in milliseconds
318 * @param show_warning display message after 2 seconds
319 * @return true if command was returned, otherwise false
321 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
) {
323 uint64_t start_time
= msclock();
325 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
329 if (response
== NULL
) {
333 int bytes_completed
= 0;
335 if (msclock() - start_time
> ms_timeout
) {
338 if (msclock() - start_time
> 2000 && show_warning
) {
339 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
340 PrintAndLog("Waiting for a response from the proxmark...");
341 PrintAndLog("You can cancel this operation by pressing the pm3 button");
342 show_warning
= false;
344 if (getCommand(response
, CMD_BUFFER_CHECK_TIME
)) {
345 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
346 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
347 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
348 bytes_completed
+= copy_bytes
;
349 } else if (response
->cmd
== CMD_ACK
) {
359 bool GetFromFpgaRAM(uint8_t *dest
, int bytes
) {
361 uint64_t start_time
= msclock();
363 UsbCommand c
= {CMD_HF_PLOT
, {0, 0, 0}};
368 int bytes_completed
= 0;
369 bool show_warning
= true;
371 if (msclock() - start_time
> 2000 && show_warning
) {
372 PrintAndLog("Waiting for a response from the proxmark...");
373 PrintAndLog("You can cancel this operation by pressing the pm3 button");
374 show_warning
= false;
376 if (getCommand(&response
, CMD_BUFFER_CHECK_TIME
)) {
377 if (response
.cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
378 int copy_bytes
= MIN(bytes
- bytes_completed
, response
.arg
[1]);
379 memcpy(dest
+ response
.arg
[0], response
.d
.asBytes
, copy_bytes
);
380 bytes_completed
+= copy_bytes
;
381 } else if (response
.cmd
== CMD_ACK
) {
391 bool OpenProxmark(void *port
, bool wait_for_port
, int timeout
) {
392 char *portname
= (char *)port
;
393 if (!wait_for_port
) {
394 sp
= uart_open(portname
);
396 printf("Waiting for Proxmark to appear on %s ", portname
);
400 sp
= uart_open(portname
);
404 } while (++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
408 // check result of uart opening
409 if (sp
== INVALID_SERIAL_PORT
) {
410 printf("ERROR: invalid serial port\n");
412 serial_port_name
= NULL
;
414 } else if (sp
== CLAIMED_SERIAL_PORT
) {
415 printf("ERROR: serial port is claimed by another process\n");
417 serial_port_name
= NULL
;
420 // start the USB communication thread
421 serial_port_name
= portname
;
423 pthread_create(&USB_communication_thread
, NULL
, &uart_communication
, &conn
);
429 void CloseProxmark(void) {
433 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
434 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
436 // In Bionic libc, pthread_t is an integer.
438 if (USB_communication_thread
!= 0) {
439 pthread_join(USB_communication_thread
, NULL
);
442 // pthread_t is a struct on other libc, treat as an opaque memory reference
443 pthread_join(USB_communication_thread
, NULL
);
450 // Clean up our state
452 serial_port_name
= NULL
;
454 memset(&USB_communication_thread
, 0, sizeof(pthread_t
));
460 * Waits for a certain response type. This method waits for a maximum of
461 * ms_timeout milliseconds for a specified response command.
462 *@brief WaitForResponseTimeout
463 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
464 * @param response struct to copy received command into.
466 * @param show_warning display message after 2 seconds
467 * @return true if command was returned, otherwise false
469 bool WaitForResponseTimeoutW(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
, bool show_warning
) {
474 printf("Waiting for %04x cmd\n", cmd
);
477 uint64_t start_time
= msclock();
479 if (response
== NULL
) {
483 // Wait until the command is received
485 if (ms_timeout
!= -1 && 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;
494 if (getCommand(response
, CMD_BUFFER_CHECK_TIME
)) {
495 if (cmd
== CMD_UNKNOWN
|| response
->cmd
== cmd
) {
504 bool WaitForResponseTimeout(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
) {
505 return WaitForResponseTimeoutW(cmd
, response
, ms_timeout
, true);
508 bool WaitForResponse(uint32_t cmd
, UsbCommand
* response
) {
509 return WaitForResponseTimeoutW(cmd
, response
, -1, true);