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