]> git.zerfleddert.de Git - proxmark3-svn/blob - client/comms.c
d7f4265f9b76dd6f129ad35bbfce6b07d5659c2d
[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 <pthread.h>
15 #include <inttypes.h>
16
17 #if defined(__linux__) && !defined(NO_UNLINK)
18 #include <unistd.h> // for unlink()
19 #endif
20 #include "uart.h"
21 #include "ui.h"
22 #include "common.h"
23 #include "util_darwin.h"
24 #include "util_posix.h"
25
26
27 // Serial port that we are communicating with the PM3 on.
28 static serial_port sp = NULL;
29 static char *serial_port_name = NULL;
30
31 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
32 static bool offline;
33
34 typedef struct {
35 bool run; // If TRUE, continue running the uart_communication thread
36 bool block_after_ACK; // if true, block after receiving an ACK package
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 if (bytes_read != len - *received_len) {
199 printf("uart_receive() returned true but not enough bytes could be received. received: %d, wanted to receive: %d, already received before: %d\n",
200 bytes_read, len - *received_len, *received_len);
201 }
202 *received_len += bytes_read;
203 bytes_read = 0;
204 }
205 return (*received_len == len);
206 }
207
208
209 static void
210 #ifdef __has_attribute
211 #if __has_attribute(force_align_arg_pointer)
212 __attribute__((force_align_arg_pointer))
213 #endif
214 #endif
215 *uart_communication(void *targ) {
216 communication_arg_t *conn = (communication_arg_t*)targ;
217 uint8_t rx[sizeof(UsbCommand)];
218 size_t rxlen = 0;
219 uint8_t *prx = rx;
220 UsbCommand *command = (UsbCommand*)rx;
221 UsbResponse *response = (UsbResponse*)rx;
222
223 #if defined(__MACH__) && defined(__APPLE__)
224 disableAppNap("Proxmark3 polling UART");
225 #endif
226
227 while (conn->run) {
228 bool ACK_received = false;
229 prx = rx;
230 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)
231 if (receive_from_serial(sp, prx, bytes_to_read, &rxlen)) {
232 prx += rxlen;
233 if (response->cmd & CMD_VARIABLE_SIZE_FLAG) { // new style response with variable size
234 // printf("received new style response %04" PRIx16 ", datalen = %d, arg[0] = %08" PRIx32 ", arg[1] = %08" PRIx32 ", arg[2] = %08" PRIx32 "\n",
235 // response->cmd, response->datalen, response->arg[0], response->arg[1], response->arg[2]);
236 bytes_to_read = response->datalen;
237 if (receive_from_serial(sp, prx, bytes_to_read, &rxlen)) {
238 UsbCommand resp;
239 resp.cmd = response->cmd & ~CMD_VARIABLE_SIZE_FLAG;
240 resp.arg[0] = response->arg[0];
241 resp.arg[1] = response->arg[1];
242 resp.arg[2] = response->arg[2];
243 memcpy(&resp.d.asBytes, &response->d.asBytes, response->datalen);
244 UsbCommandReceived(&resp);
245 if (resp.cmd == CMD_ACK) {
246 ACK_received = true;
247 }
248 }
249 } else { // old style response uses same data structure as commands. Fixed size.
250 // printf("received old style response %016" PRIx64 ", arg[0] = %016" PRIx64 "\n", 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) {
255 ACK_received = true;
256 }
257 }
258 }
259 }
260
261 pthread_mutex_lock(&txBufferMutex);
262
263 if (conn->block_after_ACK) {
264 // if we just received an ACK, wait here until a new command is to be transmitted
265 if (ACK_received) {
266 while (!txBuffer_pending) {
267 pthread_cond_wait(&txBufferSig, &txBufferMutex);
268 }
269 }
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 pthread_cond_signal(&txBufferSig); // tell main thread that txBuffer is empty
278 }
279
280 pthread_mutex_unlock(&txBufferMutex);
281 }
282
283 #if defined(__MACH__) && defined(__APPLE__)
284 enableAppNap();
285 #endif
286
287 pthread_exit(NULL);
288 return NULL;
289 }
290
291
292 /**
293 * Data transfer from Proxmark to client. This method times out after
294 * ms_timeout milliseconds.
295 * @brief GetFromBigBuf
296 * @param dest Destination address for transfer
297 * @param bytes number of bytes to be transferred
298 * @param start_index offset into Proxmark3 BigBuf[]
299 * @param response struct to copy last command (CMD_ACK) into
300 * @param ms_timeout timeout in milliseconds
301 * @param show_warning display message after 2 seconds
302 * @return true if command was returned, otherwise false
303 */
304 bool GetFromBigBuf(uint8_t *dest, int bytes, int start_index, UsbCommand *response, size_t ms_timeout, bool show_warning)
305 {
306 UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}};
307 SendCommand(&c);
308
309 uint64_t start_time = msclock();
310
311 UsbCommand resp;
312 if (response == NULL) {
313 response = &resp;
314 }
315
316 int bytes_completed = 0;
317 while(true) {
318 if (getCommand(response)) {
319 if (response->cmd == CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
320 int copy_bytes = MIN(bytes - bytes_completed, response->arg[1]);
321 memcpy(dest + response->arg[0], response->d.asBytes, copy_bytes);
322 bytes_completed += copy_bytes;
323 } else if (response->cmd == CMD_ACK) {
324 return true;
325 }
326 }
327
328 if (msclock() - start_time > ms_timeout) {
329 break;
330 }
331
332 if (msclock() - start_time > 2000 && show_warning) {
333 PrintAndLog("Waiting for a response from the proxmark...");
334 PrintAndLog("You can cancel this operation by pressing the pm3 button");
335 show_warning = false;
336 }
337 }
338
339 return false;
340 }
341
342
343 bool GetFromFpgaRAM(uint8_t *dest, int bytes)
344 {
345 UsbCommand c = {CMD_HF_PLOT, {0, 0, 0}};
346 SendCommand(&c);
347
348 uint64_t start_time = msclock();
349
350 UsbCommand response;
351
352 int bytes_completed = 0;
353 bool show_warning = true;
354 while(true) {
355 if (getCommand(&response)) {
356 if (response.cmd == CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
357 int copy_bytes = MIN(bytes - bytes_completed, response.arg[1]);
358 memcpy(dest + response.arg[0], response.d.asBytes, copy_bytes);
359 bytes_completed += copy_bytes;
360 } else if (response.cmd == CMD_ACK) {
361 return true;
362 }
363 }
364
365 if (msclock() - start_time > 2000 && show_warning) {
366 PrintAndLog("Waiting for a response from the proxmark...");
367 PrintAndLog("You can cancel this operation by pressing the pm3 button");
368 show_warning = false;
369 }
370 }
371
372 return false;
373 }
374
375
376 bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode) {
377 char *portname = (char *)port;
378 if (!wait_for_port) {
379 sp = uart_open(portname);
380 } else {
381 printf("Waiting for Proxmark to appear on %s ", portname);
382 fflush(stdout);
383 int openCount = 0;
384 do {
385 sp = uart_open(portname);
386 msleep(1000);
387 printf(".");
388 fflush(stdout);
389 } while(++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
390 printf("\n");
391 }
392
393 // check result of uart opening
394 if (sp == INVALID_SERIAL_PORT) {
395 printf("ERROR: invalid serial port\n");
396 sp = NULL;
397 serial_port_name = NULL;
398 return false;
399 } else if (sp == CLAIMED_SERIAL_PORT) {
400 printf("ERROR: serial port is claimed by another process\n");
401 sp = NULL;
402 serial_port_name = NULL;
403 return false;
404 } else {
405 // start the USB communication thread
406 serial_port_name = portname;
407 conn.run = true;
408 conn.block_after_ACK = flash_mode;
409 pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn);
410 return true;
411 }
412 }
413
414
415 void CloseProxmark(void) {
416 conn.run = false;
417
418 #ifdef __BIONIC__
419 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
420 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
421 //
422 // In Bionic libc, pthread_t is an integer.
423
424 if (USB_communication_thread != 0) {
425 pthread_join(USB_communication_thread, NULL);
426 }
427 #else
428 // pthread_t is a struct on other libc, treat as an opaque memory reference
429 pthread_join(USB_communication_thread, NULL);
430 #endif
431
432 if (sp) {
433 uart_close(sp);
434 }
435
436 #if defined(__linux__) && !defined(NO_UNLINK)
437 // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
438 //
439 // This may be disabled at compile-time with -DNO_UNLINK (used for a JNI-based serial port on Android).
440 if (serial_port_name) {
441 unlink(serial_port_name);
442 }
443 #endif
444
445 // Clean up our state
446 sp = NULL;
447 serial_port_name = NULL;
448 #ifdef __BIONIC__
449 memset(&USB_communication_thread, 0, sizeof(pthread_t));
450 #endif
451 }
452
453
454 /**
455 * Waits for a certain response type. This method waits for a maximum of
456 * ms_timeout milliseconds for a specified response command.
457 *@brief WaitForResponseTimeout
458 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
459 * @param response struct to copy received command into.
460 * @param ms_timeout
461 * @param show_warning display message after 2 seconds
462 * @return true if command was returned, otherwise false
463 */
464 bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
465
466 UsbCommand resp;
467
468 #ifdef COMMS_DEBUG
469 printf("Waiting for %04x cmd\n", cmd);
470 #endif
471
472 if (response == NULL) {
473 response = &resp;
474 }
475
476 uint64_t start_time = msclock();
477
478 // Wait until the command is received
479 while (true) {
480 while(getCommand(response)) {
481 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
482 return true;
483 }
484 }
485
486 if (msclock() - start_time > ms_timeout) {
487 break;
488 }
489
490 if (msclock() - start_time > 2000 && show_warning) {
491 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
492 PrintAndLog("Waiting for a response from the proxmark...");
493 PrintAndLog("You can cancel this operation by pressing the pm3 button");
494 show_warning = false;
495 }
496 }
497 return false;
498 }
499
500
501 bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
502 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
503 }
504
505 bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
506 return WaitForResponseTimeoutW(cmd, response, -1, true);
507 }
508
Impressum, Datenschutz