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