Merge pull request #165 from wllm-rbnt/master
[legacy-proxmark3.git] / client / util.c
blobe5cbc4aa11054fcd72a173af99a413d766362b2e
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 //-----------------------------------------------------------------------------
11 #include "util.h"
12 #define MAX_BIN_BREAK_LENGTH (3072+384+1)
14 #ifndef _WIN32
15 #include <termios.h>
16 #include <sys/ioctl.h>
19 int ukbhit(void)
21 int cnt = 0;
22 int error;
23 static struct termios Otty, Ntty;
26 if ( tcgetattr( 0, &Otty) == -1 ) return -1;
27 Ntty = Otty;
29 Ntty.c_iflag = 0; /* input mode */
30 Ntty.c_oflag = 0; /* output mode */
31 Ntty.c_lflag &= ~ICANON; /* raw mode */
32 Ntty.c_cc[VMIN] = CMIN; /* minimum time to wait */
33 Ntty.c_cc[VTIME] = CTIME; /* minimum characters to wait for */
35 if (0 == (error = tcsetattr(0, TCSANOW, &Ntty))) {
36 error += ioctl(0, FIONREAD, &cnt);
37 error += tcsetattr(0, TCSANOW, &Otty);
40 return ( error == 0 ? cnt : -1 );
43 #else
44 #include <conio.h>
45 int ukbhit(void) {
46 return kbhit();
48 #endif
50 // log files functions
51 void AddLogLine(char *file, char *extData, char *c) {
52 FILE *fLog = NULL;
53 char filename[FILE_PATH_SIZE] = {0x00};
54 int len = 0;
56 len = strlen(file);
57 if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;
58 memcpy(filename, file, len);
60 fLog = fopen(filename, "a");
61 if (!fLog) {
62 printf("Could not append log file %s", filename);
63 return;
66 fprintf(fLog, "%s", extData);
67 fprintf(fLog, "%s\n", c);
68 fclose(fLog);
71 void AddLogHex(char *fileName, char *extData, const uint8_t * data, const size_t len){
72 AddLogLine(fileName, extData, sprint_hex(data, len));
75 void AddLogUint64(char *fileName, char *extData, const uint64_t data) {
76 char buf[100] = {0};
77 sprintf(buf, "%x%x", (unsigned int)((data & 0xFFFFFFFF00000000) >> 32), (unsigned int)(data & 0xFFFFFFFF));
78 AddLogLine(fileName, extData, buf);
81 void AddLogCurrentDT(char *fileName) {
82 char buff[20];
83 struct tm *curTime;
85 time_t now = time(0);
86 curTime = gmtime(&now);
88 strftime (buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", curTime);
89 AddLogLine(fileName, "\nanticollision: ", buff);
92 void FillFileNameByUID(char *fileName, uint8_t * uid, char *ext, int byteCount) {
93 char * fnameptr = fileName;
94 memset(fileName, 0x00, 200);
96 for (int j = 0; j < byteCount; j++, fnameptr += 2)
97 sprintf(fnameptr, "%02x", uid[j]);
98 sprintf(fnameptr, "%s", ext);
101 // printing and converting functions
103 void print_hex(const uint8_t * data, const size_t len)
105 size_t i;
107 for (i=0; i < len; i++)
108 printf("%02x ", data[i]);
110 printf("\n");
113 char *sprint_hex(const uint8_t *data, const size_t len) {
115 int maxLen = ( len > 1024/3) ? 1024/3 : len;
116 static char buf[1024];
117 memset(buf, 0x00, 1024);
118 char *tmp = buf;
119 size_t i;
121 for (i=0; i < maxLen; ++i, tmp += 3)
122 sprintf(tmp, "%02x ", data[i]);
124 return buf;
127 char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) {
128 // make sure we don't go beyond our char array memory
129 int max_len;
130 if (breaks==0)
131 max_len = ( len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len;
132 else
133 max_len = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks);
135 static char buf[MAX_BIN_BREAK_LENGTH]; // 3072 + end of line characters if broken at 8 bits
136 //clear memory
137 memset(buf, 0x00, sizeof(buf));
138 char *tmp = buf;
140 size_t in_index = 0;
141 // loop through the out_index to make sure we don't go too far
142 for (size_t out_index=0; out_index < max_len; out_index++) {
143 // set character - (should be binary but verify it isn't more than 1 digit)
144 if (data[in_index]<10)
145 sprintf(tmp++, "%u", data[in_index]);
146 // check if a line break is needed and we have room to print it in our array
147 if ( (breaks > 0) && !((in_index+1) % breaks) && (out_index+1 != max_len) ) {
148 // increment and print line break
149 out_index++;
150 sprintf(tmp++, "%s","\n");
152 in_index++;
155 return buf;
158 char *sprint_bin(const uint8_t *data, const size_t len) {
159 return sprint_bin_break(data, len, 0);
161 void num_to_bytes(uint64_t n, size_t len, uint8_t* dest)
163 while (len--) {
164 dest[len] = (uint8_t) n;
165 n >>= 8;
169 uint64_t bytes_to_num(uint8_t* src, size_t len)
171 uint64_t num = 0;
172 while (len--)
174 num = (num << 8) | (*src);
175 src++;
177 return num;
180 void num_to_bytebits(uint64_t n, size_t len, uint8_t *dest) {
181 while (len--) {
182 dest[len] = n & 1;
183 n >>= 1;
187 // aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp
188 // to
189 // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii
190 // up to 64 bytes or 512 bits
191 uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize){
192 static uint8_t buf[64];
193 memset(buf, 0x00, 64);
194 uint8_t *tmp = buf;
195 for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){
196 for (size_t i = 0; i < blockSize; i++){
197 tmp[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)];
200 return tmp;
203 //assumes little endian
204 char * printBits(size_t const size, void const * const ptr)
206 unsigned char *b = (unsigned char*) ptr;
207 unsigned char byte;
208 static char buf[1024];
209 char * tmp = buf;
210 int i, j;
212 for (i=size-1;i>=0;i--)
214 for (j=7;j>=0;j--)
216 byte = b[i] & (1<<j);
217 byte >>= j;
218 sprintf(tmp, "%u", byte);
219 tmp++;
222 return buf;
225 // -------------------------------------------------------------------------
226 // string parameters lib
227 // -------------------------------------------------------------------------
229 // -------------------------------------------------------------------------
230 // line - param line
231 // bg, en - symbol numbers in param line of beginning an ending parameter
232 // paramnum - param number (from 0)
233 // -------------------------------------------------------------------------
234 int param_getptr(const char *line, int *bg, int *en, int paramnum)
236 int i;
237 int len = strlen(line);
239 *bg = 0;
240 *en = 0;
242 // skip spaces
243 while (line[*bg] ==' ' || line[*bg]=='\t') (*bg)++;
244 if (*bg >= len) {
245 return 1;
248 for (i = 0; i < paramnum; i++) {
249 while (line[*bg]!=' ' && line[*bg]!='\t' && line[*bg] != '\0') (*bg)++;
250 while (line[*bg]==' ' || line[*bg]=='\t') (*bg)++;
252 if (line[*bg] == '\0') return 1;
255 *en = *bg;
256 while (line[*en] != ' ' && line[*en] != '\t' && line[*en] != '\0') (*en)++;
258 (*en)--;
260 return 0;
264 char param_getchar(const char *line, int paramnum)
266 int bg, en;
268 if (param_getptr(line, &bg, &en, paramnum)) return 0x00;
270 return line[bg];
273 uint8_t param_get8(const char *line, int paramnum)
275 return param_get8ex(line, paramnum, 0, 10);
279 * @brief Reads a decimal integer (actually, 0-254, not 255)
280 * @param line
281 * @param paramnum
282 * @return -1 if error
284 uint8_t param_getdec(const char *line, int paramnum, uint8_t *destination)
286 uint8_t val = param_get8ex(line, paramnum, 255, 10);
287 if( (int8_t) val == -1) return 1;
288 (*destination) = val;
289 return 0;
292 * @brief Checks if param is decimal
293 * @param line
294 * @param paramnum
295 * @return
297 uint8_t param_isdec(const char *line, int paramnum)
299 int bg, en;
300 //TODO, check more thorougly
301 if (!param_getptr(line, &bg, &en, paramnum)) return 1;
302 // return strtoul(&line[bg], NULL, 10) & 0xff;
304 return 0;
307 uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base)
309 int bg, en;
311 if (!param_getptr(line, &bg, &en, paramnum))
312 return strtoul(&line[bg], NULL, base) & 0xff;
313 else
314 return deflt;
317 uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base)
319 int bg, en;
321 if (!param_getptr(line, &bg, &en, paramnum))
322 return strtoul(&line[bg], NULL, base);
323 else
324 return deflt;
327 uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base)
329 int bg, en;
331 if (!param_getptr(line, &bg, &en, paramnum))
332 return strtoull(&line[bg], NULL, base);
333 else
334 return deflt;
336 return 0;
339 int param_gethex(const char *line, int paramnum, uint8_t * data, int hexcnt)
341 int bg, en, temp, i;
343 if (hexcnt % 2)
344 return 1;
346 if (param_getptr(line, &bg, &en, paramnum)) return 1;
348 if (en - bg + 1 != hexcnt)
349 return 1;
351 for(i = 0; i < hexcnt; i += 2) {
352 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
354 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
355 data[i / 2] = temp & 0xff;
358 return 0;
360 int param_gethex_ex(const char *line, int paramnum, uint8_t * data, int *hexcnt)
362 int bg, en, temp, i;
364 //if (hexcnt % 2)
365 // return 1;
367 if (param_getptr(line, &bg, &en, paramnum)) return 1;
369 *hexcnt = en - bg + 1;
370 if (*hexcnt % 2) //error if not complete hex bytes
371 return 1;
373 for(i = 0; i < *hexcnt; i += 2) {
374 if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1;
376 sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp);
377 data[i / 2] = temp & 0xff;
380 return 0;
382 int param_getstr(const char *line, int paramnum, char * str)
384 int bg, en;
386 if (param_getptr(line, &bg, &en, paramnum)) return 0;
388 memcpy(str, line + bg, en - bg + 1);
389 str[en - bg + 1] = 0;
391 return en - bg + 1;
395 The following methods comes from Rfidler sourcecode.
396 https://github.com/ApertureLabsLtd/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/
399 // convert hex to sequence of 0/1 bit values
400 // returns number of bits converted
401 int hextobinarray(char *target, char *source)
403 int length, i, count= 0;
404 char x;
406 length = strlen(source);
407 // process 4 bits (1 hex digit) at a time
408 while(length--)
410 x= *(source++);
411 // capitalize
412 if (x >= 'a' && x <= 'f')
413 x -= 32;
414 // convert to numeric value
415 if (x >= '0' && x <= '9')
416 x -= '0';
417 else if (x >= 'A' && x <= 'F')
418 x -= 'A' - 10;
419 else
420 return 0;
421 // output
422 for(i= 0 ; i < 4 ; ++i, ++count)
423 *(target++)= (x >> (3 - i)) & 1;
426 return count;
429 // convert hex to human readable binary string
430 int hextobinstring(char *target, char *source)
432 int length;
434 if(!(length= hextobinarray(target, source)))
435 return 0;
436 binarraytobinstring(target, target, length);
437 return length;
440 // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source)
441 // return number of bits converted
442 int binarraytohex(char *target,char *source, int length)
444 unsigned char i, x;
445 int j = length;
447 if(j % 4)
448 return 0;
450 while(j)
452 for(i= x= 0 ; i < 4 ; ++i)
453 x += ( source[i] << (3 - i));
454 sprintf(target,"%X", x);
455 ++target;
456 source += 4;
457 j -= 4;
459 return length;
462 // convert binary array to human readable binary
463 void binarraytobinstring(char *target, char *source, int length)
465 int i;
467 for(i= 0 ; i < length ; ++i)
468 *(target++)= *(source++) + '0';
469 *target= '\0';
472 // return parity bit required to match type
473 uint8_t GetParity( uint8_t *bits, uint8_t type, int length)
475 int x;
477 for(x= 0 ; length > 0 ; --length)
478 x += bits[length - 1];
479 x %= 2;
481 return x ^ type;
484 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
485 void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length)
487 *(target++)= GetParity(source, EVEN, length / 2);
488 memcpy(target, source, length);
489 target += length;
490 *(target)= GetParity(source + length / 2, ODD, length / 2);
493 void xor(unsigned char *dst, unsigned char *src, size_t len) {
494 for( ; len > 0; len--,dst++,src++)
495 *dst ^= *src;
498 int32_t le24toh (uint8_t data[3]) {
499 return (data[2] << 16) | (data[1] << 8) | data[0];
502 // RotateLeft - Ultralight, Desfire, works on byte level
503 // 00-01-02 >> 01-02-00
504 void rol(uint8_t *data, const size_t len){
505 uint8_t first = data[0];
506 for (size_t i = 0; i < len-1; i++) {
507 data[i] = data[i+1];
509 data[len-1] = first;