]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/comms.c
b62f6fda47e3f94c796345e118ae052b27c323b5
[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 <pthread.h>
13
14 #include "comms.h"
15 #include "uart.h"
16 #include "ui.h"
17 #include "common.h"
18 #include "util_posix.h"
19
20 // Declare globals.
21
22 // Serial port that we are communicating with the PM3 on.
23 static serial_port sp;
24
25 // If TRUE, then there is no active connection to the PM3, and we will drop commands sent.
26 static bool offline;
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.
33 static UsbCommand txcmd;
34 volatile 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})
38 static UsbCommand cmdBuffer[CMD_BUFFER_SIZE];
39
40 // Points to the next empty position to write to
41 static int cmd_head = 0;
42
43 // Points to the position of the last unread command
44 static int cmd_tail = 0;
45
46 // to lock cmdBuffer operations from different threads
47 static pthread_mutex_t cmdBufferMutex = PTHREAD_MUTEX_INITIALIZER;
48
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
52 void SetOffline(bool new_offline) {
53 offline = new_offline;
54 }
55
56 bool IsOffline() {
57 return offline;
58 }
59
60 bool 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
88 void CloseProxmark(void) {
89 uart_close(sp);
90 }
91
92 void SendCommand(UsbCommand *c) {
93 #ifdef COMMS_DEBUG
94 printf("Sending %04x cmd\n", c->cmd);
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);
107
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 */
119 void 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 */
131 void 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 */
155 int 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
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 //----------------------------------------------------------------------------------
179 static void UsbCommandReceived(UsbCommand *UC)
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
197 default:
198 storeCommand(UC);
199 break;
200 }
201
202 }
203
204
205 void
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) {
212 receiver_arg *conn = (receiver_arg*)targ;
213 size_t rxlen;
214 uint8_t rx[sizeof(UsbCommand)];
215 uint8_t *prx = rx;
216
217 while (conn->run) {
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
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 */
254 bool 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
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
297 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
298 * @param response struct to copy received command into.
299 * @param ms_timeout
300 * @param show_warning display message after 2 seconds
301 * @return true if command was returned, otherwise false
302 */
303 bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
304
305 UsbCommand resp;
306
307 #ifdef COMMS_DEBUG
308 printf("Waiting for %04x cmd\n", cmd);
309 #endif
310
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)) {
320 if (cmd == CMD_UNKNOWN || response->cmd == cmd) {
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) {
330 // 2 seconds elapsed (but this doesn't mean the timeout was exceeded)
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
340 bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout) {
341 return WaitForResponseTimeoutW(cmd, response, ms_timeout, true);
342 }
343
344 bool WaitForResponse(uint32_t cmd, UsbCommand* response) {
345 return WaitForResponseTimeoutW(cmd, response, -1, true);
346 }
347
Impressum, Datenschutz