Various error-handling fixes, mostly in Unix PuTTY but one (failure
[u/mdw/putty] / unix / uxstore.c
CommitLineData
1709795f 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>
3f935d5b 8#include <string.h>
8dacc30e 9#include <assert.h>
3f935d5b 10#include <errno.h>
0ac15bdc 11#include <ctype.h>
c5e438ec 12#include <unistd.h>
13#include <fcntl.h>
8dacc30e 14#include <dirent.h>
c5e438ec 15#include <sys/stat.h>
16#include <sys/types.h>
1709795f 17#include "putty.h"
18#include "storage.h"
0ac15bdc 19#include "tree234.h"
1709795f 20
8dacc30e 21enum {
22 INDEX_DIR, INDEX_HOSTKEYS, INDEX_RANDSEED,
23 INDEX_SESSIONDIR, INDEX_SESSION,
24};
25
26static const char hex[16] = "0123456789ABCDEF";
27
28static char *mungestr(const char *in)
29{
30 char *out, *ret;
31
32 if (!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
60static 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
83static 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 */
111static 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
faec60ed 130/*
131 * For the moment, the only existing Unix utility is pterm and that
132 * has no GUI configuration at all, so our write routines need do
133 * nothing. Eventually I suppose these will read and write an rc
134 * file somewhere or other.
135 */
1709795f 136
3f935d5b 137void *open_settings_w(const char *sessionname, char **errmsg)
1709795f 138{
8dacc30e 139 char filename[FILENAME_MAX];
140 FILE *fp;
141
3f935d5b 142 *errmsg = NULL;
143
8dacc30e 144 /*
3f935d5b 145 * Start by making sure the .putty directory and its sessions
146 * subdir actually exist. Ignore error returns from mkdir since
147 * they're perfectly likely to be `already exists', and any
148 * other error will trip us up later on so there's no real need
149 * to catch it now.
8dacc30e 150 */
3f935d5b 151 make_filename(filename, INDEX_DIR, sessionname);
152 mkdir(filename, 0700);
8dacc30e 153 make_filename(filename, INDEX_SESSIONDIR, sessionname);
154 mkdir(filename, 0700);
155
156 make_filename(filename, INDEX_SESSION, sessionname);
157 fp = fopen(filename, "w");
3f935d5b 158 if (!fp) {
159 *errmsg = dupprintf("Unable to create %s: %s",
160 filename, strerror(errno));
161 return NULL; /* can't open */
162 }
8dacc30e 163 return fp;
1709795f 164}
165
c85623f9 166void write_setting_s(void *handle, const char *key, const char *value)
1709795f 167{
8dacc30e 168 FILE *fp = (FILE *)handle;
169 fprintf(fp, "%s=%s\n", key, value);
1709795f 170}
171
c85623f9 172void write_setting_i(void *handle, const char *key, int value)
1709795f 173{
8dacc30e 174 FILE *fp = (FILE *)handle;
175 fprintf(fp, "%s=%d\n", key, value);
1709795f 176}
177
178void close_settings_w(void *handle)
179{
8dacc30e 180 FILE *fp = (FILE *)handle;
181 fclose(fp);
1709795f 182}
183
faec60ed 184/*
185 * Reading settings, for the moment, is done by retrieving X
186 * resources from the X display. When we introduce disk files, I
187 * think what will happen is that the X resources will override
188 * PuTTY's inbuilt defaults, but that the disk files will then
189 * override those. This isn't optimal, but it's the best I can
190 * immediately work out.
191 */
192
8dacc30e 193struct keyval {
c85623f9 194 const char *key;
195 const char *value;
0ac15bdc 196};
197
198static tree234 *xrmtree = NULL;
199
8dacc30e 200int keycmp(void *av, void *bv)
0ac15bdc 201{
8dacc30e 202 struct keyval *a = (struct keyval *)av;
203 struct keyval *b = (struct keyval *)bv;
0ac15bdc 204 return strcmp(a->key, b->key);
205}
206
207void provide_xrm_string(char *string)
208{
c85623f9 209 char *p, *q, *key;
8dacc30e 210 struct keyval *xrms, *ret;
0ac15bdc 211
212 p = q = strchr(string, ':');
213 if (!q) {
214 fprintf(stderr, "pterm: expected a colon in resource string"
215 " \"%s\"\n", string);
216 return;
217 }
218 q++;
219 while (p > string && p[-1] != '.' && p[-1] != '*')
220 p--;
8dacc30e 221 xrms = snew(struct keyval);
3d88e64d 222 key = snewn(q-p, char);
c85623f9 223 memcpy(key, p, q-p);
224 key[q-p-1] = '\0';
225 xrms->key = key;
e93ed432 226 while (*q && isspace((unsigned char)*q))
0ac15bdc 227 q++;
228 xrms->value = dupstr(q);
229
230 if (!xrmtree)
8dacc30e 231 xrmtree = newtree234(keycmp);
0ac15bdc 232
233 ret = add234(xrmtree, xrms);
234 if (ret) {
235 /* Override an existing string. */
236 del234(xrmtree, ret);
237 add234(xrmtree, xrms);
238 }
239}
240
c85623f9 241const char *get_setting(const char *key)
0ac15bdc 242{
8dacc30e 243 struct keyval tmp, *ret;
0ac15bdc 244 tmp.key = key;
245 if (xrmtree) {
246 ret = find234(xrmtree, &tmp, NULL);
247 if (ret)
248 return ret->value;
249 }
c5e438ec 250 return x_get_default(key);
0ac15bdc 251}
252
c85623f9 253void *open_settings_r(const char *sessionname)
1709795f 254{
8dacc30e 255 char filename[FILENAME_MAX];
256 FILE *fp;
257 char *line;
258 tree234 *ret;
259
260 make_filename(filename, INDEX_SESSION, sessionname);
261 fp = fopen(filename, "r");
262 if (!fp)
263 return NULL; /* can't open */
264
265 ret = newtree234(keycmp);
266
267 while ( (line = fgetline(fp)) ) {
268 char *value = strchr(line, '=');
269 struct keyval *kv;
270
271 if (!value)
272 continue;
273 *value++ = '\0';
274 value[strcspn(value, "\r\n")] = '\0'; /* trim trailing NL */
275
276 kv = snew(struct keyval);
277 kv->key = dupstr(line);
278 kv->value = dupstr(value);
279 add234(ret, kv);
280
281 sfree(line);
282 }
283
284 fclose(fp);
285
286 return ret;
1709795f 287}
288
c85623f9 289char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
1709795f 290{
8dacc30e 291 tree234 *tree = (tree234 *)handle;
292 const char *val;
293 struct keyval tmp, *kv;
294
295 tmp.key = key;
296 if (tree != NULL &&
297 (kv = find234(tree, &tmp, NULL)) != NULL) {
298 val = kv->value;
299 assert(val != NULL);
300 } else
301 val = get_setting(key);
302
faec60ed 303 if (!val)
304 return NULL;
305 else {
306 strncpy(buffer, val, buflen);
307 buffer[buflen-1] = '\0';
308 return buffer;
309 }
1709795f 310}
311
c85623f9 312int read_setting_i(void *handle, const char *key, int defvalue)
1709795f 313{
8dacc30e 314 tree234 *tree = (tree234 *)handle;
315 const char *val;
316 struct keyval tmp, *kv;
317
318 tmp.key = key;
319 if (tree != NULL &&
320 (kv = find234(tree, &tmp, NULL)) != NULL) {
321 val = kv->value;
322 assert(val != NULL);
323 } else
324 val = get_setting(key);
325
faec60ed 326 if (!val)
327 return defvalue;
328 else
329 return atoi(val);
1709795f 330}
331
9a30e26b 332int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
333{
334 return !!read_setting_s(handle, name, result->name, sizeof(result->name));
335}
336int read_setting_filename(void *handle, const char *name, Filename *result)
337{
338 return !!read_setting_s(handle, name, result->path, sizeof(result->path));
339}
340
341void write_setting_fontspec(void *handle, const char *name, FontSpec result)
342{
343 write_setting_s(handle, name, result.name);
344}
345void write_setting_filename(void *handle, const char *name, Filename result)
346{
347 write_setting_s(handle, name, result.path);
348}
349
1709795f 350void close_settings_r(void *handle)
351{
8dacc30e 352 tree234 *tree = (tree234 *)handle;
353 struct keyval *kv;
354
355 if (!tree)
356 return;
357
358 while ( (kv = index234(tree, 0)) != NULL) {
359 del234(tree, kv);
360 sfree((char *)kv->key);
361 sfree((char *)kv->value);
362 sfree(kv);
363 }
364
365 freetree234(tree);
1709795f 366}
367
c85623f9 368void del_settings(const char *sessionname)
1709795f 369{
8dacc30e 370 char filename[FILENAME_MAX];
371 make_filename(filename, INDEX_SESSION, sessionname);
372 unlink(filename);
1709795f 373}
374
375void *enum_settings_start(void)
376{
8dacc30e 377 DIR *dp;
378 char filename[FILENAME_MAX];
1709795f 379
8dacc30e 380 make_filename(filename, INDEX_SESSIONDIR, NULL);
381 dp = opendir(filename);
1709795f 382
8dacc30e 383 return dp;
1709795f 384}
385
8dacc30e 386char *enum_settings_next(void *handle, char *buffer, int buflen)
c5e438ec 387{
8dacc30e 388 DIR *dp = (DIR *)handle;
389 struct dirent *de;
390 struct stat st;
391 char fullpath[FILENAME_MAX];
c5e438ec 392 int len;
8dacc30e 393 char *unmunged;
394
395 make_filename(fullpath, INDEX_SESSIONDIR, NULL);
396 len = strlen(fullpath);
397
398 while ( (de = readdir(dp)) != NULL ) {
399 if (len < FILENAME_MAX) {
400 fullpath[len] = '/';
401 strncpy(fullpath+len+1, de->d_name, FILENAME_MAX-(len+1));
402 fullpath[FILENAME_MAX-1] = '\0';
403 }
404
405 if (stat(fullpath, &st) < 0 || !S_ISREG(st.st_mode))
406 continue; /* try another one */
407
408 unmunged = unmungestr(de->d_name);
409 strncpy(buffer, unmunged, buflen);
410 buffer[buflen-1] = '\0';
411 sfree(unmunged);
412 return buffer;
413 }
414
415 return NULL;
c5e438ec 416}
417
8dacc30e 418void enum_settings_finish(void *handle)
c5e438ec 419{
8dacc30e 420 DIR *dp = (DIR *)handle;
421 closedir(dp);
c5e438ec 422}
423
424/*
425 * Lines in the host keys file are of the form
426 *
427 * type@port:hostname keydata
428 *
429 * e.g.
430 *
431 * rsa@22:foovax.example.org 0x23,0x293487364395345345....2343
432 */
c85623f9 433int verify_host_key(const char *hostname, int port,
434 const char *keytype, const char *key)
1709795f 435{
c5e438ec 436 FILE *fp;
437 char filename[FILENAME_MAX];
438 char *line;
439 int ret;
440
8dacc30e 441 make_filename(filename, INDEX_HOSTKEYS, NULL);
c5e438ec 442 fp = fopen(filename, "r");
443 if (!fp)
444 return 1; /* key does not exist */
445
446 ret = 1;
447 while ( (line = fgetline(fp)) ) {
448 int i;
449 char *p = line;
450 char porttext[20];
451
452 line[strcspn(line, "\n")] = '\0'; /* strip trailing newline */
453
454 i = strlen(keytype);
455 if (strncmp(p, keytype, i))
456 goto done;
457 p += i;
458
459 if (*p != '@')
460 goto done;
461 p++;
462
463 sprintf(porttext, "%d", port);
464 i = strlen(porttext);
465 if (strncmp(p, porttext, i))
466 goto done;
467 p += i;
468
469 if (*p != ':')
470 goto done;
471 p++;
472
473 i = strlen(hostname);
474 if (strncmp(p, hostname, i))
475 goto done;
476 p += i;
477
478 if (*p != ' ')
479 goto done;
480 p++;
481
482 /*
483 * Found the key. Now just work out whether it's the right
484 * one or not.
485 */
486 if (!strcmp(p, key))
487 ret = 0; /* key matched OK */
488 else
489 ret = 2; /* key mismatch */
490
491 done:
492 sfree(line);
493 if (ret != 1)
494 break;
495 }
496
497 return ret;
1709795f 498}
499
c85623f9 500void store_host_key(const char *hostname, int port,
501 const char *keytype, const char *key)
1709795f 502{
c5e438ec 503 FILE *fp;
504 int fd;
505 char filename[FILENAME_MAX];
506
8dacc30e 507 make_filename(filename, INDEX_HOSTKEYS, NULL);
c5e438ec 508 fd = open(filename, O_CREAT | O_APPEND | O_RDWR, 0600);
509 if (fd < 0) {
510 char dir[FILENAME_MAX];
511
8dacc30e 512 make_filename(dir, INDEX_DIR, NULL);
c5e438ec 513 mkdir(dir, 0700);
514 fd = open(filename, O_CREAT | O_APPEND | O_RDWR, 0600);
515 }
516 if (fd < 0) {
517 perror(filename);
518 exit(1);
519 }
520 fp = fdopen(fd, "a");
521 fprintf(fp, "%s@%d:%s %s\n", keytype, port, hostname, key);
522 fclose(fp);
1709795f 523}
524
525void read_random_seed(noise_consumer_t consumer)
526{
d9c40fd6 527 int fd;
528 char fname[FILENAME_MAX];
529
8dacc30e 530 make_filename(fname, INDEX_RANDSEED, NULL);
d9c40fd6 531 fd = open(fname, O_RDONLY);
532 if (fd) {
533 char buf[512];
534 int ret;
535 while ( (ret = read(fd, buf, sizeof(buf))) > 0)
536 consumer(buf, ret);
537 close(fd);
538 }
1709795f 539}
540
541void write_random_seed(void *data, int len)
542{
d9c40fd6 543 int fd;
544 char fname[FILENAME_MAX];
545
8dacc30e 546 make_filename(fname, INDEX_RANDSEED, NULL);
e3ac3c05 547 /*
548 * Don't truncate the random seed file if it already exists; if
549 * something goes wrong half way through writing it, it would
550 * be better to leave the old data there than to leave it empty.
551 */
552 fd = open(fname, O_CREAT | O_WRONLY, 0600);
d9c40fd6 553 if (fd < 0) {
554 char dir[FILENAME_MAX];
555
8dacc30e 556 make_filename(dir, INDEX_DIR, NULL);
d9c40fd6 557 mkdir(dir, 0700);
e3ac3c05 558 fd = open(fname, O_CREAT | O_WRONLY, 0600);
d9c40fd6 559 }
560
561 while (len > 0) {
562 int ret = write(fd, data, len);
563 if (ret <= 0) break;
564 len -= ret;
565 data = (char *)data + len;
566 }
567
568 close(fd);
1709795f 569}
570
571void cleanup_all(void)
572{
573}