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