]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winstore.c
Render timing.c robust in the face of strangeness. The strangenesses
[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 "putty.h"
10 #include "storage.h"
11
12 static const char *const puttystr = PUTTY_REG_POS "\\Sessions";
13
14 static char seedpath[2 * MAX_PATH + 10] = "\0";
15
16 static const char hex[16] = "0123456789ABCDEF";
17
18 static void mungestr(const char *in, char *out)
19 {
20     int candot = 0;
21
22     while (*in) {
23         if (*in == ' ' || *in == '\\' || *in == '*' || *in == '?' ||
24             *in == '%' || *in < ' ' || *in > '~' || (*in == '.'
25                                                      && !candot)) {
26             *out++ = '%';
27             *out++ = hex[((unsigned char) *in) >> 4];
28             *out++ = hex[((unsigned char) *in) & 15];
29         } else
30             *out++ = *in;
31         in++;
32         candot = 1;
33     }
34     *out = '\0';
35     return;
36 }
37
38 static void unmungestr(const char *in, char *out, int outlen)
39 {
40     while (*in) {
41         if (*in == '%' && in[1] && in[2]) {
42             int i, j;
43
44             i = in[1] - '0';
45             i -= (i > 9 ? 7 : 0);
46             j = in[2] - '0';
47             j -= (j > 9 ? 7 : 0);
48
49             *out++ = (i << 4) + j;
50             if (!--outlen)
51                 return;
52             in += 3;
53         } else {
54             *out++ = *in++;
55             if (!--outlen)
56                 return;
57         }
58     }
59     *out = '\0';
60     return;
61 }
62
63 void *open_settings_w(const char *sessionname, char **errmsg)
64 {
65     HKEY subkey1, sesskey;
66     int ret;
67     char *p;
68
69     *errmsg = NULL;
70
71     if (!sessionname || !*sessionname)
72         sessionname = "Default Settings";
73
74     p = snewn(3 * strlen(sessionname) + 1, char);
75     mungestr(sessionname, p);
76
77     ret = RegCreateKey(HKEY_CURRENT_USER, puttystr, &subkey1);
78     if (ret != ERROR_SUCCESS) {
79         sfree(p);
80         *errmsg = dupprintf("Unable to create registry key\n"
81                             "HKEY_CURRENT_USER\\%s", puttystr);
82         return NULL;
83     }
84     ret = RegCreateKey(subkey1, p, &sesskey);
85     RegCloseKey(subkey1);
86     if (ret != ERROR_SUCCESS) {
87         *errmsg = dupprintf("Unable to create registry key\n"
88                             "HKEY_CURRENT_USER\\%s\\%s", puttystr, p);
89         sfree(p);
90         return NULL;
91     }
92     sfree(p);
93     return (void *) sesskey;
94 }
95
96 void write_setting_s(void *handle, const char *key, const char *value)
97 {
98     if (handle)
99         RegSetValueEx((HKEY) handle, key, 0, REG_SZ, value,
100                       1 + strlen(value));
101 }
102
103 void write_setting_i(void *handle, const char *key, int value)
104 {
105     if (handle)
106         RegSetValueEx((HKEY) handle, key, 0, REG_DWORD,
107                       (CONST BYTE *) &value, sizeof(value));
108 }
109
110 void close_settings_w(void *handle)
111 {
112     RegCloseKey((HKEY) handle);
113 }
114
115 void *open_settings_r(const char *sessionname)
116 {
117     HKEY subkey1, sesskey;
118     char *p;
119
120     if (!sessionname || !*sessionname)
121         sessionname = "Default Settings";
122
123     p = snewn(3 * strlen(sessionname) + 1, char);
124     mungestr(sessionname, p);
125
126     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS) {
127         sesskey = NULL;
128     } else {
129         if (RegOpenKey(subkey1, p, &sesskey) != ERROR_SUCCESS) {
130             sesskey = NULL;
131         }
132         RegCloseKey(subkey1);
133     }
134
135     sfree(p);
136
137     return (void *) sesskey;
138 }
139
140 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
141 {
142     DWORD type, size;
143     size = buflen;
144
145     if (!handle ||
146         RegQueryValueEx((HKEY) handle, key, 0,
147                         &type, buffer, &size) != ERROR_SUCCESS ||
148         type != REG_SZ) return NULL;
149     else
150         return buffer;
151 }
152
153 int read_setting_i(void *handle, const char *key, int defvalue)
154 {
155     DWORD type, val, size;
156     size = sizeof(val);
157
158     if (!handle ||
159         RegQueryValueEx((HKEY) handle, key, 0, &type,
160                         (BYTE *) &val, &size) != ERROR_SUCCESS ||
161         size != sizeof(val) || type != REG_DWORD)
162         return defvalue;
163     else
164         return val;
165 }
166
167 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
168 {
169     char *settingname;
170     FontSpec ret;
171
172     if (!read_setting_s(handle, name, ret.name, sizeof(ret.name)))
173         return 0;
174     settingname = dupcat(name, "IsBold", NULL);
175     ret.isbold = read_setting_i(handle, settingname, -1);
176     sfree(settingname);
177     if (ret.isbold == -1) return 0;
178     settingname = dupcat(name, "CharSet", NULL);
179     ret.charset = read_setting_i(handle, settingname, -1);
180     sfree(settingname);
181     if (ret.charset == -1) return 0;
182     settingname = dupcat(name, "Height", NULL);
183     ret.height = read_setting_i(handle, settingname, INT_MIN);
184     sfree(settingname);
185     if (ret.height == INT_MIN) return 0;
186     *result = ret;
187     return 1;
188 }
189
190 void write_setting_fontspec(void *handle, const char *name, FontSpec font)
191 {
192     char *settingname;
193
194     write_setting_s(handle, name, font.name);
195     settingname = dupcat(name, "IsBold", NULL);
196     write_setting_i(handle, settingname, font.isbold);
197     sfree(settingname);
198     settingname = dupcat(name, "CharSet", NULL);
199     write_setting_i(handle, settingname, font.charset);
200     sfree(settingname);
201     settingname = dupcat(name, "Height", NULL);
202     write_setting_i(handle, settingname, font.height);
203     sfree(settingname);
204 }
205
206 int read_setting_filename(void *handle, const char *name, Filename *result)
207 {
208     return !!read_setting_s(handle, name, result->path, sizeof(result->path));
209 }
210
211 void write_setting_filename(void *handle, const char *name, Filename result)
212 {
213     write_setting_s(handle, name, result.path);
214 }
215
216 void close_settings_r(void *handle)
217 {
218     RegCloseKey((HKEY) handle);
219 }
220
221 void del_settings(const char *sessionname)
222 {
223     HKEY subkey1;
224     char *p;
225
226     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &subkey1) != ERROR_SUCCESS)
227         return;
228
229     p = snewn(3 * strlen(sessionname) + 1, char);
230     mungestr(sessionname, p);
231     RegDeleteKey(subkey1, p);
232     sfree(p);
233
234     RegCloseKey(subkey1);
235 }
236
237 struct enumsettings {
238     HKEY key;
239     int i;
240 };
241
242 void *enum_settings_start(void)
243 {
244     struct enumsettings *ret;
245     HKEY key;
246
247     if (RegOpenKey(HKEY_CURRENT_USER, puttystr, &key) != ERROR_SUCCESS)
248         return NULL;
249
250     ret = snew(struct enumsettings);
251     if (ret) {
252         ret->key = key;
253         ret->i = 0;
254     }
255
256     return ret;
257 }
258
259 char *enum_settings_next(void *handle, char *buffer, int buflen)
260 {
261     struct enumsettings *e = (struct enumsettings *) handle;
262     char *otherbuf;
263     otherbuf = snewn(3 * buflen, char);
264     if (RegEnumKey(e->key, e->i++, otherbuf, 3 * buflen) == ERROR_SUCCESS) {
265         unmungestr(otherbuf, buffer, buflen);
266         sfree(otherbuf);
267         return buffer;
268     } else {
269         sfree(otherbuf);
270         return NULL;
271     }
272 }
273
274 void enum_settings_finish(void *handle)
275 {
276     struct enumsettings *e = (struct enumsettings *) handle;
277     RegCloseKey(e->key);
278     sfree(e);
279 }
280
281 static void hostkey_regname(char *buffer, const char *hostname,
282                             int port, const char *keytype)
283 {
284     int len;
285     strcpy(buffer, keytype);
286     strcat(buffer, "@");
287     len = strlen(buffer);
288     len += sprintf(buffer + len, "%d:", port);
289     mungestr(hostname, buffer + strlen(buffer));
290 }
291
292 int verify_host_key(const char *hostname, int port,
293                     const char *keytype, const char *key)
294 {
295     char *otherstr, *regname;
296     int len;
297     HKEY rkey;
298     DWORD readlen;
299     DWORD type;
300     int ret, compare;
301
302     len = 1 + strlen(key);
303
304     /*
305      * Now read a saved key in from the registry and see what it
306      * says.
307      */
308     otherstr = snewn(len, char);
309     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
310
311     hostkey_regname(regname, hostname, port, keytype);
312
313     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
314                    &rkey) != ERROR_SUCCESS)
315         return 1;                      /* key does not exist in registry */
316
317     readlen = len;
318     ret = RegQueryValueEx(rkey, regname, NULL, &type, otherstr, &readlen);
319
320     if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA &&
321         !strcmp(keytype, "rsa")) {
322         /*
323          * Key didn't exist. If the key type is RSA, we'll try
324          * another trick, which is to look up the _old_ key format
325          * under just the hostname and translate that.
326          */
327         char *justhost = regname + 1 + strcspn(regname, ":");
328         char *oldstyle = snewn(len + 10, char); /* safety margin */
329         readlen = len;
330         ret = RegQueryValueEx(rkey, justhost, NULL, &type,
331                               oldstyle, &readlen);
332
333         if (ret == ERROR_SUCCESS && type == REG_SZ) {
334             /*
335              * The old format is two old-style bignums separated by
336              * a slash. An old-style bignum is made of groups of
337              * four hex digits: digits are ordered in sensible
338              * (most to least significant) order within each group,
339              * but groups are ordered in silly (least to most)
340              * order within the bignum. The new format is two
341              * ordinary C-format hex numbers (0xABCDEFG...XYZ, with
342              * A nonzero except in the special case 0x0, which
343              * doesn't appear anyway in RSA keys) separated by a
344              * comma. All hex digits are lowercase in both formats.
345              */
346             char *p = otherstr;
347             char *q = oldstyle;
348             int i, j;
349
350             for (i = 0; i < 2; i++) {
351                 int ndigits, nwords;
352                 *p++ = '0';
353                 *p++ = 'x';
354                 ndigits = strcspn(q, "/");      /* find / or end of string */
355                 nwords = ndigits / 4;
356                 /* now trim ndigits to remove leading zeros */
357                 while (q[(ndigits - 1) ^ 3] == '0' && ndigits > 1)
358                     ndigits--;
359                 /* now move digits over to new string */
360                 for (j = 0; j < ndigits; j++)
361                     p[ndigits - 1 - j] = q[j ^ 3];
362                 p += ndigits;
363                 q += nwords * 4;
364                 if (*q) {
365                     q++;               /* eat the slash */
366                     *p++ = ',';        /* add a comma */
367                 }
368                 *p = '\0';             /* terminate the string */
369             }
370
371             /*
372              * Now _if_ this key matches, we'll enter it in the new
373              * format. If not, we'll assume something odd went
374              * wrong, and hyper-cautiously do nothing.
375              */
376             if (!strcmp(otherstr, key))
377                 RegSetValueEx(rkey, regname, 0, REG_SZ, otherstr,
378                               strlen(otherstr) + 1);
379         }
380     }
381
382     RegCloseKey(rkey);
383
384     compare = strcmp(otherstr, key);
385
386     sfree(otherstr);
387     sfree(regname);
388
389     if (ret == ERROR_MORE_DATA ||
390         (ret == ERROR_SUCCESS && type == REG_SZ && compare))
391         return 2;                      /* key is different in registry */
392     else if (ret != ERROR_SUCCESS || type != REG_SZ)
393         return 1;                      /* key does not exist in registry */
394     else
395         return 0;                      /* key matched OK in registry */
396 }
397
398 void store_host_key(const char *hostname, int port,
399                     const char *keytype, const char *key)
400 {
401     char *regname;
402     HKEY rkey;
403
404     regname = snewn(3 * (strlen(hostname) + strlen(keytype)) + 15, char);
405
406     hostkey_regname(regname, hostname, port, keytype);
407
408     if (RegCreateKey(HKEY_CURRENT_USER, PUTTY_REG_POS "\\SshHostKeys",
409                      &rkey) != ERROR_SUCCESS)
410         return;                        /* key does not exist in registry */
411     RegSetValueEx(rkey, regname, 0, REG_SZ, key, strlen(key) + 1);
412     RegCloseKey(rkey);
413 }
414
415 /*
416  * Find the random seed file path and store it in `seedpath'.
417  */
418 static void get_seedpath(void)
419 {
420     HKEY rkey;
421     DWORD type, size;
422
423     size = sizeof(seedpath);
424
425     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &rkey) ==
426         ERROR_SUCCESS) {
427         int ret = RegQueryValueEx(rkey, "RandSeedFile",
428                                   0, &type, seedpath, &size);
429         if (ret != ERROR_SUCCESS || type != REG_SZ)
430             seedpath[0] = '\0';
431         RegCloseKey(rkey);
432     } else
433         seedpath[0] = '\0';
434
435     if (!seedpath[0]) {
436         int len, ret;
437
438         len =
439             GetEnvironmentVariable("HOMEDRIVE", seedpath,
440                                    sizeof(seedpath));
441         ret =
442             GetEnvironmentVariable("HOMEPATH", seedpath + len,
443                                    sizeof(seedpath) - len);
444         if (ret == 0) {                /* probably win95; store in \WINDOWS */
445             GetWindowsDirectory(seedpath, sizeof(seedpath));
446             len = strlen(seedpath);
447         } else
448             len += ret;
449         strcpy(seedpath + len, "\\PUTTY.RND");
450     }
451 }
452
453 void read_random_seed(noise_consumer_t consumer)
454 {
455     HANDLE seedf;
456
457     if (!seedpath[0])
458         get_seedpath();
459
460     seedf = CreateFile(seedpath, GENERIC_READ,
461                        FILE_SHARE_READ | FILE_SHARE_WRITE,
462                        NULL, OPEN_EXISTING, 0, NULL);
463
464     if (seedf != INVALID_HANDLE_VALUE) {
465         while (1) {
466             char buf[1024];
467             DWORD len;
468
469             if (ReadFile(seedf, buf, sizeof(buf), &len, NULL) && len)
470                 consumer(buf, len);
471             else
472                 break;
473         }
474         CloseHandle(seedf);
475     }
476 }
477
478 void write_random_seed(void *data, int len)
479 {
480     HANDLE seedf;
481
482     if (!seedpath[0])
483         get_seedpath();
484
485     seedf = CreateFile(seedpath, GENERIC_WRITE, 0,
486                        NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
487
488     if (seedf != INVALID_HANDLE_VALUE) {
489         DWORD lenwritten;
490
491         WriteFile(seedf, data, len, &lenwritten, NULL);
492         CloseHandle(seedf);
493     }
494 }
495
496 /*
497  * Recursively delete a registry key and everything under it.
498  */
499 static void registry_recursive_remove(HKEY key)
500 {
501     DWORD i;
502     char name[MAX_PATH + 1];
503     HKEY subkey;
504
505     i = 0;
506     while (RegEnumKey(key, i, name, sizeof(name)) == ERROR_SUCCESS) {
507         if (RegOpenKey(key, name, &subkey) == ERROR_SUCCESS) {
508             registry_recursive_remove(subkey);
509             RegCloseKey(subkey);
510         }
511         RegDeleteKey(key, name);
512     }
513 }
514
515 void cleanup_all(void)
516 {
517     HKEY key;
518     int ret;
519     char name[MAX_PATH + 1];
520
521     /* ------------------------------------------------------------
522      * Wipe out the random seed file.
523      */
524     if (!seedpath[0])
525         get_seedpath();
526     remove(seedpath);
527
528     /* ------------------------------------------------------------
529      * Destroy all registry information associated with PuTTY.
530      */
531
532     /*
533      * Open the main PuTTY registry key and remove everything in it.
534      */
535     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_POS, &key) ==
536         ERROR_SUCCESS) {
537         registry_recursive_remove(key);
538         RegCloseKey(key);
539     }
540     /*
541      * Now open the parent key and remove the PuTTY main key. Once
542      * we've done that, see if the parent key has any other
543      * children.
544      */
545     if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_PARENT,
546                    &key) == ERROR_SUCCESS) {
547         RegDeleteKey(key, PUTTY_REG_PARENT_CHILD);
548         ret = RegEnumKey(key, 0, name, sizeof(name));
549         RegCloseKey(key);
550         /*
551          * If the parent key had no other children, we must delete
552          * it in its turn. That means opening the _grandparent_
553          * key.
554          */
555         if (ret != ERROR_SUCCESS) {
556             if (RegOpenKey(HKEY_CURRENT_USER, PUTTY_REG_GPARENT,
557                            &key) == ERROR_SUCCESS) {
558                 RegDeleteKey(key, PUTTY_REG_GPARENT_CHILD);
559                 RegCloseKey(key);
560             }
561         }
562     }
563     /*
564      * Now we're done.
565      */
566 }