]> git.sesse.net Git - freerainbowtables/blob - Common/rt api/Public.cpp
UINT4 -> uint32
[freerainbowtables] / Common / rt api / Public.cpp
1 /*
2  * freerainbowtables is a project for generating, distributing, and using
3  * perfect rainbow tables
4  *
5  * Copyright (C) Zhu Shuanglei <shuanglei@hotmail.com>
6  * Copyright Martin Westergaard Jørgensen <martinwj2005@gmail.com>
7  * Copyright 2009, 2010 Daniël Niggebrugge <niggebrugge@fox-it.com>
8  * Copyright 2009, 2010 James Nobis <frt@quelrod.net>
9  *
10  * This file is part of freerainbowtables.
11  *
12  * freerainbowtables is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 2 of the License.
15  *
16  * freerainbowtables is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with freerainbowtables.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #if defined(_WIN32) && !defined(__GNUC__)
26         #pragma warning(disable : 4786)
27 #endif
28
29 #ifdef _WIN32
30         #ifdef BOINC
31                 #include "boinc_win.h"
32         #endif
33 #else
34 //#include "config.h"
35 #include <cstdio>
36 #include <cctype>
37 #include <ctime>
38 #include <cstring>
39 #include <cstdlib>
40 #include <csignal>
41 #include <unistd.h>
42
43 #endif
44 #ifdef BOINC
45         #include "filesys.h"
46         #include "boinc_api.h"
47 #endif
48 #include "Public.h"
49
50 #ifdef _WIN32
51         #include <windows.h>
52 #endif
53
54 #if defined(_WIN32) && !defined(__GNUC__)
55         #include <windows.h>
56         #include <time.h>
57
58         #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
59                 #define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
60         #else
61                 #define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
62         #endif
63  
64         struct timezone
65         {
66                 int  tz_minuteswest; /* minutes W of Greenwich */
67                 int  tz_dsttime;     /* type of dst correction */
68         };
69  
70         int gettimeofday(struct timeval *tv, struct timezone *tz)
71         {
72                 // Define a structure to receive the current Windows filetime
73                 FILETIME ft;
74  
75                 // Initialize the present time to 0 and the timezone to UTC
76                 unsigned __int64 tmpres = 0;
77                 static int tzflag = 0;
78  
79                 if (NULL != tv)
80                 {
81                         GetSystemTimeAsFileTime(&ft);
82  
83                         // The GetSystemTimeAsFileTime returns the number of 100 nanosecond 
84                         // intervals since Jan 1, 1601 in a structure. Copy the high bits to 
85                         // the 64 bit tmpres, shift it left by 32 then or in the low 32 bits.
86                         tmpres |= ft.dwHighDateTime;
87                         tmpres <<= 32;
88                         tmpres |= ft.dwLowDateTime;
89  
90                         // Convert to microseconds by dividing by 10
91                         tmpres /= 10;
92  
93                         // The Unix epoch starts on Jan 1 1970.  Need to subtract the difference 
94                         // in seconds from Jan 1 1601.
95                         tmpres -= DELTA_EPOCH_IN_MICROSECS;
96          
97                         // Finally change microseconds to seconds and place in the seconds value. 
98                         // The modulus picks up the microseconds.
99                         tv->tv_sec = (long)(tmpres / 1000000UL);
100                         tv->tv_usec = (long)(tmpres % 1000000UL);
101                 }
102          
103                 if (NULL != tz)
104                 {
105                         if (!tzflag)
106                         {
107                                 _tzset();
108                                 tzflag++;
109                         }
110           
111                         // Adjust for the timezone west of Greenwich
112                         tz->tz_minuteswest = _timezone / 60;
113                         tz->tz_dsttime = _daylight;
114                 }
115          
116                 return 0;
117         }
118
119 #elif defined(__APPLE__) || \
120         ((defined(__unix__) || defined(unix)) && !defined(USG))
121
122         #include <sys/param.h>
123
124         #if defined(BSD)
125                 #include <sys/sysctl.h>
126         #elif defined(__linux__)
127                 #include <sys/sysinfo.h>
128         #else
129                 #error Unsupported Operating System
130         #endif
131 #endif
132
133 //////////////////////////////////////////////////////////////////////
134
135 timeval sub_timeofday( timeval tv2, timeval tv )
136 {
137         timeval final;
138
139         final.tv_usec = tv2.tv_usec - tv.tv_usec;
140         final.tv_sec = tv2.tv_sec - tv.tv_sec;
141
142         if ( final.tv_usec < 0 )
143         {
144                 final.tv_usec += 1000000;
145                 --final.tv_sec;
146         }
147
148         return final;
149 }
150
151 long GetFileLen(FILE* file)
152 {
153         // XXX on x86/x86_64 linux returns long
154         // 32-bit this is a problem if the file is > (2^31-1) bytes
155         long pos = ftell(file);
156         fseek(file, 0, SEEK_END);
157         long len = ftell(file);
158         fseek(file, pos, SEEK_SET);
159
160         return len;
161 }
162
163 string TrimString(string s)
164 {
165         while (s.size() > 0)
166         {
167                 if (s[0] == ' ' || s[0] == '\t')
168                         s = s.substr(1);
169                 else
170                         break;
171         }
172
173         while (s.size() > 0)
174         {
175                 if (s[s.size() - 1] == ' ' || s[s.size() - 1] == '\t')
176                         s = s.substr(0, s.size() - 1);
177                 else
178                         break;
179         }
180
181         return s;
182 }
183 bool GetHybridCharsets(string sCharset, vector<tCharset>& vCharset)
184 {
185         // Example: hybrid(mixalpha-numeric-all-space#1-6,numeric#1-4)
186         if(sCharset.substr(0, 6) != "hybrid") // Not hybrid charset
187                 return false;
188
189         string::size_type nEnd = sCharset.rfind(')');
190         string::size_type nStart = (int) sCharset.rfind('(');
191         string sChar = sCharset.substr(nStart + 1, nEnd - nStart - 1);
192         vector<string> vParts;
193         SeperateString(sChar, ",", vParts);
194         for(uint32 i = 0; i < vParts.size(); i++)
195         {
196                 tCharset stCharset;
197                 vector<string> vParts2;
198                 SeperateString(vParts[i], "#", vParts2);
199                 stCharset.sName = vParts2[0];
200                 vector<string> vParts3;
201                 SeperateString(vParts2[1], "-", vParts3);
202                 stCharset.nPlainLenMin = atoi(vParts3[0].c_str());
203                 stCharset.nPlainLenMax = atoi(vParts3[1].c_str());
204                 vCharset.push_back(stCharset);
205         }
206         return true;
207 }
208 #ifdef BOINC
209 bool boinc_ReadLinesFromFile(string sPathName, vector<string>& vLine)
210 {
211         vLine.clear();
212         char input_path[512];
213         boinc_resolve_filename(sPathName.c_str(), input_path, sizeof(input_path));
214         FILE *file = boinc_fopen(input_path, "rb");
215         if (!file) {
216                 fprintf(stderr,
217                         "Couldn't find input file, resolved name %s.\n", input_path
218                 );
219                 exit(-1);
220         }
221
222         if (file != NULL)
223         {
224                 unsigned int len = GetFileLen(file);
225                 char* data = new char[len + 1];
226                 fread(data, 1, len, file);
227                 data[len] = '\0';
228                 string content = data;
229                 content += "\n";
230                 delete [] data;
231
232                 unsigned int i;
233                 for (i = 0; i < content.size(); i++)
234                 {
235                         if (content[i] == '\r')
236                                 content[i] = '\n';
237                 }
238
239                 string::size_type n;
240                 while ((n = content.find("\n", 0)) != string::npos)
241                 {
242                         string line = content.substr(0, n);
243                         line = TrimString(line);
244                         if (line != "")
245                                 vLine.push_back(line);
246                         content = content.substr(n + 1);
247                 }
248
249                 fclose(file);
250         }
251         else
252                 return false;
253
254         return true;
255 }
256 #endif
257 bool ReadLinesFromFile(string sPathName, vector<string>& vLine)
258 {
259         vLine.clear();
260
261         FILE* file = fopen(sPathName.c_str(), "rb");
262         if (file != NULL)
263         {
264                 unsigned int len = GetFileLen(file);
265                 char* data = new char[len + 1];
266                 fread(data, 1, len, file);
267                 data[len] = '\0';
268                 string content = data;
269                 content += "\n";
270                 delete [] data;
271
272                 unsigned int i;
273                 for (i = 0; i < content.size(); i++)
274                 {
275                         if (content[i] == '\r')
276                                 content[i] = '\n';
277                 }
278
279                 string::size_type n;
280                 while ((n = content.find("\n", 0)) != string::npos)
281                 {
282                         string line = content.substr(0, n);
283                         line = TrimString(line);
284                         if (line != "")
285                                 vLine.push_back(line);
286                         content = content.substr(n + 1);
287                 }
288
289                 fclose(file);
290         }
291         else
292                 return false;
293
294         return true;
295 }
296
297 bool writeResultLineToFile(string sOutputFile, string sHash, string sPlain, string sBinary)
298 {
299         FILE* file = fopen(sOutputFile.c_str(), "a");
300         if (file!=NULL)
301         {
302                 string buffer = sHash + ":" + sPlain + ":" + sBinary + "\n";
303                 fputs (buffer.c_str(), file);
304                 fclose (file);
305                 return true;
306         }
307         else
308                 return false;
309 }
310
311 bool SeperateString(string s, string sSeperator, vector<string>& vPart)
312 {
313         vPart.clear();
314
315         unsigned int i;
316         for (i = 0; i < sSeperator.size(); i++)
317         {
318                 string::size_type n;
319                 if ( (n = s.find(sSeperator[i])) != string::npos)
320                 {
321                         vPart.push_back(s.substr(0, n));
322                         s = s.substr(n + 1);
323                 }
324                 else
325                 {
326                         printf("not found: %c\n", sSeperator[i]);
327                         printf("s: %s\n", s.c_str());
328                         return false;
329                 }
330         }
331         vPart.push_back(s);
332
333         return true;
334 }
335
336 string uint64tostr(uint64 n)
337 {
338         char str[32];
339
340 #ifdef _WIN32
341         sprintf(str, "%I64u", n);
342 #else
343         sprintf(str, "%llu", n);
344 #endif
345
346         return str;
347 }
348
349 string uint64tohexstr(uint64 n)
350 {
351         char str[32];
352
353 #ifdef _WIN32
354         sprintf(str, "%016I64x", n);
355 #else
356         sprintf(str, "%016llx", n);
357 #endif
358
359         return str;
360 }
361
362 string HexToStr(const unsigned char* pData, int nLen)
363 {
364         string sRet;
365         int i;
366         for (i = 0; i < nLen; i++)
367         {
368                 char szByte[3];
369                 sprintf(szByte, "%02x", pData[i]);
370                 sRet += szByte;
371         }
372
373         return sRet;
374 }
375
376 unsigned long GetAvailPhysMemorySize()
377 {
378 #ifdef _WIN32
379         MEMORYSTATUS ms;
380         GlobalMemoryStatus(&ms);
381         return ms.dwAvailPhys;
382 #elif defined(BSD)
383         int mib[2] = { CTL_HW, HW_PHYSMEM };
384         uint64 physMem;
385         //XXX warning size_t isn't portable
386         size_t len;
387         len = sizeof(physMem);
388         sysctl(mib, 2, &physMem, &len, NULL, 0);
389         return physMem;
390 #elif defined(__linux__)
391         struct sysinfo info;
392         sysinfo(&info);
393         return ( info.freeram + info.bufferram ) * (unsigned long) info.mem_unit;
394 #else
395         return 0;
396         #error Unsupported Operating System
397 #endif
398 }
399
400 string GetApplicationPath()
401 {
402         char fullPath[FILENAME_MAX];
403
404 #ifdef _WIN32
405         GetModuleFileName(NULL, fullPath, FILENAME_MAX);
406 #else
407         char szTmp[32];
408         // XXX linux/proc file system dependent
409         sprintf(szTmp, "/proc/%d/exe", getpid());
410         int bytes = readlink(szTmp, fullPath, FILENAME_MAX);
411
412         if( bytes >= 0 )
413                 fullPath[bytes] = '\0';
414 #endif
415
416         string sApplicationPath = fullPath;
417 #ifdef _WIN32
418         string::size_type nIndex = sApplicationPath.find_last_of('\\');
419 #else
420         string::size_type nIndex = sApplicationPath.find_last_of('/');
421 #endif
422
423         if ( nIndex != string::npos )
424                 sApplicationPath = sApplicationPath.substr(0, nIndex+1);
425
426         return sApplicationPath;
427 }
428
429 void ParseHash(string sHash, unsigned char* pHash, int& nHashLen)
430 {
431         uint32 i;
432         for (i = 0; i < sHash.size() / 2; i++)
433         {
434                 string sSub = sHash.substr(i * 2, 2);
435                 int nValue;
436                 sscanf(sSub.c_str(), "%02x", &nValue);
437                 pHash[i] = (unsigned char)nValue;
438         }
439
440         nHashLen = (int) sHash.size() / 2;
441 }
442
443 void Logo()
444 {
445         printf("RainbowCrack (improved) 2.0 - Making a Faster Cryptanalytic Time-Memory Trade-Off\n");
446         printf("by Martin Westergaard <martinwj2005@gmail.com>\n");
447         printf("http://www.freerainbowtables.com/\n");
448         printf("original code by Zhu Shuanglei <shuanglei@hotmail.com>\n");
449         printf("http://www.antsight.com/zsl/rainbowcrack/\n\n");
450 }
451
452 // XXX nmap is GPL2, will check newer releases regarding license
453 // Code comes from nmap, used for the linux implementation of kbhit()
454 #ifndef _WIN32
455
456 static int tty_fd = 0;
457 struct termios saved_ti;
458
459 int tty_getchar()
460 {
461         int c, numChars;
462
463         if (tty_fd && tcgetpgrp(tty_fd) == getpid()) {
464                 c = 0;
465                 numChars = read(tty_fd, &c, 1);
466                 if (numChars > 0) return c;
467         }
468
469         return -1;
470 }
471
472 void tty_done()
473 {
474         if (!tty_fd) return;
475
476         tcsetattr(tty_fd, TCSANOW, &saved_ti);
477
478         close(tty_fd);
479         tty_fd = 0;
480 }
481
482 void tty_init()
483 {
484         struct termios ti;
485
486         if (tty_fd)
487                 return;
488
489         if ((tty_fd = open("/dev/tty", O_RDONLY | O_NONBLOCK)) < 0) return;
490
491         tcgetattr(tty_fd, &ti);
492         saved_ti = ti;
493         ti.c_lflag &= ~(ICANON | ECHO);
494         ti.c_cc[VMIN] = 1;
495         ti.c_cc[VTIME] = 0;
496         tcsetattr(tty_fd, TCSANOW, &ti);
497
498         atexit(tty_done);
499 }
500
501 void tty_flush(void)
502 {
503         tcflush(tty_fd, TCIFLUSH);
504 }
505 // end nmap code
506 #endif