[英]Problem with wininet C++
有人可以在此功能中發現問題嗎? 我的應用程序發出多個請求,如果第一個請求使用SSL,則應用程序在某些計算機上崩潰(在我的4台計算機和vmware上,它可以正常運行而不會崩潰)。
這是代碼
char Buffer[1024];
DWORD dwRead;
string data;
string Request(string method, string host, string file, string headers,
string post, bool debug, bool SSL)
{
HINTERNET hSession, hDownload, hRequest;
DWORD flag;
DWORD port;
data.empty();
//SSL or not + flag :)
if (SSL)
{
port = INTERNET_DEFAULT_HTTPS_PORT;
flag = INTERNET_FLAG_SECURE; // FLAG_SECURE
}
else
{
port = INTERNET_DEFAULT_HTTP_PORT;
flag = INTERNET_FLAG_RELOAD; //FLAG_RELOAD
}
char * postdata;
postdata = new char[post.size() + 1];
strcpy(postdata, post.c_str());
char * headersdata;
headersdata = new char[headers.size() + 1];
strcpy(headersdata, headers.c_str());
//Actual request
hSession
= InternetOpen(
"Mozilla/5.0 (Windows; U; Windows NT 6.1; sl; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11",
INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hSession)
{
hDownload = InternetConnect(hSession, host.c_str(), port, NULL, NULL,
INTERNET_SERVICE_HTTP, 0, 0);
if (hDownload)
{
hRequest = HttpOpenRequest(hDownload, method.c_str(), file.c_str(),
"HTTP/1.1", NULL, NULL, flag, 0);
if (hRequest)
{
if (strlen(headersdata) && strlen(postdata))
{
HttpSendRequest(hRequest, headersdata, strlen(headersdata),
postdata, strlen(postdata));
}
else
{
HttpSendRequest(hRequest, NULL, 0, NULL, 0);
}
}
}
}
//Writing HTML response in data buffer
while (InternetReadFile(hRequest, Buffer, sizeof(Buffer), &dwRead))
{
if (dwRead == 0)
{
break;
}
Buffer[dwRead] = 0;
data += Buffer;
}
//Debug :)
if (debug)
{
ofstream dbgfile;
dbgfile.open("debug.html");
dbgfile << data;
dbgfile.close();
}
//Close handles
InternetCloseHandle(hSession);
InternetCloseHandle(hDownload);
InternetCloseHandle(hRequest);
return data;
}
謝謝。
首先,使用Buffer
會導致緩沖區溢出。
考慮以下幾行:
while (InternetReadFile(hRequest, Buffer, sizeof(Buffer), &dwRead))
和
Buffer[dwRead] = 0;
由於您在前一行中將sizeof(Buffer)
作為dwNumberOfBytesToRead參數傳遞,因此dwRead
最大值為sizeof(Buffer)
。 如果發生這種情況,則后一行將在Buffer
末尾寫入一個字節。 除非您啟用了運行時安全檢查(Runtime Security Checks),它可以解釋崩潰消息,否則您的數據布局使其不太可能導致崩潰(但這完全是偶然!)。
此外,據我記得,“此應用程序已請求運行時終止它在一個不尋常的方式”的提示信息或者通過assert()
或terminate()
在微軟的實現。 (我目前沒有MSVC,無法驗證)。 我在這段代碼中看不到任何一個的原因,因此如果不是Buffer
溢出,也可以在其他地方查找它。
嘗試刪除strlen:
HttpSendRequest(hRequest, &headers.front(), headers.size(),
&post.front(), post.size());
在這種情況下,該功能將更加安全。
無論如何,請考慮使用“ 崩潰轉儲分析” 。 在這種情況下,您將能夠從“某些計算機”中獲取的故障轉儲中檢查調用堆棧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.