2 * Copyright (c) 2008, Dave Korn.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * A copy of the GNU General Public License can be found at
12 * This implements the ExtraKeysSetting class, which persists and reads
13 * in (and saves) extra public DSA signing keys for the verification process.
14 * It stores them all in a contiguous memory buffer. Each is one line of
15 * ASCII text terminated by LF. THERE IS NO NUL-TERMINATION HERE, TAKE CARE!
16 * The buffer is sized to the exact size of the content including the terminating
17 * LF of the last entry. There is no zero after it. After reading the file,
18 * any partial last line is truncated.
20 * Written by Dave Korn <dave.korn.cygwin@gmail.com>
26 #include "UserSettings.h"
27 #include "io_stream.h"
28 #include "KeysSetting.h"
30 ExtraKeysSetting
*ExtraKeysSetting::global
;
32 ExtraKeysSetting::ExtraKeysSetting ():
33 keybuffer (NULL
), bufsize (0), numkeys (0)
36 const char *p
= UserSettings::instance().get ("extrakeys");
39 bufsize
= strlen (p
) + 1; // Include final NUL.
40 keybuffer
= strdup (p
);
41 // Replace final NUL by LF.
42 keybuffer
[bufsize
- 1] = 0x0a;
43 // Calling count_keys gets the count but also sizes the buffer
44 // correctly, discarding any trailing non-LF-terminated data.
45 bufsize
= count_keys ();
49 ExtraKeysSetting::~ExtraKeysSetting ()
53 // Replace final LF by NUL.
54 keybuffer
[bufsize
- 1] = '\0';
55 UserSettings::instance().set ("extrakeys", keybuffer
);
60 ExtraKeysSetting::flush (void)
70 ExtraKeysSetting::realloc (size_t newbufsize
)
72 char *newbuf
= new char[newbufsize
];
75 memcpy (newbuf
, keybuffer
, newbufsize
< bufsize
? newbufsize
: bufsize
);
83 ExtraKeysSetting::count_keys (void)
85 size_t offs
= 0, size
= 0;
87 while (offs
< bufsize
)
88 if (keybuffer
[offs
++] == 0x0a)
97 ExtraKeysSetting::num_keys (void)
103 ExtraKeysSetting::get_key (size_t num
, size_t *size
)
105 if (!numkeys
|| (num
>= numkeys
))
108 const char *ptr
= keybuffer
;
110 while (*ptr
++ != 0x0a);
112 // Count its size if requested.
115 const char *ptr2
= ptr
;
127 ExtraKeysSetting::add_unique_key (const char *key
)
129 size_t osize
= bufsize
;
130 realloc (bufsize
+ strlen (key
) + 1);
131 strcpy (keybuffer
+ osize
, key
);
132 keybuffer
[bufsize
- 1] = 0x0a;
137 ExtraKeysSetting::add_key (const char *key
)
139 /* Only add key if we don't already have it. */
140 const char *ptr
= keybuffer
;
141 size_t remain
= bufsize
;
142 size_t keylen
= strlen (key
);
144 while (remain
>= keylen
)
146 if (memcmp (ptr
, key
, keylen
) == 0)
153 add_unique_key (key
);