]> git.zerfleddert.de Git - proxmark3-svn/blame - client/comms.c
Merge branch 'master' into fix_iclass_sim
[proxmark3-svn] / client / comms.c
CommitLineData
f5ecd97b 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
f5ecd97b 12#include "comms.h"
ad939de5 13
14#include <pthread.h>
577b1c27 15#if defined(__linux__) && !defined(NO_UNLINK)
ad939de5 16#include <unistd.h> // for unlink()
17#endif
f5ecd97b 18#include "uart.h"
19#include "ui.h"
20#include "common.h"
2a537311 21#include "util_darwin.h"
f5ecd97b 22#include "util_posix.h"
23
f5ecd97b 24
25// Serial port that we are communicating with the PM3 on.
ad939de5 26static serial_port sp = NULL;
27static char *serial_port_name = NULL;
f5ecd97b 28
29// If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
61aaee35 30static bool offline;
f5ecd97b 31
ad939de5 32typedef struct {
33 bool run; // If TRUE, continue running the uart_communication thread
34 bool block_after_ACK; // if true, block after receiving an ACK package
35} communication_arg_t;
36
37static communication_arg_t conn;
38static pthread_t USB_communication_thread;
39
f5ecd97b 40// Transmit buffer.
ad939de5 41static UsbCommand txBuffer;
42static bool txBuffer_pending = false;
43static pthread_mutex_t txBufferMutex = PTHREAD_MUTEX_INITIALIZER;
44static pthread_cond_t txBufferSig = PTHREAD_COND_INITIALIZER;
f5ecd97b 45
46// Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
47// processed by a command handler (WaitForResponse{,Timeout})
ad939de5 48static UsbCommand rxBuffer[CMD_BUFFER_SIZE];
f5ecd97b 49
50// Points to the next empty position to write to
51static int cmd_head = 0;
52
53// Points to the position of the last unread command
54static int cmd_tail = 0;
55
ad939de5 56// to lock rxBuffer operations from different threads
57static pthread_mutex_t rxBufferMutex = PTHREAD_MUTEX_INITIALIZER;
f5ecd97b 58
61aaee35 59// These wrappers are required because it is not possible to access a static
60// global variable outside of the context of a single file.
61
62void SetOffline(bool new_offline) {
63 offline = new_offline;
64}
65
66bool IsOffline() {
67 return offline;
68}
f5ecd97b 69
70void SendCommand(UsbCommand *c) {
61aaee35 71 #ifdef COMMS_DEBUG
72 printf("Sending %04x cmd\n", c->cmd);
f5ecd97b 73 #endif
74
75 if (offline) {
76 PrintAndLog("Sending bytes to proxmark failed - offline");
77 return;
78 }
ad939de5 79
80 pthread_mutex_lock(&txBufferMutex);
f5ecd97b 81 /**
ad939de5 82 This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive,
83 but comm thread just spins here. Not good.../holiman
f5ecd97b 84 **/
ad939de5 85 while (txBuffer_pending) {
86 pthread_cond_wait(&txBufferSig, &txBufferMutex); // wait for communication thread to complete sending a previous commmand
87 }
88
89 txBuffer = *c;
90 txBuffer_pending = true;
91 pthread_cond_signal(&txBufferSig); // tell communication thread that a new command can be send
92
93 pthread_mutex_unlock(&txBufferMutex);
818efbeb 94
f5ecd97b 95}
96
97
98/**
99 * @brief This method should be called when sending a new command to the pm3. In case any old
100 * responses from previous commands are stored in the buffer, a call to this method should clear them.
101 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
102 * operation. Right now we'll just have to live with this.
103 */
104void clearCommandBuffer()
105{
106 //This is a very simple operation
ad939de5 107 pthread_mutex_lock(&rxBufferMutex);
f5ecd97b 108 cmd_tail = cmd_head;
ad939de5 109 pthread_mutex_unlock(&rxBufferMutex);
f5ecd97b 110}
111
112/**
113 * @brief storeCommand stores a USB command in a circular buffer
114 * @param UC
115 */
ad939de5 116static void storeCommand(UsbCommand *command)
f5ecd97b 117{
ad939de5 118 pthread_mutex_lock(&rxBufferMutex);
f5ecd97b 119 if( (cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail)
120 {
121 // If these two are equal, we're about to overwrite in the
122 // circular buffer.
123 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
124 }
125
126 // Store the command at the 'head' location
ad939de5 127 UsbCommand* destination = &rxBuffer[cmd_head];
f5ecd97b 128 memcpy(destination, command, sizeof(UsbCommand));
129
130 cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap
ad939de5 131 pthread_mutex_unlock(&rxBufferMutex);
f5ecd97b 132}
133
134
135/**
136 * @brief getCommand gets a command from an internal circular buffer.
137 * @param response location to write command
138 * @return 1 if response was returned, 0 if nothing has been received
139 */
ad939de5 140static int getCommand(UsbCommand* response)
f5ecd97b 141{
ad939de5 142 pthread_mutex_lock(&rxBufferMutex);
f5ecd97b 143 //If head == tail, there's nothing to read, or if we just got initialized
144 if (cmd_head == cmd_tail){
ad939de5 145 pthread_mutex_unlock(&rxBufferMutex);
f5ecd97b 146 return 0;
147 }
148
149 //Pick out the next unread command
ad939de5 150 UsbCommand* last_unread = &rxBuffer[cmd_tail];
f5ecd97b 151 memcpy(response, last_unread, sizeof(UsbCommand));
152 //Increment tail - this is a circular buffer, so modulo buffer size
153 cmd_tail = (cmd_tail + 1) % CMD_BUFFER_SIZE;
154
ad939de5 155 pthread_mutex_unlock(&rxBufferMutex);
f5ecd97b 156 return 1;
157}
158
159
babca445 160//----------------------------------------------------------------------------------
161// Entry point into our code: called whenever we received a packet over USB.
162// Handle debug commands directly, store all other commands in circular buffer.
163//----------------------------------------------------------------------------------
818efbeb 164static void UsbCommandReceived(UsbCommand *UC)
f5ecd97b 165{
166 switch(UC->cmd) {
167 // First check if we are handling a debug message
168 case CMD_DEBUG_PRINT_STRING: {
169 char s[USB_CMD_DATA_SIZE+1];
170 memset(s, 0x00, sizeof(s));
171 size_t len = MIN(UC->arg[0],USB_CMD_DATA_SIZE);
172 memcpy(s,UC->d.asBytes,len);
173 PrintAndLog("#db# %s", s);
174 return;
175 } break;
176
177 case CMD_DEBUG_PRINT_INTEGERS: {
178 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]);
179 return;
180 } break;
181
f5ecd97b 182 default:
818efbeb 183 storeCommand(UC);
f5ecd97b 184 break;
185 }
186
187}
188
189
ad939de5 190static void
f5ecd97b 191#ifdef __has_attribute
192#if __has_attribute(force_align_arg_pointer)
193__attribute__((force_align_arg_pointer))
194#endif
195#endif
ad939de5 196*uart_communication(void *targ) {
197 communication_arg_t *conn = (communication_arg_t*)targ;
f5ecd97b 198 size_t rxlen;
ad939de5 199 UsbCommand rx;
200 UsbCommand *prx = &rx;
f5ecd97b 201
2a537311
A
202#if defined(__MACH__) && defined(__APPLE__)
203 disableAppNap("Proxmark3 polling UART");
204#endif
205
818efbeb 206 while (conn->run) {
f5ecd97b 207 rxlen = 0;
ad939de5 208 bool ACK_received = false;
209 if (uart_receive(sp, (uint8_t *)prx, sizeof(UsbCommand) - (prx-&rx), &rxlen) && rxlen) {
f5ecd97b 210 prx += rxlen;
ad939de5 211 if (prx-&rx < sizeof(UsbCommand)) {
f5ecd97b 212 continue;
213 }
ad939de5 214 UsbCommandReceived(&rx);
215 if (rx.cmd == CMD_ACK) {
216 ACK_received = true;
217 }
f5ecd97b 218 }
ad939de5 219 prx = &rx;
220
221
222 pthread_mutex_lock(&txBufferMutex);
f5ecd97b 223
ad939de5 224 if (conn->block_after_ACK) {
225 // if we just received an ACK, wait here until a new command is to be transmitted
226 if (ACK_received) {
227 while (!txBuffer_pending) {
228 pthread_cond_wait(&txBufferSig, &txBufferMutex);
229 }
230 }
231 }
232
233 if(txBuffer_pending) {
234 if (!uart_send(sp, (uint8_t*) &txBuffer, sizeof(UsbCommand))) {
f5ecd97b 235 PrintAndLog("Sending bytes to proxmark failed");
236 }
ad939de5 237 txBuffer_pending = false;
238 pthread_cond_signal(&txBufferSig); // tell main thread that txBuffer is empty
f5ecd97b 239 }
ad939de5 240
241 pthread_mutex_unlock(&txBufferMutex);
f5ecd97b 242 }
243
2a537311
A
244#if defined(__MACH__) && defined(__APPLE__)
245 enableAppNap();
246#endif
247
f5ecd97b 248 pthread_exit(NULL);
249 return NULL;
250}
251
252
babca445 253/**
254 * Data transfer from Proxmark to client. This method times out after
255 * ms_timeout milliseconds.
256 * @brief GetFromBigBuf
257 * @param dest Destination address for transfer
258 * @param bytes number of bytes to be transferred
259 * @param start_index offset into Proxmark3 BigBuf[]
260 * @param response struct to copy last command (CMD_ACK) into
261 * @param ms_timeout timeout in milliseconds
262 * @param show_warning display message after 2 seconds
263 * @return true if command was returned, otherwise false
264 */
265bool GetFromBigBuf(uint8_t *dest, int bytes, int start_index, UsbCommand *response, size_t ms_timeout, bool show_warning)
266{
267 UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}};
268 SendCommand(&c);
269
270 uint64_t start_time = msclock();
271
272 UsbCommand resp;
273 if (response == NULL) {
274 response = &resp;
275 }
276
277 int bytes_completed = 0;
278 while(true) {
279 if (getCommand(response)) {
280 if (response->cmd == CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
281 int copy_bytes = MIN(bytes - bytes_completed, response->arg[1]);
282 memcpy(dest + response->arg[0], response->d.asBytes, copy_bytes);
283 bytes_completed += copy_bytes;
284 } else if (response->cmd == CMD_ACK) {
285 return true;
286 }
287 }
288
289 if (msclock() - start_time > ms_timeout) {
290 break;
291 }
292
293 if (msclock() - start_time > 2000 && show_warning) {
294 PrintAndLog("Waiting for a response from the proxmark...");
295 PrintAndLog("You can cancel this operation by pressing the pm3 button");
296 show_warning = false;
297 }
298 }
299
300 return false;
301}
302
ad939de5 303
fc52fbd4 304bool GetFromFpgaRAM(uint8_t *dest, int bytes)
305{
306 UsbCommand c = {CMD_HF_PLOT, {0, 0, 0}};
307 SendCommand(&c);
308
309 uint64_t start_time = msclock();
310
311 UsbCommand response;
312
313 int bytes_completed = 0;
314 bool show_warning = true;
315 while(true) {
316 if (getCommand(&response)) {
317 if (response.cmd == CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
318 int copy_bytes = MIN(bytes - bytes_completed, response.arg[1]);
319 memcpy(dest + response.arg[0], response.d.asBytes, copy_bytes);
320 bytes_completed += copy_bytes;
321 } else if (response.cmd == CMD_ACK) {
322 return true;
323 }
324 }
325
326 if (msclock() - start_time > 2000 && show_warning) {
327 PrintAndLog("Waiting for a response from the proxmark...");
328 PrintAndLog("You can cancel this operation by pressing the pm3 button");
329 show_warning = false;
330 }
331 }
332
333 return false;
334}
335
336
ad939de5 337bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode) {
338 char *portname = (char *)port;
339 if (!wait_for_port) {
340 sp = uart_open(portname);
341 } else {
342 printf("Waiting for Proxmark to appear on %s ", portname);
343 fflush(stdout);
344 int openCount = 0;
345 do {
346 sp = uart_open(portname);
347 msleep(1000);
348 printf(".");
349 fflush(stdout);
350 } while(++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
351 printf("\n");
352 }
353
354 // check result of uart opening
355 if (sp == INVALID_SERIAL_PORT) {
356 printf("ERROR: invalid serial port\n");
357 sp = NULL;
358 serial_port_name = NULL;
359 return false;
360 } else if (sp == CLAIMED_SERIAL_PORT) {
361 printf("ERROR: serial port is claimed by another process\n");
362 sp = NULL;
363 serial_port_name = NULL;
364 return false;
365 } else {
366 // start the USB communication thread
367 serial_port_name = portname;
368 conn.run = true;
369 conn.block_after_ACK = flash_mode;
370 pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn);
371 return true;
372 }
373}
374
375
376void CloseProxmark(void) {
377 conn.run = false;
7b2cd970
MF
378
379#ifdef __BIONIC__
380 // In Android O and later, if an invalid pthread_t is passed to pthread_join, it calls fatal().
381 // https://github.com/aosp-mirror/platform_bionic/blob/ed16b344e75f422fb36fbfd91fb30de339475880/libc/bionic/pthread_internal.cpp#L116-L128
382 //
383 // In Bionic libc, pthread_t is an integer.
384
385 if (USB_communication_thread != 0) {
386 pthread_join(USB_communication_thread, NULL);
387 }
388#else
389 // pthread_t is a struct on other libc, treat as an opaque memory reference
ad939de5 390 pthread_join(USB_communication_thread, NULL);
7b2cd970 391#endif
2bb7f7e3
MF
392
393 if (sp) {
394 uart_close(sp);
395 }
396
577b1c27 397#if defined(__linux__) && !defined(NO_UNLINK)
ad939de5 398 // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
577b1c27
MF
399 //
400 // This may be disabled at compile-time with -DNO_UNLINK (used for a JNI-based serial port on Android).
ad939de5 401 if (serial_port_name) {
402 unlink(serial_port_name);
403 }
404#endif
2bb7f7e3
MF
405
406 // Clean up our state
407 sp = NULL;
408 serial_port_name = NULL;
eed83b91 409#ifdef __BIONIC__
7b2cd970 410 memset(&USB_communication_thread, 0, sizeof(pthread_t));
eed83b91 411#endif
ad939de5 412}
413
babca445 414
f5ecd97b 415/**
416 * Waits for a certain response type. This method waits for a maximum of
417 * ms_timeout milliseconds for a specified response command.
418 *@brief WaitForResponseTimeout
61aaee35 419 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
f5ecd97b 420 * @param response struct to copy received command into.
421 * @param ms_timeout
babca445 422 * @param show_warning display message after 2 seconds
f5ecd97b 423 * @return true if command was returned, otherwise false
424 */
425bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
426
427 UsbCommand resp;
428
61aaee35 429 #ifdef COMMS_DEBUG
430 printf("Waiting for %04x cmd\n", cmd);
431 #endif
432
f5ecd97b 433 if (response == NULL) {
434 response = &resp;
435 }
436
437 uint64_t start_time = msclock();
438
439 // Wait until the command is received
440 while (true) {
441 while(getCommand(response)) {
61aaee35 442 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
f5ecd97b 443 return true;
444 }
445 }
446
447 if (msclock() - start_time > ms_timeout) {
448 break;
449 }
450
451 if (msclock() - start_time > 2000 && show_warning) {
61aaee35 452 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
f5ecd97b 453 PrintAndLog("Waiting for a response from the proxmark...");
454 PrintAndLog("You can cancel this operation by pressing the pm3 button");
455 show_warning = false;
456 }
457 }
458 return false;
459}
460
461
462bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
463 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
464}
465
466bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
467 return WaitForResponseTimeoutW(cmd, response, -1, true);
468}
469
Impressum, Datenschutz