I'm trying to do the following:
get username typed into the userField
make a SEARCH mysql_query with the username as a variable
I'm having a hard time getting past phase 2 since mysql_query takes a const char* as the query string, and I can only get username as char* or wchar_t*
I'm also compiling in unicode.
My code for now:
void mysql_connect(HWND hLoginWnd) {
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
char name[512], pass[512];
int lenUser = SendMessage(userField, WM_GETTEXT, 512, (LPARAM)name);
int lenPass = SendMessage(passField, WM_GETTEXT, 512, (LPARAM)pass);
if(lenUser > 0 && lenPass > 0) {
std::string query = "SELECT pass FROM users WHERE name='" + std::string(name) + "'";
mysql_query(&mysql, query.c_str());
}
}
What should I do?
You are setting the SQL charset to UTF-8, so use WideCharToMultiByte() to convert the retreived UI Unicode strings into UTF-8, then pass the converted data to the DB query. UTF-8 encoded data can be stored using char buffers, and you can pass a char* (or char[]) where a const char* is expected. For example:
std::string Utf8Encode(WCHAR *wStr, int wLen)
{
int utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, NULL, 0, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> utf8(utf8len);
utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, &utf8[0], utf8len, NULL, NULL);
if (utf8len > 0)
return std::string(&utf8[0], utf8len);
}
return std::string();
}
void mysql_connect(HWND hLoginWnd)
{
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
WCHAR name[512];
int lenUser = SendMessage(userField, WM_GETTEXTW, 512, (LPARAM)name);
if (lenUser > 0)
{
std::string query = "SELECT pass FROM users WHERE name='" + Utf8Encode(name, lenUser) + "'";
mysql_query(&mysql, query.c_str());
...
}
}
With that said, you really need to escape strings when building SQL statements dynamically. It is safer as it is not prone to SQL Injection attacks:
std::string Utf8EncodeAndEscape(MYSQL *mysql, WCHAR *wStr, int wLen)
{
int utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, NULL, 0, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> utf8(utf8len);
utf8len = WideCharToMultiByte(CP_UTF8, 0, wStr, wLen, &utf8[0], utf8len, NULL, NULL);
if (utf8len > 0)
{
std::vector<char> escaped(utf8len*2+1);
unsigned long escapedLen = mysql_real_escape_string(mysql, &escaped[0], &utf8[0], utf8len);
if (escapedLen > 0)
return std::string(&escaped[0], escapedLen);
}
}
return std::string();
}
void mysql_connect(HWND hLoginWnd)
{
MYSQL *con, mysql;
MYSQL_RES *res;
mysql_init(&mysql);
mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8");
mysql_real_connect(&mysql, "localhost", "root", "", "treenitaulu", 3306, NULL, 0);
WCHAR name[512];
int lenUser = SendMessage(userField, WM_GETTEXTW, 512, (LPARAM)name);
if (lenUser > 0)
{
std::string query = "SELECT pass FROM users WHERE name='" + Utf8EncodeAndEscape(&mysql, name, lenUser) + "'";
mysql_query(&mysql, query.c_str());
...
}
}
Parameterized queries would be just as safe, but are more efficient than dynamic SQL statements, especially if you need to execute the same statement multiple times:
std::wstring Utf8Decode(char *utf8Str, int utf8Len)
{
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, utf8Len, NULL, 0);
if (wLen > 0)
{
std::vector<wchar_t> wStr(wLen);
wLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str, utf8Len, &wStr[0], wLen);
if (wLen > 0)
return std::wstring(&wStr[0], wLen);
}
return std::wstring();
}
MYSQL_STMT *stmt = mysql_stmt_init(&mysql);
if (stmt)
{
std::string query = "SELECT pass FROM users WHERE name=?"
if (mysql_stmt_prepare(stmt, query.c_str(), query.length()) == 0)
{
if (mysql_stmt_param_count(stmt) == 1)
{
std::string utf8User = Utf8Encode(name, lenUser);
unsigned long utf8len = utf8User.length();
MYSQL_BIND param = {0};
param.buffer_type = MYSQL_TYPE_STRING;
param.buffer = utf8User.c_str();
param.buffer_length = utf8len;
param.length = &utf8len;
param.is_unsigned = true;
mysql_stmt_bind_param(stmt, ¶m);
char result[512];
unsigned long resultLen = 0;
MYSQL_BIND result = {0};
param.buffer_type = MYSQL_TYPE_STRING;
param.buffer = &result[0];
param.buffer_length = 512;
param.length = &resultlen;
param.is_unsigned = true;
mysql_stmt_bind_result(stmt, &result);
if (mysql_stmt_execute(stmt) == 0)
{
mysql_stmt_fetch(stmt);
mysql_stmt_free_result(stmt);
SendMessage(passField, WM_SETTEXTW, 0, (LPARAM) Utf8Decode(result, resultLen).c_str());
}
}
}
}
mysql_stmt_close(stmt);
Related
i am coding at an key authentication system with imgui. I use the Download String function to get the key. But the if says that the user input and the downloaded key are not the same.
this is the DownloadString function:
std::string DownloadString(std::string URL) {
HINTERNET interwebs = InternetOpenA("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
HINTERNET urlFile;
std::string rtn;
if (interwebs) {
urlFile = InternetOpenUrlA(interwebs, URL.c_str(), NULL, NULL, NULL, NULL);
if (urlFile) {
char buffer[2000];
DWORD bytesRead;
do {
InternetReadFile(urlFile, buffer, 2000, &bytesRead);
rtn.append(buffer, bytesRead);
memset(buffer, 0, 2000);
} while (bytesRead);
InternetCloseHandle(interwebs);
InternetCloseHandle(urlFile);
std::string p = replaceAll(rtn, "|n", "\r\n");
return p;
}
}
InternetCloseHandle(interwebs);
std::string p = replaceAll(rtn, "|n", "\r\n");
return p;
}
and this is my code:
std::string key = DownloadString("https://pastebin.com/raw/sGjce0HG");
char buf[500]{"Your key here"};
ImGui::InputText("", buf, 500);
std::string user_key = buf;
if (user_key == key)
{
ImGui::Text("key is working");
}
i hope you can help me
I have a function to upload information to a byte array, but it ends with - if (!Httpsendrequest(httprequest, szHeaders, strlen(szhheaders), szRequest, strlen(szRequest)))
string GetUrlData(const string& url, LPCSTR host, string& output)
{
string request_data = "";
output = "";
HINTERNET hIntSession = InternetOpenA("token", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hIntSession)
{
return request_data;
}
HINTERNET hHttpSession = InternetConnectA(hIntSession, host, 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
if (!hHttpSession)
{
return request_data;
}
HINTERNET hHttpRequest = HttpOpenRequestA(hHttpSession, "GET", url.c_str()
, 0, 0, 0, INTERNET_FLAG_RELOAD, 0);
if (!hHttpSession)
{
return request_data;
}
char* szHeaders = ("Content-Type: text/html\r\nUser-Agent: License");
char szRequest[1024] = { 0 };
if (!HttpSendRequestA(hHttpRequest, szHeaders, strlen(szHeaders), szRequest, strlen(szRequest)))
{
qDebug()<<"BLYA";
return request_data;
}
CHAR szBuffer[1024] = { 0 };
DWORD dwRead = 0;
while (InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer) - 1, &dwRead) && dwRead)
{
request_data.append(szBuffer, dwRead);
}
InternetCloseHandle(hHttpRequest);
InternetCloseHandle(hHttpSession);
InternetCloseHandle(hIntSession);
output = request_data;
}
The failure might have something to do with the fact that szHeaders is missing \r\n on the User-Agent header. Every header you send ust be terminated with \r\n. And BTW, there is no reason to send a Content-Type header in a GET request, since there is no message body being sent to the server.
Also, your code has a bunch of memory leaks if anything goes wrong. You need to close every handle you successfully open.
Also, there is no point in having both a return value and an output parameter that return the same data. Pick one or the other. I would suggest using a bool return value and a string output parameter.
Try something more like this:
bool GetUrlData(const string& resource, const string& host)
{
output.clear();
bool result = false;
HINTERNET hIntSession = InternetOpenA("token", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hIntSession) {
qDebug() << "InternetOpen failed, error: " << GetLastError();
return false;
}
HINTERNET hHttpSession = InternetConnectA(hIntSession, host.c_str(), 80, 0, 0, INTERNET_SERVICE_HTTP, 0, NULL);
if (!hHttpSession) {
qDebug() << "InternetConnect failed, error: " << GetLastError();
InternetCloseHandle(hIntSession);
return false;
}
HINTERNET hHttpRequest = HttpOpenRequestA(hHttpSession, "GET", resource.c_str(), 0, 0, 0, INTERNET_FLAG_RELOAD, 0);
if (!hHttpRequest) {
qDebug() << "HttpOpenRequest failed, error: " << GetLastError();
InternetCloseHandle(hHttpSession);
InternetCloseHandle(hIntSession);
return false;
}
const char* szHeaders = "User-Agent: License\r\n";
if (!HttpSendRequestA(hHttpRequest, szHeaders, -1, NULL, 0)) {
qDebug() << "HttpSendRequest failed, error: " << GetLastError();
InternetCloseHandle(hHttpRequest);
InternetCloseHandle(hHttpSession);
InternetCloseHandle(hIntSession);
return false;
}
char szBuffer[1024];
DWORD dwRead = 0;
do {
if (!InternetReadFile(hHttpRequest, szBuffer, sizeof(szBuffer), &dwRead)) {
qDebug() << "InternetReadFile failed, error: " << GetLastError();
InternetCloseHandle(hHttpRequest);
InternetCloseHandle(hHttpSession);
InternetCloseHandle(hIntSession);
return false;
}
if (dwRead == 0)
break;
output.append(szBuffer, dwRead);
}
while (true);
return true;
}
I need help with http get. I use vsc++ 2015. I have my own code, but it seems to be wrong, so I get reply from server in a strange format.
Example : 034a0686bc29ca826dbb2f1ea4dd1879═
so the Source is:
#include "Connection.h"
CConnector g_pConnector;
CConnector::CConnector() {
}
CConnector::~CConnector() {
}
void CConnector::Connect(char* Url, char* Host) { m_Url = Url; m_Host = Host; }
void CConnector::SendPOST(const char* data, std::string &sDestBuffer) { try { char httpUseragent[512]; DWORD szhttpUserAgent = sizeof(httpUseragent); ObtainUserAgentString(0, httpUseragent, &szhttpUserAgent);
CString sMsg = ""; sMsg += /*\r\ncontent-type: application/x-www-form-urlencoded*/"\r\ncontent-type: application/x-www-form-urlencoded"; sMsg += /*\r\ncontent-lenght:
*/"\r\ncontent-lenght: "; sMsg += std::to_string(strlen(data)).c_str(); sMsg += /*\r\nuser-agent: secret_agent\r\n\r\n*/"\r\nuser-agent: secret_agent\r\n\r\n";
HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (internet != NULL) {
HINTERNET connect = InternetConnectA(internet, m_Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (connect != NULL) {
HINTERNET request = HttpOpenRequestA(connect, /*POST*/"POST", m_Url, /*HTTP/1.1*/"HTTP/1.1", NULL, NULL,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, NULL);
if (request != NULL)
{
int datalen = 0;
if (data != NULL) datalen = strlen(data);
int headerlen = 0;
if (!sMsg.IsEmpty()) headerlen = strlen(sMsg);
HttpSendRequestA(request, sMsg, headerlen, _strdup(data), datalen);
if (request)
{
DWORD dataSize = 0;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char* data = NULL;
do {
char buffer[2000];
InternetReadFile(request, (LPVOID)buffer, _countof(buffer), &dwBytesRead);
char *tempData = new char[dataSize + dwBytesRead];
memcpy(tempData, data, dataSize);
memcpy(tempData + dataSize, buffer, dwBytesRead);
delete[] data;
data = tempData;
dataSize += dwBytesRead;
} while (dwBytesRead);
sDestBuffer = data;
}
InternetCloseHandle(request);
} } InternetCloseHandle(connect); } InternetCloseHandle(internet); } catch (...) {} }
void CConnector::SendGET(const char* data, std::string &sDestBuffer) { try { char httpUseragent[512]; DWORD szhttpUserAgent = sizeof(httpUseragent); ObtainUserAgentString(0, httpUseragent, &szhttpUserAgent);
CString sMsg = ""; CString Url = m_Url; Url += "?"; Url += data;
HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (internet != NULL) {
HINTERNET connect = InternetConnectA(internet, m_Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (connect != NULL) {
HINTERNET request = HttpOpenRequestA(connect, /*GET*/"GET", Url, /*HTTP/1.1*/"HTTP/1.1", NULL, NULL,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_AUTH |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_PRAGMA_NOCACHE |
INTERNET_FLAG_RELOAD, NULL);
if (request != NULL)
{
int datalen = 0;
if (data != NULL) datalen = strlen(data);
int headerlen = 0;
if (!sMsg.IsEmpty()) headerlen = strlen(sMsg);
HttpSendRequestA(request, sMsg, headerlen, _strdup(data), datalen);
if (request)
{
DWORD dataSize = 0;
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
char* data = NULL;
do {
char buffer[2000];
InternetReadFile(request, (LPVOID)buffer, _countof(buffer), &dwBytesRead);
char *tempData = new char[dataSize + dwBytesRead];
memcpy(tempData, data, dataSize);
memcpy(tempData + dataSize, buffer, dwBytesRead);
delete[] data;
data = tempData;
dataSize += dwBytesRead;
} while (dwBytesRead);
sDestBuffer = data;
}
InternetCloseHandle(request);
} } InternetCloseHandle(connect); }
InternetCloseHandle(internet); } catch (...) {} }
and I try getting reply like this
std::string request;
char key[128];
g_pConnector.Connect(script.php?something=139, "sample.com");
g_pConnector.SendGET(key, request);
Hi guys i am trying to get dll md5 hash but it is returning same value all the time, what i did wrong?
this dll is already loaded when i am trying to getHash
i am getting hash with getHash() method and calculating it with CalcHash
thnks in advanced.
#define BUFSIZE 1024
#define MD5LEN 16
int CalcHash(HANDLE hFile, char *md5sum)
{
BOOL bResult = FALSE;
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[MD5LEN];
DWORD cbHash = 0;
CHAR rgbDigits[] = "0123456789abcdef";
char byt[3];
int rc, err;
rc = CryptAcquireContext(&hProv, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if(!rc)
{
err = GetLastError();
if(err==0x80090016)
{
//first time using crypto API, need to create a new keyset
rc=CryptAcquireContext(&hProv, NULL, MS_STRONG_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET);
if(!rc)
{
err=GetLastError();
return 0;
}
}
}
CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
while(bResult = ReadFile(hFile, rgbFile, BUFSIZE, &cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
CryptHashData(hHash, rgbFile, cbRead, 0);
}
cbHash = MD5LEN;
CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);
md5sum[0] = 0;
for (DWORD i = 0; i < cbHash; i++)
{
sprintf(byt, "%c%c", rgbDigits[rgbHash[i] >> 4], rgbDigits[rgbHash[i] & 0xf]);
strcat(md5sum, byt);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return 1;
}
char *getHash()
{
CalcHash(L"dsetup.dll", md5sum);
Logger(md5sum);
return md5sum;
}
i need help about getting a fist line from a web page, found a little script working with ipchicken.com.
but i connot run it with me web script , posting the original code becouse i was mad about all things ... for that!
i search for that here but i dont find and i post a question ..
but it need to be edit correctly to works with mine php script ..
php > file.php?get=ver or ip on 192.168.1.1 port 88
switch($_GET['get'])
{
case "ip" :
echo ($_SERVER['REMOTE_ADDR']);
break;
case "ver" :
print "0.1.1";
break;
default :
break;
}
here is the original c++ code >
char *getwebpage(char *hostname, char *uri, unsigned long *total)
{
if(!hostname || !uri || !total) return (char *)0;
*total = 0;
char *headers1 = "Accept: text/html, */*\nAccept-Language: en-GB\nAccept-Encoding: none\nHost: ";
char *headers2 = (char *)malloc(strlen(headers1) + strlen(hostname) + 2);
sprintf(headers2, "%s%s\n", headers1, hostname);
HINTERNET session = InternetOpen("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
HINTERNET connect = InternetConnect(session, hostname, 80, "", "", INTERNET_SERVICE_HTTP, 0, 0);
HINTERNET http = HttpOpenRequest(connect, "GET", uri, HTTP_VERSION, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
HttpSendRequest(http, headers2, strlen(headers2), NULL, 0);
free(headers2);
unsigned long read;
char buffer[1024];
char *final = (char *)malloc(1024);
memset(buffer, 0, 1024);
while(InternetReadFile(http, buffer, 1024, &read) && (read != 0)){
CopyMemory((final + *total), buffer, read);
*total += read;
final = (char *)realloc(final, (*total + 1024));
memset((final + *total), 0, 1024);
}
InternetCloseHandle(http);
InternetCloseHandle(connect);
InternetCloseHandle(session);
return final;
}
int getmyipaddress(char *buffer)
{
unsigned long length;
char *webpage = getwebpage("www.ipchicken.com", "/", &length);
if(!webpage || length == 0) return 0;
int result = 0;
char *start = strstr(webpage, "<b>");
if(start){
start += 3;
while(*start <= ' ') start++;
char *end = start;
while(*end > ' ') end++;
*end = 0;
strcpy(buffer, start);
result = 1;
}
free(webpage);
return result;
}
and .. yea how to add a port select like this ->
char *getwebpage(char *hostname, char *uri, char *port, unsigned long *total)
HINTERNET connect = InternetConnect(session, hostname, port, "", "", INTERNET_SERVICE_HTTP, 0, 0);
You say your service is at port 88, but you call:
HINTERNET connect = InternetConnect(session, hostname, 80, ....
so maybe change to:
HINTERNET connect = InternetConnect(session, hostname, 88, ....
Try to do InternetReadFile(http, &buffer, 1024, &read). I am not sure if this will sove your problem but I am quite sure there has to be a pointer to the buffer in the function InternetReadFile() call