]> code.citadel.org Git - citadel.git/blob - citadel/utils/ctdldump.c
ctdldump: convert binary to base64 instead of hex
[citadel.git] / citadel / utils / ctdldump.c
1 // Don't run this.  It doesn't work and if you try to run it you will immediately die.
2 //
3 // Copyright (c) 2023 by Art Cancro citadel.org
4 //
5 // This program is open source software.  Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <ctype.h>
11 #include <stdio.h>
12 #include <signal.h>
13 #include <sys/types.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <netdb.h>
17 #include <string.h>
18 #include <pwd.h>
19 #include <errno.h>
20 #include <stdarg.h>
21 #include <limits.h>
22 #include <libcitadel.h>
23 #include <zlib.h>
24 #include <db.h>
25 #include "../server/sysdep.h"
26 #include "../server/citadel_defs.h"
27 #include "../server/server.h"
28 #include "../server/citadel_dirs.h"
29
30
31 // Wrapper for realloc() that crashes and burns if the call fails.
32 void *reallok(void *ptr, size_t size) {
33         void *p = realloc(ptr, size);
34         if (!p) {
35                 fprintf(stderr, "realloc() failed to resize %p to %ld bytes, error: %m\n", ptr, size);
36                 exit(1);
37         }
38         return p;
39 }
40 #define realloc reallok
41
42
43 // convert a binary blob to base64 (non-reentrant!)
44 char *b64out(void *data, size_t len) {
45         static char *outbuf = NULL;
46         static size_t outlen = 0;
47         int i;
48         char ch;
49
50         if ((outbuf == NULL) || (outlen < (len * 2))) {
51                 outbuf = reallok(outbuf, (len * 2));
52                 outlen = len * 2;
53         }
54
55         CtdlEncodeBase64(outbuf, data, len, 0);
56         return(outbuf);
57 }
58
59
60 // Open a database environment
61 DB_ENV *open_dbenv(char *dirname) {
62
63         DB_ENV *dbenv = NULL;
64
65         int ret;
66         int i;
67         u_int32_t flags = 0;
68         int dbversion_major, dbversion_minor, dbversion_patch;
69
70         fprintf(stderr,
71                 "db: open_dbenv() starting\n"
72                 "db:    Linked zlib: %s\n"
73                 "db: Compiled libdb: %s\n"
74                 "db:   Linked libdb: %s\n",
75                 zlibVersion(),
76                 DB_VERSION_STRING,
77                 db_version(&dbversion_major, &dbversion_minor, &dbversion_patch)
78         );
79
80         // Create synthetic integer version numbers and compare them.
81         // Never run with a libdb older than the one with which it was compiled.
82         int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
83         int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
84         if (compiled_db_version > linked_db_version) {
85                 fprintf(stderr, "db: ctdldump is running with a version of libdb older than the one with which it was compiled.\n"
86                         "db: This is an invalid configuration.  ctdldump will now exit to prevent data loss.");
87                 exit(CTDLEXIT_DB);
88         }
89
90         fprintf(stderr, "db: Setting up DB environment\n");
91         ret = db_env_create(&dbenv, 0);
92         if (ret) {
93                 fprintf(stderr, "db: db_env_create: %s\n", db_strerror(ret));
94                 fprintf(stderr, "db: exit code %d\n", ret);
95                 exit(CTDLEXIT_DB);
96         }
97
98         // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
99         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
100         if (ret) {
101                 fprintf(stderr, "db: set_cachesize: %s\n", db_strerror(ret));
102                 dbenv->close(dbenv, 0);
103                 fprintf(stderr, "db: exit code %d\n", ret);
104                 exit(CTDLEXIT_DB);
105         }
106
107         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
108                 fprintf(stderr, "db: set_lk_detect: %s\n", db_strerror(ret));
109                 dbenv->close(dbenv, 0);
110                 fprintf(stderr, "db: exit code %d\n", ret);
111                 exit(CTDLEXIT_DB);
112         }
113
114         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_LOG;
115         fprintf(stderr, "db: dbenv open(dir=%s, flags=%d)\n", dirname, flags);
116         ret = dbenv->open(dbenv, dirname, flags, 0);
117         if (ret) {
118                 fprintf(stderr, "db: dbenv->open: %s\n", db_strerror(ret));
119                 dbenv->close(dbenv, 0);
120                 fprintf(stderr, "db: exit code %d\n", ret);
121                 exit(CTDLEXIT_DB);
122         }
123
124         return(dbenv);
125 }
126
127
128 void close_dbenv(DB_ENV *dbenv) {
129         int ret = dbenv->close(dbenv, 0);
130         if (ret) {
131                 fprintf(stderr, "db: dbenv->close: %s\n", db_strerror(ret));
132         }
133 }
134
135
136 // export function for a message in msgmain
137 void export_msgmain(int which_cdb, DBT *in_key, DBT *in_data) {
138         long in_msgnum;
139
140         memcpy(&in_msgnum, in_key->data, sizeof(in_msgnum));
141
142         // If the msgnum is negative, we are looking at METADATA
143         if (in_msgnum < 0) {
144                 struct MetaData *meta = (struct MetaData *)in_data->data;
145                 printf("msgmeta|%ld|%d|%s|%ld|\n",
146                         meta->meta_msgnum,
147                         meta->meta_refcount,
148                         meta->meta_content_type,
149                         meta->meta_rfc822_length
150                 );
151         }
152
153         // If the msgnum is positive, we are looking at a MESSAGE
154         else if (in_msgnum > 0) {
155                 printf("msgtext|%ld|%s|\n", in_msgnum, b64out(in_data->data, in_data->size));
156         }
157
158         // If the msgnum is 0 it's probably not a valid record.
159 }
160
161
162 // export function for a user record
163 void export_user(int which_cdb, DBT *in_key, DBT *in_data) {
164
165         struct ctdluser *user = (struct ctdluser *)in_data->data;
166
167         printf("user|%d|%d|%s|%u|%d|%ld|%ld|%d|%s|%ld|%ld|%s|%ld|%ld|\n",
168                 user->version,
169                 user->uid,
170                 user->password,
171                 user->flags,
172                 user->axlevel,
173                 user->usernum,
174                 user->lastcall,
175                 user->USuserpurge,
176                 user->fullname,
177                 user->msgnum_bio,
178                 user->msgnum_pic,
179                 b64out(user->emailaddrs, strlen(user->emailaddrs)),
180                 user->msgnum_inboxrules,
181                 user->lastproc_inboxrules
182         );
183 }
184
185
186 // export function for a room record
187 void export_room(int which_cdb, DBT *in_key, DBT *in_data) {
188
189         struct ctdlroom *room = (struct ctdlroom *)in_data->data;
190
191         printf("room|%s|%s|%ld|%ld|%ld|%u|%s|%ld|%d|%ld|%d|%d|%ld|%d|%u|%d|%ld|\n",
192                 room->QRname,
193                 room->QRpasswd,
194                 room->QRroomaide,
195                 room->QRhighest,
196                 room->QRgen,
197                 room->QRflags,
198                 room->QRdirname,
199                 room->msgnum_info,
200                 room->QRfloor,
201                 room->QRmtime,
202                 room->QRep.expire_mode,
203                 room->QRep.expire_value,
204                 room->QRnumber,
205                 room->QRorder,
206                 room->QRflags2,
207                 room->QRdefaultview,
208                 room->msgnum_pic
209         );
210 }
211
212
213 // export function for a floor record
214 void export_floor(int which_cdb, DBT *in_key, DBT *in_data) {
215
216         int floor_num;
217         memcpy(&floor_num, in_key->data, sizeof(int));
218
219         struct floor *floor = (struct floor *)in_data->data;
220
221         printf("floor|%d|%u|%s|%d|%d|%d|\n",
222                 floor_num,
223                 floor->f_flags,
224                 floor->f_name,
225                 floor->f_ref_count,
226                 floor->f_ep.expire_mode,
227                 floor->f_ep.expire_value
228         );
229 }
230
231
232 // export function for a msglist or a fulltext index record
233 // (both are indexed by a long and the data is arrays of longs)
234 void export_msglist(int which_cdb, DBT *in_key, DBT *in_data) {
235         int i;
236         int num_msgs;
237         long msg;
238
239         // records are indexed by a single "long" and contains an array of zero or more "long"s
240         long roomnum;
241         memcpy(&roomnum, in_key->data, sizeof(long));
242
243         printf("msglist|%ld|", roomnum);
244
245         if (in_data->size > 0) {
246                 num_msgs = in_data->size / sizeof(long);
247                 for (i=0; i<num_msgs; ++i) {
248                         memcpy(&msg, (in_data->data + (i * sizeof(long))), sizeof(long));
249                         if (i != 0) {
250                                 printf(",");
251                         }
252                         printf("%ld", msg);
253                 }
254         }
255         printf("|\n");
256 }
257
258
259 // export function for a visit record
260 void export_visit(int which_cdb, DBT *in_key, DBT *in_data) {
261         struct visit *visit = (struct visit *)in_data->data;
262         printf("visit|%ld|%ld|%ld|%ld|%u|%s|%s|%d|\n",
263                 visit->v_roomnum,
264                 visit->v_roomgen,
265                 visit->v_usernum,
266                 visit->v_lastseen,
267                 visit->v_flags,
268                 visit->v_seen,
269                 visit->v_answered,
270                 visit->v_view
271         );
272 }
273
274
275 // export function for a directory record
276 // (This is a secondary index -- should we just regenerate the data after import?)
277 void export_dir(int which_cdb, DBT *in_key, DBT *in_data) {
278         printf("dir|");
279         fwrite(in_key->data, in_key->size, 1, stdout);
280         printf("|%s|\n", (char *)in_data->data);
281 }
282
283
284 // export function for a use table record
285 void export_usetable(int which_cdb, DBT *in_key, DBT *in_data) {
286         struct UseTable *u = (struct UseTable *)in_data->data;
287         printf("use|%d|%ld|\n", u->hash, u->timestamp);
288 }
289
290
291 // export function for large message texts
292 void export_bigmsg(int which_cdb, DBT *in_key, DBT *in_data) {
293         long msgnum;
294
295         memcpy(&msgnum, in_key->data, sizeof(msgnum));
296         printf("bigmsg|%ld|%s|\n", msgnum, b64out(in_data->data, in_data->size));
297 }
298
299
300 // export function for EUID Index records
301 void export_euidindex(int which_cdb, DBT *in_key, DBT *in_data) {
302
303         // The structure of an euidindex record *key* is:
304         // |----room_number----|----------EUID-------------|
305         //    (sizeof long)       (actual length of euid)
306
307         // The structure of an euidindex record *value* is:
308         // |-----msg_number----|----room_number----|----------EUID-------------|
309         //    (sizeof long)       (sizeof long)       (actual length of euid)
310
311         long msgnum, roomnum;
312         char *euid;
313
314         memcpy(&msgnum, in_data->data, sizeof(long));
315         memcpy(&roomnum, in_data->data+sizeof(long), sizeof(msgnum));
316         euid = in_data->data+(sizeof(long)*2);
317
318         printf("euidindex|%ld|%ld|%s|\n", msgnum, roomnum, euid);
319 }
320
321
322 // export users-by-number records
323 // (This is a secondary index -- should we just regenerate the data after import?)
324 void export_usersbynumber(int which_cdb, DBT *in_key, DBT *in_data) {
325
326         // key is a long
327         long usernum;
328         memcpy(&usernum, in_key->data, sizeof(usernum));
329
330         // value is a string
331         printf("usersbynumber|%ld|%s|\n", usernum, (char *)in_data->data);
332 }
333
334
335 // export function for a config record
336 void export_config(int which_cdb, DBT *in_key, DBT *in_data) {
337
338         size_t keylen = in_key->size;
339         printf("config|");
340         fwrite(in_data->data, keylen, 1, stdout);
341
342         printf("|");
343         fwrite(in_data->data + keylen, in_data->size - keylen, 1, stdout);
344         printf("|\n");
345 }
346
347
348 // For obsolete databases, zero all the output
349 void zero_function(int which_cdb, DBT *in_key, DBT *in_data) {
350         // do nothing
351 }
352
353
354 void (*export_functions[])(int which_cdb, DBT *in_key, DBT *in_data) = {
355         export_msgmain,         // CDB_MSGMAIN
356         export_user,            // CDB_USERS
357         export_room,            // CDB_ROOMS
358         export_floor,           // CDB_FLOORTAB
359         export_msglist,         // CDB_MSGLISTS
360         export_visit,           // CDB_VISIT
361         export_dir,             // CDB_DIRECTORY
362         export_usetable,        // CDB_USETABLE
363         export_bigmsg,          // CDB_BIGMSGS
364         zero_function,          // CDB_FULLTEXT (regenerate this on the server)
365         export_euidindex,       // CDB_EUIDINDEX
366         export_usersbynumber,   // CDB_USERSBYNUMBER
367         zero_function,          // CDB_UNUSED1 (obsolete)
368         export_config           // CDB_CONFIG
369 };
370
371
372 void export_table(int which_cdb, DB_ENV *src_dbenv) {
373         int ret;
374         int compressed;
375         char dbfilename[32];
376         uLongf destLen = 0;
377
378         // shamelessly swiped from https://docs.oracle.com/database/bdb181/html/programmer_reference/am_cursor.html
379         DB *src_dbp;
380         DBC *src_dbcp;
381         DBT in_key, in_data, uncomp_data;
382         int num_good_rows = 0;
383         int num_bad_rows = 0;
384
385         snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", which_cdb);
386
387         // create a database handle for the source table
388         ret = db_create(&src_dbp, src_dbenv, 0);
389         if (ret) {
390                 fprintf(stderr, "db: db_create: %s\n", db_strerror(ret));
391                 fprintf(stderr, "db: exit code %d\n", ret);
392                 exit(CTDLEXIT_DB);
393         }
394
395         // open the file containing the source table
396         ret = src_dbp->open(src_dbp, NULL, dbfilename, NULL, DB_BTREE, 0, 0600);
397         if (ret) {
398                 fprintf(stderr, "db: db_open: %s\n", db_strerror(ret));
399                 fprintf(stderr, "db: exit code %d\n", ret);
400                 exit(CTDLEXIT_DB);
401         }
402
403         // Acquire a cursor to read the source table
404         if ((ret = src_dbp->cursor(src_dbp, NULL, &src_dbcp, 0)) != 0) {
405                 fprintf(stderr, "db: db_cursor: %s\n", db_strerror(ret));
406                 fprintf(stderr, "db: exit code %d\n", ret);
407                 exit(CTDLEXIT_DB);
408         }
409
410         // Zero out these database keys
411         memset(&in_key,         0, sizeof(DBT));        // input
412         memset(&in_data,        0, sizeof(DBT));
413         memset(&uncomp_data,    0, sizeof(DBT));        // decompressed input (the key doesn't change)
414
415         // Walk through the database, calling export functions as we go and clearing buffers before each call.
416         while (ret = src_dbcp->get(src_dbcp, &in_key, &in_data, DB_NEXT) == 0) {
417         
418                 // If either the key or data are zero length, skip this record
419                 if ((in_key.size == 0) || (in_data.size == 0)) {
420                         ++num_bad_rows;
421                 }
422
423                 else {  // Both key and data are >0 length so we're good to go
424
425                         // Do we need to decompress?
426                         static int32_t magic = COMPRESS_MAGIC;
427                         compressed = 0;
428                         if ((in_data.size >= sizeof(struct CtdlCompressHeader)) && (!memcmp(in_data.data, &magic, sizeof(magic)))) {
429         
430                                 // yes, we need to decompress
431                                 compressed = 1;
432                                 struct CtdlCompressHeader comp;
433                                 memcpy(&comp, in_data.data, sizeof(struct CtdlCompressHeader));
434                                 uncomp_data.size = comp.uncompressed_len;
435                                 uncomp_data.data = realloc(uncomp_data.data, uncomp_data.size);
436                                 destLen = (uLongf)comp.uncompressed_len;
437         
438                                 ret = uncompress((Bytef *)uncomp_data.data, (uLongf *)&destLen,
439                                                 (const Bytef *)in_data.data+sizeof(struct CtdlCompressHeader),
440                                                 (uLong)comp.compressed_len);
441                                 if (ret != Z_OK) {
442                                         fprintf(stderr, "db: uncompress() error %d\n", ret);
443                                         exit(CTDLEXIT_DB);
444                                 }
445                         }
446         
447                         // Call the export function registered to this table
448                         export_functions[which_cdb](which_cdb, &in_key, (compressed ? &uncomp_data : &in_data));
449         
450                         // Knowing the total number of rows isn't critical to the program.  It's just for the user to know.
451                         fflush(stdout);
452                 }
453         }
454
455         // free any leftover out_data pointers
456         free(uncomp_data.data);
457
458         // ...and close the database (table)
459         ret = src_dbp->close(src_dbp, 0);
460         if (ret) {
461                 fprintf(stderr, "db: db_close: %s\n", db_strerror(ret));
462         }
463
464
465 }
466
467
468 int main(int argc, char **argv) {
469         int i = 0;
470         char *src_dir = NULL;
471         char *dst_dir = NULL;
472         int confirmed = 0;
473         static DB_ENV *src_dbenv;               // Source DB environment (global)
474
475         // Parse command line
476         int a;
477         while ((a = getopt(argc, argv, "h:d:y")) != EOF) {
478                 switch (a) {
479                 case 'h':
480                         src_dir = optarg;
481                         break;
482                 case 'd':
483                         dst_dir = optarg;
484                         break;
485                 case 'y':
486                         confirmed = 1;
487                         break;
488                 default:
489                         fprintf(stderr, "%s: usage: %s -s source_dir -d dest_dir\n", argv[0], argv[0]);
490                         exit(2);
491                 }
492         }
493
494         // Warn the user
495         fprintf(stderr, "------------------------------------------------------------------------\n");
496         fprintf(stderr, "This utility must be run while the server is NOT RUNNING.               \n");
497         fprintf(stderr, "We \033[1mguarantee\033[0m data corruption if you do not                              \n");
498         fprintf(stderr, "observe this warning!  The source [-s] directory should contain a copy  \n");
499         fprintf(stderr, "of the database from your source system.  The dump [-d] directory       \n");
500         fprintf(stderr, "should be empty and will receive your dump file.                        \n");
501         fprintf(stderr, "------------------------------------------------------------------------\n");
502         fprintf(stderr, " Source (database) directory: %s\n", src_dir);
503         fprintf(stderr, "------------------------------------------------------------------------\n");
504
505         if (confirmed == 1) {
506                 fprintf(stderr, "You have specified the [-y] flag, so processing will continue.\n");
507         }
508         else {
509                 fprintf(stderr, "Please read [ https://www.citadel.org/ctdldump.html ] to learn how to proceed.\n");
510                 exit(0);
511         }
512
513         src_dbenv = open_dbenv(src_dir);
514         for (i = 0; i < MAXCDB; ++i) {
515                 export_table(i, src_dbenv);
516         }
517         close_dbenv(src_dbenv);
518
519         exit(0);
520 }