]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winstore.c
A bunch of further warning fixes in the Windows code.
[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, (CONST BYTE *)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, (BYTE *)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,
376                           &type, (BYTE *)otherstr, &readlen);
377
378     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
379         !strcmp(keytype, "rsa")) {
380         /*
381          * Key didn't exist. If the key type is RSA, we'll try
382          * another trick, which is to look up the _old_ key format
383          * under just the hostname and translate that.
384          */
385         char *justhost = regname + 1 + strcspn(regname, ":");
386         char *oldstyle = snewn(len + 10, char); /* safety margin */
387         readlen = len;
388         ret = RegQueryValueEx(rkey, justhost, NULL, &type,
389                               (BYTE *)oldstyle, &readlen);
390
391         if (ret == ERROR_SUCCESS && type == REG_SZ) {
392             /*
393              * The old format is two old-style bignums separated by
394              * a slash. An old-style bignum is made of groups of
395              * four hex digits: digits are ordered in sensible
396              * (most to least significant) order within each group,
397              * but groups are ordered in silly (least to most)
398              * order within the bignum. The new format is two
399              * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
400              * A nonzero except in the special case 0x0, which
401              * doesn't appear anyway in RSA keys) separated by a
402              * comma. All hex digits are lowercase in both formats.
403              */
404             char *p = otherstr;
405             char *q = oldstyle;
406             int i, j;
407
408             for (i = 0; i < 2; i++) {
409                 int ndigits, nwords;
410                 *p++ = '0';
411                 *p++ = 'x';
412                 ndigits = strcspn(q, "/");      /* find / or end of string */
413                 nwords = ndigits / 4;
414                 /* now trim ndigits to remove leading zeros */
415                 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
416                     ndigits--;
417                 /* now move digits over to new string */
418                 for (j = 0; j < ndigits; j++)
419                     p[ndigits - 1 - j] = q[j ^ 3];
420                 p += ndigits;
421                 q += nwords * 4;
422                 if (*q) {
423                     q++;               /* eat the slash */
424                     *p++ = ',';        /* add a comma */
425                 }
426                 *p = '\0';             /* terminate the string */
427             }
428
429             /*
430              * Now _if_ this key matches, we'll enter it in the new
431              * format. If not, we'll assume something odd went
432              * wrong, and hyper-cautiously do nothing.
433              */
434             if (!strcmp(otherstr, key))
435                 RegSetValueEx(rkey, regname, 0, REG_SZ, (BYTE *)otherstr,
436                               strlen(otherstr) + 1);
437         }
438
439         sfree(oldstyle);
440     }
441
442     RegCloseKey(rkey);
443
444     compare = strcmp(otherstr, key);
445
446     sfree(otherstr);
447     sfree(regname);
448
449     if (ret == ERROR_MORE_DATA ||
450         (ret == ERROR_SUCCESS && type == REG_SZ && compare))
451         return 2;                      /* key is different in registry */
452     else if (ret != ERROR_SUCCESS || type != REG_SZ)
453         return 1;                      /* key does not exist in registry */
454     else
455         return 0;                      /* key matched OK in registry */
456 }
457
458 int have_ssh_host_key(const char *hostname, int port,
459                       const char *keytype)
460 {
461     /*
462      * If we have a host key, verify_host_key will return 0 or 2.
463      * If we don't have one, it'll return 1.
464      */
465     return verify_host_key(hostname, port, keytype, "") != 1;
466 }
467
468 void store_host_key(const char *hostname, int port,
469                     const char *keytype, const char *key)
470 {
471     char *regname;
472     HKEY rkey;
473
474     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
475
476     hostkey_regname(regname, hostname, port, keytype);
477
478     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
479                      &rkey) == ERROR_SUCCESS) {
480         RegSetValueEx(rkey, regname, 0, REG_SZ, (BYTE *)key, strlen(key) + 1);
481         RegCloseKey(rkey);
482     } /* else key does not exist in registry */
483
484     sfree(regname);
485 }
486
487 /*
488  * Open (or delete) the random seed file.
489  */
490 enum { DEL, OPEN_R, OPEN_W };
491 static int try_random_seed(char const *path, int action, HANDLE *ret)
492 {
493     if (action == DEL) {
494         if (!DeleteFile(path) && GetLastError() != ERROR_FILE_NOT_FOUND) {
495             nonfatal("Unable to delete '%s': %s", path,
496                      win_strerror(GetLastError()));
497         }
498         *ret = INVALID_HANDLE_VALUE;
499         return FALSE;                  /* so we'll do the next ones too */
500     }
501
502     *ret = CreateFile(path,
503                       action == OPEN_W ? GENERIC_WRITE : GENERIC_READ,
504                       action == OPEN_W ? 0 : (FILE_SHARE_READ |
505                                               FILE_SHARE_WRITE),
506                       NULL,
507                       action == OPEN_W ? CREATE_ALWAYS : OPEN_EXISTING,
508                       action == OPEN_W ? FILE_ATTRIBUTE_NORMAL : 0,
509                       NULL);
510
511     return (*ret != INVALID_HANDLE_VALUE);
512 }
513
514 static HANDLE access_random_seed(int action)
515 {
516     HKEY rkey;
517     DWORD type, size;
518     HANDLE rethandle;
519     char seedpath[2 * MAX_PATH + 10] = "\0";
520
521     /*
522      * Iterate over a selection of possible random seed paths until
523      * we find one that works.
524      * 
525      * We do this iteration separately for reading and writing,
526      * meaning that we will automatically migrate random seed files
527      * if a better location becomes available (by reading from the
528      * best location in which we actually find one, and then
529      * writing to the best location in which we can _create_ one).
530      */
531
532     /*
533      * First, try the location specified by the user in the
534      * Registry, if any.
535      */
536     size = sizeof(seedpath);
537     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
538         ERROR_SUCCESS) {
539         int ret = RegQueryValueEx(rkey, "RandSeedFile",
540                                   0, &type, (BYTE *)seedpath, &size);
541         if (ret != ERROR_SUCCESS || type != REG_SZ)
542             seedpath[0] = '\0';
543         RegCloseKey(rkey);
544
545         if (*seedpath && try_random_seed(seedpath, action, &rethandle))
546             return rethandle;
547     }
548
549     /*
550      * Next, try the user's local Application Data directory,
551      * followed by their non-local one. This is found using the
552      * SHGetFolderPath function, which won't be present on all
553      * versions of Windows.
554      */
555     if (!tried_shgetfolderpath) {
556         /* This is likely only to bear fruit on systems with IE5+
557          * installed, or WinMe/2K+. There is some faffing with
558          * SHFOLDER.DLL we could do to try to find an equivalent
559          * on older versions of Windows if we cared enough.
560          * However, the invocation below requires IE5+ anyway,
561          * so stuff that. */
562         shell32_module = load_system32_dll("shell32.dll");
563         GET_WINDOWS_FUNCTION(shell32_module, SHGetFolderPathA);
564         tried_shgetfolderpath = TRUE;
565     }
566     if (p_SHGetFolderPathA) {
567         if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA,
568                                          NULL, SHGFP_TYPE_CURRENT, seedpath))) {
569             strcat(seedpath, "\\PUTTY.RND");
570             if (try_random_seed(seedpath, action, &rethandle))
571                 return rethandle;
572         }
573
574         if (SUCCEEDED(p_SHGetFolderPathA(NULL, CSIDL_APPDATA,
575                                          NULL, SHGFP_TYPE_CURRENT, seedpath))) {
576             strcat(seedpath, "\\PUTTY.RND");
577             if (try_random_seed(seedpath, action, &rethandle))
578                 return rethandle;
579         }
580     }
581
582     /*
583      * Failing that, try %HOMEDRIVE%%HOMEPATH% as a guess at the
584      * user's home directory.
585      */
586     {
587         int len, ret;
588
589         len =
590             GetEnvironmentVariable("HOMEDRIVE", seedpath,
591                                    sizeof(seedpath));
592         ret =
593             GetEnvironmentVariable("HOMEPATH", seedpath + len,
594                                    sizeof(seedpath) - len);
595         if (ret != 0) {
596             strcat(seedpath, "\\PUTTY.RND");
597             if (try_random_seed(seedpath, action, &rethandle))
598                 return rethandle;
599         }
600     }
601
602     /*
603      * And finally, fall back to C:\WINDOWS.
604      */
605     GetWindowsDirectory(seedpath, sizeof(seedpath));
606     strcat(seedpath, "\\PUTTY.RND");
607     if (try_random_seed(seedpath, action, &rethandle))
608         return rethandle;
609
610     /*
611      * If even that failed, give up.
612      */
613     return INVALID_HANDLE_VALUE;
614 }
615
616 void read_random_seed(noise_consumer_t consumer)
617 {
618     HANDLE seedf = access_random_seed(OPEN_R);
619
620     if (seedf != INVALID_HANDLE_VALUE) {
621         while (1) {
622             char buf[1024];
623             DWORD len;
624
625             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
626                 consumer(buf, len);
627             else
628                 break;
629         }
630         CloseHandle(seedf);
631     }
632 }
633
634 void write_random_seed(void *data, int len)
635 {
636     HANDLE seedf = access_random_seed(OPEN_W);
637
638     if (seedf != INVALID_HANDLE_VALUE) {
639         DWORD lenwritten;
640
641         WriteFile(seedf, data, len, &lenwritten, NULL);
642         CloseHandle(seedf);
643     }
644 }
645
646 /*
647  * Internal function supporting the jump list registry code. All the
648  * functions to add, remove and read the list have substantially
649  * similar content, so this is a generalisation of all of them which
650  * transforms the list in the registry by prepending 'add' (if
651  * non-null), removing 'rem' from what's left (if non-null), and
652  * returning the resulting concatenated list of strings in 'out' (if
653  * non-null).
654  */
655 static int transform_jumplist_registry
656     (const char *add, const char *rem, char **out)
657 {
658     int ret;
659     HKEY pjumplist_key, psettings_tmp;
660     DWORD type;
661     DWORD value_length;
662     char *old_value, *new_value;
663     char *piterator_old, *piterator_new, *piterator_tmp;
664
665     ret = RegCreateKeyEx(HKEY_CURRENT_USER, reg_jumplist_key, 0, NULL,
666                          REG_OPTION_NON_VOLATILE, (KEY_READ | KEY_WRITE), NULL,
667                          &pjumplist_key, NULL);
668     if (ret != ERROR_SUCCESS) {
669         return JUMPLISTREG_ERROR_KEYOPENCREATE_FAILURE;
670     }
671
672     /* Get current list of saved sessions in the registry. */
673     value_length = 200;
674     old_value = snewn(value_length, char);
675     ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
676                           (BYTE *)old_value, &value_length);
677     /* When the passed buffer is too small, ERROR_MORE_DATA is
678      * returned and the required size is returned in the length
679      * argument. */
680     if (ret == ERROR_MORE_DATA) {
681         sfree(old_value);
682         old_value = snewn(value_length, char);
683         ret = RegQueryValueEx(pjumplist_key, reg_jumplist_value, NULL, &type,
684                               (BYTE *)old_value, &value_length);
685     }
686
687     if (ret == ERROR_FILE_NOT_FOUND) {
688         /* Value doesn't exist yet. Start from an empty value. */
689         *old_value = '\0';
690         *(old_value + 1) = '\0';
691     } else if (ret != ERROR_SUCCESS) {
692         /* Some non-recoverable error occurred. */
693         sfree(old_value);
694         RegCloseKey(pjumplist_key);
695         return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
696     } else if (type != REG_MULTI_SZ) {
697         /* The value present in the registry has the wrong type: we
698          * try to delete it and start from an empty value. */
699         ret = RegDeleteValue(pjumplist_key, reg_jumplist_value);
700         if (ret != ERROR_SUCCESS) {
701             sfree(old_value);
702             RegCloseKey(pjumplist_key);
703             return JUMPLISTREG_ERROR_VALUEREAD_FAILURE;
704         }
705
706         *old_value = '\0';
707         *(old_value + 1) = '\0';
708     }
709
710     /* Check validity of registry data: REG_MULTI_SZ value must end
711      * with \0\0. */
712     piterator_tmp = old_value;
713     while (((piterator_tmp - old_value) < (value_length - 1)) &&
714            !(*piterator_tmp == '\0' && *(piterator_tmp+1) == '\0')) {
715         ++piterator_tmp;
716     }
717
718     if ((piterator_tmp - old_value) >= (value_length-1)) {
719         /* Invalid value. Start from an empty value. */
720         *old_value = '\0';
721         *(old_value + 1) = '\0';
722     }
723
724     /*
725      * Modify the list, if we're modifying.
726      */
727     if (add || rem) {
728         /* Walk through the existing list and construct the new list of
729          * saved sessions. */
730         new_value = snewn(value_length + (add ? strlen(add) + 1 : 0), char);
731         piterator_new = new_value;
732         piterator_old = old_value;
733
734         /* First add the new item to the beginning of the list. */
735         if (add) {
736             strcpy(piterator_new, add);
737             piterator_new += strlen(piterator_new) + 1;
738         }
739         /* Now add the existing list, taking care to leave out the removed
740          * item, if it was already in the existing list. */
741         while (*piterator_old != '\0') {
742             if (!rem || strcmp(piterator_old, rem) != 0) {
743                 /* Check if this is a valid session, otherwise don't add. */
744                 psettings_tmp = open_settings_r(piterator_old);
745                 if (psettings_tmp != NULL) {
746                     close_settings_r(psettings_tmp);
747                     strcpy(piterator_new, piterator_old);
748                     piterator_new += strlen(piterator_new) + 1;
749                 }
750             }
751             piterator_old += strlen(piterator_old) + 1;
752         }
753         *piterator_new = '\0';
754         ++piterator_new;
755
756         /* Save the new list to the registry. */
757         ret = RegSetValueEx(pjumplist_key, reg_jumplist_value, 0, REG_MULTI_SZ,
758                             (BYTE *)new_value, piterator_new - new_value);
759
760         sfree(old_value);
761         old_value = new_value;
762     } else
763         ret = ERROR_SUCCESS;
764
765     /*
766      * Either return or free the result.
767      */
768     if (out && ret == ERROR_SUCCESS)
769         *out = old_value;
770     else
771         sfree(old_value);
772
773     /* Clean up and return. */
774     RegCloseKey(pjumplist_key);
775
776     if (ret != ERROR_SUCCESS) {
777         return JUMPLISTREG_ERROR_VALUEWRITE_FAILURE;
778     } else {
779         return JUMPLISTREG_OK;
780     }
781 }
782
783 /* Adds a new entry to the jumplist entries in the registry. */
784 int add_to_jumplist_registry(const char *item)
785 {
786     return transform_jumplist_registry(item, item, NULL);
787 }
788
789 /* Removes an item from the jumplist entries in the registry. */
790 int remove_from_jumplist_registry(const char *item)
791 {
792     return transform_jumplist_registry(NULL, item, NULL);
793 }
794
795 /* Returns the jumplist entries from the registry. Caller must free
796  * the returned pointer. */
797 char *get_jumplist_registry_entries (void)
798 {
799     char *list_value;
800
801     if (transform_jumplist_registry(NULL,NULL,&list_value) != JUMPLISTREG_OK) {
802         list_value = snewn(2, char);
803         *list_value = '\0';
804         *(list_value + 1) = '\0';
805     }
806     return list_value;
807 }
808
809 /*
810  * Recursively delete a registry key and everything under it.
811  */
812 static void registry_recursive_remove(HKEY key)
813 {
814     DWORD i;
815     char name[MAX_PATH + 1];
816     HKEY subkey;
817
818     i = 0;
819     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
820         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
821             registry_recursive_remove(subkey);
822             RegCloseKey(subkey);
823         }
824         RegDeleteKey(key, name);
825     }
826 }
827
828 void cleanup_all(void)
829 {
830     HKEY key;
831     int ret;
832     char name[MAX_PATH + 1];
833
834     /* ------------------------------------------------------------
835      * Wipe out the random seed file, in all of its possible
836      * locations.
837      */
838     access_random_seed(DEL);
839
840     /* ------------------------------------------------------------
841      * Ask Windows to delete any jump list information associated
842      * with this installation of PuTTY.
843      */
844     clear_jumplist();
845
846     /* ------------------------------------------------------------
847      * Destroy all registry information associated with PuTTY.
848      */
849
850     /*
851      * Open the main PuTTY registry key and remove everything in it.
852      */
853     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
854         ERROR_SUCCESS) {
855         registry_recursive_remove(key);
856         RegCloseKey(key);
857     }
858     /*
859      * Now open the parent key and remove the PuTTY main key. Once
860      * we've done that, see if the parent key has any other
861      * children.
862      */
863     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
864                    &key) == ERROR_SUCCESS) {
865         RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
866         ret = RegEnumKey(key, 0, name, sizeof(name));
867         RegCloseKey(key);
868         /*
869          * If the parent key had no other children, we must delete
870          * it in its turn. That means opening the _grandparent_
871          * key.
872          */
873         if (ret != ERROR_SUCCESS) {
874             if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
875                            &key) == ERROR_SUCCESS) {
876                 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
877                 RegCloseKey(key);
878             }
879         }
880     }
881     /*
882      * Now we're done.
883      */
884 }