2 ntdbrestore -- construct a ntdb from tdbdump output.
3 Copyright (C) Volker Lendecke 2010
4 Copyright (C) Simon McVittie 2005
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #ifdef HAVE_LIBREPLACE
25 #include <system/filesys.h>
27 #include <sys/types.h>
34 static int read_linehead(FILE *f)
49 for (i=0; i<sizeof(prefix); i++) {
59 if (i == sizeof(prefix)) {
64 if (sscanf(prefix, "%d) = ", &num_bytes) != 1) {
70 static int read_hex(void) {
74 fprintf(stderr, "Unexpected EOF in data\n");
76 } else if (c == '"') {
77 fprintf(stderr, "Unexpected \\\" sequence\n");
79 } else if ('0' <= c && c <= '9') {
81 } else if ('A' <= c && c <= 'F') {
83 } else if ('a' <= c && c <= 'f') {
86 fprintf(stderr, "Invalid hex: %c\n", c);
91 static int read_data(FILE *f, NTDB_DATA *d, size_t size) {
95 d->dptr = (unsigned char *)malloc(size);
96 if (d->dptr == NULL) {
101 for (i=0; i<size; i++) {
104 fprintf(stderr, "Unexpected EOF in data\n");
106 } else if (c == '"') {
108 } else if (c == '\\') {
114 assert(high == (high & 0xf0));
119 assert(low == (low & 0x0f));
120 d->dptr[i] = (low|high);
128 static int swallow(FILE *f, const char *s, int *eof)
132 if (fgets(line, sizeof(line), f) == NULL) {
138 if (strcmp(line, s) != 0) {
144 static bool read_rec(FILE *f, struct ntdb_context *ntdb, int *eof)
154 if (swallow(f, "{\n", eof) == -1) {
157 length = read_linehead(f);
161 if (read_data(f, &key, length) == -1) {
164 if (swallow(f, "\"\n", NULL) == -1) {
167 length = read_linehead(f);
171 if (read_data(f, &data, length) == -1) {
174 if ((swallow(f, "\"\n", NULL) == -1)
175 || (swallow(f, "}\n", NULL) == -1)) {
178 e = ntdb_store(ntdb, key, data, NTDB_INSERT);
179 if (e != NTDB_SUCCESS) {
180 fprintf(stderr, "NTDB error: %s\n", ntdb_errorstr(e));
191 static int restore_ntdb(const char *fname)
193 struct ntdb_context *ntdb;
195 ntdb = ntdb_open(fname, 0, O_RDWR|O_CREAT|O_EXCL, 0666, NULL);
198 fprintf(stderr, "Failed to open %s\n", fname);
204 if (!read_rec(stdin, ntdb, &eof)) {
211 if (ntdb_close(ntdb)) {
212 fprintf(stderr, "Error closing ntdb\n");
215 fprintf(stderr, "EOF\n");
219 int main(int argc, char *argv[])
224 printf("Usage: %s dbname < tdbdump_output\n", argv[0]);
230 return restore_ntdb(fname);