Ejemplo n.º 1
3
BOOL HttpRequest(HTTPREQ* req, const wchar_t* url, const wchar_t* header, DWORD header_length, const char* body, DWORD body_length)
{
	BOOL ret = FALSE;
	req->internet = WinHttpOpen(NULL, NULL, NULL, NULL, NULL);
	if (req->internet != NULL)
	{
		URL_COMPONENTS urlinfo = {0};
		urlinfo.dwStructSize = sizeof(URL_COMPONENTS);
		urlinfo.dwSchemeLength    = (DWORD)-1;
		urlinfo.dwUserNameLength  = (DWORD)-1;
		urlinfo.dwHostNameLength  = (DWORD)-1;
		urlinfo.dwUrlPathLength   = (DWORD)-1;
		urlinfo.dwExtraInfoLength = (DWORD)-1;
		urlinfo.dwPasswordLength  = (DWORD)-1;
		if (WinHttpCrackUrl(url, wcslen(url), 0, &urlinfo))
		{
			if (WinHttpSetTimeouts(req->internet, req->resolveTimeout, req->connectTimeout, req->sendTimeout, req->receiveTimeout))
			{
				TCHAR* host = new TCHAR[urlinfo.dwHostNameLength + 1];
				wmemset(host, 0, urlinfo.dwHostNameLength + 1);
				StrCpyN(host, urlinfo.lpszHostName, urlinfo.dwHostNameLength + 1);
				req->connect = WinHttpConnect(req->internet, host, urlinfo.nPort, 0);
				if (req->connect != NULL)
				{
					if (body == NULL || body_length == 0)
						req->request = WinHttpOpenRequest(req->connect, L"GET", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
					else
						req->request = WinHttpOpenRequest(req->connect, L"POST", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);

					if (req->request != NULL)
					{						
						if (WinHttpSendRequest(req->request, header, header_length, (void*)body, body_length, body_length, 0) && WinHttpReceiveResponse(req->request, 0))
						{
							TCHAR status[16] = {0};
							DWORD size = sizeof(status);
							if (WinHttpQueryHeaders(req->request, WINHTTP_QUERY_STATUS_CODE, NULL, status, &size, 0))
							{
								if (StrCmp(status, L"200") == 0)
								{
									char buffer[4096] = {0};
									DWORD length = 0;
									
									while (TRUE)
									{
										if (WinHttpReadData(req->request, buffer, sizeof(buffer), &length) && length > 0)
										{
											AppendBuffer(&req->buffer, req->dataLength, req->bufferLength, buffer, length);
											length = 0;
										}
										else
											break;
									}				

									ret = TRUE;
								}
							}
						}
					}
				}

				SAFE_DELETE_ARRAY(host);
			}
		}
	}
	
	return ret;
}
Ejemplo n.º 2
1
// POST request to URL
void WinHttpIO::post(HttpReq* req, const char* data, unsigned len)
{
    LOG_debug << "POST target URL: " << req->posturl << " chunked: " << req->chunked;

    if (req->binary)
    {
        LOG_debug << "[sending " << (data ? len : req->out->size()) << " bytes of raw data]";
    }
    else
    {
        LOG_debug << "Sending: " << *req->out;
    }

    WinHttpContext* httpctx;

    WCHAR szURL[8192];
    WCHAR szHost[256];
    URL_COMPONENTS urlComp = { sizeof urlComp };

    urlComp.lpszHostName = szHost;
    urlComp.dwHostNameLength = sizeof szHost / sizeof *szHost;
    urlComp.dwUrlPathLength = (DWORD)-1;
    urlComp.dwSchemeLength = (DWORD)-1;

    httpctx = new WinHttpContext;

    httpctx->httpio = this;
    httpctx->req = req;
    httpctx->gzip = false;

    req->httpiohandle = (void*)httpctx;

    if (MultiByteToWideChar(CP_UTF8, 0, req->posturl.c_str(), -1, szURL,
                            sizeof szURL / sizeof *szURL)
     && WinHttpCrackUrl(szURL, 0, 0, &urlComp))
    {
        if ((httpctx->hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0)))
        {
            httpctx->hRequest = WinHttpOpenRequest(httpctx->hConnect, L"POST",
                                                   urlComp.lpszUrlPath, NULL,
                                                   WINHTTP_NO_REFERER,
                                                   WINHTTP_DEFAULT_ACCEPT_TYPES,
                                                   (urlComp.nScheme == INTERNET_SCHEME_HTTPS)
                                                   ? WINHTTP_FLAG_SECURE
                                                   : 0);

            if (httpctx->hRequest)
            {
                if (proxyUsername.size())
                {
                    LOG_verbose << "Setting proxy credentials";

                    WinHttpSetCredentials(httpctx->hRequest, WINHTTP_AUTH_TARGET_PROXY,
                                          WINHTTP_AUTH_SCHEME_BASIC,
                                          (LPWSTR)proxyUsername.data(), (LPWSTR)proxyPassword.data(), NULL);
                }

                WinHttpSetTimeouts(httpctx->hRequest, 58000, 58000, 0, 0);

                WinHttpSetStatusCallback(httpctx->hRequest, asynccallback,
                                         WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE
                                       | WINHTTP_CALLBACK_FLAG_READ_COMPLETE
                                       | WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE
                                       | WINHTTP_CALLBACK_FLAG_REQUEST_ERROR
                                       | WINHTTP_CALLBACK_FLAG_SECURE_FAILURE
                                       | WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE
                                       | WINHTTP_CALLBACK_FLAG_SEND_REQUEST
                                       | WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE
                                       | WINHTTP_CALLBACK_FLAG_HANDLES,
                                         0);

                LPCWSTR pwszHeaders = req->type == REQ_JSON || !req->buf
                                    ? L"Content-Type: application/json\r\nAccept-Encoding: gzip"
                                    : L"Content-Type: application/octet-stream";

                // data is sent in HTTP_POST_CHUNK_SIZE instalments to ensure
                // semi-smooth UI progress info
                if (req->chunkedout.size())
                {
                    req->outbuf.append(req->chunkedout);
                    req->chunkedout.clear();
                }

                req->chunked = 0;

                httpctx->postlen = data ? len : req->out->size();
                httpctx->postdata = data ? data : req->out->data();

                if (urlComp.nPort == 80)
                {
                    LOG_verbose << "HTTP connection";

                    // HTTP connection: send a chunk of data immediately
                    httpctx->postpos = (httpctx->postlen < HTTP_POST_CHUNK_SIZE)
                                      ? httpctx->postlen
                                      : HTTP_POST_CHUNK_SIZE;
                }
                else
                {
                    LOG_verbose << "HTTPS connection";

                    // HTTPS connection: ignore certificate errors, send no data yet
                    DWORD flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID
                                | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
                                | SECURITY_FLAG_IGNORE_UNKNOWN_CA;

                    WinHttpSetOption(httpctx->hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &flags, sizeof flags);

                    httpctx->postpos = 0;
                }

                if (WinHttpSendRequest(httpctx->hRequest, pwszHeaders,
                                       wcslen(pwszHeaders),
                                       (LPVOID)httpctx->postdata,
                                       httpctx->postpos,
                                       httpctx->postlen,
                                       (DWORD_PTR)httpctx))
                {
                    LOG_verbose << "Request sent";
                    req->status = REQ_INFLIGHT;
                    return;
                }

                LOG_err << "Error sending request: " << req->posturl << "  Code: " << GetLastError();
            }
            else
            {
                LOG_err << "Error opening request: " << req->posturl << "  Code: " << GetLastError();
            }
        }
        else
        {
            LOG_err << "Error connecting to " << req->posturl << "  Code: " << GetLastError();
            httpctx->hRequest = NULL;
        }
    }
    else
    {
        LOG_err << "Error parsing POST URL: " << req->posturl << "  Code: " << GetLastError();
        httpctx->hRequest = NULL;
        httpctx->hConnect = NULL;
    }

    LOG_err << "Request failed";
    req->status = REQ_FAILURE;
}
Ejemplo n.º 3
0
bool KickStats::SetUrl(std::wstring url)
{
	wchar_t szHostName[MAX_PATH] = L"";
	wchar_t szURLPath[MAX_PATH * 4] = L"";
	URL_COMPONENTS urlComp;
	memset(&urlComp, 0, sizeof(urlComp));
	urlComp.dwStructSize = sizeof(urlComp);
	//urlComp.nScheme = INTERNET_SCHEME_HTTPS;
	urlComp.lpszHostName = szHostName;
	urlComp.dwHostNameLength = MAX_PATH;
	urlComp.lpszUrlPath = szURLPath;
	urlComp.dwUrlPathLength = MAX_PATH * 4;
	//urlComp.dwSchemeLength = 1;

	if (!WinHttpCrackUrl(url.c_str(), url.size(), 0, &urlComp))
	{
//		DWORD err = GetLastError();
		MessageBox(NULL, L"not a valid URL", L"error", MB_OK);
		KickLog(L"not a valid URL");
		return false;
	}
	

	m_wsHost = std::wstring(szHostName);
	m_wsPath = std::wstring(szURLPath);

	wchar_t logstr[1024];
	swprintf(logstr, L"host: %s; url-Path: %s", m_wsHost.c_str(), m_wsPath.c_str());
	KickLog(logstr);

	return true;
}
Ejemplo n.º 4
0
// POST request to URL
void WinHttpIO::post(HttpReq* req, const char* data /*= nullptr*/, unsigned len /*= 0*/)
{
	if (debug) {
		cout << "POST target URL: " << req->posturl << endl;

		if (req->binary) {
			cout << "[sending " << req->out->size() << " bytes of raw data]" << endl;
		} else {
			cout << "Sending: " << *req->out << endl;
		}
	}

	WinHttpContext* cpContext = new WinHttpContext;
	req->httpiohandle = (void*)cpContext;

	WCHAR szHost[256] = L"";
	URL_COMPONENTS urlComp = { sizeof(URL_COMPONENTS) };

	urlComp.lpszHostName = szHost;
	urlComp.dwHostNameLength = _countof(szHost);
    urlComp.dwUrlPathLength = (DWORD)-1;
    urlComp.dwSchemeLength = (DWORD)-1;

	try {
		// Crack the URL.
		std::wstring strURL = ConvertUTF16fromUTF8(req->posturl);
		BOOL bRet = WinHttpCrackUrl(strURL.c_str(), strURL.length(), 0, &urlComp);
		if (bRet == FALSE)
			throw std::exception("WinHttpCrackUrl failed");

		cpContext->hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0);
		if (cpContext->hConnect == NULL)
			throw std::exception("WinHttpConnect failed");

		cpContext->hRequest = WinHttpOpenRequest(cpContext->hConnect, L"POST", urlComp.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
			(urlComp.nScheme == INTERNET_SCHEME_HTTPS) ? WINHTTP_FLAG_SECURE : 0);
		if (cpContext->hRequest == NULL)
			throw std::exception("WinHttpOpenRequest failed");

		if (data) {
			cpContext->data.assign(data, len);
		}
		req->status = REQ_INFLIGHT;
		cpContext->processThread = std::thread(_ProcessIO, req, cpContext);

		return;
	}
	catch (std::exception& e) {
		cout << e.what() << endl;
		ATLASSERT(FALSE);
	}

	req->status = REQ_FAILURE;
}
Ejemplo n.º 5
0
bool Http::Send(WCHAR szUrl[]) {
	if (this->hSession == NULL) return false;

	HINTERNET		hConnect, hRequest;
	URL_COMPONENTS	urlComponents;
	WCHAR			szHostName[256], szUrlPath[2048];
	LPBYTE			lpHeader, lpData;
	DWORD			dwSize;

	ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS));
	urlComponents.dwStructSize = sizeof(URL_COMPONENTS);
	urlComponents.lpszHostName = szHostName;
	urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR);
	urlComponents.lpszUrlPath = szUrlPath;
	urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR);

	if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) {
		WinHttpCloseHandle(hSession);
		return false;
	}

	hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0);
	if (hConnect == NULL) {
		WinHttpCloseHandle(hSession);
		return false;
	}
	
	hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
	if (hRequest == NULL) {
		WinHttpCloseHandle(hConnect);
		WinHttpCloseHandle(hSession);
		return false;
	}


	if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) {
		WinHttpCloseHandle(hRequest);
		WinHttpCloseHandle(hConnect);
		WinHttpCloseHandle(hSession);
		return false;
	}
	WinHttpReceiveResponse(hRequest, NULL);

	dwSize = 0;
	lpData = ReadData(hRequest, &dwSize);
	HeapFree(GetProcessHeap(), 0, lpData);

	WinHttpCloseHandle(hRequest);
	WinHttpCloseHandle(hConnect);
	WinHttpCloseHandle(hSession);

	return true;
}
Ejemplo n.º 6
0
static HRESULT parse_url( const WCHAR *url, ULONG len, URL_COMPONENTS *uc )
{
    HRESULT hr = E_OUTOFMEMORY;
    WCHAR *tmp;
    DWORD err;

    memset( uc, 0, sizeof(*uc) );
    uc->dwStructSize      = sizeof(*uc);
    uc->dwHostNameLength  = 128;
    uc->lpszHostName      = heap_alloc( uc->dwHostNameLength * sizeof(WCHAR) );
    uc->dwUrlPathLength   = 128;
    uc->lpszUrlPath       = heap_alloc( uc->dwUrlPathLength * sizeof(WCHAR) );
    uc->dwExtraInfoLength = 128;
    uc->lpszExtraInfo     = heap_alloc( uc->dwExtraInfoLength * sizeof(WCHAR) );
    if (!uc->lpszHostName || !uc->lpszUrlPath || !uc->lpszExtraInfo) goto error;

    if (!WinHttpCrackUrl( url, len, ICU_DECODE, uc ))
    {
        if ((err = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
        {
            hr = HRESULT_FROM_WIN32( err );
            goto error;
        }
        if (!(tmp = heap_realloc( uc->lpszHostName, uc->dwHostNameLength * sizeof(WCHAR) ))) goto error;
        uc->lpszHostName = tmp;
        if (!(tmp = heap_realloc( uc->lpszUrlPath, uc->dwUrlPathLength * sizeof(WCHAR) ))) goto error;
        uc->lpszUrlPath = tmp;
        if (!(tmp = heap_realloc( uc->lpszExtraInfo, uc->dwExtraInfoLength * sizeof(WCHAR) ))) goto error;
        uc->lpszExtraInfo = tmp;
        WinHttpCrackUrl( url, len, ICU_DECODE, uc );
    }

    return S_OK;

error:
    heap_free( uc->lpszHostName );
    heap_free( uc->lpszUrlPath );
    heap_free( uc->lpszExtraInfo );
    return hr;
}
Ejemplo n.º 7
0
HINTERNET WinHTTPSession::setup(const Request & request, LPCWSTR method) {
	
	platform::WideString wurl(request.url());
	
	URL_COMPONENTS url;
	ZeroMemory(&url, sizeof(url));
	url.dwStructSize = sizeof(url);
	url.dwSchemeLength = url.dwHostNameLength = url.dwUrlPathLength = DWORD(-1);
	if(WinHttpCrackUrl(wurl, 0, 0, &url) != TRUE) {
		throw new Response("Invalid URL: \"" + request.url() + "\"");
	}
	
	DWORD flags = 0;
	if(url.nScheme == INTERNET_SCHEME_HTTPS) {
		flags |= WINHTTP_FLAG_SECURE;
	} else if(url.nScheme != INTERNET_SCHEME_HTTP) {
		throw new Response("Unsupported protocol");
	}
	
	if(m_scheme != url.nScheme || m_port != url.nPort
	   || m_host.compare(0, m_host.length(), url.lpszHostName, url.dwHostNameLength) != 0) {
		if(m_connection) {
			WinHttpCloseHandle(m_connection);
		}
		m_scheme = url.nScheme;
		m_host.assign(url.lpszHostName, url.dwHostNameLength);
		m_port = url.nPort;
		m_connection = WinHttpConnect(m_session, m_host.c_str(), m_port, 0);
	}
	if(!m_connection) {
		throw new Response("Could not create connection object: " + errorString());
	}
	
	LPCWSTR resource = url.dwUrlPathLength ? url.lpszUrlPath : L"/";
	
	LPCWSTR accept[] = { L"*/*", NULL };
	
	HINTERNET wrequest = WinHttpOpenRequest(m_connection, method, resource, NULL,
	                                        WINHTTP_NO_REFERER, accept, flags);
	if(!wrequest) {
		throw new Response("Could not create request object: " + errorString());
	}
	
	if(request.followRedirects()) {
		WinHttpSetStatusCallback(wrequest, statusCallback, WINHTTP_CALLBACK_FLAG_REDIRECT, 0);
	} else {
		ULONG disable = WINHTTP_DISABLE_REDIRECTS;
		WinHttpSetOption(wrequest, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable));
	}
	
	return wrequest;
}
Ejemplo n.º 8
0
void HttpProtocol::initialize(dictionary* ini, const char* section)
{
	char* url = INI::GetString(ini, section, FS_URL, NULL);
	if(!url) {
		Log::Error("Missing URL for HTTP protocol");
		return;
	}
	Log::Info("Setup session for: %s", url);
	int usz = MultiByteToWideChar(CP_ACP, 0, url, strlen(url), 0, 0);
	this->url = (wchar_t*) malloc((usz + 1) * sizeof(wchar_t));
	MultiByteToWideChar(CP_ACP, 0, url, strlen(url), this->url, usz);
	this->url[usz] = 0;
	memset(&urlc, 0, sizeof(URL_COMPONENTS));
	urlc.dwStructSize = sizeof(URL_COMPONENTS);
	urlc.dwSchemeLength = 1;
	urlc.dwHostNameLength = 1;
	urlc.dwUserNameLength = 1;
	urlc.dwPasswordLength = 1;
	urlc.dwUrlPathLength = 1;
	urlc.dwExtraInfoLength = 1;
	WinHttpCrackUrl(this->url, usz, 0, &urlc);
	this->host = (wchar_t*) malloc((urlc.dwHostNameLength + 1) * sizeof(wchar_t));
	memcpy(this->host, urlc.lpszHostName, urlc.dwHostNameLength*sizeof(wchar_t));
	this->host[urlc.dwHostNameLength] = 0;
	this->path = (wchar_t*) malloc((urlc.dwUrlPathLength + 1) * sizeof(wchar_t));
	memcpy(this->path, urlc.lpszUrlPath, urlc.dwUrlPathLength*sizeof(wchar_t));
	this->path[urlc.dwUrlPathLength] = 0;

	// Determine proxy
	char* proxy = INI::GetString(ini, section, FS_PROXY, NULL);
	if(proxy) {
		Log::Info("Using proxy: %s", proxy);
		int psz = MultiByteToWideChar(CP_ACP, 0, url, strlen(url), 0, 0);
		wchar_t* wproxy = (wchar_t*) malloc((psz + 1) * sizeof(wchar_t));
		MultiByteToWideChar(CP_ACP, 0, proxy, strlen(proxy), wproxy, psz);
		wproxy[psz] = 0;
		hSession = WinHttpOpen(USER_AGENT, WINHTTP_ACCESS_TYPE_NO_PROXY,
			wproxy, 0, 0);
		free(wproxy);
	} else {
		WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxy;
		WinHttpGetIEProxyConfigForCurrentUser(&proxy);
		int proxyType = WINHTTP_ACCESS_TYPE_NO_PROXY;
		if(proxy.lpszProxy) {
			proxyType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
			Log::Info("Using proxy: %s", proxy.lpszProxy);
		}
		hSession = WinHttpOpen(USER_AGENT, proxyType,
			proxy.lpszProxy, proxy.lpszProxyBypass, 0);
	}
}
Ejemplo n.º 9
0
void
HttpRequest::FetchFaviconForDomain()
{
    HANDLE hFile = INVALID_HANDLE_VALUE;
    wchar_t domain[MAX_PATH];
    const wchar_t * domain_ptr = domain;

    {
        URL_COMPONENTS uc;

        memset(&uc, 0, sizeof(uc));
        uc.dwStructSize = sizeof(uc);
        uc.lpszHostName = domain;
        uc.dwHostNameLength = ARRAYLENGTH(domain);

        if (!WinHttpCrackUrl(m_target.c_str(), 0, 0, &uc))
            StringCchCopy(domain, ARRAYLENGTH(domain), m_target.c_str());
    }

    MuteReports();

    do {
        khm_int32 rv;

        rv = FetchResource(domain_ptr, L"/favicon.ico", icon_mimetypes);
        if (KHM_SUCCEEDED(rv) || rv != KHM_ERROR_NOT_FOUND)
            break;

        {
            wchar_t wwwdomain[MAX_PATH];

            if (SUCCEEDED(StringCbPrintf(wwwdomain, sizeof(wwwdomain), L"www.%s", domain_ptr)) &&
                (KHM_SUCCEEDED(FetchResource(wwwdomain, L"/favicon.ico", icon_mimetypes))))
                break;
        }

        domain_ptr = wcschr(domain_ptr, L'.');
        if (domain_ptr)
            domain_ptr++;
    } while(domain_ptr != NULL && *domain_ptr != L'\0');

    MuteReports(false);
    ReportComplete(false);
}
Ejemplo n.º 10
0
bool CWinHttp::CrackURL(LPCWCH url)
{

	bool bRet=false;

	URL_COMPONENTS urlComp;

	DWORD dwUrlLen = 0;

	// Initialize the URL_COMPONENTS structure.
	ZeroMemory(&urlComp, sizeof(urlComp));
	urlComp.dwStructSize = sizeof(urlComp);
	urlComp.lpszHostName=m_strHostName;
	urlComp.lpszUrlPath=m_stUrlPath;

	// Set required component lengths to non-zero so that they are cracked.
	
	urlComp.dwHostNameLength  = 256;
	urlComp.dwUrlPathLength   = 256;
	

	// Crack the URL.
	if( !WinHttpCrackUrl(url,
						NULL,
						ICU_ESCAPE, 
						&urlComp )
						)
	{
		//int n=GetLastError();
		goto exit0;
	}
	
	else
	{
		
		m_dwServiceType=urlComp.nScheme;
		m_Port=urlComp.nPort;
	}
	bRet=true;
exit0:
	assert(bRet!=false);
	return bRet;
}
Ejemplo n.º 11
0
bool WindowsHttpDownloader::StartAsync(const char* url, const char* append_headers)
{
	int len = strlen(url);
	if (len < 8 || len > 2047)
		return false;

	_urls[0] = 0;
	AnsiToUnicode(url, _urls, _countof(_urls));
	RtlZeroMemory(&_url, sizeof(_url));
	_url.dwStructSize = sizeof(_url);
	_url.dwUrlPathLength =
		_url.dwHostNameLength =
		_url.dwExtraInfoLength =
		_url.dwUserNameLength =
		_url.dwPasswordLength =
		_url.dwSchemeLength = -1;
	if (!WinHttpCrackUrl(_urls, 0, 0, &_url))
		return false;
	return ThreadStart(append_headers ? strdup(append_headers) : NULL);
}
Ejemplo n.º 12
0
void
HttpRequest::FetchImageFromURL()
{
    HANDLE hFile = INVALID_HANDLE_VALUE;

    do {
        URL_COMPONENTS uc;
        wchar_t domain[MAX_PATH];

        memset(&uc, 0, sizeof(uc));
        uc.dwStructSize = sizeof(uc);
        uc.lpszHostName = domain;
        uc.dwHostNameLength = ARRAYLENGTH(domain);
        uc.lpszUrlPath = NULL;
        uc.dwUrlPathLength = 1;

        if (!WinHttpCrackUrl(m_target.c_str(), 0, 0, &uc))
            break;

        FetchResource(domain, uc.lpszUrlPath, image_mimetypes);

    } while(FALSE);
}
Ejemplo n.º 13
0
/**
 * Extract the url and password from a URL. The outputs are pointers
 * into the input.
 */
static int userpass_from_url(wchar_t **user, int *user_len,
			     wchar_t **pass, int *pass_len,
			     const wchar_t *url, int url_len)
{
	URL_COMPONENTS components = { 0 };

	components.dwStructSize = sizeof(components);
	/* These tell WinHttpCrackUrl that we're interested in the fields */
	components.dwUserNameLength = 1;
	components.dwPasswordLength = 1;

	if (!WinHttpCrackUrl(url, url_len, 0, &components)) {
		giterr_set(GITERR_OS, "failed to extract user/pass from url");
		return -1;
	}

	*user     = components.lpszUserName;
	*user_len = components.dwUserNameLength;
	*pass     = components.lpszPassword;
	*pass_len = components.dwPasswordLength;

	return 0;
}
Ejemplo n.º 14
0
DWORD HTTPGetFile(String url, char * outHtml, unsigned &bufeLen, CTSTR extraHeaders, int *responseCode)
{
	if (NULL == outHtml || 0 == bufeLen)
	{
		return 1;
	}
	unsigned nMaxBufLen = bufeLen;
	bufeLen = 0;
	HINTERNET hSession = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hRequest = NULL;
	URL_COMPONENTS  urlComponents;
	BOOL secure = FALSE;
	DWORD ret = 1;

	String hostName, path;

	const TCHAR *acceptTypes[] = {
		TEXT("*/*"),
		NULL
	};

	hostName.SetLength(256);
	path.SetLength(1024);

	zero(&urlComponents, sizeof(urlComponents));

	urlComponents.dwStructSize = sizeof(urlComponents);

	urlComponents.lpszHostName = hostName;
	urlComponents.dwHostNameLength = hostName.Length();

	urlComponents.lpszUrlPath = path;
	urlComponents.dwUrlPathLength = path.Length();

	WinHttpCrackUrl(url, 0, 0, &urlComponents);

	if (urlComponents.nPort == 443)
		secure = TRUE;

	hSession = WinHttpOpen(TEXT("ButelLive agent"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	if (!hSession)
		goto failure;

	DWORD dwTimeOut = 5000; // ms
	DWORD dwSize = sizeof(DWORD);
	WinHttpSetOption(hSession, WINHTTP_OPTION_CONNECT_TIMEOUT, &dwTimeOut, dwSize);
	WinHttpSetOption(hSession, WINHTTP_OPTION_SEND_TIMEOUT, &dwTimeOut, dwSize);
	WinHttpSetOption(hSession, WINHTTP_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, dwSize);

	hConnect = WinHttpConnect(hSession, hostName, urlComponents.nPort, 0);
	if (!hConnect)
		goto failure;

	hRequest = WinHttpOpenRequest(hConnect, TEXT("Get"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH);
	if (!hRequest)
		goto failure;


	BOOL bResults = WinHttpSendRequest(
		hRequest,
		extraHeaders,
		extraHeaders ? -1 : 0,
		NULL,
		0,
		0,
		NULL
		);

	// End the request.
	if (bResults)
		bResults = WinHttpReceiveResponse(hRequest, NULL);
	else
		goto failure;

	TCHAR statusCode[8];
	DWORD statusCodeLen;

	statusCodeLen = sizeof(statusCode);
	if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX))
	{
		//ERROR_WINHTTP_HEADER_NOT_FOUND
		int error = GetLastError();
		goto failure;
	}

	*responseCode = wcstoul(statusCode, NULL, 10);

	if (bResults && *responseCode == 200)
	{
		BYTE buffer[16384];
		DWORD dwSize, dwOutSize;
		do
		{
			// Check for available data.
			dwSize = 0;
			if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
				goto failure;

			if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize))
			{
				goto failure;
			}
			else
			{
				if (!dwOutSize)
					break;

				if (bufeLen + dwOutSize > nMaxBufLen)
				{
					goto failure;
				}
				//strHtml.AppendString((CTSTR)buffer, dwOutSize);
				memcpy(outHtml + bufeLen, buffer, dwOutSize);
				bufeLen += dwOutSize;
				outHtml[bufeLen] = '\0';
			}
		} while (dwSize > 0);
	}
	ret = 0;

failure:
	if (0 != ret)
	{
		DWORD dwError = GetLastError();
		if (dwError != 0)
		{
			ret = dwError;
		}
	}

	if (hSession)
		WinHttpCloseHandle(hSession);
	if (hConnect)
		WinHttpCloseHandle(hConnect);
	if (hRequest)
		WinHttpCloseHandle(hRequest);

	return ret;
}
Ejemplo n.º 15
0
BOOL HTTPGetFile (const _TCHAR *url, const _TCHAR *outputPath, const _TCHAR *extraHeaders, int *responseCode)
{
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;
    URL_COMPONENTS  urlComponents;
    BOOL secure = FALSE;
    BOOL ret = FALSE;

    _TCHAR hostName[256];
    _TCHAR path[1024];

    const TCHAR *acceptTypes[] = {
        TEXT("*/*"),
        NULL
    };

    ZeroMemory (&urlComponents, sizeof(urlComponents));

    urlComponents.dwStructSize = sizeof(urlComponents);
    
    urlComponents.lpszHostName = hostName;
    urlComponents.dwHostNameLength = _countof(hostName);

    urlComponents.lpszUrlPath = path;
    urlComponents.dwUrlPathLength = _countof(path);

    WinHttpCrackUrl(url, 0, 0, &urlComponents);

    if (urlComponents.nPort == 443)
        secure = TRUE;

    hSession = WinHttpOpen(_T("OBS Updater/1.2"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession)
    {
        *responseCode = -1;
        goto failure;
    }

    hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0);
    if (!hConnect)
    {
        *responseCode = -2;
        goto failure;
    }

    hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH);
    if (!hRequest)
    {
        *responseCode = -3;
        goto failure;
    }

    BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);
    else
        goto failure;

    TCHAR encoding[64];
    DWORD encodingLen;

    TCHAR statusCode[8];
    DWORD statusCodeLen;

    statusCodeLen = sizeof(statusCode);
    if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX))
    {
        *responseCode = -4;
        goto failure;
    }

    encoding[0] = 0;
    encodingLen = sizeof(encoding);
    if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_CONTENT_ENCODING, WINHTTP_HEADER_NAME_BY_INDEX, encoding, &encodingLen, WINHTTP_NO_HEADER_INDEX))
    {
        if (GetLastError() != ERROR_WINHTTP_HEADER_NOT_FOUND)
        {
            *responseCode = -5;
            goto failure;
        }
    }

    BOOL gzip = FALSE;
    BYTE *outputBuffer = NULL;

    z_stream strm;

    if (!_tcscmp(encoding, _T("gzip")))
    {
        gzip = TRUE;

        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = 0;
        strm.next_in = Z_NULL;
        
        ret = inflateInit2(&strm, 16+MAX_WBITS);

        if (ret != Z_OK)
            goto failure;

        outputBuffer = (BYTE *)malloc(262144);
        if (!outputBuffer)
        {
            *responseCode = -6;
            goto failure;
        }
    }

    *responseCode = wcstoul(statusCode, NULL, 10);

    if (bResults && *responseCode == 200)
    {
        BYTE buffer[32768];
        DWORD dwSize, dwOutSize, wrote;

        HANDLE updateFile;
        int lastPosition = 0;

        updateFile = CreateFile(outputPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
        if (updateFile == INVALID_HANDLE_VALUE)
        {
            *responseCode = -7;
            goto failure;
        }

        do 
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
            {
                *responseCode = -8;
                goto failure;
            }

            dwSize = min(dwSize, sizeof(buffer));

            if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize))
            {
                *responseCode = -9;
                goto failure;
            }
            else
            {
                if (!dwOutSize)
                    break;

                if (gzip)
                {
                    do
                    {
                        strm.avail_in = dwOutSize;
                        strm.next_in = buffer;

                        strm.avail_out = 262144;
                        strm.next_out = outputBuffer;

                        int zret = inflate(&strm, Z_NO_FLUSH);
                        if (zret != Z_STREAM_END && zret != Z_OK)
                        {
                            inflateEnd(&strm);
                            CloseHandle (updateFile);
                            goto failure;
                        }

                        if (!WriteFile(updateFile, outputBuffer, 262144 - strm.avail_out, &wrote, NULL))
                        {
                            *responseCode = -10;
                            CloseHandle (updateFile);
                            goto failure;
                        }
                        if (wrote != 262144 - strm.avail_out)
                        {
                            *responseCode = -11;
                            CloseHandle (updateFile);
                            goto failure;
                        }

                        completedFileSize += wrote;
                    }
                    while (strm.avail_out == 0);
                }
                else
                {
                    if (!WriteFile(updateFile, buffer, dwOutSize, &wrote, NULL))
                    {
                        *responseCode = -12;
                        CloseHandle (updateFile);
                        goto failure;
                    }

                    if (wrote != dwOutSize)
                    {
                        *responseCode = -13;
                        CloseHandle (updateFile);
                        goto failure;
                    }

                    completedFileSize += dwOutSize;
                }

                int position = (int)(((float)completedFileSize / (float)totalFileSize) * 100.0f);
                if (position > lastPosition)
                {
                    lastPosition = position;
                    SendDlgItemMessage (hwndMain, IDC_PROGRESS, PBM_SETPOS, position, 0);
                }
            }

            if (WaitForSingleObject(cancelRequested, 0) == WAIT_OBJECT_0)
            {
                *responseCode = -14;
                CloseHandle (updateFile);
                goto failure;
            }

        } while (dwSize > 0);

        CloseHandle (updateFile);
    }

    ret = TRUE;

failure:
    if (outputBuffer)
        free(outputBuffer);
    if (hSession)
        WinHttpCloseHandle(hSession);
    if (hConnect)
        WinHttpCloseHandle(hConnect);
    if (hRequest)
        WinHttpCloseHandle(hRequest);

    return ret;
}
Ejemplo n.º 16
0
BOOL HTTPGetFile (CTSTR url, CTSTR outputPath, CTSTR extraHeaders, int *responseCode)
{
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;
    URL_COMPONENTS  urlComponents;
    BOOL secure = FALSE;
    BOOL ret = FALSE;

    String hostName, path;

    const TCHAR *acceptTypes[] = {
        TEXT("*/*"),
        NULL
    };

    hostName.SetLength(256);
    path.SetLength(1024);

    zero(&urlComponents, sizeof(urlComponents));

    urlComponents.dwStructSize = sizeof(urlComponents);
    
    urlComponents.lpszHostName = hostName;
    urlComponents.dwHostNameLength = hostName.Length();

    urlComponents.lpszUrlPath = path;
    urlComponents.dwUrlPathLength = path.Length();

    WinHttpCrackUrl(url, 0, 0, &urlComponents);

    if (urlComponents.nPort == 443)
        secure = TRUE;

    hSession = WinHttpOpen(OBS_VERSION_STRING, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession)
        goto failure;

    hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0);
    if (!hConnect)
        goto failure;

    hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH);
    if (!hRequest)
        goto failure;

    BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);
    else
        goto failure;

    TCHAR statusCode[8];
    DWORD statusCodeLen;

    statusCodeLen = sizeof(statusCode);
    if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX))
        goto failure;

    *responseCode = wcstoul(statusCode, NULL, 10);

    if (bResults && *responseCode == 200)
    {
        BYTE buffer[16384];
        DWORD dwSize, dwOutSize;

        XFile updateFile;

        if (!updateFile.Open(outputPath, XFILE_WRITE, CREATE_ALWAYS))
            goto failure;

        do 
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                goto failure;

            if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize))
            {
                goto failure;
            }
            else
            {
                if (!dwOutSize)
                    break;

                if (!updateFile.Write(buffer, dwOutSize))
                    goto failure;
            }
        } while (dwSize > 0);

        updateFile.Close();
    }

    ret = TRUE;

failure:
    if (hSession)
        WinHttpCloseHandle(hSession);
    if (hConnect)
        WinHttpCloseHandle(hConnect);
    if (hRequest)
        WinHttpCloseHandle(hRequest);

    return ret;
}
Ejemplo n.º 17
0
String HTTPGetString (CTSTR url, CTSTR extraHeaders, int *responseCode, String verb)
{
    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;
    URL_COMPONENTS  urlComponents;
    BOOL secure = FALSE;
	String result = "";
	String body = TEXT("");
	String nurl = url;

    String hostName, path;

    const TCHAR *acceptTypes[] = {
        TEXT("*/*"),
        NULL
    };

	if (verb == TEXT("POST")){
		CTSTR s = srchr(url, TEXT('?'));
		body = String(s + 1);
		nurl = nurl.Left(s - url);
	}

    hostName.SetLength(256);
    path.SetLength(1024);

    zero(&urlComponents, sizeof(urlComponents));

    urlComponents.dwStructSize = sizeof(urlComponents);
    
    urlComponents.lpszHostName = hostName;
    urlComponents.dwHostNameLength = hostName.Length();

    urlComponents.lpszUrlPath = path;
    urlComponents.dwUrlPathLength = path.Length();

	WinHttpCrackUrl(nurl, 0, 0, &urlComponents);

    if (urlComponents.nPort == 443)
        secure = TRUE;

    hSession = WinHttpOpen(TEXT("gecko test"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession)
        goto failure;

    hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0);
    if (!hConnect)
        goto failure;

    hRequest = WinHttpOpenRequest(hConnect, verb, path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH);
    if (!hRequest)
        goto failure;

    BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, body.Array(), 
		body.Length(), body.Length(), 0);

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);
    else
        goto failure;

    TCHAR statusCode[8];
    DWORD statusCodeLen;

    statusCodeLen = sizeof(statusCode);
    if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX))
        goto failure;

    *responseCode = wcstoul(statusCode, NULL, 10);	

    if (bResults && *responseCode == 200)
    {
        CHAR buffer[16384];
        DWORD dwSize, dwOutSize;

        do 
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                goto failure;

            if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize))
            {
                goto failure;
            }
            else
            {
                if (!dwOutSize)
                    break;

				// Ensure the string is terminated.
				buffer[dwOutSize] = 0;

				String b = String((LPCSTR)buffer);
				result.AppendString(b);
            }
        } while (dwSize > 0);
    }

failure:
    if (hSession)
        WinHttpCloseHandle(hSession);
    if (hConnect)
        WinHttpCloseHandle(hConnect);
    if (hRequest)
        WinHttpCloseHandle(hRequest);

    return result;
}
/*!
 * @brief Initialise the HTTP(S) connection.
 * @param transport Pointer to the transport instance.
 * @return Indication of success or failure.
 */
static BOOL server_init_winhttp(Transport* transport)
{
	URL_COMPONENTS bits;
	wchar_t tmpHostName[URL_SIZE];
	wchar_t tmpUrlPath[URL_SIZE];
	HttpTransportContext* ctx = (HttpTransportContext*)transport->ctx;

	dprintf("[WINHTTP] Initialising ...");

	// configure proxy
	if (ctx->proxy)
	{
		dprintf("[DISPATCH] Configuring with proxy: %S", ctx->proxy);
		ctx->internet = WinHttpOpen(ctx->ua, WINHTTP_ACCESS_TYPE_NAMED_PROXY, ctx->proxy, WINHTTP_NO_PROXY_BYPASS, 0);
	}
	else
	{
		ctx->internet = WinHttpOpen(ctx->ua, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	}

	if (!ctx->internet)
	{
		dprintf("[DISPATCH] Failed WinHttpOpen: %d", GetLastError());
		return FALSE;
	}

	dprintf("[DISPATCH] Configured hInternet: 0x%.8x", ctx->internet);

	// The InternetCrackUrl method was poorly designed...
	ZeroMemory(tmpHostName, sizeof(tmpHostName));
	ZeroMemory(tmpUrlPath, sizeof(tmpUrlPath));

	ZeroMemory(&bits, sizeof(bits));
	bits.dwStructSize = sizeof(bits);

	bits.dwHostNameLength = URL_SIZE - 1;
	bits.lpszHostName = tmpHostName;

	bits.dwUrlPathLength = URL_SIZE - 1;
	bits.lpszUrlPath = tmpUrlPath;

	dprintf("[DISPATCH] About to crack URL: %S", transport->url);
	WinHttpCrackUrl(transport->url, 0, 0, &bits);

	SAFE_FREE(ctx->uri);
	ctx->uri = _wcsdup(tmpUrlPath);
	transport->comms_last_packet = current_unix_timestamp();

	dprintf("[DISPATCH] Configured URI: %S", ctx->uri);
	dprintf("[DISPATCH] Host: %S Port: %u", tmpHostName, bits.nPort);

	// Allocate the connection handle
	ctx->connection = WinHttpConnect(ctx->internet, tmpHostName, bits.nPort, 0);
	if (!ctx->connection)
	{
		dprintf("[DISPATCH] Failed WinHttpConnect: %d", GetLastError());
		return FALSE;
	}

	dprintf("[DISPATCH] Configured hConnection: 0x%.8x", ctx->connection);

	return TRUE;
}
Ejemplo n.º 19
0
BOOL CSyoboiCalUtil::SendReserve(const vector<RESERVE_DATA>* reserveList, const vector<TUNER_RESERVE_INFO>* tunerList)
{
	if( reserveList == NULL || tunerList == NULL ){
		return FALSE;
	}
	if( reserveList->size() == 0 ){
		return FALSE;
	}

	wstring iniAppPath = L"";
	GetModuleIniPath(iniAppPath);
	if( GetPrivateProfileInt(L"SYOBOI", L"use", 0, iniAppPath.c_str()) == 0 ){
		return FALSE;
	}
	_OutputDebugString(L"★SyoboiCalUtil:SendReserve");

	wstring textPath;
	GetModuleFolderPath(textPath);
	textPath += L"\\SyoboiCh.txt";
	CParseServiceChgText srvChg;
	srvChg.ParseText(textPath.c_str());

	wstring proxyServerName;
	wstring proxyUserName;
	wstring proxyPassword;
	if( GetPrivateProfileInt(L"SYOBOI", L"useProxy", 0, iniAppPath.c_str()) != 0 ){
		proxyServerName = GetPrivateProfileToString(L"SYOBOI", L"ProxyServer", L"", iniAppPath.c_str());
		proxyUserName = GetPrivateProfileToString(L"SYOBOI", L"ProxyID", L"", iniAppPath.c_str());
		proxyPassword = GetPrivateProfileToString(L"SYOBOI", L"ProxyPWD", L"", iniAppPath.c_str());
	}

	wstring id=GetPrivateProfileToString(L"SYOBOI", L"userID", L"", iniAppPath.c_str());

	wstring pass=GetPrivateProfileToString(L"SYOBOI", L"PWD", L"", iniAppPath.c_str());

	int slot = GetPrivateProfileInt(L"SYOBOI", L"slot", 0, iniAppPath.c_str());

	wstring devcolors=GetPrivateProfileToString(L"SYOBOI", L"devcolors", L"", iniAppPath.c_str());
	
	wstring epgurl=GetPrivateProfileToString(L"SYOBOI", L"epgurl", L"", iniAppPath.c_str());

	if( id.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoUserID");
		return FALSE;
	}

	//Authorization
	wstring auth = L"";
	auth = id;
	auth += L":";
	auth += pass;
	string authA;
	WtoA(auth, authA);

	DWORD destSize = 0;
	Base64Enc(authA.c_str(), (DWORD)authA.size(), NULL, &destSize);
	vector<WCHAR> base64(destSize + 1, L'\0');
	Base64Enc(authA.c_str(), (DWORD)authA.size(), &base64.front(), &destSize);
	//無駄なCRLFが混じることがあるため
	std::replace(base64.begin(), base64.end(), L'\r', L'\0');
	std::replace(base64.begin(), base64.end(), L'\n', L'\0');

	wstring authHead = L"";
	Format(authHead, L"Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", &base64.front());

	//data
	wstring dataParam;
	wstring param;
	map<DWORD, wstring> tunerMap;
	for( size_t i=0; i<tunerList->size(); i++ ){
		for( size_t j=0; j<(*tunerList)[i].reserveList.size(); j++ ){
			tunerMap.insert(pair<DWORD, wstring>((*tunerList)[i].reserveList[j], (*tunerList)[i].tunerName));
		}
	}
	map<DWORD, wstring>::iterator itrTuner;
	DWORD dataCount = 0;
	for(size_t i=0; i<reserveList->size(); i++ ){
		if( dataCount>=200 ){
			break;
		}
		const RESERVE_DATA* info = &(*reserveList)[i];
		if( info->recSetting.recMode == RECMODE_NO || info->recSetting.recMode == RECMODE_VIEW ){
			continue;
		}
		wstring device=L"";
		itrTuner = tunerMap.find(info->reserveID);
		if( itrTuner != tunerMap.end() ){
			device = itrTuner->second;
		}

		wstring stationName = info->stationName;
		srvChg.ChgText(stationName);

		__int64 startTime = GetTimeStamp(info->startTime);
		Format(param, L"%I64d\t%I64d\t%s\t%s\t%s\t\t0\t%d\n", startTime, startTime+info->durationSecond, device.c_str(), info->title.c_str(), stationName.c_str(), info->reserveID );
		dataParam+=param;
	}

	if(dataParam.size() == 0 ){
		_OutputDebugString(L"★SyoboiCalUtil:NoReserve");
		return FALSE;
	}

	string utf8;
	UrlEncodeUTF8(dataParam.c_str(), (DWORD)dataParam.size(), utf8);
	string data;
	Format(data, "slot=%d&data=%s",slot, utf8.c_str());

	if( devcolors.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(devcolors.c_str(), (DWORD)devcolors.size(), utf8);
		data += "&devcolors=";
		data += utf8;
	}
	if( epgurl.size() > 0){
		utf8 = "";
		UrlEncodeUTF8(epgurl.c_str(), (DWORD)epgurl.size(), utf8);
		data += "&epgurl=";
		data += utf8;
	}
	vector<char> dataBuff(data.begin(), data.end());

	//URLの分解
	URL_COMPONENTS stURL = {};
	stURL.dwStructSize = sizeof(stURL);
	stURL.dwSchemeLength = (DWORD)-1;
	stURL.dwHostNameLength = (DWORD)-1;
	stURL.dwUrlPathLength = (DWORD)-1;
	stURL.dwExtraInfoLength = (DWORD)-1;
	if( WinHttpCrackUrl(SYOBOI_UP_URL, 0, 0, &stURL) == FALSE || stURL.dwHostNameLength == 0 ){
		return FALSE;
	}
	wstring host(stURL.lpszHostName, stURL.dwHostNameLength);
	wstring sendUrl(stURL.lpszUrlPath, stURL.dwUrlPathLength + stURL.dwExtraInfoLength);

	HINTERNET session;
	if( proxyServerName.empty() ){
		session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	}else{
		session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NAMED_PROXY, proxyServerName.c_str(), WINHTTP_NO_PROXY_BYPASS, 0);
	}
	if( session == NULL ){
		return FALSE;
	}

	LPCWSTR result = L"1";
	HINTERNET connect = NULL;
	HINTERNET request = NULL;

	if( WinHttpSetTimeouts(session, 15000, 15000, 15000, 15000) == FALSE ){
		result = L"0 SetTimeouts";
		goto EXIT;
	}
	//コネクションオープン
	connect = WinHttpConnect(session, host.c_str(), stURL.nPort, 0);
	if( connect == NULL ){
		result = L"0 Connect";
		goto EXIT;
	}
	//リクエストオープン
	request = WinHttpOpenRequest(connect, L"POST", sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
	                             stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ? WINHTTP_FLAG_SECURE : 0);
	if( request == NULL ){
		result = L"0 OpenRequest";
		goto EXIT;
	}
	if( proxyServerName.empty() == false ){
		//ProxyのIDかパスワードがあったらセット
		if( proxyUserName.empty() == false || proxyPassword.empty() == false ){
			if( WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC,
			                          proxyUserName.c_str(), proxyPassword.c_str(), NULL) == FALSE ){
				result = L"0 SetCredentials";
				goto EXIT;
			}
		}
	}
	if( WinHttpSendRequest(request, authHead.c_str(), (DWORD)-1, &dataBuff.front(), (DWORD)dataBuff.size(), (DWORD)dataBuff.size(), 0) == FALSE ){
		result = L"0 SendRequest";
		goto EXIT;
	}
	if( WinHttpReceiveResponse(request, NULL) == FALSE ){
		result = L"0 ReceiveResponse";
		goto EXIT;
	}
	//HTTPのステータスコード確認
	DWORD statusCode;
	DWORD statusCodeSize = sizeof(statusCode);
	if( WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
	                        &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX) == FALSE ){
		statusCode = 0;
	}
	if( statusCode != 200 && statusCode != 201 ){
		result = L"0 StatusNotOK";
		goto EXIT;
	}

EXIT:
	if( request != NULL ){
		WinHttpCloseHandle(request);
	}
	if( connect != NULL ){
		WinHttpCloseHandle(connect);
	}
	if( session != NULL ){
		WinHttpCloseHandle(session);
	}

	_OutputDebugString(L"★SyoboiCalUtil:SendRequest res:%s", result);

	if( result[0] != L'1' ){
		return FALSE;
	}
	return TRUE;
}
Ejemplo n.º 20
0
int Songs::LoadHistory(const char *userId) {
	//ここでサーバに接続して前回と前々回の点数を受信
	HINTERNET      hSession, hConnect, hRequest;
	URL_COMPONENTS urlComponents;
	WCHAR          szHostName[256], szUrlPath[2048];
	//URL
	WCHAR          szUrl[256] = L"http://globalstudios.jp/mai-archive/api_history.php?user="******"Sample Application/1.0",
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS,
		0);
	if (hSession == NULL)
		return -1;

	ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS));
	urlComponents.dwStructSize = sizeof(URL_COMPONENTS);
	urlComponents.lpszHostName = szHostName;
	urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR);
	urlComponents.lpszUrlPath = szUrlPath;
	urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR);


	if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) {
		WinHttpCloseHandle(hSession);
		return -1;
	}

	//接続
	hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0);
	if (hConnect == NULL) {
		WinHttpCloseHandle(hSession);
		return -1;
	}

	hRequest = WinHttpOpenRequest(hConnect,
		L"GET",
		szUrlPath,
		NULL,
		WINHTTP_NO_REFERER,
		WINHTTP_DEFAULT_ACCEPT_TYPES,
		0);
	if (hRequest == NULL) {
		WinHttpCloseHandle(hConnect);
		WinHttpCloseHandle(hSession);
		return -1;
	}

	if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) {
		WinHttpCloseHandle(hRequest);
		WinHttpCloseHandle(hConnect);
		WinHttpCloseHandle(hSession);
		return 0;
	}

	WinHttpReceiveResponse(hRequest, NULL);

	//ボディ取得
	lpData = ReadData(hRequest, &dwSize);
	for (int i = 0; i < NUMSONGS; i++) {
		char* temp = NULL;
		char* ctx;//内部的に使用するので深く考えない

		if (i == 0) {
			temp = strtok_s((char*)lpData, "\n", &ctx);

		} else {
			temp = strtok_s(0, "\n", &ctx);
		}
		if (temp == NULL)break;
		int history[2] = {};
		int hoge;
		sscanf_s(temp, "%d||%d||%d", &hoge, &history[0], &history[1]);
		//以下の式を実行することによってデータを保存
		//song[Search(<曲ID>)]->songHistory->Set(<前回と前々回の点数(配列ポインタ)>);
		song[Search(hoge)]->songHistory->Set(history);
	}
	HeapFree(GetProcessHeap(), 0, lpData);

	WinHttpCloseHandle(hRequest);
	WinHttpCloseHandle(hConnect);
	WinHttpCloseHandle(hSession);

	return 0;
}
Ejemplo n.º 21
0
// Set URL
bool SoffidEssoManager::SaveURLServer (const char* url)
{
	URL_COMPONENTS urlComp;		// Initialize the URL_COMPONENTS structure.

	// Set required component lengths to non-zero so that they are cracked.
	ZeroMemory(&urlComp, sizeof(urlComp));
	urlComp.dwStructSize = sizeof(urlComp);
	WCHAR szScheme[15];
	urlComp.lpszScheme = szScheme;
	urlComp.dwSchemeLength = 14;
	WCHAR szHostName[256];
	urlComp.lpszHostName = szHostName;
	urlComp.dwHostNameLength = 255;
	WCHAR szPath[5096];
	urlComp.lpszUrlPath = szPath;
	urlComp.dwUrlPathLength = 4095;

	int strLen = mbstowcs(NULL, url, strlen(url) + 1);
	wchar_t* wUrl = (wchar_t*) malloc(strLen * sizeof(wchar_t));
	mbstowcs(wUrl, url, strlen(url) + 1);

	// Use WinHttpOpen to obtain a session handle.
	HINTERNET hSession = WinHttpOpen(SoffidEssoManager::DEF_CON_AGENT.c_str(),
			WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME,
			WINHTTP_NO_PROXY_BYPASS, 0);

	// Specify an HTTP server.
	if (hSession)
	{
		if (!WinHttpCrackUrl(wUrl, wcslen(wUrl), 0, &urlComp))
		{
			MessageBox(NULL, Utils::LoadResourcesString(8).c_str(),
					Utils::LoadResourcesString(1001).c_str(),
					MB_OK | MB_ICONEXCLAMATION);
			return false;
		}
		WinHttpSetStatusCallback(hSession, asyncCallback,
				WINHTTP_CALLBACK_FLAG_SECURE_FAILURE, 0);
	}
	else
		return false;

	// Obtener la lista de host
	size_t size;
	if (debug)
		log("Connecting to https://%ls:%d/cert\n", szHostName, urlComp.nPort);

	LPCSTR cert = readURL(hSession, szHostName, urlComp.nPort, L"/cert", true, &size);

	// Check error obtain certificate
	if (cert == NULL)
	{
		log("Error getting certificate");
		return FALSE;
	}

	std::string fileName = getMazingerDir();
	fileName += SoffidEssoManager::DEF_CERTIFICATE_NAME;

	FILE *f = fopen(fileName.c_str(), "wb");

	if (f == NULL)
	{
		log("Error generating file %s", fileName.c_str());
		return FALSE;
	}

	else
	{
		fwrite(cert, size, 1, f);
		fclose(f);
	}

	// Write certificate
	SeyconCommon::writeProperty("CertificateFile", fileName.c_str());

	// Write ESSO Server
	SeyconCommon::writeProperty("SSOServer", MZNC_wstrtostr(szHostName).c_str());

	char szPort[100];
	sprintf(szPort, "%d", urlComp.nPort);

	// Write server prot
	SeyconCommon::writeProperty("seycon.https.port", szPort);

	return true;
}
Ejemplo n.º 22
0
static INT_PTR CALLBACK Window_UpdateCheckDlg(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	const wchar_t* kValueNextVersion[2] = {UPDATE_RELEASE, UPDATE_BETA};
	const char* kVersionType[2] = {"Release", "Beta"};
	UpdateData* data;
	int child_id;
//	int child_notify;
	
	switch(uMsg) {
	case WM_INITDIALOG:{
		wchar_t szHost[256];
		URL_COMPONENTS urlComp = {sizeof(urlComp)};
		urlComp.lpszHostName = szHost;
		urlComp.dwHostNameLength = sizeof(szHost)/sizeof(szHost[0]);
		urlComp.dwUrlPathLength = 1;
		urlComp.dwSchemeLength = 1;
		
		if(lParam != UPDATE_SHOW) // code in WM_WINDOWPOSCHANGING isn't enough...
			SetWindowLongPtr(hDlg, GWL_EXSTYLE, WS_EX_NOACTIVATE);
		
		data = calloc(1, sizeof(UpdateData));
		if(!data)
			goto error;
		data->ref_count = 2;
		data->type = lParam;
		data->update_window = hDlg;
		data->status_text = GetDlgItem(hDlg, IDC_STATUS);
		data->icon_update = LoadImage(g_instance, MAKEINTRESOURCE(IDI_UPDATE), IMAGE_ICON, 0,0, LR_DEFAULTSIZE);
		SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)data->icon_update);
		SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)data->icon_update);
		data->icon_update_small = LoadImage(g_instance, MAKEINTRESOURCE(IDI_UPDATE_S), IMAGE_ICON, 0,0, LR_DEFAULTSIZE);
		data->next_version[0] = api.GetInt(NULL, kValueNextVersion[0], 1);
		#if VER_IsReleaseOrHigher() // release build, opt-in beta check
		data->next_version[1] = api.GetInt(NULL, kValueNextVersion[1], 0);
		#else // non-release build, force beta check
		data->next_version[1] = 1;
		#endif
		SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)data);
		
		data->session = WinHttpOpen(L"T-Clock/" L(VER_SHORT_DOTS), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC);
		if(!data->session)
			goto error;
		WinHttpSetTimeouts(data->session, 30000, 10000, 30000, 30000);
		WinHttpSetStatusCallback(data->session, HttpProgress, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0);
		WinHttpCrackUrl(kUpdateURL, 0, 0, &urlComp);
		data->connection = WinHttpConnect(data->session, urlComp.lpszHostName, urlComp.nPort, 0);
		if(!data->connection)
			goto error;
		data->request = WinHttpOpenRequest(data->connection, L"GET", urlComp.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, (urlComp.nScheme==INTERNET_SCHEME_HTTPS?WINHTTP_FLAG_SECURE:0));
		if(!data->request)
			goto error;
		WinHttpSendRequest(data->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, (DWORD_PTR)data);
		return 1;
		error:
		SendMessage(hDlg, WM_DOWNLOAD_RESULT, 1, 0);
		UpdateCheck_Free(data); // frees 2nd reference (callback)
		if(lParam != UPDATE_SHOW)
			EndDialog(hDlg, IDCANCEL);
		return 1;}
	case WM_WINDOWPOSCHANGING:{
		WINDOWPOS* wndpos = (WINDOWPOS*)lParam;
		data = (UpdateData*)GetWindowLongPtr(hDlg,DWLP_USER);
		if(data && data->type != UPDATE_SHOW) {
			wndpos->flags &= ~SWP_SHOWWINDOW;
			wndpos->flags |= SWP_NOACTIVATE|SWP_NOZORDER;
		}
		return 1;}
	case WM_WINDOWPOSCHANGED:
		return 1;
	case WM_DESTROY:
		data = (UpdateData*)GetWindowLongPtr(hDlg,DWLP_USER);
		DestroyIcon(data->icon_update_small);
		DestroyIcon(data->icon_update);
		UpdateCheck_Free(data);
		return 1;
	case WMBC_INITDIALOG:
		data = (UpdateData*)GetWindowLongPtr(hDlg,DWLP_USER);
		update_notify_data_.button[0].icon = data->icon_update_small;
		// update check
		update_notify_data_.check[0].state = 0;
		if(data->next_version[0])
			update_notify_data_.check[0].state |= BST_CHECKED;
		// beta check
		update_notify_data_.check[1].state = BST_MBC_AUTODISABLE;
		if(data->next_version[1])
			update_notify_data_.check[1].state |= BST_CHECKED;
		#if !VER_IsReleaseOrHigher() // non-release build, forced beta check
		update_notify_data_.check[1].state &= ~BST_MBC_AUTODISABLE;
		update_notify_data_.check[1].style = WS_DISABLED;
		#endif
		SetWindowLongPtr(hDlg, DWLP_MSGRESULT, (LONG_PTR)&update_notify_data_);
		return 1;
	case WMBC_CHECKS:
		data = (UpdateData*)GetWindowLongPtr(hDlg,DWLP_USER);
		if(!data->next_version[0] != !(wParam&1)) {
			data->next_version[0] = (wParam&1);
			api.SetInt(NULL, kValueNextVersion[0], data->next_version[0]);
		}
		if(!data->next_version[1] != !(wParam&2)) {
			data->next_version[1] = (wParam&2 ? 1 : 0);
			api.SetInt(NULL, kValueNextVersion[1], data->next_version[1]);
		}
		return 1;
	case WM_DOWNLOAD_RESULT:
		data = (UpdateData*)GetWindowLongPtr(hDlg,DWLP_USER);
		if(wParam == 0) {
			int idx = 0;
			char* pos;
			unsigned version[2];
			unsigned version_next[2];
			const char* version_str[2] = {0};
			char* version_text[2];
			
			// parse version data
			pos = data->buffer;
			for(;;) {
				if(!version_str[1]) {
					version_text[0] = pos;
					pos = strchr(version_text[0], '\n');
					if(!pos || pos-version_text[0] > 21)
						break;
					*pos++ = '\0';
					version_text[1] = strchr(version_text[0], '|');
					if(!version_text[1])
						break;
					*version_text[1]++ = '\0';
					for(idx=0; idx<2; ++idx) {
						if(!version_str[0]) {
							// revision
							version_next[idx] = data->next_version[idx];
							if(version_next[idx] && version_next[idx] < VER_REVISION)
								version_next[idx] = VER_REVISION;
							version[idx] = atoi(version_text[idx]);
							if(version[idx] <= version_next[idx])
								version_next[idx] = 0;
						} else {
							// version string
							version_str[idx] = version_text[idx];
						}
					}
					if(!version_str[0]) {
						version_str[0] = (char*)1;
						continue;
					}
				}
				// version description
				version_text[0] = strchr(pos, '|');
				if(!version_text[0])
					break;
				++version_text[0];
				version_text[1] = strchr(version_text[0], '|');
				if(!version_text[1])
					break;
				*version_text[1]++ = '\0';
				idx = -1;
				break;
			}
			if(idx != -1) {
				SendMessage(hDlg, WM_DOWNLOAD_RESULT, 2, 0);
				return 1;
			}
			// show version
			if(data->type == UPDATE_SHOW) {
				version_next[0] = version[0];
				version_next[1] = version[1];
			}
			if(version_next[0] || version_next[1]) {
				if(data->type != UPDATE_SILENT) {
					wchar_t* abovebehind;
					wchar_t* msg,* msg_pos,* msg_end;
					msg = msg_pos = (wchar_t*)malloc((512*UPDATE_BUFFER) * sizeof(msg[0]));
					msg_end = msg + UPDATE_BUFFER;
					if(!msg) {
						SendMessage(hDlg, WM_DOWNLOAD_RESULT, 2, 0);
						return 1;
					}
					ShowWindow(hDlg, SW_HIDE);
					idx = version[0]-VER_REVISION;
					abovebehind = (idx<0 ? L"above" : L"behind");
					msg_pos += swprintf(msg_pos, msg_end-msg_pos, FMT("Your version: ") FMT(VER_REVISION_TAG) FMT("	(%i change(s) %s stable)\n\n"), abs(idx), abovebehind);
					for(idx=0; idx<2; ++idx) {
						if(version_next[idx]) {
							msg_pos += swprintf(msg_pos, msg_end-msg_pos, FMT("%hs:	v%hs#%u\n"), kVersionType[idx], version_str[idx], version[idx]);
							msg_pos += UpdateCheck_WriteDescription(msg_pos, msg_end-msg_pos, version_text[idx]);
							if(!idx)
								msg_pos += swprintf(msg_pos, msg_end-msg_pos, FMT("\n"));
						}
					}
					child_id = MessageBoxCustom(hDlg, msg, L"T-Clock updates", MB_ICONINFORMATION|MB_SETFOREGROUND);
					switch(child_id) {
					case ID_MBC1:
						api.ExecFile(kDownloadURL, hDlg);
						break;
					case ID_MBC2:
						for(idx=0; idx<2; ++idx) {
							if(version[idx] && data->next_version[idx])
								api.SetInt(NULL, kValueNextVersion[idx], version[idx]);
						}
						break;
					case ID_MBC3:
						break;
					}
					free(msg);
				}
				EndDialog(hDlg, IDYES);
			} else {
				EndDialog(hDlg, IDNO);
			}
		} else if(data && data->type == UPDATE_SHOW) {
			wchar_t text[64];
			wchar_t* text_pos;
			size_t maxlen;
			text_pos = text + swprintf(text, _countof(text), FMT("<ERROR> "));
			maxlen = _countof(text) + text_pos - text;
			
			SendMessage(GetDlgItem(hDlg,IDC_PROGRESS), PBM_SETSTATE, PBST_ERROR, 0);
			switch(wParam) {
			case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
				swprintf(text_pos, maxlen, FMT("got HTTP status: %i"), (int)lParam);
				break;
			case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
				if(lParam & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR)
					swprintf(text_pos, maxlen, FMT("SSL error"));
				else
					swprintf(text_pos, maxlen, FMT("invalid SSL certificate"));
				break;
			case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
				swprintf(text_pos, maxlen, FMT("connection issues"));
				break;
			case 2:
				swprintf(text_pos, maxlen, FMT("invalid response"));
				break;
			/* case 1 */
			default:
				swprintf(text_pos, maxlen, FMT("failed to check for updates"));
			}
			SetWindowText(data->status_text, text);
		} else {
			EndDialog(hDlg, IDCANCEL);
		}
		return 1;
	case WM_COMMAND:
		child_id = LOWORD(wParam);
//		child_notify = HIWORD(wParam);
		switch(child_id) {
		case IDCANCEL:
			EndDialog(hDlg, IDCANCEL);
			break;
		}
		return 1;
	}
	return 0;
}
		//--------------------------------------------------------------------------------------------------
		//--------------------------------------------------------------------------------------------------
		HttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const CSCore::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)
		{
			CS_ASSERT(CSCore::Application::Get()->GetTaskScheduler()->IsMainThread() == true, "Http requests can currently only be made on the main thread");
			CS_ASSERT(in_delegate != nullptr, "Cannot make an http request with a null delegate");
			CS_ASSERT(in_url.empty() == false, "Cannot make an http request to a blank url");

			URL_COMPONENTS urlComps;

			//Initialize the URL_COMPONENTS structure.
			ZeroMemory(&urlComps, sizeof(URL_COMPONENTS));
			urlComps.dwStructSize = sizeof(URL_COMPONENTS);

			//Set required component lengths to non-zero so that they are cracked.
			urlComps.dwSchemeLength    = (DWORD)-1;
			urlComps.dwHostNameLength  = (DWORD)-1;
			urlComps.dwUrlPathLength   = (DWORD)-1;
			urlComps.dwExtraInfoLength = (DWORD)-1;

			//Change the URL to wide string
			std::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url));

			//Crack the URL.
			if (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps))
			{
				CS_LOG_FATAL("Cannot crack URL: " + in_url);
				return nullptr;
			}

			//Weirdly the cracked URL struct only gives you the ability to crack your own URL
			std::wstring hostName = urlComps.lpszHostName;
			hostName = hostName.substr(0, urlComps.dwHostNameLength);
			HINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0);

			if (!connectionHandle)
			{
				CS_LOG_ERROR("Failed to connect to server: " + in_url);
				return nullptr;
			}

			//Set up the request based on whether it is POST or GET and whether it is SSL
			LPCWSTR type = (in_type == CSNetworking::HttpRequest::Type::k_get ? L"GET" : L"POST");
			HINTERNET requestHandle = 0;

			std::wstring urlPath = urlComps.lpszUrlPath;
			urlPath = urlPath.substr(0, urlComps.dwUrlPathLength);

			if (urlComps.nScheme == INTERNET_SCHEME_HTTPS)
			{
				requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
				if (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false)
				{
					CS_LOG_ERROR("Failed to open request: " + in_url);
					WinHttpCloseHandle(connectionHandle);
					return nullptr;
				}
			}
			else
			{
				requestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
				if (requestHandle == nullptr)
				{
					CS_LOG_ERROR("Failed to open request: " + in_url);
					WinHttpCloseHandle(connectionHandle);
					return nullptr;
				}
			}

			if (in_headers.empty() == false)
			{
				std::wstring headerBlob = ConvertHeaders(in_headers);

				if (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false)
				{
					CS_LOG_ERROR("Failed to add http headers: " + in_url);
					WinHttpCloseHandle(requestHandle);
					WinHttpCloseHandle(connectionHandle);
					return nullptr;
				}
			}

			HttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate);
			m_requests.push_back(httpRequest);
			return httpRequest;
		}
Ejemplo n.º 24
0
BOOL processFile(BackgroundCopyFileImpl *file, BackgroundCopyJobImpl *job)
{
    static const WCHAR prefix[] = {'B','I','T', 0};
    WCHAR tmpDir[MAX_PATH], tmpName[MAX_PATH];
    WCHAR host[MAX_PATH], path[MAX_PATH];
    URL_COMPONENTSW uc;
    BOOL ret;

    if (!GetTempPathW(MAX_PATH, tmpDir))
    {
        ERR("Couldn't create temp file name: %d\n", GetLastError());
        /* Guessing on what state this should give us */
        transitionJobState(job, BG_JOB_STATE_QUEUED, BG_JOB_STATE_TRANSIENT_ERROR);
        return FALSE;
    }

    if (!GetTempFileNameW(tmpDir, prefix, 0, tmpName))
    {
        ERR("Couldn't create temp file: %d\n", GetLastError());
        /* Guessing on what state this should give us */
        transitionJobState(job, BG_JOB_STATE_QUEUED, BG_JOB_STATE_TRANSIENT_ERROR);
        return FALSE;
    }

    EnterCriticalSection(&job->cs);
    file->fileProgress.BytesTotal = BG_SIZE_UNKNOWN;
    file->fileProgress.BytesTransferred = 0;
    file->fileProgress.Completed = FALSE;
    LeaveCriticalSection(&job->cs);

    TRACE("Transferring: %s -> %s -> %s\n",
          debugstr_w(file->info.RemoteName),
          debugstr_w(tmpName),
          debugstr_w(file->info.LocalName));

    uc.dwStructSize      = sizeof(uc);
    uc.nScheme           = 0;
    uc.lpszScheme        = NULL;
    uc.dwSchemeLength    = 0;
    uc.lpszUserName      = NULL;
    uc.dwUserNameLength  = 0;
    uc.lpszPassword      = NULL;
    uc.dwPasswordLength  = 0;
    uc.lpszHostName      = host;
    uc.dwHostNameLength  = sizeof(host)/sizeof(host[0]);
    uc.nPort             = 0;
    uc.lpszUrlPath       = path;
    uc.dwUrlPathLength   = sizeof(path)/sizeof(path[0]);
    uc.lpszExtraInfo     = NULL;
    uc.dwExtraInfoLength = 0;
    ret = WinHttpCrackUrl(file->info.RemoteName, 0, 0, &uc);
    if (!ret)
    {
        TRACE("WinHttpCrackUrl failed, trying local file copy\n");
        if (!transfer_file_local(file, tmpName)) return FALSE;
    }
    else if (!transfer_file_http(file, &uc, tmpName))
    {
        WARN("HTTP transfer failed\n");
        return FALSE;
    }

    if (transitionJobState(job, BG_JOB_STATE_CONNECTING, BG_JOB_STATE_QUEUED) ||
        transitionJobState(job, BG_JOB_STATE_TRANSFERRING, BG_JOB_STATE_QUEUED))
    {
        lstrcpyW(file->tempFileName, tmpName);

        EnterCriticalSection(&job->cs);
        file->fileProgress.Completed = TRUE;
        job->jobProgress.FilesTransferred++;
        LeaveCriticalSection(&job->cs);

        return TRUE;
    }
    else
    {
        DeleteFileW(tmpName);
        return FALSE;
    }
}
Ejemplo n.º 25
0
BOOL server_init_http_winhttp(Remote* remote, SOCKET fd)
{
	URL_COMPONENTS bits;
	wchar_t tmpHostName[512];
	wchar_t tmpUrlPath[1024];
	HttpTransportContext* ctx = (HttpTransportContext*)remote->transport->ctx;

	dprintf("[WINHTTP] Initialising ...");

	// configure proxy
	if (ctx->proxy && wcscmp(ctx->proxy, L"METERPRETER_PROXY") != 0)
	{
		dprintf("[DISPATCH] Configuring with proxy: %S", ctx->proxy);
		ctx->internet = WinHttpOpen(ctx->ua, WINHTTP_ACCESS_TYPE_NAMED_PROXY, ctx->proxy, WINHTTP_NO_PROXY_BYPASS, 0);
	}
	else
	{
		ctx->internet = WinHttpOpen(ctx->ua, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	}

	if (!ctx->internet)
	{
		dprintf("[DISPATCH] Failed WinHttpOpen: %d", GetLastError());
		return FALSE;
	}

	dprintf("[DISPATCH] Configured hInternet: 0x%.8x", ctx->internet);

	// The InternetCrackUrl method was poorly designed...
	ZeroMemory(tmpHostName, sizeof(tmpHostName));
	ZeroMemory(tmpUrlPath, sizeof(tmpUrlPath));

	ZeroMemory(&bits, sizeof(bits));
	bits.dwStructSize = sizeof(bits);

	bits.dwHostNameLength = HOSTNAME_LEN - 1;
	bits.lpszHostName = tmpHostName;

	bits.dwUrlPathLength = URLPATH_LEN - 1;
	bits.lpszUrlPath = tmpUrlPath;

	dprintf("[DISPATCH] About to crack URL: %S", remote->transport->url);
	WinHttpCrackUrl(remote->transport->url, 0, 0, &bits);

	ctx->uri = _wcsdup(tmpUrlPath);

	dprintf("[DISPATCH] Configured URI: %S", ctx->uri);
	dprintf("[DISPATCH] Host: %S Port: %u", tmpHostName, bits.nPort);

	// Allocate the connection handle
	ctx->connection = WinHttpConnect(ctx->internet, tmpHostName, bits.nPort, 0);
	if (!ctx->connection)
	{
		dprintf("[DISPATCH] Failed WinHttpConnect: %d", GetLastError());
		return FALSE;
	}

	dprintf("[DISPATCH] Configured hConnection: 0x%.8x", ctx->connection);

	// Bring up the scheduler subsystem.
	return scheduler_initialize(remote) == ERROR_SUCCESS;
}
Ejemplo n.º 26
0
//リクエストを送る
//内部メモリバッファにDLする場合はファイル容量に要注意
//戻り値:エラーコード
DWORD CWinHTTPUtil::SendRequest( 
	LPCWSTR url,					//[IN] アクセスするURL
	NW_VERB_MODE verbMode,			//[IN] VERBの種類
	LPCWSTR addHttpHeader,			//[IN] Httpヘッダに追加するものあるなら指定
	LPCWSTR saveFilePath,			//[IN] DLファイル名、NULL時は内部メモリバッファにDL
	UPLOAD_DATA_LIST* upList		//[IN] サーバーに送信するデータ(PUT or POST)
	)
{
	if( url == NULL ){
		return ERR_INVALID_ARG;
	}
	if( this->session == NULL ){
		return ERR_NW_NO_SESSION;
	}
	//リクエストクローズ
	if( this->request != NULL ){
		WinHttpSetStatusCallback( this->request, NULL, NULL, NULL );
		WinHttpCloseHandle(this->request);
		this->request = NULL;
	}
	ClearUpList();
	for( size_t i=0; i<this->dlBuffList.size(); i++ ){
		SAFE_DELETE(this->dlBuffList[i]);
	}
	this->dlBuffList.clear();

	//URLの分解
	URL_COMPONENTS stURL;
	ZeroMemory(&stURL, sizeof(URL_COMPONENTS));
	stURL.dwStructSize = sizeof(URL_COMPONENTS);

	stURL.dwSchemeLength    = -1;
	stURL.dwHostNameLength  = -1;
	stURL.dwUrlPathLength   = -1;
	stURL.dwExtraInfoLength = -1;

	if( WinHttpCrackUrl( url, (DWORD)wcslen(url), 0, &stURL) == NULL ){
		return ERR_FALSE;
	}
	if( stURL.dwHostNameLength <= 0 ){
		return ERR_FALSE;
	}

	wstring host = L"";
	host.insert(0,stURL.lpszHostName, stURL.dwHostNameLength );
	host += L"\0";

	if( CompareNoCase(host, stURL.lpszHostName) != 0 || this->lastPort != stURL.nPort){
		//前回と違うコネクションなのでやりなおし
		if( this->connect != NULL ){
			WinHttpCloseHandle(this->connect);
			this->connect = NULL;
		}
	}

	//コネクションオープン
	if( this->connect == NULL ){
		this->connect = WinHttpConnect( this->session, host.c_str(), stURL.nPort, 0 );
		if( this->connect == NULL ){
			return ERR_NW_OPEN_CONNECT;
		}
	}

	//Verbの設定
	wstring verb = L"GET";
	if( verbMode == NW_VERB_GET ){
		verb = L"GET";
	}else if( verbMode == NW_VERB_POST ){
		verb = L"POST";
	}else if( verbMode == NW_VERB_PUT ){
		verb = L"PUT";
	}

	wstring sendUrl = L"";
	sendUrl.insert(0, stURL.lpszUrlPath, stURL.dwUrlPathLength+stURL.dwExtraInfoLength);
	sendUrl += L"\0";

	//リクエストオープン
	if( stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ){
		this->request = WinHttpOpenRequest( this->connect, verb.c_str(), sendUrl.c_str(),
			NULL, WINHTTP_NO_REFERER, 
			WINHTTP_DEFAULT_ACCEPT_TYPES, 
			WINHTTP_FLAG_SECURE);
	}else{
		this->request = WinHttpOpenRequest( this->connect, verb.c_str(), sendUrl.c_str(),
			NULL, WINHTTP_NO_REFERER, 
			WINHTTP_DEFAULT_ACCEPT_TYPES, 
			0 );
	}
	if( this->request == NULL ){
		return ERR_NW_OPEN_REQUEST;
	}

	if( this->useProxy == TRUE ){
		//ProxyのIDとパスワードがあったらセット
		if( this->proxyID.size() > 0 || this->proxyPWD.size() > 0 ){
			if( WinHttpSetCredentials( this->request,
				WINHTTP_AUTH_TARGET_PROXY,
				WINHTTP_AUTH_SCHEME_BASIC,
				this->proxyID.c_str(),
				this->proxyPWD.c_str(),
				NULL )  == FALSE ){
				return ERR_NW_PROXY_LOGIN;
			}
		}
	}

	//HTTPヘッダを設定
	if( addHttpHeader != NULL ){
		WinHttpAddRequestHeaders( this->request, addHttpHeader, -1, WINHTTP_ADDREQ_FLAG_ADD );
	}

	//コールバック設定
	WinHttpSetStatusCallback(this->request, StatusCallback, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS, NULL );

	//アップロードデータのコピー
	this->totalUpSize = 0;
	if( upList != NULL ){
		for( DWORD i=0; i<upList->listCount; i++ ){
			UPLOAD_DATA* item = new UPLOAD_DATA;
			item->filePathFlag = upList->list[i].filePathFlag;
			item->buffSize = upList->list[i].buffSize;
			if( item->buffSize > 0 ){
				item->buff = new BYTE[item->buffSize];
				memcpy(item->buff, upList->list[i].buff, item->buffSize);
			}
			upDataList.push_back(item);

			if( item->filePathFlag == TRUE ){
				HANDLE file = CreateFileW( (WCHAR*)item->buff, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
				if( file == INVALID_HANDLE_VALUE ){
					//ファイルにアクセスできないのでエラー
					return ERR_NW_OPEN_FILE;
				}
				DWORD HSize=0;
				DWORD LSize=0;
				LSize = GetFileSize(file, &HSize);
				CloseHandle(file);
				if( HSize > 0 ){
					//DWORD以上は未サポート
					return ERR_SIZE;
				}
				this->totalUpSize += LSize;
			}else{
				this->totalUpSize  += item->buffSize;
			}
		}
	}

	this->lastHost = host;
	this->lastPort = stURL.nPort;
	if( saveFilePath != NULL ){
		this->saveFilePath = saveFilePath;
	}else{
		this->saveFilePath = L"";
	}

	ResetEvent(this->upStopEvent);
	ResetEvent(this->responseCompEvent);
	this->errEndCode = NO_ERR;
	if( WinHttpSendRequest( this->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, totalUpSize, (DWORD_PTR)this) == FALSE ){
		return ERR_NW_SEND_REQUEST;
	}
	if( this->asyncMode == FALSE ){
		//同期なので完了するまで待つ
		WaitForSingleObject(this->responseCompEvent, INFINITE);
		return this->errEndCode;
	}
	return NO_ERR;
}