]>
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
59 struct termios Otty
, Ntty
;
60 if ( tcgetattr(STDIN_FILENO
, &Otty
) == -1 ) return -1;
62 Ntty
.c_lflag
&= ~ICANON
; /* disable buffered i/o */
63 if (0 == (error
= tcsetattr(STDIN_FILENO
, TCSANOW
, &Ntty
))) { // set new attributes
65 error
+= tcsetattr(STDIN_FILENO
, TCSANOW
, &Otty
); // reset attributes
67 return ( error
== 0 ? c
: -1 );
78 // log files functions
79 void AddLogLine(char *file
, char *extData
, char *c
) {
81 char filename
[FILE_PATH_SIZE
] = {0x00};
85 if (len
> FILE_PATH_SIZE
) len
= FILE_PATH_SIZE
;
86 memcpy(filename
, file
, len
);
88 fLog
= fopen(filename
, "a");
90 printf("Could not append log file %s", filename
);
94 fprintf(fLog
, "%s", extData
);
95 fprintf(fLog
, "%s\n", c
);
99 void AddLogHex(char *fileName
, char *extData
, const uint8_t * data
, const size_t len
){
100 AddLogLine(fileName
, extData
, sprint_hex(data
, len
));
103 void AddLogUint64(char *fileName
, char *extData
, const uint64_t data
) {
105 sprintf(buf
, "%x%x", (unsigned int)((data
& 0xFFFFFFFF00000000) >> 32), (unsigned int)(data
& 0xFFFFFFFF));
106 AddLogLine(fileName
, extData
, buf
);
109 void AddLogCurrentDT(char *fileName
) {
113 time_t now
= time(0);
114 curTime
= gmtime(&now
);
116 strftime (buff
, sizeof(buff
), "%Y-%m-%d %H:%M:%S", curTime
);
117 AddLogLine(fileName
, "\nanticollision: ", buff
);
120 void FillFileNameByUID(char *fileName
, uint8_t *uid
, char *ext
, int byteCount
) {
121 char * fnameptr
= fileName
;
123 for (int j
= 0; j
< byteCount
; j
++, fnameptr
+= 2)
124 sprintf(fnameptr
, "%02x", (unsigned int) uid
[j
]);
125 sprintf(fnameptr
, "%s", ext
);
128 // fill buffer from structure [{uint8_t data, size_t length},...]
129 int FillBuffer(uint8_t *data
, size_t maxDataLength
, size_t *dataLength
, ...) {
132 va_start(valist
, dataLength
);
134 uint8_t *vdata
= NULL
;
137 vdata
= va_arg(valist
, uint8_t *);
141 vlength
= va_arg(valist
, size_t);
142 if (*dataLength
+ vlength
> maxDataLength
) {
147 memcpy(&data
[*dataLength
], vdata
, vlength
);
148 *dataLength
+= vlength
;
157 bool CheckStringIsHEXValue(const char *value
) {
158 for (int i
= 0; i
< strlen(value
); i
++)
159 if (!isxdigit(value
[i
]))
162 if (strlen(value
) % 2)
168 void hex_to_buffer(const uint8_t *buf
, const uint8_t *hex_data
, const size_t hex_len
, const size_t hex_max_len
,
169 const size_t min_str_len
, const size_t spaces_between
, bool uppercase
) {
171 char *tmp
= (char *)buf
;
173 int maxLen
= (hex_len
> hex_max_len
) ? hex_max_len
: hex_len
;
175 for (int i
= 0; i
< maxLen
; ++i
, tmp
+= 2 + spaces_between
) {
176 sprintf(tmp
, (uppercase
) ? "%02X" : "%02x", (unsigned int) hex_data
[i
]);
179 for (int j
= 0; j
< spaces_between
; j
++)
180 sprintf(tmp
+ 2 + j
, " ");
183 size_t len
= strlen(tmp
);
184 int minStrLen
= min_str_len
> len
? min_str_len
: 0;
185 if (minStrLen
> hex_max_len
)
186 minStrLen
= hex_max_len
;
187 for (int i
= len
; i
< minStrLen
; i
++, tmp
+= 1)
193 // printing and converting functions
195 char *sprint_hex(const uint8_t *data
, const size_t len
) {
196 static char buf
[4097] = {0};
198 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, 0, 1, false);
203 char *sprint_hex_inrow_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
204 static char buf
[4097] = {0};
206 hex_to_buffer((uint8_t *)buf
, data
, len
, sizeof(buf
) - 1, min_str_len
, 0, false);
211 char *sprint_hex_inrow(const uint8_t *data
, const size_t len
) {
212 return sprint_hex_inrow_ex(data
, len
, 0);
215 char *sprint_bin_break(const uint8_t *data
, const size_t len
, const uint8_t breaks
) {
216 // make sure we don't go beyond our char array memory
219 max_len
= ( len
> MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
;
221 max_len
= ( len
+(len
/breaks
) > MAX_BIN_BREAK_LENGTH
) ? MAX_BIN_BREAK_LENGTH
: len
+(len
/breaks
);
223 static char buf
[MAX_BIN_BREAK_LENGTH
]; // 3072 + end of line characters if broken at 8 bits
225 memset(buf
, 0x00, sizeof(buf
));
229 // loop through the out_index to make sure we don't go too far
230 for (size_t out_index
=0; out_index
< max_len
; out_index
++) {
231 // set character - (should be binary but verify it isn't more than 1 digit)
232 if (data
[in_index
]<10)
233 sprintf(tmp
++, "%u", (unsigned int) data
[in_index
]);
234 // check if a line break is needed and we have room to print it in our array
235 if ( (breaks
> 0) && !((in_index
+1) % breaks
) && (out_index
+1 < max_len
) ) {
236 // increment and print line break
238 sprintf(tmp
++, "%s","\n");
246 char *sprint_bin(const uint8_t *data
, const size_t len
) {
247 return sprint_bin_break(data
, len
, 0);
250 char *sprint_ascii_ex(const uint8_t *data
, const size_t len
, const size_t min_str_len
) {
251 static char buf
[1024];
253 memset(buf
, 0x00, 1024);
254 size_t max_len
= (len
> 1010) ? 1010 : len
;
258 tmp
[i
] = ((c
< 32) || (c
== 127)) ? '.' : c
;
262 int minStrLen
= min_str_len
> i
? min_str_len
: 0;
263 for(; i
< minStrLen
; ++i
)
269 char *sprint_ascii(const uint8_t *data
, const size_t len
) {
270 return sprint_ascii_ex(data
, len
, 0);
273 void num_to_bytes(uint64_t n
, size_t len
, uint8_t* dest
)
276 dest
[len
] = (uint8_t) n
;
281 uint64_t bytes_to_num(uint8_t* src
, size_t len
)
286 num
= (num
<< 8) | (*src
);
292 void num_to_bytebits(uint64_t n
, size_t len
, uint8_t *dest
) {
299 //least significant bit first
300 void num_to_bytebitsLSBF(uint64_t n
, size_t len
, uint8_t *dest
) {
301 for(int i
= 0 ; i
< len
; ++i
) {
307 // Swap bit order on a uint32_t value. Can be limited by nrbits just use say 8bits reversal
308 // And clears the rest of the bits.
309 uint32_t SwapBits(uint32_t value
, int nrbits
) {
310 uint32_t newvalue
= 0;
311 for(int i
= 0; i
< nrbits
; i
++) {
312 newvalue
^= ((value
>> i
) & 1) << (nrbits
- 1 - i
);
317 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
319 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
320 // up to 64 bytes or 512 bits
321 uint8_t *SwapEndian64(const uint8_t *src
, const size_t len
, const uint8_t blockSize
){
322 static uint8_t buf
[64];
323 memset(buf
, 0x00, 64);
324 for (uint8_t block
=0; block
< (uint8_t)(len
/blockSize
); block
++){
325 for (size_t i
= 0; i
< blockSize
; i
++){
326 buf
[i
+(blockSize
*block
)] = src
[(blockSize
-1-i
)+(blockSize
*block
)];
332 //assumes little endian
333 char *printBits(size_t const size
, void const * const ptr
)
335 unsigned char *b
= (unsigned char*) ptr
;
337 static char buf
[1024];
341 for (i
=size
-1;i
>=0;i
--)
345 byte
= b
[i
] & (1<<j
);
347 sprintf(tmp
, "%u", (unsigned int)byte
);
354 char *printBitsPar(const uint8_t *b
, size_t len
) {
355 static char buf1
[512] = {0};
356 static char buf2
[512] = {0};
362 memset(buf
, 0x00, 512);
364 for (int i
= 0; i
< len
; i
++) {
365 buf
[i
] = ((b
[i
/ 8] << (i
% 8)) & 0x80) ? '1':'0';
371 // -------------------------------------------------------------------------
372 // string parameters lib
373 // -------------------------------------------------------------------------
375 // -------------------------------------------------------------------------
377 // bg, en - symbol numbers in param line of beginning and ending parameter
378 // paramnum - param number (from 0)
379 // -------------------------------------------------------------------------
380 int param_getptr(const char *line
, int *bg
, int *en
, int paramnum
)
383 int len
= strlen(line
);
389 while (line
[*bg
] ==' ' || line
[*bg
]=='\t') (*bg
)++;
394 for (i
= 0; i
< paramnum
; i
++) {
395 while (line
[*bg
]!=' ' && line
[*bg
]!='\t' && line
[*bg
] != '\0') (*bg
)++;
396 while (line
[*bg
]==' ' || line
[*bg
]=='\t') (*bg
)++;
398 if (line
[*bg
] == '\0') return 1;
402 while (line
[*en
] != ' ' && line
[*en
] != '\t' && line
[*en
] != '\0') (*en
)++;
410 int param_getlength(const char *line
, int paramnum
)
414 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0;
419 char param_getchar(const char *line
, int paramnum
) {
420 return param_getchar_indx(line
, 0, paramnum
);
423 char param_getchar_indx(const char *line
, int indx
, int paramnum
) {
426 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 0x00;
431 return line
[bg
+ indx
];
434 uint8_t param_get8(const char *line
, int paramnum
)
436 return param_get8ex(line
, paramnum
, 0, 10);
440 * @brief Reads a decimal integer (actually, 0-254, not 255)
443 * @return -1 if error
445 uint8_t param_getdec(const char *line
, int paramnum
, uint8_t *destination
)
447 uint8_t val
= param_get8ex(line
, paramnum
, 255, 10);
448 if( (int8_t) val
== -1) return 1;
449 (*destination
) = val
;
453 * @brief Checks if param is decimal
458 uint8_t param_isdec(const char *line
, int paramnum
)
461 //TODO, check more thorougly
462 if (!param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
463 // return strtoul(&line[bg], NULL, 10) & 0xff;
468 uint8_t param_get8ex(const char *line
, int paramnum
, int deflt
, int base
)
472 if (!param_getptr(line
, &bg
, &en
, paramnum
))
473 return strtoul(&line
[bg
], NULL
, base
) & 0xff;
478 uint32_t param_get32ex(const char *line
, int paramnum
, int deflt
, int base
)
482 if (!param_getptr(line
, &bg
, &en
, paramnum
))
483 return strtoul(&line
[bg
], NULL
, base
);
488 uint64_t param_get64ex(const char *line
, int paramnum
, int deflt
, int base
)
492 if (!param_getptr(line
, &bg
, &en
, paramnum
))
493 return strtoull(&line
[bg
], NULL
, base
);
498 int param_gethex(const char *line
, int paramnum
, uint8_t *data
, int hexcnt
)
505 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
507 if (en
- bg
+ 1 != hexcnt
)
510 for(i
= 0; i
< hexcnt
; i
+= 2) {
511 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
513 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
514 data
[i
/ 2] = temp
& 0xff;
520 int param_gethex_ex(const char *line
, int paramnum
, uint8_t *data
, int *hexcnt
)
527 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
529 if (en
- bg
+ 1 > *hexcnt
) return 1;
531 *hexcnt
= en
- bg
+ 1;
532 if (*hexcnt
% 2) //error if not complete hex bytes
535 for(i
= 0; i
< *hexcnt
; i
+= 2) {
536 if (!(isxdigit((unsigned char)line
[bg
+ i
]) && isxdigit((unsigned char)line
[bg
+ i
+ 1])) ) return 1;
538 sscanf((char[]){line
[bg
+ i
], line
[bg
+ i
+ 1], 0}, "%X", &temp
);
539 data
[i
/ 2] = temp
& 0xff;
545 int param_gethex_to_eol(const char *line
, int paramnum
, uint8_t * data
, int maxdatalen
, int *datalen
) {
550 if (param_getptr(line
, &bg
, &en
, paramnum
)) return 1;
556 if (line
[indx
] == '\t' || line
[indx
] == ' ') {
561 if (isxdigit((unsigned char)line
[indx
])) {
562 buf
[strlen(buf
) + 1] = 0x00;
563 buf
[strlen(buf
)] = line
[indx
];
565 // if we have symbols other than spaces and hex
569 if (*datalen
>= maxdatalen
) {
570 // if we dont have space in buffer and have symbols to translate
574 if (strlen(buf
) >= 2) {
575 sscanf(buf
, "%x", &temp
);
576 data
[*datalen
] = (uint8_t)(temp
& 0xff);
585 //error when not completed hex bytes
591 int param_getstr(const char *line
, int paramnum
, char * str
, size_t buffersize
)
595 if (param_getptr(line
, &bg
, &en
, paramnum
)) {
599 // Prevent out of bounds errors
600 if (en
- bg
+ 1 >= buffersize
) {
601 printf("out of bounds error: want %d bytes have %zd bytes\n", en
- bg
+ 1 + 1, buffersize
);
605 memcpy(str
, line
+ bg
, en
- bg
+ 1);
606 str
[en
- bg
+ 1] = 0;
612 The following methods comes from Rfidler sourcecode.
613 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
616 // convert hex to sequence of 0/1 bit values
617 // returns number of bits converted
618 int hextobinarray(char *target
, char *source
)
620 int length
, i
, count
= 0;
621 char* start
= source
;
624 length
= strlen(source
);
625 // process 4 bits (1 hex digit) at a time
630 if (x
>= 'a' && x
<= 'f')
632 // convert to numeric value
633 if (x
>= '0' && x
<= '9')
635 else if (x
>= 'A' && x
<= 'F')
638 printf("Discovered unknown character %c %d at idx %tu of %s\n", x
, x
, source
- start
, start
);
642 for(i
= 0 ; i
< 4 ; ++i
, ++count
)
643 *(target
++)= (x
>> (3 - i
)) & 1;
649 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
650 // return number of bits converted
651 int binarraytohex(char *target
,char *source
, int length
)
661 for(i
= x
= 0 ; i
< 4 ; ++i
)
662 x
+= ( source
[i
] << (3 - i
));
663 sprintf(target
,"%X", (unsigned int)x
);
671 // return parity bit required to match type
672 uint8_t GetParity( uint8_t *bits
, uint8_t type
, int length
)
676 for(x
= 0 ; length
> 0 ; --length
)
677 x
+= bits
[length
- 1];
683 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
684 void wiegand_add_parity(uint8_t *target
, uint8_t *source
, uint8_t length
)
686 *(target
++)= GetParity(source
, EVEN
, length
/ 2);
687 memcpy(target
, source
, length
);
689 *(target
)= GetParity(source
+ length
/ 2, ODD
, length
/ 2);
692 // xor two arrays together for len items. The dst array contains the new xored values.
693 void xor(unsigned char *dst
, unsigned char *src
, size_t len
) {
694 for( ; len
> 0; len
--,dst
++,src
++)
698 // RotateLeft - Ultralight, Desfire, works on byte level
699 // 00-01-02 >> 01-02-00
700 void rol(uint8_t *data
, const size_t len
){
701 uint8_t first
= data
[0];
702 for (size_t i
= 0; i
< len
-1; i
++) {
709 // Replace unprintable characters with a dot in char buffer
710 void clean_ascii(unsigned char *buf
, size_t len
) {
711 for (size_t i
= 0; i
< len
; i
++) {
712 if (!isprint(buf
[i
]))
717 // replace \r \n to \0
718 void strcleanrn(char *buf
, size_t len
) {
719 strcreplace(buf
, len
, '\n', '\0');
720 strcreplace(buf
, len
, '\r', '\0');
723 // replace char in buffer
724 void strcreplace(char *buf
, size_t len
, char from
, char to
) {
725 for (size_t i
= 0; i
< len
; i
++) {
731 char *strmcopy(char *buf
) {
733 if ((str
= (char*) malloc(strlen(buf
) + 1)) != NULL
) {
734 memset(str
, 0, strlen(buf
) + 1);
741 // determine number of logical CPU cores (use for multithreaded functions)
742 extern int num_CPUs(void)
745 #include <sysinfoapi.h>
747 GetSystemInfo(&sysinfo
);
748 return sysinfo
.dwNumberOfProcessors
;
749 #elif defined(__linux__) || defined(__APPLE__)
751 return sysconf(_SC_NPROCESSORS_ONLN
);