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