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 WindowsHttpDownloader::Initialize(const char* user_agent, int timeout_sec, unsigned buf_block_size_kb, unsigned buf_block_count)
{
	if (!WinHttpCheckPlatform())
		return false;
	if (_http.session != NULL)
		return false;

	WCHAR ua[MAX_PATH] = {};
	if (user_agent)
		AnsiToUnicode(user_agent, ua);

	_http.session = WinHttpOpen(ua[0] != 0 ? ua : NULL,
		WINHTTP_ACCESS_TYPE_NO_PROXY,
		WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	if (_http.session == NULL)
		return false;

	int timeout = timeout_sec * 1000;
	if (timeout > 100)
		WinHttpSetTimeouts(_http.session, timeout, timeout, timeout, timeout);

	for (int i = 0; i < _countof(_events); i++) {
		_events[i] = CreateEventExW(NULL, NULL,
			(i != EventBuf && i != EventDataAvailable) ? CREATE_EVENT_MANUAL_RESET : 0,
			EVENT_ALL_ACCESS);
	}
	return _buffered.Initialize(buf_block_size_kb, buf_block_count);
}
Ejemplo n.º 4
0
static int winhttp_connect(
    winhttp_subtransport *t,
    const char *url)
{
    wchar_t *ua = L"git/1.0 (libgit2 " WIDEN(LIBGIT2_VERSION) L")";
    wchar_t *wide_host;
    int32_t port;
    const char *default_port = "80";
    int error = -1;
    int default_timeout = TIMEOUT_INFINITE;
    int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;

    /* Prepare port */
    if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
        return -1;

    /* Prepare host */
    if (git__utf8_to_16_alloc(&wide_host, t->connection_data.host) < 0) {
        giterr_set(GITERR_OS, "Unable to convert host to wide characters");
        return -1;
    }

    /* Establish session */
    t->session = WinHttpOpen(
                     ua,
                     WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                     WINHTTP_NO_PROXY_NAME,
                     WINHTTP_NO_PROXY_BYPASS,
                     0);

    if (!t->session) {
        giterr_set(GITERR_OS, "Failed to init WinHTTP");
        goto on_error;
    }

    if (!WinHttpSetTimeouts(t->session, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
        giterr_set(GITERR_OS, "Failed to set timeouts for WinHTTP");
        goto on_error;
    }


    /* Establish connection */
    t->connection = WinHttpConnect(
                        t->session,
                        wide_host,
                        (INTERNET_PORT) port,
                        0);

    if (!t->connection) {
        giterr_set(GITERR_OS, "Failed to connect to host");
        goto on_error;
    }

    error = 0;

on_error:
    git__free(wide_host);

    return error;
}
Ejemplo n.º 5
0
//#else
void CSinaSvr::PostWeibo(LPCTSTR lpContent)
{
	BOOL bResults= FALSE;
HINTERNET  hSession = NULL,hConnect = NULL,	hRequest = NULL;
	TCHAR szServer[1024] = _T("weibo.com");
	TCHAR szParam[1024]  = _T("aj/mblog/add");
	TCHAR szHeader[1024] = {0};
	TCHAR szCookie[1024] = {0};
	_stprintf(szHeader,_T("Accept: */*\r\nContent-Type: application/x-www-form-urlencoded\r\nReferer: http://weibo.com/%s\r\nx-requested-with: XMLHttpRequest\r\n"),m_szCurUID);
	_stprintf(szCookie,_T("Cookie: %s\r\n"),m_strCookie.GetBuffer());
	WCHAR szwPost[1024]={0};
	_stprintf(szwPost,_T("_t=0&pic_id=&text=%s"),lpContent);

	char szPost[1024]= {0};
	WideCharToMultiByte(CP_UTF8, 0, szwPost, -1, szPost, MAX_PATH, NULL, NULL);

	PBYTE pBuf = new BYTE[1024*1024];

	hSession = WinHttpOpen(0,  
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME, 
		WINHTTP_NO_PROXY_BYPASS, 0 );
	
	if(hSession)
		WinHttpSetTimeouts( hSession, 600000, 600000, 600000, 600000);

	if( hSession )
		hConnect = WinHttpConnect( hSession,szServer,80, 0 );

	if (hConnect)
        hRequest = WinHttpOpenRequest( hConnect, L"POST", szParam, 
		NULL, WINHTTP_NO_REFERER, 
		WINHTTP_DEFAULT_ACCEPT_TYPES, 
		0);
	int nLen = strlen(szPost);
	WinHttpAddRequestHeaders( hRequest, 
		szCookie, 
		-1, 
		WINHTTP_ADDREQ_FLAG_ADD);
	// Send a Request.
    if (hRequest) 
		bResults = WinHttpSendRequest( hRequest, szHeader,-1, szPost, nLen,nLen,0);

	DWORD dwLen;
	GetHttpResponse(pBuf,dwLen,hRequest);

	if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
	
	delete []pBuf;
	PostWeibo1(lpContent);
}
Ejemplo n.º 6
0
int main(int argc, char* argv[])
{
	printf("Hello World!\n");

	BOOL bResults=FALSE;
	HINTERNET  hSession = NULL,hConnect = NULL,	hRequest = NULL;
	
	//http://login.sina.com.cn/sso/login.php
	TCHAR szServer[1024] = _T("login.sina.com.cn");
	TCHAR szParam[1024]  = _T("sso/login.php");
	TCHAR szHeader[1024] = _T("Accept: */*\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n");
	char szPost[1024]   = "[email protected]&password=93732717&entry=miniblog&act=1&from=referer%3Awww_index";
	PBYTE pBuf = new BYTE[1024*1024];

	hSession = WinHttpOpen(0,  
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME, 
		WINHTTP_NO_PROXY_BYPASS, 0 );
	
	if(hSession)
		WinHttpSetTimeouts( hSession, 600000, 600000, 600000, 600000);

	if( hSession )
		hConnect = WinHttpConnect( hSession,szServer,80, 0 );

	if (hConnect)
        hRequest = WinHttpOpenRequest( hConnect, L"POST", szParam, 
		NULL, WINHTTP_NO_REFERER, 
		WINHTTP_DEFAULT_ACCEPT_TYPES, 
		0);
	int nLen = strlen(szPost);
	// Send a Request.
    if (hRequest) 
		bResults = WinHttpSendRequest( hRequest, szHeader,-1, szPost, nLen,nLen,0);

	DWORD dwLen;
	GetHttpResponse(pBuf,dwLen,hRequest);

	WriteResponseInfo(pBuf,_T("out.txt"));
	if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
	
	delete []pBuf;
	return 0;
}
Ejemplo n.º 7
0
//セッションをオープンする
//戻り値:エラーコード
DWORD CWinHTTPUtil::OpenSession(
	LPCWSTR agent,				//[IN] Agentの設定
	BOOL async,					//[IN] 非同期モードで動くかどうか(TRUE:非同期)
	BOOL useProxy,				//[IN] Proxy使うかどうか(TRUE:Proxy使う)
	USE_PROXY_INFO* proxyInfo	//[IN] Proxy使う場合の設定情報
	)
{
	if( this->session != NULL ){
		//すでにセッション張ってる
		return ERR_NW_ALREADY_SESSION;
	}


	this->useProxy = useProxy;
	this->asyncMode = async;
	if( useProxy == TRUE ){
		if( proxyInfo->userName != NULL ){
			this->proxyID = proxyInfo->userName;
		}
		if( proxyInfo->password != NULL ){
			this->proxyPWD = proxyInfo->password;
		}
	}else{
		this->proxyID = L"";
		this->proxyPWD = L"";
	}

	if( this->useProxy == FALSE ){
		this->session = WinHttpOpen( agent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC );
	}else{
		if( proxyInfo == NULL ){
			return ERR_INVALID_ARG;
		}
		this->session = WinHttpOpen( agent, WINHTTP_ACCESS_TYPE_NAMED_PROXY, proxyInfo->serverName, proxyInfo->proxyBypass, WINHTTP_FLAG_ASYNC );
	}
	
	if( this->session == NULL ){
		return ERR_NW_OPEN_SESSION;
	}else{
		WinHttpSetTimeouts( this->session, 1000*60, 1000*60*2, 1000*60*2, 1000*30*4 ); 
	}

	return NO_ERR;
}
Ejemplo n.º 8
0
static int winhttp_stream_connect(winhttp_stream *s)
{
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
	git_buf buf = GIT_BUF_INIT;
	char *proxy_url = NULL;
	wchar_t ct[MAX_CONTENT_TYPE_LEN];
	LPCWSTR types[] = { L"*/*", NULL };
	BOOL peerdist = FALSE;
	int error = -1;
	unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS;
	int default_timeout = TIMEOUT_INFINITE;
	int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;

	/* Prepare URL */
	git_buf_printf(&buf, "%s%s", t->connection_data.path, s->service_url);

	if (git_buf_oom(&buf))
		return -1;

	/* Convert URL to wide characters */
	if (git__utf8_to_16_alloc(&s->request_uri, git_buf_cstr(&buf)) < 0) {
		giterr_set(GITERR_OS, "Failed to convert string to wide form");
		goto on_error;
	}

	/* Establish request */
	s->request = WinHttpOpenRequest(
			t->connection,
			s->verb,
			s->request_uri,
			NULL,
			WINHTTP_NO_REFERER,
			types,
			t->connection_data.use_ssl ? WINHTTP_FLAG_SECURE : 0);

	if (!s->request) {
		giterr_set(GITERR_OS, "Failed to open request");
		goto on_error;
	}

	if (!WinHttpSetTimeouts(s->request, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
		giterr_set(GITERR_OS, "Failed to set timeouts for WinHTTP");
		goto on_error;
	}

	/* Set proxy if necessary */
	if (git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url) < 0)
		goto on_error;

	if (proxy_url) {
		WINHTTP_PROXY_INFO proxy_info;
		wchar_t *proxy_wide;

		/* Convert URL to wide characters */
		int proxy_wide_len = git__utf8_to_16_alloc(&proxy_wide, proxy_url);

		if (proxy_wide_len < 0) {
			giterr_set(GITERR_OS, "Failed to convert string to wide form");
			goto on_error;
		}

		/* Strip any trailing forward slash on the proxy URL;
		 * WinHTTP doesn't like it if one is present */
		if (proxy_wide_len > 1 && L'/' == proxy_wide[proxy_wide_len - 2])
			proxy_wide[proxy_wide_len - 2] = L'\0';

		proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
		proxy_info.lpszProxy = proxy_wide;
		proxy_info.lpszProxyBypass = NULL;

		if (!WinHttpSetOption(s->request,
			WINHTTP_OPTION_PROXY,
			&proxy_info,
			sizeof(WINHTTP_PROXY_INFO))) {
			giterr_set(GITERR_OS, "Failed to set proxy");
			git__free(proxy_wide);
			goto on_error;
		}

		git__free(proxy_wide);
	}

	/* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
	 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
	 */
	if (!WinHttpSetOption(s->request,
		WINHTTP_OPTION_DISABLE_FEATURE,
		&disable_redirects,
		sizeof(disable_redirects))) {
			giterr_set(GITERR_OS, "Failed to disable redirects");
			goto on_error;
	}

	/* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
	 * adds itself. This option may not be supported by the underlying
	 * platform, so we do not error-check it */
	WinHttpSetOption(s->request,
		WINHTTP_OPTION_PEERDIST_EXTENSION_STATE,
		&peerdist,
		sizeof(peerdist));

	/* Send Pragma: no-cache header */
	if (!WinHttpAddRequestHeaders(s->request, pragma_nocache, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
		giterr_set(GITERR_OS, "Failed to add a header to the request");
		goto on_error;
	}

	if (post_verb == s->verb) {
		/* Send Content-Type and Accept headers -- only necessary on a POST */
		git_buf_clear(&buf);
		if (git_buf_printf(&buf,
			"Content-Type: application/x-git-%s-request",
			s->service) < 0)
			goto on_error;

		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "Failed to convert content-type to wide characters");
			goto on_error;
		}

		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
			giterr_set(GITERR_OS, "Failed to add a header to the request");
			goto on_error;
		}

		git_buf_clear(&buf);
		if (git_buf_printf(&buf,
			"Accept: application/x-git-%s-result",
			s->service) < 0)
			goto on_error;

		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "Failed to convert accept header to wide characters");
			goto on_error;
		}

		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
			giterr_set(GITERR_OS, "Failed to add a header to the request");
			goto on_error;
		}
	}

	/* If requested, disable certificate validation */
	if (t->connection_data.use_ssl) {
		int flags;

		if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0)
			goto on_error;
	}

	/* If we have a credential on the subtransport, apply it to the request */
	if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT &&
		t->auth_mechanism == GIT_WINHTTP_AUTH_BASIC &&
		apply_basic_credential(s->request, t->cred) < 0)
		goto on_error;
	else if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_DEFAULT &&
		t->auth_mechanism == GIT_WINHTTP_AUTH_NEGOTIATE &&
		apply_default_credentials(s->request) < 0)
		goto on_error;

	/* If no other credentials have been applied and the URL has username and
	 * password, use those */
	if (!t->cred && t->connection_data.user && t->connection_data.pass) {
		if (!t->url_cred &&
			git_cred_userpass_plaintext_new(&t->url_cred, t->connection_data.user, t->connection_data.pass) < 0)
			goto on_error;
		if (apply_basic_credential(s->request, t->url_cred) < 0)
			goto on_error;
	}

	/* We've done everything up to calling WinHttpSendRequest. */

	error = 0;

on_error:
	if (error < 0)
		winhttp_stream_close(s);

	git__free(proxy_url);
	git_buf_free(&buf);
	return error;
}
Ejemplo n.º 9
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.º 10
0
static int winhttp_connect(
	winhttp_subtransport *t)
{
	wchar_t *wide_host;
	int32_t port;
	wchar_t *wide_ua;
	git_buf ua = GIT_BUF_INIT;
	int error = -1;
	int default_timeout = TIMEOUT_INFINITE;
	int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;

	t->session = NULL;
	t->connection = NULL;

	/* Prepare port */
	if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
		return -1;

	/* Prepare host */
	if (git__utf8_to_16_alloc(&wide_host, t->connection_data.host) < 0) {
		giterr_set(GITERR_OS, "unable to convert host to wide characters");
		return -1;
	}

	if ((error = user_agent(&ua)) < 0) {
		git__free(wide_host);
		return error;
	}

	if (git__utf8_to_16_alloc(&wide_ua, git_buf_cstr(&ua)) < 0) {
		giterr_set(GITERR_OS, "unable to convert host to wide characters");
		git__free(wide_host);
		git_buf_free(&ua);
		return -1;
	}

	git_buf_free(&ua);

	/* Establish session */
	t->session = WinHttpOpen(
		wide_ua,
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS,
		0);

	if (!t->session) {
		giterr_set(GITERR_OS, "failed to init WinHTTP");
		goto on_error;
	}

	if (!WinHttpSetTimeouts(t->session, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
		giterr_set(GITERR_OS, "failed to set timeouts for WinHTTP");
		goto on_error;
	}

	
	/* Establish connection */
	t->connection = WinHttpConnect(
		t->session,
		wide_host,
		(INTERNET_PORT) port,
		0);

	if (!t->connection) {
		giterr_set(GITERR_OS, "failed to connect to host");
		goto on_error;
	}

	if (WinHttpSetStatusCallback(t->connection, winhttp_status, WINHTTP_CALLBACK_FLAG_SECURE_FAILURE, 0) == WINHTTP_INVALID_STATUS_CALLBACK) {
		giterr_set(GITERR_OS, "failed to set status callback");
		goto on_error;
	}

	error = 0;

on_error:
	if (error < 0)
		winhttp_close_connection(t);

	git__free(wide_host);
	git__free(wide_ua);

	return error;
}
Ejemplo n.º 11
0
static int winhttp_stream_connect(winhttp_stream *s)
{
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
	git_buf buf = GIT_BUF_INIT;
	char *proxy_url = NULL;
	wchar_t ct[MAX_CONTENT_TYPE_LEN];
	LPCWSTR types[] = { L"*/*", NULL };
	BOOL peerdist = FALSE;
	int error = -1;
	unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS;
	int default_timeout = TIMEOUT_INFINITE;
	int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
	size_t i;
	const git_proxy_options *proxy_opts;

	/* Prepare URL */
	git_buf_printf(&buf, "%s%s", t->connection_data.path, s->service_url);

	if (git_buf_oom(&buf))
		return -1;

	/* Convert URL to wide characters */
	if (git__utf8_to_16_alloc(&s->request_uri, git_buf_cstr(&buf)) < 0) {
		giterr_set(GITERR_OS, "failed to convert string to wide form");
		goto on_error;
	}

	/* Establish request */
	s->request = WinHttpOpenRequest(
			t->connection,
			s->verb,
			s->request_uri,
			NULL,
			WINHTTP_NO_REFERER,
			types,
			t->connection_data.use_ssl ? WINHTTP_FLAG_SECURE : 0);

	if (!s->request) {
		giterr_set(GITERR_OS, "failed to open request");
		goto on_error;
	}

	if (!WinHttpSetTimeouts(s->request, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
		giterr_set(GITERR_OS, "failed to set timeouts for WinHTTP");
		goto on_error;
	}

	proxy_opts = &t->owner->proxy;
	if (proxy_opts->type == GIT_PROXY_AUTO) {
		/* Set proxy if necessary */
		if (git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url) < 0)
			goto on_error;
	}
	else if (proxy_opts->type == GIT_PROXY_SPECIFIED) {
		proxy_url = git__strdup(proxy_opts->url);
		GITERR_CHECK_ALLOC(proxy_url);
	}

	if (proxy_url) {
		git_buf processed_url = GIT_BUF_INIT;
		WINHTTP_PROXY_INFO proxy_info;
		wchar_t *proxy_wide;

		if (!git__prefixcmp(proxy_url, SCHEME_HTTP)) {
			t->proxy_connection_data.use_ssl = false;
		} else if (!git__prefixcmp(proxy_url, SCHEME_HTTPS)) {
			t->proxy_connection_data.use_ssl = true;
		} else {
			giterr_set(GITERR_NET, "invalid URL: '%s'", proxy_url);
			return -1;
		}

		gitno_connection_data_free_ptrs(&t->proxy_connection_data);

		if ((error = gitno_extract_url_parts(&t->proxy_connection_data.host, &t->proxy_connection_data.port, NULL,
				&t->proxy_connection_data.user, &t->proxy_connection_data.pass, proxy_url, NULL)) < 0)
			goto on_error;

		if (t->proxy_connection_data.user && t->proxy_connection_data.pass) {
			if (t->proxy_cred) {
				t->proxy_cred->free(t->proxy_cred);
			}

			if ((error = git_cred_userpass_plaintext_new(&t->proxy_cred, t->proxy_connection_data.user, t->proxy_connection_data.pass)) < 0)
				goto on_error;
		}

		if (t->proxy_connection_data.use_ssl)
			git_buf_PUTS(&processed_url, SCHEME_HTTPS);
		else
			git_buf_PUTS(&processed_url, SCHEME_HTTP);

		git_buf_puts(&processed_url, t->proxy_connection_data.host);
		if (t->proxy_connection_data.port)
			git_buf_printf(&processed_url, ":%s", t->proxy_connection_data.port);

		if (git_buf_oom(&processed_url)) {
			giterr_set_oom();
			error = -1;
			goto on_error;
		}

		/* Convert URL to wide characters */
		error = git__utf8_to_16_alloc(&proxy_wide, processed_url.ptr);
		git_buf_free(&processed_url);
		if (error < 0)
			goto on_error;

		proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
		proxy_info.lpszProxy = proxy_wide;
		proxy_info.lpszProxyBypass = NULL;

		if (!WinHttpSetOption(s->request,
			WINHTTP_OPTION_PROXY,
			&proxy_info,
			sizeof(WINHTTP_PROXY_INFO))) {
			giterr_set(GITERR_OS, "failed to set proxy");
			git__free(proxy_wide);
			goto on_error;
		}

		git__free(proxy_wide);

		if (t->proxy_cred) {
			if (t->proxy_cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT) {
				if ((error = apply_userpass_credential_proxy(s->request, t->proxy_cred)) < 0)
					goto on_error;
			}
		}

	}

	/* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
	 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
	 */
	if (!WinHttpSetOption(s->request,
		WINHTTP_OPTION_DISABLE_FEATURE,
		&disable_redirects,
		sizeof(disable_redirects))) {
			giterr_set(GITERR_OS, "failed to disable redirects");
			goto on_error;
	}

	/* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
	 * adds itself. This option may not be supported by the underlying
	 * platform, so we do not error-check it */
	WinHttpSetOption(s->request,
		WINHTTP_OPTION_PEERDIST_EXTENSION_STATE,
		&peerdist,
		sizeof(peerdist));

	/* Send Pragma: no-cache header */
	if (!WinHttpAddRequestHeaders(s->request, pragma_nocache, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
		giterr_set(GITERR_OS, "failed to add a header to the request");
		goto on_error;
	}

	if (post_verb == s->verb) {
		/* Send Content-Type and Accept headers -- only necessary on a POST */
		git_buf_clear(&buf);
		if (git_buf_printf(&buf,
			"Content-Type: application/x-git-%s-request",
			s->service) < 0)
			goto on_error;

		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "failed to convert content-type to wide characters");
			goto on_error;
		}

		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
			giterr_set(GITERR_OS, "failed to add a header to the request");
			goto on_error;
		}

		git_buf_clear(&buf);
		if (git_buf_printf(&buf,
			"Accept: application/x-git-%s-result",
			s->service) < 0)
			goto on_error;

		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "failed to convert accept header to wide characters");
			goto on_error;
		}

		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
			giterr_set(GITERR_OS, "failed to add a header to the request");
			goto on_error;
		}
	}

	for (i = 0; i < t->owner->custom_headers.count; i++) {
		if (t->owner->custom_headers.strings[i]) {
			git_buf_clear(&buf);
			git_buf_puts(&buf, t->owner->custom_headers.strings[i]);
			if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
				giterr_set(GITERR_OS, "failed to convert custom header to wide characters");
				goto on_error;
			}

			if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
				WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
				giterr_set(GITERR_OS, "failed to add a header to the request");
				goto on_error;
			}
		}
	}

	/* If requested, disable certificate validation */
	if (t->connection_data.use_ssl) {
		int flags;

		if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0)
			goto on_error;
	}

	/* If we have a credential on the subtransport, apply it to the request */
	if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT &&
		apply_userpass_credential(s->request, t->auth_mechanisms, t->cred) < 0)
		goto on_error;
	else if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_DEFAULT &&
		apply_default_credentials(s->request, t->auth_mechanisms) < 0)
		goto on_error;

	/* If no other credentials have been applied and the URL has username and
	 * password, use those */
	if (!t->cred && t->connection_data.user && t->connection_data.pass) {
		if (!t->url_cred &&
			git_cred_userpass_plaintext_new(&t->url_cred, t->connection_data.user, t->connection_data.pass) < 0)
			goto on_error;
		if (apply_userpass_credential(s->request, GIT_WINHTTP_AUTH_BASIC, t->url_cred) < 0)
			goto on_error;
	}

	/* We've done everything up to calling WinHttpSendRequest. */

	error = 0;

on_error:
	if (error < 0)
		winhttp_stream_close(s);

	git__free(proxy_url);
	git_buf_free(&buf);
	return error;
}
Ejemplo n.º 12
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;
}
Ejemplo n.º 13
0
int main(int argc, char **argv) {
	
	// Prepare log file and check argument count
	FILE* log_file = fopen("track_results.log","a");
	if(argc != 4) {
		fprintf(log_file, "Incorrect number of arguments.\n");
		return 1;
	}

	int desired_fps = atoi(argv[3]);
	if(desired_fps > 60 || desired_fps < 1) {
		fprintf(log_file, "Invalid FPS: please select a value in the range [1-60].\n");
		return 1;
	}

	////////// GROUND TRUTH SETUP AND PROCESSING //////////

	// Open and extract bounding rect info from gt file
	char buffer[100];
	memset(buffer, 0, sizeof(buffer));
	int gt_rect[4];

	FILE* gt_file = fopen(argv[2], "r");
	fgets(buffer, 100, gt_file);

	char* token = strtok(buffer, ",");
	gt_rect[0] = atoi(token);

	int i = 1;
	while(i < 4) {
		token = strtok(NULL, ",");
		gt_rect[i] = atoi(token);
		i++;
	}

	fclose(gt_file);

	// Load image and compress to a reasonable size
	IplImage* gt = cvLoadImage(argv[1]);

	IplImage* gt_resized = cvCreateImage(cvSize(320, 240), gt->depth, gt->nChannels); //1280,720
	cvResize(gt, gt_resized, CV_INTER_NN);

	// Show bounding rect
	CvPoint corner1 = cvPoint(gt_rect[0], gt_rect[1]);
	CvPoint corner2 = cvPoint(gt_rect[0] + gt_rect[2], gt_rect[1] + gt_rect[3]);
	CvScalar rect_color = CV_RGB(255,0,0);

	cvRectangle(gt_resized, corner1, corner2, rect_color, 2);

	cvNamedWindow( "Ground Truth Reference", CV_WINDOW_AUTOSIZE );
    cvShowImage( "Ground Truth Reference", gt_resized );

	// Set ROI for ground truth
	CvRect quarter = cvRect(gt_rect[0], gt_rect[1], gt_rect[2], gt_rect[3]);
	cvSetImageROI(gt_resized, quarter);

	////////// PREPARE GOPRO FOR VIDEO CAPTURE //////////

	// Basic connectivity tests
	HINTERNET hSession = WinHttpOpen( L"GoPro HTTP Transfer/1.1", 
                              WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                              WINHTTP_NO_PROXY_NAME, 
                              WINHTTP_NO_PROXY_BYPASS, 0 ); 

	if(hSession == NULL) {
		printf("Error %u in WinHttpOpen.\n", GetLastError());
		std::cin.get();
		return 1;
	}

	if( !WinHttpSetTimeouts( hSession, 10000, 10000, 10000, 10000 )) {
		printf( "Error %u in WinHttpSetTimeouts.\n", GetLastError());
		std::cin.get();
		return 1;
	}

	HINTERNET hConnect = WinHttpConnect( hSession, L"10.5.5.9", 80, 0);

	if(hConnect == NULL) {
		printf("Error %u in WinHttpConnect.\n", GetLastError());
		std::cin.get();
		return 1;
	}
	
	// Power on
	bool error = ping_request(hConnect, L"/bacpac/PW?t=goprohero&p=%01");
	if(error) {
		return 1;
	}

	Sleep(5000); //give time to boot up

	//Clear memory

	error = ping_request(hConnect, L"/camera/DA?t=goprohero");
	if(error) {
		return 1;
	}

	Sleep(5000); //give time to delete files

	// Set to video mode
	error = ping_request(hConnect, L"/camera/CM?t=goprohero&p=%00");
	if(error) {
		return 1;
	}

	Sleep(1000);

	// Set video resolution to 720p, 30FPS
	error = ping_request(hConnect, L"/camera/VR?t=goprohero&p=%00");
	if(error) {
		return 1;
	}

	Sleep(1000);

	WinHttpCloseHandle(hConnect);
	WinHttpCloseHandle(hSession);

	////////// PREPARE TIMING & VIDEO RESOURCES //////////

	// Prepare timing instrumentation (for FPS control)
	__int64 last_time = 0;
	__int64 current_time = 0;
	__int64 freq = 0;
	int frame_time = 1000 / desired_fps;

	// Play video
	cvNamedWindow( "MOV Window", CV_WINDOW_AUTOSIZE );
	CvCapture* track_video = cvCreateFileCapture( "tags.mov" );
	IplImage* current_frame;

	// Record annotated video
	CvSize write_size = cvSize(
       (int)cvGetCaptureProperty( track_video, CV_CAP_PROP_FRAME_WIDTH),
       (int)cvGetCaptureProperty( track_video, CV_CAP_PROP_FRAME_HEIGHT)
    );	
	CvVideoWriter *writer = cvCreateVideoWriter( "output.avi", CV_FOURCC('M','J','P','G'), 20, write_size, 1);

	// Start timer
	QueryPerformanceCounter((LARGE_INTEGER*) &last_time);

	////////// MAIN PROCESSING LOOP //////////

	bool to_search = true;
	bool next = true;
	CvRect est = quarter;

	while(1) {

		// Read in current frame
		current_frame = cvQueryFrame(track_video);
		if(current_frame == NULL) {
			break;
		}

		if(to_search == false) {
			est = process_frame(gt_resized, current_frame, quarter, &next, log_file);
			rect_color = CV_RGB(0,255,0);
		} else {
			est = search(gt_resized, current_frame, quarter, &next, log_file);
			rect_color = CV_RGB(255,0,0);
		}

		fprintf(log_file, "Coordinates: %d , %d\t\t", est.x, est.y);
		if(to_search) {
			fprintf(log_file, "Recommended Action: Search\n");
		} else {
			// X direction flight planning
			if(est.x < ((current_frame->width / 2) - 10)) {
				fprintf(log_file, "Recommended Action: Move Right , ");
			}
			else if(est.x > ((current_frame->width / 2) + 10)) {
				fprintf(log_file, "Recommended Action: Move Left, ");
			}
			else {
				fprintf(log_file, "Recommended Action: Hover, ");
			}
			
			// Y direction flight planning
			if(est.y < ((current_frame->height / 2) - 10)) {
				fprintf(log_file, "Move Backwards\n");
			}
			else if(est.y > ((current_frame->width / 2) + 10)) {
				fprintf(log_file, "Move Forwards\n");
			}
			else {
				fprintf(log_file, "Hover\n");
			}
		}
		to_search = next;

		// Swap frames
		quarter = est;

		CvPoint corner1 = cvPoint(est.x, est.y);
		CvPoint corner2 = cvPoint(est.x + est.width, est.y + est.height);

		cvRectangle(current_frame, corner1, corner2, rect_color, 2);

		// Display frame
		cvShowImage( "MOV Window", current_frame );
		cvWriteFrame( writer, current_frame );

		// FPS Control
		QueryPerformanceCounter((LARGE_INTEGER*) &current_time);
		QueryPerformanceFrequency((LARGE_INTEGER*) &freq);

		int elapsed_time = (int)((current_time - last_time) / freq);
		int wait_time = frame_time - (elapsed_time / 1000);

		if(wait_time < 0) {
			continue;
		}

		char ext_key = cvWaitKey(wait_time);
		if(ext_key == 27) {
			break;
		}

	}

	////////// CLEAN-UP //////////

	cvReleaseCapture( &track_video );
	cvReleaseVideoWriter( &writer );
	cvDestroyWindow( "MOV Window" );

	cvReleaseImage( &gt );
	cvReleaseImage( &gt_resized );

	cvDestroyWindow( "Ground Truth Reference" );

	fclose(log_file);

	return 0;

}
Ejemplo n.º 14
0
HTTPAPI_RESULT HTTPAPI_ExecuteRequest(HTTP_HANDLE handle, HTTPAPI_REQUEST_TYPE requestType, const char* relativePath,
    HTTP_HEADERS_HANDLE httpHeadersHandle, const unsigned char* content,
    size_t contentLength, unsigned int* statusCode,
    HTTP_HEADERS_HANDLE responseHeadersHandle, BUFFER_HANDLE responseContent)
{
    HTTPAPI_RESULT result;
    if (g_HTTPAPIState != HTTPAPI_INITIALIZED)
    {
        LogError("g_HTTPAPIState not HTTPAPI_INITIALIZED");
        result = HTTPAPI_NOT_INIT;
    }
    else
    {
        HTTP_HANDLE_DATA* handleData = (HTTP_HANDLE_DATA*)handle;

        if ((handleData == NULL) ||
            (relativePath == NULL) ||
            (httpHeadersHandle == NULL))
        {
            result = HTTPAPI_INVALID_ARG;
            LogError("NULL parameter detected (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
        }
        else
        {
            wchar_t* requestTypeString = NULL;

            switch (requestType)
            {
            default:
                break;

            case HTTPAPI_REQUEST_GET:
                requestTypeString = L"GET";
                break;

            case HTTPAPI_REQUEST_POST:
                requestTypeString = L"POST";
                break;

            case HTTPAPI_REQUEST_PUT:
                requestTypeString = L"PUT";
                break;

            case HTTPAPI_REQUEST_DELETE:
                requestTypeString = L"DELETE";
                break;

            case HTTPAPI_REQUEST_PATCH:
                requestTypeString = L"PATCH";
                break;
            }

            if (requestTypeString == NULL)
            {
                result = HTTPAPI_INVALID_ARG;
                LogError("requestTypeString was NULL (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
            }
            else
            {
                const char* headers2;
                headers2 = ConstructHeadersString(httpHeadersHandle);
                if (headers2 != NULL)
                {
                    size_t requiredCharactersForRelativePath = MultiByteToWideChar(CP_ACP, 0, relativePath, -1, NULL, 0);
                    wchar_t* relativePathTemp = (wchar_t*)malloc((requiredCharactersForRelativePath+1) * sizeof(wchar_t));
                    result = HTTPAPI_OK; /*legacy code*/

                    if (relativePathTemp == NULL)
                    {
                        result = HTTPAPI_ALLOC_FAILED;
                        LogError("malloc failed (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                    }
                    else
                    {
                        if (MultiByteToWideChar(CP_ACP, 0, relativePath, -1, relativePathTemp, (int)requiredCharactersForRelativePath) == 0)
                        {
                            result = HTTPAPI_STRING_PROCESSING_ERROR;
                            LogError("MultiByteToWideChar was 0. (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                        }
                        else
                        {
                            size_t requiredCharactersForHeaders = MultiByteToWideChar(CP_ACP, 0, headers2, -1, NULL, 0);

                            wchar_t* headersTemp = (wchar_t*)malloc((requiredCharactersForHeaders +1) * sizeof(wchar_t) );
                            if (headersTemp == NULL)
                            {
                                result = HTTPAPI_STRING_PROCESSING_ERROR;
                                LogError("MultiByteToWideChar was 0. (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                            }
                            else
                            {
                                if (MultiByteToWideChar(CP_ACP, 0, headers2, -1, headersTemp, (int)requiredCharactersForHeaders) == 0)
                                {
                                    result = HTTPAPI_STRING_PROCESSING_ERROR;
                                    LogError("MultiByteToWideChar was 0(result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                }
                                else
                                {
                                    HINTERNET requestHandle = WinHttpOpenRequest(
                                        handleData->ConnectionHandle,
                                        requestTypeString,
                                        relativePathTemp,
                                        NULL,
                                        WINHTTP_NO_REFERER,
                                        WINHTTP_DEFAULT_ACCEPT_TYPES,
                                        WINHTTP_FLAG_SECURE);
                                    if (requestHandle == NULL)
                                    {
                                        result = HTTPAPI_OPEN_REQUEST_FAILED;
                                        LogErrorWinHTTPWithGetLastErrorAsString("WinHttpOpenRequest failed (result = %s).", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                    }
                                    else
                                    {
                                        if ((handleData->x509SchannelHandle!=NULL) && 
                                            !WinHttpSetOption(
                                                requestHandle,
                                                WINHTTP_OPTION_CLIENT_CERT_CONTEXT,
                                                (void*)x509_schannel_get_certificate_context(handleData->x509SchannelHandle),
                                                sizeof(CERT_CONTEXT)
                                        ))
                                        {
                                            LogErrorWinHTTPWithGetLastErrorAsString("unable to WinHttpSetOption");
                                            result = HTTPAPI_SET_X509_FAILURE;
                                        }
                                        else
                                        {
                                            if (WinHttpSetTimeouts(requestHandle,
                                                0,                      /*_In_  int dwResolveTimeout - The initial value is zero, meaning no time-out (infinite). */
                                                60000,                  /*_In_  int dwConnectTimeout, -  The initial value is 60,000 (60 seconds).*/
                                                handleData->timeout,    /*_In_  int dwSendTimeout, -  The initial value is 30,000 (30 seconds).*/
                                                handleData->timeout     /* int dwReceiveTimeout The initial value is 30,000 (30 seconds).*/
                                            ) == FALSE)
                                            {
                                                result = HTTPAPI_SET_TIMEOUTS_FAILED;
                                                LogErrorWinHTTPWithGetLastErrorAsString("WinHttpOpenRequest failed (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                            }
                                            else
                                            {
                                                DWORD dwSecurityFlags = 0;

                                                if (!WinHttpSetOption(
                                                    requestHandle,
                                                    WINHTTP_OPTION_SECURITY_FLAGS,
                                                    &dwSecurityFlags,
                                                    sizeof(dwSecurityFlags)))
                                                {
                                                    result = HTTPAPI_SET_OPTION_FAILED;
                                                    LogErrorWinHTTPWithGetLastErrorAsString("WinHttpSetOption failed (result = %s).", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                }
                                                else
                                                {
                                                    if (!WinHttpSendRequest(
                                                        requestHandle,
                                                        headersTemp,
                                                        (DWORD)-1L, /*An unsigned long integer value that contains the length, in characters, of the additional headers. If this parameter is -1L ... */
                                                        (void*)content,
                                                        (DWORD)contentLength,
                                                        (DWORD)contentLength,
                                                        0))
                                                    {
                                                        result = HTTPAPI_SEND_REQUEST_FAILED;
                                                        LogErrorWinHTTPWithGetLastErrorAsString("WinHttpSendRequest: (result = %s).", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                    }
                                                    else
                                                    {
                                                        if (!WinHttpReceiveResponse(
                                                            requestHandle,
                                                            0))
                                                        {
                                                            result = HTTPAPI_RECEIVE_RESPONSE_FAILED;
                                                            LogErrorWinHTTPWithGetLastErrorAsString("WinHttpReceiveResponse: (result = %s).", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                        }
                                                        else
                                                        {
                                                            DWORD dwStatusCode = 0;
                                                            DWORD dwBufferLength = sizeof(DWORD);
                                                            DWORD responseBytesAvailable;

                                                            if (!WinHttpQueryHeaders(
                                                                requestHandle,
                                                                WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
                                                                WINHTTP_HEADER_NAME_BY_INDEX,
                                                                &dwStatusCode,
                                                                &dwBufferLength,
                                                                WINHTTP_NO_HEADER_INDEX))
                                                            {
                                                                result = HTTPAPI_QUERY_HEADERS_FAILED;
                                                                LogErrorWinHTTPWithGetLastErrorAsString("WinHttpQueryHeaders failed (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                            }
                                                            else
                                                            {
                                                                BUFFER_HANDLE useToReadAllResponse = (responseContent != NULL) ? responseContent : BUFFER_new();

                                                                if (statusCode != NULL)
                                                                {
                                                                    *statusCode = dwStatusCode;
                                                                }

                                                                if (useToReadAllResponse == NULL)
                                                                {
                                                                    result = HTTPAPI_ERROR;
                                                                    LogError("(result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                }
                                                                else
                                                                {

                                                                    int goOnAndReadEverything = 1;
                                                                    do
                                                                    {
                                                                        /*from MSDN: If no data is available and the end of the file has not been reached, one of two things happens. If the session is synchronous, the request waits until data becomes available.*/
                                                                        if (!WinHttpQueryDataAvailable(requestHandle, &responseBytesAvailable))
                                                                        {
                                                                            result = HTTPAPI_QUERY_DATA_AVAILABLE_FAILED;
                                                                            LogErrorWinHTTPWithGetLastErrorAsString("WinHttpQueryDataAvailable failed (result = %s).", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                            goOnAndReadEverything = 0;
                                                                        }
                                                                        else if (responseBytesAvailable == 0)
                                                                        {
                                                                            /*end of the stream, go out*/
                                                                            result = HTTPAPI_OK;
                                                                            goOnAndReadEverything = 0;
                                                                        }
                                                                        else
                                                                        {
                                                                            if (BUFFER_enlarge(useToReadAllResponse, responseBytesAvailable) != 0)
                                                                            {
                                                                                result = HTTPAPI_ERROR;
                                                                                LogError("(result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                                goOnAndReadEverything = 0;
                                                                            }
                                                                            else
                                                                            {
                                                                                /*Add the read bytes to the response buffer*/
                                                                                size_t bufferSize;
                                                                                const unsigned char* bufferContent;

                                                                                if (BUFFER_content(useToReadAllResponse, &bufferContent) != 0)
                                                                                {
                                                                                    result = HTTPAPI_ERROR;
                                                                                    LogError("(result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                                    goOnAndReadEverything = 0;
                                                                                }
                                                                                else if (BUFFER_size(useToReadAllResponse, &bufferSize) != 0)
                                                                                {
                                                                                    result = HTTPAPI_ERROR;
                                                                                    LogError("(result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                                    goOnAndReadEverything = 0;
                                                                                }
                                                                                else
                                                                                {
                                                                                    DWORD bytesReceived;
                                                                                    if (!WinHttpReadData(requestHandle, (LPVOID)(bufferContent + bufferSize - responseBytesAvailable), responseBytesAvailable, &bytesReceived))
                                                                                    {
                                                                                        result = HTTPAPI_READ_DATA_FAILED;
                                                                                        LogErrorWinHTTPWithGetLastErrorAsString("WinHttpReadData failed (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                                        goOnAndReadEverything = 0;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        /*if for some reason bytesReceived is zero If you are using WinHttpReadData synchronously, and the return value is TRUE and the number of bytes read is zero, the transfer has been completed and there are no more bytes to read on the handle.*/
                                                                                        if (bytesReceived == 0)
                                                                                        {
                                                                                            /*end of everything, but this looks like an error still, or a non-conformance between WinHttpQueryDataAvailable and WinHttpReadData*/
                                                                                            result = HTTPAPI_READ_DATA_FAILED;
                                                                                            LogError("bytesReceived was unexpectedly zero (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                                            goOnAndReadEverything = 0;
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            /*all is fine, keep going*/
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }

                                                                    } while (goOnAndReadEverything != 0);
                                                                }
                                                            }

                                                            if (result == HTTPAPI_OK && responseHeadersHandle != NULL)
                                                            {
                                                                wchar_t* responseHeadersTemp;
                                                                DWORD responseHeadersTempLength = sizeof(responseHeadersTemp);

                                                                (void)WinHttpQueryHeaders(
                                                                    requestHandle,
                                                                    WINHTTP_QUERY_RAW_HEADERS_CRLF,
                                                                    WINHTTP_HEADER_NAME_BY_INDEX,
                                                                    WINHTTP_NO_OUTPUT_BUFFER,
                                                                    &responseHeadersTempLength,
                                                                    WINHTTP_NO_HEADER_INDEX);

                                                                responseHeadersTemp = (wchar_t*)malloc(responseHeadersTempLength + 2);
                                                                if (responseHeadersTemp == NULL)
                                                                {
                                                                    result = HTTPAPI_ALLOC_FAILED;
                                                                    LogError("malloc failed: (result = %s)", ENUM_TO_STRING(HTTPAPI_RESULT, result));
                                                                }
                                                                else
                                                                {
                                                                    if (WinHttpQueryHeaders(
                                                                        requestHandle,
                                                                        WINHTTP_QUERY_RAW_HEADERS_CRLF,
                                                                        WINHTTP_HEADER_NAME_BY_INDEX,
                                                                        responseHeadersTemp,
                                                                        &responseHeadersTempLength,
                                                                        WINHTTP_NO_HEADER_INDEX))
                                                                    {
                                                                        wchar_t *next_token;
                                                                        wchar_t* token = wcstok_s(responseHeadersTemp, L"\r\n", &next_token);
                                                                        while ((token != NULL) &&
                                                                            (token[0] != L'\0'))
                                                                        {
                                                                            char* tokenTemp;
                                                                            size_t tokenTemp_size;

                                                                            tokenTemp_size = WideCharToMultiByte(CP_ACP, 0, token, -1, NULL, 0, NULL, NULL);
                                                                            if (tokenTemp_size == 0)
                                                                            {
                                                                                LogError("WideCharToMultiByte failed");
                                                                            }
                                                                            else
                                                                            {
                                                                                tokenTemp = (char*)malloc(sizeof(char)*tokenTemp_size);
                                                                                if (tokenTemp == NULL)
                                                                                {
                                                                                    LogError("malloc failed");
                                                                                }
                                                                                else
                                                                                {
                                                                                    if (WideCharToMultiByte(CP_ACP, 0, token, -1, tokenTemp, (int)tokenTemp_size, NULL, NULL) > 0)
                                                                                    {
                                                                                        /*breaking the token in 2 parts: everything before the first ":" and everything after the first ":"*/
                                                                                        /* if there is no such character, then skip it*/
                                                                                        /*if there is a : then replace is by a '\0' and so it breaks the original string in name and value*/

                                                                                        char* whereIsColon = strchr(tokenTemp, ':');
                                                                                        if (whereIsColon != NULL)
                                                                                        {
                                                                                            *whereIsColon = '\0';
                                                                                            if (HTTPHeaders_AddHeaderNameValuePair(responseHeadersHandle, tokenTemp, whereIsColon + 1) != HTTP_HEADERS_OK)
                                                                                            {
                                                                                                LogError("HTTPHeaders_AddHeaderNameValuePair failed");
                                                                                                result = HTTPAPI_HTTP_HEADERS_FAILED;
                                                                                                break;
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        LogError("WideCharToMultiByte failed");
                                                                                    }
                                                                                    free(tokenTemp);
                                                                                }
                                                                            }


                                                                            token = wcstok_s(NULL, L"\r\n", &next_token);
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        LogError("WinHttpQueryHeaders failed");
                                                                    }

                                                                    free(responseHeadersTemp);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        (void)WinHttpCloseHandle(requestHandle);
                                    }
                                }
                                free(headersTemp);
                            }
                        }
                        free(relativePathTemp);
                    }
                    free((void*)headers2);
                }
                else
                {
                    result = HTTPAPI_ALLOC_FAILED; /*likely*/
                    LogError("ConstructHeadersString failed");
                }
            }
        }
    }

    return result;
}
Ejemplo n.º 15
0
static int winhttp_connect(
	winhttp_subtransport *t)
{
	wchar_t *wide_host;
	int32_t port;
	wchar_t *wide_ua;
	git_buf ua = GIT_BUF_INIT;
	int error = -1;
	int default_timeout = TIMEOUT_INFINITE;
	int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
	DWORD protocols =
		WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
		WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
		WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;

	t->session = NULL;
	t->connection = NULL;

	/* Prepare port */
	if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
		return -1;

	/* Prepare host */
	if (git__utf8_to_16_alloc(&wide_host, t->connection_data.host) < 0) {
		giterr_set(GITERR_OS, "unable to convert host to wide characters");
		return -1;
	}


	if ((error = git_http__user_agent(&ua)) < 0) {
		git__free(wide_host);
		return error;
	}

	if (git__utf8_to_16_alloc(&wide_ua, git_buf_cstr(&ua)) < 0) {
		giterr_set(GITERR_OS, "unable to convert host to wide characters");
		git__free(wide_host);
		git_buf_free(&ua);
		return -1;
	}

	git_buf_free(&ua);

	/* Establish session */
	t->session = WinHttpOpen(
		wide_ua,
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS,
		0);

	if (!t->session) {
		giterr_set(GITERR_OS, "failed to init WinHTTP");
		goto on_error;
	}

	/*
	 * Do a best-effort attempt to enable TLS 1.2 but allow this to
	 * fail; if TLS 1.2 support is not available for some reason,
	 * ignore the failure (it will keep the default protocols).
	 */
	WinHttpSetOption(t->session,
		WINHTTP_OPTION_SECURE_PROTOCOLS,
		&protocols,
		sizeof(protocols));

	if (!WinHttpSetTimeouts(t->session, default_timeout, default_connect_timeout, default_timeout, default_timeout)) {
		giterr_set(GITERR_OS, "failed to set timeouts for WinHTTP");
		goto on_error;
	}


	/* Establish connection */
	t->connection = WinHttpConnect(
		t->session,
		wide_host,
		(INTERNET_PORT) port,
		0);

	if (!t->connection) {
		giterr_set(GITERR_OS, "failed to connect to host");
		goto on_error;
	}

	if (WinHttpSetStatusCallback(t->connection, winhttp_status, WINHTTP_CALLBACK_FLAG_SECURE_FAILURE, 0) == WINHTTP_INVALID_STATUS_CALLBACK) {
		giterr_set(GITERR_OS, "failed to set status callback");
		goto on_error;
	}

	error = 0;

on_error:
	if (error < 0)
		winhttp_close_connection(t);

	git__free(wide_host);
	git__free(wide_ua);

	return error;
}