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