2 * winstore.c: Windows-specific implementation of the interface
3 * defined in storage.h.
15 #define CSIDL_APPDATA 0x001a
17 #ifndef CSIDL_LOCAL_APPDATA
18 #define CSIDL_LOCAL_APPDATA 0x001c
21 static const char *const reg_jumplist_key = PUTTY_REG_POS "\\Jumplist";
22 static const char *const reg_jumplist_value = "Recent sessions";
23 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
25 static const char hex[16] = "0123456789ABCDEF";
27 static int tried_shgetfolderpath = FALSE;
28 static HMODULE shell32_module = NULL;
29 DECL_WINDOWS_FUNCTION(static, HRESULT, SHGetFolderPathA,
30 (HWND, int, HANDLE, DWORD, LPSTR));
32 static void mungestr(const char *in, char *out)
37 if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
38 *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
41 *out++ = hex[((unsigned char) *in) >> 4];
42 *out++ = hex[((unsigned char) *in) & 15];
52 static void unmungestr(const char *in, char *out, int outlen)
55 if (*in == '%' && in[1] && in[2]) {
63 *out++ = (i << 4) + j;
77 void *open_settings_w(const char *sessionname, char **errmsg)
79 HKEY subkey1, sesskey;
85 if (!sessionname || !*sessionname)
86 sessionname = "Default Settings";
88 p = snewn(3 * strlen(sessionname) + 1, char);
89 mungestr(sessionname, p);
91 ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
92 if (ret != ERROR_SUCCESS) {
94 *errmsg = dupprintf("Unable to create registry key\n"
95 "HKEY_CURRENT_USER\\%s", puttystr);
98 ret = RegCreateKey(subkey1, p, &sesskey);
100 if (ret != ERROR_SUCCESS) {
101 *errmsg = dupprintf("Unable to create registry key\n"
102 "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
107 return (void *) sesskey;
110 void write_setting_s(void *handle, const char *key, const char *value)
113 RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
117 void write_setting_i(void *handle, const char *key, int value)
120 RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
121 (CONST BYTE *) &value, sizeof(value));
124 void close_settings_w(void *handle)
126 RegCloseKey((HKEY) handle);
129 void *open_settings_r(const char *sessionname)
131 HKEY subkey1, sesskey;
134 if (!sessionname || !*sessionname)
135 sessionname = "Default Settings";
137 p = snewn(3 * strlen(sessionname) + 1, char);
138 mungestr(sessionname, p);
140 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
143 if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
146 RegCloseKey(subkey1);
151 return (void *) sesskey;
154 char *read_setting_s(void *handle, const char *key)
156 DWORD type, allocsize, size;
162 /* Find out the type and size of the data. */
163 if (RegQueryValueEx((HKEY) handle, key, 0,
164 &type, NULL, &size) != ERROR_SUCCESS ||
168 allocsize = size+1; /* allow for an extra NUL if needed */
169 ret = snewn(allocsize, char);
170 if (RegQueryValueEx((HKEY) handle, key, 0,
171 &type, ret, &size) != ERROR_SUCCESS ||
176 assert(size < allocsize);
177 ret[size] = '\0'; /* add an extra NUL in case RegQueryValueEx
178 * didn't supply one */
183 int read_setting_i(void *handle, const char *key, int defvalue)
185 DWORD type, val, size;
189 RegQueryValueEx((HKEY) handle, key, 0, &type,
190 (BYTE *) &val, &size) != ERROR_SUCCESS ||
191 size != sizeof(val) || type != REG_DWORD)
197 FontSpec *read_setting_fontspec(void *handle, const char *name)
202 int isbold, height, charset;
204 fontname = read_setting_s(handle, name);
208 settingname = dupcat(name, "IsBold", NULL);
209 isbold = read_setting_i(handle, settingname, -1);
216 settingname = dupcat(name, "CharSet", NULL);
217 charset = read_setting_i(handle, settingname, -1);
224 settingname = dupcat(name, "Height", NULL);
225 height = read_setting_i(handle, settingname, INT_MIN);
227 if (height == INT_MIN) {
232 ret = fontspec_new(fontname, isbold, height, charset);
237 void write_setting_fontspec(void *handle, const char *name, FontSpec *font)
241 write_setting_s(handle, name, font->name);
242 settingname = dupcat(name, "IsBold", NULL);
243 write_setting_i(handle, settingname, font->isbold);
245 settingname = dupcat(name, "CharSet", NULL);
246 write_setting_i(handle, settingname, font->charset);
248 settingname = dupcat(name, "Height", NULL);
249 write_setting_i(handle, settingname, font->height);
253 Filename *read_setting_filename(void *handle, const char *name)
255 char *tmp = read_setting_s(handle, name);
257 Filename *ret = filename_from_str(tmp);
264 void write_setting_filename(void *handle, const char *name, Filename *result)
266 write_setting_s(handle, name, result->path);
269 void close_settings_r(void *handle)
271 RegCloseKey((HKEY) handle);
274 void del_settings(const char *sessionname)
279 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
282 p = snewn(3 * strlen(sessionname) + 1, char);
283 mungestr(sessionname, p);
284 RegDeleteKey(subkey1, p);
287 RegCloseKey(subkey1);
289 remove_session_from_jumplist(sessionname);
292 struct enumsettings {
297 void *enum_settings_start(void)
299 struct enumsettings *ret;
302 if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
305 ret = snew(struct enumsettings);
314 char *enum_settings_next(void *handle, char *buffer, int buflen)
316 struct enumsettings *e = (struct enumsettings *) handle;
318 otherbuf = snewn(3 * buflen, char);
319 if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
320 unmungestr(otherbuf, buffer, buflen);
329 void enum_settings_finish(void *handle)
331 struct enumsettings *e = (struct enumsettings *) handle;
336 static void hostkey_regname(char *buffer, const char *hostname,
337 int port, const char *keytype)
340 strcpy(buffer, keytype);
342 len = strlen(buffer);
343 len += sprintf(buffer + len, "%d:", port);
344 mungestr(hostname, buffer + strlen(buffer));
347 int verify_host_key(const char *hostname, int port,
348 const char *keytype, const char *key)
350 char *otherstr, *regname;
357 len = 1 + strlen(key);
360 * Now read a saved key in from the registry and see what it
363 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
365 hostkey_regname(regname, hostname, port, keytype);
367 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
368 &rkey) != ERROR_SUCCESS) {
370 return 1; /* key does not exist in registry */
374 otherstr = snewn(len, char);
375 ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
377 if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
378 !strcmp(keytype, "rsa")) {
380 * Key didn't exist. If the key type is RSA, we'll try
381 * another trick, which is to look up the _old_ key format
382 * under just the hostname and translate that.
384 char *justhost = regname + 1 + strcspn(regname, ":");
385 char *oldstyle = snewn(len + 10, char); /* safety margin */
387 ret = RegQueryValueEx(rkey, justhost, NULL, &type,
390 if (ret == ERROR_SUCCESS && type == REG_SZ) {
392 * The old format is two old-style bignums separated by
393 * a slash. An old-style bignum is made of groups of
394 * four hex digits: digits are ordered in sensible
395 * (most to least significant) order within each group,
396 * but groups are ordered in silly (least to most)
397 * order within the bignum. The new format is two
398 * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
399 * A nonzero except in the special case 0x0, which
400 * doesn't appear anyway in RSA keys) separated by a
401 * comma. All hex digits are lowercase in both formats.
407 for (i = 0; i < 2; i++) {
411 ndigits = strcspn(q, "/"); /* find / or end of string */
412 nwords = ndigits / 4;
413 /* now trim ndigits to remove leading zeros */
414 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
416 /* now move digits over to new string */
417 for (j = 0; j < ndigits; j++)
418 p[ndigits - 1 - j] = q[j ^ 3];
422 q++; /* eat the slash */
423 *p++ = ','; /* add a comma */
425 *p = '\0'; /* terminate the string */
429 * Now _if_ this key matches, we'll enter it in the new
430 * format. If not, we'll assume something odd went
431 * wrong, and hyper-cautiously do nothing.
433 if (!strcmp(otherstr, key))
434 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
435 strlen(otherstr) + 1);
443 compare = strcmp(otherstr, key);
448 if (ret == ERROR_MORE_DATA ||
449 (ret == ERROR_SUCCESS && type == REG_SZ && compare))
450 return 2; /* key is different in registry */
451 else if (ret != ERROR_SUCCESS || type != REG_SZ)
452 return 1; /* key does not exist in registry */
454 return 0; /* key matched OK in registry */
457 int have_ssh_host_key(const char *hostname, int port,
461 * If we have a host key, verify_host_key will return 0 or 2.
462 * If we don't have one, it'll return 1.
464 return verify_host_key(hostname, port, keytype, "") != 1;
467 void store_host_key(const char *hostname, int port,
468 const char *keytype, const char *key)
473 regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
475 hostkey_regname(regname, hostname, port, keytype);
477 if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
478 &rkey) == ERROR_SUCCESS) {
479 RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
481 } /* else key does not exist in registry */
487 * Open (or delete) the random seed file.
489 enum { DEL, OPEN_R, OPEN_W };
490 static int try_random_seed(char const *path, int action, HANDLE *ret)
493 if (!DeleteFile(path) && GetLastError() != ERROR_FILE_NOT_FOUND) {
494 nonfatal("Unable to delete '%s': %s", path,
495 win_strerror(GetLastError()));
497 *ret = INVALID_HANDLE_VALUE;
498 return FALSE; /* so we'll do the next ones too */
501 *ret = CreateFile(path,
502 action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
503 action == OPEN_W ? 0 : (FILE_SHARE_READ |
506 action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
507 action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
510 return (*ret != INVALID_HANDLE_VALUE);
513 static HANDLE access_random_seed(int action)
518 char seedpath[2 * MAX_PATH + 10] = "\0";
521 * Iterate over a selection of possible random seed paths until
522 * we find one that works.
524 * We do this iteration separately for reading and writing,
525 * meaning that we will automatically migrate random seed files
526 * if a better location becomes available (by reading from the
527 * best location in which we actually find one, and then
528 * writing to the best location in which we can _create_ one).
532 * First, try the location specified by the user in the
535 size = sizeof(seedpath);
536 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
538 int ret = RegQueryValueEx(rkey, "RandSeedFile",
539 0, &type, seedpath, &size);
540 if (ret != ERROR_SUCCESS || type != REG_SZ)
544 if (*seedpath && try_random_seed(seedpath, action, &rethandle))
549 * Next, try the user's local Application Data directory,
550 * followed by their non-local one. This is found using the
551 * SHGetFolderPath function, which won't be present on all
552 * versions of Windows.
554 if (!tried_shgetfolderpath) {
555 /* This is likely only to bear fruit on systems with IE5+
556 * installed, or WinMe/2K+. There is some faffing with
557 * SHFOLDER.DLL we could do to try to find an equivalent
558 * on older versions of Windows if we cared enough.
559 * However, the invocation below requires IE5+ anyway,
561 shell32_module = load_system32_dll("shell32.dll");
562 GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA);
563 tried_shgetfolderpath = TRUE;
565 if (p_SHGetFolderPathA) {
566 if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA,
567 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
568 strcat(seedpath, "\\PUTTY.RND");
569 if (try_random_seed(seedpath, action, &rethandle))
573 if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA,
574 NULL, SHGFP_TYPE_CURRENT, seedpath))) {
575 strcat(seedpath, "\\PUTTY.RND");
576 if (try_random_seed(seedpath, action, &rethandle))
582 * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
583 * user's home directory.
589 GetEnvironmentVariable("HOMEDRIVE", seedpath,
592 GetEnvironmentVariable("HOMEPATH", seedpath + len,
593 sizeof(seedpath) - len);
595 strcat(seedpath, "\\PUTTY.RND");
596 if (try_random_seed(seedpath, action, &rethandle))
602 * And finally, fall back to C:\WINDOWS.
604 GetWindowsDirectory(seedpath, sizeof(seedpath));
605 strcat(seedpath, "\\PUTTY.RND");
606 if (try_random_seed(seedpath, action, &rethandle))
610 * If even that failed, give up.
612 return INVALID_HANDLE_VALUE;
615 void read_random_seed(noise_consumer_t consumer)
617 HANDLE seedf = access_random_seed(OPEN_R);
619 if (seedf != INVALID_HANDLE_VALUE) {
624 if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
633 void write_random_seed(void *data, int len)
635 HANDLE seedf = access_random_seed(OPEN_W);
637 if (seedf != INVALID_HANDLE_VALUE) {
640 WriteFile(seedf, data, len, &lenwritten, NULL);
646 * Internal function supporting the jump list registry code. All the
647 * functions to add, remove and read the list have substantially
648 * similar content, so this is a generalisation of all of them which
649 * transforms the list in the registry by prepending 'add' (if
650 * non-null), removing 'rem' from what's left (if non-null), and
651 * returning the resulting concatenated list of strings in 'out' (if
654 static int transform_jumplist_registry
655 (const char *add, const char *rem, char **out)
658 HKEY pjumplist_key, psettings_tmp;
661 char *old_value, *new_value;
662 char *piterator_old, *piterator_new, *piterator_tmp;
664 ret = RegCreateKeyEx(HKEY_CURRENT_USER, reg_jumplist_key, 0, NULL,
665 REG_OPTION_NON_VOLATILE, (KEY_READ | KEY_WRITE), NULL,
666 &pjumplist_key, NULL);
667 if (ret != ERROR_SUCCESS) {
668 return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE;
671 /* Get current list of saved sessions in the registry. */
673 old_value = snewn(value_length, char);
674 ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
675 old_value, &value_length);
676 /* When the passed buffer is too small, ERROR_MORE_DATA is
677 * returned and the required size is returned in the length
679 if (ret == ERROR_MORE_DATA) {
681 old_value = snewn(value_length, char);
682 ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
683 old_value, &value_length);
686 if (ret == ERROR_FILE_NOT_FOUND) {
687 /* Value doesn't exist yet. Start from an empty value. */
689 *(old_value + 1) = '\0';
690 } else if (ret != ERROR_SUCCESS) {
691 /* Some non-recoverable error occurred. */
693 RegCloseKey(pjumplist_key);
694 return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
695 } else if (type != REG_MULTI_SZ) {
696 /* The value present in the registry has the wrong type: we
697 * try to delete it and start from an empty value. */
698 ret = RegDeleteValue(pjumplist_key, reg_jumplist_value);
699 if (ret != ERROR_SUCCESS) {
701 RegCloseKey(pjumplist_key);
702 return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
706 *(old_value + 1) = '\0';
709 /* Check validity of registry data: REG_MULTI_SZ value must end
711 piterator_tmp = old_value;
712 while (((piterator_tmp - old_value) < (value_length - 1)) &&
713 !(*piterator_tmp == '\0' && *(piterator_tmp+1) == '\0')) {
717 if ((piterator_tmp - old_value) >= (value_length-1)) {
718 /* Invalid value. Start from an empty value. */
720 *(old_value + 1) = '\0';
724 * Modify the list, if we're modifying.
727 /* Walk through the existing list and construct the new list of
729 new_value = snewn(value_length + (add ? strlen(add) + 1 : 0), char);
730 piterator_new = new_value;
731 piterator_old = old_value;
733 /* First add the new item to the beginning of the list. */
735 strcpy(piterator_new, add);
736 piterator_new += strlen(piterator_new) + 1;
738 /* Now add the existing list, taking care to leave out the removed
739 * item, if it was already in the existing list. */
740 while (*piterator_old != '\0') {
741 if (!rem || strcmp(piterator_old, rem) != 0) {
742 /* Check if this is a valid session, otherwise don't add. */
743 psettings_tmp = open_settings_r(piterator_old);
744 if (psettings_tmp != NULL) {
745 close_settings_r(psettings_tmp);
746 strcpy(piterator_new, piterator_old);
747 piterator_new += strlen(piterator_new) + 1;
750 piterator_old += strlen(piterator_old) + 1;
752 *piterator_new = '\0';
755 /* Save the new list to the registry. */
756 ret = RegSetValueEx(pjumplist_key, reg_jumplist_value, 0, REG_MULTI_SZ,
757 new_value, piterator_new - new_value);
760 old_value = new_value;
765 * Either return or free the result.
767 if (out && ret == ERROR_SUCCESS)
772 /* Clean up and return. */
773 RegCloseKey(pjumplist_key);
775 if (ret != ERROR_SUCCESS) {
776 return JUMPLISTREG_ERROR_VALUEWRITE_FAILURE;
778 return JUMPLISTREG_OK;
782 /* Adds a new entry to the jumplist entries in the registry. */
783 int add_to_jumplist_registry(const char *item)
785 return transform_jumplist_registry(item, item, NULL);
788 /* Removes an item from the jumplist entries in the registry. */
789 int remove_from_jumplist_registry(const char *item)
791 return transform_jumplist_registry(NULL, item, NULL);
794 /* Returns the jumplist entries from the registry. Caller must free
795 * the returned pointer. */
796 char *get_jumplist_registry_entries (void)
800 if (transform_jumplist_registry(NULL,NULL,&list_value) != JUMPLISTREG_OK) {
801 list_value = snewn(2, char);
803 *(list_value + 1) = '\0';
809 * Recursively delete a registry key and everything under it.
811 static void registry_recursive_remove(HKEY key)
814 char name[MAX_PATH + 1];
818 while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
819 if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
820 registry_recursive_remove(subkey);
823 RegDeleteKey(key, name);
827 void cleanup_all(void)
831 char name[MAX_PATH + 1];
833 /* ------------------------------------------------------------
834 * Wipe out the random seed file, in all of its possible
837 access_random_seed(DEL);
839 /* ------------------------------------------------------------
840 * Ask Windows to delete any jump list information associated
841 * with this installation of PuTTY.
845 /* ------------------------------------------------------------
846 * Destroy all registry information associated with PuTTY.
850 * Open the main PuTTY registry key and remove everything in it.
852 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
854 registry_recursive_remove(key);
858 * Now open the parent key and remove the PuTTY main key. Once
859 * we've done that, see if the parent key has any other
862 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
863 &key) == ERROR_SUCCESS) {
864 RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
865 ret = RegEnumKey(key, 0, name, sizeof(name));
868 * If the parent key had no other children, we must delete
869 * it in its turn. That means opening the _grandparent_
872 if (ret != ERROR_SUCCESS) {
873 if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
874 &key) == ERROR_SUCCESS) {
875 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);