1/*
2 * Source file for missing WinCE functionality
3 * Copyright © 2012 RealVNC Ltd.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20#include "missing.h"
21
22#include <config.h>
23#include <libusbi.h>
24
25#include <windows.h>
26
27// The registry path to store environment variables
28#define ENVIRONMENT_REG_PATH _T("Software\\libusb\\environment")
29
30/* Workaround getenv not being available on WinCE.
31 * Instead look in HKLM\Software\libusb\environment */
32char *getenv(const char *name)
33{
34	static char value[MAX_PATH];
35	TCHAR wValue[MAX_PATH];
36	WCHAR wName[MAX_PATH];
37	DWORD dwType, dwData;
38	HKEY hkey;
39	LONG rc;
40
41	if (!name)
42		return NULL;
43
44	if (MultiByteToWideChar(CP_UTF8, 0, name, -1, wName, MAX_PATH) <= 0) {
45		usbi_dbg("Failed to convert environment variable name to wide string");
46		return NULL;
47	}
48	wName[MAX_PATH - 1] = 0; // Be sure it's NUL terminated
49
50	rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, ENVIRONMENT_REG_PATH, 0, KEY_QUERY_VALUE, &hkey);
51	if (rc != ERROR_SUCCESS) {
52		usbi_dbg("Failed to open registry key for getenv with error %d", rc);
53		return NULL;
54	}
55
56	// Attempt to read the key
57	dwData = sizeof(wValue);
58	rc = RegQueryValueEx(hkey, wName, NULL, &dwType,
59		(LPBYTE)&wValue, &dwData);
60	RegCloseKey(hkey);
61	if (rc != ERROR_SUCCESS) {
62		usbi_dbg("Failed to read registry key value for getenv with error %d", rc);
63		return NULL;
64	}
65	if (dwType != REG_SZ) {
66		usbi_dbg("Registry value was of type %d instead of REG_SZ", dwType);
67		return NULL;
68	}
69
70	// Success in reading the key, convert from WCHAR to char
71	if (WideCharToMultiByte(CP_UTF8, 0,
72			wValue, dwData / sizeof(*wValue),
73			value, MAX_PATH,
74			NULL, NULL) <= 0) {
75		usbi_dbg("Failed to convert environment variable value to narrow string");
76		return NULL;
77	}
78	value[MAX_PATH - 1] = 0; // Be sure it's NUL terminated
79	return value;
80}
81