]>
cvs.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 // fill buffer from structure [{uint8_t data, size_t length},...]
115 int FillBuffer(uint8_t *data
, size_t maxDataLength
, size_t *dataLength
, ...) {
118 va_start(valist
, dataLength
);
120 uint8_t *vdata
= NULL
;
123 vdata
= va_arg(valist
, uint8_t *);
127 vlength
= va_arg(valist
, size_t);
128 if (*dataLength
+ vlength
> maxDataLength
) {
133 memcpy(&data
[*dataLength
], vdata
, vlength
);
134 *dataLength
+= vlength
;
143 void hex_to_buffer(const uint8_t *buf
, const uint8_t *hex_data
, const size_t hex_len
, const size_t hex_max_len
,
144 const size_t min_str_len
, const size_t spaces_between
, bool uppercase
) {
146 char *tmp
= (char *)buf
;
148 memset(tmp
, 0x00, hex_max_len
);
150 int maxLen
= ( hex_len
> hex_max_len
) ? hex_max_len
: hex_len
;
152 for (i
= 0; i
< maxLen
; ++i
, tmp
+= 2 + spaces_between
) {
153 sprintf(tmp
, (uppercase
) ? "%02X" : "%02x", (unsigned int) hex_data
[i
]);
155 for (int j
= 0; j
< spaces_between
; j
++)
156 sprintf(tmp
+ 2 + j
, " ");
159 i
*= (2 + spaces_between
);
160 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
161 if (minStrLen
> hex_max_len
)
162 minStrLen
= hex_max_len
;
163 for(; i
< minStrLen
; i
++, tmp
+= 1)
169 // printing and converting functions
171 char *sprint_hex(const uint8_t *data
, const size_t len
) {
172 static char buf
[4097] = {0};
174 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, 0, 1, false);
179 char *sprint_hex_inrow_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
180 static char buf
[4097] = {0};
182 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, min_str_len
, 0, false);
187 char *sprint_hex_inrow(const uint8_t *data
, const size_t len
) {
188 return sprint_hex_inrow_ex(data
, len
, 0);
191 char *sprint_bin_break(const uint8_t *data
, const size_t len
, const uint8_t breaks
) {
192 // make sure we don't go beyond our char array memory
195 max_len
= ( len
> MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
;
197 max_len
= ( len
+(len
/breaks
) > MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
+(len
/breaks
);
199 static char buf
[MAX_BIN_BREAK_LENGTH
]; // 3072 + end of line characters if broken at 8 bits
201 memset(buf
, 0x00, sizeof(buf
));
205 // loop through the out_index to make sure we don't go too far
206 for (size_t out_index
=0; out_index
< max_len
; out_index
++) {
207 // set character - (should be binary but verify it isn't more than 1 digit)
208 if (data
[in_index
]<10)
209 sprintf(tmp
++, "%u", (unsigned int) data
[in_index
]);
210 // check if a line break is needed and we have room to print it in our array
211 if ( (breaks
> 0) && !((in_index
+1) % breaks
) && (out_index
+1 < max_len
) ) {
212 // increment and print line break
214 sprintf(tmp
++, "%s","\n");
222 char *sprint_bin(const uint8_t *data
, const size_t len
) {
223 return sprint_bin_break(data
, len
, 0);
226 char *sprint_ascii_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
227 static char buf
[1024];
229 memset(buf
, 0x00, 1024);
230 size_t max_len
= (len
> 1010) ? 1010 : len
;
234 tmp
[i
] = ((c
< 32) || (c
== 127)) ? '.' : c
;
238 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
239 for(; i
< minStrLen
; ++i
)
245 void num_to_bytes(uint64_t n
, size_t len
, uint8_t* dest
)
248 dest
[len
] = (uint8_t) n
;
253 uint64_t bytes_to_num(uint8_t* src
, size_t len
)
258 num
= (num
<< 8) | (*src
);
264 void num_to_bytebits(uint64_t n
, size_t len
, uint8_t *dest
) {
271 //least significant bit first
272 void num_to_bytebitsLSBF(uint64_t n
, size_t len
, uint8_t *dest
) {
273 for(int i
= 0 ; i
< len
; ++i
) {
279 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
280 // And clears the rest of the bits.
281 uint32_t SwapBits(uint32_t value
, int nrbits
) {
282 uint32_t newvalue
= 0;
283 for(int i
= 0; i
< nrbits
; i
++) {
284 newvalue
^= ((value
>> i
) & 1) << (nrbits
- 1 - i
);
289 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
291 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
292 // up to 64 bytes or 512 bits
293 uint8_t *SwapEndian64(const uint8_t *src
, const size_t len
, const uint8_t blockSize
){
294 static uint8_t buf
[64];
295 memset(buf
, 0x00, 64);
297 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
298 for (size_t i
= 0; i
< blockSize
; i
++){
299 tmp
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
305 //assumes little endian
306 char * printBits(size_t const size
, void const * const ptr
)
308 unsigned char *b
= (unsigned char*) ptr
;
310 static char buf
[1024];
314 for (i
=size
-1;i
>=0;i
--)
318 byte
= b
[i
] & (1<<j
);
320 sprintf(tmp
, "%u", (unsigned int)byte
);
327 char * printBitsPar(const uint8_t *b
, size_t len
) {
328 static char buf1
[512] = {0};
329 static char buf2
[512] = {0};
335 memset(buf
, 0x00, 512);
337 for (int i
= 0; i
< len
; i
++) {
338 buf
[i
] = ((b
[i
/ 8] << (i
% 8)) & 0x80) ? '1':'0';
344 // -------------------------------------------------------------------------
345 // string parameters lib
346 // -------------------------------------------------------------------------
348 // -------------------------------------------------------------------------
350 // bg, en - symbol numbers in param line of beginning and ending parameter
351 // paramnum - param number (from 0)
352 // -------------------------------------------------------------------------
353 int param_getptr(const char *line
, int *bg
, int *en
, int paramnum
)
356 int len
= strlen(line
);
362 while (line
[*bg
] ==' ' || line
[*bg
]=='\t') (*bg
)++;
367 for (i
= 0; i
< paramnum
; i
++) {
368 while (line
[*bg
]!=' ' && line
[*bg
]!='\t' && line
[*bg
] != '\0') (*bg
)++;
369 while (line
[*bg
]==' ' || line
[*bg
]=='\t') (*bg
)++;
371 if (line
[*bg
] == '\0') return 1;
375 while (line
[*en
] != ' ' && line
[*en
] != '\t' && line
[*en
] != '\0') (*en
)++;
383 int param_getlength(const char *line
, int paramnum
)
387 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0;
392 char param_getchar(const char *line
, int paramnum
) {
393 return param_getchar_indx(line
, 0, paramnum
);
396 char param_getchar_indx(const char *line
, int indx
, int paramnum
) {
399 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0x00;
404 return line
[bg
+ indx
];
407 uint8_t param_get8(const char *line
, int paramnum
)
409 return param_get8ex(line
, paramnum
, 0, 10);
413 * @brief Reads a decimal integer (actually, 0-254, not 255)
416 * @return -1 if error
418 uint8_t param_getdec(const char *line
, int paramnum
, uint8_t *destination
)
420 uint8_t val
= param_get8ex(line
, paramnum
, 255, 10);
421 if( (int8_t) val
== -1) return 1;
422 (*destination
) = val
;
426 * @brief Checks if param is decimal
431 uint8_t param_isdec(const char *line
, int paramnum
)
434 //TODO, check more thorougly
435 if (!param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
436 // return strtoul(&line[bg], NULL, 10) & 0xff;
441 uint8_t param_get8ex(const char *line
, int paramnum
, int deflt
, int base
)
445 if (!param_getptr(line
, &bg
, &en
, paramnum
))
446 return strtoul(&line
[bg
], NULL
, base
) & 0xff;
451 uint32_t param_get32ex(const char *line
, int paramnum
, int deflt
, int base
)
455 if (!param_getptr(line
, &bg
, &en
, paramnum
))
456 return strtoul(&line
[bg
], NULL
, base
);
461 uint64_t param_get64ex(const char *line
, int paramnum
, int deflt
, int base
)
465 if (!param_getptr(line
, &bg
, &en
, paramnum
))
466 return strtoull(&line
[bg
], NULL
, base
);
471 int param_gethex(const char *line
, int paramnum
, uint8_t * data
, int hexcnt
)
478 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
480 if (en
- bg
+ 1 != hexcnt
)
483 for(i
= 0; i
< hexcnt
; i
+= 2) {
484 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
486 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
487 data
[i
/ 2] = temp
& 0xff;
492 int param_gethex_ex(const char *line
, int paramnum
, uint8_t * data
, int *hexcnt
)
499 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
501 *hexcnt
= en
- bg
+ 1;
502 if (*hexcnt
% 2) //error if not complete hex bytes
505 for(i
= 0; i
< *hexcnt
; i
+= 2) {
506 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
508 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
509 data
[i
/ 2] = temp
& 0xff;
515 int param_gethex_to_eol(const char *line
, int paramnum
, uint8_t * data
, int maxdatalen
, int *datalen
) {
520 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
526 if (line
[indx
] == '\t' || line
[indx
] == ' ') {
531 if (isxdigit((unsigned char)line
[indx
])) {
532 buf
[strlen(buf
) + 1] = 0x00;
533 buf
[strlen(buf
)] = line
[indx
];
535 // if we have symbols other than spaces and hex
539 if (*datalen
>= maxdatalen
) {
540 // if we dont have space in buffer and have symbols to translate
544 if (strlen(buf
) >= 2) {
545 sscanf(buf
, "%x", &temp
);
546 data
[*datalen
] = (uint8_t)(temp
& 0xff);
555 //error when not completed hex bytes
561 int param_getstr(const char *line
, int paramnum
, char * str
, size_t buffersize
)
565 if (param_getptr(line
, &bg
, &en
, paramnum
)) {
569 // Prevent out of bounds errors
570 if (en
- bg
+ 1 >= buffersize
) {
571 printf("out of bounds error: want %d bytes have %zd bytes\n", en
- bg
+ 1 + 1, buffersize
);
575 memcpy(str
, line
+ bg
, en
- bg
+ 1);
576 str
[en
- bg
+ 1] = 0;
582 The following methods comes from Rfidler sourcecode.
583 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
586 // convert hex to sequence of 0/1 bit values
587 // returns number of bits converted
588 int hextobinarray(char *target
, char *source
)
590 int length
, i
, count
= 0;
591 char* start
= source
;
594 length
= strlen(source
);
595 // process 4 bits (1 hex digit) at a time
600 if (x
>= 'a' && x
<= 'f')
602 // convert to numeric value
603 if (x
>= '0' && x
<= '9')
605 else if (x
>= 'A' && x
<= 'F')
608 printf("Discovered unknown character %c %d at idx %tu of %s\n", x
, x
, source
- start
, start
);
612 for(i
= 0 ; i
< 4 ; ++i
, ++count
)
613 *(target
++)= (x
>> (3 - i
)) & 1;
619 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
620 // return number of bits converted
621 int binarraytohex(char *target
,char *source
, int length
)
631 for(i
= x
= 0 ; i
< 4 ; ++i
)
632 x
+= ( source
[i
] << (3 - i
));
633 sprintf(target
,"%X", (unsigned int)x
);
641 // return parity bit required to match type
642 uint8_t GetParity( uint8_t *bits
, uint8_t type
, int length
)
646 for(x
= 0 ; length
> 0 ; --length
)
647 x
+= bits
[length
- 1];
653 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
654 void wiegand_add_parity(uint8_t *target
, uint8_t *source
, uint8_t length
)
656 *(target
++)= GetParity(source
, EVEN
, length
/ 2);
657 memcpy(target
, source
, length
);
659 *(target
)= GetParity(source
+ length
/ 2, ODD
, length
/ 2);
662 // xor two arrays together for len items. The dst array contains the new xored values.
663 void xor(unsigned char *dst
, unsigned char *src
, size_t len
) {
664 for( ; len
> 0; len
--,dst
++,src
++)
668 // RotateLeft - Ultralight, Desfire, works on byte level
669 // 00-01-02 >> 01-02-00
670 void rol(uint8_t *data
, const size_t len
){
671 uint8_t first
= data
[0];
672 for (size_t i
= 0; i
< len
-1; i
++) {
679 // Replace unprintable characters with a dot in char buffer
680 void clean_ascii(unsigned char *buf
, size_t len
) {
681 for (size_t i
= 0; i
< len
; i
++) {
682 if (!isprint(buf
[i
]))
687 // replace \r \n to \0
688 void strcleanrn(char *buf
, size_t len
) {
689 strcreplace(buf
, len
, '\n', '\0');
690 strcreplace(buf
, len
, '\r', '\0');
693 // replace char in buffer
694 void strcreplace(char *buf
, size_t len
, char from
, char to
) {
695 for (size_t i
= 0; i
< len
; i
++) {
701 char *strmcopy(char *buf
) {
703 if ((str
= (char*) malloc(strlen(buf
) + 1)) != NULL
) {
704 memset(str
, 0, strlen(buf
) + 1);
711 // determine number of logical CPU cores (use for multithreaded functions)
712 extern int num_CPUs(void)
715 #include <sysinfoapi.h>
717 GetSystemInfo(&sysinfo
);
718 return sysinfo
.dwNumberOfProcessors
;
719 #elif defined(__linux__) || defined(__APPLE__)
721 return sysconf(_SC_NPROCESSORS_ONLN
);