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