Update README.md
[puttycyg-ng.git] / windows / winstore.c
blobe28b1cb10c0bd47e9b6c975d29a1371f221558cd
1 /*
2 * winstore.c: Windows-specific implementation of the interface
3 * defined in storage.h.
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <limits.h>
9 #include "putty.h"
10 #include "storage.h"
12 #include <shlobj.h>
13 #ifndef CSIDL_APPDATA
14 #define CSIDL_APPDATA 0x001a
15 #endif
16 #ifndef CSIDL_LOCAL_APPDATA
17 #define CSIDL_LOCAL_APPDATA 0x001c
18 #endif
20 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
22 static const char hex[16] = "0123456789ABCDEF";
24 static int tried_shgetfolderpath = FALSE;
25 static HMODULE shell32_module = NULL;
26 typedef HRESULT (WINAPI *p_SHGetFolderPath_t)
27 (HWND, int, HANDLE, DWORD, LPTSTR);
28 static p_SHGetFolderPath_t p_SHGetFolderPath = NULL;
30 static void mungestr(const char *in, char *out)
32 int candot = 0;
34 while (*in) {
35 if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
36 *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
37 && !candot)) {
38 *out++ = '%';
39 *out++ = hex[((unsigned char) *in) >> 4];
40 *out++ = hex[((unsigned char) *in) & 15];
41 } else
42 *out++ = *in;
43 in++;
44 candot = 1;
46 *out = '\0';
47 return;
50 static void unmungestr(const char *in, char *out, int outlen)
52 while (*in) {
53 if (*in == '%' && in[1] && in[2]) {
54 int i, j;
56 i = in[1] - '0';
57 i -= (i > 9 ? 7 : 0);
58 j = in[2] - '0';
59 j -= (j > 9 ? 7 : 0);
61 *out++ = (i << 4) + j;
62 if (!--outlen)
63 return;
64 in += 3;
65 } else {
66 *out++ = *in++;
67 if (!--outlen)
68 return;
71 *out = '\0';
72 return;
75 void *open_settings_w(const char *sessionname, char **errmsg)
77 HKEY subkey1, sesskey;
78 int ret;
79 char *p;
81 *errmsg = NULL;
83 if (!sessionname || !*sessionname)
84 sessionname = "Default Settings";
86 p = snewn(3 * strlen(sessionname) + 1, char);
87 mungestr(sessionname, p);
89 ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
90 if (ret != ERROR_SUCCESS) {
91 sfree(p);
92 *errmsg = dupprintf("Unable to create registry key\n"
93 "HKEY_CURRENT_USER\\%s", puttystr);
94 return NULL;
96 ret = RegCreateKey(subkey1, p, &sesskey);
97 RegCloseKey(subkey1);
98 if (ret != ERROR_SUCCESS) {
99 *errmsg = dupprintf("Unable to create registry key\n"
100 "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
101 sfree(p);
102 return NULL;
104 sfree(p);
105 return (void *) sesskey;
108 void write_setting_s(void *handle, const char *key, const char *value)
110 if (handle)
111 RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
112 1 + strlen(value));
115 void write_setting_i(void *handle, const char *key, int value)
117 if (handle)
118 RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
119 (CONST BYTE *) &value, sizeof(value));
122 void close_settings_w(void *handle)
124 RegCloseKey((HKEY) handle);
127 void *open_settings_r(const char *sessionname)
129 HKEY subkey1, sesskey;
130 char *p;
132 if (!sessionname || !*sessionname)
133 sessionname = "Default Settings";
135 p = snewn(3 * strlen(sessionname) + 1, char);
136 mungestr(sessionname, p);
138 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
139 sesskey = NULL;
140 } else {
141 if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
142 sesskey = NULL;
144 RegCloseKey(subkey1);
147 sfree(p);
149 return (void *) sesskey;
152 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
154 DWORD type, size;
155 size = buflen;
157 if (!handle ||
158 RegQueryValueEx((HKEY) handle, key, 0,
159 &type, buffer, &size) != ERROR_SUCCESS ||
160 type != REG_SZ) return NULL;
161 else
162 return buffer;
165 int read_setting_i(void *handle, const char *key, int defvalue)
167 DWORD type, val, size;
168 size = sizeof(val);
170 if (!handle ||
171 RegQueryValueEx((HKEY) handle, key, 0, &type,
172 (BYTE *) &val, &size) != ERROR_SUCCESS ||
173 size != sizeof(val) || type != REG_DWORD)
174 return defvalue;
175 else
176 return val;
179 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
181 char *settingname;
182 FontSpec ret;
184 if (!read_setting_s(handle, name, ret.name, sizeof(ret.name)))
185 return 0;
186 settingname = dupcat(name, "IsBold", NULL);
187 ret.isbold = read_setting_i(handle, settingname, -1);
188 sfree(settingname);
189 if (ret.isbold == -1) return 0;
190 settingname = dupcat(name, "CharSet", NULL);
191 ret.charset = read_setting_i(handle, settingname, -1);
192 sfree(settingname);
193 if (ret.charset == -1) return 0;
194 settingname = dupcat(name, "Height", NULL);
195 ret.height = read_setting_i(handle, settingname, INT_MIN);
196 sfree(settingname);
197 if (ret.height == INT_MIN) return 0;
198 *result = ret;
199 return 1;
202 void write_setting_fontspec(void *handle, const char *name, FontSpec font)
204 char *settingname;
206 write_setting_s(handle, name, font.name);
207 settingname = dupcat(name, "IsBold", NULL);
208 write_setting_i(handle, settingname, font.isbold);
209 sfree(settingname);
210 settingname = dupcat(name, "CharSet", NULL);
211 write_setting_i(handle, settingname, font.charset);
212 sfree(settingname);
213 settingname = dupcat(name, "Height", NULL);
214 write_setting_i(handle, settingname, font.height);
215 sfree(settingname);
218 int read_setting_filename(void *handle, const char *name, Filename *result)
220 return !!read_setting_s(handle, name, result->path, sizeof(result->path));
223 void write_setting_filename(void *handle, const char *name, Filename result)
225 write_setting_s(handle, name, result.path);
228 void close_settings_r(void *handle)
230 RegCloseKey((HKEY) handle);
233 void del_settings(const char *sessionname)
235 HKEY subkey1;
236 char *p;
238 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
239 return;
241 p = snewn(3 * strlen(sessionname) + 1, char);
242 mungestr(sessionname, p);
243 RegDeleteKey(subkey1, p);
244 sfree(p);
246 RegCloseKey(subkey1);
249 struct enumsettings {
250 HKEY key;
251 int i;
254 void *enum_settings_start(void)
256 struct enumsettings *ret;
257 HKEY key;
259 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
260 return NULL;
262 ret = snew(struct enumsettings);
263 if (ret) {
264 ret->key = key;
265 ret->i = 0;
268 return ret;
271 char *enum_settings_next(void *handle, char *buffer, int buflen)
273 struct enumsettings *e = (struct enumsettings *) handle;
274 char *otherbuf;
275 otherbuf = snewn(3 * buflen, char);
276 if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
277 unmungestr(otherbuf, buffer, buflen);
278 sfree(otherbuf);
279 return buffer;
280 } else {
281 sfree(otherbuf);
282 return NULL;
286 void enum_settings_finish(void *handle)
288 struct enumsettings *e = (struct enumsettings *) handle;
289 RegCloseKey(e->key);
290 sfree(e);
293 static void hostkey_regname(char *buffer, const char *hostname,
294 int port, const char *keytype)
296 int len;
297 strcpy(buffer, keytype);
298 strcat(buffer, "@");
299 len = strlen(buffer);
300 len += sprintf(buffer + len, "%d:", port);
301 mungestr(hostname, buffer + strlen(buffer));
304 int verify_host_key(const char *hostname, int port,
305 const char *keytype, const char *key)
307 char *otherstr, *regname;
308 int len;
309 HKEY rkey;
310 DWORD readlen;
311 DWORD type;
312 int ret, compare;
314 len = 1 + strlen(key);
317 * Now read a saved key in from the registry and see what it
318 * says.
320 otherstr = snewn(len, char);
321 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
323 hostkey_regname(regname, hostname, port, keytype);
325 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
326 &rkey) != ERROR_SUCCESS)
327 return 1; /* key does not exist in registry */
329 readlen = len;
330 ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
332 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
333 !strcmp(keytype, "rsa")) {
335 * Key didn't exist. If the key type is RSA, we'll try
336 * another trick, which is to look up the _old_ key format
337 * under just the hostname and translate that.
339 char *justhost = regname + 1 + strcspn(regname, ":");
340 char *oldstyle = snewn(len + 10, char); /* safety margin */
341 readlen = len;
342 ret = RegQueryValueEx(rkey, justhost, NULL, &type,
343 oldstyle, &readlen);
345 if (ret == ERROR_SUCCESS && type == REG_SZ) {
347 * The old format is two old-style bignums separated by
348 * a slash. An old-style bignum is made of groups of
349 * four hex digits: digits are ordered in sensible
350 * (most to least significant) order within each group,
351 * but groups are ordered in silly (least to most)
352 * order within the bignum. The new format is two
353 * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
354 * A nonzero except in the special case 0x0, which
355 * doesn't appear anyway in RSA keys) separated by a
356 * comma. All hex digits are lowercase in both formats.
358 char *p = otherstr;
359 char *q = oldstyle;
360 int i, j;
362 for (i = 0; i < 2; i++) {
363 int ndigits, nwords;
364 *p++ = '0';
365 *p++ = 'x';
366 ndigits = strcspn(q, "/"); /* find / or end of string */
367 nwords = ndigits / 4;
368 /* now trim ndigits to remove leading zeros */
369 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
370 ndigits--;
371 /* now move digits over to new string */
372 for (j = 0; j < ndigits; j++)
373 p[ndigits - 1 - j] = q[j ^ 3];
374 p += ndigits;
375 q += nwords * 4;
376 if (*q) {
377 q++; /* eat the slash */
378 *p++ = ','; /* add a comma */
380 *p = '\0'; /* terminate the string */
384 * Now _if_ this key matches, we'll enter it in the new
385 * format. If not, we'll assume something odd went
386 * wrong, and hyper-cautiously do nothing.
388 if (!strcmp(otherstr, key))
389 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
390 strlen(otherstr) + 1);
394 RegCloseKey(rkey);
396 compare = strcmp(otherstr, key);
398 sfree(otherstr);
399 sfree(regname);
401 if (ret == ERROR_MORE_DATA ||
402 (ret == ERROR_SUCCESS && type == REG_SZ && compare))
403 return 2; /* key is different in registry */
404 else if (ret != ERROR_SUCCESS || type != REG_SZ)
405 return 1; /* key does not exist in registry */
406 else
407 return 0; /* key matched OK in registry */
410 void store_host_key(const char *hostname, int port,
411 const char *keytype, const char *key)
413 char *regname;
414 HKEY rkey;
416 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
418 hostkey_regname(regname, hostname, port, keytype);
420 if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
421 &rkey) == ERROR_SUCCESS) {
422 RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
423 RegCloseKey(rkey);
424 } /* else key does not exist in registry */
426 sfree(regname);
430 * Open (or delete) the random seed file.
432 enum { DEL, OPEN_R, OPEN_W };
433 static int try_random_seed(char const *path, int action, HANDLE *ret)
435 if (action == DEL) {
436 remove(path);
437 *ret = INVALID_HANDLE_VALUE;
438 return FALSE; /* so we'll do the next ones too */
441 *ret = CreateFile(path,
442 action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
443 action == OPEN_W ? 0 : (FILE_SHARE_READ |
444 FILE_SHARE_WRITE),
445 NULL,
446 action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
447 action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
448 NULL);
450 return (*ret != INVALID_HANDLE_VALUE);
453 static HANDLE access_random_seed(int action)
455 HKEY rkey;
456 DWORD type, size;
457 HANDLE rethandle;
458 char seedpath[2 * MAX_PATH + 10] = "\0";
461 * Iterate over a selection of possible random seed paths until
462 * we find one that works.
464 * We do this iteration separately for reading and writing,
465 * meaning that we will automatically migrate random seed files
466 * if a better location becomes available (by reading from the
467 * best location in which we actually find one, and then
468 * writing to the best location in which we can _create_ one).
472 * First, try the location specified by the user in the
473 * Registry, if any.
475 size = sizeof(seedpath);
476 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
477 ERROR_SUCCESS) {
478 int ret = RegQueryValueEx(rkey, "RandSeedFile",
479 0, &type, seedpath, &size);
480 if (ret != ERROR_SUCCESS || type != REG_SZ)
481 seedpath[0] = '\0';
482 RegCloseKey(rkey);
484 if (*seedpath && try_random_seed(seedpath, action, &rethandle))
485 return rethandle;
489 * Next, try the user's local Application Data directory,
490 * followed by their non-local one. This is found using the
491 * SHGetFolderPath function, which won't be present on all
492 * versions of Windows.
494 if (!tried_shgetfolderpath) {
495 /* This is likely only to bear fruit on systems with IE5+
496 * installed, or WinMe/2K+. There is some faffing with
497 * SHFOLDER.DLL we could do to try to find an equivalent
498 * on older versions of Windows if we cared enough.
499 * However, the invocation below requires IE5+ anyway,
500 * so stuff that. */
501 shell32_module = LoadLibrary("SHELL32.DLL");
502 if (shell32_module) {
503 p_SHGetFolderPath = (p_SHGetFolderPath_t)
504 GetProcAddress(shell32_module, "SHGetFolderPathA");
507 if (p_SHGetFolderPath) {
508 if (SUCCEEDED(p_SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA,
509 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
510 strcat(seedpath, "\\PUTTY.RND");
511 if (try_random_seed(seedpath, action, &rethandle))
512 return rethandle;
515 if (SUCCEEDED(p_SHGetFolderPath(NULL, CSIDL_APPDATA,
516 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
517 strcat(seedpath, "\\PUTTY.RND");
518 if (try_random_seed(seedpath, action, &rethandle))
519 return rethandle;
524 * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
525 * user's home directory.
528 int len, ret;
530 len =
531 GetEnvironmentVariable("HOMEDRIVE", seedpath,
532 sizeof(seedpath));
533 ret =
534 GetEnvironmentVariable("HOMEPATH", seedpath + len,
535 sizeof(seedpath) - len);
536 if (ret != 0) {
537 strcat(seedpath, "\\PUTTY.RND");
538 if (try_random_seed(seedpath, action, &rethandle))
539 return rethandle;
544 * And finally, fall back to C:\WINDOWS.
546 GetWindowsDirectory(seedpath, sizeof(seedpath));
547 strcat(seedpath, "\\PUTTY.RND");
548 if (try_random_seed(seedpath, action, &rethandle))
549 return rethandle;
552 * If even that failed, give up.
554 return INVALID_HANDLE_VALUE;
557 void read_random_seed(noise_consumer_t consumer)
559 HANDLE seedf = access_random_seed(OPEN_R);
561 if (seedf != INVALID_HANDLE_VALUE) {
562 while (1) {
563 char buf[1024];
564 DWORD len;
566 if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
567 consumer(buf, len);
568 else
569 break;
571 CloseHandle(seedf);
575 void write_random_seed(void *data, int len)
577 HANDLE seedf = access_random_seed(OPEN_W);
579 if (seedf != INVALID_HANDLE_VALUE) {
580 DWORD lenwritten;
582 WriteFile(seedf, data, len, &lenwritten, NULL);
583 CloseHandle(seedf);
588 * Recursively delete a registry key and everything under it.
590 static void registry_recursive_remove(HKEY key)
592 DWORD i;
593 char name[MAX_PATH + 1];
594 HKEY subkey;
596 i = 0;
597 while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
598 if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
599 registry_recursive_remove(subkey);
600 RegCloseKey(subkey);
602 RegDeleteKey(key, name);
606 void cleanup_all(void)
608 HKEY key;
609 int ret;
610 char name[MAX_PATH + 1];
612 /* ------------------------------------------------------------
613 * Wipe out the random seed file, in all of its possible
614 * locations.
616 access_random_seed(DEL);
618 /* ------------------------------------------------------------
619 * Destroy all registry information associated with PuTTY.
623 * Open the main PuTTY registry key and remove everything in it.
625 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
626 ERROR_SUCCESS) {
627 registry_recursive_remove(key);
628 RegCloseKey(key);
631 * Now open the parent key and remove the PuTTY main key. Once
632 * we've done that, see if the parent key has any other
633 * children.
635 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
636 &key) == ERROR_SUCCESS) {
637 RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
638 ret = RegEnumKey(key, 0, name, sizeof(name));
639 RegCloseKey(key);
641 * If the parent key had no other children, we must delete
642 * it in its turn. That means opening the _grandparent_
643 * key.
645 if (ret != ERROR_SUCCESS) {
646 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
647 &key) == ERROR_SUCCESS) {
648 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
649 RegCloseKey(key);
654 * Now we're done.