Merge pull request #926 from pwpiwi/fix_iso15693_fpga
[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 #define _POSIX_C_SOURCE 199309L // need clock_gettime()
13
14 #include "comms.h"
15
16 #include <stdio.h>
17 #include <stddef.h>
18 #include <string.h>
19 #include <pthread.h>
20 #include <inttypes.h>
21 #include <time.h>
22 #include <sys/time.h>
23
24 #include "uart.h"
25 #include "ui.h"
26 #include "common.h"
27 #include "util_darwin.h"
28 #include "util_posix.h"
29
30
31 // Serial port that we are communicating with the PM3 on.
32 static serial_port sp = NULL;
33 static char *serial_port_name = NULL;
34
35 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
36 static bool offline;
37
38 typedef struct {
39 bool run; // If TRUE, continue running the uart_communication thread
40 } communication_arg_t;
41
42 static communication_arg_t conn;
43 static pthread_t USB_communication_thread;
44
45 // Transmit buffer.
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;
50
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()
55
56 static UsbCommand rxBuffer[CMD_BUFFER_SIZE];
57
58 // Points to the next empty position to write to
59 static int cmd_head = 0;
60
61 // Points to the position of the last unread command
62 static int cmd_tail = 0;
63
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;
67
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.
70
71 void SetOffline(bool new_offline) {
72 offline = new_offline;
73 }
74
75 bool IsOffline() {
76 return offline;
77 }
78
79 void SendCommand(UsbCommand *c) {
80 #ifdef COMMS_DEBUG
81 printf("Sending %04" PRIx64 " cmd\n", c->cmd);
82 #endif
83
84 if (offline) {
85 PrintAndLog("Sending bytes to proxmark failed - offline");
86 return;
87 }
88
89 pthread_mutex_lock(&txBufferMutex);
90 /**
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
93 **/
94 while (txBuffer_pending) {
95 pthread_cond_wait(&txBufferSig, &txBufferMutex); // wait for communication thread to complete sending a previous commmand
96 }
97
98 txBuffer = *c;
99 txBuffer_pending = true;
100 pthread_cond_signal(&txBufferSig); // tell communication thread that a new command can be send
101
102 pthread_mutex_unlock(&txBufferMutex);
103
104 }
105
106
107 /**
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.
112 */
113 void clearCommandBuffer() {
114 //This is a very simple operation
115 pthread_mutex_lock(&rxBufferMutex);
116 cmd_tail = cmd_head;
117 pthread_mutex_unlock(&rxBufferMutex);
118 }
119
120 /**
121 * @brief storeCommand stores a USB command in a circular buffer
122 * @param UC
123 */
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
128 // circular buffer.
129 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
130 }
131
132 // Store the command at the 'head' location
133 UsbCommand* destination = &rxBuffer[cmd_head];
134 memcpy(destination, command, sizeof(UsbCommand));
135
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);
139 }
140
141
142 /**
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
146 */
147 static int getCommand(UsbCommand* response, uint32_t ms_timeout) {
148
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;
156 }
157 pthread_mutex_lock(&rxBufferMutex);
158 int res = 0;
159 while (cmd_head == cmd_tail && !res) {
160 res = pthread_cond_timedwait(&rxBufferSig, &rxBufferMutex, &end_time);
161 }
162 if (res) { // timeout
163 pthread_mutex_unlock(&rxBufferMutex);
164 return 0;
165 }
166
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;
172
173 pthread_mutex_unlock(&rxBufferMutex);
174 return 1;
175 }
176
177
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) {
183 switch (UC->cmd) {
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);
191 return;
192 } break;
193
194 case CMD_DEBUG_PRINT_INTEGERS: {
195 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]);
196 return;
197 } break;
198
199 default:
200 storeCommand(UC);
201 break;
202 }
203
204 }
205
206
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;
209 *received_len = 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) {
212 #ifdef COMMS_DEBUG
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);
216 }
217 #endif
218 *received_len += bytes_read;
219 bytes_read = 0;
220 }
221 return (*received_len == len);
222 }
223
224
225 static void
226 #ifdef __has_attribute
227 #if __has_attribute(force_align_arg_pointer)
228 __attribute__((force_align_arg_pointer))
229 #endif
230 #endif
231 *uart_communication(void *targ) {
232 communication_arg_t *conn = (communication_arg_t*)targ;
233 uint8_t rx[sizeof(UsbCommand)];
234 size_t rxlen = 0;
235 uint8_t *prx = rx;
236 UsbCommand *command = (UsbCommand*)rx;
237 UsbResponse *response = (UsbResponse*)rx;
238
239 #if defined(__MACH__) && defined(__APPLE__)
240 disableAppNap("Proxmark3 polling UART");
241 #endif
242
243 while (conn->run) {
244 bool ACK_received = false;
245 prx = rx;
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)) {
248 prx += rxlen;
249 if (response->cmd & CMD_VARIABLE_SIZE_FLAG) { // new style response with variable size
250 #ifdef COMMS_DEBUG
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]);
253 #endif
254 bytes_to_read = response->datalen;
255 if (receive_from_serial(sp, prx, bytes_to_read, &rxlen)) {
256 UsbCommand resp;
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) {
264 ACK_received = true;
265 }
266 }
267 } else { // old style response uses same data structure as commands. Fixed size.
268 #ifdef COMMS_DEBUG
269 PrintAndLog("received old style response %016" PRIx64 ", arg[0] = %016" PRIx64, command->cmd, command->arg[0]);
270 #endif
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) {
275 ACK_received = true;
276 }
277 }
278 }
279 }
280
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
285 if (ACK_received) {
286 while (!txBuffer_pending) {
287 pthread_cond_wait(&txBufferSig, &txBufferMutex);
288 }
289 }
290 if (txBuffer_pending) {
291 if (!uart_send(sp, (uint8_t*) &txBuffer, sizeof(UsbCommand))) {
292 PrintAndLog("Sending bytes to proxmark failed");
293 }
294 txBuffer_pending = false;
295 }
296 pthread_cond_signal(&txBufferSig); // tell main thread that txBuffer is empty
297 pthread_mutex_unlock(&txBufferMutex);
298 }
299
300 #if defined(__MACH__) && defined(__APPLE__)
301 enableAppNap();
302 #endif
303
304 pthread_exit(NULL);
305 return NULL;
306 }
307
308
309 /**
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
320 */
321 bool GetFromBigBuf(uint8_t *dest, int bytes, int start_index, UsbCommand *response, size_t ms_timeout, bool show_warning) {
322
323 uint64_t start_time = msclock();
324
325 UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}};
326 SendCommand(&c);
327
328 UsbCommand resp;
329 if (response == NULL) {
330 response = &resp;
331 }
332
333 int bytes_completed = 0;
334 while (true) {
335 if (msclock() - start_time > ms_timeout) {
336 break; // timeout
337 }
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;
343 }
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) {
350 return true;
351 }
352 }
353 }
354
355 return false;
356 }
357
358
359 bool GetFromFpgaRAM(uint8_t *dest, int bytes) {
360
361 uint64_t start_time = msclock();
362
363 UsbCommand c = {CMD_HF_PLOT, {0, 0, 0}};
364 SendCommand(&c);
365
366 UsbCommand response;
367
368 int bytes_completed = 0;
369 bool show_warning = true;
370 while (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;
375 }
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) {
382 return true;
383 }
384 }
385 }
386
387 return false;
388 }
389
390
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);
395 } else {
396 printf("Waiting for Proxmark to appear on %s ", portname);
397 fflush(stdout);
398 int openCount = 0;
399 do {
400 sp = uart_open(portname);
401 msleep(1000);
402 printf(".");
403 fflush(stdout);
404 } while (++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
405 printf("\n");
406 }
407
408 // check result of uart opening
409 if (sp == INVALID_SERIAL_PORT) {
410 printf("ERROR: invalid serial port\n");
411 sp = NULL;
412 serial_port_name = NULL;
413 return false;
414 } else if (sp == CLAIMED_SERIAL_PORT) {
415 printf("ERROR: serial port is claimed by another process\n");
416 sp = NULL;
417 serial_port_name = NULL;
418 return false;
419 } else {
420 // start the USB communication thread
421 serial_port_name = portname;
422 conn.run = true;
423 pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn);
424 return true;
425 }
426 }
427
428
429 void CloseProxmark(void) {
430 conn.run = false;
431
432 #ifdef __BIONIC__
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
435 //
436 // In Bionic libc, pthread_t is an integer.
437
438 if (USB_communication_thread != 0) {
439 pthread_join(USB_communication_thread, NULL);
440 }
441 #else
442 // pthread_t is a struct on other libc, treat as an opaque memory reference
443 pthread_join(USB_communication_thread, NULL);
444 #endif
445
446 if (sp) {
447 uart_close(sp);
448 }
449
450 // Clean up our state
451 sp = NULL;
452 serial_port_name = NULL;
453 #ifdef __BIONIC__
454 memset(&USB_communication_thread, 0, sizeof(pthread_t));
455 #endif
456 }
457
458
459 /**
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.
465 * @param ms_timeout
466 * @param show_warning display message after 2 seconds
467 * @return true if command was returned, otherwise false
468 */
469 bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
470
471 UsbCommand resp;
472
473 #ifdef COMMS_DEBUG
474 printf("Waiting for %04x cmd\n", cmd);
475 #endif
476
477 uint64_t start_time = msclock();
478
479 if (response == NULL) {
480 response = &resp;
481 }
482
483 // Wait until the command is received
484 while (true) {
485 if (ms_timeout != -1 && msclock() > start_time + ms_timeout) {
486 break; // timeout
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 if (getCommand(response, CMD_BUFFER_CHECK_TIME)) {
495 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
496 return true;
497 }
498 }
499 }
500 return false;
501 }
502
503
504 bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
505 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
506 }
507
508 bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
509 return WaitForResponseTimeoutW(cmd, response, -1, true);
510 }
511
Impressum, Datenschutz