]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winstore.c
Update version number for 0.66 release.
[PuTTY.git] / windows / winstore.c
1 /*
2  * winstore.c: Windows-specific implementation of the interface
3  * defined in storage.h.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <limits.h>
9 #include <assert.h>
10 #include "putty.h"
11 #include "storage.h"
12
13 #include <shlobj.h>
14 #ifndef CSIDL_APPDATA
15 #define CSIDL_APPDATA 0x001a
16 #endif
17 #ifndef CSIDL_LOCAL_APPDATA
18 #define CSIDL_LOCAL_APPDATA 0x001c
19 #endif
20
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";
24
25 static const char hex[16] = "0123456789ABCDEF";
26
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));
31
32 static void mungestr(const char *in, char *out)
33 {
34     int candot = 0;
35
36     while (*in) {
37         if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
38             *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
39                                                      && !candot)) {
40             *out++ = '%';
41             *out++ = hex[((unsigned char) *in) >> 4];
42             *out++ = hex[((unsigned char) *in) & 15];
43         } else
44             *out++ = *in;
45         in++;
46         candot = 1;
47     }
48     *out = '\0';
49     return;
50 }
51
52 static void unmungestr(const char *in, char *out, int outlen)
53 {
54     while (*in) {
55         if (*in == '%' && in[1] && in[2]) {
56             int i, j;
57
58             i = in[1] - '0';
59             i -= (i > 9 ? 7 : 0);
60             j = in[2] - '0';
61             j -= (j > 9 ? 7 : 0);
62
63             *out++ = (i << 4) + j;
64             if (!--outlen)
65                 return;
66             in += 3;
67         } else {
68             *out++ = *in++;
69             if (!--outlen)
70                 return;
71         }
72     }
73     *out = '\0';
74     return;
75 }
76
77 void *open_settings_w(const char *sessionname, char **errmsg)
78 {
79     HKEY subkey1, sesskey;
80     int ret;
81     char *p;
82
83     *errmsg = NULL;
84
85     if (!sessionname || !*sessionname)
86         sessionname = "Default Settings";
87
88     p = snewn(3 * strlen(sessionname) + 1, char);
89     mungestr(sessionname, p);
90
91     ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
92     if (ret != ERROR_SUCCESS) {
93         sfree(p);
94         *errmsg = dupprintf("Unable to create registry key\n"
95                             "HKEY_CURRENT_USER\\%s", puttystr);
96         return NULL;
97     }
98     ret = RegCreateKey(subkey1, p, &sesskey);
99     RegCloseKey(subkey1);
100     if (ret != ERROR_SUCCESS) {
101         *errmsg = dupprintf("Unable to create registry key\n"
102                             "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
103         sfree(p);
104         return NULL;
105     }
106     sfree(p);
107     return (void *) sesskey;
108 }
109
110 void write_setting_s(void *handle, const char *key, const char *value)
111 {
112     if (handle)
113         RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
114                       1 + strlen(value));
115 }
116
117 void write_setting_i(void *handle, const char *key, int value)
118 {
119     if (handle)
120         RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
121                       (CONST BYTE *) &value, sizeof(value));
122 }
123
124 void close_settings_w(void *handle)
125 {
126     RegCloseKey((HKEY) handle);
127 }
128
129 void *open_settings_r(const char *sessionname)
130 {
131     HKEY subkey1, sesskey;
132     char *p;
133
134     if (!sessionname || !*sessionname)
135         sessionname = "Default Settings";
136
137     p = snewn(3 * strlen(sessionname) + 1, char);
138     mungestr(sessionname, p);
139
140     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
141         sesskey = NULL;
142     } else {
143         if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
144             sesskey = NULL;
145         }
146         RegCloseKey(subkey1);
147     }
148
149     sfree(p);
150
151     return (void *) sesskey;
152 }
153
154 char *read_setting_s(void *handle, const char *key)
155 {
156     DWORD type, allocsize, size;
157     char *ret;
158
159     if (!handle)
160         return NULL;
161
162     /* Find out the type and size of the data. */
163     if (RegQueryValueEx((HKEY) handle, key, 0,
164                         &type, NULL, &size) != ERROR_SUCCESS ||
165         type != REG_SZ)
166         return NULL;
167
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 ||
172         type != REG_SZ) {
173         sfree(ret);
174         return NULL;
175     }
176     assert(size < allocsize);
177     ret[size] = '\0'; /* add an extra NUL in case RegQueryValueEx
178                        * didn't supply one */
179
180     return ret;
181 }
182
183 int read_setting_i(void *handle, const char *key, int defvalue)
184 {
185     DWORD type, val, size;
186     size = sizeof(val);
187
188     if (!handle ||
189         RegQueryValueEx((HKEY) handle, key, 0, &type,
190                         (BYTE *) &val, &size) != ERROR_SUCCESS ||
191         size != sizeof(val) || type != REG_DWORD)
192         return defvalue;
193     else
194         return val;
195 }
196
197 FontSpec *read_setting_fontspec(void *handle, const char *name)
198 {
199     char *settingname;
200     char *fontname;
201     FontSpec *ret;
202     int isbold, height, charset;
203
204     fontname = read_setting_s(handle, name);
205     if (!fontname)
206         return NULL;
207
208     settingname = dupcat(name, "IsBold", NULL);
209     isbold = read_setting_i(handle, settingname, -1);
210     sfree(settingname);
211     if (isbold == -1) {
212         sfree(fontname);
213         return NULL;
214     }
215
216     settingname = dupcat(name, "CharSet", NULL);
217     charset = read_setting_i(handle, settingname, -1);
218     sfree(settingname);
219     if (charset == -1) {
220         sfree(fontname);
221         return NULL;
222     }
223
224     settingname = dupcat(name, "Height", NULL);
225     height = read_setting_i(handle, settingname, INT_MIN);
226     sfree(settingname);
227     if (height == INT_MIN) {
228         sfree(fontname);
229         return NULL;
230     }
231
232     ret = fontspec_new(fontname, isbold, height, charset);
233     sfree(fontname);
234     return ret;
235 }
236
237 void write_setting_fontspec(void *handle, const char *name, FontSpec *font)
238 {
239     char *settingname;
240
241     write_setting_s(handle, name, font->name);
242     settingname = dupcat(name, "IsBold", NULL);
243     write_setting_i(handle, settingname, font->isbold);
244     sfree(settingname);
245     settingname = dupcat(name, "CharSet", NULL);
246     write_setting_i(handle, settingname, font->charset);
247     sfree(settingname);
248     settingname = dupcat(name, "Height", NULL);
249     write_setting_i(handle, settingname, font->height);
250     sfree(settingname);
251 }
252
253 Filename *read_setting_filename(void *handle, const char *name)
254 {
255     char *tmp = read_setting_s(handle, name);
256     if (tmp) {
257         Filename *ret = filename_from_str(tmp);
258         sfree(tmp);
259         return ret;
260     } else
261         return NULL;
262 }
263
264 void write_setting_filename(void *handle, const char *name, Filename *result)
265 {
266     write_setting_s(handle, name, result->path);
267 }
268
269 void close_settings_r(void *handle)
270 {
271     RegCloseKey((HKEY) handle);
272 }
273
274 void del_settings(const char *sessionname)
275 {
276     HKEY subkey1;
277     char *p;
278
279     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
280         return;
281
282     p = snewn(3 * strlen(sessionname) + 1, char);
283     mungestr(sessionname, p);
284     RegDeleteKey(subkey1, p);
285     sfree(p);
286
287     RegCloseKey(subkey1);
288
289     remove_session_from_jumplist(sessionname);
290 }
291
292 struct enumsettings {
293     HKEY key;
294     int i;
295 };
296
297 void *enum_settings_start(void)
298 {
299     struct enumsettings *ret;
300     HKEY key;
301
302     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
303         return NULL;
304
305     ret = snew(struct enumsettings);
306     if (ret) {
307         ret->key = key;
308         ret->i = 0;
309     }
310
311     return ret;
312 }
313
314 char *enum_settings_next(void *handle, char *buffer, int buflen)
315 {
316     struct enumsettings *e = (struct enumsettings *) handle;
317     char *otherbuf;
318     otherbuf = snewn(3 * buflen, char);
319     if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
320         unmungestr(otherbuf, buffer, buflen);
321         sfree(otherbuf);
322         return buffer;
323     } else {
324         sfree(otherbuf);
325         return NULL;
326     }
327 }
328
329 void enum_settings_finish(void *handle)
330 {
331     struct enumsettings *e = (struct enumsettings *) handle;
332     RegCloseKey(e->key);
333     sfree(e);
334 }
335
336 static void hostkey_regname(char *buffer, const char *hostname,
337                             int port, const char *keytype)
338 {
339     int len;
340     strcpy(buffer, keytype);
341     strcat(buffer, "@");
342     len = strlen(buffer);
343     len += sprintf(buffer + len, "%d:", port);
344     mungestr(hostname, buffer + strlen(buffer));
345 }
346
347 int verify_host_key(const char *hostname, int port,
348                     const char *keytype, const char *key)
349 {
350     char *otherstr, *regname;
351     int len;
352     HKEY rkey;
353     DWORD readlen;
354     DWORD type;
355     int ret, compare;
356
357     len = 1 + strlen(key);
358
359     /*
360      * Now read a saved key in from the registry and see what it
361      * says.
362      */
363     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
364
365     hostkey_regname(regname, hostname, port, keytype);
366
367     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
368                    &rkey) != ERROR_SUCCESS) {
369         sfree(regname);
370         return 1;                      /* key does not exist in registry */
371     }
372
373     readlen = len;
374     otherstr = snewn(len, char);
375     ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
376
377     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
378         !strcmp(keytype, "rsa")) {
379         /*
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.
383          */
384         char *justhost = regname + 1 + strcspn(regname, ":");
385         char *oldstyle = snewn(len + 10, char); /* safety margin */
386         readlen = len;
387         ret = RegQueryValueEx(rkey, justhost, NULL, &type,
388                               oldstyle, &readlen);
389
390         if (ret == ERROR_SUCCESS && type == REG_SZ) {
391             /*
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.
402              */
403             char *p = otherstr;
404             char *q = oldstyle;
405             int i, j;
406
407             for (i = 0; i < 2; i++) {
408                 int ndigits, nwords;
409                 *p++ = '0';
410                 *p++ = 'x';
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)
415                     ndigits--;
416                 /* now move digits over to new string */
417                 for (j = 0; j < ndigits; j++)
418                     p[ndigits - 1 - j] = q[j ^ 3];
419                 p += ndigits;
420                 q += nwords * 4;
421                 if (*q) {
422                     q++;               /* eat the slash */
423                     *p++ = ',';        /* add a comma */
424                 }
425                 *p = '\0';             /* terminate the string */
426             }
427
428             /*
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.
432              */
433             if (!strcmp(otherstr, key))
434                 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
435                               strlen(otherstr) + 1);
436         }
437
438         sfree(oldstyle);
439     }
440
441     RegCloseKey(rkey);
442
443     compare = strcmp(otherstr, key);
444
445     sfree(otherstr);
446     sfree(regname);
447
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 */
453     else
454         return 0;                      /* key matched OK in registry */
455 }
456
457 void store_host_key(const char *hostname, int port,
458                     const char *keytype, const char *key)
459 {
460     char *regname;
461     HKEY rkey;
462
463     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
464
465     hostkey_regname(regname, hostname, port, keytype);
466
467     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
468                      &rkey) == ERROR_SUCCESS) {
469         RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
470         RegCloseKey(rkey);
471     } /* else key does not exist in registry */
472
473     sfree(regname);
474 }
475
476 /*
477  * Open (or delete) the random seed file.
478  */
479 enum { DEL, OPEN_R, OPEN_W };
480 static int try_random_seed(char const *path, int action, HANDLE *ret)
481 {
482     if (action == DEL) {
483         if (!DeleteFile(path) && GetLastError() != ERROR_FILE_NOT_FOUND) {
484             nonfatal("Unable to delete '%s': %s", path,
485                      win_strerror(GetLastError()));
486         }
487         *ret = INVALID_HANDLE_VALUE;
488         return FALSE;                  /* so we'll do the next ones too */
489     }
490
491     *ret = CreateFile(path,
492                       action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
493                       action == OPEN_W ? 0 : (FILE_SHARE_READ |
494                                               FILE_SHARE_WRITE),
495                       NULL,
496                       action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
497                       action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
498                       NULL);
499
500     return (*ret != INVALID_HANDLE_VALUE);
501 }
502
503 static HANDLE access_random_seed(int action)
504 {
505     HKEY rkey;
506     DWORD type, size;
507     HANDLE rethandle;
508     char seedpath[2 * MAX_PATH + 10] = "\0";
509
510     /*
511      * Iterate over a selection of possible random seed paths until
512      * we find one that works.
513      * 
514      * We do this iteration separately for reading and writing,
515      * meaning that we will automatically migrate random seed files
516      * if a better location becomes available (by reading from the
517      * best location in which we actually find one, and then
518      * writing to the best location in which we can _create_ one).
519      */
520
521     /*
522      * First, try the location specified by the user in the
523      * Registry, if any.
524      */
525     size = sizeof(seedpath);
526     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
527         ERROR_SUCCESS) {
528         int ret = RegQueryValueEx(rkey, "RandSeedFile",
529                                   0, &type, seedpath, &size);
530         if (ret != ERROR_SUCCESS || type != REG_SZ)
531             seedpath[0] = '\0';
532         RegCloseKey(rkey);
533
534         if (*seedpath && try_random_seed(seedpath, action, &rethandle))
535             return rethandle;
536     }
537
538     /*
539      * Next, try the user's local Application Data directory,
540      * followed by their non-local one. This is found using the
541      * SHGetFolderPath function, which won't be present on all
542      * versions of Windows.
543      */
544     if (!tried_shgetfolderpath) {
545         /* This is likely only to bear fruit on systems with IE5+
546          * installed, or WinMe/2K+. There is some faffing with
547          * SHFOLDER.DLL we could do to try to find an equivalent
548          * on older versions of Windows if we cared enough.
549          * However, the invocation below requires IE5+ anyway,
550          * so stuff that. */
551         shell32_module = load_system32_dll("shell32.dll");
552         GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA);
553         tried_shgetfolderpath = TRUE;
554     }
555     if (p_SHGetFolderPathA) {
556         if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA,
557                                          NULL, SHGFP_TYPE_CURRENT, seedpath))) {
558             strcat(seedpath, "\\PUTTY.RND");
559             if (try_random_seed(seedpath, action, &rethandle))
560                 return rethandle;
561         }
562
563         if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA,
564                                          NULL, SHGFP_TYPE_CURRENT, seedpath))) {
565             strcat(seedpath, "\\PUTTY.RND");
566             if (try_random_seed(seedpath, action, &rethandle))
567                 return rethandle;
568         }
569     }
570
571     /*
572      * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
573      * user's home directory.
574      */
575     {
576         int len, ret;
577
578         len =
579             GetEnvironmentVariable("HOMEDRIVE", seedpath,
580                                    sizeof(seedpath));
581         ret =
582             GetEnvironmentVariable("HOMEPATH", seedpath + len,
583                                    sizeof(seedpath) - len);
584         if (ret != 0) {
585             strcat(seedpath, "\\PUTTY.RND");
586             if (try_random_seed(seedpath, action, &rethandle))
587                 return rethandle;
588         }
589     }
590
591     /*
592      * And finally, fall back to C:\WINDOWS.
593      */
594     GetWindowsDirectory(seedpath, sizeof(seedpath));
595     strcat(seedpath, "\\PUTTY.RND");
596     if (try_random_seed(seedpath, action, &rethandle))
597         return rethandle;
598
599     /*
600      * If even that failed, give up.
601      */
602     return INVALID_HANDLE_VALUE;
603 }
604
605 void read_random_seed(noise_consumer_t consumer)
606 {
607     HANDLE seedf = access_random_seed(OPEN_R);
608
609     if (seedf != INVALID_HANDLE_VALUE) {
610         while (1) {
611             char buf[1024];
612             DWORD len;
613
614             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
615                 consumer(buf, len);
616             else
617                 break;
618         }
619         CloseHandle(seedf);
620     }
621 }
622
623 void write_random_seed(void *data, int len)
624 {
625     HANDLE seedf = access_random_seed(OPEN_W);
626
627     if (seedf != INVALID_HANDLE_VALUE) {
628         DWORD lenwritten;
629
630         WriteFile(seedf, data, len, &lenwritten, NULL);
631         CloseHandle(seedf);
632     }
633 }
634
635 /*
636  * Internal function supporting the jump list registry code. All the
637  * functions to add, remove and read the list have substantially
638  * similar content, so this is a generalisation of all of them which
639  * transforms the list in the registry by prepending 'add' (if
640  * non-null), removing 'rem' from what's left (if non-null), and
641  * returning the resulting concatenated list of strings in 'out' (if
642  * non-null).
643  */
644 static int transform_jumplist_registry
645     (const char *add, const char *rem, char **out)
646 {
647     int ret;
648     HKEY pjumplist_key, psettings_tmp;
649     DWORD type;
650     int value_length;
651     char *old_value, *new_value;
652     char *piterator_old, *piterator_new, *piterator_tmp;
653
654     ret = RegCreateKeyEx(HKEY_CURRENT_USER, reg_jumplist_key, 0, NULL,
655                          REG_OPTION_NON_VOLATILE, (KEY_READ | KEY_WRITE), NULL,
656                          &pjumplist_key, NULL);
657     if (ret != ERROR_SUCCESS) {
658         return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE;
659     }
660
661     /* Get current list of saved sessions in the registry. */
662     value_length = 200;
663     old_value = snewn(value_length, char);
664     ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
665                           old_value, &value_length);
666     /* When the passed buffer is too small, ERROR_MORE_DATA is
667      * returned and the required size is returned in the length
668      * argument. */
669     if (ret == ERROR_MORE_DATA) {
670         sfree(old_value);
671         old_value = snewn(value_length, char);
672         ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
673                               old_value, &value_length);
674     }
675
676     if (ret == ERROR_FILE_NOT_FOUND) {
677         /* Value doesn't exist yet. Start from an empty value. */
678         *old_value = '\0';
679         *(old_value + 1) = '\0';
680     } else if (ret != ERROR_SUCCESS) {
681         /* Some non-recoverable error occurred. */
682         sfree(old_value);
683         RegCloseKey(pjumplist_key);
684         return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
685     } else if (type != REG_MULTI_SZ) {
686         /* The value present in the registry has the wrong type: we
687          * try to delete it and start from an empty value. */
688         ret = RegDeleteValue(pjumplist_key, reg_jumplist_value);
689         if (ret != ERROR_SUCCESS) {
690             sfree(old_value);
691             RegCloseKey(pjumplist_key);
692             return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
693         }
694
695         *old_value = '\0';
696         *(old_value + 1) = '\0';
697     }
698
699     /* Check validity of registry data: REG_MULTI_SZ value must end
700      * with \0\0. */
701     piterator_tmp = old_value;
702     while (((piterator_tmp - old_value) < (value_length - 1)) &&
703            !(*piterator_tmp == '\0' && *(piterator_tmp+1) == '\0')) {
704         ++piterator_tmp;
705     }
706
707     if ((piterator_tmp - old_value) >= (value_length-1)) {
708         /* Invalid value. Start from an empty value. */
709         *old_value = '\0';
710         *(old_value + 1) = '\0';
711     }
712
713     /*
714      * Modify the list, if we're modifying.
715      */
716     if (add || rem) {
717         /* Walk through the existing list and construct the new list of
718          * saved sessions. */
719         new_value = snewn(value_length + (add ? strlen(add) + 1 : 0), char);
720         piterator_new = new_value;
721         piterator_old = old_value;
722
723         /* First add the new item to the beginning of the list. */
724         if (add) {
725             strcpy(piterator_new, add);
726             piterator_new += strlen(piterator_new) + 1;
727         }
728         /* Now add the existing list, taking care to leave out the removed
729          * item, if it was already in the existing list. */
730         while (*piterator_old != '\0') {
731             if (!rem || strcmp(piterator_old, rem) != 0) {
732                 /* Check if this is a valid session, otherwise don't add. */
733                 psettings_tmp = open_settings_r(piterator_old);
734                 if (psettings_tmp != NULL) {
735                     close_settings_r(psettings_tmp);
736                     strcpy(piterator_new, piterator_old);
737                     piterator_new += strlen(piterator_new) + 1;
738                 }
739             }
740             piterator_old += strlen(piterator_old) + 1;
741         }
742         *piterator_new = '\0';
743         ++piterator_new;
744
745         /* Save the new list to the registry. */
746         ret = RegSetValueEx(pjumplist_key, reg_jumplist_value, 0, REG_MULTI_SZ,
747                             new_value, piterator_new - new_value);
748
749         sfree(old_value);
750         old_value = new_value;
751     } else
752         ret = ERROR_SUCCESS;
753
754     /*
755      * Either return or free the result.
756      */
757     if (out && ret == ERROR_SUCCESS)
758         *out = old_value;
759     else
760         sfree(old_value);
761
762     /* Clean up and return. */
763     RegCloseKey(pjumplist_key);
764
765     if (ret != ERROR_SUCCESS) {
766         return JUMPLISTREG_ERROR_VALUEWRITE_FAILURE;
767     } else {
768         return JUMPLISTREG_OK;
769     }
770 }
771
772 /* Adds a new entry to the jumplist entries in the registry. */
773 int add_to_jumplist_registry(const char *item)
774 {
775     return transform_jumplist_registry(item, item, NULL);
776 }
777
778 /* Removes an item from the jumplist entries in the registry. */
779 int remove_from_jumplist_registry(const char *item)
780 {
781     return transform_jumplist_registry(NULL, item, NULL);
782 }
783
784 /* Returns the jumplist entries from the registry. Caller must free
785  * the returned pointer. */
786 char *get_jumplist_registry_entries (void)
787 {
788     char *list_value;
789
790     if (transform_jumplist_registry(NULL,NULL,&list_value) != JUMPLISTREG_OK) {
791         list_value = snewn(2, char);
792         *list_value = '\0';
793         *(list_value + 1) = '\0';
794     }
795     return list_value;
796 }
797
798 /*
799  * Recursively delete a registry key and everything under it.
800  */
801 static void registry_recursive_remove(HKEY key)
802 {
803     DWORD i;
804     char name[MAX_PATH + 1];
805     HKEY subkey;
806
807     i = 0;
808     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
809         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
810             registry_recursive_remove(subkey);
811             RegCloseKey(subkey);
812         }
813         RegDeleteKey(key, name);
814     }
815 }
816
817 void cleanup_all(void)
818 {
819     HKEY key;
820     int ret;
821     char name[MAX_PATH + 1];
822
823     /* ------------------------------------------------------------
824      * Wipe out the random seed file, in all of its possible
825      * locations.
826      */
827     access_random_seed(DEL);
828
829     /* ------------------------------------------------------------
830      * Ask Windows to delete any jump list information associated
831      * with this installation of PuTTY.
832      */
833     clear_jumplist();
834
835     /* ------------------------------------------------------------
836      * Destroy all registry information associated with PuTTY.
837      */
838
839     /*
840      * Open the main PuTTY registry key and remove everything in it.
841      */
842     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
843         ERROR_SUCCESS) {
844         registry_recursive_remove(key);
845         RegCloseKey(key);
846     }
847     /*
848      * Now open the parent key and remove the PuTTY main key. Once
849      * we've done that, see if the parent key has any other
850      * children.
851      */
852     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
853                    &key) == ERROR_SUCCESS) {
854         RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
855         ret = RegEnumKey(key, 0, name, sizeof(name));
856         RegCloseKey(key);
857         /*
858          * If the parent key had no other children, we must delete
859          * it in its turn. That means opening the _grandparent_
860          * key.
861          */
862         if (ret != ERROR_SUCCESS) {
863             if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
864                            &key) == ERROR_SUCCESS) {
865                 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
866                 RegCloseKey(key);
867             }
868         }
869     }
870     /*
871      * Now we're done.
872      */
873 }