]> git.zerfleddert.de Git - proxmark3-svn/blame - client/comms.c
rework of GetFromBigBuf() (#597)
[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
12#include <pthread.h>
13
14#include "comms.h"
15#include "uart.h"
16#include "ui.h"
17#include "common.h"
f5ecd97b 18#include "util_posix.h"
19
20// Declare globals.
21
22// Serial port that we are communicating with the PM3 on.
818efbeb 23static serial_port sp;
f5ecd97b 24
25// If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
61aaee35 26static bool offline;
f5ecd97b 27
28// Transmit buffer.
29// TODO: Use locks and execute this on the main thread, rather than the receiver
30// thread. Running on the main thread means we need to be careful in the
31// flasher, as it means SendCommand is no longer async, and can't be used as a
32// buffer for a pending command when the connection is re-established.
33static UsbCommand txcmd;
34volatile static bool txcmd_pending = false;
35
36// Used by UsbReceiveCommand as a ring buffer for messages that are yet to be
37// processed by a command handler (WaitForResponse{,Timeout})
38static UsbCommand cmdBuffer[CMD_BUFFER_SIZE];
39
40// Points to the next empty position to write to
41static int cmd_head = 0;
42
43// Points to the position of the last unread command
44static int cmd_tail = 0;
45
46// to lock cmdBuffer operations from different threads
47static pthread_mutex_t cmdBufferMutex = PTHREAD_MUTEX_INITIALIZER;
48
61aaee35 49// These wrappers are required because it is not possible to access a static
50// global variable outside of the context of a single file.
51
52void SetOffline(bool new_offline) {
53 offline = new_offline;
54}
55
56bool IsOffline() {
57 return offline;
58}
f5ecd97b 59
818efbeb 60bool OpenProxmark(char *portname, bool waitCOMPort, int timeout) {
61 if (!waitCOMPort) {
62 sp = uart_open(portname);
63 } else {
64 printf("Waiting for Proxmark to appear on %s ", portname);
65 fflush(stdout);
66 int openCount = 0;
67 do {
68 sp = uart_open(portname);
69 msleep(1000);
70 printf(".");
71 fflush(stdout);
72 } while(++openCount < timeout && (sp == INVALID_SERIAL_PORT || sp == CLAIMED_SERIAL_PORT));
73 printf("\n");
74 }
75
76 // check result of uart opening
77 if (sp == INVALID_SERIAL_PORT) {
78 printf("ERROR: invalid serial port\n");
79 return false;
80 } else if (sp == CLAIMED_SERIAL_PORT) {
81 printf("ERROR: serial port is claimed by another process\n");
82 return false;
83 } else {
84 return true;
85 }
86}
87
88void CloseProxmark(void) {
89 uart_close(sp);
90}
91
f5ecd97b 92void SendCommand(UsbCommand *c) {
61aaee35 93 #ifdef COMMS_DEBUG
94 printf("Sending %04x cmd\n", c->cmd);
f5ecd97b 95 #endif
96
97 if (offline) {
98 PrintAndLog("Sending bytes to proxmark failed - offline");
99 return;
100 }
101 /**
102 The while-loop below causes hangups at times, when the pm3 unit is unresponsive
103 or disconnected. The main console thread is alive, but comm thread just spins here.
104 Not good.../holiman
105 **/
106 while(txcmd_pending);
818efbeb 107
f5ecd97b 108 txcmd = *c;
109 txcmd_pending = true;
110}
111
112
113/**
114 * @brief This method should be called when sending a new command to the pm3. In case any old
115 * responses from previous commands are stored in the buffer, a call to this method should clear them.
116 * A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
117 * operation. Right now we'll just have to live with this.
118 */
119void clearCommandBuffer()
120{
121 //This is a very simple operation
122 pthread_mutex_lock(&cmdBufferMutex);
123 cmd_tail = cmd_head;
124 pthread_mutex_unlock(&cmdBufferMutex);
125}
126
127/**
128 * @brief storeCommand stores a USB command in a circular buffer
129 * @param UC
130 */
131void storeCommand(UsbCommand *command)
132{
133 pthread_mutex_lock(&cmdBufferMutex);
134 if( (cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail)
135 {
136 // If these two are equal, we're about to overwrite in the
137 // circular buffer.
138 PrintAndLog("WARNING: Command buffer about to overwrite command! This needs to be fixed!");
139 }
140
141 // Store the command at the 'head' location
142 UsbCommand* destination = &cmdBuffer[cmd_head];
143 memcpy(destination, command, sizeof(UsbCommand));
144
145 cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; //increment head and wrap
146 pthread_mutex_unlock(&cmdBufferMutex);
147}
148
149
150/**
151 * @brief getCommand gets a command from an internal circular buffer.
152 * @param response location to write command
153 * @return 1 if response was returned, 0 if nothing has been received
154 */
155int getCommand(UsbCommand* response)
156{
157 pthread_mutex_lock(&cmdBufferMutex);
158 //If head == tail, there's nothing to read, or if we just got initialized
159 if (cmd_head == cmd_tail){
160 pthread_mutex_unlock(&cmdBufferMutex);
161 return 0;
162 }
163
164 //Pick out the next unread command
165 UsbCommand* last_unread = &cmdBuffer[cmd_tail];
166 memcpy(response, last_unread, sizeof(UsbCommand));
167 //Increment tail - this is a circular buffer, so modulo buffer size
168 cmd_tail = (cmd_tail + 1) % CMD_BUFFER_SIZE;
169
170 pthread_mutex_unlock(&cmdBufferMutex);
171 return 1;
172}
173
174
babca445 175//----------------------------------------------------------------------------------
176// Entry point into our code: called whenever we received a packet over USB.
177// Handle debug commands directly, store all other commands in circular buffer.
178//----------------------------------------------------------------------------------
818efbeb 179static void UsbCommandReceived(UsbCommand *UC)
f5ecd97b 180{
181 switch(UC->cmd) {
182 // First check if we are handling a debug message
183 case CMD_DEBUG_PRINT_STRING: {
184 char s[USB_CMD_DATA_SIZE+1];
185 memset(s, 0x00, sizeof(s));
186 size_t len = MIN(UC->arg[0],USB_CMD_DATA_SIZE);
187 memcpy(s,UC->d.asBytes,len);
188 PrintAndLog("#db# %s", s);
189 return;
190 } break;
191
192 case CMD_DEBUG_PRINT_INTEGERS: {
193 PrintAndLog("#db# %08x, %08x, %08x \r\n", UC->arg[0], UC->arg[1], UC->arg[2]);
194 return;
195 } break;
196
f5ecd97b 197 default:
818efbeb 198 storeCommand(UC);
f5ecd97b 199 break;
200 }
201
202}
203
204
205void
206#ifdef __has_attribute
207#if __has_attribute(force_align_arg_pointer)
208__attribute__((force_align_arg_pointer))
209#endif
210#endif
211*uart_receiver(void *targ) {
818efbeb 212 receiver_arg *conn = (receiver_arg*)targ;
f5ecd97b 213 size_t rxlen;
214 uint8_t rx[sizeof(UsbCommand)];
215 uint8_t *prx = rx;
216
818efbeb 217 while (conn->run) {
f5ecd97b 218 rxlen = 0;
219 if (uart_receive(sp, prx, sizeof(UsbCommand) - (prx-rx), &rxlen) && rxlen) {
220 prx += rxlen;
221 if (prx-rx < sizeof(UsbCommand)) {
222 continue;
223 }
224 UsbCommandReceived((UsbCommand*)rx);
225 }
226 prx = rx;
227
228 if(txcmd_pending) {
229 if (!uart_send(sp, (uint8_t*) &txcmd, sizeof(UsbCommand))) {
230 PrintAndLog("Sending bytes to proxmark failed");
231 }
232 txcmd_pending = false;
233 }
234 }
235
236 pthread_exit(NULL);
237 return NULL;
238}
239
240
babca445 241
242/**
243 * Data transfer from Proxmark to client. This method times out after
244 * ms_timeout milliseconds.
245 * @brief GetFromBigBuf
246 * @param dest Destination address for transfer
247 * @param bytes number of bytes to be transferred
248 * @param start_index offset into Proxmark3 BigBuf[]
249 * @param response struct to copy last command (CMD_ACK) into
250 * @param ms_timeout timeout in milliseconds
251 * @param show_warning display message after 2 seconds
252 * @return true if command was returned, otherwise false
253 */
254bool GetFromBigBuf(uint8_t *dest, int bytes, int start_index, UsbCommand *response, size_t ms_timeout, bool show_warning)
255{
256 UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}};
257 SendCommand(&c);
258
259 uint64_t start_time = msclock();
260
261 UsbCommand resp;
262 if (response == NULL) {
263 response = &resp;
264 }
265
266 int bytes_completed = 0;
267 while(true) {
268 if (getCommand(response)) {
269 if (response->cmd == CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K) {
270 int copy_bytes = MIN(bytes - bytes_completed, response->arg[1]);
271 memcpy(dest + response->arg[0], response->d.asBytes, copy_bytes);
272 bytes_completed += copy_bytes;
273 } else if (response->cmd == CMD_ACK) {
274 return true;
275 }
276 }
277
278 if (msclock() - start_time > ms_timeout) {
279 break;
280 }
281
282 if (msclock() - start_time > 2000 && show_warning) {
283 PrintAndLog("Waiting for a response from the proxmark...");
284 PrintAndLog("You can cancel this operation by pressing the pm3 button");
285 show_warning = false;
286 }
287 }
288
289 return false;
290}
291
292
f5ecd97b 293/**
294 * Waits for a certain response type. This method waits for a maximum of
295 * ms_timeout milliseconds for a specified response command.
296 *@brief WaitForResponseTimeout
61aaee35 297 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
f5ecd97b 298 * @param response struct to copy received command into.
299 * @param ms_timeout
babca445 300 * @param show_warning display message after 2 seconds
f5ecd97b 301 * @return true if command was returned, otherwise false
302 */
303bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
304
305 UsbCommand resp;
306
61aaee35 307 #ifdef COMMS_DEBUG
308 printf("Waiting for %04x cmd\n", cmd);
309 #endif
310
f5ecd97b 311 if (response == NULL) {
312 response = &resp;
313 }
314
315 uint64_t start_time = msclock();
316
317 // Wait until the command is received
318 while (true) {
319 while(getCommand(response)) {
61aaee35 320 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
f5ecd97b 321 return true;
322 }
323 }
324
325 if (msclock() - start_time > ms_timeout) {
326 break;
327 }
328
329 if (msclock() - start_time > 2000 && show_warning) {
61aaee35 330 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
f5ecd97b 331 PrintAndLog("Waiting for a response from the proxmark...");
332 PrintAndLog("You can cancel this operation by pressing the pm3 button");
333 show_warning = false;
334 }
335 }
336 return false;
337}
338
339
340bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
341 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
342}
343
344bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
345 return WaitForResponseTimeoutW(cmd, response, -1, true);
346}
347
Impressum, Datenschutz