]> git.zerfleddert.de Git - proxmark3-svn/blob - client/util.c
Merge pull request #488 from pwpiwi/fix_usbpower
[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 #include "util.h"
12
13 #include <stdint.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <time.h>
19 #include "data.h"
20
21 #ifdef _WIN32
22 #include <windows.h>
23 #endif
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_hex_inrow_ex(const uint8_t *data, const size_t len, const size_t min_str_len) {
158
159 int maxLen = ( len > 1024/2) ? 1024/2 : len;
160 static char buf[1024] = {0};
161 char *tmp = buf;
162 size_t i;
163
164 for (i = 0; i < maxLen; ++i, tmp += 2)
165 sprintf(tmp, "%02x", (unsigned int) data[i]);
166
167 i *= 2;
168 int minStrLen = min_str_len > i ? min_str_len : 0;
169 for(; i < minStrLen; i++, tmp += 1)
170 sprintf(tmp, " ");
171
172 return buf;
173 }
174
175 char *sprint_hex_inrow(const uint8_t *data, const size_t len) {
176 return sprint_hex_inrow_ex(data, len, 0);
177 }
178
179 char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) {
180 // make sure we don't go beyond our char array memory
181 int max_len;
182 if (breaks==0)
183 max_len = ( len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len;
184 else
185 max_len = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks);
186
187 static char buf[MAX_BIN_BREAK_LENGTH]; // 3072 + end of line characters if broken at 8 bits
188 //clear memory
189 memset(buf, 0x00, sizeof(buf));
190 char *tmp = buf;
191
192 size_t in_index = 0;
193 // loop through the out_index to make sure we don't go too far
194 for (size_t out_index=0; out_index < max_len; out_index++) {
195 // set character - (should be binary but verify it isn't more than 1 digit)
196 if (data[in_index]<10)
197 sprintf(tmp++, "%u", (unsigned int) data[in_index]);
198 // check if a line break is needed and we have room to print it in our array
199 if ( (breaks > 0) && !((in_index+1) % breaks) && (out_index+1 < max_len) ) {
200 // increment and print line break
201 out_index++;
202 sprintf(tmp++, "%s","\n");
203 }
204 in_index++;
205 }
206
207 return buf;
208 }
209
210 char *sprint_bin(const uint8_t *data, const size_t len) {
211 return sprint_bin_break(data, len, 0);
212 }
213
214 char *sprint_hex_ascii(const uint8_t *data, const size_t len) {
215 static char buf[1024];
216 char *tmp = buf;
217 memset(buf, 0x00, 1024);
218 size_t max_len = (len > 255) ? 255 : len;
219 // max 255 bytes * 3 + 2 characters = 767 in buffer
220 sprintf(tmp, "%s| ", sprint_hex(data, max_len) );
221
222 size_t i = 0;
223 size_t pos = (max_len * 3)+2;
224 // add another 255 characters ascii = 1020 characters of buffer used
225 while(i < max_len) {
226 char c = data[i];
227 if ( (c < 32) || (c == 127))
228 c = '.';
229 sprintf(tmp+pos+i, "%c", c);
230 ++i;
231 }
232 return buf;
233 }
234
235 char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_str_len) {
236 static char buf[1024];
237 char *tmp = buf;
238 memset(buf, 0x00, 1024);
239 size_t max_len = (len > 1010) ? 1010 : len;
240 size_t i = 0;
241 while(i < max_len){
242 char c = data[i];
243 tmp[i] = ((c < 32) || (c == 127)) ? '.' : c;
244 ++i;
245 }
246
247 int minStrLen = min_str_len > i ? min_str_len : 0;
248 for(; i < minStrLen; ++i)
249 tmp[i] = ' ';
250
251 return buf;
252 }
253
254 char *sprint_ascii(const uint8_t *data, const size_t len) {
255 return sprint_ascii_ex(data, len, 0);
256 }
257
258 void num_to_bytes(uint64_t n, size_t len, uint8_t* dest)
259 {
260 while (len--) {
261 dest[len] = (uint8_t) n;
262 n >>= 8;
263 }
264 }
265
266 uint64_t bytes_to_num(uint8_t* src, size_t len)
267 {
268 uint64_t num = 0;
269 while (len--)
270 {
271 num = (num << 8) | (*src);
272 src++;
273 }
274 return num;
275 }
276
277 void num_to_bytebits(uint64_t n, size_t len, uint8_t *dest) {
278 while (len--) {
279 dest[len] = n & 1;
280 n >>= 1;
281 }
282 }
283
284 //least significant bit first
285 void num_to_bytebitsLSBF(uint64_t n, size_t len, uint8_t *dest) {
286 for(int i = 0 ; i < len ; ++i) {
287 dest[i] = n & 1;
288 n >>= 1;
289 }
290 }
291
292 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
293 // And clears the rest of the bits.
294 uint32_t SwapBits(uint32_t value, int nrbits) {
295 uint32_t newvalue = 0;
296 for(int i = 0; i < nrbits; i++) {
297 newvalue ^= ((value >> i) & 1) << (nrbits - 1 - i);
298 }
299 return newvalue;
300 }
301
302 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
303 // to
304 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
305 // up to 64 bytes or 512 bits
306 uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize){
307 static uint8_t buf[64];
308 memset(buf, 0x00, 64);
309 uint8_t *tmp = buf;
310 for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){
311 for (size_t i = 0; i < blockSize; i++){
312 tmp[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)];
313 }
314 }
315 return tmp;
316 }
317
318 // takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64),
319 // returns: the dest array contains the reordered src array.
320 void SwapEndian64ex(const uint8_t *src, const size_t len, const uint8_t blockSize, uint8_t *dest){
321 for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){
322 for (size_t i = 0; i < blockSize; i++){
323 dest[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)];
324 }
325 }
326 }
327
328 //assumes little endian
329 char * printBits(size_t const size, void const * const ptr)
330 {
331 unsigned char *b = (unsigned char*) ptr;
332 unsigned char byte;
333 static char buf[1024];
334 char * tmp = buf;
335 int i, j;
336
337 for (i=size-1;i>=0;i--)
338 {
339 for (j=7;j>=0;j--)
340 {
341 byte = b[i] & (1<<j);
342 byte >>= j;
343 sprintf(tmp, "%u", (unsigned int)byte);
344 tmp++;
345 }
346 }
347 return buf;
348 }
349
350 // -------------------------------------------------------------------------
351 // string parameters lib
352 // -------------------------------------------------------------------------
353
354 // -------------------------------------------------------------------------
355 // line - param line
356 // bg, en - symbol numbers in param line of beginning and ending parameter
357 // paramnum - param number (from 0)
358 // -------------------------------------------------------------------------
359 int param_getptr(const char *line, int *bg, int *en, int paramnum)
360 {
361 int i;
362 int len = strlen(line);
363
364 *bg = 0;
365 *en = 0;
366
367 // skip spaces
368 while (line[*bg] ==' ' || line[*bg]=='\t') (*bg)++;
369 if (*bg >= len) {
370 return 1;
371 }
372
373 for (i = 0; i < paramnum; i++) {
374 while (line[*bg]!=' ' && line[*bg]!='\t' && line[*bg] != '\0') (*bg)++;
375 while (line[*bg]==' ' || line[*bg]=='\t') (*bg)++;
376
377 if (line[*bg] == '\0') return 1;
378 }
379
380 *en = *bg;
381 while (line[*en] != ' ' && line[*en] != '\t' && line[*en] != '\0') (*en)++;
382
383 (*en)--;
384
385 return 0;
386 }
387
388
389 int param_getlength(const char *line, int paramnum)
390 {
391 int bg, en;
392
393 if (param_getptr(line, &bg, &en, paramnum)) return 0;
394
395 return en - bg + 1;
396 }
397
398 char param_getchar(const char *line, int paramnum) {
399 return param_getchar_indx(line, 0, paramnum);
400 }
401
402 char param_getchar_indx(const char *line, int indx, int paramnum) {
403 int bg, en;
404
405 if (param_getptr(line, &bg, &en, paramnum)) return 0x00;
406
407 if (bg + indx > en)
408 return '\0';
409
410 return line[bg + indx];
411 }
412
413 uint8_t param_get8(const char *line, int paramnum)
414 {
415 return param_get8ex(line, paramnum, 0, 10);
416 }
417
418 /**
419 * @brief Reads a decimal integer (actually, 0-254, not 255)
420 * @param line
421 * @param paramnum
422 * @return -1 if error
423 */
424 uint8_t param_getdec(const char *line, int paramnum, uint8_t *destination)
425 {
426 uint8_t val = param_get8ex(line, paramnum, 255, 10);
427 if( (int8_t) val == -1) return 1;
428 (*destination) = val;
429 return 0;
430 }
431 /**
432 * @brief Checks if param is decimal
433 * @param line
434 * @param paramnum
435 * @return
436 */
437 uint8_t param_isdec(const char *line, int paramnum)
438 {
439 int bg, en;
440 //TODO, check more thorougly
441 if (!param_getptr(line, &bg, &en, paramnum)) return 1;
442 // return strtoul(&line[bg], NULL, 10) & 0xff;
443
444 return 0;
445 }
446
447 uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base)
448 {
449 int bg, en;
450
451 if (!param_getptr(line, &bg, &en, paramnum))
452 return strtoul(&line[bg], NULL, base) & 0xff;
453 else
454 return deflt;
455 }
456
457 uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base)
458 {
459 int bg, en;
460
461 if (!param_getptr(line, &bg, &en, paramnum))
462 return strtoul(&line[bg], NULL, base);
463 else
464 return deflt;
465 }
466
467 uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base)
468 {
469 int bg, en;
470
471 if (!param_getptr(line, &bg, &en, paramnum))
472 return strtoull(&line[bg], NULL, base);
473 else
474 return deflt;
475 }
476
477 int param_gethex(const char *line, int paramnum, uint8_t * data, int hexcnt)
478 {
479 int bg, en, temp, i;
480
481 if (hexcnt % 2)
482 return 1;
483
484 if (param_getptr(line, &bg, &en, paramnum)) return 1;
485
486 if (en - bg + 1 != hexcnt)
487 return 1;
488
489 for(i = 0; i < hexcnt; i += 2) {
490 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
491
492 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
493 data[i / 2] = temp & 0xff;
494 }
495
496 return 0;
497 }
498 int param_gethex_ex(const char *line, int paramnum, uint8_t * data, int *hexcnt)
499 {
500 int bg, en, temp, i;
501
502 //if (hexcnt % 2)
503 // return 1;
504
505 if (param_getptr(line, &bg, &en, paramnum)) return 1;
506
507 *hexcnt = en - bg + 1;
508 if (*hexcnt % 2) //error if not complete hex bytes
509 return 1;
510
511 for(i = 0; i < *hexcnt; i += 2) {
512 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
513
514 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
515 data[i / 2] = temp & 0xff;
516 }
517
518 return 0;
519 }
520
521 int param_gethex_to_eol(const char *line, int paramnum, uint8_t * data, int maxdatalen, int *datalen) {
522 int bg, en;
523 uint32_t temp;
524 char buf[5] = {0};
525
526 if (param_getptr(line, &bg, &en, paramnum)) return 1;
527
528 *datalen = 0;
529
530 int indx = bg;
531 while (line[indx]) {
532 if (line[indx] == '\t' || line[indx] == ' ') {
533 indx++;
534 continue;
535 }
536
537 if (isxdigit(line[indx])) {
538 buf[strlen(buf) + 1] = 0x00;
539 buf[strlen(buf)] = line[indx];
540 } else {
541 // if we have symbols other than spaces and hex
542 return 1;
543 }
544
545 if (*datalen >= maxdatalen) {
546 // if we dont have space in buffer and have symbols to translate
547 return 2;
548 }
549
550 if (strlen(buf) >= 2) {
551 sscanf(buf, "%x", &temp);
552 data[*datalen] = (uint8_t)(temp & 0xff);
553 *buf = 0;
554 (*datalen)++;
555 }
556
557 indx++;
558 }
559
560 if (strlen(buf) > 0)
561 //error when not completed hex bytes
562 return 3;
563
564 return 0;
565 }
566
567 int param_getstr(const char *line, int paramnum, char * str, size_t buffersize)
568 {
569 int bg, en;
570
571 if (param_getptr(line, &bg, &en, paramnum)) {
572 return 0;
573 }
574
575 // Prevent out of bounds errors
576 if (en - bg + 1 >= buffersize) {
577 printf("out of bounds error: want %d bytes have %zd bytes\n", en - bg + 1 + 1, buffersize);
578 return 0;
579 }
580
581 memcpy(str, line + bg, en - bg + 1);
582 str[en - bg + 1] = 0;
583
584 return en - bg + 1;
585 }
586
587 /*
588 The following methods comes from Rfidler sourcecode.
589 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
590 */
591
592 // convert hex to sequence of 0/1 bit values
593 // returns number of bits converted
594 int hextobinarray(char *target, char *source)
595 {
596 int length, i, count= 0;
597 char* start = source;
598 char x;
599
600 length = strlen(source);
601 // process 4 bits (1 hex digit) at a time
602 while(length--)
603 {
604 x= *(source++);
605 // capitalize
606 if (x >= 'a' && x <= 'f')
607 x -= 32;
608 // convert to numeric value
609 if (x >= '0' && x <= '9')
610 x -= '0';
611 else if (x >= 'A' && x <= 'F')
612 x -= 'A' - 10;
613 else {
614 printf("Discovered unknown character %c %d at idx %d of %s\n", x, x, source - start, start);
615 return 0;
616 }
617 // output
618 for(i= 0 ; i < 4 ; ++i, ++count)
619 *(target++)= (x >> (3 - i)) & 1;
620 }
621
622 return count;
623 }
624
625 // convert hex to human readable binary string
626 int hextobinstring(char *target, char *source)
627 {
628 int length;
629
630 if(!(length= hextobinarray(target, source)))
631 return 0;
632 binarraytobinstring(target, target, length);
633 return length;
634 }
635
636 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
637 // return number of bits converted
638 int binarraytohex(char *target,char *source, int length)
639 {
640 unsigned char i, x;
641 int j = length;
642
643 if(j % 4)
644 return 0;
645
646 while(j)
647 {
648 for(i= x= 0 ; i < 4 ; ++i)
649 x += ( source[i] << (3 - i));
650 sprintf(target,"%X", (unsigned int)x);
651 ++target;
652 source += 4;
653 j -= 4;
654 }
655 return length;
656 }
657
658 // convert binary array to human readable binary
659 void binarraytobinstring(char *target, char *source, int length)
660 {
661 int i;
662
663 for(i= 0 ; i < length ; ++i)
664 *(target++)= *(source++) + '0';
665 *target= '\0';
666 }
667
668 // return parity bit required to match type
669 uint8_t GetParity( uint8_t *bits, uint8_t type, int length)
670 {
671 int x;
672
673 for(x= 0 ; length > 0 ; --length)
674 x += bits[length - 1];
675 x %= 2;
676
677 return x ^ type;
678 }
679
680 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
681 void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length)
682 {
683 *(target++)= GetParity(source, EVEN, length / 2);
684 memcpy(target, source, length);
685 target += length;
686 *(target)= GetParity(source + length / 2, ODD, length / 2);
687 }
688
689 // xor two arrays together for len items. The dst array contains the new xored values.
690 void xor(unsigned char *dst, unsigned char *src, size_t len) {
691 for( ; len > 0; len--,dst++,src++)
692 *dst ^= *src;
693 }
694
695 int32_t le24toh (uint8_t data[3]) {
696 return (data[2] << 16) | (data[1] << 8) | data[0];
697 }
698 uint32_t le32toh (uint8_t *data) {
699 return (uint32_t)( (data[3]<<24) | (data[2]<<16) | (data[1]<<8) | data[0]);
700 }
701
702 // RotateLeft - Ultralight, Desfire, works on byte level
703 // 00-01-02 >> 01-02-00
704 void rol(uint8_t *data, const size_t len){
705 uint8_t first = data[0];
706 for (size_t i = 0; i < len-1; i++) {
707 data[i] = data[i+1];
708 }
709 data[len-1] = first;
710 }
711
712
713 // Replace unprintable characters with a dot in char buffer
714 void clean_ascii(unsigned char *buf, size_t len) {
715 for (size_t i = 0; i < len; i++) {
716 if (!isprint(buf[i]))
717 buf[i] = '.';
718 }
719 }
720
721 // replace \r \n to \0
722 void strcleanrn(char *buf, size_t len) {
723 strcreplace(buf, len, '\n', '\0');
724 strcreplace(buf, len, '\r', '\0');
725 }
726
727 // replace char in buffer
728 void strcreplace(char *buf, size_t len, char from, char to) {
729 for (size_t i = 0; i < len; i++) {
730 if (buf[i] == from)
731 buf[i] = to;
732 }
733 }
734
735 char *strmcopy(char *buf) {
736 char * str = NULL;
737 if ((str = (char*) malloc(strlen(buf) + 1)) != NULL) {
738 memset(str, 0, strlen(buf) + 1);
739 strcpy(str, buf);
740 }
741 return str;
742 }
743
744
745 // determine number of logical CPU cores (use for multithreaded functions)
746 extern int num_CPUs(void)
747 {
748 #if defined(_WIN32)
749 #include <sysinfoapi.h>
750 SYSTEM_INFO sysinfo;
751 GetSystemInfo(&sysinfo);
752 return sysinfo.dwNumberOfProcessors;
753 #elif defined(__linux__) || defined(__APPLE__)
754 #include <unistd.h>
755 return sysconf(_SC_NPROCESSORS_ONLN);
756 #else
757 return 1;
758 #endif
759 }
760
Impressum, Datenschutz