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 #include "util_posix.h"
22 // Serial port that we are communicating with the PM3 on.
23 static serial_port sp
;
25 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
29 // TODO: Use locks and execute this on the main thread, rather than the receiver
30 // thread. Running on the main thread means we need to be careful in the
31 // flasher, as it means SendCommand is no longer async, and can't be used as a
32 // buffer for a pending command when the connection is re-established.
33 static UsbCommand txcmd
;
34 volatile static bool txcmd_pending
= false;
36 // Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
37 // processed by a command handler (WaitForResponse{,Timeout})
38 static UsbCommand cmdBuffer
[CMD_BUFFER_SIZE
];
40 // Points to the next empty position to write to
41 static int cmd_head
= 0;
43 // Points to the position of the last unread command
44 static int cmd_tail
= 0;
46 // to lock cmdBuffer operations from different threads
47 static pthread_mutex_t cmdBufferMutex
= PTHREAD_MUTEX_INITIALIZER
;
49 // These wrappers are required because it is not possible to access a static
50 // global variable outside of the context of a single file.
52 void SetOffline(bool new_offline
) {
53 offline
= new_offline
;
60 bool OpenProxmark(char *portname
, bool waitCOMPort
, int timeout
) {
62 sp
= uart_open(portname
);
64 printf("Waiting for Proxmark to appear on %s ", portname
);
68 sp
= uart_open(portname
);
72 } while(++openCount
< timeout
&& (sp
== INVALID_SERIAL_PORT
|| sp
== CLAIMED_SERIAL_PORT
));
76 // check result of uart opening
77 if (sp
== INVALID_SERIAL_PORT
) {
78 printf("ERROR: invalid serial port\n");
80 } else if (sp
== CLAIMED_SERIAL_PORT
) {
81 printf("ERROR: serial port is claimed by another process\n");
88 void CloseProxmark(void) {
92 void SendCommand(UsbCommand
*c
) {
94 printf("Sending %04x cmd\n", c
->cmd
);
98 PrintAndLog("Sending bytes to proxmark failed - offline");
102 The while-loop below causes hangups at times, when the pm3 unit is unresponsive
103 or disconnected. The main console thread is alive, but comm thread just spins here.
106 while(txcmd_pending
);
109 txcmd_pending
= true;
114 * @brief This method should be called when sending a new command to the pm3. In case any old
115 * responses from previous commands are stored in the buffer, a call to this method should clear them.
116 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
117 * operation. Right now we'll just have to live with this.
119 void clearCommandBuffer()
121 //This is a very simple operation
122 pthread_mutex_lock(&cmdBufferMutex
);
124 pthread_mutex_unlock(&cmdBufferMutex
);
128 * @brief storeCommand stores a USB command in a circular buffer
131 void storeCommand(UsbCommand
*command
)
133 pthread_mutex_lock(&cmdBufferMutex
);
134 if( (cmd_head
+1) % CMD_BUFFER_SIZE
== cmd_tail
)
136 // If these two are equal, we're about to overwrite in the
138 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
141 // Store the command at the 'head' location
142 UsbCommand
* destination
= &cmdBuffer
[cmd_head
];
143 memcpy(destination
, command
, sizeof(UsbCommand
));
145 cmd_head
= (cmd_head
+1) % CMD_BUFFER_SIZE
; //increment head and wrap
146 pthread_mutex_unlock(&cmdBufferMutex
);
151 * @brief getCommand gets a command from an internal circular buffer.
152 * @param response location to write command
153 * @return 1 if response was returned, 0 if nothing has been received
155 int getCommand(UsbCommand
* response
)
157 pthread_mutex_lock(&cmdBufferMutex
);
158 //If head == tail, there's nothing to read, or if we just got initialized
159 if (cmd_head
== cmd_tail
){
160 pthread_mutex_unlock(&cmdBufferMutex
);
164 //Pick out the next unread command
165 UsbCommand
* last_unread
= &cmdBuffer
[cmd_tail
];
166 memcpy(response
, last_unread
, sizeof(UsbCommand
));
167 //Increment tail - this is a circular buffer, so modulo buffer size
168 cmd_tail
= (cmd_tail
+ 1) % CMD_BUFFER_SIZE
;
170 pthread_mutex_unlock(&cmdBufferMutex
);
175 //----------------------------------------------------------------------------------
176 // Entry point into our code: called whenever we received a packet over USB.
177 // Handle debug commands directly, store all other commands in circular buffer.
178 //----------------------------------------------------------------------------------
179 static void UsbCommandReceived(UsbCommand
*UC
)
182 // First check if we are handling a debug message
183 case CMD_DEBUG_PRINT_STRING
: {
184 char s
[USB_CMD_DATA_SIZE
+1];
185 memset(s
, 0x00, sizeof(s
));
186 size_t len
= MIN(UC
->arg
[0],USB_CMD_DATA_SIZE
);
187 memcpy(s
,UC
->d
.asBytes
,len
);
188 PrintAndLog("#db# %s", s
);
192 case CMD_DEBUG_PRINT_INTEGERS
: {
193 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC
->arg
[0], UC
->arg
[1], UC
->arg
[2]);
206 #ifdef __has_attribute
207 #if __has_attribute(force_align_arg_pointer)
208 __attribute__((force_align_arg_pointer
))
211 *uart_receiver(void *targ
) {
212 receiver_arg
*conn
= (receiver_arg
*)targ
;
214 uint8_t rx
[sizeof(UsbCommand
)];
219 if (uart_receive(sp
, prx
, sizeof(UsbCommand
) - (prx
-rx
), &rxlen
) && rxlen
) {
221 if (prx
-rx
< sizeof(UsbCommand
)) {
224 UsbCommandReceived((UsbCommand
*)rx
);
229 if (!uart_send(sp
, (uint8_t*) &txcmd
, sizeof(UsbCommand
))) {
230 PrintAndLog("Sending bytes to proxmark failed");
232 txcmd_pending
= false;
243 * Data transfer from Proxmark to client. This method times out after
244 * ms_timeout milliseconds.
245 * @brief GetFromBigBuf
246 * @param dest Destination address for transfer
247 * @param bytes number of bytes to be transferred
248 * @param start_index offset into Proxmark3 BigBuf[]
249 * @param response struct to copy last command (CMD_ACK) into
250 * @param ms_timeout timeout in milliseconds
251 * @param show_warning display message after 2 seconds
252 * @return true if command was returned, otherwise false
254 bool GetFromBigBuf(uint8_t *dest
, int bytes
, int start_index
, UsbCommand
*response
, size_t ms_timeout
, bool show_warning
)
256 UsbCommand c
= {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
, {start_index
, bytes
, 0}};
259 uint64_t start_time
= msclock();
262 if (response
== NULL
) {
266 int bytes_completed
= 0;
268 if (getCommand(response
)) {
269 if (response
->cmd
== CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
) {
270 int copy_bytes
= MIN(bytes
- bytes_completed
, response
->arg
[1]);
271 memcpy(dest
+ response
->arg
[0], response
->d
.asBytes
, copy_bytes
);
272 bytes_completed
+= copy_bytes
;
273 } else if (response
->cmd
== CMD_ACK
) {
278 if (msclock() - start_time
> ms_timeout
) {
282 if (msclock() - start_time
> 2000 && show_warning
) {
283 PrintAndLog("Waiting for a response from the proxmark...");
284 PrintAndLog("You can cancel this operation by pressing the pm3 button");
285 show_warning
= false;
294 * Waits for a certain response type. This method waits for a maximum of
295 * ms_timeout milliseconds for a specified response command.
296 *@brief WaitForResponseTimeout
297 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
298 * @param response struct to copy received command into.
300 * @param show_warning display message after 2 seconds
301 * @return true if command was returned, otherwise false
303 bool WaitForResponseTimeoutW(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
, bool show_warning
) {
308 printf("Waiting for %04x cmd\n", cmd
);
311 if (response
== NULL
) {
315 uint64_t start_time
= msclock();
317 // Wait until the command is received
319 while(getCommand(response
)) {
320 if (cmd
== CMD_UNKNOWN
|| response
->cmd
== cmd
) {
325 if (msclock() - start_time
> ms_timeout
) {
329 if (msclock() - start_time
> 2000 && show_warning
) {
330 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
331 PrintAndLog("Waiting for a response from the proxmark...");
332 PrintAndLog("You can cancel this operation by pressing the pm3 button");
333 show_warning
= false;
340 bool WaitForResponseTimeout(uint32_t cmd
, UsbCommand
* response
, size_t ms_timeout
) {
341 return WaitForResponseTimeoutW(cmd
, response
, ms_timeout
, true);
344 bool WaitForResponse(uint32_t cmd
, UsbCommand
* response
) {
345 return WaitForResponseTimeoutW(cmd
, response
, -1, true);