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; }
static int winhttp_connect( winhttp_subtransport *t, const char *url) { wchar_t *ua = L"git/1.0 (libgit2 " WIDEN(LIBGIT2_VERSION) L")"; git_win32_path host; int32_t port; const char *default_port = "80"; /* Prepare port */ if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0) return -1; /* Prepare host */ git_win32_path_from_c(host, t->connection_data.host); /* 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, QT_TRANSLATE_NOOP("libgit2", "Failed to init WinHTTP")); return -1; } /* Establish connection */ t->connection = WinHttpConnect( t->session, host, (INTERNET_PORT) port, 0); if (!t->connection) { giterr_set(GITERR_OS, QT_TRANSLATE_NOOP("libgit2", "Failed to connect to host")); return -1; } return 0; }
BOOL APICaller::GetConnection() { if (connection != NULL) { return TRUE; } session = WinHttpOpen(L"GenericAPICaller", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (session != NULL) { connection = WinHttpConnect(session, siteUrl, INTERNET_DEFAULT_HTTPS_PORT, 0); if (connection != NULL) { return TRUE; } WinHttpCloseHandle(session); session = NULL; } return FALSE; }
/* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":80 */ Py_INCREF(((PyObject *)__pyx_v_ret)); __pyx_r = ((PyObject *)__pyx_v_ret); goto __pyx_L0; goto __pyx_L2; } __pyx_L2:; __pyx_r = Py_None; Py_INCREF(Py_None); goto __pyx_L0; __pyx_L1:; Py_XDECREF(__pyx_2); __Pyx_AddTraceback("_pymfclib_winhttp.getIEProxyConfigForCurrentUser"); __pyx_r = 0; __pyx_L0:; Py_DECREF(__pyx_v_ret); return __pyx_r; } static int __pyx_f_17_pymfclib_winhttp_14WinHTTPSession___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_f_17_pymfclib_winhttp_14WinHTTPSession___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_agent = 0; HINTERNET __pyx_v_handle; int __pyx_r; __pyx_t_17_pymfclib_winhttp_PYMFC_WCHAR *__pyx_1; int __pyx_2; static char *__pyx_argnames[] = {"agent",0}; if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_agent)) return -1; Py_INCREF(__pyx_v_self); Py_INCREF(__pyx_v_agent); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":87 */ __pyx_1 = PyUnicode_AsUnicode(__pyx_v_agent); if (__pyx_1 == NULL) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 87; goto __pyx_L1;} __pyx_v_handle = WinHttpOpen(__pyx_1,WINHTTP_ACCESS_TYPE_NO_PROXY,NULL,NULL,0); /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":88 */ __pyx_2 = (!(__pyx_v_handle != 0)); if (__pyx_2) { pymRaiseWin32Err(); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 89; goto __pyx_L1;} goto __pyx_L2; } __pyx_L2:; /* "c:\src\ip\pymfc\pymfclib\_pymfclib_winhttp.pyx":90 */ ((struct __pyx_obj_17_pymfclib_winhttp_WinHTTPSession *)__pyx_v_self)->hInternet = __pyx_v_handle; __pyx_r = 0; goto __pyx_L0; __pyx_L1:; __Pyx_AddTraceback("_pymfclib_winhttp.WinHTTPSession.__init__"); __pyx_r = -1; __pyx_L0:; Py_DECREF(__pyx_v_self); Py_DECREF(__pyx_v_agent); return __pyx_r; }
void WinHttpIO::setuseragent(string* useragent) { string wuseragent; wuseragent.resize((useragent->size() + 1) * sizeof(wchar_t)); wuseragent.resize(sizeof(wchar_t) * (MultiByteToWideChar(CP_UTF8, 0, useragent->c_str(), -1, (wchar_t*)wuseragent.data(), wuseragent.size() / sizeof(wchar_t) + 1) - 1)); // create the session handle using the default settings. hSession = WinHttpOpen((LPCWSTR)wuseragent.data(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof (protocols)); }
void shoes_winhttp(LPCWSTR host, INTERNET_PORT port, LPCWSTR path, TCHAR **mem, ULONG memlen, HANDLE file, LPDWORD size, shoes_download_handler handler, void *data) { DWORD len = 0, rlen = 0, status = 0, complete = 0, flen = 0, total = 0, written = 0; LPTSTR buf = SHOE_ALLOC_N(TCHAR, SHOES_BUFSIZE); LPTSTR fbuf = SHOE_ALLOC_N(TCHAR, SHOES_CHUNKSIZE); LPWSTR uagent = SHOE_ALLOC_N(WCHAR, SHOES_BUFSIZE); HINTERNET sess = NULL, conn = NULL, req = NULL; SHOES_TIME last = 0; if (buf == NULL || fbuf == NULL || uagent == NULL) goto done; _snwprintf(uagent, SHOES_BUFSIZE, L"Shoes/0.r%d (%S) %S/%d", SHOES_REVISION, SHOES_PLATFORM, SHOES_RELEASE_NAME, SHOES_BUILD_DATE); sess = WinHttpOpen(uagent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (sess == NULL) goto done; conn = WinHttpConnect(sess, host, port, 0); if (conn == NULL) goto done; req = WinHttpOpenRequest(conn, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (req == NULL) goto done; if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0)) goto done; if (!WinHttpReceiveResponse(req, NULL)) goto done; len = sizeof(DWORD); if (!WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &len, NULL)) goto done; else { shoes_download_event event; event.stage = SHOES_HTTP_STATUS; event.status = status; if (handler != NULL) handler(&event, data); } shoes_winhttp_headers(req, handler, data); *size = 0; len = sizeof(buf); if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_LENGTH, NULL, buf, &len, NULL)) { *size = _wtoi((wchar_t *)buf); if (*mem != NULL && *size > memlen) { SHOE_REALLOC_N(*mem, char, (memlen = *size)); if (*mem == NULL) goto done; }
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; }
static void test_async( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; char buffer[1024]; info.test = async_test; info.count = sizeof(async_test) / sizeof(async_test[0]); info.index = 0; info.wait = CreateEventW( NULL, FALSE, FALSE, NULL ); ses = WinHttpOpen( user_agent, 0, NULL, NULL, WINHTTP_FLAG_ASYNC ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_query_data, __LINE__ ); ret = WinHttpQueryDataAvailable( req, NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_read_data, __LINE__ ); ret = WinHttpReadData( req, buffer, sizeof(buffer), NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); WaitForSingleObject( info.wait, INFINITE ); CloseHandle( info.wait ); }
char *HTTP_get_first_block_if_possible(wchar_t *host, wchar_t *path, wchar_t *agent_name) { BOOL bResults; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; char *rt; hSession = WinHttpOpen(agent_name, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession==NULL) return NULL; hConnect = WinHttpConnect( hSession, host, INTERNET_DEFAULT_HTTP_PORT, 0); if (hConnect==NULL) return NULL; hRequest = WinHttpOpenRequest( hConnect, NULL, path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest==NULL) return NULL; bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if(bResults==FALSE) return NULL; bResults = WinHttpReceiveResponse( hRequest, NULL ); if(bResults==FALSE) return NULL; LPSTR pszOutBuffer; DWORD dwDownloaded = 0; DWORD dwSize = 0; // Check only for first portion! if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) ) return NULL; pszOutBuffer = malloc (dwSize+1); ZeroMemory(pszOutBuffer, dwSize+1); if(WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) rt=pszOutBuffer; else { free (pszOutBuffer); rt=NULL; }; if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return rt; };
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; }
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; }
CHttpClient::CHttpClient(const wchar_t *app_name) { ResetError(); hSession = WinHttpOpen(app_name? app_name:L"NVIDIA HTTP Client", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); }
/*! * @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; }
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; }
bool GameJoltAPI::SendRequest( CStdString &output, CStdString url ) { // The private key must be set to send a request. if ( m_GamePrivateKey == _T("") ) { m_ErrorMessage += _T("(You must put in your game's private key before you can use any of the API functions.)"); return false; } //////////////////////////////////// // Let's form the URL first. url = GJAPI_ROOT + GJAPI_VERSION + url; CStdString signature( md5( CStdStringA( _T("http://") + GJAPI_SERVER + url + m_GamePrivateKey ) ) ); url += _T("&signature=") + signature; // Now let's build the request. BOOL ret = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; hSession = WinHttpOpen ( L"Game Jolt API Construct/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if ( hSession ) hConnect = WinHttpConnect ( hSession, CStdStringW( GJAPI_SERVER ), INTERNET_DEFAULT_PORT, 0 ); else m_ErrorMessage += _T("(Could not open HTTP session.)"); if ( hConnect ) hRequest = WinHttpOpenRequest ( hConnect, L"GET", CStdStringW( url ), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH ); else m_ErrorMessage += _T("(Could not connect to the HTTP session.)"); if ( hRequest ) ret = WinHttpSendRequest ( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); else m_ErrorMessage += _T("(Could not set up the HTTP request.)"); if ( ret ) ret = WinHttpReceiveResponse( hRequest, NULL ); else m_ErrorMessage += _T("(Could not send the HTTP request.)"); DWORD bufferSize = 0; DWORD outputDownloaded = 0; LPSTR outputBuffer = 0; // Keep checking for data until there is nothing left. if ( ret ) { do { // Check for available data. bufferSize = 0; WinHttpQueryDataAvailable( hRequest, &bufferSize ); // Allocate space for the buffer. outputBuffer = new char[bufferSize + 1]; if ( outputBuffer ) { // Read the data. ZeroMemory( outputBuffer, bufferSize + 1 ); if ( WinHttpReadData( hRequest, (LPVOID)outputBuffer, bufferSize, &outputDownloaded ) ) output += outputBuffer; // Free the memory allocated to the buffer. delete [] outputBuffer; } } while( bufferSize > 0 ); } else m_ErrorMessage += _T("(Did not get a response from the server.)"); if ( hRequest ) WinHttpCloseHandle( hRequest ); if ( hConnect ) WinHttpCloseHandle( hConnect ); if ( hSession ) WinHttpCloseHandle( hSession ); return true; }
khm_int32 HttpRequest::FetchResource(const wchar_t * domain, const wchar_t * resource, const wchar_t ** mimetypes) { HANDLE hFile = INVALID_HANDLE_VALUE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; DWORD nTotalBytes = 0; BOOL bContinue = TRUE; khm_int32 rv = KHM_ERROR_GENERAL; hSession = WinHttpOpen(USER_AGENT, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) { ReportStatus(KHERR_ERROR, L"Can't create HTTP session", L"%s", GetLastErrorString().c_str()); goto done; } hConnect = WinHttpConnect(hSession, domain, INTERNET_DEFAULT_HTTP_PORT, 0); if (hConnect == NULL) { ReportStatus(KHERR_ERROR, L"Can't open HTTP connection", L"%s", GetLastErrorString().c_str()); goto done; } hRequest = WinHttpOpenRequest(hConnect, L"GET", resource, NULL, WINHTTP_NO_REFERER, mimetypes, WINHTTP_FLAG_ESCAPE_PERCENT); if (hRequest == NULL) { ReportStatus(KHERR_ERROR, L"Can't open request", L"%s", GetLastErrorString().c_str()); goto done; } { DWORD opt; opt = WINHTTP_DISABLE_AUTHENTICATION; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; opt = WINHTTP_DISABLE_COOKIES; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; opt = WINHTTP_DISABLE_KEEP_ALIVE; if (!WinHttpSetOption(hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &opt, sizeof(opt))) goto done; } rv = KHM_ERROR_NOT_FOUND; if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) { ReportStatus(KHERR_ERROR, L"Can't send request to server", L"Unable to send HTTP request to server at %s.\n" L"%s", domain, GetLastErrorString().c_str()); goto done; } if (!WinHttpReceiveResponse(hRequest, NULL)) { ReportStatus(KHERR_ERROR, L"Error while receiving response", L"%s", GetLastErrorString().c_str()); goto done; } rv = KHM_ERROR_GENERAL; { DWORD status = 0; DWORD nb = sizeof(status); if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE|WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &nb, WINHTTP_NO_HEADER_INDEX)) { ReportStatus(KHERR_ERROR, L"Error while querying response status", L"%s", GetLastErrorString().c_str()); goto done; } if (status == HTTP_STATUS_NOT_FOUND) { switch (m_method) { case ByFavIcon: // Status reports are ignored for Favicon searches // anyway. break; case ByGravatar: ReportStatus(KHERR_ERROR, L"Could not find Gravatar", L"An icon could not be found for %s on %s.\n", m_target.c_str(), domain); break; default: ReportStatus(KHERR_ERROR, L"The requested resource was not found", L"The requested resource was not found on %s.", domain); break; } rv = KHM_ERROR_NOT_FOUND; goto done; } if (status != HTTP_STATUS_OK) { ReportStatus(KHERR_ERROR, L"The request failed", L"The server at %s returned an unexpected status (%d)", domain, status); rv = KHM_ERROR_GENERAL; goto done; } } { wchar_t contenttype[128]; DWORD nb = sizeof(contenttype); int i; if (WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, contenttype, &nb, WINHTTP_NO_HEADER_INDEX)) { std::wstring::size_type epos; epos = m_path.rfind(L'.'); if (epos != std::wstring::npos) m_path.erase(epos); for (i=0; i < ARRAYLENGTH(content_type_map); i++) { if (!_wcsicmp(contenttype, content_type_map[i].content_type)) break; } if (i < ARRAYLENGTH(content_type_map)) { m_path.append(content_type_map[i].extension); } else { ReportStatus(KHERR_WARNING, L"Unknown content type", L"The content type %s was not expected for this request.", contenttype); } } else { ReportStatus(KHERR_WARNING, L"Could not query response content type", L"%s", GetLastErrorString().c_str()); } } /* The request went through. Create the file now */ hFile = CreateFile(m_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_TEMPORARY, NULL); if (hFile == INVALID_HANDLE_VALUE) { ReportStatus(KHERR_ERROR, L"Can't create file", L"%s", GetLastErrorString().c_str()); goto done; } while (nTotalBytes < MAX_ICON_SIZE && bContinue) { DWORD nBytes = 0; BYTE * buffer = NULL; DWORD nRead = 0; DWORD nWritten = 0; bContinue = FALSE; if (!WinHttpQueryDataAvailable(hRequest, &nBytes)) break; if (nBytes == 0) { bContinue = TRUE; break; } if (nBytes + nTotalBytes > MAX_ICON_SIZE) break; buffer = PNEW BYTE[nBytes]; if (buffer == NULL) break; if (!WinHttpReadData(hRequest, buffer, nBytes, &nRead) || nRead == 0) { /* Fail */ } else { /* Data found */ if (WriteFile(hFile, buffer, nRead, &nWritten, NULL)) bContinue = TRUE; } delete [] buffer; nTotalBytes += nBytes; } if (bContinue) { /* Done with file */ rv = KHM_ERROR_SUCCESS; } else { /* File is incomplete */ ReportStatus(KHERR_ERROR, L"Download incomplete", L"The download was terminated unexpectedly."); DeleteFile(m_path.c_str()); } done: if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); ReportComplete(KHM_SUCCEEDED(rv)); return rv; }
DWORD WINAPI SendProc(LPVOID data) { DWORD dataSize = 0; DWORD bytesDownloaded = 0; LPSTR outBuffer; BOOL result = FALSE; HINTERNET session = NULL,connection = NULL,request = NULL; std::wstring *wurl = (std::wstring*)data; if( wurl == NULL ) { return result; } session = WinHttpOpen(GA_HOST.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if( session ) connection = WinHttpConnect( session, GA_HOST.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0 ); if( connection ) request = WinHttpOpenRequest( connection, L"GET", wurl->c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0 ); if( request ) result = WinHttpSendRequest( request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); //DWORD n = GetLastError(); if( result ) result = WinHttpReceiveResponse( request, NULL ); if( result ) { do { dataSize = 0; if( !WinHttpQueryDataAvailable( request, &dataSize ) ) return FALSE; outBuffer = new char[dataSize+1]; if( !outBuffer ) { return false; } else { ZeroMemory( outBuffer, dataSize+1 ); if( !WinHttpReadData( request, (LPVOID)outBuffer, dataSize, &bytesDownloaded ) ) { delete []outBuffer; return false; } // TODO: if you care about the response, please handle it here... // delete[] outBuffer; } } while( dataSize > 0 ); } // clean up if( request ) WinHttpCloseHandle( request ); if( connection ) WinHttpCloseHandle( connection ); if( session ) WinHttpCloseHandle( session ); delete wurl; return result; }
// 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; }
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; }
string fetchUrl(string server, string path) { BOOL bResults = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; string result; wstring wserver(server.begin(), server.end()); wstring wpath(path.begin(), path.end()); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"Penis Browser/1.1", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, wserver.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", wpath.c_str(), NULL, WINHTTP_NO_REFERER, NULL, NULL); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { DWORD dwSize = 0; do { DWORD dwDownloaded = 0; LPSTR pszOutBuffer; // Check for available data. WinHttpQueryDataAvailable(hRequest, &dwSize); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; // Read the Data. ZeroMemory(pszOutBuffer, dwSize + 1); if (WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) result.append(string(pszOutBuffer, dwDownloaded)); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } while (dwSize > 0); } // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return result; }
void main() { DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer = NULL; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; BOOL bResults = FALSE; hSession=WinHttpOpen(L"User-Agent",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0); if(hSession) { hConnect=WinHttpConnect(hSession,L"kinggigi.sinaapp.com",INTERNET_DEFAULT_HTTP_PORT,0); } if(hConnect) { hRequest=WinHttpOpenRequest(hConnect, L"POST",L"hello.php",L"HTTP/1.1", WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0); } LPCWSTR header=L"Content-type: application/x-www-form-urlencoded"; SIZE_T len = lstrlenW(header); WinHttpAddRequestHeaders(hRequest,header,DWORD(len), WINHTTP_ADDREQ_FLAG_ADD); if(hRequest) { std::string data="val1=10&val2=9"; const void *ss=(const char *)data.c_str(); bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, const_cast<void *>(ss), data.length(), data.length(), 0); ////bResults=WinHttpSendRequest(hRequest,WINHTTP_NO_ADDITIONAL_HEADERS, 0,WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); } if(bResults) { bResults=WinHttpReceiveResponse(hRequest,NULL); } if(bResults) { do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) { printf( "Error %u in WinHttpQueryDataAvailable.\n",GetLastError()); break; } if (!dwSize) break; pszOutBuffer = new char[dwSize+1]; if (!pszOutBuffer) { printf("Out of memory\n"); break; } ZeroMemory(pszOutBuffer, dwSize+1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) { printf( "Error %u in WinHttpReadData.\n", GetLastError()); } else { printf("%s", pszOutBuffer); } delete [] pszOutBuffer; if (!dwDownloaded) break; } while (dwSize > 0); } if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); system("pause"); }
BOOL DoBlockingHttpGet( const char* sRequestedPage, char* pBufferOut, const unsigned int /*nBufferOutSize*/, DWORD* pBytesRead ) { BOOL bResults = FALSE, bSuccess = FALSE; HINTERNET hSession = nullptr, hConnect = nullptr, hRequest = nullptr; WCHAR wBuffer[1024]; size_t nTemp; char* sDataDestOffset = &pBufferOut[0]; DWORD nBytesToRead = 0; DWORD nBytesFetched = 0; char sClientName[1024]; sprintf_s( sClientName, 1024, "Retro Achievements Client" ); WCHAR wClientNameBuffer[1024]; mbstowcs_s( &nTemp, wClientNameBuffer, 1024, sClientName, strlen(sClientName)+1 ); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen( wClientNameBuffer, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if( hSession != nullptr ) { hConnect = WinHttpConnect( hSession, L"www.retroachievements.org", INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP Request handle. if( hConnect != nullptr ) { mbstowcs_s( &nTemp, wBuffer, 1024, sRequestedPage, strlen(sRequestedPage)+1 ); hRequest = WinHttpOpenRequest( hConnect, L"GET", wBuffer, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); // Send a Request. if( hRequest != nullptr ) { bResults = WinHttpSendRequest( hRequest, L"Content-Type: application/x-www-form-urlencoded", 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if( WinHttpReceiveResponse( hRequest, NULL ) ) { nBytesToRead = 0; (*pBytesRead) = 0; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); while( nBytesToRead > 0 ) { char sHttpReadData[8192]; ZeroMemory( sHttpReadData, 8192*sizeof(char) ); assert( nBytesToRead <= 8192 ); if( nBytesToRead <= 8192 ) { nBytesFetched = 0; if( WinHttpReadData( hRequest, &sHttpReadData, nBytesToRead, &nBytesFetched ) ) { assert( nBytesToRead == nBytesFetched ); //Read: parse buffer memcpy( sDataDestOffset, sHttpReadData, nBytesFetched ); sDataDestOffset += nBytesFetched; (*pBytesRead) += nBytesFetched; } } bSuccess = TRUE; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); } } } } } // Close open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return bSuccess; }
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; }
bool HttpQuery(const HttpRequest& request, HttpResponse& response) { // initialize response.statusCode = -1; HINTERNET internet = NULL; HINTERNET connectedInternet = NULL; HINTERNET requestInternet = NULL; BOOL httpResult = FALSE; DWORD error = 0; std::deque<LPCWSTR> acceptTypes; std::deque<BufferPair> availableBuffers; // access http internet = WinHttpOpen(L"Raven", WINHTTP_ACCESS_TYPE_NO_PROXY, NULL, NULL, 0); error = GetLastError(); if (!internet) goto CLEANUP; // connect connectedInternet = WinHttpConnect(internet, request.server.c_str(), (int)request.port, 0); error = GetLastError(); if (!connectedInternet) goto CLEANUP; // open request for (int i = 0; i<(int)request.acceptTypes.size(); i++) { acceptTypes.push_front(request.acceptTypes[i].c_str()); } acceptTypes.push_front(0); requestInternet = WinHttpOpenRequest(connectedInternet, request.method.c_str(), request.query.c_str(), NULL, WINHTTP_NO_REFERER, &acceptTypes[0], (request.secure ? WINHTTP_FLAG_SECURE : 0)); error = GetLastError(); if (!requestInternet) goto CLEANUP; // authentication, cookie and request if (request.username != L"" && request.password != L"") { WinHttpSetCredentials(requestInternet, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_BASIC, request.username.c_str(), request.password.c_str(), NULL); } if (request.contentType != L"") { httpResult = WinHttpAddRequestHeaders(requestInternet, (L"Content-type:" + request.contentType).c_str(), -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD); } if (request.cookie != L"") { WinHttpAddRequestHeaders(requestInternet, (L"Cookie:" + request.cookie).c_str(), -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD); } // extra headers for (auto it = request.extraHeaders.begin(); it != request.extraHeaders.end(); it++) { std::wstring key = it->first; std::wstring value = it->second; WinHttpAddRequestHeaders(requestInternet, (key + L":" + value).c_str(), -1, WINHTTP_ADDREQ_FLAG_REPLACE | WINHTTP_ADDREQ_FLAG_ADD); } if (request.body.size()>0) { httpResult = WinHttpSendRequest(requestInternet, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (LPVOID)&request.body[0], (int)request.body.size(), (int)request.body.size(), NULL); } else { httpResult = WinHttpSendRequest(requestInternet, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, NULL); } error = GetLastError(); if (httpResult == FALSE) goto CLEANUP; // receive response httpResult = WinHttpReceiveResponse(requestInternet, NULL); error = GetLastError(); if (httpResult != TRUE) goto CLEANUP; DWORD headerLength = sizeof(DWORD); // read response status code DWORD statusCode = 0; httpResult = WinHttpQueryHeaders(requestInternet, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &headerLength, WINHTTP_NO_HEADER_INDEX); error = GetLastError(); if (httpResult == FALSE) goto CLEANUP; response.statusCode = statusCode; // read respons cookie httpResult = WinHttpQueryHeaders(requestInternet, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, NULL, &headerLength, WINHTTP_NO_HEADER_INDEX); error = GetLastError(); if (error == ERROR_INSUFFICIENT_BUFFER) { wchar_t* rawHeader = new wchar_t[headerLength / sizeof(wchar_t)]; ZeroMemory(rawHeader, headerLength); httpResult = WinHttpQueryHeaders(requestInternet, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, rawHeader, &headerLength, WINHTTP_NO_HEADER_INDEX); const wchar_t* cookieStart = wcsstr(rawHeader, L"Cookie:"); if (cookieStart) { const wchar_t* cookieEnd = wcsstr(cookieStart, L";"); if (cookieEnd) { response.cookie = std::wstring(cookieStart + 7, cookieEnd - cookieStart - 7); } } delete[] rawHeader; } // read response body while (true) { DWORD bytesAvailable = 0; BOOL queryDataAvailableResult = WinHttpQueryDataAvailable(requestInternet, &bytesAvailable); error = GetLastError(); if (queryDataAvailableResult == TRUE && bytesAvailable != 0) { char* utf8 = new char[bytesAvailable]; DWORD bytesRead = 0; BOOL readDataResult = WinHttpReadData(requestInternet, utf8, bytesAvailable, &bytesRead); error = GetLastError(); if (readDataResult == TRUE) { availableBuffers.push_front(BufferPair(utf8, bytesRead)); } else { delete[] utf8; } } else { break; } } // concatincate response body int totalSize = 0; for each (BufferPair p in availableBuffers) { totalSize += p.length; } response.body.resize(totalSize); if (totalSize>0) { char* utf8 = new char[totalSize]; { char* temp = utf8; for each (BufferPair p in availableBuffers) { memcpy(temp, p.buffer, p.length); temp += p.length; } }
static int winhttp_connect( winhttp_subtransport *t) { wchar_t *ua = L"git/1.0 (libgit2 " WIDEN(LIBGIT2_VERSION) L")"; wchar_t *wide_host; int32_t port; 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; } /* 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: if (error < 0) winhttp_close_connection(t); git__free(wide_host); return error; }
// Main entry point int __cdecl wmain() { HRESULT hr = S_OK; WS_ERROR* error = NULL; WS_SERVICE_PROXY* serviceProxy = NULL; WS_HEAP* heap = NULL; WS_ENDPOINT_ADDRESS address = {}; static const WS_STRING serviceUrl = WS_STRING_VALUE(L"http://terraservice.net/TerraService2.asmx"); WS_CHANNEL_PROPERTY channelPropertyArray[4]; WS_ADDRESSING_VERSION addressingVersion = WS_ADDRESSING_VERSION_TRANSPORT; WS_ENVELOPE_VERSION envelopeVersion = WS_ENVELOPE_VERSION_SOAP_1_1; WCHAR* place = NULL; WS_HTTP_PROXY_SETTING_MODE proxySettingMode = WS_HTTP_PROXY_SETTING_MODE_CUSTOM; WS_CUSTOM_HTTP_PROXY customProxy = {}; address.url = serviceUrl; WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions = {}; WINHTTP_PROXY_INFO proxyInfo = {}; HINTERNET session = NULL; channelPropertyArray[0].id = WS_CHANNEL_PROPERTY_ADDRESSING_VERSION; channelPropertyArray[0].value = &addressingVersion; channelPropertyArray[0].valueSize = sizeof(addressingVersion); channelPropertyArray[1].id = WS_CHANNEL_PROPERTY_ENVELOPE_VERSION; channelPropertyArray[1].value = &envelopeVersion; channelPropertyArray[1].valueSize = sizeof(envelopeVersion); channelPropertyArray[2].id = WS_CHANNEL_PROPERTY_HTTP_PROXY_SETTING_MODE; channelPropertyArray[2].value = &proxySettingMode; channelPropertyArray[2].valueSize = sizeof(proxySettingMode); channelPropertyArray[3].id = WS_CHANNEL_PROPERTY_CUSTOM_HTTP_PROXY; channelPropertyArray[3].value = &customProxy; channelPropertyArray[3].valueSize = sizeof(customProxy); // This part illustrates how to setup a HTTP header authentication security binding // against the HTTP proxy server in case it requires authentication. // declare and initialize a default windows credential WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL windowsCredential = {}; // zero out the struct windowsCredential.credential.credentialType = WS_STRING_WINDOWS_INTEGRATED_AUTH_CREDENTIAL_TYPE; // set the credential type // for illustration only; usernames and passwords should never be included in source files windowsCredential.username.chars = L"domain\\user"; windowsCredential.username.length = (ULONG)wcslen(windowsCredential.username.chars); windowsCredential.password.chars = L"password"; windowsCredential.password.length = (ULONG)wcslen(windowsCredential.password.chars); // declare and initialize properties to set the authentication scheme to Basic ULONG scheme = WS_HTTP_HEADER_AUTH_SCHEME_NEGOTIATE; ULONG target = WS_HTTP_HEADER_AUTH_TARGET_PROXY; WS_SECURITY_BINDING_PROPERTY httpProxyAuthBindingProperties[2] = { { WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_SCHEME, &scheme, sizeof(scheme) }, { WS_SECURITY_BINDING_PROPERTY_HTTP_HEADER_AUTH_TARGET, &target, sizeof(target) } }; // declare and initialize an HTTP header authentication security binding for the HTTP proxy server WS_HTTP_HEADER_AUTH_SECURITY_BINDING httpProxyAuthBinding = {}; // zero out the struct httpProxyAuthBinding.binding.bindingType = WS_HTTP_HEADER_AUTH_SECURITY_BINDING_TYPE; // set the binding type httpProxyAuthBinding.binding.properties = httpProxyAuthBindingProperties; httpProxyAuthBinding.binding.propertyCount = WsCountOf(httpProxyAuthBindingProperties); httpProxyAuthBinding.clientCredential = &windowsCredential.credential; // declare and initialize the array of all security bindings WS_SECURITY_BINDING* securityBindings[1] = { &httpProxyAuthBinding.binding }; // declare and initialize the security description WS_SECURITY_DESCRIPTION securityDescription = {}; // zero out the struct securityDescription.securityBindings = securityBindings; securityDescription.securityBindingCount = WsCountOf(securityBindings); // Create an error object for storing rich error information hr = WsCreateError( NULL, 0, &error); if (FAILED(hr)) { goto Exit; } // Create a heap to store deserialized data hr = WsCreateHeap( /*maxSize*/ 2048, /*trimSize*/ 512, NULL, 0, &heap, error); if (FAILED(hr)) { goto Exit; } session = WinHttpOpen(L"NWS Example", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (!session) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_RUN_INPROCESS | WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoProxyOptions.fAutoLogonIfChallenged = FALSE; WinHttpGetProxyForUrl( session, serviceUrl.chars, &autoProxyOptions, &proxyInfo); if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) { if (proxyInfo.lpszProxy) { customProxy.servers.chars = proxyInfo.lpszProxy; customProxy.servers.length = (ULONG)wcslen(proxyInfo.lpszProxy); } if (proxyInfo.lpszProxyBypass) { customProxy.bypass.chars = proxyInfo.lpszProxyBypass; customProxy.bypass.length = (ULONG)wcslen(proxyInfo.lpszProxyBypass); } } hr = WsCreateServiceProxy( WS_CHANNEL_TYPE_REQUEST, WS_HTTP_CHANNEL_BINDING, &securityDescription, NULL, 0, channelPropertyArray, WsCountOf(channelPropertyArray), &serviceProxy, error); if (FAILED(hr)) { goto Exit; } // Open channel to address hr = WsOpenServiceProxy( serviceProxy, &address, NULL, error); if (FAILED(hr)) { goto Exit; } for (int i = 0; i < 100; i++) { LonLatPt point = {10.0, 10.0}; hr = TerraServiceSoap_ConvertLonLatPtToNearestPlace( serviceProxy, &point, &place, heap, NULL, 0, NULL, error); if (FAILED(hr)) { goto Exit; } if (place != NULL) { wprintf(L"Place @ Lattitude=%f, Longitutde=%f is %s\n", point.Lon, point.Lat, place); } else { wprintf(L"Could not find any place for Lattitude=%f, Longitutde=%f\n", point.Lon, point.Lat); } fflush(stdout); hr = WsResetHeap( heap, error); if (FAILED(hr)) { goto Exit; } } Exit: if (FAILED(hr)) { // Print out the error PrintError(hr, error); } if (proxyInfo.lpszProxy) { ::GlobalFree(proxyInfo.lpszProxy); } if (proxyInfo.lpszProxyBypass) { ::GlobalFree(proxyInfo.lpszProxyBypass); } if (serviceProxy != NULL) { WsCloseServiceProxy(serviceProxy, NULL, NULL); WsFreeServiceProxy(serviceProxy); } if (!session) { WinHttpCloseHandle(session); } if (heap != NULL) { WsFreeHeap(heap); } if (error != NULL) { WsFreeError(error); } fflush(stdout); return SUCCEEDED(hr) ? 0 : -1; }
int _tmain(int argc, _TCHAR* argv[]) { // WinHTTP Sessions Overview | https://msdn.microsoft.com/en-us/library/windows/desktop/aa384270(v=vs.85).aspx DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, L"www.microsoft.com", INTERNET_DEFAULT_HTTPS_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", NULL, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError()); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; if (!pszOutBuffer) { printf("Out of memory\n"); dwSize = 0; } else { // Read the data. ZeroMemory(pszOutBuffer, dwSize + 1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) printf("Error %u in WinHttpReadData.\n", GetLastError()); else printf("%s", pszOutBuffer); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } } while (dwSize > 0); } // Report any errors. if (!bResults) printf("Error %d has occurred.\n", GetLastError()); // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return 0; }
// Detect any proxy configuration settings automatically. // static void windows_detect_autoproxy_settings() { if (log_flags.proxy_debug) { post_sysmon_msg("[proxy] automatic proxy check in progress"); } HINTERNET hWinHttp = NULL; WINHTTP_AUTOPROXY_OPTIONS autoproxy_options; WINHTTP_PROXY_INFO proxy_info; PARSED_URL purl; std::wstring network_test_url; size_t pos; memset(&autoproxy_options, 0, sizeof(autoproxy_options)); memset(&proxy_info, 0, sizeof(proxy_info)); autoproxy_options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoproxy_options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoproxy_options.fAutoLogonIfChallenged = TRUE; network_test_url = boinc_ascii_to_wide(nvc_config.network_test_url).c_str(); hWinHttp = WinHttpOpen( L"BOINC client", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL ); char msg[1024], buf[1024]; safe_strcpy(msg, "[proxy] "); if (WinHttpGetProxyForUrl(hWinHttp, network_test_url.c_str(), &autoproxy_options, &proxy_info)) { // Apparently there are some conditions where WinHttpGetProxyForUrl can return // success but where proxy_info.lpszProxy is null. Maybe related to UPNP? // // For the time being check to see if proxy_info.lpszProxy is non-null. // if (proxy_info.lpszProxy) { std::string proxy(boinc_wide_to_ascii(std::wstring(proxy_info.lpszProxy))); std::string new_proxy; if (log_flags.proxy_debug) { safe_strcat(msg, "proxy list: "); safe_strcat(msg, proxy.c_str()); } if (!proxy.empty()) { // Trim string if more than one proxy is defined // proxy list is defined as: // ([<scheme>=][<scheme>"://"]<server>[":"<port>]) // Find and erase first delimeter type. pos = proxy.find(';'); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Find and erase second delimeter type. pos = proxy.find(' '); if (pos != -1 ) { new_proxy = proxy.erase(pos); proxy = new_proxy; } // Parse the remaining url parse_url(proxy.c_str(), purl); // Store the results for future use. if (0 != strcmp(working_proxy_info.autodetect_server_name, purl.host)) { // Reset clients connection error detection path net_status.need_physical_connection = false; working_proxy_info.autodetect_protocol = purl.protocol; safe_strcpy(working_proxy_info.autodetect_server_name, purl.host); working_proxy_info.autodetect_port = purl.port; } if (log_flags.proxy_debug) { snprintf(buf, sizeof(buf), "proxy detected %s:%d", purl.host, purl.port); safe_strcat(msg, buf); } } } // Clean up if (proxy_info.lpszProxy) GlobalFree(proxy_info.lpszProxy); if (proxy_info.lpszProxyBypass) GlobalFree(proxy_info.lpszProxyBypass); } else { // We can get here if the user is switching from a network that // requires a proxy to one that does not require a proxy. working_proxy_info.autodetect_protocol = 0; safe_strcpy(working_proxy_info.autodetect_server_name, ""); working_proxy_info.autodetect_port = 0; if (log_flags.proxy_debug) { safe_strcat(msg, "no automatic proxy detected"); } } if (hWinHttp) WinHttpCloseHandle(hWinHttp); if (log_flags.proxy_debug) { post_sysmon_msg(msg); } }
static void test_connection_cache( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; info.test = cache_test; info.count = sizeof(cache_test) / sizeof(cache_test[0]); info.index = 0; info.wait = NULL; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ info.index = 0; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ }
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; }