d55f8e9de1c9ad8f424318a93a72d6e299e75a4a
[citadel.git] / citadel / modules / migrate / serv_migrate.c
1 /*
2  * This module dumps and/or loads the Citadel database in XML format.
3  *
4  * Copyright (c) 1987-2018 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 /*
16  * Explanation of <progress> tags:
17  *
18  * 0%              nothing
19  * 2%              finished exporting configuration
20  * 7%              finished exporting users
21  * 12%             finished exporting openids
22  * 17%             finished exporting rooms
23  * 18%             finished exporting floors
24  * 25%             finished exporting visits
25  * 100%            finished exporting messages
26  */
27
28 #include "sysdep.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <pwd.h>
35 #include <errno.h>
36 #include <sys/types.h>
37
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
48
49 #include <sys/wait.h>
50 #include <string.h>
51 #include <ctype.h>
52 #include <limits.h>
53 #include <expat.h>
54 #include <libcitadel.h>
55 #include "citadel.h"
56 #include "server.h"
57 #include "citserver.h"
58 #include "support.h"
59 #include "config.h"
60 #include "database.h"
61 #include "msgbase.h"
62 #include "user_ops.h"
63 #include "euidindex.h"
64 #include "ctdl_module.h"
65
66 #define END_OF_MESSAGE  "---eom---dbd---"
67
68 char migr_tempfilename1[PATH_MAX];
69 char migr_tempfilename2[PATH_MAX];
70 FILE *migr_global_message_list;
71 int total_msgs = 0;
72 char *ikey = NULL;                      // If we're importing a config key we store it here.
73
74
75 /******************************************************************************
76  *        Code which implements the export appears in this section            *
77  ******************************************************************************/
78
79 /*
80  * Output a string to the client with these characters escaped:  & < > " '
81  */
82 void xml_strout(char *str) {
83
84         char *c = str;
85
86         if (str == NULL) {
87                 return;
88         }
89
90         while (*c != 0) {
91                 if (*c == '\"') {
92                         client_write(HKEY("&quot;"));
93                 }
94                 else if (*c == '\'') {
95                         client_write(HKEY("&apos;"));
96                 }
97                 else if (*c == '<') {
98                         client_write(HKEY("&lt;"));
99                 }
100                 else if (*c == '>') {
101                         client_write(HKEY("&gt;"));
102                 }
103                 else if (*c == '&') {
104                         client_write(HKEY("&amp;"));
105                 }
106                 else {
107                         client_write(c, 1);
108                 }
109                 ++c;
110         }
111 }
112
113
114 /*
115  * Export a user record as XML
116  */
117 void migr_export_users_backend(struct ctdluser *buf, void *data) {
118         client_write(HKEY("<user>\n"));
119         cprintf("<u_version>%d</u_version>\n", buf->version);
120         cprintf("<u_uid>%ld</u_uid>\n", (long)buf->uid);
121         client_write(HKEY("<u_password>"));     xml_strout(buf->password);              client_write(HKEY("</u_password>\n"));
122         cprintf("<u_flags>%u</u_flags>\n", buf->flags);
123         cprintf("<u_timescalled>%ld</u_timescalled>\n", buf->timescalled);
124         cprintf("<u_posted>%ld</u_posted>\n", buf->posted);
125         cprintf("<u_axlevel>%d</u_axlevel>\n", buf->axlevel);
126         cprintf("<u_usernum>%ld</u_usernum>\n", buf->usernum);
127         cprintf("<u_lastcall>%ld</u_lastcall>\n", (long)buf->lastcall);
128         cprintf("<u_USuserpurge>%d</u_USuserpurge>\n", buf->USuserpurge);
129         client_write(HKEY("<u_fullname>"));     xml_strout(buf->fullname);              client_write(HKEY("</u_fullname>\n"));
130         cprintf("<u_msgnum_bio>%ld</u_msgnum_bio>\n", buf->msgnum_bio);
131         cprintf("<u_msgnum_pic>%ld</u_msgnum_pic>\n", buf->msgnum_pic);
132         client_write(HKEY("</user>\n"));
133 }
134
135
136 void migr_export_users(void) {
137         ForEachUser(migr_export_users_backend, NULL);
138 }
139
140
141 void migr_export_room_msg(long msgnum, void *userdata) {
142         cprintf("%ld\n", msgnum);
143         fprintf(migr_global_message_list, "%ld\n", msgnum);
144 }
145
146
147 void migr_export_rooms_backend(struct ctdlroom *buf, void *data) {
148         client_write(HKEY("<room>\n"));
149         client_write(HKEY("<QRname>")); xml_strout(buf->QRname);        client_write(HKEY("</QRname>\n"));
150         client_write(HKEY("<QRpasswd>"));       xml_strout(buf->QRpasswd);      client_write(HKEY("</QRpasswd>\n"));
151         cprintf("<QRroomaide>%ld</QRroomaide>\n", buf->QRroomaide);
152         cprintf("<QRhighest>%ld</QRhighest>\n", buf->QRhighest);
153         cprintf("<QRgen>%ld</QRgen>\n", (long)buf->QRgen);
154         cprintf("<QRflags>%u</QRflags>\n", buf->QRflags);
155         if (buf->QRflags & QR_DIRECTORY) {
156                 client_write(HKEY("<QRdirname>"));
157                 xml_strout(buf->QRdirname);
158                 client_write(HKEY("</QRdirname>\n"));
159         }
160         cprintf("<QRfloor>%d</QRfloor>\n", buf->QRfloor);
161         cprintf("<QRmtime>%ld</QRmtime>\n", (long)buf->QRmtime);
162         cprintf("<QRexpire_mode>%d</QRexpire_mode>\n", buf->QRep.expire_mode);
163         cprintf("<QRexpire_value>%d</QRexpire_value>\n", buf->QRep.expire_value);
164         cprintf("<QRnumber>%ld</QRnumber>\n", buf->QRnumber);
165         cprintf("<QRorder>%d</QRorder>\n", buf->QRorder);
166         cprintf("<QRflags2>%u</QRflags2>\n", buf->QRflags2);
167         cprintf("<QRdefaultview>%d</QRdefaultview>\n", buf->QRdefaultview);
168         cprintf("<msgnum_info>%ld</msgnum_info>\n", buf->msgnum_info);
169         cprintf("<msgnum_pic>%ld</msgnum_pic>\n", buf->msgnum_pic);
170         client_write(HKEY("</room>\n"));
171
172         /* message list goes inside this tag */
173
174         CtdlGetRoom(&CC->room, buf->QRname);
175         client_write(HKEY("<room_messages>"));
176         client_write(HKEY("<FRname>")); xml_strout(CC->room.QRname);    client_write(HKEY("</FRname>\n"));
177         client_write(HKEY("<FRmsglist>"));
178         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, migr_export_room_msg, NULL);
179         client_write(HKEY("</FRmsglist>\n"));
180         client_write(HKEY("</room_messages>\n"));
181
182
183 }
184
185
186 void migr_export_rooms(void) {
187         char cmd[SIZ];
188         migr_global_message_list = fopen(migr_tempfilename1, "w");
189         if (migr_global_message_list != NULL) {
190                 CtdlForEachRoom(migr_export_rooms_backend, NULL);
191                 fclose(migr_global_message_list);
192         }
193
194         /*
195          * Process the 'global' message list.  (Sort it and remove dups.
196          * Dups are ok because a message may be in more than one room, but
197          * this will be handled by exporting the reference count, not by
198          * exporting the message multiple times.)
199          */
200         snprintf(cmd, sizeof cmd, "sort -n <%s >%s", migr_tempfilename1, migr_tempfilename2);
201         if (system(cmd) != 0) syslog(LOG_ALERT, "Error %d", errno);
202         snprintf(cmd, sizeof cmd, "uniq <%s >%s", migr_tempfilename2, migr_tempfilename1);
203         if (system(cmd) != 0) syslog(LOG_ALERT, "Error %d", errno);
204
205
206         snprintf(cmd, sizeof cmd, "wc -l %s", migr_tempfilename1);
207         FILE *fp = popen(cmd, "r");
208         if (fp) {
209                 fgets(cmd, sizeof cmd, fp);
210                 pclose(fp);
211                 total_msgs = atoi(cmd);
212         }
213         else {
214                 total_msgs = 1; // any nonzero just to keep it from barfing
215         }
216         syslog(LOG_DEBUG, "Total messages to be exported: %d", total_msgs);
217 }
218
219
220 void migr_export_floors(void) {
221         struct floor qfbuf, *buf;
222         int i;
223
224         for (i=0; i < MAXFLOORS; ++i) {
225                 client_write(HKEY("<floor>\n"));
226                 cprintf("<f_num>%d</f_num>\n", i);
227                 CtdlGetFloor(&qfbuf, i);
228                 buf = &qfbuf;
229                 cprintf("<f_flags>%u</f_flags>\n", buf->f_flags);
230                 client_write(HKEY("<f_name>")); xml_strout(buf->f_name); client_write(HKEY("</f_name>\n"));
231                 cprintf("<f_ref_count>%d</f_ref_count>\n", buf->f_ref_count);
232                 cprintf("<f_ep_expire_mode>%d</f_ep_expire_mode>\n", buf->f_ep.expire_mode);
233                 cprintf("<f_ep_expire_value>%d</f_ep_expire_value>\n", buf->f_ep.expire_value);
234                 client_write(HKEY("</floor>\n"));
235         }
236 }
237
238
239 /*
240  * Return nonzero if the supplied string contains only characters which are valid in a sequence set.
241  */
242 int is_sequence_set(char *s) {
243         if (!s) return(0);
244
245         char *c = s;
246         char ch;
247         while (ch = *c++, ch) {
248                 if (!strchr("0123456789*,:", ch)) {
249                         return(0);
250                 }
251         }
252         return(1);
253 }
254
255
256 /* 
257  *  Traverse the visits file...
258  */
259 void migr_export_visits(void) {
260         visit vbuf;
261         struct cdbdata *cdbv;
262
263         cdb_rewind(CDB_VISIT);
264
265         while (cdbv = cdb_next_item(CDB_VISIT), cdbv != NULL) {
266                 memset(&vbuf, 0, sizeof(visit));
267                 memcpy(&vbuf, cdbv->ptr,
268                        ((cdbv->len > sizeof(visit)) ?
269                         sizeof(visit) : cdbv->len));
270                 cdb_free(cdbv);
271
272                 client_write(HKEY("<visit>\n"));
273                 cprintf("<v_roomnum>%ld</v_roomnum>\n", vbuf.v_roomnum);
274                 cprintf("<v_roomgen>%ld</v_roomgen>\n", vbuf.v_roomgen);
275                 cprintf("<v_usernum>%ld</v_usernum>\n", vbuf.v_usernum);
276
277                 client_write(HKEY("<v_seen>"));
278                 if ( (!IsEmptyStr(vbuf.v_seen)) && (is_sequence_set(vbuf.v_seen)) ) {
279                         xml_strout(vbuf.v_seen);
280                 }
281                 else {
282                         cprintf("%ld", vbuf.v_lastseen);
283                 }
284                 client_write(HKEY("</v_seen>"));
285
286                 if ( (!IsEmptyStr(vbuf.v_answered)) && (is_sequence_set(vbuf.v_answered)) ) {
287                         client_write(HKEY("<v_answered>"));
288                         xml_strout(vbuf.v_answered);
289                         client_write(HKEY("</v_answered>\n"));
290                 }
291
292                 cprintf("<v_flags>%u</v_flags>\n", vbuf.v_flags);
293                 cprintf("<v_view>%d</v_view>\n", vbuf.v_view);
294                 client_write(HKEY("</visit>\n"));
295         }
296 }
297
298
299 void migr_export_message(long msgnum) {
300         struct MetaData smi;
301         struct CtdlMessage *msg;
302         struct ser_ret smr;
303
304         /* We can use a static buffer here because there will never be more than
305          * one of this operation happening at any given time, and it's really best
306          * to just keep it allocated once instead of torturing malloc/free.
307          * Call this function with msgnum "-1" to free the buffer when finished.
308          */
309         static int encoded_alloc = 0;
310         static char *encoded_msg = NULL;
311
312         if (msgnum < 0) {
313                 if ((encoded_alloc == 0) && (encoded_msg != NULL)) {
314                         free(encoded_msg);
315                         encoded_alloc = 0;
316                         encoded_msg = NULL;
317                 }
318                 return;
319         }
320
321         /* Ok, here we go ... */
322
323         msg = CtdlFetchMessage(msgnum, 1, 0);
324         if (msg == NULL) return;        /* fail silently */
325
326         client_write(HKEY("<message>\n"));
327         GetMetaData(&smi, msgnum);
328         cprintf("<msg_msgnum>%ld</msg_msgnum>\n", msgnum);
329         cprintf("<msg_meta_refcount>%d</msg_meta_refcount>\n", smi.meta_refcount);
330         cprintf("<msg_meta_rfc822_length>%ld</msg_meta_rfc822_length>\n", smi.meta_rfc822_length);
331         client_write(HKEY("<msg_meta_content_type>")); xml_strout(smi.meta_content_type); client_write(HKEY("</msg_meta_content_type>\n"));
332
333         client_write(HKEY("<msg_text>"));
334         CtdlSerializeMessage(&smr, msg);
335         CM_Free(msg);
336
337         /* Predict the buffer size we need.  Expand the buffer if necessary. */
338         int encoded_len = smr.len * 15 / 10 ;
339         if (encoded_len > encoded_alloc) {
340                 encoded_alloc = encoded_len;
341                 encoded_msg = realloc(encoded_msg, encoded_alloc);
342         }
343
344         if (encoded_msg == NULL) {
345                 /* Questionable hack that hopes it'll work next time and we only lose one message */
346                 encoded_alloc = 0;
347         }
348         else {
349                 /* Once we do the encoding we know the exact size */
350                 encoded_len = CtdlEncodeBase64(encoded_msg, (char *)smr.ser, smr.len, 1);
351                 client_write(encoded_msg, encoded_len);
352         }
353
354         free(smr.ser);
355
356         client_write(HKEY("</msg_text>\n"));
357         client_write(HKEY("</message>\n"));
358 }
359
360
361 void migr_export_openids(void) {
362         struct cdbdata *cdboi;
363         long usernum;
364         char url[512];
365
366         cdb_rewind(CDB_EXTAUTH);
367         while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
368                 if (cdboi->len > sizeof(long)) {
369                         client_write(HKEY("<openid>\n"));
370                         memcpy(&usernum, cdboi->ptr, sizeof(long));
371                         snprintf(url, sizeof url, "%s", (cdboi->ptr)+sizeof(long) );
372                         client_write(HKEY("<oid_url>"));
373                         xml_strout(url);
374                         client_write(HKEY("</oid_url>\n"));
375                         cprintf("<oid_usernum>%ld</oid_usernum>\n", usernum);
376                         client_write(HKEY("</openid>\n"));
377                 }
378                 cdb_free(cdboi);
379         }
380 }
381
382
383 void migr_export_configs(void) {
384         struct cdbdata *cdbcfg;
385         int keylen = 0;
386         char *key = NULL;
387         char *value = NULL;
388
389         cdb_rewind(CDB_CONFIG);
390         while (cdbcfg = cdb_next_item(CDB_CONFIG), cdbcfg != NULL) {
391
392                 keylen = strlen(cdbcfg->ptr);
393                 key = cdbcfg->ptr;
394                 value = cdbcfg->ptr + keylen + 1;
395
396                 client_write("<config key=\"", 13);
397                 xml_strout(key);
398                 client_write("\">", 2);
399                 xml_strout(value);
400                 client_write("</config>\n", 10);
401                 cdb_free(cdbcfg);
402         }
403 }
404
405
406 void migr_export_messages(void) {
407         char buf[SIZ];
408         long msgnum;
409         int count = 0;
410         int progress = 0;
411         int prev_progress = 0;
412         CitContext *Ctx;
413
414         Ctx = CC;
415         migr_global_message_list = fopen(migr_tempfilename1, "r");
416         if (migr_global_message_list != NULL) {
417                 syslog(LOG_INFO, "Opened %s", migr_tempfilename1);
418                 while ((Ctx->kill_me == 0) && 
419                        (fgets(buf, sizeof(buf), migr_global_message_list) != NULL)) {
420                         msgnum = atol(buf);
421                         if (msgnum > 0L) {
422                                 migr_export_message(msgnum);
423                                 ++count;
424                         }
425                         progress = (count * 74 / total_msgs) + 25 ;
426                         if ((progress > prev_progress) && (progress < 100)) {
427                                 cprintf("<progress>%d</progress>\n", progress);
428                         }
429                         prev_progress = progress;
430                 }
431                 fclose(migr_global_message_list);
432         }
433         if (Ctx->kill_me == 0) {
434                 syslog(LOG_INFO, "Exported %d messages.", count);
435         }
436         else {
437                 syslog(LOG_ERR, "Export aborted due to client disconnect!");
438         }
439
440         migr_export_message(-1L);       /* This frees the encoding buffer */
441 }
442
443
444 void migr_do_export(void) {
445         CitContext *Ctx;
446
447         Ctx = CC;
448         cprintf("%d Exporting all Citadel databases.\n", LISTING_FOLLOWS);
449         Ctx->dont_term = 1;
450
451         client_write(HKEY("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"));
452         client_write(HKEY("<citadel_migrate_data>\n"));
453         cprintf("<version>%d</version>\n", REV_LEVEL);
454         cprintf("<progress>%d</progress>\n", 0);
455
456         /* export the configuration database */
457         migr_export_configs();
458         cprintf("<progress>%d</progress>\n", 2);
459         
460         if (Ctx->kill_me == 0)  migr_export_users();
461         cprintf("<progress>%d</progress>\n", 7);
462         if (Ctx->kill_me == 0)  migr_export_openids();
463         cprintf("<progress>%d</progress>\n", 12);
464         if (Ctx->kill_me == 0)  migr_export_rooms();
465         cprintf("<progress>%d</progress>\n", 17);
466         if (Ctx->kill_me == 0)  migr_export_floors();
467         cprintf("<progress>%d</progress>\n", 18);
468         if (Ctx->kill_me == 0)  migr_export_visits();
469         cprintf("<progress>%d</progress>\n", 25);
470         if (Ctx->kill_me == 0)  migr_export_messages();
471         client_write(HKEY("</citadel_migrate_data>\n"));
472         cprintf("<progress>%d</progress>\n", 100);
473         client_write(HKEY("000\n"));
474         Ctx->dont_term = 0;
475 }
476
477
478 /******************************************************************************
479  *                              Import code                                   *
480  *    Here's the code that implements the import side.  It's going to end up  *
481  *        being one big loop with lots of global variables.  I don't care.    *
482  * You wouldn't run multiple concurrent imports anyway.  If this offends your *
483  * delicate sensibilities  then go rewrite it in Ruby on Rails or something.  *
484  ******************************************************************************/
485
486
487 int citadel_migrate_data = 0;           /* Are we inside a <citadel_migrate_data> tag pair? */
488 StrBuf *migr_chardata = NULL;
489 StrBuf *migr_MsgData = NULL;
490 struct ctdluser usbuf;
491 struct ctdlroom qrbuf;
492 char openid_url[512];
493 long openid_usernum = 0;
494 char FRname[ROOMNAMELEN];
495 struct floor flbuf;
496 int floornum = 0;
497 visit vbuf;
498 struct MetaData smi;
499 long import_msgnum = 0;
500
501 /*
502  * This callback stores up the data which appears in between tags.
503  */
504 void migr_xml_chardata(void *data, const XML_Char *s, int len)
505 {
506         StrBufAppendBufPlain(migr_chardata, s, len, 0);
507 }
508
509
510 void migr_xml_start(void *data, const char *el, const char **attr) {
511         int i;
512
513         /*** GENERAL STUFF ***/
514
515         /* Reset chardata_len to zero and init buffer */
516         FlushStrBuf(migr_chardata);
517         FlushStrBuf(migr_MsgData);
518
519         if (!strcasecmp(el, "citadel_migrate_data")) {
520                 ++citadel_migrate_data;
521
522                 /* As soon as it looks like the input data is a genuine Citadel XML export,
523                  * whack the existing database on disk to make room for the new one.
524                  */
525                 if (citadel_migrate_data == 1) {
526                         for (i = 0; i < MAXCDB; ++i) {
527                                 cdb_trunc(i);
528                         }
529                 }
530                 return;
531         }
532
533         if (citadel_migrate_data != 1) {
534                 syslog(LOG_ALERT, "Out-of-sequence tag <%s> detected.  Warning: ODD-DATA!", el);
535                 return;
536         }
537
538         /* When we begin receiving XML for one of these record types, clear out the associated
539          * buffer so we don't accidentally carry over any data from a previous record.
540          */
541         if (!strcasecmp(el, "user"))                    memset(&usbuf, 0, sizeof (struct ctdluser));
542         else if (!strcasecmp(el, "openid"))             memset(openid_url, 0, sizeof openid_url);
543         else if (!strcasecmp(el, "room"))               memset(&qrbuf, 0, sizeof (struct ctdlroom));
544         else if (!strcasecmp(el, "room_messages"))      memset(FRname, 0, sizeof FRname);
545         else if (!strcasecmp(el, "floor"))              memset(&flbuf, 0, sizeof (struct floor));
546         else if (!strcasecmp(el, "visit"))              memset(&vbuf, 0, sizeof (visit));
547
548         else if (!strcasecmp(el, "message")) {
549                 memset(&smi, 0, sizeof (struct MetaData));
550                 import_msgnum = 0;
551         }
552         else if (!strcasecmp(el, "config")) {
553                 if (ikey != NULL) {
554                         free(ikey);
555                         ikey = NULL;
556                 }
557                 while (*attr) {
558                         if (!strcasecmp(attr[0], "key")) {
559                                 ikey = strdup(attr[1]);
560                         }
561                         attr += 2;
562                 }
563         }
564
565 }
566
567
568 int migr_userrecord(void *data, const char *el)
569 {
570         if (!strcasecmp(el, "u_version"))                       usbuf.version = atoi(ChrPtr(migr_chardata));
571         else if (!strcasecmp(el, "u_uid"))                      usbuf.uid = atol(ChrPtr(migr_chardata));
572         else if (!strcasecmp(el, "u_password"))                 safestrncpy(usbuf.password, ChrPtr(migr_chardata), sizeof usbuf.password);
573         else if (!strcasecmp(el, "u_flags"))                    usbuf.flags = atoi(ChrPtr(migr_chardata));
574         else if (!strcasecmp(el, "u_timescalled"))              usbuf.timescalled = atol(ChrPtr(migr_chardata));
575         else if (!strcasecmp(el, "u_posted"))                   usbuf.posted = atol(ChrPtr(migr_chardata));
576         else if (!strcasecmp(el, "u_axlevel"))                  usbuf.axlevel = atoi(ChrPtr(migr_chardata));
577         else if (!strcasecmp(el, "u_usernum"))                  usbuf.usernum = atol(ChrPtr(migr_chardata));
578         else if (!strcasecmp(el, "u_lastcall"))                 usbuf.lastcall = atol(ChrPtr(migr_chardata));
579         else if (!strcasecmp(el, "u_USuserpurge"))              usbuf.USuserpurge = atoi(ChrPtr(migr_chardata));
580         else if (!strcasecmp(el, "u_fullname"))                 safestrncpy(usbuf.fullname, ChrPtr(migr_chardata), sizeof usbuf.fullname);
581         else if (!strcasecmp(el, "u_msgnum_bio"))               usbuf.msgnum_bio = atol(ChrPtr(migr_chardata));
582         else if (!strcasecmp(el, "u_msgnum_pic"))               usbuf.msgnum_pic = atol(ChrPtr(migr_chardata));
583         else return 0;
584         return 1;
585 }
586
587
588 int migr_roomrecord(void *data, const char *el)
589 {
590         if (!strcasecmp(el, "QRname"))                          safestrncpy(qrbuf.QRname, ChrPtr(migr_chardata), sizeof qrbuf.QRname);
591         else if (!strcasecmp(el, "QRpasswd"))                   safestrncpy(qrbuf.QRpasswd, ChrPtr(migr_chardata), sizeof qrbuf.QRpasswd);
592         else if (!strcasecmp(el, "QRroomaide"))                 qrbuf.QRroomaide = atol(ChrPtr(migr_chardata));
593         else if (!strcasecmp(el, "QRhighest"))                  qrbuf.QRhighest = atol(ChrPtr(migr_chardata));
594         else if (!strcasecmp(el, "QRgen"))                      qrbuf.QRgen = atol(ChrPtr(migr_chardata));
595         else if (!strcasecmp(el, "QRflags"))                    qrbuf.QRflags = atoi(ChrPtr(migr_chardata));
596         else if (!strcasecmp(el, "QRdirname"))                  safestrncpy(qrbuf.QRdirname, ChrPtr(migr_chardata), sizeof qrbuf.QRdirname);
597         else if (!strcasecmp(el, "QRfloor"))                    qrbuf.QRfloor = atoi(ChrPtr(migr_chardata));
598         else if (!strcasecmp(el, "QRmtime"))                    qrbuf.QRmtime = atol(ChrPtr(migr_chardata));
599         else if (!strcasecmp(el, "QRexpire_mode"))              qrbuf.QRep.expire_mode = atoi(ChrPtr(migr_chardata));
600         else if (!strcasecmp(el, "QRexpire_value"))             qrbuf.QRep.expire_value = atoi(ChrPtr(migr_chardata));
601         else if (!strcasecmp(el, "QRnumber"))                   qrbuf.QRnumber = atol(ChrPtr(migr_chardata));
602         else if (!strcasecmp(el, "QRorder"))                    qrbuf.QRorder = atoi(ChrPtr(migr_chardata));
603         else if (!strcasecmp(el, "QRflags2"))                   qrbuf.QRflags2 = atoi(ChrPtr(migr_chardata));
604         else if (!strcasecmp(el, "QRdefaultview"))              qrbuf.QRdefaultview = atoi(ChrPtr(migr_chardata));
605         else if (!strcasecmp(el, "msgnum_info"))                qrbuf.msgnum_info = atol(ChrPtr(migr_chardata));
606         else if (!strcasecmp(el, "msgnum_pic"))                 qrbuf.msgnum_pic = atol(ChrPtr(migr_chardata));
607         else return 0;
608         return 1;
609 }
610
611
612 int migr_floorrecord(void *data, const char *el)
613 {
614         if (!strcasecmp(el, "f_num"))                           floornum = atoi(ChrPtr(migr_chardata));
615         else if (!strcasecmp(el, "f_flags"))                    flbuf.f_flags = atoi(ChrPtr(migr_chardata));
616         else if (!strcasecmp(el, "f_name"))                     safestrncpy(flbuf.f_name, ChrPtr(migr_chardata), sizeof flbuf.f_name);
617         else if (!strcasecmp(el, "f_ref_count"))                flbuf.f_ref_count = atoi(ChrPtr(migr_chardata));
618         else if (!strcasecmp(el, "f_ep_expire_mode"))           flbuf.f_ep.expire_mode = atoi(ChrPtr(migr_chardata));
619         else if (!strcasecmp(el, "f_ep_expire_value"))          flbuf.f_ep.expire_value = atoi(ChrPtr(migr_chardata));
620         else return 0;
621         return 1;
622 }
623
624
625 int migr_visitrecord(void *data, const char *el)
626 {
627         if (!strcasecmp(el, "v_roomnum"))                       vbuf.v_roomnum = atol(ChrPtr(migr_chardata));
628         else if (!strcasecmp(el, "v_roomgen"))                  vbuf.v_roomgen = atol(ChrPtr(migr_chardata));
629         else if (!strcasecmp(el, "v_usernum"))                  vbuf.v_usernum = atol(ChrPtr(migr_chardata));
630
631         else if (!strcasecmp(el, "v_seen")) {
632                 int is_textual_seen = 0;
633                 int i;
634                 int max = StrLength(migr_chardata);
635
636                 vbuf.v_lastseen = atol(ChrPtr(migr_chardata));
637                 is_textual_seen = 0;
638                 for (i=0; i < max; ++i) 
639                         if (!isdigit(ChrPtr(migr_chardata)[i]))
640                                 is_textual_seen = 1;
641                 if (is_textual_seen)
642                         safestrncpy(vbuf.v_seen, ChrPtr(migr_chardata), sizeof vbuf.v_seen);
643         }
644
645         else if (!strcasecmp(el, "v_answered"))                 safestrncpy(vbuf.v_answered, ChrPtr(migr_chardata), sizeof vbuf.v_answered);
646         else if (!strcasecmp(el, "v_flags"))                    vbuf.v_flags = atoi(ChrPtr(migr_chardata));
647         else if (!strcasecmp(el, "v_view"))                     vbuf.v_view = atoi(ChrPtr(migr_chardata));
648         else return 0;
649         return 1;
650 }
651
652
653 void migr_xml_end(void *data, const char *el)
654 {
655         const char *ptr;
656         int msgcount = 0;
657         long msgnum = 0L;
658         long *msglist = NULL;
659         int msglist_alloc = 0;
660         /*** GENERAL STUFF ***/
661
662         if (!strcasecmp(el, "citadel_migrate_data")) {
663                 --citadel_migrate_data;
664                 return;
665         }
666
667         if (citadel_migrate_data != 1) {
668                 syslog(LOG_ALERT, "Out-of-sequence tag <%s> detected.  Warning: ODD-DATA!", el);
669                 return;
670         }
671
672         // syslog(LOG_DEBUG, "END TAG: <%s> DATA: <%s>\n", el, (migr_chardata_len ? migr_chardata : ""));
673
674         /*** CONFIG ***/
675
676         if (!strcasecmp(el, "config"))
677         {
678                 syslog(LOG_DEBUG, "Imported config key=%s", ikey);
679
680                 if (ikey != NULL) {
681                         CtdlSetConfigStr(ikey, (char *)ChrPtr(migr_chardata));
682                         free(ikey);
683                         ikey = NULL;
684                 }
685                 else {
686                         syslog(LOG_INFO, "Closed a <config> tag but no key name was supplied.");
687                 }
688         }
689
690         /*** USER ***/
691         else if ((!strncasecmp(el, HKEY("u_"))) && 
692                  migr_userrecord(data, el))
693                 ; /* Nothing to do anymore */
694         else if (!strcasecmp(el, "user")) {
695                 CtdlPutUser(&usbuf);
696                 syslog(LOG_INFO, "Imported user: %s", usbuf.fullname);
697         }
698
699         /*** OPENID ***/
700
701         else if (!strcasecmp(el, "oid_url"))                    safestrncpy(openid_url, ChrPtr(migr_chardata), sizeof openid_url);
702         else if (!strcasecmp(el, "oid_usernum"))                openid_usernum = atol(ChrPtr(migr_chardata));
703
704         else if (!strcasecmp(el, "openid")) {                   /* see serv_openid_rp.c for a description of the record format */
705                 char *oid_data;
706                 int oid_data_len;
707                 oid_data_len = sizeof(long) + strlen(openid_url) + 1;
708                 oid_data = malloc(oid_data_len);
709                 memcpy(oid_data, &openid_usernum, sizeof(long));
710                 memcpy(&oid_data[sizeof(long)], openid_url, strlen(openid_url) + 1);
711                 cdb_store(CDB_EXTAUTH, openid_url, strlen(openid_url), oid_data, oid_data_len);
712                 free(oid_data);
713                 syslog(LOG_INFO, "Imported OpenID: %s (%ld)", openid_url, openid_usernum);
714         }
715
716         /*** ROOM ***/
717         else if ((!strncasecmp(el, HKEY("QR"))) && 
718                  migr_roomrecord(data, el))
719                 ; /* Nothing to do anymore */
720         else if (!strcasecmp(el, "room")) {
721                 CtdlPutRoom(&qrbuf);
722                 syslog(LOG_INFO, "Imported room: %s", qrbuf.QRname);
723         }
724
725         /*** ROOM MESSAGE POINTERS ***/
726
727         else if (!strcasecmp(el, "FRname"))                     safestrncpy(FRname, ChrPtr(migr_chardata), sizeof FRname);
728
729         else if (!strcasecmp(el, "FRmsglist")) {
730                 if (!IsEmptyStr(FRname)) {
731                         msgcount = 0;
732                         msglist_alloc = 1000;
733                         msglist = malloc(sizeof(long) * msglist_alloc);
734
735                         syslog(LOG_DEBUG, "Message list for: %s", FRname);
736
737                         ptr = ChrPtr(migr_chardata);
738                         while (*ptr != 0) {
739                                 while ((*ptr != 0) && (!isdigit(*ptr))) {
740                                         ++ptr;
741                                 }
742                                 if ((*ptr != 0) && (isdigit(*ptr))) {
743                                         msgnum = atol(ptr);
744                                         if (msgnum > 0L) {
745                                                 if (msgcount >= msglist_alloc) {
746                                                         msglist_alloc *= 2;
747                                                         msglist = realloc(msglist, sizeof(long) * msglist_alloc);
748                                                 }
749                                                 msglist[msgcount++] = msgnum;
750                                                 }
751                                         }
752                                         while ((*ptr != 0) && (isdigit(*ptr))) {
753                                                 ++ptr;
754                                         }
755                                 }
756                         }
757                         if (msgcount > 0) {
758                                 CtdlSaveMsgPointersInRoom(FRname, msglist, msgcount, 0, NULL, 1);
759                         }
760                         free(msglist);
761                         msglist = NULL;
762                         msglist_alloc = 0;
763                         syslog(LOG_DEBUG, "Imported %d messages.", msgcount);
764                         if (server_shutting_down) {
765                                 return;
766                 }
767         }
768
769         /*** FLOORS ***/
770         else if ((!strncasecmp(el, HKEY("f_"))) && 
771                  migr_floorrecord(data, el))
772                 ; /* Nothing to do anymore */
773
774         else if (!strcasecmp(el, "floor")) {
775                 CtdlPutFloor(&flbuf, floornum);
776                 syslog(LOG_INFO, "Imported floor #%d (%s)", floornum, flbuf.f_name);
777         }
778
779         /*** VISITS ***/
780         else if ((!strncasecmp(el, HKEY("v_"))) && migr_visitrecord(data, el)) {
781                 ; /* Nothing to do anymore */
782         }
783         else if (!strcasecmp(el, "visit")) {
784                 put_visit(&vbuf);
785                 syslog(LOG_INFO, "Imported visit: %ld/%ld/%ld", vbuf.v_roomnum, vbuf.v_roomgen, vbuf.v_usernum);
786         }
787
788         /*** MESSAGES ***/
789         
790         else if (!strcasecmp(el, "msg_msgnum"))                 smi.meta_msgnum = import_msgnum = atol(ChrPtr(migr_chardata));
791         else if (!strcasecmp(el, "msg_meta_refcount"))          smi.meta_refcount = atoi(ChrPtr(migr_chardata));
792         else if (!strcasecmp(el, "msg_meta_rfc822_length"))     smi.meta_rfc822_length = atoi(ChrPtr(migr_chardata));
793         else if (!strcasecmp(el, "msg_meta_content_type"))      safestrncpy(smi.meta_content_type, ChrPtr(migr_chardata), sizeof smi.meta_content_type);
794
795         else if (!strcasecmp(el, "msg_text"))
796         {
797                 long rc;
798                 struct CtdlMessage *msg;
799
800                 FlushStrBuf(migr_MsgData);
801                 StrBufDecodeBase64To(migr_chardata, migr_MsgData);
802
803                 msg = CtdlDeserializeMessage(import_msgnum, -1,
804                                              ChrPtr(migr_MsgData), 
805                                              StrLength(migr_MsgData));
806                 if (msg != NULL) {
807                         rc = CtdlSaveThisMessage(msg, import_msgnum, 0);
808                         if (rc == 0) {
809                                 PutMetaData(&smi);
810                         }
811                         CM_Free(msg);
812                 }
813                 else {
814                         rc = -1;
815                 }
816
817                 syslog(LOG_INFO,
818                        "%s message #%ld, size=%d, refcount=%d, bodylength=%ld, content-type: %s",
819                        (rc!= 0)?"failed to import ":"Imported ",
820                        import_msgnum,
821                        StrLength(migr_MsgData),
822                        smi.meta_refcount,
823                        smi.meta_rfc822_length,
824                        smi.meta_content_type
825                 );
826                 memset(&smi, 0, sizeof(smi));
827         }
828
829         /*** MORE GENERAL STUFF ***/
830
831         FlushStrBuf(migr_chardata);
832 }
833
834
835 /*
836  * Import begins here
837  */
838 void migr_do_import(void) {
839         StrBuf *Buf;
840         XML_Parser xp;
841         int Finished = 0;
842         
843         unbuffer_output();
844         migr_chardata = NewStrBufPlain(NULL, SIZ * 20);
845         migr_MsgData = NewStrBufPlain(NULL, SIZ * 20);
846         Buf = NewStrBufPlain(NULL, SIZ);
847         xp = XML_ParserCreate(NULL);
848         if (!xp) {
849                 cprintf("%d Failed to create XML parser instance\n", ERROR+INTERNAL_ERROR);
850                 return;
851         }
852         XML_SetElementHandler(xp, migr_xml_start, migr_xml_end);
853         XML_SetCharacterDataHandler(xp, migr_xml_chardata);
854
855         CC->dont_term = 1;
856
857         cprintf("%d sock it to me\n", SEND_LISTING);
858         unbuffer_output();
859
860         client_set_inbound_buf(SIZ * 10);
861
862         while (!Finished && client_read_random_blob(Buf, -1) >= 0) {
863                 if ((StrLength(Buf) > 4) && !strcmp(ChrPtr(Buf) + StrLength(Buf) - 4, "000\n")) {
864                         Finished = 1;
865                         StrBufCutAt(Buf, StrLength(Buf) - 4, NULL);
866                 }
867                 if (server_shutting_down)
868                         break;  // Should we break or return?
869                 
870                 if (StrLength(Buf) == 0)
871                         continue;
872
873                 XML_Parse(xp, ChrPtr(Buf), StrLength(Buf), 0);
874                 FlushStrBuf(Buf);
875         }
876
877         XML_Parse(xp, "", 0, 1);
878         XML_ParserFree(xp);
879         FreeStrBuf(&Buf);
880         FreeStrBuf(&migr_chardata);
881         FreeStrBuf(&migr_MsgData);
882         rebuild_euid_index();
883         rebuild_usersbynumber();
884         CtdlSetConfigInt("MM_fulltext_wordbreaker", -1);        // Set an invalid wordbreaker to force re-indexing
885         CC->dont_term = 0;
886 }
887
888
889 /******************************************************************************
890  *                         Dispatcher, Common code                            *
891  ******************************************************************************/
892 /*
893  * Dump out the pathnames of directories which can be copied "as is"
894  */
895 void migr_do_listdirs(void) {
896         cprintf("%d Don't forget these:\n", LISTING_FOLLOWS);
897         cprintf("files|%s\n",           ctdl_file_dir);
898         cprintf("messages|%s\n",        ctdl_message_dir);
899         cprintf("keys|%s\n",            ctdl_key_dir);
900         cprintf("000\n");
901 }
902
903
904 /******************************************************************************
905  *                    Repair database integrity                               *
906  ******************************************************************************/
907
908 StrBuf *PlainMessageBuf = NULL;
909 HashList *UsedMessageIDS = NULL;
910
911 int migr_restore_message_metadata(long msgnum, int refcount)
912 {
913         CitContext *CCC = MyContext();
914         struct MetaData smi;
915         struct CtdlMessage *msg;
916         char *mptr = NULL;
917
918         /* We can use a static buffer here because there will never be more than
919          * one of this operation happening at any given time, and it's really best
920          * to just keep it allocated once instead of torturing malloc/free.
921          * Call this function with msgnum "-1" to free the buffer when finished.
922          */
923         static int encoded_alloc = 0;
924         static char *encoded_msg = NULL;
925
926         if (msgnum < 0) {
927                 if ((encoded_alloc == 0) && (encoded_msg != NULL)) {
928                         free(encoded_msg);
929                         encoded_alloc = 0;
930                         encoded_msg = NULL;
931                         // todo FreeStrBuf(&PlainMessageBuf); PlainMessageBuf = NULL;
932                 }
933                 return 0;
934         }
935
936         if (PlainMessageBuf == NULL) {
937                 PlainMessageBuf = NewStrBufPlain(NULL, 10*SIZ);
938         }
939
940         /* Ok, here we go ... */
941
942         msg = CtdlFetchMessage(msgnum, 1, 0);
943         if (msg == NULL) {
944                 return 1;
945         }
946
947         GetMetaData(&smi, msgnum);
948         smi.meta_msgnum = msgnum;
949         smi.meta_refcount = refcount;
950         
951         /* restore the content type from the message body: */
952         mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
953         if (mptr != NULL) {
954                 char *aptr;
955                 safestrncpy(smi.meta_content_type, &mptr[13], sizeof smi.meta_content_type);
956                 striplt(smi.meta_content_type);
957                 aptr = smi.meta_content_type;
958                 while (!IsEmptyStr(aptr)) {
959                         if ((*aptr == ';')
960                             || (*aptr == ' ')
961                             || (*aptr == 13)
962                             || (*aptr == 10)) {
963                                 memset(aptr, 0, sizeof(smi.meta_content_type) - (aptr - smi.meta_content_type));
964                         }
965                         else aptr++;
966                 }
967         }
968
969         CCC->redirect_buffer = PlainMessageBuf;
970         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
971         smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
972         CCC->redirect_buffer = NULL;
973
974         syslog(LOG_INFO,
975                "Setting message #%ld meta data to: refcount=%d, bodylength=%ld, content-type: %s",
976                smi.meta_msgnum,
977                smi.meta_refcount,
978                smi.meta_rfc822_length,
979                smi.meta_content_type
980         );
981
982         PutMetaData(&smi);
983
984         CM_Free(msg);
985
986         return 0;
987 }
988
989
990 void migr_check_room_msg(long msgnum, void *userdata) {
991         fprintf(migr_global_message_list, "%ld %s\n", msgnum, CC->room.QRname);
992 }
993
994
995 void migr_check_rooms_backend(struct ctdlroom *buf, void *data) {
996
997         /* message list goes inside this tag */
998
999         CtdlGetRoom(&CC->room, buf->QRname);
1000         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, migr_check_room_msg, NULL);
1001 }
1002
1003
1004 void RemoveMessagesFromRooms(StrBuf *RoomNameVec, long msgnum) {
1005         struct MetaData smi;
1006         const char *Pos = NULL;
1007         StrBuf *oneRoom = NewStrBuf();
1008
1009         syslog(LOG_INFO, "removing message pointer %ld from these rooms: %s", msgnum, ChrPtr(RoomNameVec));
1010
1011         while (Pos != StrBufNOTNULL){
1012                 StrBufExtract_NextToken(oneRoom, RoomNameVec, &Pos, '|');
1013                 CtdlDeleteMessages(ChrPtr(oneRoom), &msgnum, 1, "");
1014         };
1015         GetMetaData(&smi, msgnum);
1016         AdjRefCount(msgnum, -smi.meta_refcount);
1017 }
1018
1019
1020 void migr_do_restore_meta(void) {
1021         char buf[SIZ];
1022         int failGetMessage;
1023         long msgnum = 0;
1024         int lastnum = 0;
1025         int refcount = 0;
1026         CitContext *Ctx;
1027         char *prn;
1028         StrBuf *RoomNames;
1029         char cmd[SIZ];
1030
1031         migr_global_message_list = fopen(migr_tempfilename1, "w");
1032         if (migr_global_message_list != NULL) {
1033                 CtdlForEachRoom(migr_check_rooms_backend, NULL);
1034                 fclose(migr_global_message_list);
1035         }
1036
1037         /*
1038          * Process the 'global' message list.  (Sort it and remove dups.
1039          * Dups are ok because a message may be in more than one room, but
1040          * this will be handled by exporting the reference count, not by
1041          * exporting the message multiple times.)
1042          */
1043         snprintf(cmd, sizeof cmd, "sort -n <%s >%s", migr_tempfilename1, migr_tempfilename2);
1044         if (system(cmd) != 0) syslog(LOG_ALERT, "Error %d", errno);
1045
1046         RoomNames = NewStrBuf();
1047         Ctx = CC;
1048         migr_global_message_list = fopen(migr_tempfilename2, "r");
1049         if (migr_global_message_list != NULL) {
1050                 syslog(LOG_INFO, "Opened %s", migr_tempfilename1);
1051                 while ((Ctx->kill_me == 0) && 
1052                        (fgets(buf, sizeof(buf), migr_global_message_list) != NULL)) {
1053                         msgnum = atol(buf);
1054                         if (msgnum == 0L) 
1055                                 continue;
1056                         if (lastnum == 0) {
1057                                 lastnum = msgnum;
1058                         }
1059                         prn = strchr(buf, ' ');
1060                         if (lastnum != msgnum) {
1061                                 failGetMessage = migr_restore_message_metadata(lastnum, refcount);
1062                                 if (failGetMessage) {
1063                                         RemoveMessagesFromRooms(RoomNames, lastnum);
1064                                 }
1065                                 refcount = 1;
1066                                 lastnum = msgnum;
1067                                 if (prn != NULL) {
1068                                         StrBufPlain(RoomNames, prn + 1, -1);
1069                                 }
1070                                 StrBufTrim(RoomNames);
1071                         }
1072                         else {
1073                                 if (prn != NULL) {
1074                                         if (StrLength(RoomNames) > 0) {
1075                                                 StrBufAppendBufPlain(RoomNames, HKEY("|"), 0);
1076                                         }
1077                                         StrBufAppendBufPlain(RoomNames, prn, -1, 1);
1078                                         StrBufTrim(RoomNames);
1079                                 }
1080                                 refcount ++;
1081                         }
1082                         lastnum = msgnum;
1083                 }
1084                 failGetMessage = migr_restore_message_metadata(msgnum, refcount);
1085                 if (failGetMessage) {
1086                         RemoveMessagesFromRooms(RoomNames, lastnum);
1087                 }
1088                 fclose(migr_global_message_list);
1089         }
1090
1091         migr_restore_message_metadata(-1L, -1); /* This frees the encoding buffer */
1092         cprintf("%d system analysis completed", CIT_OK);
1093         Ctx->kill_me = 1;
1094 }
1095
1096
1097 /******************************************************************************
1098  *                         Dispatcher, Common code                            *
1099  ******************************************************************************/
1100 void cmd_migr(char *cmdbuf) {
1101         char cmd[32];
1102         
1103         if (CtdlAccessCheck(ac_internal)) return;
1104         
1105         if (CtdlTrySingleUser()) {
1106                 CtdlDisableHouseKeeping();
1107                 CtdlMakeTempFileName(migr_tempfilename1, sizeof migr_tempfilename1);
1108                 CtdlMakeTempFileName(migr_tempfilename2, sizeof migr_tempfilename2);
1109
1110                 extract_token(cmd, cmdbuf, 0, '|', sizeof cmd);
1111                 if (!strcasecmp(cmd, "export")) {
1112                         migr_do_export();
1113                 }
1114                 else if (!strcasecmp(cmd, "import")) {
1115                         migr_do_import();
1116                 }
1117                 else if (!strcasecmp(cmd, "listdirs")) {
1118                         migr_do_listdirs();
1119                 }
1120                 else if (!strcasecmp(cmd, "restoremeta")) {
1121                         migr_do_restore_meta();
1122                 }
1123                 else {
1124                         cprintf("%d illegal command\n", ERROR + ILLEGAL_VALUE);
1125                 }
1126
1127                 unlink(migr_tempfilename1);
1128                 unlink(migr_tempfilename2);
1129
1130                 CtdlEnableHouseKeeping();
1131                 CtdlEndSingleUser();
1132         }
1133         else {
1134                 cprintf("%d The migrator is already running.\n", ERROR + RESOURCE_BUSY);
1135         }
1136 }
1137
1138
1139 /******************************************************************************
1140  *                              Module Hook                                  *
1141  ******************************************************************************/
1142
1143 CTDL_MODULE_INIT(migrate)
1144 {
1145         if (!threading)
1146         {
1147                 CtdlRegisterProtoHook(cmd_migr, "MIGR", "Across-the-wire migration");
1148         }
1149         
1150         /* return our module name for the log */
1151         return "migrate";
1152 }