Always enable fast response mode (was enabled for flasher only)
[proxmark3-svn] / client / comms.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2009 Michael Gernoth <michael at gernoth.net>
3 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
4 //
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
7 // the license.
8 //-----------------------------------------------------------------------------
9 // Code for communicating with the proxmark3 hardware.
10 //-----------------------------------------------------------------------------
11
12 #include "comms.h"
13
14 #include <stdio.h>
15 #include <pthread.h>
16 #include <inttypes.h>
17
18 #if defined(__linux__) && !defined(NO_UNLINK)
19 #include <unistd.h> // for unlink()
20 #endif
21 #include "uart.h"
22 #include "ui.h"
23 #include "common.h"
24 #include "util_darwin.h"
25 #include "util_posix.h"
26
27
28 // Serial port that we are communicating with the PM3 on.
29 static serial_port sp = NULL;
30 static char *serial_port_name = NULL;
31
32 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
33 static bool offline;
34
35 typedef struct {
36 bool run; // If TRUE, continue running the uart_communication thread
37 } communication_arg_t;
38
39 static communication_arg_t conn;
40 static pthread_t USB_communication_thread;
41
42 // Transmit buffer.
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;
47
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];
52
53 // Points to the next empty position to write to
54 static int cmd_head = 0;
55
56 // Points to the position of the last unread command
57 static int cmd_tail = 0;
58
59 // to lock rxBuffer operations from different threads
60 static pthread_mutex_t rxBufferMutex = PTHREAD_MUTEX_INITIALIZER;
61
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.
64
65 void SetOffline(bool new_offline) {
66 offline = new_offline;
67 }
68
69 bool IsOffline() {
70 return offline;
71 }
72
73 void SendCommand(UsbCommand *c) {
74 #ifdef COMMS_DEBUG
75 printf("Sending %04x cmd\n", c->cmd);
76 #endif
77
78 if (offline) {
79 PrintAndLog("Sending bytes to proxmark failed - offline");
80 return;
81 }
82
83 pthread_mutex_lock(&txBufferMutex);
84 /**
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
87 **/
88 while (txBuffer_pending) {
89 pthread_cond_wait(&txBufferSig, &txBufferMutex); // wait for communication thread to complete sending a previous commmand
90 }
91
92 txBuffer = *c;
93 txBuffer_pending = true;
94 pthread_cond_signal(&txBufferSig); // tell communication thread that a new command can be send
95
96 pthread_mutex_unlock(&txBufferMutex);
97
98 }
99
100
101 /**
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.
106 */
107 void clearCommandBuffer()
108 {
109 //This is a very simple operation
110 pthread_mutex_lock(&rxBufferMutex);
111 cmd_tail = cmd_head;
112 pthread_mutex_unlock(&rxBufferMutex);
113 }
114
115 /**
116 * @brief storeCommand stores a USB command in a circular buffer
117 * @param UC
118 */
119 static void storeCommand(UsbCommand *command)
120 {
121 pthread_mutex_lock(&rxBufferMutex);
122 if( (cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail)
123 {
124 // If these two are equal, we're about to overwrite in the
125 // circular buffer.
126 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
127 }
128
129 // Store the command at the 'head' location
130 UsbCommand* destination = &rxBuffer[cmd_head];
131 memcpy(destination, command, sizeof(UsbCommand));
132
133 cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap
134 pthread_mutex_unlock(&rxBufferMutex);
135 }
136
137
138 /**
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
142 */
143 static int getCommand(UsbCommand* response)
144 {
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);
149 return 0;
150 }
151
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;
157
158 pthread_mutex_unlock(&rxBufferMutex);
159 return 1;
160 }
161
162
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)
168 {
169 switch(UC->cmd) {
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);
177 return;
178 } break;
179
180 case CMD_DEBUG_PRINT_INTEGERS: {
181 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]);
182 return;
183 } break;
184
185 default:
186 storeCommand(UC);
187 break;
188 }
189
190 }
191
192
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;
195 *received_len = 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) {
198 #ifdef COMMS_DEBUG
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);
202 }
203 #endif
204 *received_len += bytes_read;
205 bytes_read = 0;
206 }
207 return (*received_len == len);
208 }
209
210
211 static void
212 #ifdef __has_attribute
213 #if __has_attribute(force_align_arg_pointer)
214 __attribute__((force_align_arg_pointer))
215 #endif
216 #endif
217 *uart_communication(void *targ) {
218 communication_arg_t *conn = (communication_arg_t*)targ;
219 uint8_t rx[sizeof(UsbCommand)];
220 size_t rxlen = 0;
221 uint8_t *prx = rx;
222 UsbCommand *command = (UsbCommand*)rx;
223 UsbResponse *response = (UsbResponse*)rx;
224
225 #if defined(__MACH__) && defined(__APPLE__)
226 disableAppNap("Proxmark3 polling UART");
227 #endif
228
229 while (conn->run) {
230 bool ACK_received = false;
231 prx = rx;
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)) {
234 prx += 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)) {
240 UsbCommand resp;
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) {
248 ACK_received = true;
249 }
250 }
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) {
257 ACK_received = true;
258 }
259 }
260 }
261 }
262
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
267 if (ACK_received) {
268 while (!txBuffer_pending) {
269 pthread_cond_wait(&txBufferSig, &txBufferMutex);
270 }
271 }
272 if (txBuffer_pending) {
273 if (!uart_send(sp, (uint8_t*) &txBuffer, sizeof(UsbCommand))) {
274 PrintAndLog("Sending bytes to proxmark failed");
275 }
276 txBuffer_pending = false;
277 }
278 pthread_cond_signal(&txBufferSig); // tell main thread that txBuffer is empty
279 pthread_mutex_unlock(&txBufferMutex);
280 }
281
282 #if defined(__MACH__) && defined(__APPLE__)
283 enableAppNap();
284 #endif
285
286 pthread_exit(NULL);
287 return NULL;
288 }
289
290
291 /**
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
302 */
303 bool GetFromBigBuf(uint8_t *dest, int bytes, int start_index, UsbCommand *response, size_t ms_timeout, bool show_warning)
304 {
305 UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}};
306 SendCommand(&c);
307
308 uint64_t start_time = msclock();
309
310 UsbCommand resp;
311 if (response == NULL) {
312 response = &resp;
313 }
314
315 int bytes_completed = 0;
316 while(true) {
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) {
323 return true;
324 }
325 }
326
327 if (msclock() - start_time > ms_timeout) {
328 break;
329 }
330
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;
335 }
336 }
337
338 return false;
339 }
340
341
342 bool GetFromFpgaRAM(uint8_t *dest, int bytes)
343 {
344 UsbCommand c = {CMD_HF_PLOT, {0, 0, 0}};
345 SendCommand(&c);
346
347 uint64_t start_time = msclock();
348
349 UsbCommand response;
350
351 int bytes_completed = 0;
352 bool show_warning = true;
353 while(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) {
360 return true;
361 }
362 }
363
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;
368 }
369 }
370
371 return false;
372 }
373
374
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);
379 } else {
380 printf("Waiting for Proxmark to appear on %s ", portname);
381 fflush(stdout);
382 int openCount = 0;
383 do {
384 sp = uart_open(portname);
385 msleep(1000);
386 printf(".");
387 fflush(stdout);
388 } while(++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
389 printf("\n");
390 }
391
392 // check result of uart opening
393 if (sp == INVALID_SERIAL_PORT) {
394 printf("ERROR: invalid serial port\n");
395 sp = NULL;
396 serial_port_name = NULL;
397 return false;
398 } else if (sp == CLAIMED_SERIAL_PORT) {
399 printf("ERROR: serial port is claimed by another process\n");
400 sp = NULL;
401 serial_port_name = NULL;
402 return false;
403 } else {
404 // start the USB communication thread
405 serial_port_name = portname;
406 conn.run = true;
407 pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn);
408 return true;
409 }
410 }
411
412
413 void CloseProxmark(void) {
414 conn.run = false;
415
416 #ifdef __BIONIC__
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
419 //
420 // In Bionic libc, pthread_t is an integer.
421
422 if (USB_communication_thread != 0) {
423 pthread_join(USB_communication_thread, NULL);
424 }
425 #else
426 // pthread_t is a struct on other libc, treat as an opaque memory reference
427 pthread_join(USB_communication_thread, NULL);
428 #endif
429
430 if (sp) {
431 uart_close(sp);
432 }
433
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/*
436 //
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);
440 }
441 #endif
442
443 // Clean up our state
444 sp = NULL;
445 serial_port_name = NULL;
446 #ifdef __BIONIC__
447 memset(&USB_communication_thread, 0, sizeof(pthread_t));
448 #endif
449 }
450
451
452 /**
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.
458 * @param ms_timeout
459 * @param show_warning display message after 2 seconds
460 * @return true if command was returned, otherwise false
461 */
462 bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
463
464 UsbCommand resp;
465
466 #ifdef COMMS_DEBUG
467 printf("Waiting for %04x cmd\n", cmd);
468 #endif
469
470 if (response == NULL) {
471 response = &resp;
472 }
473
474 uint64_t start_time = msclock();
475
476 // Wait until the command is received
477 while (true) {
478 while (getCommand(response)) {
479 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
480 return true;
481 }
482 }
483
484 if (msclock() - start_time > ms_timeout) {
485 break;
486 }
487
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;
493 }
494 }
495 return false;
496 }
497
498
499 bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
500 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
501 }
502
503 bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
504 return WaitForResponseTimeoutW(cmd, response, -1, true);
505 }
506
Impressum, Datenschutz