Merge pull request #241 from pwpiwi/ukbhit_fix
[proxmark3-svn] / client / util.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // utilities
9 //-----------------------------------------------------------------------------
10
11 #if !defined(_WIN32)
12 #define _POSIX_C_SOURCE 199309L // need nanosleep()
13 #endif
14
15 #include "util.h"
16
17 #include <stdint.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <time.h>
23 #include "data.h"
24
25 #define MAX_BIN_BREAK_LENGTH (3072+384+1)
26
27 #ifndef _WIN32
28 #include <termios.h>
29 #include <sys/ioctl.h>
30 #include <unistd.h>
31
32 int ukbhit(void)
33 {
34 int cnt = 0;
35 int error;
36 static struct termios Otty, Ntty;
37
38 if ( tcgetattr(STDIN_FILENO, &Otty) == -1 ) return -1;
39 Ntty = Otty;
40
41 Ntty.c_iflag = 0x0000; // input mode
42 Ntty.c_oflag = 0x0000; // output mode
43 Ntty.c_lflag &= ~ICANON; // control mode = raw
44 Ntty.c_cc[VMIN] = 1; // return if at least 1 character is in the queue
45 Ntty.c_cc[VTIME] = 0; // no timeout. Wait forever
46
47 if (0 == (error = tcsetattr(STDIN_FILENO, TCSANOW, &Ntty))) { // set new attributes
48 error += ioctl(STDIN_FILENO, FIONREAD, &cnt); // get number of characters availabe
49 error += tcsetattr(STDIN_FILENO, TCSANOW, &Otty); // reset attributes
50 }
51
52 return ( error == 0 ? cnt : -1 );
53 }
54
55 #else
56
57 #include <conio.h>
58 int ukbhit(void) {
59 return kbhit();
60 }
61 #endif
62
63 // log files functions
64 void AddLogLine(char *file, char *extData, char *c) {
65 FILE *fLog = NULL;
66 char filename[FILE_PATH_SIZE] = {0x00};
67 int len = 0;
68
69 len = strlen(file);
70 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
71 memcpy(filename, file, len);
72
73 fLog = fopen(filename, "a");
74 if (!fLog) {
75 printf("Could not append log file %s", filename);
76 return;
77 }
78
79 fprintf(fLog, "%s", extData);
80 fprintf(fLog, "%s\n", c);
81 fclose(fLog);
82 }
83
84 void AddLogHex(char *fileName, char *extData, const uint8_t * data, const size_t len){
85 AddLogLine(fileName, extData, sprint_hex(data, len));
86 }
87
88 void AddLogUint64(char *fileName, char *extData, const uint64_t data) {
89 char buf[100] = {0};
90 sprintf(buf, "%x%x", (unsigned int)((data & 0xFFFFFFFF00000000) >> 32), (unsigned int)(data & 0xFFFFFFFF));
91 AddLogLine(fileName, extData, buf);
92 }
93
94 void AddLogCurrentDT(char *fileName) {
95 char buff[20];
96 struct tm *curTime;
97
98 time_t now = time(0);
99 curTime = gmtime(&now);
100
101 strftime (buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", curTime);
102 AddLogLine(fileName, "\nanticollision: ", buff);
103 }
104
105 void FillFileNameByUID(char *fileName, uint8_t * uid, char *ext, int byteCount) {
106 char * fnameptr = fileName;
107 memset(fileName, 0x00, 200);
108
109 for (int j = 0; j < byteCount; j++, fnameptr += 2)
110 sprintf(fnameptr, "%02x", (unsigned int) uid[j]);
111 sprintf(fnameptr, "%s", ext);
112 }
113
114 // printing and converting functions
115
116 void print_hex(const uint8_t * data, const size_t len)
117 {
118 size_t i;
119
120 for (i=0; i < len; i++)
121 printf("%02x ", data[i]);
122
123 printf("\n");
124 }
125
126 void print_hex_break(const uint8_t *data, const size_t len, uint8_t breaks) {
127
128 int rownum = 0;
129 printf("[%02d] | ", rownum);
130 for (int i = 0; i < len; ++i) {
131
132 printf("%02X ", data[i]);
133
134 // check if a line break is needed
135 if ( breaks > 0 && !((i+1) % breaks) && (i+1 < len) ) {
136 ++rownum;
137 printf("\n[%02d] | ", rownum);
138 }
139 }
140 printf("\n");
141 }
142
143 char *sprint_hex(const uint8_t *data, const size_t len) {
144
145 int maxLen = ( len > 1024/3) ? 1024/3 : len;
146 static char buf[1024];
147 memset(buf, 0x00, 1024);
148 char *tmp = buf;
149 size_t i;
150
151 for (i=0; i < maxLen; ++i, tmp += 3)
152 sprintf(tmp, "%02x ", (unsigned int) data[i]);
153
154 return buf;
155 }
156
157 char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) {
158 // make sure we don't go beyond our char array memory
159 int max_len;
160 if (breaks==0)
161 max_len = ( len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len;
162 else
163 max_len = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks);
164
165 static char buf[MAX_BIN_BREAK_LENGTH]; // 3072 + end of line characters if broken at 8 bits
166 //clear memory
167 memset(buf, 0x00, sizeof(buf));
168 char *tmp = buf;
169
170 size_t in_index = 0;
171 // loop through the out_index to make sure we don't go too far
172 for (size_t out_index=0; out_index < max_len-1; out_index++) {
173 // set character - (should be binary but verify it isn't more than 1 digit)
174 if (data[in_index]<10)
175 sprintf(tmp++, "%u", (unsigned int) data[in_index]);
176 // check if a line break is needed and we have room to print it in our array
177 if ( (breaks > 0) && !((in_index+1) % breaks) && (out_index+1 != max_len) ) {
178 // increment and print line break
179 out_index++;
180 sprintf(tmp++, "%s","\n");
181 }
182 in_index++;
183 }
184
185 return buf;
186 }
187
188 char *sprint_bin(const uint8_t *data, const size_t len) {
189 return sprint_bin_break(data, len, 0);
190 }
191
192 char *sprint_hex_ascii(const uint8_t *data, const size_t len) {
193 static char buf[1024];
194 char *tmp = buf;
195 memset(buf, 0x00, 1024);
196 size_t max_len = (len > 1010) ? 1010 : len;
197
198 sprintf(tmp, "%s| ", sprint_hex(data, max_len) );
199
200 size_t i = 0;
201 size_t pos = (max_len * 3)+2;
202 while(i < max_len){
203 char c = data[i];
204 if ( (c < 32) || (c == 127))
205 c = '.';
206 sprintf(tmp+pos+i, "%c", c);
207 ++i;
208 }
209 return buf;
210 }
211
212 char *sprint_ascii(const uint8_t *data, const size_t len) {
213 static char buf[1024];
214 char *tmp = buf;
215 memset(buf, 0x00, 1024);
216 size_t max_len = (len > 1010) ? 1010 : len;
217 size_t i = 0;
218 while(i < max_len){
219 char c = data[i];
220 tmp[i] = ((c < 32) || (c == 127)) ? '.' : c;
221 ++i;
222 }
223 return buf;
224 }
225
226 void num_to_bytes(uint64_t n, size_t len, uint8_t* dest)
227 {
228 while (len--) {
229 dest[len] = (uint8_t) n;
230 n >>= 8;
231 }
232 }
233
234 uint64_t bytes_to_num(uint8_t* src, size_t len)
235 {
236 uint64_t num = 0;
237 while (len--)
238 {
239 num = (num << 8) | (*src);
240 src++;
241 }
242 return num;
243 }
244
245 void num_to_bytebits(uint64_t n, size_t len, uint8_t *dest) {
246 while (len--) {
247 dest[len] = n & 1;
248 n >>= 1;
249 }
250 }
251
252 //least significant bit first
253 void num_to_bytebitsLSBF(uint64_t n, size_t len, uint8_t *dest) {
254 for(int i = 0 ; i < len ; ++i) {
255 dest[i] = n & 1;
256 n >>= 1;
257 }
258 }
259
260 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
261 // And clears the rest of the bits.
262 uint32_t SwapBits(uint32_t value, int nrbits) {
263 uint32_t newvalue = 0;
264 for(int i = 0; i < nrbits; i++) {
265 newvalue ^= ((value >> i) & 1) << (nrbits - 1 - i);
266 }
267 return newvalue;
268 }
269
270 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
271 // to
272 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
273 // up to 64 bytes or 512 bits
274 uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize){
275 static uint8_t buf[64];
276 memset(buf, 0x00, 64);
277 uint8_t *tmp = buf;
278 for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){
279 for (size_t i = 0; i < blockSize; i++){
280 tmp[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)];
281 }
282 }
283 return tmp;
284 }
285
286 // takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64),
287 // returns: the dest array contains the reordered src array.
288 void SwapEndian64ex(const uint8_t *src, const size_t len, const uint8_t blockSize, uint8_t *dest){
289 for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){
290 for (size_t i = 0; i < blockSize; i++){
291 dest[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)];
292 }
293 }
294 }
295
296 //assumes little endian
297 char * printBits(size_t const size, void const * const ptr)
298 {
299 unsigned char *b = (unsigned char*) ptr;
300 unsigned char byte;
301 static char buf[1024];
302 char * tmp = buf;
303 int i, j;
304
305 for (i=size-1;i>=0;i--)
306 {
307 for (j=7;j>=0;j--)
308 {
309 byte = b[i] & (1<<j);
310 byte >>= j;
311 sprintf(tmp, "%u", (unsigned int)byte);
312 tmp++;
313 }
314 }
315 return buf;
316 }
317
318 // -------------------------------------------------------------------------
319 // string parameters lib
320 // -------------------------------------------------------------------------
321
322 // -------------------------------------------------------------------------
323 // line - param line
324 // bg, en - symbol numbers in param line of beginning an ending parameter
325 // paramnum - param number (from 0)
326 // -------------------------------------------------------------------------
327 int param_getptr(const char *line, int *bg, int *en, int paramnum)
328 {
329 int i;
330 int len = strlen(line);
331
332 *bg = 0;
333 *en = 0;
334
335 // skip spaces
336 while (line[*bg] ==' ' || line[*bg]=='\t') (*bg)++;
337 if (*bg >= len) {
338 return 1;
339 }
340
341 for (i = 0; i < paramnum; i++) {
342 while (line[*bg]!=' ' && line[*bg]!='\t' && line[*bg] != '\0') (*bg)++;
343 while (line[*bg]==' ' || line[*bg]=='\t') (*bg)++;
344
345 if (line[*bg] == '\0') return 1;
346 }
347
348 *en = *bg;
349 while (line[*en] != ' ' && line[*en] != '\t' && line[*en] != '\0') (*en)++;
350
351 (*en)--;
352
353 return 0;
354 }
355
356
357 char param_getchar(const char *line, int paramnum)
358 {
359 int bg, en;
360
361 if (param_getptr(line, &bg, &en, paramnum)) return 0x00;
362
363 return line[bg];
364 }
365
366 uint8_t param_get8(const char *line, int paramnum)
367 {
368 return param_get8ex(line, paramnum, 0, 10);
369 }
370
371 /**
372 * @brief Reads a decimal integer (actually, 0-254, not 255)
373 * @param line
374 * @param paramnum
375 * @return -1 if error
376 */
377 uint8_t param_getdec(const char *line, int paramnum, uint8_t *destination)
378 {
379 uint8_t val = param_get8ex(line, paramnum, 255, 10);
380 if( (int8_t) val == -1) return 1;
381 (*destination) = val;
382 return 0;
383 }
384 /**
385 * @brief Checks if param is decimal
386 * @param line
387 * @param paramnum
388 * @return
389 */
390 uint8_t param_isdec(const char *line, int paramnum)
391 {
392 int bg, en;
393 //TODO, check more thorougly
394 if (!param_getptr(line, &bg, &en, paramnum)) return 1;
395 // return strtoul(&line[bg], NULL, 10) & 0xff;
396
397 return 0;
398 }
399
400 uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base)
401 {
402 int bg, en;
403
404 if (!param_getptr(line, &bg, &en, paramnum))
405 return strtoul(&line[bg], NULL, base) & 0xff;
406 else
407 return deflt;
408 }
409
410 uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base)
411 {
412 int bg, en;
413
414 if (!param_getptr(line, &bg, &en, paramnum))
415 return strtoul(&line[bg], NULL, base);
416 else
417 return deflt;
418 }
419
420 uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base)
421 {
422 int bg, en;
423
424 if (!param_getptr(line, &bg, &en, paramnum))
425 return strtoull(&line[bg], NULL, base);
426 else
427 return deflt;
428 }
429
430 int param_gethex(const char *line, int paramnum, uint8_t * data, int hexcnt)
431 {
432 int bg, en, temp, i;
433
434 if (hexcnt % 2)
435 return 1;
436
437 if (param_getptr(line, &bg, &en, paramnum)) return 1;
438
439 if (en - bg + 1 != hexcnt)
440 return 1;
441
442 for(i = 0; i < hexcnt; i += 2) {
443 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
444
445 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
446 data[i / 2] = temp & 0xff;
447 }
448
449 return 0;
450 }
451 int param_gethex_ex(const char *line, int paramnum, uint8_t * data, int *hexcnt)
452 {
453 int bg, en, temp, i;
454
455 //if (hexcnt % 2)
456 // return 1;
457
458 if (param_getptr(line, &bg, &en, paramnum)) return 1;
459
460 *hexcnt = en - bg + 1;
461 if (*hexcnt % 2) //error if not complete hex bytes
462 return 1;
463
464 for(i = 0; i < *hexcnt; i += 2) {
465 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
466
467 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
468 data[i / 2] = temp & 0xff;
469 }
470
471 return 0;
472 }
473 int param_getstr(const char *line, int paramnum, char * str)
474 {
475 int bg, en;
476
477 if (param_getptr(line, &bg, &en, paramnum)) return 0;
478
479 memcpy(str, line + bg, en - bg + 1);
480 str[en - bg + 1] = 0;
481
482 return en - bg + 1;
483 }
484
485 /*
486 The following methods comes from Rfidler sourcecode.
487 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
488 */
489
490 // convert hex to sequence of 0/1 bit values
491 // returns number of bits converted
492 int hextobinarray(char *target, char *source)
493 {
494 int length, i, count= 0;
495 char x;
496
497 length = strlen(source);
498 // process 4 bits (1 hex digit) at a time
499 while(length--)
500 {
501 x= *(source++);
502 // capitalize
503 if (x >= 'a' && x <= 'f')
504 x -= 32;
505 // convert to numeric value
506 if (x >= '0' && x <= '9')
507 x -= '0';
508 else if (x >= 'A' && x <= 'F')
509 x -= 'A' - 10;
510 else
511 return 0;
512 // output
513 for(i= 0 ; i < 4 ; ++i, ++count)
514 *(target++)= (x >> (3 - i)) & 1;
515 }
516
517 return count;
518 }
519
520 // convert hex to human readable binary string
521 int hextobinstring(char *target, char *source)
522 {
523 int length;
524
525 if(!(length= hextobinarray(target, source)))
526 return 0;
527 binarraytobinstring(target, target, length);
528 return length;
529 }
530
531 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
532 // return number of bits converted
533 int binarraytohex(char *target,char *source, int length)
534 {
535 unsigned char i, x;
536 int j = length;
537
538 if(j % 4)
539 return 0;
540
541 while(j)
542 {
543 for(i= x= 0 ; i < 4 ; ++i)
544 x += ( source[i] << (3 - i));
545 sprintf(target,"%X", (unsigned int)x);
546 ++target;
547 source += 4;
548 j -= 4;
549 }
550 return length;
551 }
552
553 // convert binary array to human readable binary
554 void binarraytobinstring(char *target, char *source, int length)
555 {
556 int i;
557
558 for(i= 0 ; i < length ; ++i)
559 *(target++)= *(source++) + '0';
560 *target= '\0';
561 }
562
563 // return parity bit required to match type
564 uint8_t GetParity( uint8_t *bits, uint8_t type, int length)
565 {
566 int x;
567
568 for(x= 0 ; length > 0 ; --length)
569 x += bits[length - 1];
570 x %= 2;
571
572 return x ^ type;
573 }
574
575 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
576 void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length)
577 {
578 *(target++)= GetParity(source, EVEN, length / 2);
579 memcpy(target, source, length);
580 target += length;
581 *(target)= GetParity(source + length / 2, ODD, length / 2);
582 }
583
584 // xor two arrays together for len items. The dst array contains the new xored values.
585 void xor(unsigned char *dst, unsigned char *src, size_t len) {
586 for( ; len > 0; len--,dst++,src++)
587 *dst ^= *src;
588 }
589
590 int32_t le24toh (uint8_t data[3]) {
591 return (data[2] << 16) | (data[1] << 8) | data[0];
592 }
593 uint32_t le32toh (uint8_t *data) {
594 return (uint32_t)( (data[3]<<24) | (data[2]<<16) | (data[1]<<8) | data[0]);
595 }
596
597 // RotateLeft - Ultralight, Desfire, works on byte level
598 // 00-01-02 >> 01-02-00
599 void rol(uint8_t *data, const size_t len){
600 uint8_t first = data[0];
601 for (size_t i = 0; i < len-1; i++) {
602 data[i] = data[i+1];
603 }
604 data[len-1] = first;
605 }
606
607
608 // Replace unprintable characters with a dot in char buffer
609 void clean_ascii(unsigned char *buf, size_t len) {
610 for (size_t i = 0; i < len; i++) {
611 if (!isprint(buf[i]))
612 buf[i] = '.';
613 }
614 }
615
616
617 // Timer functions
618 #if !defined (_WIN32)
619 #include <errno.h>
620
621 static void nsleep(uint64_t n) {
622 struct timespec timeout;
623 timeout.tv_sec = n/1000000000;
624 timeout.tv_nsec = n%1000000000;
625 while (nanosleep(&timeout, &timeout) && errno == EINTR);
626 }
627
628 void msleep(uint32_t n) {
629 nsleep(1000000 * n);
630 }
631
632 #endif // _WIN32
633
634 // a milliseconds timer for performance measurement
635 uint64_t msclock() {
636 #if defined(_WIN32)
637 #include <sys/types.h>
638 struct _timeb t;
639 if (_ftime_s(&t)) {
640 return 0;
641 } else {
642 return 1000 * t.time + t.millitm;
643 }
644 #else
645 struct timespec t;
646 clock_gettime(CLOCK_MONOTONIC, &t);
647 return (t.tv_sec * 1000 + t.tv_nsec / 1000000);
648 #endif
649 }
Impressum, Datenschutz