]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winstore.c
6944849658f5ff185df52bfee39e239a6dce31e0
[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 int have_ssh_host_key(const char *hostname, int port,
458                       const char *keytype)
459 {
460     /*
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.
463      */
464     return verify_host_key(hostname, port, keytype, "") != 1;
465 }
466
467 void store_host_key(const char *hostname, int port,
468                     const char *keytype, const char *key)
469 {
470     char *regname;
471     HKEY rkey;
472
473     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
474
475     hostkey_regname(regname, hostname, port, keytype);
476
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);
480         RegCloseKey(rkey);
481     } /* else key does not exist in registry */
482
483     sfree(regname);
484 }
485
486 /*
487  * Open (or delete) the random seed file.
488  */
489 enum { DEL, OPEN_R, OPEN_W };
490 static int try_random_seed(char const *path, int action, HANDLE *ret)
491 {
492     if (action == DEL) {
493         if (!DeleteFile(path) && GetLastError() != ERROR_FILE_NOT_FOUND) {
494             nonfatal("Unable to delete '%s': %s", path,
495                      win_strerror(GetLastError()));
496         }
497         *ret = INVALID_HANDLE_VALUE;
498         return FALSE;                  /* so we'll do the next ones too */
499     }
500
501     *ret = CreateFile(path,
502                       action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
503                       action == OPEN_W ? 0 : (FILE_SHARE_READ |
504                                               FILE_SHARE_WRITE),
505                       NULL,
506                       action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
507                       action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
508                       NULL);
509
510     return (*ret != INVALID_HANDLE_VALUE);
511 }
512
513 static HANDLE access_random_seed(int action)
514 {
515     HKEY rkey;
516     DWORD type, size;
517     HANDLE rethandle;
518     char seedpath[2 * MAX_PATH + 10] = "\0";
519
520     /*
521      * Iterate over a selection of possible random seed paths until
522      * we find one that works.
523      * 
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).
529      */
530
531     /*
532      * First, try the location specified by the user in the
533      * Registry, if any.
534      */
535     size = sizeof(seedpath);
536     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
537         ERROR_SUCCESS) {
538         int ret = RegQueryValueEx(rkey, "RandSeedFile",
539                                   0, &type, seedpath, &size);
540         if (ret != ERROR_SUCCESS || type != REG_SZ)
541             seedpath[0] = '\0';
542         RegCloseKey(rkey);
543
544         if (*seedpath && try_random_seed(seedpath, action, &rethandle))
545             return rethandle;
546     }
547
548     /*
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.
553      */
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,
560          * so stuff that. */
561         shell32_module = load_system32_dll("shell32.dll");
562         GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA);
563         tried_shgetfolderpath = TRUE;
564     }
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))
570                 return rethandle;
571         }
572
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))
577                 return rethandle;
578         }
579     }
580
581     /*
582      * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
583      * user's home directory.
584      */
585     {
586         int len, ret;
587
588         len =
589             GetEnvironmentVariable("HOMEDRIVE", seedpath,
590                                    sizeof(seedpath));
591         ret =
592             GetEnvironmentVariable("HOMEPATH", seedpath + len,
593                                    sizeof(seedpath) - len);
594         if (ret != 0) {
595             strcat(seedpath, "\\PUTTY.RND");
596             if (try_random_seed(seedpath, action, &rethandle))
597                 return rethandle;
598         }
599     }
600
601     /*
602      * And finally, fall back to C:\WINDOWS.
603      */
604     GetWindowsDirectory(seedpath, sizeof(seedpath));
605     strcat(seedpath, "\\PUTTY.RND");
606     if (try_random_seed(seedpath, action, &rethandle))
607         return rethandle;
608
609     /*
610      * If even that failed, give up.
611      */
612     return INVALID_HANDLE_VALUE;
613 }
614
615 void read_random_seed(noise_consumer_t consumer)
616 {
617     HANDLE seedf = access_random_seed(OPEN_R);
618
619     if (seedf != INVALID_HANDLE_VALUE) {
620         while (1) {
621             char buf[1024];
622             DWORD len;
623
624             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
625                 consumer(buf, len);
626             else
627                 break;
628         }
629         CloseHandle(seedf);
630     }
631 }
632
633 void write_random_seed(void *data, int len)
634 {
635     HANDLE seedf = access_random_seed(OPEN_W);
636
637     if (seedf != INVALID_HANDLE_VALUE) {
638         DWORD lenwritten;
639
640         WriteFile(seedf, data, len, &lenwritten, NULL);
641         CloseHandle(seedf);
642     }
643 }
644
645 /*
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
652  * non-null).
653  */
654 static int transform_jumplist_registry
655     (const char *add, const char *rem, char **out)
656 {
657     int ret;
658     HKEY pjumplist_key, psettings_tmp;
659     DWORD type;
660     DWORD value_length;
661     char *old_value, *new_value;
662     char *piterator_old, *piterator_new, *piterator_tmp;
663
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;
669     }
670
671     /* Get current list of saved sessions in the registry. */
672     value_length = 200;
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
678      * argument. */
679     if (ret == ERROR_MORE_DATA) {
680         sfree(old_value);
681         old_value = snewn(value_length, char);
682         ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
683                               old_value, &value_length);
684     }
685
686     if (ret == ERROR_FILE_NOT_FOUND) {
687         /* Value doesn't exist yet. Start from an empty value. */
688         *old_value = '\0';
689         *(old_value + 1) = '\0';
690     } else if (ret != ERROR_SUCCESS) {
691         /* Some non-recoverable error occurred. */
692         sfree(old_value);
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) {
700             sfree(old_value);
701             RegCloseKey(pjumplist_key);
702             return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
703         }
704
705         *old_value = '\0';
706         *(old_value + 1) = '\0';
707     }
708
709     /* Check validity of registry data: REG_MULTI_SZ value must end
710      * with \0\0. */
711     piterator_tmp = old_value;
712     while (((piterator_tmp - old_value) < (value_length - 1)) &&
713            !(*piterator_tmp == '\0' && *(piterator_tmp+1) == '\0')) {
714         ++piterator_tmp;
715     }
716
717     if ((piterator_tmp - old_value) >= (value_length-1)) {
718         /* Invalid value. Start from an empty value. */
719         *old_value = '\0';
720         *(old_value + 1) = '\0';
721     }
722
723     /*
724      * Modify the list, if we're modifying.
725      */
726     if (add || rem) {
727         /* Walk through the existing list and construct the new list of
728          * saved sessions. */
729         new_value = snewn(value_length + (add ? strlen(add) + 1 : 0), char);
730         piterator_new = new_value;
731         piterator_old = old_value;
732
733         /* First add the new item to the beginning of the list. */
734         if (add) {
735             strcpy(piterator_new, add);
736             piterator_new += strlen(piterator_new) + 1;
737         }
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;
748                 }
749             }
750             piterator_old += strlen(piterator_old) + 1;
751         }
752         *piterator_new = '\0';
753         ++piterator_new;
754
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);
758
759         sfree(old_value);
760         old_value = new_value;
761     } else
762         ret = ERROR_SUCCESS;
763
764     /*
765      * Either return or free the result.
766      */
767     if (out && ret == ERROR_SUCCESS)
768         *out = old_value;
769     else
770         sfree(old_value);
771
772     /* Clean up and return. */
773     RegCloseKey(pjumplist_key);
774
775     if (ret != ERROR_SUCCESS) {
776         return JUMPLISTREG_ERROR_VALUEWRITE_FAILURE;
777     } else {
778         return JUMPLISTREG_OK;
779     }
780 }
781
782 /* Adds a new entry to the jumplist entries in the registry. */
783 int add_to_jumplist_registry(const char *item)
784 {
785     return transform_jumplist_registry(item, item, NULL);
786 }
787
788 /* Removes an item from the jumplist entries in the registry. */
789 int remove_from_jumplist_registry(const char *item)
790 {
791     return transform_jumplist_registry(NULL, item, NULL);
792 }
793
794 /* Returns the jumplist entries from the registry. Caller must free
795  * the returned pointer. */
796 char *get_jumplist_registry_entries (void)
797 {
798     char *list_value;
799
800     if (transform_jumplist_registry(NULL,NULL,&list_value) != JUMPLISTREG_OK) {
801         list_value = snewn(2, char);
802         *list_value = '\0';
803         *(list_value + 1) = '\0';
804     }
805     return list_value;
806 }
807
808 /*
809  * Recursively delete a registry key and everything under it.
810  */
811 static void registry_recursive_remove(HKEY key)
812 {
813     DWORD i;
814     char name[MAX_PATH + 1];
815     HKEY subkey;
816
817     i = 0;
818     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
819         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
820             registry_recursive_remove(subkey);
821             RegCloseKey(subkey);
822         }
823         RegDeleteKey(key, name);
824     }
825 }
826
827 void cleanup_all(void)
828 {
829     HKEY key;
830     int ret;
831     char name[MAX_PATH + 1];
832
833     /* ------------------------------------------------------------
834      * Wipe out the random seed file, in all of its possible
835      * locations.
836      */
837     access_random_seed(DEL);
838
839     /* ------------------------------------------------------------
840      * Ask Windows to delete any jump list information associated
841      * with this installation of PuTTY.
842      */
843     clear_jumplist();
844
845     /* ------------------------------------------------------------
846      * Destroy all registry information associated with PuTTY.
847      */
848
849     /*
850      * Open the main PuTTY registry key and remove everything in it.
851      */
852     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
853         ERROR_SUCCESS) {
854         registry_recursive_remove(key);
855         RegCloseKey(key);
856     }
857     /*
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
860      * children.
861      */
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));
866         RegCloseKey(key);
867         /*
868          * If the parent key had no other children, we must delete
869          * it in its turn. That means opening the _grandparent_
870          * key.
871          */
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);
876                 RegCloseKey(key);
877             }
878         }
879     }
880     /*
881      * Now we're done.
882      */
883 }