2 * winstore.c: Windows-specific implementation of the interface
3 * defined in storage.h.
14 #define CSIDL_APPDATA 0x001a
16 #ifndef CSIDL_LOCAL_APPDATA
17 #define CSIDL_LOCAL_APPDATA 0x001c
20 static const char *const reg_jumplist_key = PUTTY_REG_POS "\\Jumplist";
21 static const char *const reg_jumplist_value = "Recent sessions";
22 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
24 static const char hex[16] = "0123456789ABCDEF";
26 static int tried_shgetfolderpath = FALSE;
27 static HMODULE shell32_module = NULL;
28 DECL_WINDOWS_FUNCTION(static, HRESULT, SHGetFolderPathA,
29 (HWND, int, HANDLE, DWORD, LPSTR));
31 static void mungestr(const char *in, char *out)
36 if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
37 *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
40 *out++ = hex[((unsigned char) *in) >> 4];
41 *out++ = hex[((unsigned char) *in) & 15];
51 static void unmungestr(const char *in, char *out, int outlen)
54 if (*in == '%' && in[1] && in[2]) {
62 *out++ = (i << 4) + j;
76 void *open_settings_w(const char *sessionname, char **errmsg)
78 HKEY subkey1, sesskey;
84 if (!sessionname || !*sessionname)
85 sessionname = "Default Settings";
87 p = snewn(3 * strlen(sessionname) + 1, char);
88 mungestr(sessionname, p);
90 ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
91 if (ret != ERROR_SUCCESS) {
93 *errmsg = dupprintf("Unable to create registry key\n"
94 "HKEY_CURRENT_USER\\%s", puttystr);
97 ret = RegCreateKey(subkey1, p, &sesskey);
99 if (ret != ERROR_SUCCESS) {
100 *errmsg = dupprintf("Unable to create registry key\n"
101 "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
106 return (void *) sesskey;
109 void write_setting_s(void *handle, const char *key, const char *value)
112 RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
116 void write_setting_i(void *handle, const char *key, int value)
119 RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
120 (CONST BYTE *) &value, sizeof(value));
123 void close_settings_w(void *handle)
125 RegCloseKey((HKEY) handle);
128 void *open_settings_r(const char *sessionname)
130 HKEY subkey1, sesskey;
133 if (!sessionname || !*sessionname)
134 sessionname = "Default Settings";
136 p = snewn(3 * strlen(sessionname) + 1, char);
137 mungestr(sessionname, p);
139 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
142 if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
145 RegCloseKey(subkey1);
150 return (void *) sesskey;
153 char *read_setting_s(void *handle, const char *key)
161 /* Find out the type and size of the data. */
162 if (RegQueryValueEx((HKEY) handle, key, 0,
163 &type, NULL, &size) != ERROR_SUCCESS ||
167 ret = snewn(size+1, char);
168 if (RegQueryValueEx((HKEY) handle, key, 0,
169 &type, ret, &size) != ERROR_SUCCESS ||
170 type != REG_SZ) return NULL;
175 int read_setting_i(void *handle, const char *key, int defvalue)
177 DWORD type, val, size;
181 RegQueryValueEx((HKEY) handle, key, 0, &type,
182 (BYTE *) &val, &size) != ERROR_SUCCESS ||
183 size != sizeof(val) || type != REG_DWORD)
189 FontSpec *read_setting_fontspec(void *handle, const char *name)
193 int isbold, height, charset;
195 fontname = read_setting_s(handle, name);
199 settingname = dupcat(name, "IsBold", NULL);
200 isbold = read_setting_i(handle, settingname, -1);
202 if (isbold == -1) return NULL;
204 settingname = dupcat(name, "CharSet", NULL);
205 charset = read_setting_i(handle, settingname, -1);
207 if (charset == -1) return NULL;
209 settingname = dupcat(name, "Height", NULL);
210 height = read_setting_i(handle, settingname, INT_MIN);
212 if (height == INT_MIN) return NULL;
214 return fontspec_new(fontname, isbold, height, charset);
217 void write_setting_fontspec(void *handle, const char *name, FontSpec *font)
221 write_setting_s(handle, name, font->name);
222 settingname = dupcat(name, "IsBold", NULL);
223 write_setting_i(handle, settingname, font->isbold);
225 settingname = dupcat(name, "CharSet", NULL);
226 write_setting_i(handle, settingname, font->charset);
228 settingname = dupcat(name, "Height", NULL);
229 write_setting_i(handle, settingname, font->height);
233 Filename *read_setting_filename(void *handle, const char *name)
235 char *tmp = read_setting_s(handle, name);
237 Filename *ret = filename_from_str(tmp);
244 void write_setting_filename(void *handle, const char *name, Filename *result)
246 write_setting_s(handle, name, result->path);
249 void close_settings_r(void *handle)
251 RegCloseKey((HKEY) handle);
254 void del_settings(const char *sessionname)
259 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
262 p = snewn(3 * strlen(sessionname) + 1, char);
263 mungestr(sessionname, p);
264 RegDeleteKey(subkey1, p);
267 RegCloseKey(subkey1);
269 remove_session_from_jumplist(sessionname);
272 struct enumsettings {
277 void *enum_settings_start(void)
279 struct enumsettings *ret;
282 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
285 ret = snew(struct enumsettings);
294 char *enum_settings_next(void *handle, char *buffer, int buflen)
296 struct enumsettings *e = (struct enumsettings *) handle;
298 otherbuf = snewn(3 * buflen, char);
299 if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
300 unmungestr(otherbuf, buffer, buflen);
309 void enum_settings_finish(void *handle)
311 struct enumsettings *e = (struct enumsettings *) handle;
316 static void hostkey_regname(char *buffer, const char *hostname,
317 int port, const char *keytype)
320 strcpy(buffer, keytype);
322 len = strlen(buffer);
323 len += sprintf(buffer + len, "%d:", port);
324 mungestr(hostname, buffer + strlen(buffer));
327 int verify_host_key(const char *hostname, int port,
328 const char *keytype, const char *key)
330 char *otherstr, *regname;
337 len = 1 + strlen(key);
340 * Now read a saved key in from the registry and see what it
343 otherstr = snewn(len, char);
344 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
346 hostkey_regname(regname, hostname, port, keytype);
348 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
349 &rkey) != ERROR_SUCCESS)
350 return 1; /* key does not exist in registry */
353 ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
355 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
356 !strcmp(keytype, "rsa")) {
358 * Key didn't exist. If the key type is RSA, we'll try
359 * another trick, which is to look up the _old_ key format
360 * under just the hostname and translate that.
362 char *justhost = regname + 1 + strcspn(regname, ":");
363 char *oldstyle = snewn(len + 10, char); /* safety margin */
365 ret = RegQueryValueEx(rkey, justhost, NULL, &type,
368 if (ret == ERROR_SUCCESS && type == REG_SZ) {
370 * The old format is two old-style bignums separated by
371 * a slash. An old-style bignum is made of groups of
372 * four hex digits: digits are ordered in sensible
373 * (most to least significant) order within each group,
374 * but groups are ordered in silly (least to most)
375 * order within the bignum. The new format is two
376 * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
377 * A nonzero except in the special case 0x0, which
378 * doesn't appear anyway in RSA keys) separated by a
379 * comma. All hex digits are lowercase in both formats.
385 for (i = 0; i < 2; i++) {
389 ndigits = strcspn(q, "/"); /* find / or end of string */
390 nwords = ndigits / 4;
391 /* now trim ndigits to remove leading zeros */
392 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
394 /* now move digits over to new string */
395 for (j = 0; j < ndigits; j++)
396 p[ndigits - 1 - j] = q[j ^ 3];
400 q++; /* eat the slash */
401 *p++ = ','; /* add a comma */
403 *p = '\0'; /* terminate the string */
407 * Now _if_ this key matches, we'll enter it in the new
408 * format. If not, we'll assume something odd went
409 * wrong, and hyper-cautiously do nothing.
411 if (!strcmp(otherstr, key))
412 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
413 strlen(otherstr) + 1);
419 compare = strcmp(otherstr, key);
424 if (ret == ERROR_MORE_DATA ||
425 (ret == ERROR_SUCCESS && type == REG_SZ && compare))
426 return 2; /* key is different in registry */
427 else if (ret != ERROR_SUCCESS || type != REG_SZ)
428 return 1; /* key does not exist in registry */
430 return 0; /* key matched OK in registry */
433 void store_host_key(const char *hostname, int port,
434 const char *keytype, const char *key)
439 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
441 hostkey_regname(regname, hostname, port, keytype);
443 if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
444 &rkey) == ERROR_SUCCESS) {
445 RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
447 } /* else key does not exist in registry */
453 * Open (or delete) the random seed file.
455 enum { DEL, OPEN_R, OPEN_W };
456 static int try_random_seed(char const *path, int action, HANDLE *ret)
460 *ret = INVALID_HANDLE_VALUE;
461 return FALSE; /* so we'll do the next ones too */
464 *ret = CreateFile(path,
465 action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
466 action == OPEN_W ? 0 : (FILE_SHARE_READ |
469 action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
470 action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
473 return (*ret != INVALID_HANDLE_VALUE);
476 static HANDLE access_random_seed(int action)
481 char seedpath[2 * MAX_PATH + 10] = "\0";
484 * Iterate over a selection of possible random seed paths until
485 * we find one that works.
487 * We do this iteration separately for reading and writing,
488 * meaning that we will automatically migrate random seed files
489 * if a better location becomes available (by reading from the
490 * best location in which we actually find one, and then
491 * writing to the best location in which we can _create_ one).
495 * First, try the location specified by the user in the
498 size = sizeof(seedpath);
499 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
501 int ret = RegQueryValueEx(rkey, "RandSeedFile",
502 0, &type, seedpath, &size);
503 if (ret != ERROR_SUCCESS || type != REG_SZ)
507 if (*seedpath && try_random_seed(seedpath, action, &rethandle))
512 * Next, try the user's local Application Data directory,
513 * followed by their non-local one. This is found using the
514 * SHGetFolderPath function, which won't be present on all
515 * versions of Windows.
517 if (!tried_shgetfolderpath) {
518 /* This is likely only to bear fruit on systems with IE5+
519 * installed, or WinMe/2K+. There is some faffing with
520 * SHFOLDER.DLL we could do to try to find an equivalent
521 * on older versions of Windows if we cared enough.
522 * However, the invocation below requires IE5+ anyway,
524 shell32_module = load_system32_dll("shell32.dll");
525 GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA);
526 tried_shgetfolderpath = TRUE;
528 if (p_SHGetFolderPathA) {
529 if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA,
530 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
531 strcat(seedpath, "\\PUTTY.RND");
532 if (try_random_seed(seedpath, action, &rethandle))
536 if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA,
537 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
538 strcat(seedpath, "\\PUTTY.RND");
539 if (try_random_seed(seedpath, action, &rethandle))
545 * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
546 * user's home directory.
552 GetEnvironmentVariable("HOMEDRIVE", seedpath,
555 GetEnvironmentVariable("HOMEPATH", seedpath + len,
556 sizeof(seedpath) - len);
558 strcat(seedpath, "\\PUTTY.RND");
559 if (try_random_seed(seedpath, action, &rethandle))
565 * And finally, fall back to C:\WINDOWS.
567 GetWindowsDirectory(seedpath, sizeof(seedpath));
568 strcat(seedpath, "\\PUTTY.RND");
569 if (try_random_seed(seedpath, action, &rethandle))
573 * If even that failed, give up.
575 return INVALID_HANDLE_VALUE;
578 void read_random_seed(noise_consumer_t consumer)
580 HANDLE seedf = access_random_seed(OPEN_R);
582 if (seedf != INVALID_HANDLE_VALUE) {
587 if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
596 void write_random_seed(void *data, int len)
598 HANDLE seedf = access_random_seed(OPEN_W);
600 if (seedf != INVALID_HANDLE_VALUE) {
603 WriteFile(seedf, data, len, &lenwritten, NULL);
609 * Internal function supporting the jump list registry code. All the
610 * functions to add, remove and read the list have substantially
611 * similar content, so this is a generalisation of all of them which
612 * transforms the list in the registry by prepending 'add' (if
613 * non-null), removing 'rem' from what's left (if non-null), and
614 * returning the resulting concatenated list of strings in 'out' (if
617 static int transform_jumplist_registry
618 (const char *add, const char *rem, char **out)
621 HKEY pjumplist_key, psettings_tmp;
624 char *old_value, *new_value;
625 char *piterator_old, *piterator_new, *piterator_tmp;
627 ret = RegCreateKeyEx(HKEY_CURRENT_USER, reg_jumplist_key, 0, NULL,
628 REG_OPTION_NON_VOLATILE, (KEY_READ | KEY_WRITE), NULL,
629 &pjumplist_key, NULL);
630 if (ret != ERROR_SUCCESS) {
631 return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE;
634 /* Get current list of saved sessions in the registry. */
636 old_value = snewn(value_length, char);
637 ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
638 old_value, &value_length);
639 /* When the passed buffer is too small, ERROR_MORE_DATA is
640 * returned and the required size is returned in the length
642 if (ret == ERROR_MORE_DATA) {
644 old_value = snewn(value_length, char);
645 ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
646 old_value, &value_length);
649 if (ret == ERROR_FILE_NOT_FOUND) {
650 /* Value doesn't exist yet. Start from an empty value. */
652 *(old_value + 1) = '\0';
653 } else if (ret != ERROR_SUCCESS) {
654 /* Some non-recoverable error occurred. */
656 RegCloseKey(pjumplist_key);
657 return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
658 } else if (type != REG_MULTI_SZ) {
659 /* The value present in the registry has the wrong type: we
660 * try to delete it and start from an empty value. */
661 ret = RegDeleteValue(pjumplist_key, reg_jumplist_value);
662 if (ret != ERROR_SUCCESS) {
664 RegCloseKey(pjumplist_key);
665 return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
669 *(old_value + 1) = '\0';
672 /* Check validity of registry data: REG_MULTI_SZ value must end
674 piterator_tmp = old_value;
675 while (((piterator_tmp - old_value) < (value_length - 1)) &&
676 !(*piterator_tmp == '\0' && *(piterator_tmp+1) == '\0')) {
680 if ((piterator_tmp - old_value) >= (value_length-1)) {
681 /* Invalid value. Start from an empty value. */
683 *(old_value + 1) = '\0';
687 * Modify the list, if we're modifying.
690 /* Walk through the existing list and construct the new list of
692 new_value = snewn(value_length + (add ? strlen(add) + 1 : 0), char);
693 piterator_new = new_value;
694 piterator_old = old_value;
696 /* First add the new item to the beginning of the list. */
698 strcpy(piterator_new, add);
699 piterator_new += strlen(piterator_new) + 1;
701 /* Now add the existing list, taking care to leave out the removed
702 * item, if it was already in the existing list. */
703 while (*piterator_old != '\0') {
704 if (!rem || strcmp(piterator_old, rem) != 0) {
705 /* Check if this is a valid session, otherwise don't add. */
706 psettings_tmp = open_settings_r(piterator_old);
707 if (psettings_tmp != NULL) {
708 close_settings_r(psettings_tmp);
709 strcpy(piterator_new, piterator_old);
710 piterator_new += strlen(piterator_new) + 1;
713 piterator_old += strlen(piterator_old) + 1;
715 *piterator_new = '\0';
718 /* Save the new list to the registry. */
719 ret = RegSetValueEx(pjumplist_key, reg_jumplist_value, 0, REG_MULTI_SZ,
720 new_value, piterator_new - new_value);
723 old_value = new_value;
728 * Either return or free the result.
735 /* Clean up and return. */
736 RegCloseKey(pjumplist_key);
738 if (ret != ERROR_SUCCESS) {
739 return JUMPLISTREG_ERROR_VALUEWRITE_FAILURE;
741 return JUMPLISTREG_OK;
745 /* Adds a new entry to the jumplist entries in the registry. */
746 int add_to_jumplist_registry(const char *item)
748 return transform_jumplist_registry(item, item, NULL);
751 /* Removes an item from the jumplist entries in the registry. */
752 int remove_from_jumplist_registry(const char *item)
754 return transform_jumplist_registry(NULL, item, NULL);
757 /* Returns the jumplist entries from the registry. Caller must free
758 * the returned pointer. */
759 char *get_jumplist_registry_entries (void)
763 if (transform_jumplist_registry(NULL,NULL,&list_value) != ERROR_SUCCESS) {
764 list_value = snewn(2, char);
766 *(list_value + 1) = '\0';
772 * Recursively delete a registry key and everything under it.
774 static void registry_recursive_remove(HKEY key)
777 char name[MAX_PATH + 1];
781 while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
782 if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
783 registry_recursive_remove(subkey);
786 RegDeleteKey(key, name);
790 void cleanup_all(void)
794 char name[MAX_PATH + 1];
796 /* ------------------------------------------------------------
797 * Wipe out the random seed file, in all of its possible
800 access_random_seed(DEL);
802 /* ------------------------------------------------------------
803 * Ask Windows to delete any jump list information associated
804 * with this installation of PuTTY.
808 /* ------------------------------------------------------------
809 * Destroy all registry information associated with PuTTY.
813 * Open the main PuTTY registry key and remove everything in it.
815 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
817 registry_recursive_remove(key);
821 * Now open the parent key and remove the PuTTY main key. Once
822 * we've done that, see if the parent key has any other
825 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
826 &key) == ERROR_SUCCESS) {
827 RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
828 ret = RegEnumKey(key, 0, name, sizeof(name));
831 * If the parent key had no other children, we must delete
832 * it in its turn. That means opening the _grandparent_
835 if (ret != ERROR_SUCCESS) {
836 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
837 &key) == ERROR_SUCCESS) {
838 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);