Remediated an unrecoverable problem in CDB_USETABLE.
[citadel.git] / citadel / utils / ctdl3264.c
1 // Attempt to  your database from 32-bit to 64-bit.
2 // Don't run this.  It doesn't work and if you try to run it you will immediately die.
3 //
4 // Copyright (c) 2023 by Art Cancro citadel.org
5 //
6 // This program is open source software.  Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
8
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <ctype.h>
12 #include <stdio.h>
13 #include <signal.h>
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <sys/un.h>
17 #include <netdb.h>
18 #include <string.h>
19 #include <pwd.h>
20 #include <errno.h>
21 #include <stdarg.h>
22 #include <limits.h>
23 #include <libcitadel.h>
24 #include <zlib.h>
25 #include <db.h>
26 #include "../server/sysdep.h"
27 #include "../server/citadel_defs.h"
28 #include "../server/server.h"
29 #include "../server/citadel_dirs.h"
30 #include "ctdl3264_structs.h"
31
32
33 // Wrapper for realloc() that crashes and burns if the call fails.
34 void *reallok(void *ptr, size_t size) {
35         void *p = realloc(ptr, size);
36         if (!p) {
37                 fprintf(stderr, "realloc() failed to resize %p to %ld bytes, error: %m\n", ptr, size);
38                 exit(1);
39         }
40         return p;
41 }
42 #define realloc reallok
43
44
45 // Open a database environment
46 DB_ENV *open_dbenv(char *dirname) {
47
48         DB_ENV *dbenv = NULL;
49
50         int ret;
51         int i;
52         u_int32_t flags = 0;
53         int dbversion_major, dbversion_minor, dbversion_patch;
54
55         printf( "db: open_dbenv() starting\n"
56                 "db:    Linked zlib: %s\n"
57                 "db: Compiled libdb: %s\n"
58                 "db:   Linked libdb: %s\n",
59                 zlibVersion(),
60                 DB_VERSION_STRING,
61                 db_version(&dbversion_major, &dbversion_minor, &dbversion_patch)
62         );
63
64         // Create synthetic integer version numbers and compare them.
65         // Never run with a libdb older than the one with which it was compiled.
66         int compiled_db_version = ( (DB_VERSION_MAJOR * 1000000) + (DB_VERSION_MINOR * 1000) + (DB_VERSION_PATCH) );
67         int linked_db_version = ( (dbversion_major * 1000000) + (dbversion_minor * 1000) + (dbversion_patch) );
68         if (compiled_db_version > linked_db_version) {
69                 printf( "db: ctdl3264 is running with a version of libdb older than the one with which it was compiled.\n"
70                         "db: This is an invalid configuration.  ctdl3264 will now exit to prevent data loss.");
71                 exit(CTDLEXIT_DB);
72         }
73
74         printf("db: Setting up DB environment\n");
75         ret = db_env_create(&dbenv, 0);
76         if (ret) {
77                 printf("db: db_env_create: %s\n", db_strerror(ret));
78                 printf("db: exit code %d\n", ret);
79                 exit(CTDLEXIT_DB);
80         }
81
82         // We want to specify the shared memory buffer pool cachesize, but everything else is the default.
83         ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
84         if (ret) {
85                 printf("db: set_cachesize: %s\n", db_strerror(ret));
86                 dbenv->close(dbenv, 0);
87                 printf("db: exit code %d\n", ret);
88                 exit(CTDLEXIT_DB);
89         }
90
91         if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
92                 printf("db: set_lk_detect: %s\n", db_strerror(ret));
93                 dbenv->close(dbenv, 0);
94                 printf("db: exit code %d\n", ret);
95                 exit(CTDLEXIT_DB);
96         }
97
98         flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_LOG;
99         printf("db: dbenv open(dir=%s, flags=%d)\n", dirname, flags);
100         ret = dbenv->open(dbenv, dirname, flags, 0);
101         if (ret) {
102                 printf("db: dbenv->open: %s\n", db_strerror(ret));
103                 dbenv->close(dbenv, 0);
104                 printf("db: exit code %d\n", ret);
105                 exit(CTDLEXIT_DB);
106         }
107
108         return(dbenv);
109 }
110
111
112 void close_dbenv(DB_ENV *dbenv) {
113         printf("db: closing dbenv\n");
114         int ret = dbenv->close(dbenv, 0);
115         if (ret) {
116                 printf("db: dbenv->close: %s\n", db_strerror(ret));
117         }
118 }
119
120
121 // convert function for a message in msgmain
122 void convert_msgmain(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
123         int32_t in_msgnum;
124         long out_msgnum;
125         memcpy(&in_msgnum, in_key->data, sizeof(in_msgnum));
126         out_msgnum = (long)in_msgnum;
127
128         if (in_key->size != 4) {
129                 fprintf(stderr, "\033[31m\033[1m *** SOURCE DATABASE IS NOT 32-BIT *** ABORTING *** \033[0m\n");
130                 abort();
131         }
132
133         // If the msgnum is negative, we are looking at METADATA
134         if (in_msgnum < 0) {
135                 struct MetaData_32 *meta32 = (struct MetaData_32 *)in_data->data;
136
137                 // printf("\033[32m\033[1mMetadata: msgnum=%d , refcount=%d , content_type=\"%s\" , rfc822len=%d\033[0m\n", meta32->meta_msgnum, meta32->meta_refcount, meta32->meta_content_type, meta32->meta_rfc822_length);
138
139                 out_key->size = sizeof(long);
140                 out_key->data = realloc(out_key->data, out_key->size);
141                 memcpy(out_key->data, &out_msgnum, sizeof(long));
142
143                 out_data->size = sizeof(struct MetaData);
144                 out_data->data = realloc(out_data->data, out_data->size);
145                 struct MetaData *meta64 = (struct MetaData *)out_data->data;
146                 memset(meta64, 0, sizeof(struct MetaData));
147                 meta64->meta_msgnum             = (long)        meta32->meta_msgnum;
148                 meta64->meta_refcount           = (int)         meta32->meta_refcount;
149                 strcpy(meta64->meta_content_type,               meta32->meta_content_type);
150                 meta64->meta_rfc822_length      = (long)        meta32->meta_rfc822_length;
151         }
152
153         // If the msgnum is positive, we are looking at a MESSAGE
154         else if (in_msgnum > 0) {
155                 out_key->size = sizeof(long);
156                 out_key->data = realloc(out_key->data, out_key->size);
157                 memcpy(out_key->data, &out_msgnum, sizeof(long));
158
159                 // copy the message verbatim
160                 out_data->size = in_data->size;
161                 out_data->data = realloc(out_data->data, out_data->size);
162                 memcpy(out_data->data, in_data->data, out_data->size);
163                 // printf("\033[32m\033[1mMessage: %ld\033[0m\n", out_msgnum);
164         }
165
166         // If the msgnum is 0 it's probably not a valid record.
167         else {
168                 printf("\033[31mmsgmain: message number 0 is impossible, skipping this record\033[0m\n");
169         }
170 }
171
172
173 // convert function for a user record
174 void convert_users(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
175
176         // The key is a string so we can just copy it over
177         out_key->size = in_key->size;
178         out_key->data = realloc(out_key->data, out_key->size);
179         memcpy(out_key->data, in_key->data, in_key->size);
180
181         struct ctdluser_32 *user32 = (struct ctdluser_32 *)in_data->data;
182
183         out_data->size = sizeof(struct ctdluser);
184         out_data->data = realloc(out_data->data, out_data->size);
185         struct ctdluser *user64 = (struct ctdluser *)out_data->data;
186
187         user64->version                 = (int)         user32->version;
188         user64->uid                     = (uid_t)       user32->uid;
189         strcpy(user64->password,                        user32->password);
190         user64->flags                   = (unsigned)    user32->flags;
191         user64->timescalled             = (long)        user32->timescalled;
192         user64->posted                  = (long)        user32->posted;
193         user64->axlevel                 = (cit_uint8_t) user32->axlevel;
194         user64->usernum                 = (long)        user32->usernum;
195         user64->lastcall                = (time_t)      user32->lastcall;
196         user64->USuserpurge             = (int)         user32->USuserpurge;
197         strcpy(user64->fullname,                        user32->fullname);
198         user64->msgnum_bio              = (long)        user32->msgnum_bio;
199         user64->msgnum_pic              = (long)        user32->msgnum_pic;
200         strcpy(user64->emailaddrs,                      user32->emailaddrs);
201         user64->msgnum_inboxrules       = (long)        user32->msgnum_inboxrules;
202         user64->lastproc_inboxrules     = (long)        user32->lastproc_inboxrules;
203
204         // printf("\033[32m\033[1mUser: %s\033[0m\n", user64->fullname);
205 }
206
207
208 // convert function for a room record
209 void convert_rooms(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
210
211         // The key is a string so we can just copy it over
212         out_key->size = in_key->size;
213         out_key->data = realloc(out_key->data, out_key->size);
214         memcpy(out_key->data, in_key->data, in_key->size);
215
216         // data
217         struct ctdlroom_32 *room32 = (struct ctdlroom_32 *)in_data->data;
218         out_data->size = sizeof(struct ctdlroom);
219         out_data->data = realloc(out_data->data, out_data->size);
220         struct ctdlroom *room64 = (struct ctdlroom *)out_data->data;
221
222         strcpy(room64->QRname,                          room32->QRname);
223         strcpy(room64->QRpasswd,                        room32->QRpasswd);
224         room64->QRroomaide              = (long)        room32->QRroomaide;
225         room64->QRhighest               = (long)        room32->QRhighest;
226         room64->QRgen                   = (time_t)      room32->QRgen;
227         room64->QRflags                 = (unsigned)    room32->QRflags;
228         strcpy(room64->QRdirname,                       room32->QRdirname);
229         room64->msgnum_info             = (long)        room32->msgnum_info;
230         room64->QRfloor                 = (char)        room32->QRfloor;
231         room64->QRmtime                 = (time_t)      room32->QRmtime;
232         room64->QRep.expire_mode        = (int)         room32->QRep.expire_mode;
233         room64->QRep.expire_value       = (int)         room32->QRep.expire_value;
234         room64->QRnumber                = (long)        room32->QRnumber;
235         room64->QRorder                 = (char)        room32->QRorder;
236         room64->QRflags2                = (unsigned)    room32->QRflags2;
237         room64->QRdefaultview           = (int)         room32->QRdefaultview;
238         room64->msgnum_pic              = (long)        room32->msgnum_pic;
239
240         // printf("\033[32m\033[1mRoom: %s\033[0m\n", room64->QRname);
241 }
242
243
244 // convert function for a floor record
245 void convert_floors(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
246
247         // the key is an "int", and "int" is 32-bits on both 32 and 64 bit platforms.
248         out_key->size = in_key->size;
249         out_key->data = realloc(out_key->data, out_key->size);
250         memcpy(out_key->data, in_key->data, in_key->size);
251
252         // data
253         struct floor_32 *floor32 = (struct floor_32 *)in_data->data;
254         out_data->size = sizeof(struct floor);
255         out_data->data = realloc(out_data->data, out_data->size);
256         struct floor *floor64 = (struct floor *)out_data->data;
257
258         // these are probably bit-for-bit identical, actually ... but we do it the "right" way anyway
259         floor64->f_flags                = (unsigned short)      floor32->f_flags;
260         strcpy(floor64->f_name,                                 floor32->f_name);
261         floor64->f_ref_count            = (int)                 floor32->f_ref_count;
262         floor64->f_ep.expire_mode       = (int)                 floor32->f_ep.expire_mode;
263         floor64->f_ep.expire_value      = (int)                 floor32->f_ep.expire_value;
264
265         // printf("\033[32m\033[1mFloor: %s\033[0m\n", floor64->f_name);
266 }
267
268
269 // convert function for a msglist or a fulltext index record
270 // (both are indexed by a long and the data is arrays of longs)
271 void convert_msglists(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
272         int i;
273
274         char *table = (which_cdb == CDB_FULLTEXT) ? "FullText" : "Msglist";
275
276         // records are indexed by a single "long" and contains an array of zero or more "long"s
277         // and remember ... "long" is int32_t on the source system
278         int32_t in_roomnum;
279         long out_roomnum;
280         memcpy(&in_roomnum, in_key->data, sizeof(in_roomnum));
281         out_roomnum = (long) in_roomnum;
282
283         if (in_key->size != 4) {
284                 fprintf(stderr, "\033[31m\033[1m *** SOURCE DATABASE IS NOT 32-BIT *** ABORTING *** \033[0m\n");
285                 abort();
286         }
287
288         int num_msgs = in_data->size / sizeof(int32_t);
289         // printf("\033[32m\033[1m%s: key %ld (%d messages)\033[0m\n", table, out_roomnum, num_msgs);
290
291         // the key is a "long"
292         out_key->size = sizeof(out_roomnum);
293         out_key->data = realloc(out_key->data, out_key->size);
294         memcpy(out_key->data, &out_roomnum, sizeof(out_roomnum));
295
296         // the data is another array, but a wider type
297         out_data->size = sizeof(long) * num_msgs;
298         out_data->data = realloc(out_data->data, out_data->size);
299
300         int32_t in_msg = 0;
301         long out_msg = 0;
302         for (i=0; i<num_msgs; ++i) {
303                 memcpy(&in_msg, (in_data->data + (i * sizeof(int32_t))), sizeof(int32_t));
304                 out_msg = (long) in_msg;
305                 memcpy((out_data->data + (i * sizeof(long))), &out_msg, sizeof(long));
306                 // printf("msg#%ld\n", out_msg);
307         }
308 }
309
310
311 // convert function for a visit record
312 void convert_visits(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
313
314         // data
315         struct visit_32 *visit32 = (struct visit_32 *)in_data->data;
316         out_data->size = sizeof(struct visit);
317         out_data->data = realloc(out_data->data, out_data->size);
318         struct visit *visit64 = (struct visit *)out_data->data;
319
320         //  the data (zero it out so it will compress well)
321         memset(visit64, 0, sizeof(struct visit));
322         visit64->v_roomnum              = (long)        visit32->v_roomnum;
323         visit64->v_roomgen              = (long)        visit32->v_roomgen;
324         visit64->v_usernum              = (long)        visit32->v_usernum;
325         visit64->v_lastseen             = (long)        visit32->v_lastseen;
326         visit64->v_flags                = (unsigned)    visit32->v_flags;
327         strcpy(visit64->v_seen,                         visit32->v_seen);
328         strcpy(visit64->v_answered,                     visit32->v_answered);
329         visit64->v_view                 = (int)         visit32->v_view;
330
331         // printf("\033[32m\033[1mVisit: room %10ld, gen %10ld, user %10ld\033[0m\n", visit64->v_roomnum, visit64->v_roomgen, visit64->v_usernum);
332
333         // create the key (which is based on the data, so there is no need to convert the old key)
334         out_key->size = sizeof(struct visit_index);
335         out_key->data = realloc(out_key->data, out_key->size);
336         struct visit_index *newvisitindex = (struct visit_index *) out_key->data;
337         newvisitindex->iRoomID          =               visit64->v_roomnum;
338         newvisitindex->iRoomGen         =               visit64->v_roomgen;
339         newvisitindex->iUserID          =               visit64->v_usernum;
340 }
341
342
343 // convert function for a directory record
344 void convert_dir(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
345
346         // the key is a string
347         out_key->size = in_key->size;
348         out_key->data = realloc(out_key->data, out_key->size + 1);
349         memcpy(out_key->data, in_key->data, in_key->size);
350         char *k = (char *)out_key->data;
351         k[out_key->size] = 0;
352
353         // the data is also a string
354         out_data->size = in_data->size;
355         out_data->data = realloc(out_data->data, out_data->size + 1);
356         memcpy(out_data->data, in_data->data, in_data->size);
357         char *d = (char *)out_data->data;
358         d[out_data->size] = 0;
359
360         // please excuse my friend, he isn't null terminated
361         // printf("\033[32m\033[1mDirectory entry: %s -> %s\033[0m\n", (char *)out_key->data, (char *)out_data->data);
362 }
363
364
365 // convert function for a use table record
366 void convert_usetable(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
367
368         // the key is an int, which is the same size (32 bits) on both 32 and 64 bit systems
369         out_key->size = in_key->size;
370         out_key->data = realloc(out_key->data, out_key->size);
371         memcpy(out_key->data, in_key->data, in_key->size);
372
373         // the data is a "struct UseTable"
374         struct UseTable_32 *use32 = (struct UseTable_32 *)in_data->data;
375         out_data->size = sizeof(struct UseTable);
376         out_data->data = realloc(out_data->data, out_data->size);
377         memset(out_data->data, 0, out_data->size);
378         struct UseTable *use64 = (struct UseTable *)out_data->data;
379
380         //  the data
381         use64->hash                     =               use32->hash;
382         use64->timestamp                = (time_t)      use32->timestamp;
383
384         printf("\033[32m\033[1muse table: %d , %s\033[0m\n", use64->hash, asctime(localtime(&use64->timestamp)));
385 }
386
387
388 // convert function for large message texts
389 void convert_bigmsgs(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
390
391         // The key is a packed long
392         int32_t in_msgnum;
393         long out_msgnum;
394         memcpy(&in_msgnum, in_key->data, sizeof(in_msgnum));
395         out_msgnum = (long)in_msgnum;
396
397         if (in_key->size != 4) {
398                 fprintf(stderr, "\033[31m\033[1m *** SOURCE DATABASE IS NOT 32-BIT *** ABORTING *** \033[0m\n");
399                 abort();
400         }
401
402         out_key->size = sizeof(long);
403         out_key->data = realloc(out_key->data, out_key->size);
404         memcpy(out_key->data, &out_msgnum, sizeof(long));
405
406         // the data is binary-ish but has no packed integers
407         out_data->size = in_data->size;
408         out_data->data = realloc(out_data->data, out_data->size);
409         memcpy(out_data->data, in_data->data, in_data->size);
410
411         // printf("\033[32m\033[1mBigmsg %ld , length %d\033[0m\n", out_msgnum, out_data->size);
412 }
413
414
415 // convert function for EUID Index records
416 void convert_euidindex(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
417
418         // The structure of an euidindex record *key* is:
419         // |----room_number----|----------EUID-------------|
420         //    (sizeof long)       (actual length of euid)
421
422         // The structure of an euidindex record *value* is:
423         // |-----msg_number----|----room_number----|----------EUID-------------|
424         //    (sizeof long)       (sizeof long)       (actual length of euid)
425
426         int32_t in_msgnum = 0;
427         int32_t in_roomnum = 0;
428         char euid[SIZ];
429         long out_msgnum = 0;
430         long out_roomnum = 0;
431
432         memcpy(&in_msgnum, in_data->data, sizeof(in_msgnum));
433         memcpy(&in_roomnum, in_data->data+sizeof(int32_t), sizeof(in_msgnum));
434         strcpy(euid, in_data->data+(sizeof(int32_t)*2));
435
436         out_msgnum = (long) in_msgnum;
437         out_roomnum = (long) in_roomnum;
438         // printf("euidindex: msgnum=%ld, roomnum=%ld, euid=\"%s\"\n", out_msgnum, out_roomnum, euid);
439
440         out_key->size = sizeof(long) + strlen(euid) + 1;
441         out_key->data = realloc(out_key->data, out_key->size);
442         memcpy(out_key->data, &out_roomnum, sizeof(out_roomnum));
443         strcpy(out_key->data+sizeof(out_roomnum), euid);
444
445         out_data->size = sizeof(long) + sizeof(long) + strlen(euid) + 1;
446         out_data->data = realloc(out_data->data, out_data->size);
447         memcpy(out_data->data, &out_msgnum, sizeof(out_msgnum));
448         memcpy(out_data->data+sizeof(out_msgnum), &out_roomnum, sizeof(out_roomnum));
449         strcpy(out_data->data+sizeof(out_msgnum)+sizeof(out_roomnum), euid);
450
451
452         //int i;
453         //char ch;
454 //
455         //printf("  in_key:             ");
456         //for (i=0; i<in_key->size; ++i) {
457                 //ch = 0;
458                 //memcpy(&ch, in_key->data+i, 1);
459                 //printf("%02X ", (int) ch);
460         //}
461         //printf("\n");
462 //
463         //printf(" out_key: ");
464         //for (i=0; i<out_key->size; ++i) {
465                 //ch = 0;
466                 //memcpy(&ch, out_key->data+i, 1);
467                 //printf("%02X ", (int) ch);
468         //}
469         //printf("\n");
470 //
471         //printf(" in_data:                         ");
472         //for (i=0; i<in_data->size; ++i) {
473                 //ch = 0;
474                 //memcpy(&ch, in_data->data+i, 1);
475         //      printf("%02X ", (int) ch);
476         //}
477         //printf("\n");
478 //
479         //printf("out_data: ");
480         //for (i=0; i<out_data->size; ++i) {
481                 //ch = 0;
482                 //memcpy(&ch, out_data->data+i, 1);
483                 //printf("%02X ", (int) ch);
484         //}
485         //printf("\n");
486
487
488 }
489
490
491 // convert users-by-number records
492 void convert_usersbynumber(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
493
494         // key is a long
495         // and remember ... "long" is int32_t on the source system
496         int32_t in_usernum;
497         long out_usernum;
498         memcpy(&in_usernum, in_key->data, sizeof(in_usernum));
499         out_usernum = (long) in_usernum;
500
501         if (in_key->size != 4) {
502                 fprintf(stderr, "\033[31m\033[1m *** SOURCE DATABASE IS NOT 32-BIT *** ABORTING *** \033[0m\n");
503                 abort();
504         }
505
506         out_key->size = sizeof(out_usernum);
507         out_key->data = realloc(out_key->data, out_key->size);
508         memcpy(out_key->data, &out_usernum, sizeof(out_usernum));
509
510         // value is a string
511         out_data->size = in_data->size;
512         out_data->data = realloc(out_data->data, out_data->size);
513         memcpy(out_data->data, in_data->data, in_data->size);
514
515         // printf("usersbynumber: %ld --> %s\n", out_usernum, (char *)out_data->data);
516 }
517
518
519 // convert function for a config record
520 void convert_config(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
521
522         // the key is a string
523         out_key->size = in_key->size;
524         out_key->data = realloc(out_key->data, out_key->size + 1);
525         memcpy(out_key->data, in_key->data, in_key->size);
526         char *k = (char *)out_key->data;
527         k[out_key->size] = 0;
528
529         // the data is a pair of strings
530         out_data->size = in_data->size;
531         out_data->data = realloc(out_data->data, out_data->size + 1);
532         memcpy(out_data->data, in_data->data, in_data->size);
533         char *d = (char *)out_data->data;
534         d[out_data->size] = 0;
535
536         // please excuse my friend, he isn't null terminated
537         // printf("\033[32m\033[1mConfig entry: %s -> %s\033[0m\n", (char *)out_key->data, (char *)out_data->data+strlen(out_data->data)+1);
538 }
539
540
541 // For obsolete databases, zero all the output
542 void zero_function(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) {
543         out_key->size = 0;
544         out_data->size = 0;
545 }
546
547
548 void (*convert_functions[])(int which_cdb, DBT *in_key, DBT *in_data, DBT *out_key, DBT *out_data) = {
549         convert_msgmain,        // CDB_MSGMAIN
550         convert_users,          // CDB_USERS
551         convert_rooms,          // CDB_ROOMS
552         convert_floors,         // CDB_FLOORTAB
553         convert_msglists,       // CDB_MSGLISTS
554         convert_visits,         // CDB_VISIT
555         convert_dir,            // CDB_DIRECTORY
556         convert_usetable,       // CDB_USETABLE
557         convert_bigmsgs,        // CDB_BIGMSGS
558         convert_msglists,       // CDB_FULLTEXT
559         convert_euidindex,      // CDB_EUIDINDEX
560         convert_usersbynumber,  // CDB_USERSBYNUMBER
561         zero_function,          // CDB_UNUSED1 (obsolete)
562         convert_config          // CDB_CONFIG
563 };
564
565
566 void convert_table(int which_cdb, DB_ENV *src_dbenv, DB_ENV *dst_dbenv) {
567         int ret;
568         int compressed;
569         char dbfilename[32];
570         uLongf destLen = 0;
571
572         printf("\033[43m\033[K\033[0m\n");
573         printf("\033[43m\033[30m Converting table %02x \033[K\033[0m\n", which_cdb);
574         printf("\033[43m\033[K\033[0m\n");
575
576         // shamelessly swiped from https://docs.oracle.com/database/bdb181/html/programmer_reference/am_cursor.html
577         DB *src_dbp, *dst_dbp;
578         DBC *src_dbcp;
579         DBT in_key, in_data, out_key, out_data, uncomp_data, recomp_data;
580         int num_rows = 0;
581
582         snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", which_cdb);
583
584         // create a database handle for the source table
585         ret = db_create(&src_dbp, src_dbenv, 0);
586         if (ret) {
587                 printf("db: db_create: %s\n", db_strerror(ret));
588                 printf("db: exit code %d\n", ret);
589                 exit(CTDLEXIT_DB);
590         }
591
592         // open the file containing the source table
593         printf("\033[33m\033[1mdb: opening source %s\033[0m\n", dbfilename);
594         ret = src_dbp->open(src_dbp, NULL, dbfilename, NULL, DB_BTREE, 0, 0600);
595         if (ret) {
596                 printf("db: db_open: %s\n", db_strerror(ret));
597                 printf("db: exit code %d\n", ret);
598                 exit(CTDLEXIT_DB);
599         }
600
601         // create a database handle for the destination table
602         ret = db_create(&dst_dbp, dst_dbenv, 0);
603         if (ret) {
604                 printf("db: db_create: %s\n", db_strerror(ret));
605                 printf("db: exit code %d\n", ret);
606                 exit(CTDLEXIT_DB);
607         }
608
609         // open the file containing the destination table
610         printf("\033[33m\033[1mdb: opening destination %s\033[0m\n", dbfilename);
611         ret = dst_dbp->open(dst_dbp, NULL, dbfilename, NULL, DB_BTREE, (DB_CREATE | DB_TRUNCATE), 0600);
612         if (ret) {
613                 printf("db: db_open: %s\n", db_strerror(ret));
614                 printf("db: exit code %d\n", ret);
615                 exit(CTDLEXIT_DB);
616         }
617
618         // Acquire a cursor to read the source table
619         printf("\033[33m\033[1mdb: acquiring cursor\033[0m\n");
620         if ((ret = src_dbp->cursor(src_dbp, NULL, &src_dbcp, 0)) != 0) {
621                 printf("db: db_cursor: %s\n", db_strerror(ret));
622                 printf("db: exit code %d\n", ret);
623                 exit(CTDLEXIT_DB);
624         }
625
626         // Zero out these database keys
627         memset(&in_key,         0, sizeof(DBT));        // input
628         memset(&in_data,        0, sizeof(DBT));
629         memset(&out_key,        0, sizeof(DBT));        // output
630         memset(&out_data,       0, sizeof(DBT));
631         memset(&uncomp_data,    0, sizeof(DBT));        // decompressed input (the key doesn't change)
632         memset(&recomp_data,    0, sizeof(DBT));        // recompressed input (the key doesn't change)
633
634         // Walk through the database, calling convert functions as we go and clearing buffers before each call.
635         while (out_key.size = 0, out_data.size = 0, (ret = src_dbcp->get(src_dbcp, &in_key, &in_data, DB_NEXT)) == 0) {
636         
637                 // Knowing the total number of rows isn't critical to the program.  It's just for the user to know.
638                 ++num_rows;
639                 printf("   \033[32m%d\033[0m\r", num_rows);
640                 fflush(stdout);
641
642                 // If either the key or data are zero length, skip this record
643                 if ((in_key.size == 0) || (in_data.size == 0)) {
644                         printf("\033[31minput keylen=%d , datalen=%d , skipping record\033[0m\n", in_key.size, in_data.size);
645                 }
646
647                 else {  // Both key and data are >0 length so we're good to go
648
649                         // Do we need to decompress?
650                         static int32_t magic = COMPRESS_MAGIC;
651                         compressed = 0;
652                         if ( (in_data.size >= sizeof(struct CtdlCompressHeader_32)) && (!memcmp(in_data.data, &magic, sizeof(magic))) ) {
653         
654                                 // yes, we need to decompress
655                                 compressed = 1;
656                                 struct CtdlCompressHeader_32 comp32;
657                                 memcpy(&comp32, in_data.data, sizeof(struct CtdlCompressHeader_32));
658                                 uncomp_data.size = comp32.uncompressed_len;
659                                 uncomp_data.data = realloc(uncomp_data.data, uncomp_data.size);
660                                 destLen = (uLongf)comp32.uncompressed_len;
661         
662                                 ret = uncompress((Bytef *)uncomp_data.data, (uLongf *)&destLen, (const Bytef *)in_data.data+sizeof(struct CtdlCompressHeader_32), (uLong)comp32.compressed_len);
663                                 if (ret != Z_OK) {
664                                         printf("db: uncompress() error %d\n", ret);
665                                         exit(CTDLEXIT_DB);
666                                 }
667                                 // printf("DB: %02x ,  in_keylen: %-3d ,  in_datalen: %-10d , dataptr: %012lx \033[31m(decompressed)\033[0m\n", which_cdb, (int)in_key.size, comp32.uncompressed_len, (long unsigned int)uncomp_data.data);
668                         }
669                         else {
670                                 // printf("DB: %02x ,  in_keylen: %-3d ,  in_datalen: %-10d , dataptr: %012lx\n", which_cdb, (int)in_key.size, (int)in_data.size, (long unsigned int)in_data.data);
671                         }
672         
673                         // Call the convert function registered to this table
674                         convert_functions[which_cdb](which_cdb, &in_key, (compressed ? &uncomp_data : &in_data), &out_key, &out_data);
675         
676                         // The logic here is that if the source data was compressed, we compress the output too
677                         if (compressed) {
678                                 struct CtdlCompressHeader zheader;
679                                 memset(&zheader, 0, sizeof(struct CtdlCompressHeader));
680                                 zheader.magic = COMPRESS_MAGIC;
681                                 zheader.uncompressed_len = out_data.size;
682                                 recomp_data.data = realloc(recomp_data.data, ((out_data.size * 101) / 100) + 100 + sizeof(struct CtdlCompressHeader));
683         
684                                 if (compress2((Bytef *)(recomp_data.data + sizeof(struct CtdlCompressHeader)), &destLen, (Bytef *)out_data.data, (uLongf) out_data.size, 1) != Z_OK) {
685                                         printf("db: compress() error\n");
686                                         exit(CTDLEXIT_DB);
687                                 }
688                                 recomp_data.size = destLen;
689                         }
690         
691                         // write the converted record to the target database
692                         if (out_key.size > 0) {
693         
694                                 // If we compressed the output, write recomp_data instead of out_data
695                                 if (compressed) {
696                                         // printf("DB: %02x , out_keylen: %-3d , out_datalen: %-10d , dataptr: %012lx \033[31m(compressed)\033[0m\n", which_cdb, (int)out_key.size, (int)recomp_data.size, (long unsigned int)recomp_data.data);
697                                         ret = dst_dbp->put(dst_dbp, NULL, &out_key, &recomp_data, 0);
698                                 }
699                                 else {
700                                         // printf("DB: %02x , out_keylen: %-3d , out_datalen: %-10d , dataptr: %012lx\n", which_cdb, (int)out_key.size, (int)out_data.size, (long unsigned int)out_data.data);
701                                         ret = dst_dbp->put(dst_dbp, NULL, &out_key, &out_data, 0);
702                                 }
703         
704                                 if (ret) {
705                                         printf("db: cdb_put(%d): %s", which_cdb, db_strerror(ret));
706                                         exit(CTDLEXIT_DB);
707                                 }
708                         }
709                         else {
710                                 printf("\033[31moutput keylen=%d , skipping record\033[0m\n", out_key.size);
711                         }
712                 }
713         }
714
715         if (ret != DB_NOTFOUND) {
716                 printf("db: db_get: %s\n", db_strerror(ret));
717                 printf("db: exit code %d\n", ret);
718                 exit(CTDLEXIT_DB);
719         }
720
721         printf("%d rows\n", num_rows);
722
723         // free any leftover out_data pointers
724         free(out_key.data);
725         free(out_data.data);
726         free(uncomp_data.data);
727         free(recomp_data.data);
728
729         // ...and close the database (table)
730         printf("\033[33m\033[1mdb: closing source %02x\033[0m\n", which_cdb);
731         ret = src_dbp->close(src_dbp, 0);
732         if (ret) {
733                 printf("db: db_close: %s\n", db_strerror(ret));
734         }
735
736         printf("\033[33m\033[1mdb: closing destination %02x\033[0m\n", which_cdb);
737         ret = dst_dbp->close(dst_dbp, 0);
738         if (ret) {
739                 printf("db: db_close: %s\n", db_strerror(ret));
740         }
741
742         printf("\n");
743
744 }
745
746
747 int main(int argc, char **argv) {
748         char *src_dir = NULL;
749         char *dst_dir = NULL;
750         int confirmed = 0;
751         static DB_ENV *src_dbenv;               // Source DB environment (global)
752         static DB_ENV *dst_dbenv;               // Source DB environment (global)
753
754         // Check to make sure we're running on the target 64-bit system
755         if (sizeof(void *) != 8) {
756                 fprintf(stderr, "%s: this is a %ld-bit system.\n", argv[0], sizeof(void *)*8);
757                 fprintf(stderr, "%s: you must run this on a 64-bit system, onto which a 32-bit database has been copied.\n", argv[0]);
758                 exit(1);
759         }
760
761         // Parse command line
762         int a;
763         while ((a = getopt(argc, argv, "s:d:y")) != EOF) {
764                 switch (a) {
765                 case 's':
766                         src_dir = optarg;
767                         break;
768                 case 'd':
769                         dst_dir = optarg;
770                         break;
771                 case 'y':
772                         confirmed = 1;
773                         break;
774                 default:
775                         fprintf(stderr, "%s: usage: %s -s source_dir -d dest_dir\n", argv[0], argv[0]);
776                         exit(2);
777                 }
778         }
779
780         // Warn the user
781         printf("------------------------------------------------------------------------\n");
782         printf("ctdl3264 converts a Citadel database written on a 32-bit system to one  \n");
783         printf("that can be run on a 64-bit system.  It is intended to be run OFFLINE.  \n");
784         printf("Neither the source nor the target data directories should be mounted by \n");
785         printf("a running Citadel server.  We \033[1mguarantee\033[0m data corruption if you do not   \n");
786         printf("observe this warning!  The source [-s] directory should contain a copy  \n");
787         printf("of the database from your 32-bit system.  The destination [-d] directory\n");
788         printf("should be empty and will receive your 64-bit database.                  \n");
789         printf("------------------------------------------------------------------------\n");
790         printf("     Source 32-bit directory: %s\n", src_dir);
791         printf("Destination 64-bit directory: %s\n", dst_dir);
792         printf("------------------------------------------------------------------------\n");
793
794         if (confirmed == 1) {
795                 printf("You have specified the [-y] flag, so processing will continue.\n");
796         }
797         else {
798                 printf("Please read [ https://www.citadel.org/ctdl3264.html ] to learn how to proceed.\n");
799                 exit(0);
800         }
801
802         src_dbenv = open_dbenv(src_dir);
803         dst_dbenv = open_dbenv(dst_dir);
804         //for (int i = 0; i < MAXCDB; ++i) {
805                 //convert_table(i, src_dbenv, dst_dbenv);
806         //}
807         convert_table(7, src_dbenv, dst_dbenv);
808         close_dbenv(src_dbenv);
809         close_dbenv(dst_dbenv);
810
811         exit(0);
812 }