Exemplo n.º 1
10
BOOL CFTPCtrl::FtpUploadFile(CString filePath)
{
	HANDLE hOpenFile = (HANDLE)CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
	if(hOpenFile==INVALID_HANDLE_VALUE)
	{
		AfxMessageBox(_T("打开文件失败,请检查文件路径后重试!"));
		CloseHandle(hOpenFile);
		return FALSE;
	}

	CString fileName = GetFileName(filePath);

	HINTERNET hFtpOpen = FtpOpenFile( m_hConnect,fileName, GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0 );
	if ( NULL == hFtpOpen )
	{
		AfxMessageBox(_T("Ftp远程文件打开失败!"));
		return FALSE;
	}
	
	DWORD fileSize=GetFileSize(hOpenFile,NULL);
	char *buffer=new char[fileSize];//最后一位为'/0',C-Style字符串的结束符。
	DWORD readSize;
	if (FALSE==ReadFile(hOpenFile,buffer,fileSize,&readSize,NULL))
	{
		AfxMessageBox(_T("读取本地文件失败!"));
		return FALSE;
	}	
	DWORD dwBytesWritten;
	if (FALSE==InternetWriteFile(  hFtpOpen, buffer,fileSize,&dwBytesWritten))
	{
		AfxMessageBox(_T("上传文件失败!"));
		return FALSE;
	}

	CloseHandle( hOpenFile );
	InternetCloseHandle(hFtpOpen);
	return TRUE;

}
Exemplo n.º 2
0
static HRESULT write_post_stream(Protocol *protocol)
{
    BYTE buf[0x20000];
    DWORD written;
    ULONG size;
    BOOL res;
    HRESULT hres;

    protocol->flags &= ~FLAG_REQUEST_COMPLETE;

    while(1) {
        size = 0;
        hres = IStream_Read(protocol->post_stream, buf, sizeof(buf), &size);
        if(FAILED(hres) || !size)
            break;
        res = InternetWriteFile(protocol->request, buf, size, &written);
        if(!res) {
            FIXME("InternetWriteFile failed: %u\n", GetLastError());
            hres = E_FAIL;
            break;
        }
    }

    if(SUCCEEDED(hres)) {
        IStream_Release(protocol->post_stream);
        protocol->post_stream = NULL;

        hres = protocol->vtbl->end_request(protocol);
    }

    if(FAILED(hres))
        return report_result(protocol, hres);

    return S_OK;
}
Exemplo n.º 3
0
unsigned __stdcall 
CHttp::worker_InternetWriteFile(LPVOID  lp )
{
	INTERNETWRITEFILE		*param = (INTERNETWRITEFILE*)lp;

	return InternetWriteFile (	param->hFile, param->lpBuffer, 
								param->dwNumberOfBytesToWrite, param->lpdwNumberOfBytesWritten );
}
Exemplo n.º 4
0
    void openHTTPConnection (URL_COMPONENTS& uc, URL::OpenStreamProgressCallback* progressCallback,
                             void* progressCallbackContext)
    {
        const TCHAR* mimeTypes[] = { _T("*/*"), 0 };

        DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;

        if (address.startsWithIgnoreCase ("https:"))
            flags |= INTERNET_FLAG_SECURE;  // (this flag only seems necessary if the OS is running IE6 -
                                            //  IE7 seems to automatically work out when it's https)

        request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
                                   uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);

        if (request != 0)
        {
            INTERNET_BUFFERS buffers = { 0 };
            buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
            buffers.lpcszHeader = headers.toWideCharPointer();
            buffers.dwHeadersLength = (DWORD) headers.length();
            buffers.dwBufferTotal = (DWORD) postData.getSize();

            if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
            {
                int bytesSent = 0;

                for (;;)
                {
                    const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
                    DWORD bytesDone = 0;

                    if (bytesToDo > 0
                         && ! InternetWriteFile (request,
                                                 static_cast <const char*> (postData.getData()) + bytesSent,
                                                 (DWORD) bytesToDo, &bytesDone))
                    {
                        break;
                    }

                    if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
                    {
                        if (HttpEndRequest (request, 0, 0, 0))
                            return;

                        break;
                    }

                    bytesSent += bytesDone;

                    if (progressCallback != nullptr
                          && ! progressCallback (progressCallbackContext, bytesSent, (int) postData.getSize()))
                        break;
                }
            }
        }

        close();
    }
fsInternetResult fsHttpFile::Write(LPBYTE pBuffer, DWORD dwSize, DWORD *pdwWritten)
{
	if (m_hFile == NULL)
	{
		if (pdwWritten)
			*pdwWritten = 0;
		return IR_NOTINITIALIZED;
	}		

	if (m_uLeftToUpload == 0)
		return IR_S_FALSE;

	DWORD dwWritten;

	BOOL bRet = InternetWriteFile (m_hFile, pBuffer, dwSize, &dwWritten);

	if (pdwWritten)
		*pdwWritten = dwWritten;

	if (!bRet)
		return fsWinInetErrorToIR ();

	m_uLeftToUpload -= dwWritten;

	if (m_uLeftToUpload == 0)
	{
		if (m_bUseMultipart)
		{
			fsString str = "\r\n"; str += m_strLabel; str += "--\r\n";
			DWORD dw;
			if (FALSE == InternetWriteFile (m_hFile, str, str.GetLength (), &dw))
				return fsWinInetErrorToIR ();
		}

		bRet = HttpEndRequest (m_hFile, NULL, 0, NULL);
		if (!bRet)
			return fsWinInetErrorToIR ();
	}

	return IR_SUCCESS;
}
Exemplo n.º 6
0
unsigned int __stdcall speedtest(void *param)
{
	int i;
	unsigned long started;
	unsigned long elapsed;
	unsigned long speed;
	unsigned long w;
	char fbuf[4096];
	struct spds spd = *(struct spds *)param;
	struct spds *pspd = (struct spds *)param;
	HINTERNET ih = InternetOpen("Mozilla/4.0 (compatible)", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
	HINTERNET ich;
	HINTERNET ftph;
	URL_COMPONENTS url;
	pspd->gotinfo = true;
	url.lpszUserName = (char *)malloc(128);
	url.dwUserNameLength = 128;
	url.lpszPassword = (char *)malloc(128);
	url.dwPasswordLength = 128;
	url.lpszHostName = (char *)malloc(128);
	url.dwHostNameLength = 128;
	url.dwStructSize = sizeof(url);
	InternetCrackUrl(spd.url, 0, 0, &url);
	ich = InternetConnect(ih, url.lpszHostName, url.nPort, url.lpszUserName, url.lpszPassword, INTERNET_SERVICE_FTP, 0, 0);
	if(ich)
	{
		ftph = FtpOpenFile(ich, "speed.test", GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY, 0);
		if(ftph)
		{
			memset(fbuf, 'A', sizeof(fbuf));
			started = GetTickCount() / 1000;
			for(i = 0; i < spd.size * 1024 / 4096; i++)
			{
				InternetWriteFile(ftph, fbuf, sizeof(fbuf), &w);
				elapsed = GetTickCount() / 1000 - started;
			}
			speed = spd.size / ((elapsed) ? elapsed : 1);
			irc_privmsg(spd.target, "speedtest complete (upload speed: %luKB/s)", speed);
		}
	}
	InternetCloseHandle(ftph);
	InternetCloseHandle(ich);
	InternetCloseHandle(ih);
	free(url.lpszUserName);
	free(url.lpszPassword);
	free(url.lpszHostName);
	clearthread(spd.tnum);
	_endthreadex(0);
	return 0;
}
Exemplo n.º 7
0
bool WebIO::UploadFileData(std::string file, std::string data)
{
	WebIO::m_hFile = FtpOpenFileA(WebIO::m_hConnect, file.c_str(), GENERIC_WRITE, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD, 0);

	if (WebIO::m_hFile)
	{
		DWORD size = 0;
		InternetWriteFile(WebIO::m_hFile, data.c_str(), data.size(), &size);
		InternetCloseHandle(WebIO::m_hFile);

		return (size == data.size());
	}

	return false;
}
Exemplo n.º 8
0
BOOL WINAPI my_InternetWriteFile(HINTERNET hFile, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpdwNumberOfBytesWritten)
{
	BOOL Ret = FALSE;

	ENTER_HOOK();

	if (Ret = InternetWriteFile(hFile, lpBuffer, dwNumberOfBytesToWrite, lpdwNumberOfBytesWritten))
	{
		if ((dwNumberOfBytesToWrite) && (lpBuffer))
			IeQueryUrlPostForms(hFile, NULL, (PVOID)lpBuffer, dwNumberOfBytesToWrite);
	}

	LEAVE_HOOK();

	return(Ret);
}
Exemplo n.º 9
0
HRESULT CKpInternetStream::WritePartial(const BYTE* pbBuffer, UINT64 uCount,
	UINT64* puWritten)
{
	EnsureInitialized();

	if(m_hFile == NULL) { if(puWritten != NULL) *puWritten = 0; return STG_E_INVALIDHANDLE; }
	if(pbBuffer == NULL) CKPIS_W_FAIL(E_POINTER);
	if(uCount > static_cast<UINT64>(DWORD_MAX)) CKPIS_W_FAIL(E_INVALIDARG);

	DWORD dwWritten = 0;
	const BOOL bRes = InternetWriteFile(m_hFile, pbBuffer, static_cast<DWORD>(
		uCount), &dwWritten);
	if(bRes == FALSE) CKPIS_W_FAIL(STG_E_WRITEFAULT);

	if(puWritten != NULL) *puWritten = dwWritten;
	return S_OK;
}
Exemplo n.º 10
0
BOOL CHttpRequestSender::WriteTrailingBoundary(HINTERNET hRequest)
{
  BOOL bRet = FALSE;

  CString sText;
  bRet= FormatTrailingBoundary(sText);
  if(!bRet)
    return FALSE;
  
  strconv_t strconv;
  LPCSTR pszText = strconv.t2a(sText);
  if(pszText==NULL)
    return FALSE;

  DWORD dwBytesWritten = 0;
  bRet=InternetWriteFile(hRequest, pszText, (DWORD)strlen(pszText), &dwBytesWritten);
	if(!bRet)
    return FALSE;

  UploadProgress(dwBytesWritten);

  return TRUE;
}
Exemplo n.º 11
0
int HttpConnection::sendData(const char* data, int data_len)
{
    int totalBytesRead = 0;
    int ret = 0;
    DWORD bytesWritten = 0;
    DWORD errorCode = 0;

    if (!InternetWriteFile(req, data, data_len, &bytesWritten)) {
        errorCode = GetLastError();

        char* tmp = createHttpErrorMessage(errorCode);
        setErrorF(errorCode, "InternetWriteFile error %d: %s", errorCode, tmp);
        LOG.info("%s", getLastErrorMsg());
        delete [] tmp; tmp = NULL;
        //
        // The certificate is not trusted. Send the right error code to the
        // client
        //
        if (errorCode == ERROR_INTERNET_INVALID_CA) {
            setError(ERR_HTTPS_INVALID_CA, "The certificate is invalid");
            LOG.error("%s", getLastErrorMsg());

            // try to understand a bit more on the certificate
            INTERNET_CERTIFICATE_INFO   certificateInfo;
            DWORD                       certInfoLength = sizeof(INTERNET_CERTIFICATE_INFO);                
            if (TRUE == InternetQueryOption(req, INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT, 
                &certificateInfo, &certInfoLength)) {

                    char* subj   = (char*)certificateInfo.lpszSubjectInfo;
                    char* issuer = (char*)certificateInfo.lpszIssuerInfo;    
                    LOG.debug("Cert Subject %s", subj);
                    LOG.debug("Cert Issuer %s",  issuer);

            } else {                        
                LOG.debug("Cannot retrieve info about the certificate");
            }     
        } else if (errorCode == ERROR_INTERNET_OFFLINE_MODE) {                     // 00002 -> retry
            LOG.debug("Offline mode detected: go-online and retry...");
            WCHAR* wurl = toWideChar(url.fullURL);
            InternetGoOnline(wurl, NULL, NULL);
            delete [] wurl;
        } else if (errorCode == ERROR_INTERNET_TIMEOUT ||                     // 12002 -> out code 2007
            errorCode == ERROR_INTERNET_INCORRECT_HANDLE_STATE) {      // 12019 -> out code 2007
                setError(ERR_HTTP_TIME_OUT, "Network error: the request has timed out -> exit.");
                LOG.debug("%s", getLastErrorMsg());
        } else if (errorCode == ERROR_INTERNET_CANNOT_CONNECT) {              // 12029 -> out code 2001
            setError(ERR_CONNECT, "Network error: the attempt to connect to the server failed -> exit"); 
            LOG.debug("%s", getLastErrorMsg());
        }
        // Other network error: retry.
        LOG.info("Network error writing data from client");
        resetError();
    }

    if (bytesWritten != data_len) {
        LOG.error("[%s] Warning: possible loss of data: %d bytes read, %d bytes written", 
            __FUNCTION__, data_len, bytesWritten);
    }

    return errorCode;
}
Exemplo n.º 12
0
// Upload file
bool FtpClient::upload(const string & source, const string & destination)
{

	// Check connection
	if (mFtpHnd == NULL)
	{

		// Report error and break
		OutputDebugStringA("Not connected to FTP server:\n");
		showError();
		return false;

	}

	// Check if file exists
	if (!boost::filesystem::exists(boost::filesystem::path(source)))
	{

		// Report error and break
		OutputDebugStringA((string() + "\"" + source + "\" does not exist").c_str());
		return false;

	}

	// Split destination to vector
	vector<string> mPath;
	boost::split(mPath, destination, boost::is_any_of("/"));

	// Iterate through directories
	LPCSTR mFilename;
	for (vector<string>::const_iterator mDirectory = mPath.cbegin(); mDirectory != mPath.cend(); ++mDirectory)
	{

		// End of the line
		if (mDirectory == mPath.end() - 1)
		{

			// Convert to character array
			mFilename = (LPCSTR)mDirectory->c_str();

		}
		else
		{

			// Convert to character array
			LPCSTR nDirectory = (LPCSTR)mDirectory->c_str();

			// Open directory
			if (!FtpSetCurrentDirectoryA(mFtpHnd, nDirectory))
			{

				// Create directory
				if (!FtpCreateDirectoryA(mFtpHnd, nDirectory))
				{

					// Report error and break
					OutputDebugStringA("Unable to create directory:\n");
					showError();
					return false;

				}
				else
				{

					// Open new directory
					if (!FtpSetCurrentDirectoryA(mFtpHnd, nDirectory))
					{

						// Report error and break
						OutputDebugStringA("Unable to open new directory:\n");
						showError();
						return false;

					}

				}

			}

		}

	}

	// Check for existing file
	LPWIN32_FIND_DATAA mInfo = LPWIN32_FIND_DATAA();
	HINTERNET mRemoteFileHnd = FtpFindFirstFileA(mFtpHnd, mFilename, mInfo, INTERNET_FLAG_RELOAD, 0);

	// Clean up memory
	LocalFree(mInfo);
	delete mInfo;

	// File exists
	if (mRemoteFileHnd != NULL)
	{
		
		// Warn
		OutputDebugStringA("File already exists. Overwriting.\n");

		// Close remote file
		InternetCloseHandle(mRemoteFileHnd);

		// Delete file
		if (!FtpDeleteFileA(mFtpHnd, mFilename))
		{

			// Report error and break
			OutputDebugStringA("Unable to delete file from server:\n");
			showError();
			mPath.clear();
			return false;

		}

	}

	// Open remote file for upload
	HINTERNET mFileHnd = FtpOpenFileA(mFtpHnd, mFilename, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY, 0);
	if (mFileHnd == NULL)
	{

		// Report error and break
		OutputDebugStringA("Unable to open remote file:\n");
		showError();
		return false;

	}

	// Open local file
	mFileIO.open(source.c_str(), ios::in|ios::binary|ios::ate);
	mFileSize = (DWORD)mFileIO.tellg();
	mFileIO.seekg(0, ios::beg);

	// Return flag
	bool mUploadSuccess = false;

	// Check file size
	if (mFileSize > 0)
	{

		// Allocate memory for buffer and read file
		mBuffer = new int_fast8_t[mFileSize];
		mFileIO.read(mBuffer, mFileSize);
		
		// Write buffer to remote file
		mBytesWritten = 0;
		mUploadSuccess = InternetWriteFile(mFileHnd, mBuffer, mFileSize, &mBytesWritten) == TRUE;
		if (!mUploadSuccess)
			showError();

		// Clean up
		delete [] mBuffer;

	}

	// Close file, clean up
	mFileIO.close();
	InternetCloseHandle(mFileHnd);
	mFileHnd = NULL;
	mPath.clear();

	// Write result
	OutputDebugStringA(mUploadSuccess ? "File uploaded.\n" : "Upload did not complete.\n");

	// Return flag
	return mUploadSuccess;

}
Exemplo n.º 13
0
bool Download::httpSendReqEx(HINTERNET hConnect, const string &dest,
                             const vector< pair<string, string> > &headers,
                             const string &upFile, const string &outFile, ProgressWindow &pw) const {
  INTERNET_BUFFERS BufferIn;
  memset(&BufferIn, 0, sizeof(BufferIn));
  BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS );

  HINTERNET hRequest = HttpOpenRequest (hConnect, "POST", dest.c_str(), NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);

  DWORD dwBytesRead = 0;
  DWORD dwBytesWritten = 0;
  BYTE pBuffer[4*1024]; // Read from file in 4K chunks

  string hdr;
  for (size_t k = 0; k<headers.size(); k++) {
    if (!trim(headers[k].second).empty()) {
      hdr += headers[k].first + ": " + headers[k].second + "\r\n";
    }
  }

  int retry = 5;
  while (retry>0) {

    HANDLE hFile = CreateFile(upFile.c_str(), GENERIC_READ, FILE_SHARE_READ,
                              NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile == HANDLE(-1))
      return false;


    BufferIn.dwBufferTotal = GetFileSize (hFile, NULL);
    BufferIn.dwHeadersLength = hdr.length();
    BufferIn.lpcszHeader = hdr.c_str();

    double totSize = BufferIn.dwBufferTotal;

    if (!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0)) {
      CloseHandle(hFile);
      InternetCloseHandle(hRequest);
      return false;
    }

    DWORD sum = 0;
    do {
      if (!ReadFile (hFile, pBuffer, sizeof(pBuffer), &dwBytesRead, NULL)) {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        return false;
      }

      if (dwBytesRead > 0) {
        if (!InternetWriteFile(hRequest, pBuffer, dwBytesRead, &dwBytesWritten)) {
          CloseHandle(hFile);
          InternetCloseHandle(hRequest);
          return false;
        }
      }
      sum += dwBytesWritten;

      try {
        pw.setProgress(int(1000 * double(sum) / totSize));
      }
      catch (std::exception &) {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        throw;
      }
    }
    while (dwBytesRead == sizeof(pBuffer)) ;

    CloseHandle(hFile);

    if (!HttpEndRequest(hRequest, NULL, 0, 0)) {
      DWORD error = GetLastError();
      if (error == ERROR_INTERNET_FORCE_RETRY)
        retry--;
      else if (error == ERROR_INTERNET_TIMEOUT) {
        throw std::exception("Fick inget svar i tid (ERROR_INTERNET_TIMEOUT)");
      }
      else {
        InternetCloseHandle(hRequest);
        return false;
      }
    }
    else
      retry = 0; // Done
  }

  DWORD dwStatus = 0;
  DWORD dwBufLen = sizeof(dwStatus);
  int success = HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
                                        (LPVOID)&dwStatus, &dwBufLen, 0);

  if (success) {
    if (dwStatus >= 400) {
      char bf[256];
      switch (dwStatus) {
        case HTTP_STATUS_BAD_REQUEST:
          sprintf_s(bf, "HTTP Error 400: The request could not be processed by the server due to invalid syntax.");
          break;
        case HTTP_STATUS_DENIED:
          sprintf_s(bf, "HTTP Error 401: The requested resource requires user authentication.");
          break;
        case HTTP_STATUS_FORBIDDEN:
          sprintf_s(bf, "HTTP Error 403: Åtkomst nekad (access is denied).");
          break;
        case HTTP_STATUS_NOT_FOUND:
          sprintf_s(bf, "HTTP Error 404: Resursen kunde ej hittas (not found).");
          break;
        case HTTP_STATUS_NOT_SUPPORTED:
          sprintf_s(bf, "HTTP Error 501: Förfrågan stöds ej (not supported).");
          break;
        case HTTP_STATUS_SERVER_ERROR:
          sprintf_s(bf, "HTTP Error 500: Internt serverfel (server error).");
          break;
        default:
          sprintf_s(bf, "HTTP Status Error %d", dwStatus);
      }
      throw dwException(bf, dwStatus);
    }
  }

  int fileno = _open(outFile.c_str(), O_BINARY|O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE);

  do {
    dwBytesRead=0;
    if (InternetReadFile(hRequest, pBuffer, sizeof(pBuffer)-1, &dwBytesRead)) {
      _write(fileno, pBuffer, dwBytesRead);
    }
  } while(dwBytesRead>0);

  _close(fileno);

  InternetCloseHandle(hRequest);
  return true;
}
Exemplo n.º 14
0
BOOL CPostData::UseHttpSendReqEx( std::string& lpost)
{
	USES_CONVERSION;
	long lgg;					CString strtemp;
	lgg = lpost.size();

	INTERNET_BUFFERS BufferIn;
	DWORD dwBytesWritten;

	BOOL bRet;

	TCHAR head[1024];        
	std::wstring strt = MS_CONTENTTYPE;
	std::wstring strt1 = CA2W(CSNManager::GetInstance()->GetSN().c_str());
	//_stprintf_s(head, _countof(head), _T("%s\r\nSN: %s;\r\nMoneyhubuid: %s;\r\n"), strt.c_str() ,strt1.c_str() ,m_strHWID.c_str());
	_stprintf_s(head, _countof(head), _T("Sn: %s\r\nMoneyhubuid: %s\r\n"), strt1.c_str() ,m_strHWID.c_str());
	//TCHAR head[]= strt.c_str(); 

	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL; 
    BufferIn.lpcszHeader = head;
    BufferIn.dwHeadersLength = 0;
    BufferIn.dwHeadersTotal = sizeof(head);
    BufferIn.lpvBuffer = (LPSTR)lpost.c_str();                
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = lgg; // This is the only member used other than dwStructSize
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

	DWORD dwFlags = 0;
		DWORD dwBuffLen = sizeof(dwFlags);
		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

		dwFlags |=	(SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags) );

    if(!HttpSendRequestEx( m_hInetFile, &BufferIn, NULL, 0, 0))
    {
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx");
		CloseHandles();
        printf( "Error on HttpSendRequestEx %d\n",GetLastError() );
        return FALSE;
    }

	bRet=TRUE;
	bRet = InternetWriteFile( m_hInetFile, (LPSTR)lpost.c_str(), lgg, &dwBytesWritten);

	if(!bRet)
	{
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx  InternetWriteFile");
     	CloseHandles();
        printf( "\nError on InternetWriteFile %lu\n",GetLastError() );
        return FALSE;
    }

	bRet = HttpEndRequest(m_hInetFile, NULL, 0, 0);
    if(!bRet)
    {
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx   HttpEndRequest");
    	CloseHandles();
        printf( "Error on HttpEndRequest %lu \n", GetLastError());
        return FALSE;
    }

		char pcBuffer[BUFFSIZE];
		DWORD dwBytesRead;
	    LPSTR	lpszData1;
		lpszData1 = new char[1024*1024];
		lpszData1[0]='\0';

		//printf("\nThe following was returned by the server:\n");
		do
		{	dwBytesRead=0;
			if(InternetReadFile(m_hInetFile, pcBuffer, BUFFSIZE-1, &dwBytesRead))
			{
				pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer
        		strcat(lpszData1,pcBuffer);
				//printf("%s", pcBuffer);
			}
			else
                return FALSE;
				//lpszData1 ="";
				//printf("\nInternetReadFile failed");
		}while(dwBytesRead>0);
		//printf("\n");
		lpost = "";
		lpost = CW2A(UTF8ToUnicode(lpszData1).c_str());
	    delete []lpszData1;

	CloseHandles();
	//return  ERR_SUCCESS;
	return TRUE;
}
fsInternetResult fsHttpFile::OpenEx(LPCSTR pszFilePath, UINT64 uStartPos, UINT64 uUploadPartSize, UINT64 uUploadTotalSize)
{
	if (uUploadTotalSize == _UI64_MAX)
		return Open_imp (pszFilePath, uStartPos, 0);

	if (uStartPos + uUploadPartSize > uUploadTotalSize)
		return IR_INVALIDPARAM;

	if (!m_pServer) 
		return IR_NOTINITIALIZED;

	HINTERNET hServer = m_pServer->GetHandle ();  

	if (!hServer)
		return IR_NOTINITIALIZED;

	CloseHandle ();

	if (lstrlen (pszFilePath) > 9000)
		return IR_BADURL;

	fsString strFilePath = pszFilePath;
	fsString strFileName;
	if (m_bUseMultipart)
	{
		LPSTR psz = strrchr (strFilePath, '/');
		if (psz)
		{
			strFileName = psz + 1;
			psz [1] = 0;
		}
		else
			strFileName = pszFilePath;
	}

	LPTSTR ppszAcceptedTypes [2] = { "*/*", NULL }; 

	m_hFile = HttpOpenRequest (hServer, "POST", strFilePath, m_pszHttpVersion,
		NULL, (LPCSTR*)ppszAcceptedTypes, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION, 0);

	if (m_hFile == NULL)
		return fsWinInetErrorToIR ();

	fsInternetResult ir = SetupProxy ();
	if (ir != IR_SUCCESS)
	{
		CloseHandle ();
		return ir;
	}

	
	CHAR szHdr [10000] = "";
	
	if (m_bUseMultipart)
		lstrcpy (szHdr, "Content-Type: multipart/form-data; boundary=---------------------------284583012225247");
	else
	{
		lstrcpy (szHdr, "Content-Type: application/x-www-form-urlencoded");
		if (m_strCharset.IsEmpty () == FALSE)
		{
			lstrcat (szHdr, "; charset=");
			lstrcat (szHdr, m_strCharset);
		}
	}

	if (uStartPos || uUploadPartSize != uUploadTotalSize)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		sprintf (szHdr + lstrlen (szHdr), "Range: bytes=%I64u-%I64u/%I64u", uStartPos, 
			uStartPos + uUploadPartSize - 1, uUploadTotalSize); 
	}

	if (m_pszCookies)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		sprintf (szHdr + lstrlen (szHdr), "Cookie: %s", m_pszCookies); 
	}

	if (m_pszAdditionalHeaders)
	{
		if (*szHdr)
			lstrcat (szHdr, "\r\n");
		lstrcat (szHdr, m_pszAdditionalHeaders);
	}

	
	IgnoreSecurityProblems ();

	int nSizeAdd = 0;
	fsString strMultipartHdr;

	if (m_bUseMultipart)
	{
		m_strLabel = "-----------------------------284583012225247";

		strMultipartHdr = m_strLabel; strMultipartHdr += "\r\n";
		strMultipartHdr += "Content-Disposition: form-data; name=\"uploadFormFile\"; filename=\"";
		strMultipartHdr += strFileName; strMultipartHdr += "\"\r\n";
		strMultipartHdr += "Content-Type: application/octet-stream\r\n\r\n";

		nSizeAdd = strMultipartHdr.GetLength () + m_strLabel.GetLength () + 6;
	}
 
	INTERNET_BUFFERS BufferIn = {0};
	BufferIn.dwStructSize = sizeof (INTERNET_BUFFERS);
	BufferIn.lpcszHeader = szHdr;
	BufferIn.dwHeadersLength = BufferIn.dwHeadersTotal = lstrlen (szHdr);
	BufferIn.dwBufferTotal = (DWORD) (uUploadPartSize + nSizeAdd);

	if (!HttpSendRequestEx (m_hFile, &BufferIn, NULL, HSR_INITIATE, 0))
	{
		ir = fsWinInetErrorToIR ();
		CloseHandle ();
		return  ir; 
	}

	if (m_bUseMultipart)
	{
		DWORD dw;
		if (FALSE == InternetWriteFile (m_hFile, strMultipartHdr, strMultipartHdr.GetLength (), &dw))
		{
			ir = fsWinInetErrorToIR ();
			CloseHandle ();
			return  ir; 
		}
	}

	m_uLeftToUpload = uUploadPartSize;

	return IR_SUCCESS;
}
Exemplo n.º 16
0
BOOL CHttpRequestSender::WriteAttachmentPart(HINTERNET hRequest, CString sName)
{
  BOOL bRet = FALSE;
    
  /* Write part header */
  CString sHeader;
  bRet= FormatAttachmentPartHeader(sName, sHeader);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error formatting attachment part header."), 0);
    return FALSE;
  }
  
  strconv_t strconv;
  LPCSTR pszHeader = strconv.t2a(sHeader);
  if(pszHeader==NULL)
  {
    m_Assync->SetProgress(_T("Error converting attachment part header to ASCII."), 0);
    return FALSE;
  }

  DWORD dwBytesWritten = 0;
  bRet=InternetWriteFile(hRequest, pszHeader, (DWORD)strlen(pszHeader), &dwBytesWritten);
	if(!bRet)
  {
    m_Assync->SetProgress(_T("Error uploading attachment part header."), 0);
    return FALSE;
  }
  UploadProgress(dwBytesWritten);

  /* Write attachment data */

  std::map<CString, CHttpRequestFile>::iterator it = m_Request.m_aIncludedFiles.find(sName);
  if(it==m_Request.m_aIncludedFiles.end())
  {
    m_Assync->SetProgress(_T("Error searching for attachment part name."), 0);
    return FALSE; 
  }

  CString sFileName = it->second.m_sSrcFileName.GetBuffer(0);
  HANDLE hFile = CreateFile(sFileName, 
     GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); 
  if(hFile==INVALID_HANDLE_VALUE)
  {    
    m_Assync->SetProgress(_T("Error opening attachment file."), 0);
    return FALSE; 
  }

  BYTE pBuffer[1024];
  DWORD dwBytesRead = 0;
  for(;;)
  {
    if(m_Assync->IsCancelled())
      return FALSE;

    bRet = ReadFile(hFile, pBuffer, 1024, &dwBytesRead, NULL);
    if(!bRet)
    {
      m_Assync->SetProgress(_T("Error reading data from attachment file."), 0);
      CloseHandle(hFile);
      return FALSE;
    }

    if(dwBytesRead==0)
      break; // EOF

    DWORD dwBytesWritten = 0;
    bRet=InternetWriteFile(hRequest, pBuffer, dwBytesRead, &dwBytesWritten);
	  if(!bRet)
    {
      m_Assync->SetProgress(_T("Error uploading attachment part data."), 0);
      return FALSE;
    }
    UploadProgress(dwBytesWritten);
  }

  CloseHandle(hFile);

  /* Write part footer */

  CString sFooter;
  bRet= FormatAttachmentPartFooter(sName, sFooter);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error formatting attachment part footer."), 0);
    return FALSE;
  }
  
  LPCSTR pszFooter = strconv.t2a(sFooter);
  if(pszFooter==NULL)
  {
    m_Assync->SetProgress(_T("Error converting attachment part footer to ASCII."), 0);
    return FALSE;
  }

  bRet=InternetWriteFile(hRequest, pszFooter, (DWORD)strlen(pszFooter), &dwBytesWritten);
	if(!bRet)
  {
    m_Assync->SetProgress(_T("Error uploading attachment part footer."), 0);
    return FALSE;
  }
  UploadProgress(dwBytesWritten);

  return TRUE;
}
Exemplo n.º 17
0
BOOL CHttpRequestSender::WriteTextPart(HINTERNET hRequest, CString sName)
{
  BOOL bRet = FALSE;
    
  /* Write part header */
  CString sHeader;
  bRet= FormatTextPartHeader(sName, sHeader);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error formatting text part header."), 0);
    return FALSE;
  }
  
  strconv_t strconv;
  LPCSTR pszHeader = strconv.t2a(sHeader);
  if(pszHeader==NULL)
  {
    m_Assync->SetProgress(_T("Error converting text part header to ASCII."), 0);
    return FALSE;
  }

  DWORD dwBytesWritten = 0;
  bRet=InternetWriteFile(hRequest, pszHeader, (DWORD)strlen(pszHeader), &dwBytesWritten);
	if(!bRet)
  {
    m_Assync->SetProgress(_T("Error uploading text part header."), 0);
    return FALSE;
  }
  UploadProgress(dwBytesWritten);

  /* Write form data */

  std::map<CString, std::string>::iterator it = m_Request.m_aTextFields.find(sName);
  if(it==m_Request.m_aTextFields.end())
  {
    m_Assync->SetProgress(_T("Error searching for text part header name."), 0);
    return FALSE; 
  }
  
  size_t nDataSize = it->second.length();
  int pos = 0;    
  DWORD dwBytesRead = 0;
  for(;;)
  {
    if(m_Assync->IsCancelled())
    {
      return FALSE;
    }

    dwBytesRead = (DWORD)MIN(1024, nDataSize-pos);    
    if(dwBytesRead==0)
      break; // EOF

    std::string sBuffer = it->second.substr(pos, dwBytesRead);
    
    DWORD dwBytesWritten = 0;
    bRet=InternetWriteFile(hRequest, sBuffer.c_str(), dwBytesRead, &dwBytesWritten);
	  if(!bRet)
    {
      m_Assync->SetProgress(_T("Error uploading text part data."), 0);
      return FALSE;
    }
    UploadProgress(dwBytesWritten);

    pos += dwBytesRead;    
  }

  /* Write part footer */

  CString sFooter;
  bRet= FormatTextPartFooter(sName, sFooter);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error formatting text part footer."), 0);
    return FALSE;
  }
  
  LPCSTR pszFooter = strconv.t2a(sFooter);
  if(pszFooter==NULL)
  {
    m_Assync->SetProgress(_T("Error converting text part footer to ASCII."), 0);
    return FALSE;
  }

  bRet=InternetWriteFile(hRequest, pszFooter, (DWORD)strlen(pszFooter), &dwBytesWritten);
	if(!bRet)
  {
    m_Assync->SetProgress(_T("Error uploading text part footer."), 0);
    return FALSE;
  }
  UploadProgress(dwBytesWritten);

  return TRUE;
}
Exemplo n.º 18
0
BOOL CHttpUploadFileProc::UseHttpSendReqEx(HINTERNET hRequest, CFile &file)
{
    //	生成form-data协议信息	<begin>
    CStringA	straHeader;
    CStringA	straContentHead;
    CStringA	straContentTail;

    straHeader = GetHttpAppendHeader();
    straContentHead = GetContentHead(file.GetFileName());
    straContentTail = GetContentTail();
    //	生成form-data协议信息	<end>

    ULONGLONG	ullFileLength = file.GetLength();
    DWORD	dwContentLength = straContentHead.GetLength() + (DWORD) ullFileLength + straContentTail.GetLength();

    INTERNET_BUFFERS BufferIn = {0};
    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL;
    //BufferIn.lpcszHeader = NULL;
    //BufferIn.dwHeadersLength = 0;
    BufferIn.lpcszHeader = straHeader.LockBuffer();
    straHeader.UnlockBuffer();
    BufferIn.dwHeadersLength = (DWORD)straHeader.GetLength();
    BufferIn.dwHeadersTotal = 0;
    BufferIn.lpvBuffer = NULL;
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = dwContentLength;
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_SENDING_FILE, 0);
    if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        return FALSE;

    UINT	uProgressBegin = 10;
    UINT	uProgressEnd = 90;
    UINT	uProgressCur = 0;
    UINT	uReadCountSum = 0;


    const UINT uBufSize = 1024;
    BYTE pBuffer[uBufSize];
    UINT uReadCount;
    DWORD dwBytesWritten;
    BOOL bRet;
    float	fSendPercent;
    UINT	uProgressScale;


    //	Write Head
    bRet = InternetWriteFile( hRequest, straContentHead.LockBuffer(), straContentHead.GetLength(), &dwBytesWritten);
    straContentHead.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }

    if (IsTerminated())	return FALSE;
    //	Write file contents
    uReadCountSum = 0;
    bRet = TRUE;
    file.SeekToBegin();
    do {
        if (IsTerminated())	return FALSE;
        uReadCount = file.Read(pBuffer, uBufSize);
        if (0 == uReadCount)
            break;

        if(! InternetWriteFile( hRequest, pBuffer, uReadCount, &dwBytesWritten))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            return FALSE;
        }

        uReadCountSum += uReadCount;
        fSendPercent = (float)uReadCountSum / BufferIn.dwBufferTotal;
        uProgressScale = (UINT) ((uProgressEnd - uProgressBegin) * fSendPercent);
        uProgressCur = uProgressBegin + uProgressScale;
        NotifyReceiver(P_HUF_PROGRESS, uProgressCur);

    } while (uReadCount == uBufSize);

    if (IsTerminated())	return FALSE;
    //	Write Tail
    bRet = InternetWriteFile( hRequest, straContentTail.LockBuffer(), straContentTail.GetLength(), &dwBytesWritten);
    straContentTail.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }
    NotifyReceiver(P_HUF_PROGRESS, uProgressEnd);


    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_WAIT_RESPONSE, 0);
    if (!HttpEndRequest(hRequest, NULL, 0, 0))
    {
        NotifyReceiver(E_HUF_WAIT_RESPONSE_FAILD, 0);
        bRet = FALSE;
    }

    return bRet;
}
Exemplo n.º 19
0
void ResourceHandle::onRequestComplete(LPARAM lParam)
{
    if (d->m_writing) {
        DWORD bytesWritten;
        InternetWriteFile(d->m_secondaryHandle,
                          d->m_formDataString + (d->m_formDataLength - d->m_bytesRemainingToWrite),
                          d->m_bytesRemainingToWrite,
                          &bytesWritten);
        d->m_bytesRemainingToWrite -= bytesWritten;
        if (!d->m_bytesRemainingToWrite) {
            // End the request.
            d->m_writing = false;
            HttpEndRequest(d->m_secondaryHandle, 0, 0, (DWORD_PTR)d->m_jobId);
            free(d->m_formDataString);
            d->m_formDataString = 0;
        }
        return;
    }

    HINTERNET handle = (method() == "POST") ? d->m_secondaryHandle : d->m_resourceHandle;
    BOOL ok = FALSE;

    static const int bufferSize = 32768;
    char buffer[bufferSize];
    INTERNET_BUFFERSA buffers;
    buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
    buffers.lpvBuffer = buffer;
    buffers.dwBufferLength = bufferSize;

    bool receivedAnyData = false;
    while ((ok = InternetReadFileExA(handle, &buffers, IRF_NO_WAIT, (DWORD_PTR)this)) && buffers.dwBufferLength) {
        if (!hasReceivedResponse()) {
            setHasReceivedResponse();
            ResourceResponse response;
            client()->didReceiveResponse(this, response);
        }
        client()->didReceiveData(this, buffer, buffers.dwBufferLength, 0);
        buffers.dwBufferLength = bufferSize;
    }

    PlatformDataStruct platformData;
    platformData.errorString = 0;
    platformData.error = 0;
    platformData.loaded = ok;

    if (!ok) {
        int error = GetLastError();
        if (error == ERROR_IO_PENDING)
            return;
        DWORD errorStringChars = 0;
        if (!InternetGetLastResponseInfo(&platformData.error, 0, &errorStringChars)) {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                platformData.errorString = new TCHAR[errorStringChars];
                InternetGetLastResponseInfo(&platformData.error, platformData.errorString, &errorStringChars);
            }
        }
        _RPTF1(_CRT_WARN, "Load error: %i\n", error);
    }
    
    if (d->m_secondaryHandle)
        InternetCloseHandle(d->m_secondaryHandle);
    InternetCloseHandle(d->m_resourceHandle);

    client()->didFinishLoading(this);
    delete this;
}
Exemplo n.º 20
0
bool ResourceHandle::onRequestComplete()
{
    if (!d->m_internetHandle) { // 0 if canceled.
        deref(); // balances ref in start
        return false;
    }

    if (d->m_bytesRemainingToWrite) {
        DWORD bytesWritten;
        InternetWriteFile(d->m_requestHandle,
                          d->m_formData.data() + (d->m_formData.size() - d->m_bytesRemainingToWrite),
                          d->m_bytesRemainingToWrite,
                          &bytesWritten);
        d->m_bytesRemainingToWrite -= bytesWritten;
        if (d->m_bytesRemainingToWrite)
            return true;
        d->m_formData.clear();
    }

    if (!d->m_sentEndRequest) {
        HttpEndRequestW(d->m_requestHandle, 0, 0, reinterpret_cast<DWORD_PTR>(this));
        d->m_sentEndRequest = true;
        return true;
    }

    static const int bufferSize = 32768;
    char buffer[bufferSize];
    INTERNET_BUFFERSA buffers;
    buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
    buffers.lpvBuffer = buffer;
    buffers.dwBufferLength = bufferSize;

    BOOL ok = FALSE;
    while ((ok = InternetReadFileExA(d->m_requestHandle, &buffers, d->m_loadSynchronously ? 0 : IRF_NO_WAIT, reinterpret_cast<DWORD_PTR>(this))) && buffers.dwBufferLength) {
        if (!d->m_hasReceivedResponse) {
            d->m_hasReceivedResponse = true;

            ResourceResponse response;
            response.setURL(firstRequest().url());

            String httpStatusText = queryHTTPHeader(d->m_requestHandle, HTTP_QUERY_STATUS_TEXT);
            if (!httpStatusText.isNull())
                response.setHTTPStatusText(httpStatusText);

            String httpStatusCode = queryHTTPHeader(d->m_requestHandle, HTTP_QUERY_STATUS_CODE);
            if (!httpStatusCode.isNull())
                response.setHTTPStatusCode(httpStatusCode.toInt());

            String httpContentLength = queryHTTPHeader(d->m_requestHandle, HTTP_QUERY_CONTENT_LENGTH);
            if (!httpContentLength.isNull())
                response.setExpectedContentLength(httpContentLength.toInt());

            String httpContentType = queryHTTPHeader(d->m_requestHandle, HTTP_QUERY_CONTENT_TYPE);
            if (!httpContentType.isNull()) {
                response.setMimeType(extractMIMETypeFromMediaType(httpContentType));
                response.setTextEncodingName(extractCharsetFromMediaType(httpContentType));
            }

            if (ResourceHandleClient* resourceHandleClient = client())
                resourceHandleClient->didReceiveResponse(this, response);
        }

        // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
        // -1 means we do not provide any data about transfer size to inspector so it would use
        // Content-Length headers or content size to show transfer size.
        if (ResourceHandleClient* resourceHandleClient = client())
            resourceHandleClient->didReceiveData(this, buffer, buffers.dwBufferLength, -1);
        buffers.dwBufferLength = bufferSize;
    }

    if (!ok && GetLastError() == ERROR_IO_PENDING)
        return true;

    if (ResourceHandleClient* resourceHandleClient = client())
        resourceHandleClient->didFinishLoading(this, 0);

    InternetCloseHandle(d->m_requestHandle);
    InternetCloseHandle(d->m_connectHandle);
    deref(); // balances ref in start
    return false;
}
Exemplo n.º 21
0
CNetDataImpl* CNetRequestImpl::sendStream(common::InputStream* bodyStream)
{
    CNetDataImpl* pNetData = new CNetDataImpl;

    do
    {
        if ( isError() )
            break;

        if ( !HttpAddRequestHeaders( hRequest, szMultipartContType, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE ) )
        {
            pszErrFunction = L"HttpAddRequestHeaders";
            break;
        }

	    INTERNET_BUFFERS BufferIn;
        memset(&BufferIn, 0, sizeof(INTERNET_BUFFERS));
	    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
        BufferIn.dwBufferTotal = bodyStream->available() + strlen(szMultipartPrefix) + strlen(szMultipartPostfix);

        if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        {
            pszErrFunction = L"HttpSendRequestEx";
            break;
        }

	    DWORD dwBytesWritten = 0;
        if ( !InternetWriteFile( hRequest, szMultipartPrefix, strlen(szMultipartPrefix), &dwBytesWritten) )
        {
            pszErrFunction = L"InternetWriteFile";
            break;
        }

        DWORD dwBufSize = 4096;
        char* pBuf = (char*)malloc(dwBufSize);
        int nReaded = 0;

	    do
	    {
            nReaded = bodyStream->read(pBuf,0,dwBufSize);
            if ( nReaded > 0 )
            {
		        if ( !InternetWriteFile( hRequest, pBuf, nReaded, &dwBytesWritten) )
                {
                    pszErrFunction = L"InternetWriteFile";
                    break;
                }
            }
	    }while(nReaded > 0);

        free(pBuf);

        if ( !InternetWriteFile( hRequest, szMultipartPostfix, strlen(szMultipartPostfix), &dwBytesWritten) )
        {
            pszErrFunction = L"InternetWriteFile";
            break;
        }

        if ( !HttpEndRequest(hRequest, NULL, 0, 0) )
        {
            pszErrFunction = L"HttpEndRequest";
            break;
        }

        if ( isError() )
            break;

        readResponse(pNetData);
    }while(0);

    return pNetData;
}
Exemplo n.º 22
0
Arquivo: swas.cpp Projeto: Kerogi/swas
bool SendFile(HANDLE hFile, const TCHAR* sUrl, const char* sVariableName, const char* sFileName) {
	if(!hFile) return false;
	bool result = false;
	LARGE_INTEGER lnSize;
	if(!GetFileSizeEx(hFile, &lnSize)){
		CloseHandle(hFile);
		return false;
	}
	DWORD nDataSize = lnSize.LowPart;
	if(!(nDataSize>0)) {
		CloseHandle(hFile);
		return false;
	}
	std::vector<char> pData(nDataSize);
	DWORD nReadSize = 0; 
	if(!ReadFile(hFile, (void*)&pData[0], nDataSize, &nReadSize, NULL) || !(nReadSize >0) || (nReadSize != nDataSize)) {
		CloseHandle(hFile);
		return false;
	}
	CloseHandle(hFile);

	TCHAR extraInfo[URL_PART_SIZE];
	TCHAR hostName[URL_PART_SIZE];
	TCHAR passwordSet[URL_PART_SIZE];
	TCHAR schemeUrl[URL_PART_SIZE];
	TCHAR fileUrlPath[URL_PART_SIZE];
	TCHAR userName[URL_PART_SIZE];

	URL_COMPONENTS aUrl;
	aUrl.dwStructSize=sizeof(URL_COMPONENTS);
	aUrl.dwHostNameLength=URL_PART_SIZE;
	aUrl.dwPasswordLength=URL_PART_SIZE;
	aUrl.dwSchemeLength=URL_PART_SIZE;
	aUrl.dwUrlPathLength=URL_PART_SIZE;
	aUrl.dwUserNameLength=URL_PART_SIZE;
	aUrl.dwExtraInfoLength=URL_PART_SIZE;
	aUrl.lpszExtraInfo=extraInfo;
	aUrl.lpszHostName=hostName;
	aUrl.lpszPassword=passwordSet;
	aUrl.lpszScheme=schemeUrl;
	aUrl.lpszUrlPath=fileUrlPath;
	aUrl.lpszUserName=userName;

	PCTSTR rgpszAcceptTypes[] = {_T("text/*"), NULL};

	if(!InternetCrackUrl(sUrl, 0, 0, &aUrl)) return false;
	HINTERNET hInternet = InternetOpen(TEXT("swas"),INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hInternet) {
		HINTERNET hConnect = InternetConnect(hInternet,aUrl.lpszHostName, aUrl.nPort, aUrl.lpszUserName, aUrl.lpszHostName, INTERNET_SERVICE_HTTP, 0, 0);
		if(hConnect){
			HINTERNET hReq = HttpOpenRequest(hConnect, TEXT("POST"), aUrl.lpszUrlPath, NULL, NULL, rgpszAcceptTypes, 
				INTERNET_FLAG_NO_UI | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0);
			if(hReq) {
				

				//see http://stackoverflow.com/questions/6407755/how-to-send-a-zip-file-using-wininet-in-my-vc-application
				char sBoundary[HEADERS_MAX_SIZE];
				if(GenerateBoundary(sBoundary, HEADERS_MAX_SIZE, sFileName)) {
					std::stringstream osHeaders;
					std::stringstream osHeadPart;
					std::stringstream osTailPart;
					const char const endl[] = "\r\n"; 

					osHeaders<<"Content-Type: multipart/form-data; boundary="<<sBoundary;

					osHeadPart<<"--"<<sBoundary<<endl;
					osHeadPart<<"Content-Disposition: form-data; ";
					osHeadPart<<"name=\""<<((NULL != sVariableName)?sVariableName:"filearg")<<"\"; ";
					osHeadPart<<"filename=\""<<((NULL != sFileName)?sFileName:"Chrome Tabs")<<"\""<<endl;
					osHeadPart<<"Content-Type: application/octet-stream"<<endl;
					osHeadPart<<endl;

					osTailPart<<endl<<"--"<<sBoundary<<"--"<<endl;

					std::string sHeaders = osHeaders.str();
					std::string sHeadPart = osHeadPart.str();
					std::string sTailPart = osTailPart.str();

					HttpAddRequestHeadersA(hReq, sHeaders.c_str(), -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD); 
				
					INTERNET_BUFFERS bufferIn;

					memset(&bufferIn, 0, sizeof(INTERNET_BUFFERS));

					bufferIn.dwStructSize  = sizeof(INTERNET_BUFFERS);
					bufferIn.dwBufferTotal = sHeadPart.length() + nDataSize + sTailPart.length();
					DWORD bytesWritten;
					if(HttpSendRequestEx(hReq, &bufferIn, NULL, HSR_INITIATE, 0)) {
						InternetWriteFile(hReq, (const void*)sHeadPart.c_str(), sHeadPart.length(), &bytesWritten);

						InternetWriteFile(hReq, (const void*)&pData[0], nDataSize, &bytesWritten);
						// or a while loop for call InternetWriteFile every 1024 bytes...

						InternetWriteFile(hReq, (const void*)sTailPart.c_str(), sTailPart.length(), &bytesWritten);
						result = true;
					}else{
						ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
					}
				}
				HttpEndRequest(hReq, NULL, HSR_INITIATE, 0);

			}else{
				ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
			}
		}else{
			ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
		}
		InternetCloseHandle(hInternet);
	}
	return result;
}
Exemplo n.º 23
0
BOOL CPostData::UseHttpSendReqEx( std::string& lpost)
{
	long lgg;
	lgg = lpost.size();

	USES_CONVERSION;
	INTERNET_BUFFERS BufferIn;
	DWORD dwBytesWritten;

	BOOL bRet;

	TCHAR head[1024];        
	std::wstring strt = MS_CONTENTTYPE;
	std::wstring strt1 = CA2W(CSNManager::GetInstance()->GetSN().c_str());
	_stprintf_s(head, _countof(head), _T("%s\r\nSN: %s;\r\nMoneyhubUID: %s;\r\n"), strt.c_str() ,strt1.c_str() ,m_strHWID.c_str());
	//TCHAR head[]= strt.c_str(); 

	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL; 
    BufferIn.lpcszHeader = head;
    BufferIn.dwHeadersLength = 0;
    BufferIn.dwHeadersTotal = sizeof(head);
    BufferIn.lpvBuffer = (LPSTR)lpost.c_str();                
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = lgg; // This is the only member used other than dwStructSize
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if(!HttpSendRequestEx( m_hInetFile, &BufferIn, NULL, 0, 2))
    {
		CloseHandles();
        printf( "Error on HttpSendRequestEx %d\n",GetLastError() );
        return FALSE;
    }

	bRet=TRUE;
	bRet = InternetWriteFile( m_hInetFile, (LPSTR)lpost.c_str(), lgg, &dwBytesWritten);

	if(!bRet)
	{
     	CloseHandles();
        printf( "\nError on InternetWriteFile %lu\n",GetLastError() );
        return FALSE;
    }

	bRet = HttpEndRequest(m_hInetFile, NULL, 0, 0);
    if(!bRet)
    {
    	CloseHandles();
        printf( "Error on HttpEndRequest %lu \n", GetLastError());
        return FALSE;
    }

		char pcBuffer[BUFFSIZE];
		DWORD dwBytesRead;
	    LPSTR	lpszData1;
		lpszData1 = new char[1024*1024];
		lpszData1[0]='\0';

		//printf("\nThe following was returned by the server:\n");
		do
		{	dwBytesRead=0;
			if(InternetReadFile(m_hInetFile, pcBuffer, BUFFSIZE-1, &dwBytesRead))
			{
				pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer
        		strcat(lpszData1,pcBuffer);
				//printf("%s", pcBuffer);
			}
			else
                return FALSE;
				//lpszData1 ="";
				//printf("\nInternetReadFile failed");
		}while(dwBytesRead>0);
		//printf("\n");
		lpost = "";
		lpost = CW2A(UTF8ToUnicode(lpszData1).c_str());
	    delete []lpszData1;

	CloseHandles();
	//return  ERR_SUCCESS;
	return TRUE;
}
Exemplo n.º 24
0
STDMETHODIMP HttpRequest::Send(IHttpResponse** pVal)
{
    
	HRESULT hr=S_OK;
    
	ATLASSERT(pVal);
	(*pVal)=NULL;
	if(!this->m_szUrl || _tcslen(this->m_szUrl)==0) {
		InfoMsgBox(_T("请先指定请求的目标URL地址!"));
		return hr;
	}
    
	//显示进度
	rcContext.hOpen=this->m_hOpen;
	rcContext.dwPostFileLength=0;
	rcContext.dwPostedLength=0;
	rcContext.dwContentLength=0;
	rcContext.dwReceivedLength=0;
	if (this->m_blShowRequestProgress){
		ZeroMemory(rcContext.szMemo,sizeof(rcContext.szMemo));//STRLEN_DEFAULT);
		_tcscpy_s(rcContext.szMemo,_T("请稍候,正在准备连接..."));
		rcContext.hThread=CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ProgressDialog,0,0,&(rcContext.dwThreadID));
	}

	//请求方法
	TCHAR szUrl[STRLEN_4K]={0};
	_tcscpy_s(szUrl,m_szUrl);
	TCHAR szMethod[STRLEN_SMALL]=_T("POST");
	if(this->m_szMethod && _tcslen(this->m_szMethod)>0){
		ZeroMemory(szMethod,sizeof(szMethod));
		_tcscpy_s(szMethod,m_szMethod);
	}

	//±äÁ¿¶¨Òå
	DWORD dwError=0;
	DWORD dwFlags=0;
	HINTERNET hConnect=0;			//Internetȇȡ
	HINTERNET hRequest=0;			//InternetÁ¬½Ó
	INTERNET_PORT dwPort;

	BOOL postFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÌá½»Îļþ¡£
	HANDLE hPostFile=0;
	DWORD dwPostFileSize=0;

	BOOL sendRequestSucceeded=TRUE;	//·¢ËÍÇëÇóÊÇ·ñ³É¹¦

	DWORD dwSize=0;

	DWORD dwStatusCode=0;	//httpÇëÇóÏìÓ¦´úÂë
	DWORD dwContentLength=0;	//httpÇëÇóÏìÓ¦ÄÚÈݳ¤¶È
	DWORD dwErrorCode=0;	//httpÇëÇóÏìÓ¦´íÎóÂë
	TCHAR szContentType[STRLEN_DEFAULT]={0};	//httpÇëÇóÏìÓ¦ÄÚÈÝÀàÐÍ
	CComBSTR szResText(L"");				//httpÇëÇóÏìÓ¦·µ»Ø½á¹ûÎı¾
	TCHAR* szHeader=NULL;	//httpÇëÇóÏìӦͷÐÅÏ¢

	BOOL getHeanderSucceeded=TRUE;	//»ñÈ¡httpÇëÇóÏìӦͷÐÅÏ¢ÊÇ·ñ³É¹¦

	char readBuffer[STRLEN_1K]={0};	//ÿ´Î¶ÁÈ¡µÄÏìÓ¦ÄÚÈÝ
	DWORD dwCalcLength=0;	//ͨ¹ýÄÚÈݼÆËã³öÀ´µÄContentLength
	
	BOOL responseFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÏìÓ¦ÄÚÈݱ¾µØ±£´æÎļþ
	HANDLE hResponseFile=0;	//ÇëÇóÏìÓ¦ÄÚÈݱ£´æµ½±¾µØÎļþµÄÎļþ¾ä±ú

	int requestCount=1;	//ÇëÇó´ÎÊý
	
	TCHAR szAccept[] = _T("*/*");
	LPTSTR AcceptTypes[2]={0};
	AcceptTypes[0]=szAccept;
	AcceptTypes[1]=NULL;

	
	CComPtr<IHttpResponse> response;	//ÇëÇóÏìÓ¦¶ÔÏó

	//Á¬½Ó
	dwPort=this->m_usUrlPort;	//¶Ë¿ÚºÅ
	dwFlags= INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD |INTERNET_FLAG_KEEP_CONNECTION;
	if (this->m_blUrlIsSSL) dwFlags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
	
	//´ò¿ªÁ¬½Ó
	if ( !(hConnect = InternetConnect(this->m_hOpen,this->m_szUrlHost , dwPort, _T(""),  _T(""), INTERNET_SERVICE_HTTP, 0, (DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet连接错误:%s"));
		goto clean;
	}
	
reconnect:
	//´ò¿ªÇëÇó
	if ( !(hRequest = HttpOpenRequest(hConnect,this->m_szMethod,this->m_szUrlFile, _T("HTTP/1.1"), _T(""),(LPCTSTR*)AcceptTypes, dwFlags ,(DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet打开请求错误:%s"));
		goto clean;
	}
	
	//ÓÐÖ¸¶¨Ìá½»Îļþ
	if (this->m_szPostFile && _tcslen(this->m_szPostFile)) {
		postFileFlag=PathFileExists(this->m_szPostFile);
	}
	
	//Èç¹ûÓÐÌá½»µÄÎļþ
	if(postFileFlag) {
		if ((hPostFile = CreateFile(this->m_szPostFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,(HANDLE)NULL)) == (HANDLE)(-1))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("提交的文件不存在或者无法打开:%s"));			
			goto clean;
		}        
		dwPostFileSize=GetFileSize(hPostFile,NULL);
		rcContext.dwPostFileLength=dwPostFileSize;
		TCHAR szPostFileSize[STRLEN_SMALL]={0};
		_stprintf_s(szPostFileSize,_T("%d"),dwPostFileSize);
		this->AddHeader(T2BSTR(_T("Content-Length")),T2BSTR(szPostFileSize));
	}
	
	//ÉèÖÃÇëÇóÍ·
	if (this->m_szHeader && _tcslen(this->m_szHeader)) {
		if (!HttpAddRequestHeaders(hRequest,this->m_szHeader,-1L,HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("设置请求头错误:%s"));
			goto clean;
		}
	}
	/*
	InternetSetOption(FhRequest,     
                  INTERNET_OPTION_CLIENT_CERT_CONTEXT,   
                  (LPVOID)pdDesiredCert,     
                  sizeof(CERT_CONTEXT));   
 INTERNET_FLAG_KEEP_CONNECTION£¬INTERNET_FLAG_EXISTING_CONNECT
	*/
	//´¦Àí¶îÍâÉèÖ㨺öÂÔһЩ´íÎó£©
	dwFlags=0;
	dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA|SECURITY_FLAG_IGNORE_REVOCATION|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS|SECURITY_FLAG_IGNORE_CERT_DATE_INVALID|SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
	if (!InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("设置请求选项错误:%s"));
		goto clean;
	}
	
	//·¢ËÍÇëÇó
again:
	if(postFileFlag){	//ÓÐÌá½»ÎļþÄÚÈÝ
		INTERNET_BUFFERS BufferIn = {0};
		DWORD dwBytesWritten;
		BYTE bts[STRLEN_1K]={0};
		DWORD dwBtsRead=0;
		DWORD dwTotalBytes=0;

		BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
		BufferIn.Next=NULL;
		BufferIn.dwBufferTotal=dwPostFileSize;

		sendRequestSucceeded=HttpSendRequestEx(hRequest, &BufferIn, NULL, HSR_INITIATE,(DWORD)&rcContext);
		
		while(ReadFile(hPostFile, bts, STRLEN_1K, &dwBtsRead, NULL) && dwBtsRead>0 && dwTotalBytes<=dwPostFileSize){
			if (!InternetWriteFile(hRequest, bts,dwBtsRead, &dwBytesWritten))
			{
				dwError=GetLastError();
				ErrorMsgBox(dwError,_T("发送文件内容错误:%s"));
				goto clean;
			}
			dwTotalBytes+=dwBtsRead;
			rcContext.dwPostedLength=dwTotalBytes;
		}
		
		if(!HttpEndRequest(hRequest, NULL, 0, 0))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("关闭HTTP连接时错误:%s"));
			goto clean;
		}
	}//if end
	else{	//ûÓÐÌá½»ÎļþÄÚÈÝ
		sendRequestSucceeded=HttpSendRequest(hRequest, NULL, 0, NULL, 0);
	}	//else end

	//²é¿´ÊÇ·ñÇëÇó·¢Ëͳɹ¦
	if (!sendRequestSucceeded){
		dwError=GetLastError();
		switch(dwError){
			case ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED:
				if(InternetErrorDlg(GetDesktopWindow(),hRequest,ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,FLAGS_ERROR_UI_FILTER_FOR_ERRORS|FLAGS_ERROR_UI_FLAGS_GENERATE_DATA|FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,NULL)!=ERROR_SUCCESS)
				{
					requestCount++;
					if (requestCount>2) {
						InfoMsgBox(_T("已经尝试发送请求操作2次仍无法成功,请联系系统管理员!"));
						goto clean;
					}	//Èç¹ûÑ­»·ÇëÇó´ÎÊý¶àÓÚÁ½´Î£¬ÄÇô²»ÔÙÑ­»·
					else goto again;
				}
				break;
			case ERROR_SUCCESS:
				break;
			default:
				ErrorMsgBox(dwError,_T("发送请求错误:%s"));
				goto clean;
		}//switch end
	}//if end

	//È¡ÏìӦ״̬ÏûÏ¢
	dwSize= sizeof(DWORD);
	if (!HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatusCode, &dwSize, NULL))
	{
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("获取响应代码错误:%s"));
		goto clean;
	}

	switch(dwStatusCode){
		case HTTP_STATUS_DENIED:	//ÐèÒªµÇ¼
		case HTTP_STATUS_PROXY_AUTH_REQ:
			InfoMsgBox(_T("请求的地址需要登录,请您先登录后再发送请求!"));
			goto clean;
		case HTTP_STATUS_REDIRECT:	//Öض¨Ïò
		case HTTP_STATUS_MOVED:
			{
				TCHAR szRedirect[4096]={0};
				DWORD dwRedirect=sizeof(szRedirect);
				if (!HttpQueryInfo(hRequest,HTTP_QUERY_LOCATION,(LPVOID)szRedirect,&dwRedirect,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(hr,_T("获取重定向地址错误:%s"));
					goto clean;
				}
				this->put_Url(szRedirect);
				//ÏȹرÕÁ¬½ÓºÍÇëÇó£¬È»ºóÖØÐÂÁ¬½Ó
				if (!InternetCloseHandle(hRequest))
				{
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("关闭HTTP请求错误:%s"));
					goto clean;
				}
				//if (!InternetCloseHandle(hConnect))
				//{
				//	dwError=GetLastError();
				//	ErrorMsgBox(dwError,_T("关闭HTTP连接错误:%s"));
				//	goto clean;
				//}
				//MessageBox(0,szRedirect,_T("重定向"),0);
				goto reconnect;
			}
		case HTTP_STATUS_OK:
		default:
			break;
	}

	//¹¹ÔìÇëÇóÏìÓ¦¡£
	response.p=NULL;
	hr=response.CoCreateInstance(_T("YRExchange.HttpResponse"));
	if (FAILED(hr)) {
		ErrorMsgBox(hr,_T("创建HttpResponse错误:%s"));
		goto clean;
	}
	response->put_StatusCode(dwStatusCode);
	response->put_ErrorCode(dwError);

	//ÏìÓ¦ÄÚÈÝ´óС
	dwSize=sizeof(dwContentLength);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER ,&dwContentLength,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容长度错误:%s"));
		//goto clean;
		if (dwContentLength>0) {
			response->put_ContentLength(dwContentLength);
			rcContext.dwContentLength=dwContentLength;
		}
	}

	//ÏìÓ¦ÄÚÈÝÀàÐÍ 
	dwSize=sizeof(szContentType);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_TYPE ,(LPVOID)szContentType,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容类型错误:%s"));
		//goto clean;
		if (_tcslen(szContentType)>0) response->put_ContentType(T2BSTR(szContentType));
	}
	
	//ËùÓÐÏìӦͷÐÅÏ¢
	szHeader=new TCHAR[STRLEN_8K];
	dwSize=STRLEN_8K*sizeof(TCHAR);
getheader:
	getHeanderSucceeded=HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF ,(LPVOID)szHeader,&dwSize,NULL);
	if(!getHeanderSucceeded){
		dwError=GetLastError();
		if (dwError==ERROR_INSUFFICIENT_BUFFER){
			TCHAR szXX[100]={0};
			_stprintf_s(szXX,_T("dwError=%d,dwSize=%d"),dwError,dwSize);
			InfoMsgBox(szXX);
			SAFE_FREE_STRING_PTR(szHeader);
			szHeader=new TCHAR[dwSize+2];
			dwSize+=2;
			dwSize=dwSize*sizeof(TCHAR);
			goto getheader;
		}
		else if (dwError!=ERROR_SUCCESS){
			ErrorMsgBox(dwError,_T("获取请求响应头信息错误:%s"));
			goto clean;
		}
	}
	if(szHeader) response->put_Header(T2BSTR(szHeader));
	//ÏìÓ¦ÄÚÈÝ´¦Àí
	if (this->m_blSaveResponseToFile && this->m_szResponseFile && _tcslen(this->m_szResponseFile)>0 && dwStatusCode != 201){	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½Îļþ
		//´´½¨Îļþ 
		hResponseFile = CreateFile(this->m_szResponseFile,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		if (hResponseFile == INVALID_HANDLE_VALUE) 
		{ 
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("打开响应内容本地保存文件错误:%s"));
			goto clean;
		}
		responseFileFlag=TRUE;
	}
	do{
		ZeroMemory(readBuffer,STRLEN_1K);
		dwSize=0;
		if (!InternetReadFile(hRequest,(LPVOID)readBuffer,sizeof(readBuffer),&dwSize)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("读取请求响应内容错误:%s"));
			goto clean;
		}
		if (dwSize!=0){
			dwCalcLength+=dwSize;
			if (responseFileFlag){	//дÎļþ
				DWORD dwWritten=0;
				if (!WriteFile(hResponseFile,readBuffer,dwSize,&dwWritten,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("写入响应内容本地保存文件错误:%s"));
					goto clean;
				}
			}
			else{	//×·¼Óµ½ÏàÓ¦Îı¾
				char buffer[STRLEN_1K+2]={0};
				strncpy_s(buffer,readBuffer,dwSize);
				if (szResText) szResText.Append(buffer);
			}
			if (dwCalcLength==dwContentLength) break;
			rcContext.dwReceivedLength=dwCalcLength;
		}//if end
	}while(dwSize!=0);
	
	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½ÏìÓ¦Îı¾
	if (!responseFileFlag){
		response->put_ContentText(szResText.Detach());
	}//
	//×ÊÔ´»ØÊÕ
clean:
	//¹Ø±ÕÎļþ
	if(hPostFile) CloseHandle(hPostFile);
	if(hResponseFile) {
		FlushFileBuffers(hResponseFile);
		CloseHandle(hResponseFile);
	}

	//»ØÊÕhttpÁ¬½ÓºÍÇëÇó¾ä±ú
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnect) InternetCloseHandle(hConnect);

	//¹Ø±Õ״̬¿ò
	//if (this->m_blShowRequestProgress) WaitForMultipleObjects(1,&rcContext.hThread,TRUE,INFINITE); 
	if (this->m_blShowRequestProgress) EndDialog(rcContext.hProgressWnd,0);

	SAFE_FREE_STRING_PTR(szHeader);

	response.CopyTo(pVal);

	return S_OK;
}
Exemplo n.º 25
0
BOOL baidu_upload(CString sfile, CString token, CString fname,DWORD *process)
{
	if (sfile == L"")
	{
		MessageBox(NULL, L"Îļþ·¾¶²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (token == L"")
	{
		MessageBox(NULL, L"token²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (fname == L"")
	{
		MessageBox(NULL, L"ÎļþÃû²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}

	CString url(L"/rest/2.0/pcs/file?method=upload&ondup=overwrite&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);

	DWORD total_length = 0;//ÉÏ´«Êý¾Ý×Ü´óС
	DWORD file_length = 0;//ÉÏ´«ÎļþµÄ´óС
	//DWORD read_length = 0;//ÒѾ­´ÓÎļþ¶ÁÈ¡µÄ´óС
	DWORD sent_length = 0;//ÒѾ­ÉÏ´«µÄÎļþµÄ´óС

	DWORD sent_bfleng = 0;//µ±Ç°Êý¾Ý¿éÒÑÉÏ´«´óС

	DWORD head_length = 0;//Êý¾ÝÍ·´óС
	DWORD tail_length = 0;//Êý¾Ýβ´óС



	DWORD read_part = 1024 * 1024 * 2;
	DWORD send_part = 1024;

	DWORD read_tmp = 0;//µ±Ç°´ÓÎļþ¶ÁÈ¡µ½»º³åÇøµÄ´óС
	DWORD sent_tmp = 0;//µ±Ç°·¢ËÍ´óС


	CFile cfile(sfile, CFile::modeRead);
	file_length = (DWORD)cfile.GetLength();
	CHAR *send_buffer = new CHAR[read_part];


	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(fname, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, L"pcs.baidu.com", 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, L"POST", url, NULL, NULL, NULL, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_RELOAD, 0);

	TCHAR ct[] = L"Content-Type: multipart/form-data; boundary=--myself";
	HttpAddRequestHeaders(hRequest, ct, lstrlen(ct), HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);


	CHAR head[] = "----myself\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\"\r\n\r\n";
	CHAR tail[] = "\r\n----myself--\r\n";
	head_length = strlen(head);
	tail_length = strlen(tail);

	total_length = file_length + head_length + tail_length;

	INTERNET_BUFFERS Ibuffer;
	ZeroMemory(&Ibuffer, sizeof(INTERNET_BUFFERS));
	Ibuffer.dwBufferTotal = total_length;
	Ibuffer.dwStructSize = sizeof(INTERNET_BUFFERS);

	HttpSendRequestEx(hRequest, &Ibuffer, NULL, 0, NULL);

	InternetWriteFile(hRequest, head, head_length, &sent_tmp);
	sent_length += sent_tmp;

	while (read_tmp = cfile.Read(send_buffer, read_part))
	{
		sent_bfleng = 0;
		while (sent_bfleng != read_tmp)
		{
			if (read_tmp - sent_bfleng > send_part)
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, send_part, &sent_tmp);
			}
			else
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, read_tmp - sent_bfleng, &sent_tmp);
			}
			if (sent_tmp == 0)
			{
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				delete[] send_buffer;
				return FALSE;
			}
			sent_bfleng += sent_tmp;
			sent_length += sent_tmp;
			*process = (DWORD)(100 * (double)sent_length / total_length);
		}
	}

	InternetWriteFile(hRequest, tail, tail_length, &sent_tmp);
	sent_length += sent_tmp;
	*process = (DWORD)(100 * (double)sent_length / total_length);

	HttpEndRequest(hRequest, NULL, 0, NULL);
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] send_buffer;


	return TRUE;

}
Exemplo n.º 26
0
BOOL CNetFile::DoThread(LPVOID pData)
{_STT();
	if ( !m_bUpload )
	{
		m_dwTransferStatus = NETFILE_DS_DOWNLOADING;

		// Post callback
		DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this );

		DWORD ready = 0;

		// Get available data
		if ( !InternetQueryDataAvailable( m_hFile, &ready, 0, 0 ) )
		{	m_dwTransferError = GetLastError();
			return FALSE;
		} // end if

		// Quit if no more data
		if ( ready == 0 ) return FALSE;

		// Get total length if needed
		if ( m_bGetTotalLength )
		{	m_bGetTotalLength = FALSE;

			// Send the query command
			char bufQuery[ 32 ] = "0";
			DWORD dwLengthBufQuery = sizeof( bufQuery );
			DWORD dwHeaderIndex = 0;
			HttpQueryInfo( m_hFile, HTTP_QUERY_CONTENT_LENGTH,
							bufQuery, &dwLengthBufQuery, &dwHeaderIndex );

			// Did we find the header?
			if ( dwHeaderIndex != ERROR_HTTP_HEADER_NOT_FOUND )

				// Convert length from ASCII string to a DWORD.
				m_dwTotalLength = (DWORD)atol( bufQuery );

		} // end if

		while ( ready )
		{
			// Don't byte of more than this computer can chew
			DWORD size = ( ready < m_dwBlockSize ) ? ready : m_dwBlockSize;

			// Allocate a buffer to save new data
			LPBYTE buf = new BYTE[ size + 1 ];
			if ( buf == NULL )
			{
				m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
				return FALSE;
			} // end if

			// Attempt to read new data
			DWORD	read = 0;
			if ( !InternetReadFile( m_hFile, buf, size, &read ) )
			{			   
				delete [] buf;
				m_dwTransferError = GetLastError();
				return FALSE;
			} // end if

			// Check for end of file
			if ( read == 0 )
			{
				m_dwTransferStatus = NETFILE_DS_DONE;
				return FALSE;
			} // end if

			if ( m_bMem )
			{
				if ( m_pMem != NULL )
				{
					LPBYTE temp = new BYTE[ m_dwDataRead + size + 1 ];
					if ( temp == NULL )
					{
						m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
						return FALSE;
					} // end if
					memcpy( temp, m_pMem, m_dwDataRead );
					memcpy( &temp[ m_dwDataRead ], buf, size );
					temp[ m_dwDataRead + size ] = NULL;
					delete [] m_pMem;
					m_pMem = temp;
				} // end if
				else
				{
					m_pMem = new BYTE[ size + 1 ];
					if ( m_pMem == NULL )
					{
						m_dwTransferError = ERROR_NOT_ENOUGH_MEMORY;
						return FALSE;
					} // end if
					memcpy( m_pMem, buf, size );
					m_pMem[ size ] = NULL;
				} // end else
			} // end if

			// Write the data to the file
			else if ( !m_local.Write( buf, read ) )
			{
				delete [] buf;
				m_dwTransferError = GetLastError();
				return FALSE;
			} // end if

			// Delete buffer
			delete [] buf;

			// Add this to data received
			m_dwDataRead += size;

			// Read the next block
			ready -= size;

		} // end while

	}

	else
	{		
		// Do we have any memory
		if ( m_pMem == NULL || m_dwMemSize == 0 )
		{	m_dwTransferStatus = NETFILE_DS_ERROR;
			return FALSE;
		} // end if

		m_dwTransferStatus = NETFILE_DS_UPLOADING;

		// Post callback
		DoCallback( (WPARAM)m_dwTransferStatus, (LPARAM)this );

		// Don't byte of more than this computer can chew
		DWORD left = m_dwMemSize - m_dwDataWritten;
		DWORD write = ( left < m_dwBlockSize ) ? left : m_dwBlockSize;
		DWORD written = 0;
		
		// Attempt to write some data
		if ( !InternetWriteFile( m_hFile, &m_pMem[ m_dwDataWritten ], write, &written ) )
		{
			m_dwTransferStatus = NETFILE_DS_ERROR;
			m_dwTransferError = GetLastError();
			return FALSE;
		} // end if

		// Count this data
		m_dwDataWritten += written;

		// Have we written all the data?
		if ( m_dwDataWritten == m_dwMemSize )
		{
			m_dwTransferStatus = NETFILE_DS_DONE;
			return FALSE;
		} // end if

	} // end else

	// Wait a bit
	Sleep( 15 );

	// Keep going
	return TRUE; 
}