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