Various error-handling fixes, mostly in Unix PuTTY but one (failure
[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)
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 /*
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 */
136
137 void *open_settings_w(const char *sessionname, char **errmsg)
138 {
139 char filename[FILENAME_MAX];
140 FILE *fp;
141
142 *errmsg = NULL;
143
144 /*
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.
150 */
151 make_filename(filename, INDEX_DIR, sessionname);
152 mkdir(filename, 0700);
153 make_filename(filename, INDEX_SESSIONDIR, sessionname);
154 mkdir(filename, 0700);
155
156 make_filename(filename, INDEX_SESSION, sessionname);
157 fp = fopen(filename, "w");
158 if (!fp) {
159 *errmsg = dupprintf("Unable to create %s: %s",
160 filename, strerror(errno));
161 return NULL; /* can't open */
162 }
163 return fp;
164 }
165
166 void write_setting_s(void *handle, const char *key, const char *value)
167 {
168 FILE *fp = (FILE *)handle;
169 fprintf(fp, "%s=%s\n", key, value);
170 }
171
172 void write_setting_i(void *handle, const char *key, int value)
173 {
174 FILE *fp = (FILE *)handle;
175 fprintf(fp, "%s=%d\n", key, value);
176 }
177
178 void close_settings_w(void *handle)
179 {
180 FILE *fp = (FILE *)handle;
181 fclose(fp);
182 }
183
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
193 struct keyval {
194 const char *key;
195 const char *value;
196 };
197
198 static tree234 *xrmtree = NULL;
199
200 int keycmp(void *av, void *bv)
201 {
202 struct keyval *a = (struct keyval *)av;
203 struct keyval *b = (struct keyval *)bv;
204 return strcmp(a->key, b->key);
205 }
206
207 void provide_xrm_string(char *string)
208 {
209 char *p, *q, *key;
210 struct keyval *xrms, *ret;
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--;
221 xrms = snew(struct keyval);
222 key = snewn(q-p, char);
223 memcpy(key, p, q-p);
224 key[q-p-1] = '\0';
225 xrms->key = key;
226 while (*q && isspace((unsigned char)*q))
227 q++;
228 xrms->value = dupstr(q);
229
230 if (!xrmtree)
231 xrmtree = newtree234(keycmp);
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
241 const char *get_setting(const char *key)
242 {
243 struct keyval tmp, *ret;
244 tmp.key = key;
245 if (xrmtree) {
246 ret = find234(xrmtree, &tmp, NULL);
247 if (ret)
248 return ret->value;
249 }
250 return x_get_default(key);
251 }
252
253 void *open_settings_r(const char *sessionname)
254 {
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;
287 }
288
289 char *read_setting_s(void *handle, const char *key, char *buffer, int buflen)
290 {
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
303 if (!val)
304 return NULL;
305 else {
306 strncpy(buffer, val, buflen);
307 buffer[buflen-1] = '\0';
308 return buffer;
309 }
310 }
311
312 int read_setting_i(void *handle, const char *key, int defvalue)
313 {
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
326 if (!val)
327 return defvalue;
328 else
329 return atoi(val);
330 }
331
332 int read_setting_fontspec(void *handle, const char *name, FontSpec *result)
333 {
334 return !!read_setting_s(handle, name, result->name, sizeof(result->name));
335 }
336 int 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
341 void write_setting_fontspec(void *handle, const char *name, FontSpec result)
342 {
343 write_setting_s(handle, name, result.name);
344 }
345 void write_setting_filename(void *handle, const char *name, Filename result)
346 {
347 write_setting_s(handle, name, result.path);
348 }
349
350 void close_settings_r(void *handle)
351 {
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);
366 }
367
368 void del_settings(const char *sessionname)
369 {
370 char filename[FILENAME_MAX];
371 make_filename(filename, INDEX_SESSION, sessionname);
372 unlink(filename);
373 }
374
375 void *enum_settings_start(void)
376 {
377 DIR *dp;
378 char filename[FILENAME_MAX];
379
380 make_filename(filename, INDEX_SESSIONDIR, NULL);
381 dp = opendir(filename);
382
383 return dp;
384 }
385
386 char *enum_settings_next(void *handle, char *buffer, int buflen)
387 {
388 DIR *dp = (DIR *)handle;
389 struct dirent *de;
390 struct stat st;
391 char fullpath[FILENAME_MAX];
392 int len;
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;
416 }
417
418 void enum_settings_finish(void *handle)
419 {
420 DIR *dp = (DIR *)handle;
421 closedir(dp);
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 */
433 int verify_host_key(const char *hostname, int port,
434 const char *keytype, const char *key)
435 {
436 FILE *fp;
437 char filename[FILENAME_MAX];
438 char *line;
439 int ret;
440
441 make_filename(filename, INDEX_HOSTKEYS, NULL);
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;
498 }
499
500 void store_host_key(const char *hostname, int port,
501 const char *keytype, const char *key)
502 {
503 FILE *fp;
504 int fd;
505 char filename[FILENAME_MAX];
506
507 make_filename(filename, INDEX_HOSTKEYS, NULL);
508 fd = open(filename, O_CREAT | O_APPEND | O_RDWR, 0600);
509 if (fd < 0) {
510 char dir[FILENAME_MAX];
511
512 make_filename(dir, INDEX_DIR, NULL);
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);
523 }
524
525 void read_random_seed(noise_consumer_t consumer)
526 {
527 int fd;
528 char fname[FILENAME_MAX];
529
530 make_filename(fname, INDEX_RANDSEED, NULL);
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 }
539 }
540
541 void write_random_seed(void *data, int len)
542 {
543 int fd;
544 char fname[FILENAME_MAX];
545
546 make_filename(fname, INDEX_RANDSEED, NULL);
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);
553 if (fd < 0) {
554 char dir[FILENAME_MAX];
555
556 make_filename(dir, INDEX_DIR, NULL);
557 mkdir(dir, 0700);
558 fd = open(fname, O_CREAT | O_WRONLY, 0600);
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);
569 }
570
571 void cleanup_all(void)
572 {
573 }