Close the host keys file after use. Well spotted Theo Markettos.
[u/mdw/putty] / unix / uxstore.c
1 /*
2 * uxstore.c: Unix-specific implementation of the interface defined
3 * in storage.h.
4 */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <errno.h>
11 #include <ctype.h>
12 #include <unistd.h>
13 #include <fcntl.h>
14 #include <dirent.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include "putty.h"
18 #include "storage.h"
19 #include "tree234.h"
20
21 enum {
22 INDEX_DIR, INDEX_HOSTKEYS, INDEX_RANDSEED,
23 INDEX_SESSIONDIR, INDEX_SESSION,
24 };
25
26 static const char hex[16] = "0123456789ABCDEF";
27
28 static char *mungestr(const char *in)
29 {
30 char *out, *ret;
31
32 if (!in || !*in)
33 in = "Default Settings";
34
35 ret = out = snewn(3*strlen(in)+1, char);
36
37 while (*in) {
38 /*
39 * There are remarkably few punctuation characters that
40 * aren't shell-special in some way or likely to be used as
41 * separators in some file format or another! Hence we use
42 * opt-in for safe characters rather than opt-out for
43 * specific unsafe ones...
44 */
45 if (*in!='+' && *in!='-' && *in!='.' && *in!='@' && *in!='_' &&
46 !(*in >= '0' && *in <= '9') &&
47 !(*in >= 'A' && *in <= 'Z') &&
48 !(*in >= 'a' && *in <= 'z')) {
49 *out++ = '%';
50 *out++ = hex[((unsigned char) *in) >> 4];
51 *out++ = hex[((unsigned char) *in) & 15];
52 } else
53 *out++ = *in;
54 in++;
55 }
56 *out = '\0';
57 return ret;
58 }
59
60 static char *unmungestr(const char *in)
61 {
62 char *out, *ret;
63 out = ret = snewn(strlen(in)+1, char);
64 while (*in) {
65 if (*in == '%' && in[1] && in[2]) {
66 int i, j;
67
68 i = in[1] - '0';
69 i -= (i > 9 ? 7 : 0);
70 j = in[2] - '0';
71 j -= (j > 9 ? 7 : 0);
72
73 *out++ = (i << 4) + j;
74 in += 3;
75 } else {
76 *out++ = *in++;
77 }
78 }
79 *out = '\0';
80 return ret;
81 }
82
83 static void make_filename(char *filename, int index, const char *subname)
84 {
85 char *home;
86 int len;
87 home = getenv("HOME");
88 strncpy(filename, home, FILENAME_MAX);
89 len = strlen(filename);
90 if (index == INDEX_SESSION) {
91 char *munged = mungestr(subname);
92 char *fn = dupprintf("/.putty/sessions/%s", munged);
93 strncpy(filename + len, fn, FILENAME_MAX - len);
94 sfree(fn);
95 sfree(munged);
96 } else {
97 strncpy(filename + len,
98 index == INDEX_DIR ? "/.putty" :
99 index == INDEX_SESSIONDIR ? "/.putty/sessions" :
100 index == INDEX_HOSTKEYS ? "/.putty/sshhostkeys" :
101 index == INDEX_RANDSEED ? "/.putty/randomseed" :
102 "/.putty/ERROR", FILENAME_MAX - len);
103 }
104 filename[FILENAME_MAX-1] = '\0';
105 }
106
107 /*
108 * Read an entire line of text from a file. Return a buffer
109 * malloced to be as big as necessary (caller must free).
110 */
111 static char *fgetline(FILE *fp)
112 {
113 char *ret = snewn(512, char);
114 int size = 512, len = 0;
115 while (fgets(ret + len, size - len, fp)) {
116 len += strlen(ret + len);
117 if (ret[len-1] == '\n')
118 break; /* got a newline, we're done */
119 size = len + 512;
120 ret = sresize(ret, size, char);
121 }
122 if (len == 0) { /* first fgets returned NULL */
123 sfree(ret);
124 return NULL;
125 }
126 ret[len] = '\0';
127 return ret;
128 }
129
130 void *open_settings_w(const char *sessionname, char **errmsg)
131 {
132 char filename[FILENAME_MAX];
133 FILE *fp;
134
135 *errmsg = NULL;
136
137 /*
138 * Start by making sure the .putty directory and its sessions
139 * subdir actually exist. Ignore error returns from mkdir since
140 * they're perfectly likely to be `already exists', and any
141 * other error will trip us up later on so there's no real need
142 * to catch it now.
143 */
144 make_filename(filename, INDEX_DIR, sessionname);
145 mkdir(filename, 0700);
146 make_filename(filename, INDEX_SESSIONDIR, sessionname);
147 mkdir(filename, 0700);
148
149 make_filename(filename, INDEX_SESSION, sessionname);
150 fp = fopen(filename, "w");
151 if (!fp) {
152 *errmsg = dupprintf("Unable to create %s: %s",
153 filename, strerror(errno));
154 return NULL; /* can't open */
155 }
156 return fp;
157 }
158
159 void write_setting_s(void *handle, const char *key, const char *value)
160 {
161 FILE *fp = (FILE *)handle;
162 fprintf(fp, "%s=%s\n", key, value);
163 }
164
165 void write_setting_i(void *handle, const char *key, int value)
166 {
167 FILE *fp = (FILE *)handle;
168 fprintf(fp, "%s=%d\n", key, value);
169 }
170
171 void close_settings_w(void *handle)
172 {
173 FILE *fp = (FILE *)handle;
174 fclose(fp);
175 }
176
177 /*
178 * Reading settings, for the moment, is done by retrieving X
179 * resources from the X display. When we introduce disk files, I
180 * think what will happen is that the X resources will override
181 * PuTTY's inbuilt defaults, but that the disk files will then
182 * override those. This isn't optimal, but it's the best I can
183 * immediately work out.
184 * FIXME: the above comment is a bit out of date. Did it happen?
185 */
186
187 struct keyval {
188 const char *key;
189 const char *value;
190 };
191
192 static tree234 *xrmtree = NULL;
193
194 int keycmp(void *av, void *bv)
195 {
196 struct keyval *a = (struct keyval *)av;
197 struct keyval *b = (struct keyval *)bv;
198 return strcmp(a->key, b->key);
199 }
200
201 void provide_xrm_string(char *string)
202 {
203 char *p, *q, *key;
204 struct keyval *xrms, *ret;
205
206 p = q = strchr(string, ':');
207 if (!q) {
208 fprintf(stderr, "pterm: expected a colon in resource string"
209 " \"%s\"\n", string);
210 return;
211 }
212 q++;
213 while (p > string && p[-1] != '.' && p[-1] != '*')
214 p--;
215 xrms = snew(struct keyval);
216 key = snewn(q-p, char);
217 memcpy(key, p, q-p);
218 key[q-p-1] = '\0';
219 xrms->key = key;
220 while (*q && isspace((unsigned char)*q))
221 q++;
222 xrms->value = dupstr(q);
223
224 if (!xrmtree)
225 xrmtree = newtree234(keycmp);
226
227 ret = add234(xrmtree, xrms);
228 if (ret) {
229 /* Override an existing string. */
230 del234(xrmtree, ret);
231 add234(xrmtree, xrms);
232 }
233 }
234
235 const char *get_setting(const char *key)
236 {
237 struct keyval tmp, *ret;
238 tmp.key = key;
239 if (xrmtree) {
240 ret = find234(xrmtree, &tmp, NULL);
241 if (ret)
242 return ret->value;
243 }
244 return x_get_default(key);
245 }
246
247 void *open_settings_r(const char *sessionname)
248 {
249 char filename[FILENAME_MAX];
250 FILE *fp;
251 char *line;
252 tree234 *ret;
253
254 make_filename(filename, INDEX_SESSION, sessionname);
255 fp = fopen(filename, "r");
256 if (!fp)
257 return NULL; /* can't open */
258
259 ret = newtree234(keycmp);
260
261 while ( (line = fgetline(fp)) ) {
262 char *value = strchr(line, '=');
263 struct keyval *kv;
264
265 if (!value)
266 continue;
267 *value++ = '\0';
268 value[strcspn(value, "\r\n")] = '\0'; /* trim trailing NL */
269
270 kv = snew(struct keyval);
271 kv->key = dupstr(line);
272 kv->value = dupstr(value);
273 add234(ret, kv);
274
275 sfree(line);
276 }
277
278 fclose(fp);
279
280 return ret;
281 }
282
283 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
284 {
285 tree234 *tree = (tree234 *)handle;
286 const char *val;
287 struct keyval tmp, *kv;
288
289 tmp.key = key;
290 if (tree != NULL &&
291 (kv = find234(tree, &tmp, NULL)) != NULL) {
292 val = kv->value;
293 assert(val != NULL);
294 } else
295 val = get_setting(key);
296
297 if (!val)
298 return NULL;
299 else {
300 strncpy(buffer, val, buflen);
301 buffer[buflen-1] = '\0';
302 return buffer;
303 }
304 }
305
306 int read_setting_i(void *handle, const char *key, int defvalue)
307 {
308 tree234 *tree = (tree234 *)handle;
309 const char *val;
310 struct keyval tmp, *kv;
311
312 tmp.key = key;
313 if (tree != NULL &&
314 (kv = find234(tree, &tmp, NULL)) != NULL) {
315 val = kv->value;
316 assert(val != NULL);
317 } else
318 val = get_setting(key);
319
320 if (!val)
321 return defvalue;
322 else
323 return atoi(val);
324 }
325
326 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
327 {
328 return !!read_setting_s(handle, name, result->name, sizeof(result->name));
329 }
330 int read_setting_filename(void *handle, const char *name, Filename *result)
331 {
332 return !!read_setting_s(handle, name, result->path, sizeof(result->path));
333 }
334
335 void write_setting_fontspec(void *handle, const char *name, FontSpec result)
336 {
337 write_setting_s(handle, name, result.name);
338 }
339 void write_setting_filename(void *handle, const char *name, Filename result)
340 {
341 write_setting_s(handle, name, result.path);
342 }
343
344 void close_settings_r(void *handle)
345 {
346 tree234 *tree = (tree234 *)handle;
347 struct keyval *kv;
348
349 if (!tree)
350 return;
351
352 while ( (kv = index234(tree, 0)) != NULL) {
353 del234(tree, kv);
354 sfree((char *)kv->key);
355 sfree((char *)kv->value);
356 sfree(kv);
357 }
358
359 freetree234(tree);
360 }
361
362 void del_settings(const char *sessionname)
363 {
364 char filename[FILENAME_MAX];
365 make_filename(filename, INDEX_SESSION, sessionname);
366 unlink(filename);
367 }
368
369 void *enum_settings_start(void)
370 {
371 DIR *dp;
372 char filename[FILENAME_MAX];
373
374 make_filename(filename, INDEX_SESSIONDIR, NULL);
375 dp = opendir(filename);
376
377 return dp;
378 }
379
380 char *enum_settings_next(void *handle, char *buffer, int buflen)
381 {
382 DIR *dp = (DIR *)handle;
383 struct dirent *de;
384 struct stat st;
385 char fullpath[FILENAME_MAX];
386 int len;
387 char *unmunged;
388
389 make_filename(fullpath, INDEX_SESSIONDIR, NULL);
390 len = strlen(fullpath);
391
392 while ( (de = readdir(dp)) != NULL ) {
393 if (len < FILENAME_MAX) {
394 fullpath[len] = '/';
395 strncpy(fullpath+len+1, de->d_name, FILENAME_MAX-(len+1));
396 fullpath[FILENAME_MAX-1] = '\0';
397 }
398
399 if (stat(fullpath, &st) < 0 || !S_ISREG(st.st_mode))
400 continue; /* try another one */
401
402 unmunged = unmungestr(de->d_name);
403 strncpy(buffer, unmunged, buflen);
404 buffer[buflen-1] = '\0';
405 sfree(unmunged);
406 return buffer;
407 }
408
409 return NULL;
410 }
411
412 void enum_settings_finish(void *handle)
413 {
414 DIR *dp = (DIR *)handle;
415 closedir(dp);
416 }
417
418 /*
419 * Lines in the host keys file are of the form
420 *
421 * type@port:hostname keydata
422 *
423 * e.g.
424 *
425 * rsa@22:foovax.example.org 0x23,0x293487364395345345....2343
426 */
427 int verify_host_key(const char *hostname, int port,
428 const char *keytype, const char *key)
429 {
430 FILE *fp;
431 char filename[FILENAME_MAX];
432 char *line;
433 int ret;
434
435 make_filename(filename, INDEX_HOSTKEYS, NULL);
436 fp = fopen(filename, "r");
437 if (!fp)
438 return 1; /* key does not exist */
439
440 ret = 1;
441 while ( (line = fgetline(fp)) ) {
442 int i;
443 char *p = line;
444 char porttext[20];
445
446 line[strcspn(line, "\n")] = '\0'; /* strip trailing newline */
447
448 i = strlen(keytype);
449 if (strncmp(p, keytype, i))
450 goto done;
451 p += i;
452
453 if (*p != '@')
454 goto done;
455 p++;
456
457 sprintf(porttext, "%d", port);
458 i = strlen(porttext);
459 if (strncmp(p, porttext, i))
460 goto done;
461 p += i;
462
463 if (*p != ':')
464 goto done;
465 p++;
466
467 i = strlen(hostname);
468 if (strncmp(p, hostname, i))
469 goto done;
470 p += i;
471
472 if (*p != ' ')
473 goto done;
474 p++;
475
476 /*
477 * Found the key. Now just work out whether it's the right
478 * one or not.
479 */
480 if (!strcmp(p, key))
481 ret = 0; /* key matched OK */
482 else
483 ret = 2; /* key mismatch */
484
485 done:
486 sfree(line);
487 if (ret != 1)
488 break;
489 }
490
491 fclose(fp);
492 return ret;
493 }
494
495 void store_host_key(const char *hostname, int port,
496 const char *keytype, const char *key)
497 {
498 FILE *fp;
499 int fd;
500 char filename[FILENAME_MAX];
501
502 make_filename(filename, INDEX_HOSTKEYS, NULL);
503 fd = open(filename, O_CREAT | O_APPEND | O_RDWR, 0600);
504 if (fd < 0) {
505 char dir[FILENAME_MAX];
506
507 make_filename(dir, INDEX_DIR, NULL);
508 mkdir(dir, 0700);
509 fd = open(filename, O_CREAT | O_APPEND | O_RDWR, 0600);
510 }
511 if (fd < 0) {
512 perror(filename);
513 exit(1);
514 }
515 fp = fdopen(fd, "a");
516 fprintf(fp, "%s@%d:%s %s\n", keytype, port, hostname, key);
517 fclose(fp);
518 }
519
520 void read_random_seed(noise_consumer_t consumer)
521 {
522 int fd;
523 char fname[FILENAME_MAX];
524
525 make_filename(fname, INDEX_RANDSEED, NULL);
526 fd = open(fname, O_RDONLY);
527 if (fd) {
528 char buf[512];
529 int ret;
530 while ( (ret = read(fd, buf, sizeof(buf))) > 0)
531 consumer(buf, ret);
532 close(fd);
533 }
534 }
535
536 void write_random_seed(void *data, int len)
537 {
538 int fd;
539 char fname[FILENAME_MAX];
540
541 make_filename(fname, INDEX_RANDSEED, NULL);
542 /*
543 * Don't truncate the random seed file if it already exists; if
544 * something goes wrong half way through writing it, it would
545 * be better to leave the old data there than to leave it empty.
546 */
547 fd = open(fname, O_CREAT | O_WRONLY, 0600);
548 if (fd < 0) {
549 char dir[FILENAME_MAX];
550
551 make_filename(dir, INDEX_DIR, NULL);
552 mkdir(dir, 0700);
553 fd = open(fname, O_CREAT | O_WRONLY, 0600);
554 }
555
556 while (len > 0) {
557 int ret = write(fd, data, len);
558 if (ret <= 0) break;
559 len -= ret;
560 data = (char *)data + len;
561 }
562
563 close(fd);
564 }
565
566 void cleanup_all(void)
567 {
568 }