// util.cpp
#include "common.h"
// internal typedefs
typedef struct wsaerror_s
{
int number;
const wchar_t *description;
} wsaerror_t;
const wchar_t *GetDirectoryPath (const wchar_t *pathname, wchar_t *path)
{
// this function builds a directory path out of a full file pathname
int char_index;
int length;
length = (int) wcslen (pathname); // get length of pathname first
if (length > MAX_PATH - 1)
length = MAX_PATH - 1; // bound it to MAX_PATH characters max
for (char_index = 0; char_index < length; char_index++)
{
path[char_index] = pathname[char_index]; // now copy pathname in the destination string
if (pathname[char_index] == 0)
break; // don't copy beyond the end of source
}
path[length] = 0; // terminate the string
// now scan the destination string starting from the end until a field separator is found
while ((length > 0) && !((path[length] == '\\') || (path[length] == '/')) && (path[length] != ':'))
length--; // go back one character after the other as long as it's not the case
// given the type of field separator we stopped on, keep it or not
if (path[length] == ':')
length++; // if it's a disk letter separator, keep it
path[length] = 0; // terminate the string at this position
return (path); // and return a pointer to it
}
void CreateOrUpdateApplicationMenu (void)
{
// this function creates or re-creates the main application menu and its accelerator table
HMENU hDropDownMenu;
ACCEL accelerators[] =
{
{FVIRTKEY | FCONTROL, L'O', MENUID_GAME_LOAD},
{FVIRTKEY | FCONTROL, L'S', MENUID_GAME_SAVE},
{FVIRTKEY, VK_PAUSE, MENUID_GAME_PAUSE},
{FVIRTKEY | FCONTROL, L'Z', MENUID_MOVE_CANCELLASTMOVE},
{FVIRTKEY, VK_HOME, MENUID_CHESSBOARD_BEGINNINGOFGAME},
{FVIRTKEY, VK_LEFT, MENUID_CHESSBOARD_PREVIOUSMOVE},
{FVIRTKEY, VK_RIGHT, MENUID_CHESSBOARD_NEXTMOVE},
{FVIRTKEY, VK_END, MENUID_CHESSBOARD_CURRENTSTATEOFGAME},
{FVIRTKEY | FCONTROL, L'G', MENUID_MOVE_GOTOMOVE},
{FVIRTKEY, VK_F1, MENUID_HELP_HELP},
{FVIRTKEY, VK_F2, MENUID_GAME_NEWGAME},
{FVIRTKEY, VK_F3, MENUID_GAME_STATISTICS},
{FVIRTKEY, VK_F4, MENUID_GAME_OPTIONS},
{FVIRTKEY, VK_F5, MENUID_CHESSBOARD_TOPVIEW},
{FVIRTKEY, VK_F6, MENUID_CHESSBOARD_DEFAULTVIEW},
{FVIRTKEY, VK_F7, MENUID_CHESSBOARD_RESETVIEW},
{FVIRTKEY, VK_UP, MENUID_CHESSBOARD_ZOOMIN},
{FVIRTKEY, VK_DOWN, MENUID_CHESSBOARD_ZOOMOUT},
{FVIRTKEY | FCONTROL, VK_DOWN, MENUID_CHESSBOARD_DISPLAYWINDOWSDESKTOP},
{FVIRTKEY, VK_F8, MENUID_CHESSBOARD_CHANGEAPPEARANCE},
{FVIRTKEY, VK_F9, MENUID_INTERNET_SHOWONLINEPLAYERS},
{FVIRTKEY, VK_F10, MENUID_INTERNET_SHOWSOUGHTGAMES},
};
// if needed, destroy the accelerators table and the application menu object
if (hMainAccelerators)
DestroyAcceleratorTable (hMainAccelerators);
hMainAccelerators = NULL;
if (IsMenu (hMainMenu))
DestroyMenu (hMainMenu);
hMainMenu = NULL;
// now create the menu again
hMainMenu = CreateMenu ();
hDropDownMenu = CreateMenu (); // create the first drop-down item
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_NEWGAME, LOCALIZE (L"Menu_GameNewGame"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_SETUPPOSITION, LOCALIZE (L"Menu_GameSetupPosition"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_LOAD, LOCALIZE (L"Menu_GameLoadGame"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_SAVE, LOCALIZE (L"Menu_GameSaveGame"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_SAVEAS, LOCALIZE (L"Menu_GameSaveGameAs"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_SAVEPOSITIONAS, LOCALIZE (L"Menu_GameSavePositionAs"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_PAUSE, LOCALIZE (L"Menu_GamePause"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_RESIGN, LOCALIZE (L"Menu_GameResign"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING | MF_GRAYED, MENUID_GAME_STATISTICS, LOCALIZE (L"Menu_GameStatistics")); // TODO
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_OPTIONS, LOCALIZE (L"Menu_GameOptions"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_GAME_QUIT, LOCALIZE (L"Menu_GameQuit"));
AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Game"));
DestroyMenu (hDropDownMenu);
hDropDownMenu = CreateMenu (); // create the second drop-down item
AppendMenu (hDropDownMenu, MF_STRING, MENUID_MOVE_CANCELLASTMOVE, LOCALIZE (L"Menu_MoveCancelLastMove"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_MOVE_SUGGESTMOVE, LOCALIZE (L"Menu_MoveSuggestMove"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_MOVE_COMMENTMOVE, LOCALIZE (L"Menu_MoveCommentMove"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_MOVE_GOTOMOVE, LOCALIZE (L"Menu_MoveGoToMove"));
AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Move"));
DestroyMenu (hDropDownMenu);
hDropDownMenu = CreateMenu (); // create the third drop-down item
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_RENAMESIDES, LOCALIZE (L"Menu_ChessboardRenameSides"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_SWAPSIDES, LOCALIZE (L"Menu_ChessboardSwapSides"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_TOPVIEW, LOCALIZE (L"Menu_ChessboardTopView"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_DEFAULTVIEW, LOCALIZE (L"Menu_ChessboardDefaultView"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_RESETVIEW, LOCALIZE (L"Menu_ChessboardResetView"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_CHANGEAPPEARANCE, LOCALIZE (L"Menu_ChessboardChangeAppearance"));
if (options.want_fullscreen)
{
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_CHESSBOARD_DISPLAYWINDOWSDESKTOP, LOCALIZE (L"Menu_ChessboardDisplayWindowsDesktop"));
}
AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Chessboard"));
DestroyMenu (hDropDownMenu);
hDropDownMenu = CreateMenu (); // create the fourth drop-down item
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_SHOWONLINEPLAYERS, LOCALIZE (L"Menu_InternetShowOnlinePlayers"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_SHOWSOUGHTGAMES, LOCALIZE (L"Menu_InternetShowSoughtGames"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_SEEKGAME, LOCALIZE (L"Menu_InternetSeekGame"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_CHATTERCHANNELS, LOCALIZE (L"Menu_InternetChatterChannels"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_ENTERCHATTEXT, LOCALIZE (L"Menu_InternetEnterChatText"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_DISPLAYPLAYERCARD, LOCALIZE (L"Menu_InternetDisplayPlayerCard"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_DISPLAYYOURCARD, LOCALIZE (L"Menu_InternetDisplayYourCard"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_INTERNET_MOTD, LOCALIZE (L"Menu_InternetDisplayMOTD"));
AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Internet"));
DestroyMenu (hDropDownMenu);
hDropDownMenu = CreateMenu (); // create the fifth drop-down item
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_HELP, LOCALIZE (L"Menu_HelpDisplayHelp"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_GETCHESSGAMES, LOCALIZE (L"Menu_HelpGetChessGames"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYVISUALTHEMES, LOCALIZE (L"Menu_HelpAddModifyThemes"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYENGINES, LOCALIZE (L"Menu_HelpAddModifyEngines"));
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ADDMODIFYTRANSLATIONS, LOCALIZE (L"Menu_HelpAddModifyTranslations"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_REPORTAPROBLEM, LOCALIZE (L"Menu_HelpReportAProblem"));
AppendMenu (hDropDownMenu, MF_SEPARATOR, 0, NULL);
AppendMenu (hDropDownMenu, MF_STRING, MENUID_HELP_ABOUT, LOCALIZE (L"Menu_HelpAbout"));
AppendMenu (hMainMenu, MF_POPUP, (UINT) hDropDownMenu, LOCALIZE (L"Menu_Help"));
DestroyMenu (hDropDownMenu);
// finally, set this menu to be the app's menu
SetMenu (hMainWnd, hMainMenu);
// (re-)create the accelerators
hMainAccelerators = CreateAcceleratorTable (accelerators, sizeof (accelerators) / sizeof (ACCEL));
return; // finished, application menu is (re)created
}
void CenterWindow (HWND hWnd, HWND hParentWnd)
{
// this function centers the specified window on the specified parent.
RECT rRect;
RECT rParentRect;
int width;
int height;
int parent_width;
int parent_height;
int x;
int y;
// get the current rectangle of the current window
GetWindowRect (hWnd, &rRect);
width = rRect.right - rRect.left;
height = rRect.bottom - rRect.top;
// does this window have a parent AND it is NOT the desktop ?
if (IsWindow (hParentWnd) && (hParentWnd != GetDesktopWindow ()))
{
// get the rectangle of the parent window
GetWindowRect (hParentWnd, &rParentRect);
parent_width = rParentRect.right - rParentRect.left;
parent_height = rParentRect.bottom - rParentRect.top;
// now compute the new X and Y positions so as to have the window centered in its parent
x = rParentRect.left + parent_width / 2 - width / 2;
y = rParentRect.top + parent_height / 2 - height / 2;
}
else
{
// else draw window in the center of the screen
x = GetSystemMetrics (SM_CXSCREEN) / 2 - width / 2;
y = GetSystemMetrics (SM_CYSCREEN) / 2 - height / 2;
}
// now ask to change the position of the window
SetWindowPos (hWnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
return; // finished
}
void HintWindow (HWND hWnd)
{
// this function makes a window blink to the foreground for one second, playing a "ding" sound
FLASHWINFO fw;
Audio_PlaySoundAtCenter (SOUNDTYPE_HINTWINDOW); // play a beep at the center of the board
SetForegroundWindow (hWnd); // modal dialog windows have priority over all others
fw.cbSize = sizeof (fw);
fw.hwnd = hWnd;
fw.dwFlags = FLASHW_CAPTION;
fw.dwTimeout = 50;
fw.uCount = 3;
FlashWindowEx (&fw); // flash it so the user notices it
return; // finished
}
float ProcessTime (void)
{
// this function returns the time in seconds elapsed since the executable process started.
// The rollover check ensures the program will continue running after clock() will have
// overflown its integer value (it does so every 24 days or so). With this rollover check
// we have a lifetime of more than billion years, w00t!
// thanks to botmeister for the rollover check idea.
static long prev_clock = 0;
static long rollover_count = 0;
long current_clock;
double time_in_seconds;
current_clock = clock (); // get system clock
// has the clock overflown ?
if (current_clock < prev_clock)
rollover_count++; // omg, it has, we're running for more than 24 days!
// now convert the time to seconds since last rollover
time_in_seconds = (double) current_clock / CLOCKS_PER_SEC; // convert clock to seconds
prev_clock = current_clock; // keep track of current time for future calls of this function
// and return the time in seconds, adding the overflow differences if necessary.
// HACK: grant the timer to start at 60 seconds to ensure all timer checks work well
return ((float) (60.0f + time_in_seconds + (((double) LONG_MAX + 1.0) / CLOCKS_PER_SEC) * rollover_count));
}
float WrapAngle (float angle)
{
// this function adds or substracts 360 enough times needed to angle to clamp it into the
// [-180, 180[ bounds.
if (angle < -180.0f)
angle += 360.0f * abs (((int) angle - 180) / 360);
else if (angle >= 180)
angle -= 360.0f * abs (((int) angle + 180) / 360);
if (angle == 180.0f)
angle = -180.0f; // needs 2nd pass to check for floating-point rounding errors
return (angle); // finished
}
bool SafeTerminateProcess (HANDLE hProcess, unsigned int uExitCode)
{
// taken from Dr. Dobbs : how to terminate any process cleanly. Simple : Create a remote
// thread in it, and make its start address point right into kernel32's ExitProcess()
// function. This of course assumes that remote code injection is possible.
unsigned long dwTID;
unsigned long dwCode;
unsigned long dwErr = 0;
HMODULE hModule;
HANDLE hProcessDup;
HANDLE hRT;
bool bSuccess = false;
bool bDup;
bDup = (DuplicateHandle (GetCurrentProcess (), hProcess, GetCurrentProcess (), &hProcessDup, PROCESS_ALL_ACCESS, FALSE, 0) != 0);
// detect the special case where the process is already dead
if (GetExitCodeProcess (bDup ? hProcessDup : hProcess, &dwCode) && (dwCode == STILL_ACTIVE))
{
hModule = GetModuleHandle (L"Kernel32");
if (hModule)
{
hRT = CreateRemoteThread (bDup ? hProcessDup : hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) GetProcAddress (hModule, "ExitProcess"),
(void *) uExitCode, 0, &dwTID);
if (hRT != NULL)
{
// must wait process to terminate to guarantee that it has exited
WaitForSingleObject (bDup ? hProcessDup : hProcess, INFINITE);
CloseHandle (hRT);
bSuccess = true;
}
else
dwErr = GetLastError ();
}
else
dwErr = GetLastError ();
}
else
dwErr = ERROR_PROCESS_ABORTED;
if (bDup)
CloseHandle (hProcessDup);
if (!bSuccess)
SetLastError (dwErr);
return (bSuccess);
}
wchar_t *ReachBeginningOfCurrentLine (wchar_t *string, wchar_t *current_pos)
{
// this function parses string backwards from current_pos until it finds either a line feed,
// or the beginning of string, and returns the first character of the line.
while ((current_pos > string) && (*current_pos != L'\n'))
current_pos--; // find the previous line feed
if (*current_pos == L'\n')
current_pos++; // if we've found one, skip it
return (current_pos); // and return where we are
}
wchar_t *ReachBeginningOfNextLine (wchar_t *string, wchar_t *current_pos)
{
// this function parses string forward from current_pos until it finds either a line feed,
// or the end of string, and returns the first character of the line (or NULL).
current_pos = wcschr (current_pos, L'\n'); // find the next line feed
if (current_pos != NULL)
current_pos++; // if we've found one, skip it
if (*current_pos == 0)
current_pos = NULL; // if it's the end of the string, don't return anything
return (current_pos); // and return what we've found
}
wchar_t *ReadACompleteLine (wchar_t *destination_line, int max_length, wchar_t *source_buffer)
{
// copy a line from a given string, ONLY if it ends with a carriage return.
// use it like:
// while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
wchar_t *pointer;
int char_index;
int source_length;
if (source_buffer[0] == 0)
{
destination_line[0] = 0;
return (NULL); // if EOS return a NULL pointer
}
pointer = wcschr (source_buffer, L'\n'); // get to the first carriage return we can find
// found none ?
if (pointer == NULL)
{
destination_line[0] = 0;
return (NULL); // if none return a NULL pointer
}
// get the number of remaining characters in source string
source_length = wcslen (source_buffer);
// as long as we haven't filled the destination string...
for (char_index = 0; char_index < max_length; char_index++)
{
destination_line[char_index] = source_buffer[char_index]; // copy the line we found
if ((char_index + 1 == source_length) || (source_buffer[char_index] == '\n'))
break; // don't copy beyond the end of source string, nor beyond the end of line
}
if (char_index < max_length)
destination_line[char_index] = 0; // terminate string ourselves
else
destination_line[max_length - 1] = 0;
return (&pointer[1]); // and return next line's source buffer pointer
}
wchar_t *wcsgets (wchar_t *destination_line, int max_length, wchar_t *source_buffer)
{
// copy a line from a given string. Kinda like fgets() when you're reading from a string.
// use it like:
// while (blah = sgets (dest, sizeof (dest), blah)) != NULL)
wchar_t *pointer;
int char_index;
int source_length;
if (source_buffer[0] == 0)
{
destination_line[0] = 0;
return (NULL); // if EOS return a NULL pointer
}
pointer = wcschr (source_buffer, L'\n'); // get to the first carriage return we can find
// found none ?
if (pointer == NULL)
{
// if so, copy the line we found
for (char_index = 0; char_index < max_length; char_index++)
{
destination_line[char_index] = source_buffer[char_index]; // copy the line we found
if (source_buffer[char_index] == 0)
break; // don't copy beyond the end of source
}
if (char_index == max_length)
destination_line[max_length - 1] = 0; // ensure string is terminated
return (&source_buffer[wcslen (source_buffer)]); // and return a pointer to the end of the string
}
else
pointer++; // else if a carriage return was found, skip it
// get the number of remaining characters in source string
source_length = wcslen (source_buffer);
// as long as we haven't filled the destination string...
for (char_index = 0; char_index < max_length; char_index++)
{
destination_line[char_index] = source_buffer[char_index]; // copy the line we found
if ((char_index + 1 == source_length) || (source_buffer[char_index] == '\n'))
break; // don't copy beyond the end of source string, nor beyond the end of line
}
if (char_index < max_length)
destination_line[char_index] = 0; // terminate string ourselves
else
destination_line[max_length - 1] = 0;
return (pointer); // and return next line's source buffer pointer
}
wchar_t *wcsistr (const wchar_t *haystack, const wchar_t *needle)
{
// windows has no wcsistr() implementation, so here is mine.
const wchar_t *ptr_upper;
const wchar_t *ptr_lower;
const wchar_t *ptr_either;
size_t needle_length;
needle_length = wcslen (needle); // get needle length
ptr_either = haystack; // start searching at the beginning of haystack
for (;;) // endless loop
{
ptr_upper = wcschr (haystack, towupper (*needle)); // find occurence of first character (uppercase)
ptr_lower = wcschr (haystack, towlower (*needle)); // find occurence of first character (lowercase)
if ((ptr_upper == NULL) && (ptr_lower == NULL))
break; // if no occurence in either case, then haystack doesn't contain needle
else if (ptr_upper == NULL)
ptr_either = ptr_lower; // no uppercase, check in lowercase
else if (ptr_lower == NULL)
ptr_either = ptr_upper; // no lowercase, check in uppercase
else if (ptr_lower < ptr_upper)
ptr_either = ptr_lower; // both occurences found, take the first one
else
ptr_either = ptr_upper; // both occurences found, take the first one
if (_wcsnicmp (ptr_either, needle, needle_length) == 0) // now compare needle case insensitively at that position in haystack
return ((wchar_t *) ptr_either); // if we find something, return its position
haystack = ptr_either + 1; // else advance in haystack
}
return (NULL); // haystack doesn't contain needle
}
void ConvertCRLFsToSingleSpaces (wchar_t *multiline_string)
{
// this function modifies multiline_string by removing CRs and turning LFs into single spaces
int length;
int char_index;
int char_index2;
length = wcslen (multiline_string); // get input string length
// for each character in string that is NOT a carriage return...
char_index2 = 0;
for (char_index = 0; char_index < length; char_index++)
if (multiline_string[char_index] != L'\r')
{
if (multiline_string[char_index] == L'\n')
multiline_string[char_index2] = L' '; // convert newlines to spaces
else
multiline_string[char_index2] = multiline_string[char_index]; // else overwrite string with itself
char_index2++; // we've written one character more
}
multiline_string[char_index2] = 0; // finish string
return; // finished, string is now single-line
}
size_t ConvertTo7BitASCII (char *dest, size_t dest_size_in_bytes, wchar_t *source)
{
// helper function to quickly convert a wide char string to 7-bit ASCII
// do the conversion. Use WideCharToMultiByte() preferentially because wcstombs()
// stops at the first non-convertible character, whereas the former doesn't.
return (WideCharToMultiByte (20127, 0, source, -1, dest, dest_size_in_bytes, NULL, NULL) - 1); // 20127 is 7-bit US-ASCII code page, -1 to null-terminate output string
}
size_t ConvertToWideChar (wchar_t *dest, size_t dest_size_in_wchars, char *source)
{
// helper function to quickly convert an ASCII string to wide char
size_t converted_count;
// do the conversion (WARNING: EXTREMELY COSTY FUNCTION!)
mbstowcs_s (&converted_count, dest, dest_size_in_wchars, source, _TRUNCATE);
return (converted_count);
}
void MinutesToWideCharString (wchar_t *dest, size_t dest_size_in_wchars, int minutes)
{
// helper function to convert a time in minutes in a string mentioning days, hours and minutes
int days;
int hours;
days = minutes / (60 * 24); // count the number of days
minutes -= days * (60 * 24); // substract the result
hours = minutes / 60; // count the number of hours
minutes -= hours * 60; // substract the result
// now choose the right display format
if (days > 0)
swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s", days, LOCALIZE (L"Days"), hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"));
else if (hours > 0)
swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s", hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"));
else
swprintf_s (dest, dest_size_in_wchars, L"%d %s", minutes, LOCALIZE (L"Minutes"));
return; // finished
}
void SecondsToWideCharString (wchar_t *dest, size_t dest_size_in_wchars, int seconds)
{
// helper function to convert a time in seconds in a string mentioning days, hours, minutes and seconds
int days;
int hours;
int minutes;
days = seconds / (60 * 60 * 24); // count the number of days
seconds -= days * (60 * 60 * 24); // substract the result
hours = seconds / (60 * 60); // count the number of hours
seconds -= hours * (60 * 60); // substract the result
minutes = seconds / 60; // count the number of minutes
seconds -= minutes * 60; // substract the result
// now choose the right display format
if (days > 0)
swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s %d %s", days, LOCALIZE (L"Days"), hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
else if (hours > 0)
swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s %d %s", hours, LOCALIZE (L"Hours"), minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
else if (minutes > 0)
swprintf_s (dest, dest_size_in_wchars, L"%d %s %d %s", minutes, LOCALIZE (L"Minutes"), seconds, LOCALIZE (L"Seconds"));
else
swprintf_s (dest, dest_size_in_wchars, L"%d %s", seconds, LOCALIZE (L"Seconds"));
return; // finished
}
int MonthStringToNumber (wchar_t *month_string)
{
// helper function to convert a month string to its equivalent number
if (_wcsnicmp (month_string, L"jan", 3) == 0) return (1); // january
else if (_wcsnicmp (month_string, L"feb", 3) == 0) return (2); // february
else if (_wcsnicmp (month_string, L"mar", 3) == 0) return (3); // march
else if (_wcsnicmp (month_string, L"apr", 3) == 0) return (4); // april
else if (_wcsnicmp (month_string, L"may", 3) == 0) return (5); // may
else if (_wcsnicmp (month_string, L"jun", 3) == 0) return (6); // june
else if (_wcsnicmp (month_string, L"jul", 3) == 0) return (7); // july
else if (_wcsnicmp (month_string, L"aug", 3) == 0) return (8); // august
else if (_wcsnicmp (month_string, L"sep", 3) == 0) return (9); // september
else if (_wcsnicmp (month_string, L"oct", 3) == 0) return (10); // october
else if (_wcsnicmp (month_string, L"nov", 3) == 0) return (11); // november
else if (_wcsnicmp (month_string, L"dec", 3) == 0) return (12); // december
return (0); // month not found or not a month
}
bool GetImageSize (const wchar_t *imagefile_pathname, int *width, int *height)
{
// routine to get the size of a DDS/JPG/PNG/TGA/BMP image. JPEG code courtesy of wischik.com.
wchar_t valid_pathname[MAX_PATH];
unsigned char buffer[26];
FILE *fp;
int length;
int pos;
length = wcslen (imagefile_pathname); // get pathname length
// does the pathname we want end with a wildcard ?
if ((length > 0) && (imagefile_pathname[length - 1] == L'*'))
{
// test if a corresponding .dds, .jpg, .jpeg, .png, .tga or .bmp file exists
wcsncpy_s (valid_pathname, WCHAR_SIZEOF (valid_pathname), imagefile_pathname, length - 1);
// try these extensions one after the other...
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"dds");
if (_waccess (valid_pathname, 0) != 0)
{
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"jpg");
if (_waccess (valid_pathname, 0) != 0)
{
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"jpeg");
if (_waccess (valid_pathname, 0) != 0)
{
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"png");
if (_waccess (valid_pathname, 0) != 0)
{
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"tga");
if (_waccess (valid_pathname, 0) != 0)
{
wcscpy_s (&valid_pathname[length - 1], WCHAR_SIZEOF (valid_pathname) - (length - 1), L"bmp");
if (_waccess (valid_pathname, 0) != 0)
return (false); // if none of these extensions match, bomb out
}
}
}
}
}
}
else
wcscpy_s (valid_pathname, WCHAR_SIZEOF (valid_pathname), imagefile_pathname); // the filename we want is known
// open the file for binary reading first
_wfopen_s (&fp, valid_pathname, L"rb");
if (fp == NULL)
return (false); // if unable to open the file, return FALSE
// get file length
fseek (fp, 0, SEEK_END);
length = ftell (fp);
fseek (fp, 0, SEEK_SET);
// if file is not large enough to hold a single chunk of data, it can't possibly be a valid image
if (length < 26)
{
fclose (fp); // so close it
return (FALSE); // and return FALSE
}
// Strategy:
// reading JPEG dimensions requires scanning through jpeg chunks
// reading PNG dimensions requires the first 24 bytes of the file
// reading BMP dimensions requires the first 26 bytes of the file
// In all formats, the file is at least 26 bytes big, so we'll read that always
fread (buffer, 26, 1, fp);
// For DDS files, dimensions are given at bytes 12 (height) and 16 (width)
if ((buffer[0] == 'D') && (buffer[1] == 'D') && (buffer[2] == 'S') && (buffer[3] == ' '))
{
memcpy (width, &buffer[16], sizeof (unsigned long));
memcpy (height, &buffer[12], sizeof (unsigned long));
fclose (fp); // close file now
return (true); // copy out the width and height and return TRUE
}
// For JPEGs, we need to read the first 12 bytes of each chunk.
// We'll read those 12 bytes at buf+2...buf+14, i.e. overwriting the existing buf.
else if ((buffer[0] == 0xFF) && (buffer[1] == 0xD8) && (buffer[2] == 0xFF))
{
pos = 2; // start at the beginning
// as long as there's the beginning of a new chunk to parse in our buffer...
while (buffer[2] == 0xFF)
{
// is that chunk the one we want ?
if ((buffer[2 + 1] == 0xC0) || (buffer[2 + 1] == 0xC1) || (buffer[2 + 1] == 0xC2) || (buffer[2 + 1] == 0xC3))
{
*height = 256 * (int) buffer[2 + 5] + (int) buffer[2 + 6]; // copy out the height and width
*width = 256 * (int) buffer[2 + 7] + (int) buffer[2 + 8];
fclose (fp); // close file now
return (true); // and return TRUE
}
pos += 2 + 256 * (int) buffer[2 + 2] + (int) buffer[2 + 3]; // else increase pos by the size of the chunk
if (pos >= length)
{
fclose (fp); // close file now
return (false); // stop searching if end of file is reached
}
fseek (fp, pos, SEEK_SET); // seek at beginning of next block
fread (&buffer[2], 10, 1, fp); // and read another 10-byte block
}
}
// PNG: the first frame is by definition an IHDR frame, which gives dimensions
else if ((buffer[0] == 0x89) && (buffer[1] == 'P') && (buffer[2] == 'N') && (buffer[3] == 'G')
&& (buffer[4] == 0x0D) && (buffer[5] == 0x0A) && (buffer[6] == 0x1A) && (buffer[7] == 0x0A)
&& (buffer[12] == 'I') && (buffer[13] == 'H') && (buffer[14] == 'D') && (buffer[15]=='R'))
{
*width = (buffer[16] << 24) | (buffer[17] << 16) | (buffer[18] << 8) | (buffer[19] << 0);
*height = (buffer[20] << 24) | (buffer[21] << 16) | (buffer[22] << 8) | (buffer[23] << 0);
fclose (fp); // close file now
return (true); // copy out the width and height and return TRUE
}
// TGA: read the image size from the TGA header
else if ((buffer[0] == 0x00) && ((buffer[1] == 0x00) || (buffer[1] == 0x01)))
{
*width = (buffer[13] << 8) | (buffer[12] << 0);
*height = (buffer[15] << 8) | (buffer[14] << 0);
fclose (fp); // close file now
return (true); // copy out the width and height and return TRUE
}
// BMP: read the bitmap file header, then the image header
else if ((buffer[0] == 'B') && (buffer[1] == 'M')
&& (buffer[6] == 0) && (buffer[7] == 0) && (buffer[8] == 0) && (buffer[9] == 0))
{
memcpy (width, &buffer[18], sizeof (unsigned long));
memcpy (height, &buffer[22], sizeof (unsigned long));
fclose (fp); // close file now
return (true); // copy out the width and height and return TRUE
}
fclose (fp); // close file now
return (false); // file is probably not a DDS, BMP, PNG, TGA or JPEG image
}
void GenerateVersionNumber (char *out_string, size_t outstring_maxsize)
{
// handy helper to generate a version number in the form YYYYMMDD
sprintf_s (out_string, outstring_maxsize, "%c%c%c%c%s%c%c",
__DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10], // year
(strncmp (__DATE__, "Jan", 3) == 0 ? "01" :
(strncmp (__DATE__, "Feb", 3) == 0 ? "02" :
(strncmp (__DATE__, "Mar", 3) == 0 ? "03" :
(strncmp (__DATE__, "Apr", 3) == 0 ? "04" :
(strncmp (__DATE__, "May", 3) == 0 ? "05" :
(strncmp (__DATE__, "Jun", 3) == 0 ? "06" :
(strncmp (__DATE__, "Jul", 3) == 0 ? "07" :
(strncmp (__DATE__, "Aug", 3) == 0 ? "08" :
(strncmp (__DATE__, "Sep", 3) == 0 ? "09" :
(strncmp (__DATE__, "Oct", 3) == 0 ? "10" :
(strncmp (__DATE__, "Nov", 3) == 0 ? "11" :
(strncmp (__DATE__, "Dec", 3) == 0 ? "12" : "??")))))))))))),
(__DATE__[4] == ' ' ? '0' : __DATE__[4]), __DATE__[5]);
return; // finished
}
void Debug_Init (const wchar_t *logfile_name)
{
// helper function for debug log file initialization
FILE *fp;
// build the log file full qualified path name
swprintf_s (logfile_pathname, WCHAR_SIZEOF (logfile_pathname), L"%s/%s", app_path, logfile_name);
// open it and erase it
_wfopen_s (&fp, logfile_pathname, L"wb");
if (fp != NULL)
{
fwprintf_s (fp, L"===LOG FILE RESET===\n"); // write the log initialization string
fclose (fp); // flush buffers and close file
}
return; // finished
}
void Debug_Log (const wchar_t *fmt, ...)
{
// helper function for debug logging
FILE *fp;
va_list argptr;
// open the log file in append mode
_wfopen_s (&fp, logfile_pathname, L"ab");
if (fp != NULL)
{
va_start (argptr, fmt);
vfwprintf_s (fp, fmt, argptr); // concatenate all the arguments in one string
va_end (argptr);
fclose (fp); // flush buffers and close it
}
return; // finished
}
void Debug_LogMove (boardmove_t *move, const wchar_t *fmt, ...)
{
// helper function for debug logging
FILE *fp;
va_list argptr;
int i;
int j;
// open the log file in append mode
_wfopen_s (&fp, logfile_pathname, L"ab");
if (fp != NULL)
{
va_start (argptr, fmt);
vfwprintf_s (fp, fmt, argptr); // concatenate all the arguments in one string
va_end (argptr);
// capture and encode the move
fwprintf (fp, L"\t+---+---+---+---+---+---+---+---+\n");
for (i = 7; i >= 0; i--) // lines are in reverse order in this stupid program of mine >.<
{
fwprintf (fp, L"\t|");
for (j = 0; j < 8; j++)
{
if (move->slots[i][j].part == PART_ROOK) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" R |" : L" r |"));
else if (move->slots[i][j].part == PART_KNIGHT) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" N |" : L" n |"));
else if (move->slots[i][j].part == PART_BISHOP) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" B |" : L" b |"));
else if (move->slots[i][j].part == PART_QUEEN) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" Q |" : L" q |"));
else if (move->slots[i][j].part == PART_KING) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" K |" : L" k |"));
else if (move->slots[i][j].part == PART_PAWN) fwprintf (fp, (move->slots[i][j].color == COLOR_WHITE ? L" P |" : L" p |"));
else fwprintf (fp, L" |");
}
fwprintf (fp, L"\n");
fwprintf (fp, L"\t+---+---+---+---+---+---+---+---+\n");
}
fclose (fp); // flush buffers and close it
}
return; // finished
}
bool Debug_SendLogToAuthor (char *reason, bool should_include_description)
{
// this function upload the engine history to the remote server for debug purposes.
wchar_t descriptionfile_pathname[MAX_PATH];
char temp_string[1024];
struct sockaddr_in service;
struct hostent *hostinfo;
SHELLEXECUTEINFO bugreport_shinfo;
MEMORYSTATUSEX memory_status;
buffer_t temp_buffer;
buffer_t description_buffer;
buffer_t logfile_buffer;
buffer_t board_buffer;
buffer_t http_buffer; // used for both request and reply
size_t dummy_size;
bool was_successful;
unsigned char color;
unsigned char part;
char *base64buffer; // mallocated
int write_index;
int read_index;
int length;
DWORD valsize;
HKEY hKey;
SOCKET s;
int i;
int j;
// get a hand on the log file and read its contents
Buffer_Initialize (&logfile_buffer);
if (Buffer_ReadFromFileW (&temp_buffer, logfile_pathname))
{
logfile_buffer.data = (char *) malloc (temp_buffer.size); // necessarily less
logfile_buffer.size = ConvertTo7BitASCII (logfile_buffer.data, temp_buffer.size, (wchar_t *) temp_buffer.data);
}
else
{
Buffer_AppendCString (&logfile_buffer, "Couldn't open log file at \"");
ConvertTo7BitASCII (temp_string, sizeof (temp_string), logfile_pathname); Buffer_AppendCString (&logfile_buffer, temp_string);
Buffer_AppendCString (&logfile_buffer, "\".\n");
}
// should the user include a problem report ?
Buffer_Initialize (&description_buffer);
if (should_include_description)
{
// have the user describe his problem with Notepad
swprintf_s (descriptionfile_pathname, WCHAR_SIZEOF (descriptionfile_pathname), L"%s\\Chess Giants bug report.txt", app_path);
Buffer_Initialize (&description_buffer);
length = wcslen (LOCALIZE (L"PleaseDescribeTheProblem"));
Buffer_Append (&description_buffer, (char *) LOCALIZE (L"PleaseDescribeTheProblem"), length * sizeof (wchar_t));
Buffer_Append (&description_buffer, (char *) L"\r\n", 2 * sizeof (wchar_t));
for (write_index = 0; write_index < length; write_index++)
Buffer_Append (&description_buffer, (char *) L"-", sizeof (wchar_t));
Buffer_Append (&description_buffer, (char *) L"\r\n", 2 * sizeof (wchar_t));
Buffer_Append (&description_buffer, (char *) L"\r\n=> ", 5 * sizeof (wchar_t));
Buffer_WriteToFileW (&description_buffer, descriptionfile_pathname);
memset (&bugreport_shinfo, 0, sizeof (bugreport_shinfo));
bugreport_shinfo.cbSize = sizeof (SHELLEXECUTEINFO);
bugreport_shinfo.fMask = SEE_MASK_NOCLOSEPROCESS;
bugreport_shinfo.lpFile = L"notepad.exe";
bugreport_shinfo.lpParameters = descriptionfile_pathname;
bugreport_shinfo.nShow = SW_SHOW;
ShellExecuteEx (&bugreport_shinfo);
WaitForSingleObject (bugreport_shinfo.hProcess, INFINITE);
CloseHandle (bugreport_shinfo.hProcess);
// get a hand on the error description file and read its contents
Buffer_Initialize (&description_buffer);
if (Buffer_ReadFromFileW (&temp_buffer, descriptionfile_pathname))
{
description_buffer.data = (char *) malloc (temp_buffer.size); // necessarily less
description_buffer.size = ConvertTo7BitASCII (description_buffer.data, temp_buffer.size, (wchar_t *) temp_buffer.data);
}
else
{
Buffer_AppendCString (&description_buffer, "Couldn't open error description file at \"");
ConvertTo7BitASCII (temp_string, sizeof (temp_string), descriptionfile_pathname); Buffer_AppendCString (&description_buffer, temp_string);
Buffer_AppendCString (&description_buffer, "\".\n");
}
}
// append the program-given reason to the description buffer
Buffer_AppendCharArray (&description_buffer, "\n\nChess Giants reason: ");
Buffer_AppendCString (&description_buffer, reason);
// capture and encode the board
Buffer_Initialize (&board_buffer);
Buffer_AppendCharArray (&board_buffer, "+---+---+---+---+---+---+---+---+\n");
for (i = 7; i >= 0; i--) // lines are in reverse order in this stupid program of mine >.<
{
Buffer_AppendCString (&board_buffer, "|");
for (j = 0; j < 8; j++)
{
part = the_board.moves[the_board.move_count - 1].slots[i][j].part;
color = the_board.moves[the_board.move_count - 1].slots[i][j].color;
if (part == PART_ROOK) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " R |" : " r |"));
else if (part == PART_KNIGHT) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " N |" : " n |"));
else if (part == PART_BISHOP) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " B |" : " b |"));
else if (part == PART_QUEEN) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " Q |" : " q |"));
else if (part == PART_KING) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " K |" : " k |"));
else if (part == PART_PAWN) Buffer_AppendCString (&board_buffer, (color == COLOR_WHITE ? " P |" : " p |"));
else Buffer_AppendCString (&board_buffer, " |");
}
Buffer_AppendCharArray (&board_buffer, "\n" "+---+---+---+---+---+---+---+---+\n");
}
// get our distribution server's IP address from the host name
hostinfo = gethostbyname ("pmbaty.com");
if (hostinfo == NULL)
return (false); // couldn't resolve hostname, return an error condition
// fill in the sockaddr server structure with the server hostinfo data
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr (inet_ntoa (*(struct in_addr *) hostinfo->h_addr_list[0]));
service.sin_port = htons (80); // connect to webserver there (port 80)
// create our socket
if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
return (false); // couldn't resolve hostname, return an error condition
// connect to the distributor's webserver using that socket
if (connect (s, (struct sockaddr *) &service, sizeof (service)) == -1)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
// build the HTTP POST query and send it
base64buffer = (char *) malloc ((max (board_buffer.size, max (logfile_buffer.size, description_buffer.size)) * 4 / 3 + 4) * sizeof (char));
Buffer_Initialize (&http_buffer);
Buffer_AppendCharArray (&http_buffer, "registrant="); ConvertTo7BitASCII (temp_string, sizeof (temp_string), (options.registration.user_email[0] != 0 ? options.registration.user_email : L"an+unregistered+user")); Buffer_AppendCString (&http_buffer, temp_string);
Buffer_AppendCharArray (&http_buffer, "&version="); GenerateVersionNumber (temp_string, sizeof (temp_string)); Buffer_AppendCString (&http_buffer, temp_string);
Buffer_AppendCharArray (&http_buffer, "&player1="); Buffer_Append (&http_buffer, (the_board.players[COLOR_WHITE].type == PLAYER_INTERNET ? "I" : (the_board.players[COLOR_WHITE].type == PLAYER_COMPUTER ? "C" : "H")), 1);
Buffer_AppendCharArray (&http_buffer, "&player2="); Buffer_Append (&http_buffer, (the_board.players[COLOR_BLACK].type == PLAYER_INTERNET ? "I" : (the_board.players[COLOR_BLACK].type == PLAYER_COMPUTER ? "C" : "H")), 1);
Buffer_AppendCharArray (&http_buffer, "&board="); base64_encode (base64buffer, board_buffer.data, board_buffer.size); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_AppendCharArray (&http_buffer, "&log="); base64_encode (base64buffer, logfile_buffer.data, logfile_buffer.size); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_AppendCharArray (&http_buffer, "&description="); base64_encode (base64buffer, description_buffer.data, description_buffer.size); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_AppendCharArray (&http_buffer, "&os="); RegOpenKeyExA (HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hKey); valsize = (DWORD) sizeof (temp_string); RegQueryValueExA (hKey, "BuildLab", NULL, NULL, (unsigned char *) temp_string, &valsize); RegCloseKey (hKey); temp_string[valsize] = 0; base64_encode (base64buffer, temp_string, strlen (temp_string)); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_AppendCharArray (&http_buffer, "&cpu="); getenv_s (&dummy_size, temp_string, sizeof (temp_string), "PROCESSOR_IDENTIFIER"); base64_encode (base64buffer, temp_string, strlen (temp_string)); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_AppendCharArray (&http_buffer, "&ram="); memory_status.dwLength = sizeof (memory_status); GlobalMemoryStatusEx (&memory_status); sprintf_s (temp_string, sizeof (temp_string), "Memory usage: %d%%\nPhysical total %d Mb (free %d Mb)\nPaging total %d Mb (free %d Mb)\nVirtual total %d Mb (free %d Mb)", (int) memory_status.dwMemoryLoad, (int) (memory_status.ullTotalPhys / (1024 * 1024)), (int) (memory_status.ullAvailPhys / (1024 * 1024)), (int) (memory_status.ullTotalPageFile / (1024 * 1024)), (int) (memory_status.ullAvailPageFile / (1024 * 1024)), (int) (memory_status.ullTotalVirtual / (1024 * 1024)), (int) (memory_status.ullAvailVirtual / (1024 * 1024))); base64_encode (base64buffer, temp_string, strlen (temp_string)); Buffer_AppendCString (&http_buffer, base64buffer);
Buffer_Forget (&description_buffer);
Buffer_Forget (&logfile_buffer);
Buffer_Forget (&board_buffer);
free (base64buffer);
length = http_buffer.size;
Buffer_Initialize (&temp_buffer);
Buffer_WriteAt (&temp_buffer, 256, "", 1); // make sure buffer is big enough
temp_buffer.size = sprintf_s (temp_buffer.data, temp_buffer.size,
"POST /chess/sendcrash.php HTTP/1.1" "\r\n"
"Host: " "pmbaty.com" "\r\n"
"Content-Type: " "application/x-www-form-urlencoded" "\r\n"
"Content-Length: %d" "\r\n"
"Connection: " "close" "\r\n"
"\r\n", length);
Buffer_PrependBuffer (&http_buffer, &temp_buffer);
Buffer_Forget (&temp_buffer);
write_index = send (s, http_buffer.data, http_buffer.size, 0); // send the HTTP query
if (write_index != http_buffer.size)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
// read the reply (10 seconds timeout)
http_buffer.data[0] = 0;
read_index = RecvWithTimeout (s, 10.0f, http_buffer.data, http_buffer.size, 0);
if (read_index < 1)
{
closesocket (s); // finished communicating, close TCP socket
return (false); // couldn't resolve hostname, return an error condition
}
closesocket (s); // finished communicating, close TCP socket
// terminate recv buffer ourselves and see if the server accepted our post
http_buffer.data[read_index] = 0;
//MessageBoxA (NULL, http_buffer, "HTTP response", MB_OK);
was_successful = (strstr (http_buffer.data, "Success") != NULL);
Buffer_Forget (&http_buffer);
return (was_successful); // and return whether the server accepted our post
}
int RecvWithTimeout (int socket_id, float timeout_in_seconds, char *outbuf, size_t outbuf_size, int flags)
{
// variant of recv() that honors a specific timeout in seconds
unsigned long nonblocking_mode;
unsigned long msec_start;
float timediff;
int total_size;
int recv_size;
// make socket non blocking
nonblocking_mode = 1;
ioctlsocket (socket_id, FIONBIO, &nonblocking_mode);
// loop endlessly, noting the time at which we start
msec_start = GetTickCount ();
total_size = 0;
for (;;)
{
// see how much time elapsed since the last time we received data
timediff = (GetTickCount () - msec_start) / 1000.0f;
if (timediff > timeout_in_seconds)
break; // if we've waited long enough, give up
// see if we have something to read from the socket
recv_size = recv (socket_id, &outbuf[total_size], outbuf_size - total_size, flags);
if (recv_size == 0)
break; // on TCP disconnection, give up too
else if (recv_size < 0)
{
Sleep (100); // if nothing was received then we want to wait a little before trying again, 0.1 seconds
continue;
}
total_size += recv_size; // increase the received bytes count
outbuf[total_size] = 0; // terminate outbuf ourselves
if (total_size == outbuf_size)
break; // if the output buffer is full, give up
msec_start = GetTickCount (); // and remember when we last received data (i.e. now)
}
return (total_size); // and return the number of bytes received
}
const wchar_t *GetLastNetworkError (void)
{
// this function retrieves and translates the last WSA error code into a full text string
static const wsaerror_t wsa_errors[] =
{
{6, L"WSA_INVALID_HANDLE: Specified event object handle is invalid. [An application attempts to use an event object, but the specified handle is not valid. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{8, L"WSA_NOT_ENOUGH_MEMORY: Insufficient memory available. [An application used a Windows Sockets function that directly maps to a Windows function. The Windows function is indicating a lack of required memory resources. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{87, L"WSA_INVALID_PARAMETER: One or more parameters are invalid. [An application used a Windows Sockets function which directly maps to a Windows function. The Windows function is indicating a problem with one or more parameters. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{995, L"WSA_OPERATION_ABORTED: Overlapped operation aborted. [An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{996, L"WSA_IO_INCOMPLETE: Overlapped I/O event object not in signaled state. [The application has tried to determine the status of an overlapped operation which is not yet completed. Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{997, L"WSA_IO_PENDING: Overlapped operations will complete later. [The application has initiated an overlapped operation that cannot be completed immediately. A completion indication will be given later when the operation has been completed. Note that this error is returned by the operating system, so the error number may change in future releases of Windows.]"},
{10004, L"WSAEINTR: Interrupted function call. [A blocking operation was interrupted by a call to WSACancelBlockingCall.]"},
{10009, L"WSAEBADF: File handle is not valid. [The file handle supplied is not valid.]"},
{10013, L"WSAEACCES: Permission denied. [An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST). Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4 SP4 or later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4 SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.]"},
{10014, L"WSAEFAULT: Bad address. [The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).]"},
{10022, L"WSAEINVAL: Invalid argument. [Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.]"},
{10024, L"WSAEMFILE: Too many open files. [Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.]"},
{10035, L"WSAEWOULDBLOCK: Resource temporarily unavailable. [This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.]"},
{10036, L"WSAEINPROGRESS: Operation now in progress. [A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.]"},
{10037, L"WSAEALREADY: Operation already in progress. [An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.]"},
{10038, L"WSAENOTSOCK: Socket operation on nonsocket. [An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.]"},
{10039, L"WSAEDESTADDRREQ: Destination address required. [A required address was omitted from an operation on a socket. For example, this error is returned if sendto is called with the remote address of ADDR_ANY.]"},
{10040, L"WSAEMSGSIZE: Message too long. [A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.]"},
{10041, L"WSAEPROTOTYPE: Protocol wrong type for socket. [A protocol was specified in the socket function call that does not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM.]"},
{10042, L"WSAENOPROTOOPT: Bad protocol option. [An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.]"},
{10043, L"WSAEPROTONOSUPPORT: Protocol not supported. [The requested protocol has not been configured into the system, or no implementation for it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.]"},
{10044, L"WSAESOCKTNOSUPPORT: Socket type not supported. [The support for the specified socket type does not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all.]"},
{10045, L"WSAEOPNOTSUPP: Operation not supported. [The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.]"},
{10046, L"WSAEPFNOSUPPORT: Protocol family not supported. [The protocol family has not been configured into the system or no implementation for it exists. This message has a slightly different meaning from WSAEAFNOSUPPORT. However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.]"},
{10047, L"WSAEAFNOSUPPORT: Address family not supported by protocol family. [An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.]"},
{10048, L"WSAEADDRINUSE: Address already in use. [Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all— connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.]"},
{10049, L"WSAEADDRNOTAVAIL: Cannot assign requested address. [The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).]"},
{10050, L"WSAENETDOWN: Network is down. [A socket operation encountered a dead network. This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.]"},
{10051, L"WSAENETUNREACH: Network is unreachable. [A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host.]"},
{10052, L"WSAENETRESET: Network dropped connection on reset. [The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed.]"},
{10053, L"WSAECONNABORTED: Software caused connection abort. [An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.]"},
{10054, L"WSAECONNRESET: Connection reset by peer. [An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.]"},
{10055, L"WSAENOBUFS: No buffer space available. [An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.]"},
{10056, L"WSAEISCONN: Socket is already connected. [A connect request was made on an already-connected socket. Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (for SOCK_STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.]"},
{10057, L"WSAENOTCONN: Socket is not connected. [A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also return this error—for example, setsockopt setting SO_KEEPALIVE if the connection has been reset.]"},
{10058, L"WSAESHUTDOWN: Cannot send after socket shutdown. [A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.]"},
{10059, L"WSAETOOMANYREFS: Too many references. [Too many references to some kernel object.]"},
{10060, L"WSAETIMEDOUT: Connection timed out. [A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.]"},
{10061, L"WSAECONNREFUSED: Connection refused. [No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.]"},
{10062, L"WSAELOOP: Cannot translate name. [Cannot translate a name.]"},
{10063, L"WSAENAMETOOLONG: Name too long. [A name component or a name was too long.]"},
{10064, L"WSAEHOSTDOWN: Host is down. [A socket operation failed because the destination host is down. A socket operation encountered a dead host. Networking activity on the local host has not been initiated. These conditions are more likely to be indicated by the error WSAETIMEDOUT.]"},
{10065, L"WSAEHOSTUNREACH: No route to host. [A socket operation was attempted to an unreachable host. See WSAENETUNREACH.]"},
{10066, L"WSAENOTEMPTY: Directory not empty. [Cannot remove a directory that is not empty.]"},
{10067, L"WSAEPROCLIM: Too many processes. [A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously.WSAStartup may fail with this error if the limit has been reached.]"},
{10068, L"WSAEUSERS: User quota exceeded. [Ran out of user quota.]"},
{10069, L"WSAEDQUOT: Disk quota exceeded. [Ran out of disk quota.]"},
{10070, L"WSAESTALE: Stale file handle reference. [The file handle reference is no longer available.]"},
{10071, L"WSAEREMOTE: Item is remote. [The item is not available locally.]"},
{10091, L"WSASYSNOTREADY: Network subsystem is unavailable. [This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable. Users should check that the appropriate Windows Sockets DLL file is in the current path, that they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded, that the Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.]"},
{10092, L"WSAVERNOTSUPPORTED: Winsock.dll version out of range. [The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.]"},
{10093, L"WSANOTINITIALISED: Successful WSAStartup not yet performed. [Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.]"},
{10101, L"WSAEDISCON: Graceful shutdown in progress. [Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.]"},
{10102, L"WSAENOMORE: No more results. [No more results can be returned by the WSALookupServiceNext function.]"},
{10103, L"WSAECANCELLED: Call has been canceled. [A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.]"},
{10104, L"WSAEINVALIDPROCTABLE: Procedure call table is invalid. [The service provider procedure call table is invalid. A service provider returned a bogus procedure table to Ws2_32.dll. This is usually caused by one or more of the function pointers being NULL.]"},
{10105, L"WSAEINVALIDPROVIDER: Service provider is invalid. [The requested service provider is invalid. This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found. This error is also returned if the service provider returned a version number other than 2.0.]"},
{10106, L"WSAEPROVIDERFAILEDINIT: Service provider failed to initialize. [The requested service provider could not be loaded or initialized. This error is returned if either a service provider's DLL could not be loaded (LoadLibrary failed) or the provider's WSPStartup or NSPStartup function failed.]"},
{10107, L"WSASYSCALLFAILURE: System call failure. [A system call that should never fail has failed. This is a generic error code, returned under various condition. Returned when a system call that should never fail does fail. For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs. Returned when a provider does not return SUCCESS and does not provide an extended error code. Can indicate a service provider implementation error.]"},
{10108, L"WSASERVICE_NOT_FOUND: Service not found. [No such service is known. The service cannot be found in the specified name space.]"},
{10109, L"WSATYPE_NOT_FOUND: Class type not found. [The specified class was not found.]"},
{10110, L"WSA_E_NO_MORE: No more results. [No more results can be returned by the WSALookupServiceNext function.]"},
{10111, L"WSA_E_CANCELLED: Call was canceled. [A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.]"},
{10112, L"WSAEREFUSED: Database query was refused. [A database query failed because it was actively refused.]"},
{11001, L"WSAHOST_NOT_FOUND: Host not found. [No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.]"},
{11002, L"WSATRY_AGAIN: Nonauthoritative host not found. [This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.]"},
{11003, L"WSANO_RECOVERY: This is a nonrecoverable error. [This indicates that some sort of nonrecoverable error occurred during a database lookup. This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.]"},
{11004, L"WSANO_DATA: Valid name, no data record of requested type. [The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.]"},
{11005, L"WSA_QOS_RECEIVERS: QOS receivers. [At least one QOS reserve has arrived.]"},
{11006, L"WSA_QOS_SENDERS: QOS senders. [At least one QOS send path has arrived.]"},
{11007, L"WSA_QOS_NO_SENDERS: No QOS senders. [There are no QOS senders.]"},
{11008, L"WSA_QOS_NO_RECEIVERS: QOS no receivers. [There are no QOS receivers.]"},
{11009, L"WSA_QOS_REQUEST_CONFIRMED: QOS request confirmed. [The QOS reserve request has been confirmed.]"},
{11010, L"WSA_QOS_ADMISSION_FAILURE: QOS admission error. [A QOS error occurred due to lack of resources.]"},
{11011, L"WSA_QOS_POLICY_FAILURE: QOS policy failure. [The QOS request was rejected because the policy system couldn't allocate the requested resource within the existing policy.]"},
{11012, L"WSA_QOS_BAD_STYLE: QOS bad style. [An unknown or conflicting QOS style was encountered.]"},
{11013, L"WSA_QOS_BAD_OBJECT: QOS bad object. [A problem was encountered with some part of the filterspec or the provider-specific buffer in general.]"},
{11014, L"WSA_QOS_TRAFFIC_CTRL_ERROR: QOS traffic control error. [An error with the underlying traffic control (TC) API as the generic QOS request was converted for local enforcement by the TC API. This could be due to an out of memory error or to an internal QOS provider error.]"},
{11015, L"WSA_QOS_GENERIC_ERROR: QOS generic error. [A general QOS error.]"},
{11016, L"WSA_QOS_ESERVICETYPE: QOS service type error. [An invalid or unrecognized service type was found in the QOS flowspec.]"},
{11017, L"WSA_QOS_EFLOWSPEC: QOS flowspec error. [An invalid or inconsistent flowspec was found in the QOS structure.]"},
{11018, L"WSA_QOS_EPROVSPECBUF: Invalid QOS provider buffer. [An invalid QOS provider-specific buffer.]"},
{11019, L"WSA_QOS_EFILTERSTYLE: Invalid QOS filter style. [An invalid QOS filter style was used.]"},
{11020, L"WSA_QOS_EFILTERTYPE: Invalid QOS filter type. [An invalid QOS filter type was used.]"},
{11021, L"WSA_QOS_EFILTERCOUNT: Incorrect QOS filter count. [An incorrect number of QOS FILTERSPECs were specified in the FLOWDESCRIPTOR.]"},
{11022, L"WSA_QOS_EOBJLENGTH: Invalid QOS object length. [An object with an invalid ObjectLength field was specified in the QOS provider-specific buffer.]"},
{11023, L"WSA_QOS_EFLOWCOUNT: Incorrect QOS flow count. [An incorrect number of flow descriptors was specified in the QOS structure.]"},
{11024, L"WSA_QOS_EUNKOWNPSOBJ: Unrecognized QOS object. [An unrecognized object was found in the QOS provider-specific buffer.]"},
{11025, L"WSA_QOS_EPOLICYOBJ: Invalid QOS policy object. [An invalid policy object was found in the QOS provider-specific buffer.]"},
{11026, L"WSA_QOS_EFLOWDESC: Invalid QOS flow descriptor. [An invalid QOS flow descriptor was found in the flow descriptor list.]"},
{11027, L"WSA_QOS_EPSFLOWSPEC: Invalid QOS provider-specific flowspec. [An invalid or inconsistent flowspec was found in the QOS provider-specific buffer.]"},
{11028, L"WSA_QOS_EPSFILTERSPEC: Invalid QOS provider-specific filterspec. [An invalid FILTERSPEC was found in the QOS provider-specific buffer.]"},
{11029, L"WSA_QOS_ESDMODEOBJ: Invalid QOS shape discard mode object. [An invalid shape discard mode object was found in the QOS provider-specific buffer.]"},
{11030, L"WSA_QOS_ESHAPERATEOBJ: Invalid QOS shaping rate object. [An invalid shaping rate object was found in the QOS provider-specific buffer.]"},
{11031, L"WSA_QOS_RESERVED_PETYPE: Reserved policy QOS element type. [A reserved policy element was found in the QOS provider-specific buffer.]"}
};
size_t error_index;
int error;
error = WSAGetLastError (); // first get the error code from the system
// for each error code we know, see if it's the one we want
for (error_index = 0; error_index < sizeof (wsa_errors) / sizeof (wsaerror_t); error_index++)
if (wsa_errors[error_index].number == error)
return (wsa_errors[error_index].description); // if it's that one, return its description
// error code not found
return (L"Unknown error.");
}
HICON W32LoadIcon (const wchar_t *fmt, ...)
{
// this function loads an icon from a file into an icon handle.
static wchar_t icofile_pathname[MAX_PATH];
va_list argptr;
// concatenate all the arguments in one string
va_start (argptr, fmt);
wvsprintf (icofile_pathname, fmt, argptr);
va_end (argptr);
// load the icon from file and return the resulting handle
return ((HICON) LoadImage (NULL, icofile_pathname, IMAGE_ICON, 0, 0, LR_LOADFROMFILE));
}
HBITMAP W32LoadImage (const wchar_t *fmt, ...)
{
// this function loads an image from a file into a bitmap handle.
static wchar_t imgfile_pathname[MAX_PATH];
va_list argptr;
// concatenate all the arguments in one string
va_start (argptr, fmt);
wvsprintf (imgfile_pathname, fmt, argptr);
va_end (argptr);
// load the image from file and return the resulting handle
return ((HBITMAP) LoadImage (NULL, imgfile_pathname, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE));
}
bool IsRegistrationCorrect (const wchar_t *email, const unsigned __int32 code)
{
// quick helper to see if the program is registered. It contains an address to potential crackers.
// Notice: user's email address may be a wchar_t array, and thus may contain Unicode characters.
// /!\ WARNING: THE CRACKER MESSAGE SHOULD NEVER CHANGE, AND NEITHER SHOULD THE ALGORITHM BELOW /!\
static const char crackermsg[] = "Please, respect my work. DON'T PUBLISH if you crack my program. Thank you and happy cracking :)";
static const wchar_t *blacklist[] = { L"bono@fff.com" }; // those crackers didn't play fair :(
unsigned __int32 correct_activationcode;
int byte_index;
int length;
// compute the maximal length of the string for which we need to checksum
length = wcslen (email);
if (length > sizeof (crackermsg) - 1)
length = sizeof (crackermsg) - 1; // bound it to the length of the cracker message
// reuse byte_index to parse the blacklist
for (byte_index = 0; byte_index < sizeof (blacklist) / sizeof (wchar_t *); byte_index++)
if (_wcsicmp (blacklist[byte_index], email) == 0)
return (false); // if email is blacklisted, report it to be false
// hash the supplied e-mail
correct_activationcode = 5381; // start value
for (byte_index = 0; byte_index < sizeof (crackermsg) - 1; byte_index++)
correct_activationcode = ((correct_activationcode << 5) + correct_activationcode)
+ ((unsigned __int32) (length > 0 ? towlower (email[byte_index % length]) : 1) // prevent zero divide
^ (unsigned __int32) crackermsg[byte_index]); // hash = hash * 33 + (char(email) ^ char(crackermsg))
correct_activationcode &= 0x7FFFFFFF; // make sure the results remain positive
// as usuals, it alls boils down to a single test :(
return ((length > sizeof ("a@b.c") - 1) && (code == correct_activationcode));
}