Idiot me _twice_! The new store_host_key() was failing in the
[sgt/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_HOSTKEYS_TMP, 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_HOSTKEYS_TMP ? "/.putty/sshhostkeys.tmp" :
102 index == INDEX_RANDSEED ? "/.putty/randomseed" :
103 "/.putty/ERROR", FILENAME_MAX - len);
104 }
105 filename[FILENAME_MAX-1] = '\0';
106 }
107
108 /*
109 * Read an entire line of text from a file. Return a buffer
110 * malloced to be as big as necessary (caller must free).
111 */
112 static char *fgetline(FILE *fp)
113 {
114 char *ret = snewn(512, char);
115 int size = 512, len = 0;
116 while (fgets(ret + len, size - len, fp)) {
117 len += strlen(ret + len);
118 if (ret[len-1] == '\n')
119 break; /* got a newline, we're done */
120 size = len + 512;
121 ret = sresize(ret, size, char);
122 }
123 if (len == 0) { /* first fgets returned NULL */
124 sfree(ret);
125 return NULL;
126 }
127 ret[len] = '\0';
128 return ret;
129 }
130
131 void *open_settings_w(const char *sessionname, char **errmsg)
132 {
133 char filename[FILENAME_MAX];
134 FILE *fp;
135
136 *errmsg = NULL;
137
138 /*
139 * Start by making sure the .putty directory and its sessions
140 * subdir actually exist. Ignore error returns from mkdir since
141 * they're perfectly likely to be `already exists', and any
142 * other error will trip us up later on so there's no real need
143 * to catch it now.
144 */
145 make_filename(filename, INDEX_DIR, sessionname);
146 mkdir(filename, 0700);
147 make_filename(filename, INDEX_SESSIONDIR, sessionname);
148 mkdir(filename, 0700);
149
150 make_filename(filename, INDEX_SESSION, sessionname);
151 fp = fopen(filename, "w");
152 if (!fp) {
153 *errmsg = dupprintf("Unable to create %s: %s",
154 filename, strerror(errno));
155 return NULL; /* can't open */
156 }
157 return fp;
158 }
159
160 void write_setting_s(void *handle, const char *key, const char *value)
161 {
162 FILE *fp = (FILE *)handle;
163 fprintf(fp, "%s=%s\n", key, value);
164 }
165
166 void write_setting_i(void *handle, const char *key, int value)
167 {
168 FILE *fp = (FILE *)handle;
169 fprintf(fp, "%s=%d\n", key, value);
170 }
171
172 void close_settings_w(void *handle)
173 {
174 FILE *fp = (FILE *)handle;
175 fclose(fp);
176 }
177
178 /*
179 * Reading settings, for the moment, is done by retrieving X
180 * resources from the X display. When we introduce disk files, I
181 * think what will happen is that the X resources will override
182 * PuTTY's inbuilt defaults, but that the disk files will then
183 * override those. This isn't optimal, but it's the best I can
184 * immediately work out.
185 * FIXME: the above comment is a bit out of date. Did it happen?
186 */
187
188 struct keyval {
189 const char *key;
190 const char *value;
191 };
192
193 static tree234 *xrmtree = NULL;
194
195 int keycmp(void *av, void *bv)
196 {
197 struct keyval *a = (struct keyval *)av;
198 struct keyval *b = (struct keyval *)bv;
199 return strcmp(a->key, b->key);
200 }
201
202 void provide_xrm_string(char *string)
203 {
204 char *p, *q, *key;
205 struct keyval *xrms, *ret;
206
207 p = q = strchr(string, ':');
208 if (!q) {
209 fprintf(stderr, "pterm: expected a colon in resource string"
210 " \"%s\"\n", string);
211 return;
212 }
213 q++;
214 while (p > string && p[-1] != '.' && p[-1] != '*')
215 p--;
216 xrms = snew(struct keyval);
217 key = snewn(q-p, char);
218 memcpy(key, p, q-p);
219 key[q-p-1] = '\0';
220 xrms->key = key;
221 while (*q && isspace((unsigned char)*q))
222 q++;
223 xrms->value = dupstr(q);
224
225 if (!xrmtree)
226 xrmtree = newtree234(keycmp);
227
228 ret = add234(xrmtree, xrms);
229 if (ret) {
230 /* Override an existing string. */
231 del234(xrmtree, ret);
232 add234(xrmtree, xrms);
233 }
234 }
235
236 const char *get_setting(const char *key)
237 {
238 struct keyval tmp, *ret;
239 tmp.key = key;
240 if (xrmtree) {
241 ret = find234(xrmtree, &tmp, NULL);
242 if (ret)
243 return ret->value;
244 }
245 return x_get_default(key);
246 }
247
248 void *open_settings_r(const char *sessionname)
249 {
250 char filename[FILENAME_MAX];
251 FILE *fp;
252 char *line;
253 tree234 *ret;
254
255 make_filename(filename, INDEX_SESSION, sessionname);
256 fp = fopen(filename, "r");
257 if (!fp)
258 return NULL; /* can't open */
259
260 ret = newtree234(keycmp);
261
262 while ( (line = fgetline(fp)) ) {
263 char *value = strchr(line, '=');
264 struct keyval *kv;
265
266 if (!value)
267 continue;
268 *value++ = '\0';
269 value[strcspn(value, "\r\n")] = '\0'; /* trim trailing NL */
270
271 kv = snew(struct keyval);
272 kv->key = dupstr(line);
273 kv->value = dupstr(value);
274 add234(ret, kv);
275
276 sfree(line);
277 }
278
279 fclose(fp);
280
281 return ret;
282 }
283
284 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
285 {
286 tree234 *tree = (tree234 *)handle;
287 const char *val;
288 struct keyval tmp, *kv;
289
290 tmp.key = key;
291 if (tree != NULL &&
292 (kv = find234(tree, &tmp, NULL)) != NULL) {
293 val = kv->value;
294 assert(val != NULL);
295 } else
296 val = get_setting(key);
297
298 if (!val)
299 return NULL;
300 else {
301 strncpy(buffer, val, buflen);
302 buffer[buflen-1] = '\0';
303 return buffer;
304 }
305 }
306
307 int read_setting_i(void *handle, const char *key, int defvalue)
308 {
309 tree234 *tree = (tree234 *)handle;
310 const char *val;
311 struct keyval tmp, *kv;
312
313 tmp.key = key;
314 if (tree != NULL &&
315 (kv = find234(tree, &tmp, NULL)) != NULL) {
316 val = kv->value;
317 assert(val != NULL);
318 } else
319 val = get_setting(key);
320
321 if (!val)
322 return defvalue;
323 else
324 return atoi(val);
325 }
326
327 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
328 {
329 return !!read_setting_s(handle, name, result->name, sizeof(result->name));
330 }
331 int read_setting_filename(void *handle, const char *name, Filename *result)
332 {
333 return !!read_setting_s(handle, name, result->path, sizeof(result->path));
334 }
335
336 void write_setting_fontspec(void *handle, const char *name, FontSpec result)
337 {
338 write_setting_s(handle, name, result.name);
339 }
340 void write_setting_filename(void *handle, const char *name, Filename result)
341 {
342 write_setting_s(handle, name, result.path);
343 }
344
345 void close_settings_r(void *handle)
346 {
347 tree234 *tree = (tree234 *)handle;
348 struct keyval *kv;
349
350 if (!tree)
351 return;
352
353 while ( (kv = index234(tree, 0)) != NULL) {
354 del234(tree, kv);
355 sfree((char *)kv->key);
356 sfree((char *)kv->value);
357 sfree(kv);
358 }
359
360 freetree234(tree);
361 }
362
363 void del_settings(const char *sessionname)
364 {
365 char filename[FILENAME_MAX];
366 make_filename(filename, INDEX_SESSION, sessionname);
367 unlink(filename);
368 }
369
370 void *enum_settings_start(void)
371 {
372 DIR *dp;
373 char filename[FILENAME_MAX];
374
375 make_filename(filename, INDEX_SESSIONDIR, NULL);
376 dp = opendir(filename);
377
378 return dp;
379 }
380
381 char *enum_settings_next(void *handle, char *buffer, int buflen)
382 {
383 DIR *dp = (DIR *)handle;
384 struct dirent *de;
385 struct stat st;
386 char fullpath[FILENAME_MAX];
387 int len;
388 char *unmunged;
389
390 make_filename(fullpath, INDEX_SESSIONDIR, NULL);
391 len = strlen(fullpath);
392
393 while ( (de = readdir(dp)) != NULL ) {
394 if (len < FILENAME_MAX) {
395 fullpath[len] = '/';
396 strncpy(fullpath+len+1, de->d_name, FILENAME_MAX-(len+1));
397 fullpath[FILENAME_MAX-1] = '\0';
398 }
399
400 if (stat(fullpath, &st) < 0 || !S_ISREG(st.st_mode))
401 continue; /* try another one */
402
403 unmunged = unmungestr(de->d_name);
404 strncpy(buffer, unmunged, buflen);
405 buffer[buflen-1] = '\0';
406 sfree(unmunged);
407 return buffer;
408 }
409
410 return NULL;
411 }
412
413 void enum_settings_finish(void *handle)
414 {
415 DIR *dp = (DIR *)handle;
416 closedir(dp);
417 }
418
419 /*
420 * Lines in the host keys file are of the form
421 *
422 * type@port:hostname keydata
423 *
424 * e.g.
425 *
426 * rsa@22:foovax.example.org 0x23,0x293487364395345345....2343
427 */
428 int verify_host_key(const char *hostname, int port,
429 const char *keytype, const char *key)
430 {
431 FILE *fp;
432 char filename[FILENAME_MAX];
433 char *line;
434 int ret;
435
436 make_filename(filename, INDEX_HOSTKEYS, NULL);
437 fp = fopen(filename, "r");
438 if (!fp)
439 return 1; /* key does not exist */
440
441 ret = 1;
442 while ( (line = fgetline(fp)) ) {
443 int i;
444 char *p = line;
445 char porttext[20];
446
447 line[strcspn(line, "\n")] = '\0'; /* strip trailing newline */
448
449 i = strlen(keytype);
450 if (strncmp(p, keytype, i))
451 goto done;
452 p += i;
453
454 if (*p != '@')
455 goto done;
456 p++;
457
458 sprintf(porttext, "%d", port);
459 i = strlen(porttext);
460 if (strncmp(p, porttext, i))
461 goto done;
462 p += i;
463
464 if (*p != ':')
465 goto done;
466 p++;
467
468 i = strlen(hostname);
469 if (strncmp(p, hostname, i))
470 goto done;
471 p += i;
472
473 if (*p != ' ')
474 goto done;
475 p++;
476
477 /*
478 * Found the key. Now just work out whether it's the right
479 * one or not.
480 */
481 if (!strcmp(p, key))
482 ret = 0; /* key matched OK */
483 else
484 ret = 2; /* key mismatch */
485
486 done:
487 sfree(line);
488 if (ret != 1)
489 break;
490 }
491
492 fclose(fp);
493 return ret;
494 }
495
496 void store_host_key(const char *hostname, int port,
497 const char *keytype, const char *key)
498 {
499 FILE *rfp, *wfp;
500 char *newtext, *line;
501 int headerlen;
502 char filename[FILENAME_MAX], tmpfilename[FILENAME_MAX];
503
504 newtext = dupprintf("%s@%d:%s %s\n", keytype, port, hostname, key);
505 headerlen = 1 + strcspn(newtext, " "); /* count the space too */
506
507 /*
508 * Open both the old file and a new file.
509 */
510 make_filename(tmpfilename, INDEX_HOSTKEYS_TMP, NULL);
511 wfp = fopen(tmpfilename, "w");
512 if (!wfp) {
513 char dir[FILENAME_MAX];
514
515 make_filename(dir, INDEX_DIR, NULL);
516 mkdir(dir, 0700);
517 wfp = fopen(tmpfilename, "w");
518 }
519 if (!wfp)
520 return;
521 make_filename(filename, INDEX_HOSTKEYS, NULL);
522 rfp = fopen(filename, "r");
523
524 /*
525 * Copy all lines from the old file to the new one that _don't_
526 * involve the same host key identifier as the one we're adding.
527 */
528 if (rfp) {
529 while ( (line = fgetline(rfp)) ) {
530 if (strncmp(line, newtext, headerlen))
531 fputs(line, wfp);
532 }
533 fclose(rfp);
534 }
535
536 /*
537 * Now add the new line at the end.
538 */
539 fputs(newtext, wfp);
540
541 fclose(wfp);
542
543 rename(tmpfilename, filename);
544
545 sfree(newtext);
546 }
547
548 void read_random_seed(noise_consumer_t consumer)
549 {
550 int fd;
551 char fname[FILENAME_MAX];
552
553 make_filename(fname, INDEX_RANDSEED, NULL);
554 fd = open(fname, O_RDONLY);
555 if (fd) {
556 char buf[512];
557 int ret;
558 while ( (ret = read(fd, buf, sizeof(buf))) > 0)
559 consumer(buf, ret);
560 close(fd);
561 }
562 }
563
564 void write_random_seed(void *data, int len)
565 {
566 int fd;
567 char fname[FILENAME_MAX];
568
569 make_filename(fname, INDEX_RANDSEED, NULL);
570 /*
571 * Don't truncate the random seed file if it already exists; if
572 * something goes wrong half way through writing it, it would
573 * be better to leave the old data there than to leave it empty.
574 */
575 fd = open(fname, O_CREAT | O_WRONLY, 0600);
576 if (fd < 0) {
577 char dir[FILENAME_MAX];
578
579 make_filename(dir, INDEX_DIR, NULL);
580 mkdir(dir, 0700);
581 fd = open(fname, O_CREAT | O_WRONLY, 0600);
582 }
583
584 while (len > 0) {
585 int ret = write(fd, data, len);
586 if (ret <= 0) break;
587 len -= ret;
588 data = (char *)data + len;
589 }
590
591 close(fd);
592 }
593
594 void cleanup_all(void)
595 {
596 }