]>
git.zerfleddert.de Git - proxmark3-svn/blob - client/util.c
b7f07bde056ec5b79834088a77de8d466b08a358
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 iZsh <izsh at fail0verflow.com>
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
7 //-----------------------------------------------------------------------------
9 //-----------------------------------------------------------------------------
25 #define MAX_BIN_BREAK_LENGTH (3072+384+1)
29 #include <sys/ioctl.h>
36 static struct termios Otty
, Ntty
;
38 if ( tcgetattr(STDIN_FILENO
, &Otty
) == -1 ) return -1;
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
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
52 return ( error
== 0 ? cnt
: -1 );
63 // log files functions
64 void AddLogLine(char *file
, char *extData
, char *c
) {
66 char filename
[FILE_PATH_SIZE
] = {0x00};
70 if (len
> FILE_PATH_SIZE
) len
= FILE_PATH_SIZE
;
71 memcpy(filename
, file
, len
);
73 fLog
= fopen(filename
, "a");
75 printf("Could not append log file %s", filename
);
79 fprintf(fLog
, "%s", extData
);
80 fprintf(fLog
, "%s\n", c
);
84 void AddLogHex(char *fileName
, char *extData
, const uint8_t * data
, const size_t len
){
85 AddLogLine(fileName
, extData
, sprint_hex(data
, len
));
88 void AddLogUint64(char *fileName
, char *extData
, const uint64_t data
) {
90 sprintf(buf
, "%x%x", (unsigned int)((data
& 0xFFFFFFFF00000000) >> 32), (unsigned int)(data
& 0xFFFFFFFF));
91 AddLogLine(fileName
, extData
, buf
);
94 void AddLogCurrentDT(char *fileName
) {
99 curTime
= gmtime(&now
);
101 strftime (buff
, sizeof(buff
), "%Y-%m-%d %H:%M:%S", curTime
);
102 AddLogLine(fileName
, "\nanticollision: ", buff
);
105 void FillFileNameByUID(char *fileName
, uint8_t * uid
, char *ext
, int byteCount
) {
106 char * fnameptr
= fileName
;
107 memset(fileName
, 0x00, 200);
109 for (int j
= 0; j
< byteCount
; j
++, fnameptr
+= 2)
110 sprintf(fnameptr
, "%02x", (unsigned int) uid
[j
]);
111 sprintf(fnameptr
, "%s", ext
);
114 void hex_to_buffer(const uint8_t *buf
, const uint8_t *hex_data
, const size_t hex_len
, const size_t hex_max_len
,
115 const size_t min_str_len
, const size_t spaces_between
, bool uppercase
) {
117 char *tmp
= (char *)buf
;
120 int maxLen
= ( hex_len
> hex_max_len
) ? hex_max_len
: hex_len
;
122 for (i
= 0; i
< maxLen
; ++i
, tmp
+= 2 + spaces_between
) {
123 sprintf(tmp
, (uppercase
) ? "%02X" : "%02x", (unsigned int) hex_data
[i
]);
125 for (int j
= 0; j
< spaces_between
; j
++)
126 sprintf(tmp
+ 2 + j
, " ");
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)
139 // printing and converting functions
141 void print_hex(const uint8_t * data
, const size_t len
)
145 for (i
=0; i
< len
; i
++)
146 printf("%02x ", data
[i
]);
151 void print_hex_break(const uint8_t *data
, const size_t len
, uint8_t breaks
) {
154 printf("[%02d] | ", rownum
);
155 for (int i
= 0; i
< len
; ++i
) {
157 printf("%02X ", data
[i
]);
159 // check if a line break is needed
160 if ( breaks
> 0 && !((i
+1) % breaks
) && (i
+1 < len
) ) {
162 printf("\n[%02d] | ", rownum
);
168 char *sprint_hex(const uint8_t *data
, const size_t len
) {
169 static char buf
[1025] = {0};
171 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, 0, 1, false);
176 char *sprint_hex_inrow_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
177 static char buf
[1025] = {0};
179 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, min_str_len
, 0, false);
184 char *sprint_hex_inrow(const uint8_t *data
, const size_t len
) {
185 return sprint_hex_inrow_ex(data
, len
, 0);
188 char *sprint_bin_break(const uint8_t *data
, const size_t len
, const uint8_t breaks
) {
189 // make sure we don't go beyond our char array memory
192 max_len
= ( len
> MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
;
194 max_len
= ( len
+(len
/breaks
) > MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
+(len
/breaks
);
196 static char buf
[MAX_BIN_BREAK_LENGTH
]; // 3072 + end of line characters if broken at 8 bits
198 memset(buf
, 0x00, sizeof(buf
));
202 // loop through the out_index to make sure we don't go too far
203 for (size_t out_index
=0; out_index
< max_len
; out_index
++) {
204 // set character - (should be binary but verify it isn't more than 1 digit)
205 if (data
[in_index
]<10)
206 sprintf(tmp
++, "%u", (unsigned int) data
[in_index
]);
207 // check if a line break is needed and we have room to print it in our array
208 if ( (breaks
> 0) && !((in_index
+1) % breaks
) && (out_index
+1 < max_len
) ) {
209 // increment and print line break
211 sprintf(tmp
++, "%s","\n");
219 char *sprint_bin(const uint8_t *data
, const size_t len
) {
220 return sprint_bin_break(data
, len
, 0);
223 char *sprint_hex_ascii(const uint8_t *data
, const size_t len
) {
224 static char buf
[1024];
226 memset(buf
, 0x00, 1024);
227 size_t max_len
= (len
> 255) ? 255 : len
;
228 // max 255 bytes * 3 + 2 characters = 767 in buffer
229 sprintf(tmp
, "%s| ", sprint_hex(data
, max_len
) );
232 size_t pos
= (max_len
* 3)+2;
233 // add another 255 characters ascii = 1020 characters of buffer used
236 if ( (c
< 32) || (c
== 127))
238 sprintf(tmp
+pos
+i
, "%c", c
);
244 char *sprint_ascii_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
245 static char buf
[1024];
247 memset(buf
, 0x00, 1024);
248 size_t max_len
= (len
> 1010) ? 1010 : len
;
252 tmp
[i
] = ((c
< 32) || (c
== 127)) ? '.' : c
;
256 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
257 for(; i
< minStrLen
; ++i
)
263 char *sprint_ascii(const uint8_t *data
, const size_t len
) {
264 return sprint_ascii_ex(data
, len
, 0);
267 void num_to_bytes(uint64_t n
, size_t len
, uint8_t* dest
)
270 dest
[len
] = (uint8_t) n
;
275 uint64_t bytes_to_num(uint8_t* src
, size_t len
)
280 num
= (num
<< 8) | (*src
);
286 void num_to_bytebits(uint64_t n
, size_t len
, uint8_t *dest
) {
293 //least significant bit first
294 void num_to_bytebitsLSBF(uint64_t n
, size_t len
, uint8_t *dest
) {
295 for(int i
= 0 ; i
< len
; ++i
) {
301 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
302 // And clears the rest of the bits.
303 uint32_t SwapBits(uint32_t value
, int nrbits
) {
304 uint32_t newvalue
= 0;
305 for(int i
= 0; i
< nrbits
; i
++) {
306 newvalue
^= ((value
>> i
) & 1) << (nrbits
- 1 - i
);
311 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
313 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
314 // up to 64 bytes or 512 bits
315 uint8_t *SwapEndian64(const uint8_t *src
, const size_t len
, const uint8_t blockSize
){
316 static uint8_t buf
[64];
317 memset(buf
, 0x00, 64);
319 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
320 for (size_t i
= 0; i
< blockSize
; i
++){
321 tmp
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
327 // takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64),
328 // returns: the dest array contains the reordered src array.
329 void SwapEndian64ex(const uint8_t *src
, const size_t len
, const uint8_t blockSize
, uint8_t *dest
){
330 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
331 for (size_t i
= 0; i
< blockSize
; i
++){
332 dest
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
337 //assumes little endian
338 char * printBits(size_t const size
, void const * const ptr
)
340 unsigned char *b
= (unsigned char*) ptr
;
342 static char buf
[1024];
346 for (i
=size
-1;i
>=0;i
--)
350 byte
= b
[i
] & (1<<j
);
352 sprintf(tmp
, "%u", (unsigned int)byte
);
359 // -------------------------------------------------------------------------
360 // string parameters lib
361 // -------------------------------------------------------------------------
363 // -------------------------------------------------------------------------
365 // bg, en - symbol numbers in param line of beginning and ending parameter
366 // paramnum - param number (from 0)
367 // -------------------------------------------------------------------------
368 int param_getptr(const char *line
, int *bg
, int *en
, int paramnum
)
371 int len
= strlen(line
);
377 while (line
[*bg
] ==' ' || line
[*bg
]=='\t') (*bg
)++;
382 for (i
= 0; i
< paramnum
; i
++) {
383 while (line
[*bg
]!=' ' && line
[*bg
]!='\t' && line
[*bg
] != '\0') (*bg
)++;
384 while (line
[*bg
]==' ' || line
[*bg
]=='\t') (*bg
)++;
386 if (line
[*bg
] == '\0') return 1;
390 while (line
[*en
] != ' ' && line
[*en
] != '\t' && line
[*en
] != '\0') (*en
)++;
398 int param_getlength(const char *line
, int paramnum
)
402 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0;
407 char param_getchar(const char *line
, int paramnum
) {
408 return param_getchar_indx(line
, 0, paramnum
);
411 char param_getchar_indx(const char *line
, int indx
, int paramnum
) {
414 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0x00;
419 return line
[bg
+ indx
];
422 uint8_t param_get8(const char *line
, int paramnum
)
424 return param_get8ex(line
, paramnum
, 0, 10);
428 * @brief Reads a decimal integer (actually, 0-254, not 255)
431 * @return -1 if error
433 uint8_t param_getdec(const char *line
, int paramnum
, uint8_t *destination
)
435 uint8_t val
= param_get8ex(line
, paramnum
, 255, 10);
436 if( (int8_t) val
== -1) return 1;
437 (*destination
) = val
;
441 * @brief Checks if param is decimal
446 uint8_t param_isdec(const char *line
, int paramnum
)
449 //TODO, check more thorougly
450 if (!param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
451 // return strtoul(&line[bg], NULL, 10) & 0xff;
456 uint8_t param_get8ex(const char *line
, int paramnum
, int deflt
, int base
)
460 if (!param_getptr(line
, &bg
, &en
, paramnum
))
461 return strtoul(&line
[bg
], NULL
, base
) & 0xff;
466 uint32_t param_get32ex(const char *line
, int paramnum
, int deflt
, int base
)
470 if (!param_getptr(line
, &bg
, &en
, paramnum
))
471 return strtoul(&line
[bg
], NULL
, base
);
476 uint64_t param_get64ex(const char *line
, int paramnum
, int deflt
, int base
)
480 if (!param_getptr(line
, &bg
, &en
, paramnum
))
481 return strtoull(&line
[bg
], NULL
, base
);
486 int param_gethex(const char *line
, int paramnum
, uint8_t * data
, int hexcnt
)
493 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
495 if (en
- bg
+ 1 != hexcnt
)
498 for(i
= 0; i
< hexcnt
; i
+= 2) {
499 if (!(isxdigit(line
[bg
+ i
]) && isxdigit(line
[bg
+ i
+ 1])) ) return 1;
501 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
502 data
[i
/ 2] = temp
& 0xff;
507 int param_gethex_ex(const char *line
, int paramnum
, uint8_t * data
, int *hexcnt
)
514 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
516 *hexcnt
= en
- bg
+ 1;
517 if (*hexcnt
% 2) //error if not complete hex bytes
520 for(i
= 0; i
< *hexcnt
; i
+= 2) {
521 if (!(isxdigit(line
[bg
+ i
]) && isxdigit(line
[bg
+ i
+ 1])) ) return 1;
523 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
524 data
[i
/ 2] = temp
& 0xff;
530 int param_gethex_to_eol(const char *line
, int paramnum
, uint8_t * data
, int maxdatalen
, int *datalen
) {
535 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
541 if (line
[indx
] == '\t' || line
[indx
] == ' ') {
546 if (isxdigit(line
[indx
])) {
547 buf
[strlen(buf
) + 1] = 0x00;
548 buf
[strlen(buf
)] = line
[indx
];
550 // if we have symbols other than spaces and hex
554 if (*datalen
>= maxdatalen
) {
555 // if we dont have space in buffer and have symbols to translate
559 if (strlen(buf
) >= 2) {
560 sscanf(buf
, "%x", &temp
);
561 data
[*datalen
] = (uint8_t)(temp
& 0xff);
570 //error when not completed hex bytes
576 int param_getstr(const char *line
, int paramnum
, char * str
, size_t buffersize
)
580 if (param_getptr(line
, &bg
, &en
, paramnum
)) {
584 // Prevent out of bounds errors
585 if (en
- bg
+ 1 >= buffersize
) {
586 printf("out of bounds error: want %d bytes have %zd bytes\n", en
- bg
+ 1 + 1, buffersize
);
590 memcpy(str
, line
+ bg
, en
- bg
+ 1);
591 str
[en
- bg
+ 1] = 0;
597 The following methods comes from Rfidler sourcecode.
598 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
601 // convert hex to sequence of 0/1 bit values
602 // returns number of bits converted
603 int hextobinarray(char *target
, char *source
)
605 int length
, i
, count
= 0;
606 char* start
= source
;
609 length
= strlen(source
);
610 // process 4 bits (1 hex digit) at a time
615 if (x
>= 'a' && x
<= 'f')
617 // convert to numeric value
618 if (x
>= '0' && x
<= '9')
620 else if (x
>= 'A' && x
<= 'F')
623 printf("Discovered unknown character %c %d at idx %d of %s\n", x
, x
, source
- start
, start
);
627 for(i
= 0 ; i
< 4 ; ++i
, ++count
)
628 *(target
++)= (x
>> (3 - i
)) & 1;
634 // convert hex to human readable binary string
635 int hextobinstring(char *target
, char *source
)
639 if(!(length
= hextobinarray(target
, source
)))
641 binarraytobinstring(target
, target
, length
);
645 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
646 // return number of bits converted
647 int binarraytohex(char *target
,char *source
, int length
)
657 for(i
= x
= 0 ; i
< 4 ; ++i
)
658 x
+= ( source
[i
] << (3 - i
));
659 sprintf(target
,"%X", (unsigned int)x
);
667 // convert binary array to human readable binary
668 void binarraytobinstring(char *target
, char *source
, int length
)
672 for(i
= 0 ; i
< length
; ++i
)
673 *(target
++)= *(source
++) + '0';
677 // return parity bit required to match type
678 uint8_t GetParity( uint8_t *bits
, uint8_t type
, int length
)
682 for(x
= 0 ; length
> 0 ; --length
)
683 x
+= bits
[length
- 1];
689 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
690 void wiegand_add_parity(uint8_t *target
, uint8_t *source
, uint8_t length
)
692 *(target
++)= GetParity(source
, EVEN
, length
/ 2);
693 memcpy(target
, source
, length
);
695 *(target
)= GetParity(source
+ length
/ 2, ODD
, length
/ 2);
698 // xor two arrays together for len items. The dst array contains the new xored values.
699 void xor(unsigned char *dst
, unsigned char *src
, size_t len
) {
700 for( ; len
> 0; len
--,dst
++,src
++)
704 int32_t le24toh (uint8_t data
[3]) {
705 return (data
[2] << 16) | (data
[1] << 8) | data
[0];
707 uint32_t le32toh (uint8_t *data
) {
708 return (uint32_t)( (data
[3]<<24) | (data
[2]<<16) | (data
[1]<<8) | data
[0]);
711 // RotateLeft - Ultralight, Desfire, works on byte level
712 // 00-01-02 >> 01-02-00
713 void rol(uint8_t *data
, const size_t len
){
714 uint8_t first
= data
[0];
715 for (size_t i
= 0; i
< len
-1; i
++) {
722 // Replace unprintable characters with a dot in char buffer
723 void clean_ascii(unsigned char *buf
, size_t len
) {
724 for (size_t i
= 0; i
< len
; i
++) {
725 if (!isprint(buf
[i
]))
730 // replace \r \n to \0
731 void strcleanrn(char *buf
, size_t len
) {
732 strcreplace(buf
, len
, '\n', '\0');
733 strcreplace(buf
, len
, '\r', '\0');
736 // replace char in buffer
737 void strcreplace(char *buf
, size_t len
, char from
, char to
) {
738 for (size_t i
= 0; i
< len
; i
++) {
744 char *strmcopy(char *buf
) {
746 if ((str
= (char*) malloc(strlen(buf
) + 1)) != NULL
) {
747 memset(str
, 0, strlen(buf
) + 1);
754 // determine number of logical CPU cores (use for multithreaded functions)
755 extern int num_CPUs(void)
758 #include <sysinfoapi.h>
760 GetSystemInfo(&sysinfo
);
761 return sysinfo
.dwNumberOfProcessors
;
762 #elif defined(__linux__) || defined(__APPLE__)
764 return sysconf(_SC_NPROCESSORS_ONLN
);