1 /*
2  * Copyright (C) the libgit2 contributors. All rights reserved.
3  *
4  * This file is part of libgit2, distributed under the GNU GPL v2 with
5  * a Linking Exception. For full terms see the included COPYING file.
6  */
7 
8 #include "error.h"
9 
10 #include "utf-conv.h"
11 
12 #ifdef GIT_WINHTTP
13 # include <winhttp.h>
14 #endif
15 
git_win32_get_error_message(DWORD error_code)16 char *git_win32_get_error_message(DWORD error_code)
17 {
18 	LPWSTR lpMsgBuf = NULL;
19 	HMODULE hModule = NULL;
20 	char *utf8_msg = NULL;
21 	DWORD dwFlags =
22 		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
23 
24 	if (!error_code)
25 		return NULL;
26 
27 #ifdef GIT_WINHTTP
28 	/* Errors raised by WinHTTP are not in the system resource table */
29 	if (error_code >= WINHTTP_ERROR_BASE &&
30 		error_code <= WINHTTP_ERROR_LAST)
31 		hModule = GetModuleHandleW(L"winhttp");
32 #endif
33 
34 	GIT_UNUSED(hModule);
35 
36 	if (hModule)
37 		dwFlags |= FORMAT_MESSAGE_FROM_HMODULE;
38 	else
39 		dwFlags |= FORMAT_MESSAGE_FROM_SYSTEM;
40 
41 	if (FormatMessageW(dwFlags, hModule, error_code,
42 		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
43 		(LPWSTR)&lpMsgBuf, 0, NULL)) {
44 		/* Convert the message to UTF-8. If this fails, we will
45 		 * return NULL, which is a condition expected by the caller */
46 		if (git__utf16_to_8_alloc(&utf8_msg, lpMsgBuf) < 0)
47 			utf8_msg = NULL;
48 
49 		LocalFree(lpMsgBuf);
50 	}
51 
52 	return utf8_msg;
53 }
54