]>
git.zerfleddert.de Git - proxmark3-svn/blob - client/util.c
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
;
119 memset(tmp
, 0x00, hex_max_len
);
121 int maxLen
= ( hex_len
> hex_max_len
) ? hex_max_len
: hex_len
;
123 for (i
= 0; i
< maxLen
; ++i
, tmp
+= 2 + spaces_between
) {
124 sprintf(tmp
, (uppercase
) ? "%02X" : "%02x", (unsigned int) hex_data
[i
]);
126 for (int j
= 0; j
< spaces_between
; j
++)
127 sprintf(tmp
+ 2 + j
, " ");
130 i
*= (2 + spaces_between
);
131 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
132 if (minStrLen
> hex_max_len
)
133 minStrLen
= hex_max_len
;
134 for(; i
< minStrLen
; i
++, tmp
+= 1)
140 // printing and converting functions
142 void print_hex(const uint8_t * data
, const size_t len
)
146 for (i
=0; i
< len
; i
++)
147 printf("%02x ", data
[i
]);
152 void print_hex_break(const uint8_t *data
, const size_t len
, uint8_t breaks
) {
155 printf("[%02d] | ", rownum
);
156 for (int i
= 0; i
< len
; ++i
) {
158 printf("%02X ", data
[i
]);
160 // check if a line break is needed
161 if ( breaks
> 0 && !((i
+1) % breaks
) && (i
+1 < len
) ) {
163 printf("\n[%02d] | ", rownum
);
169 char *sprint_hex(const uint8_t *data
, const size_t len
) {
170 static char buf
[1025] = {0};
172 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, 0, 1, false);
177 char *sprint_hex_inrow_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
178 static char buf
[1025] = {0};
180 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, min_str_len
, 0, false);
185 char *sprint_hex_inrow(const uint8_t *data
, const size_t len
) {
186 return sprint_hex_inrow_ex(data
, len
, 0);
189 char *sprint_bin_break(const uint8_t *data
, const size_t len
, const uint8_t breaks
) {
190 // make sure we don't go beyond our char array memory
193 max_len
= ( len
> MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
;
195 max_len
= ( len
+(len
/breaks
) > MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
+(len
/breaks
);
197 static char buf
[MAX_BIN_BREAK_LENGTH
]; // 3072 + end of line characters if broken at 8 bits
199 memset(buf
, 0x00, sizeof(buf
));
203 // loop through the out_index to make sure we don't go too far
204 for (size_t out_index
=0; out_index
< max_len
; out_index
++) {
205 // set character - (should be binary but verify it isn't more than 1 digit)
206 if (data
[in_index
]<10)
207 sprintf(tmp
++, "%u", (unsigned int) data
[in_index
]);
208 // check if a line break is needed and we have room to print it in our array
209 if ( (breaks
> 0) && !((in_index
+1) % breaks
) && (out_index
+1 < max_len
) ) {
210 // increment and print line break
212 sprintf(tmp
++, "%s","\n");
220 char *sprint_bin(const uint8_t *data
, const size_t len
) {
221 return sprint_bin_break(data
, len
, 0);
224 char *sprint_hex_ascii(const uint8_t *data
, const size_t len
) {
225 static char buf
[1024];
227 memset(buf
, 0x00, 1024);
228 size_t max_len
= (len
> 255) ? 255 : len
;
229 // max 255 bytes * 3 + 2 characters = 767 in buffer
230 sprintf(tmp
, "%s| ", sprint_hex(data
, max_len
) );
233 size_t pos
= (max_len
* 3)+2;
234 // add another 255 characters ascii = 1020 characters of buffer used
237 if ( (c
< 32) || (c
== 127))
239 sprintf(tmp
+pos
+i
, "%c", c
);
245 char *sprint_ascii_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
246 static char buf
[1024];
248 memset(buf
, 0x00, 1024);
249 size_t max_len
= (len
> 1010) ? 1010 : len
;
253 tmp
[i
] = ((c
< 32) || (c
== 127)) ? '.' : c
;
257 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
258 for(; i
< minStrLen
; ++i
)
264 char *sprint_ascii(const uint8_t *data
, const size_t len
) {
265 return sprint_ascii_ex(data
, len
, 0);
268 void num_to_bytes(uint64_t n
, size_t len
, uint8_t* dest
)
271 dest
[len
] = (uint8_t) n
;
276 uint64_t bytes_to_num(uint8_t* src
, size_t len
)
281 num
= (num
<< 8) | (*src
);
287 void num_to_bytebits(uint64_t n
, size_t len
, uint8_t *dest
) {
294 //least significant bit first
295 void num_to_bytebitsLSBF(uint64_t n
, size_t len
, uint8_t *dest
) {
296 for(int i
= 0 ; i
< len
; ++i
) {
302 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
303 // And clears the rest of the bits.
304 uint32_t SwapBits(uint32_t value
, int nrbits
) {
305 uint32_t newvalue
= 0;
306 for(int i
= 0; i
< nrbits
; i
++) {
307 newvalue
^= ((value
>> i
) & 1) << (nrbits
- 1 - i
);
312 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
314 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
315 // up to 64 bytes or 512 bits
316 uint8_t *SwapEndian64(const uint8_t *src
, const size_t len
, const uint8_t blockSize
){
317 static uint8_t buf
[64];
318 memset(buf
, 0x00, 64);
320 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
321 for (size_t i
= 0; i
< blockSize
; i
++){
322 tmp
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
328 // takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64),
329 // returns: the dest array contains the reordered src array.
330 void SwapEndian64ex(const uint8_t *src
, const size_t len
, const uint8_t blockSize
, uint8_t *dest
){
331 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
332 for (size_t i
= 0; i
< blockSize
; i
++){
333 dest
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
338 //assumes little endian
339 char * printBits(size_t const size
, void const * const ptr
)
341 unsigned char *b
= (unsigned char*) ptr
;
343 static char buf
[1024];
347 for (i
=size
-1;i
>=0;i
--)
351 byte
= b
[i
] & (1<<j
);
353 sprintf(tmp
, "%u", (unsigned int)byte
);
360 char * printBitsPar(const uint8_t *b
, size_t len
) {
361 static char buf1
[512] = {0};
362 static char buf2
[512] = {0};
368 memset(buf
, 0x00, 512);
370 for (int i
= 0; i
< len
; i
++) {
371 buf
[i
] = ((b
[i
/ 8] << (i
% 8)) & 0x80) ? '1':'0';
377 // -------------------------------------------------------------------------
378 // string parameters lib
379 // -------------------------------------------------------------------------
381 // -------------------------------------------------------------------------
383 // bg, en - symbol numbers in param line of beginning and ending parameter
384 // paramnum - param number (from 0)
385 // -------------------------------------------------------------------------
386 int param_getptr(const char *line
, int *bg
, int *en
, int paramnum
)
389 int len
= strlen(line
);
395 while (line
[*bg
] ==' ' || line
[*bg
]=='\t') (*bg
)++;
400 for (i
= 0; i
< paramnum
; i
++) {
401 while (line
[*bg
]!=' ' && line
[*bg
]!='\t' && line
[*bg
] != '\0') (*bg
)++;
402 while (line
[*bg
]==' ' || line
[*bg
]=='\t') (*bg
)++;
404 if (line
[*bg
] == '\0') return 1;
408 while (line
[*en
] != ' ' && line
[*en
] != '\t' && line
[*en
] != '\0') (*en
)++;
416 int param_getlength(const char *line
, int paramnum
)
420 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0;
425 char param_getchar(const char *line
, int paramnum
) {
426 return param_getchar_indx(line
, 0, paramnum
);
429 char param_getchar_indx(const char *line
, int indx
, int paramnum
) {
432 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0x00;
437 return line
[bg
+ indx
];
440 uint8_t param_get8(const char *line
, int paramnum
)
442 return param_get8ex(line
, paramnum
, 0, 10);
446 * @brief Reads a decimal integer (actually, 0-254, not 255)
449 * @return -1 if error
451 uint8_t param_getdec(const char *line
, int paramnum
, uint8_t *destination
)
453 uint8_t val
= param_get8ex(line
, paramnum
, 255, 10);
454 if( (int8_t) val
== -1) return 1;
455 (*destination
) = val
;
459 * @brief Checks if param is decimal
464 uint8_t param_isdec(const char *line
, int paramnum
)
467 //TODO, check more thorougly
468 if (!param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
469 // return strtoul(&line[bg], NULL, 10) & 0xff;
474 uint8_t param_get8ex(const char *line
, int paramnum
, int deflt
, int base
)
478 if (!param_getptr(line
, &bg
, &en
, paramnum
))
479 return strtoul(&line
[bg
], NULL
, base
) & 0xff;
484 uint32_t param_get32ex(const char *line
, int paramnum
, int deflt
, int base
)
488 if (!param_getptr(line
, &bg
, &en
, paramnum
))
489 return strtoul(&line
[bg
], NULL
, base
);
494 uint64_t param_get64ex(const char *line
, int paramnum
, int deflt
, int base
)
498 if (!param_getptr(line
, &bg
, &en
, paramnum
))
499 return strtoull(&line
[bg
], NULL
, base
);
504 int param_gethex(const char *line
, int paramnum
, uint8_t * data
, int hexcnt
)
511 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
513 if (en
- bg
+ 1 != hexcnt
)
516 for(i
= 0; i
< hexcnt
; i
+= 2) {
517 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
519 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
520 data
[i
/ 2] = temp
& 0xff;
525 int param_gethex_ex(const char *line
, int paramnum
, uint8_t * data
, int *hexcnt
)
532 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
534 *hexcnt
= en
- bg
+ 1;
535 if (*hexcnt
% 2) //error if not complete hex bytes
538 for(i
= 0; i
< *hexcnt
; i
+= 2) {
539 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
541 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
542 data
[i
/ 2] = temp
& 0xff;
548 int param_gethex_to_eol(const char *line
, int paramnum
, uint8_t * data
, int maxdatalen
, int *datalen
) {
553 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
559 if (line
[indx
] == '\t' || line
[indx
] == ' ') {
564 if (isxdigit((unsigned char)line
[indx
])) {
565 buf
[strlen(buf
) + 1] = 0x00;
566 buf
[strlen(buf
)] = line
[indx
];
568 // if we have symbols other than spaces and hex
572 if (*datalen
>= maxdatalen
) {
573 // if we dont have space in buffer and have symbols to translate
577 if (strlen(buf
) >= 2) {
578 sscanf(buf
, "%x", &temp
);
579 data
[*datalen
] = (uint8_t)(temp
& 0xff);
588 //error when not completed hex bytes
594 int param_getstr(const char *line
, int paramnum
, char * str
, size_t buffersize
)
598 if (param_getptr(line
, &bg
, &en
, paramnum
)) {
602 // Prevent out of bounds errors
603 if (en
- bg
+ 1 >= buffersize
) {
604 printf("out of bounds error: want %d bytes have %zd bytes\n", en
- bg
+ 1 + 1, buffersize
);
608 memcpy(str
, line
+ bg
, en
- bg
+ 1);
609 str
[en
- bg
+ 1] = 0;
615 The following methods comes from Rfidler sourcecode.
616 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
619 // convert hex to sequence of 0/1 bit values
620 // returns number of bits converted
621 int hextobinarray(char *target
, char *source
)
623 int length
, i
, count
= 0;
624 char* start
= source
;
627 length
= strlen(source
);
628 // process 4 bits (1 hex digit) at a time
633 if (x
>= 'a' && x
<= 'f')
635 // convert to numeric value
636 if (x
>= '0' && x
<= '9')
638 else if (x
>= 'A' && x
<= 'F')
641 printf("Discovered unknown character %c %d at idx %tu of %s\n", x
, x
, source
- start
, start
);
645 for(i
= 0 ; i
< 4 ; ++i
, ++count
)
646 *(target
++)= (x
>> (3 - i
)) & 1;
652 // convert hex to human readable binary string
653 int hextobinstring(char *target
, char *source
)
657 if(!(length
= hextobinarray(target
, source
)))
659 binarraytobinstring(target
, target
, length
);
663 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
664 // return number of bits converted
665 int binarraytohex(char *target
,char *source
, int length
)
675 for(i
= x
= 0 ; i
< 4 ; ++i
)
676 x
+= ( source
[i
] << (3 - i
));
677 sprintf(target
,"%X", (unsigned int)x
);
685 // convert binary array to human readable binary
686 void binarraytobinstring(char *target
, char *source
, int length
)
690 for(i
= 0 ; i
< length
; ++i
)
691 *(target
++)= *(source
++) + '0';
695 // return parity bit required to match type
696 uint8_t GetParity( uint8_t *bits
, uint8_t type
, int length
)
700 for(x
= 0 ; length
> 0 ; --length
)
701 x
+= bits
[length
- 1];
707 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
708 void wiegand_add_parity(uint8_t *target
, uint8_t *source
, uint8_t length
)
710 *(target
++)= GetParity(source
, EVEN
, length
/ 2);
711 memcpy(target
, source
, length
);
713 *(target
)= GetParity(source
+ length
/ 2, ODD
, length
/ 2);
716 // xor two arrays together for len items. The dst array contains the new xored values.
717 void xor(unsigned char *dst
, unsigned char *src
, size_t len
) {
718 for( ; len
> 0; len
--,dst
++,src
++)
722 int32_t le24toh (uint8_t data
[3]) {
723 return (data
[2] << 16) | (data
[1] << 8) | data
[0];
725 uint32_t le32toh (uint8_t *data
) {
726 return (uint32_t)( (data
[3]<<24) | (data
[2]<<16) | (data
[1]<<8) | data
[0]);
729 // RotateLeft - Ultralight, Desfire, works on byte level
730 // 00-01-02 >> 01-02-00
731 void rol(uint8_t *data
, const size_t len
){
732 uint8_t first
= data
[0];
733 for (size_t i
= 0; i
< len
-1; i
++) {
740 // Replace unprintable characters with a dot in char buffer
741 void clean_ascii(unsigned char *buf
, size_t len
) {
742 for (size_t i
= 0; i
< len
; i
++) {
743 if (!isprint(buf
[i
]))
748 // replace \r \n to \0
749 void strcleanrn(char *buf
, size_t len
) {
750 strcreplace(buf
, len
, '\n', '\0');
751 strcreplace(buf
, len
, '\r', '\0');
754 // replace char in buffer
755 void strcreplace(char *buf
, size_t len
, char from
, char to
) {
756 for (size_t i
= 0; i
< len
; i
++) {
762 char *strmcopy(char *buf
) {
764 if ((str
= (char*) malloc(strlen(buf
) + 1)) != NULL
) {
765 memset(str
, 0, strlen(buf
) + 1);
772 // determine number of logical CPU cores (use for multithreaded functions)
773 extern int num_CPUs(void)
776 #include <sysinfoapi.h>
778 GetSystemInfo(&sysinfo
);
779 return sysinfo
.dwNumberOfProcessors
;
780 #elif defined(__linux__) || defined(__APPLE__)
782 return sysconf(_SC_NPROCESSORS_ONLN
);