Config exporter complete.
[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  * 1%              finished exporting config
20  * 2%              finished exporting control
21  * 7%              finished exporting users
22  * 12%             finished exporting openids
23  * 17%             finished exporting rooms
24  * 18%             finished exporting floors
25  * 25%             finished exporting visits
26  * 100%            finished exporting messages
27  */
28
29 #include "sysdep.h"
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <pwd.h>
36 #include <errno.h>
37 #include <sys/types.h>
38
39 #if TIME_WITH_SYS_TIME
40 # include <sys/time.h>
41 # include <time.h>
42 #else
43 # if HAVE_SYS_TIME_H
44 #  include <sys/time.h>
45 # else
46 #  include <time.h>
47 # endif
48 #endif
49
50 #include <sys/wait.h>
51 #include <string.h>
52 #include <ctype.h>
53 #include <limits.h>
54 #include <expat.h>
55 #include <libcitadel.h>
56 #include "citadel.h"
57 #include "server.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "database.h"
62 #include "msgbase.h"
63 #include "user_ops.h"
64 #include "control.h"
65 #include "euidindex.h"
66 #include "ctdl_module.h"
67
68 #define END_OF_MESSAGE  "---eom---dbd---"
69
70 char migr_tempfilename1[PATH_MAX];
71 char migr_tempfilename2[PATH_MAX];
72 FILE *migr_global_message_list;
73 int total_msgs = 0;
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("&quot;", 6);
93                 }
94                 else if (*c == '\'') {
95                         client_write("&apos;", 6);
96                 }
97                 else if (*c == '<') {
98                         client_write("&lt;", 4);
99                 }
100                 else if (*c == '>') {
101                         client_write("&gt;", 4);
102                 }
103                 else if (*c == '&') {
104                         client_write("&amp;", 5);
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("<user>\n", 7);
119         cprintf("<u_version>%d</u_version>\n", buf->version);
120         cprintf("<u_uid>%ld</u_uid>\n", (long)buf->uid);
121         client_write("<u_password>", 12);       xml_strout(buf->password);              client_write("</u_password>\n", 14);
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("<u_fullname>", 12);       xml_strout(buf->fullname);              client_write("</u_fullname>\n", 14);
130         client_write("</user>\n", 8);
131 }
132
133
134 void migr_export_users(void) {
135         ForEachUser(migr_export_users_backend, NULL);
136 }
137
138
139 void migr_export_room_msg(long msgnum, void *userdata) {
140         cprintf("%ld\n", msgnum);
141         fprintf(migr_global_message_list, "%ld\n", msgnum);
142 }
143
144
145 void migr_export_rooms_backend(struct ctdlroom *buf, void *data) {
146         client_write("<room>\n", 7);
147         client_write("<QRname>", 8);    xml_strout(buf->QRname);        client_write("</QRname>\n", 10);
148         client_write("<QRpasswd>", 10); xml_strout(buf->QRpasswd);      client_write("</QRpasswd>\n", 12);
149         cprintf("<QRroomaide>%ld</QRroomaide>\n", buf->QRroomaide);
150         cprintf("<QRhighest>%ld</QRhighest>\n", buf->QRhighest);
151         cprintf("<QRgen>%ld</QRgen>\n", (long)buf->QRgen);
152         cprintf("<QRflags>%u</QRflags>\n", buf->QRflags);
153         if (buf->QRflags & QR_DIRECTORY) {
154                 client_write("<QRdirname>", 11);
155                 xml_strout(buf->QRdirname);
156                 client_write("</QRdirname>\n", 13);
157         }
158         cprintf("<QRinfo>%ld</QRinfo>\n", buf->QRinfo);
159         cprintf("<QRfloor>%d</QRfloor>\n", buf->QRfloor);
160         cprintf("<QRmtime>%ld</QRmtime>\n", (long)buf->QRmtime);
161         cprintf("<QRexpire_mode>%d</QRexpire_mode>\n", buf->QRep.expire_mode);
162         cprintf("<QRexpire_value>%d</QRexpire_value>\n", buf->QRep.expire_value);
163         cprintf("<QRnumber>%ld</QRnumber>\n", buf->QRnumber);
164         cprintf("<QRorder>%d</QRorder>\n", buf->QRorder);
165         cprintf("<QRflags2>%u</QRflags2>\n", buf->QRflags2);
166         cprintf("<QRdefaultview>%d</QRdefaultview>\n", buf->QRdefaultview);
167         client_write("</room>\n", 8);
168
169         /* message list goes inside this tag */
170
171         CtdlGetRoom(&CC->room, buf->QRname);
172         client_write("<room_messages>", 15);
173         client_write("<FRname>", 8);    xml_strout(CC->room.QRname);    client_write("</FRname>\n", 10);
174         client_write("<FRmsglist>", 11);
175         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, migr_export_room_msg, NULL);
176         client_write("</FRmsglist>\n", 13);
177         client_write("</room_messages>\n", 17);
178
179
180 }
181
182
183 void migr_export_rooms(void) {
184         char cmd[SIZ];
185         migr_global_message_list = fopen(migr_tempfilename1, "w");
186         if (migr_global_message_list != NULL) {
187                 CtdlForEachRoom(migr_export_rooms_backend, NULL);
188                 fclose(migr_global_message_list);
189         }
190
191         /*
192          * Process the 'global' message list.  (Sort it and remove dups.
193          * Dups are ok because a message may be in more than one room, but
194          * this will be handled by exporting the reference count, not by
195          * exporting the message multiple times.)
196          */
197         snprintf(cmd, sizeof cmd, "sort -n <%s >%s", migr_tempfilename1, migr_tempfilename2);
198         if (system(cmd) != 0) syslog(LOG_ALERT, "Error %d\n", errno);
199         snprintf(cmd, sizeof cmd, "uniq <%s >%s", migr_tempfilename2, migr_tempfilename1);
200         if (system(cmd) != 0) syslog(LOG_ALERT, "Error %d\n", errno);
201
202
203         snprintf(cmd, sizeof cmd, "wc -l %s", migr_tempfilename1);
204         FILE *fp = popen(cmd, "r");
205         if (fp) {
206                 fgets(cmd, sizeof cmd, fp);
207                 pclose(fp);
208                 total_msgs = atoi(cmd);
209         }
210         else {
211                 total_msgs = 1; // any nonzero just to keep it from barfing
212         }
213         syslog(LOG_DEBUG, "Total messages to be exported: %d", total_msgs);
214 }
215
216
217 void migr_export_floors(void) {
218         struct floor qfbuf, *buf;
219         int i;
220
221         for (i=0; i < MAXFLOORS; ++i) {
222                 client_write("<floor>\n", 8);
223                 cprintf("<f_num>%d</f_num>\n", i);
224                 CtdlGetFloor(&qfbuf, i);
225                 buf = &qfbuf;
226                 cprintf("<f_flags>%u</f_flags>\n", buf->f_flags);
227                 client_write("<f_name>", 8); xml_strout(buf->f_name); client_write("</f_name>\n", 10);
228                 cprintf("<f_ref_count>%d</f_ref_count>\n", buf->f_ref_count);
229                 cprintf("<f_ep_expire_mode>%d</f_ep_expire_mode>\n", buf->f_ep.expire_mode);
230                 cprintf("<f_ep_expire_value>%d</f_ep_expire_value>\n", buf->f_ep.expire_value);
231                 client_write("</floor>\n", 9);
232         }
233 }
234
235
236 /*
237  * Return nonzero if the supplied string contains only characters which are valid in a sequence set.
238  */
239 int is_sequence_set(char *s) {
240         if (!s) return(0);
241
242         char *c = s;
243         char ch;
244         while (ch = *c++, ch) {
245                 if (!strchr("0123456789*,:", ch)) {
246                         return(0);
247                 }
248         }
249         return(1);
250 }
251
252
253
254 /* 
255  *  Traverse the visits file...
256  */
257 void migr_export_visits(void) {
258         visit vbuf;
259         struct cdbdata *cdbv;
260
261         cdb_rewind(CDB_VISIT);
262
263         while (cdbv = cdb_next_item(CDB_VISIT), cdbv != NULL) {
264                 memset(&vbuf, 0, sizeof(visit));
265                 memcpy(&vbuf, cdbv->ptr,
266                        ((cdbv->len > sizeof(visit)) ?
267                         sizeof(visit) : cdbv->len));
268                 cdb_free(cdbv);
269
270                 client_write("<visit>\n", 8);
271                 cprintf("<v_roomnum>%ld</v_roomnum>\n", vbuf.v_roomnum);
272                 cprintf("<v_roomgen>%ld</v_roomgen>\n", vbuf.v_roomgen);
273                 cprintf("<v_usernum>%ld</v_usernum>\n", vbuf.v_usernum);
274
275                 client_write("<v_seen>", 8);
276                 if ( (!IsEmptyStr(vbuf.v_seen)) && (is_sequence_set(vbuf.v_seen)) ) {
277                         xml_strout(vbuf.v_seen);
278                 }
279                 else {
280                         cprintf("%ld", vbuf.v_lastseen);
281                 }
282                 client_write("</v_seen>", 9);
283
284                 if ( (!IsEmptyStr(vbuf.v_answered)) && (is_sequence_set(vbuf.v_answered)) ) {
285                         client_write("<v_answered>", 12);
286                         xml_strout(vbuf.v_answered);
287                         client_write("</v_answered>\n", 14);
288                 }
289
290                 cprintf("<v_flags>%u</v_flags>\n", vbuf.v_flags);
291                 cprintf("<v_view>%d</v_view>\n", vbuf.v_view);
292                 client_write("</visit>\n", 9);
293         }
294 }
295
296
297 void migr_export_message(long msgnum) {
298         struct MetaData smi;
299         struct CtdlMessage *msg;
300         struct ser_ret smr;
301
302         /* We can use a static buffer here because there will never be more than
303          * one of this operation happening at any given time, and it's really best
304          * to just keep it allocated once instead of torturing malloc/free.
305          * Call this function with msgnum "-1" to free the buffer when finished.
306          */
307         static int encoded_alloc = 0;
308         static char *encoded_msg = NULL;
309
310         if (msgnum < 0) {
311                 if ((encoded_alloc == 0) && (encoded_msg != NULL)) {
312                         free(encoded_msg);
313                         encoded_alloc = 0;
314                         encoded_msg = NULL;
315                 }
316                 return;
317         }
318
319         /* Ok, here we go ... */
320
321         msg = CtdlFetchMessage(msgnum, 1);
322         if (msg == NULL) return;        /* fail silently */
323
324         client_write("<message>\n", 10);
325         GetMetaData(&smi, msgnum);
326         cprintf("<msg_msgnum>%ld</msg_msgnum>\n", msgnum);
327         cprintf("<msg_meta_refcount>%d</msg_meta_refcount>\n", smi.meta_refcount);
328         client_write("<msg_meta_content_type>", 23); xml_strout(smi.meta_content_type); client_write("</msg_meta_content_type>\n", 25);
329
330         client_write("<msg_text>", 10);
331         CtdlSerializeMessage(&smr, msg);
332         CM_Free(msg);
333
334         /* Predict the buffer size we need.  Expand the buffer if necessary. */
335         int encoded_len = smr.len * 15 / 10 ;
336         if (encoded_len > encoded_alloc) {
337                 encoded_alloc = encoded_len;
338                 encoded_msg = realloc(encoded_msg, encoded_alloc);
339         }
340
341         if (encoded_msg == NULL) {
342                 /* Questionable hack that hopes it'll work next time and we only lose one message */
343                 encoded_alloc = 0;
344         }
345         else {
346                 /* Once we do the encoding we know the exact size */
347                 encoded_len = CtdlEncodeBase64(encoded_msg, (char *)smr.ser, smr.len, 1);
348                 client_write(encoded_msg, encoded_len);
349         }
350
351         free(smr.ser);
352
353         client_write("</msg_text>\n", 12);
354         client_write("</message>\n", 11);
355 }
356
357
358
359 void migr_export_openids(void) {
360         struct cdbdata *cdboi;
361         long usernum;
362         char url[512];
363
364         cdb_rewind(CDB_OPENID);
365         while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
366                 if (cdboi->len > sizeof(long)) {
367                         client_write("<openid>\n", 9);
368                         memcpy(&usernum, cdboi->ptr, sizeof(long));
369                         snprintf(url, sizeof url, "%s", (cdboi->ptr)+sizeof(long) );
370                         client_write("<oid_url>", 9);
371                         xml_strout(url);
372                         client_write("</oid_url>\n", 11);
373                         cprintf("<oid_usernum>%ld</oid_usernum>\n", usernum);
374                         client_write("</openid>\n", 10);
375                 }
376                 cdb_free(cdboi);
377         }
378 }
379
380
381 void migr_export_configs(void) {
382         struct cdbdata *cdbcfg;
383         int keylen = 0;
384         char *key = NULL;
385         char *value = NULL;
386
387         cdb_rewind(CDB_CONFIG);
388         while (cdbcfg = cdb_next_item(CDB_CONFIG), cdbcfg != NULL) {
389
390                 keylen = strlen(cdbcfg->ptr);
391                 key = cdbcfg->ptr;
392                 value = cdbcfg->ptr + keylen + 1;
393
394                 client_write("<config key=\"", 13);
395                 xml_strout(key);
396                 client_write("\">", 2);
397                 xml_strout(value);
398                 client_write("</config>\n", 10);
399                 cdb_free(cdbcfg);
400         }
401 }
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\n", 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.\n", count);
435         else
436                 syslog(LOG_ERR, "Export aborted due to client disconnect! \n");
437
438         migr_export_message(-1L);       /* This frees the encoding buffer */
439 }
440
441
442
443 void migr_do_export(void) {
444         CitContext *Ctx;
445
446         Ctx = CC;
447         cprintf("%d Exporting all Citadel databases.\n", LISTING_FOLLOWS);
448         Ctx->dont_term = 1;
449
450         client_write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", 40);
451         client_write("<citadel_migrate_data>\n", 23);
452         cprintf("<version>%d</version>\n", REV_LEVEL);
453         cprintf("<progress>%d</progress>\n", 0);
454
455         /* export the config file (this is done using x-macros) */
456         migr_export_configs();
457         cprintf("<progress>%d</progress>\n", 1);
458         
459         /* Export the control file */
460         get_control();
461         client_write("<control>\n", 10);
462         cprintf("<control_highest>%ld</control_highest>\n", CitControl.MMhighest);
463         cprintf("<control_flags>%u</control_flags>\n", CitControl.MMflags);
464         cprintf("<control_nextuser>%ld</control_nextuser>\n", CitControl.MMnextuser);
465         cprintf("<control_nextroom>%ld</control_nextroom>\n", CitControl.MMnextroom);
466         cprintf("<control_version>%d</control_version>\n", CitControl.MM_hosted_upgrade_level);
467         client_write("</control>\n", 11);
468         cprintf("<progress>%d</progress>\n", 2);
469
470         if (Ctx->kill_me == 0)  migr_export_users();
471         cprintf("<progress>%d</progress>\n", 7);
472         if (Ctx->kill_me == 0)  migr_export_openids();
473         cprintf("<progress>%d</progress>\n", 12);
474         if (Ctx->kill_me == 0)  migr_export_rooms();
475         cprintf("<progress>%d</progress>\n", 17);
476         if (Ctx->kill_me == 0)  migr_export_floors();
477         cprintf("<progress>%d</progress>\n", 18);
478         if (Ctx->kill_me == 0)  migr_export_visits();
479         cprintf("<progress>%d</progress>\n", 25);
480         if (Ctx->kill_me == 0)  migr_export_messages();
481         client_write("</citadel_migrate_data>\n", 24);
482         cprintf("<progress>%d</progress>\n", 100);
483         client_write("000\n", 4);
484         Ctx->dont_term = 0;
485 }
486
487
488
489
490         
491 /*
492  * Here's the code that implements the import side.  It's going to end up being
493  * one big loop with lots of global variables.  I don't care.  You wouldn't run
494  * multiple concurrent imports anyway.  If this offends your delicate sensibilities
495  * then go rewrite it in Ruby on Rails or something.
496  */
497
498
499 int citadel_migrate_data = 0;           /* Are we inside a <citadel_migrate_data> tag pair? */
500 StrBuf *migr_chardata = NULL;
501 StrBuf *migr_MsgData = NULL;
502 struct ctdluser usbuf;
503 struct ctdlroom qrbuf;
504 char openid_url[512];
505 long openid_usernum = 0;
506 char FRname[ROOMNAMELEN];
507 struct floor flbuf;
508 int floornum = 0;
509 visit vbuf;
510 struct MetaData smi;
511 long import_msgnum = 0;
512
513 /*
514  * This callback stores up the data which appears in between tags.
515  */
516 void migr_xml_chardata(void *data, const XML_Char *s, int len)
517 {
518         StrBufAppendBufPlain(migr_chardata, s, len, 0);
519 }
520
521
522 void migr_xml_start(void *data, const char *el, const char **attr) {
523         int i;
524
525         /*** GENERAL STUFF ***/
526
527         /* Reset chardata_len to zero and init buffer */
528         FlushStrBuf(migr_chardata);
529         FlushStrBuf(migr_MsgData);
530
531         if (!strcasecmp(el, "citadel_migrate_data")) {
532                 ++citadel_migrate_data;
533
534                 /* As soon as it looks like the input data is a genuine Citadel XML export,
535                  * whack the existing database on disk to make room for the new one.
536                  */
537                 if (citadel_migrate_data == 1) {
538                         for (i = 0; i < MAXCDB; ++i) {
539                                 cdb_trunc(i);
540                         }
541                 }
542                 return;
543         }
544
545         if (citadel_migrate_data != 1) {
546                 syslog(LOG_ALERT, "Out-of-sequence tag <%s> detected.  Warning: ODD-DATA!\n", el);
547                 return;
548         }
549
550         /* When we begin receiving XML for one of these record types, clear out the associated
551          * buffer so we don't accidentally carry over any data from a previous record.
552          */
553         if (!strcasecmp(el, "user"))                    memset(&usbuf, 0, sizeof (struct ctdluser));
554         else if (!strcasecmp(el, "openid"))             memset(openid_url, 0, sizeof openid_url);
555         else if (!strcasecmp(el, "room"))               memset(&qrbuf, 0, sizeof (struct ctdlroom));
556         else if (!strcasecmp(el, "room_messages"))      memset(FRname, 0, sizeof FRname);
557         else if (!strcasecmp(el, "floor"))              memset(&flbuf, 0, sizeof (struct floor));
558         else if (!strcasecmp(el, "visit"))              memset(&vbuf, 0, sizeof (visit));
559
560         else if (!strcasecmp(el, "message")) {
561                 memset(&smi, 0, sizeof (struct MetaData));
562                 import_msgnum = 0;
563         }
564         else if (!strcasecmp(el, "config")) {
565                 syslog(LOG_DEBUG, "\033[31m IMPORT OF CONFIG START ELEMENT FIXME\033\0m");
566         }
567
568 }
569
570
571
572 int migr_controlrecord(void *data, const char *el)
573 {
574         if (!strcasecmp(el, "control_highest"))         CitControl.MMhighest = atol(ChrPtr(migr_chardata));
575         else if (!strcasecmp(el, "control_flags"))              CitControl.MMflags = atoi(ChrPtr(migr_chardata));
576         else if (!strcasecmp(el, "control_nextuser"))           CitControl.MMnextuser = atol(ChrPtr(migr_chardata));
577         else if (!strcasecmp(el, "control_nextroom"))           CitControl.MMnextroom = atol(ChrPtr(migr_chardata));
578         else if (!strcasecmp(el, "control_version"))            CitControl.MM_hosted_upgrade_level = atoi(ChrPtr(migr_chardata));
579
580         else if (!strcasecmp(el, "control")) {
581                 CitControl.MMfulltext = (-1L);  /* always flush */
582                 put_control();
583                 syslog(LOG_INFO, "Completed import of control record\n");
584         }
585         else return 0;
586         return 1;
587
588 }
589
590
591 int migr_userrecord(void *data, const char *el)
592 {
593         if (!strcasecmp(el, "u_version"))                       usbuf.version = atoi(ChrPtr(migr_chardata));
594         else if (!strcasecmp(el, "u_uid"))                      usbuf.uid = atol(ChrPtr(migr_chardata));
595         else if (!strcasecmp(el, "u_password"))                 safestrncpy(usbuf.password, ChrPtr(migr_chardata), sizeof usbuf.password);
596         else if (!strcasecmp(el, "u_flags"))                    usbuf.flags = atoi(ChrPtr(migr_chardata));
597         else if (!strcasecmp(el, "u_timescalled"))              usbuf.timescalled = atol(ChrPtr(migr_chardata));
598         else if (!strcasecmp(el, "u_posted"))                   usbuf.posted = atol(ChrPtr(migr_chardata));
599         else if (!strcasecmp(el, "u_axlevel"))                  usbuf.axlevel = atoi(ChrPtr(migr_chardata));
600         else if (!strcasecmp(el, "u_usernum"))                  usbuf.usernum = atol(ChrPtr(migr_chardata));
601         else if (!strcasecmp(el, "u_lastcall"))                 usbuf.lastcall = atol(ChrPtr(migr_chardata));
602         else if (!strcasecmp(el, "u_USuserpurge"))              usbuf.USuserpurge = atoi(ChrPtr(migr_chardata));
603         else if (!strcasecmp(el, "u_fullname"))                 safestrncpy(usbuf.fullname, ChrPtr(migr_chardata), sizeof usbuf.fullname);
604         else return 0;
605         return 1;
606 }
607
608 int migr_roomrecord(void *data, const char *el)
609 {
610         if (!strcasecmp(el, "QRname"))                  safestrncpy(qrbuf.QRname, ChrPtr(migr_chardata), sizeof qrbuf.QRname);
611         else if (!strcasecmp(el, "QRpasswd"))                   safestrncpy(qrbuf.QRpasswd, ChrPtr(migr_chardata), sizeof qrbuf.QRpasswd);
612         else if (!strcasecmp(el, "QRroomaide"))                 qrbuf.QRroomaide = atol(ChrPtr(migr_chardata));
613         else if (!strcasecmp(el, "QRhighest"))                  qrbuf.QRhighest = atol(ChrPtr(migr_chardata));
614         else if (!strcasecmp(el, "QRgen"))                      qrbuf.QRgen = atol(ChrPtr(migr_chardata));
615         else if (!strcasecmp(el, "QRflags"))                    qrbuf.QRflags = atoi(ChrPtr(migr_chardata));
616         else if (!strcasecmp(el, "QRdirname"))                  safestrncpy(qrbuf.QRdirname, ChrPtr(migr_chardata), sizeof qrbuf.QRdirname);
617         else if (!strcasecmp(el, "QRinfo"))                     qrbuf.QRinfo = atol(ChrPtr(migr_chardata));
618         else if (!strcasecmp(el, "QRfloor"))                    qrbuf.QRfloor = atoi(ChrPtr(migr_chardata));
619         else if (!strcasecmp(el, "QRmtime"))                    qrbuf.QRmtime = atol(ChrPtr(migr_chardata));
620         else if (!strcasecmp(el, "QRexpire_mode"))              qrbuf.QRep.expire_mode = atoi(ChrPtr(migr_chardata));
621         else if (!strcasecmp(el, "QRexpire_value"))             qrbuf.QRep.expire_value = atoi(ChrPtr(migr_chardata));
622         else if (!strcasecmp(el, "QRnumber"))                   qrbuf.QRnumber = atol(ChrPtr(migr_chardata));
623         else if (!strcasecmp(el, "QRorder"))                    qrbuf.QRorder = atoi(ChrPtr(migr_chardata));
624         else if (!strcasecmp(el, "QRflags2"))                   qrbuf.QRflags2 = atoi(ChrPtr(migr_chardata));
625         else if (!strcasecmp(el, "QRdefaultview"))              qrbuf.QRdefaultview = atoi(ChrPtr(migr_chardata));
626         else return 0;
627         return 1;
628 }
629
630 int migr_floorrecord(void *data, const char *el)
631 {
632         if (!strcasecmp(el, "f_num"))                   floornum = atoi(ChrPtr(migr_chardata));
633         else if (!strcasecmp(el, "f_flags"))                    flbuf.f_flags = atoi(ChrPtr(migr_chardata));
634         else if (!strcasecmp(el, "f_name"))                     safestrncpy(flbuf.f_name, ChrPtr(migr_chardata), sizeof flbuf.f_name);
635         else if (!strcasecmp(el, "f_ref_count"))                flbuf.f_ref_count = atoi(ChrPtr(migr_chardata));
636         else if (!strcasecmp(el, "f_ep_expire_mode"))           flbuf.f_ep.expire_mode = atoi(ChrPtr(migr_chardata));
637         else if (!strcasecmp(el, "f_ep_expire_value"))          flbuf.f_ep.expire_value = atoi(ChrPtr(migr_chardata));
638         else return 0;
639         return 1;
640 }
641
642 int migr_visitrecord(void *data, const char *el)
643 {
644         if (!strcasecmp(el, "v_roomnum"))                       vbuf.v_roomnum = atol(ChrPtr(migr_chardata));
645         else if (!strcasecmp(el, "v_roomgen"))                  vbuf.v_roomgen = atol(ChrPtr(migr_chardata));
646         else if (!strcasecmp(el, "v_usernum"))                  vbuf.v_usernum = atol(ChrPtr(migr_chardata));
647
648         else if (!strcasecmp(el, "v_seen")) {
649                 int is_textual_seen = 0;
650                 int i;
651                 int max = StrLength(migr_chardata);
652
653                 vbuf.v_lastseen = atol(ChrPtr(migr_chardata));
654                 is_textual_seen = 0;
655                 for (i=0; i < max; ++i) 
656                         if (!isdigit(ChrPtr(migr_chardata)[i]))
657                                 is_textual_seen = 1;
658                 if (is_textual_seen)
659                         safestrncpy(vbuf.v_seen, ChrPtr(migr_chardata), sizeof vbuf.v_seen);
660         }
661
662         else if (!strcasecmp(el, "v_answered"))                 safestrncpy(vbuf.v_answered, ChrPtr(migr_chardata), sizeof vbuf.v_answered);
663         else if (!strcasecmp(el, "v_flags"))                    vbuf.v_flags = atoi(ChrPtr(migr_chardata));
664         else if (!strcasecmp(el, "v_view"))                     vbuf.v_view = atoi(ChrPtr(migr_chardata));
665         else return 0;
666         return 1;
667 }
668
669
670 void migr_xml_end(void *data, const char *el)
671 {
672         const char *ptr;
673         int msgcount = 0;
674         long msgnum = 0L;
675         long *msglist = NULL;
676         int msglist_alloc = 0;
677         /*** GENERAL STUFF ***/
678
679         if (!strcasecmp(el, "citadel_migrate_data")) {
680                 --citadel_migrate_data;
681                 return;
682         }
683
684         if (citadel_migrate_data != 1) {
685                 syslog(LOG_ALERT, "Out-of-sequence tag <%s> detected.  Warning: ODD-DATA!\n", el);
686                 return;
687         }
688
689         // syslog(LOG_DEBUG, "END TAG: <%s> DATA: <%s>\n", el, (migr_chardata_len ? migr_chardata : ""));
690
691         /*** CONFIG ***/
692
693         if (!strcasecmp(el, "config"))
694         {
695                 syslog(LOG_DEBUG, "\033[31m IMPORT OF CONFIG END ELEMENT FIXME\033\0m");
696                 CtdlSetConfigInt("c_enable_fulltext", 0);       /* always disable FIXME put this somewhere more appropriate */
697         }
698
699         /*** CONTROL ***/
700         else if ((!strncasecmp(el, HKEY("control"))) && 
701                  migr_controlrecord(data, el))
702                 ; /* Nothing to do anymore */
703         /*** USER ***/
704         else if ((!strncasecmp(el, HKEY("u_"))) && 
705                  migr_userrecord(data, el))
706                 ; /* Nothing to do anymore */
707         else if (!strcasecmp(el, "user")) {
708                 CtdlPutUser(&usbuf);
709                 syslog(LOG_INFO, "Imported user: %s\n", usbuf.fullname);
710         }
711
712         /*** OPENID ***/
713
714         else if (!strcasecmp(el, "oid_url"))                    safestrncpy(openid_url, ChrPtr(migr_chardata), sizeof openid_url);
715         else if (!strcasecmp(el, "oid_usernum"))                openid_usernum = atol(ChrPtr(migr_chardata));
716
717         else if (!strcasecmp(el, "openid")) {                   /* see serv_openid_rp.c for a description of the record format */
718                 char *oid_data;
719                 int oid_data_len;
720                 oid_data_len = sizeof(long) + strlen(openid_url) + 1;
721                 oid_data = malloc(oid_data_len);
722                 memcpy(oid_data, &openid_usernum, sizeof(long));
723                 memcpy(&oid_data[sizeof(long)], openid_url, strlen(openid_url) + 1);
724                 cdb_store(CDB_OPENID, openid_url, strlen(openid_url), oid_data, oid_data_len);
725                 free(oid_data);
726                 syslog(LOG_INFO, "Imported OpenID: %s (%ld)\n", openid_url, openid_usernum);
727         }
728
729         /*** ROOM ***/
730         else if ((!strncasecmp(el, HKEY("QR"))) && 
731                  migr_roomrecord(data, el))
732                 ; /* Nothing to do anymore */
733         else if (!strcasecmp(el, "room")) {
734                 CtdlPutRoom(&qrbuf);
735                 syslog(LOG_INFO, "Imported room: %s\n", qrbuf.QRname);
736         }
737
738         /*** ROOM MESSAGE POINTERS ***/
739
740         else if (!strcasecmp(el, "FRname"))                     safestrncpy(FRname, ChrPtr(migr_chardata), sizeof FRname);
741
742         else if (!strcasecmp(el, "FRmsglist")) {
743                 if (!IsEmptyStr(FRname)) {
744                         msgcount = 0;
745                         msglist_alloc = 1000;
746                         msglist = malloc(sizeof(long) * msglist_alloc);
747
748                         syslog(LOG_DEBUG, "Message list for: %s\n", FRname);
749
750                         ptr = ChrPtr(migr_chardata);
751                         while (*ptr != 0) {
752                                 while ((*ptr != 0) && (!isdigit(*ptr))) {
753                                         ++ptr;
754                                 }
755                                 if ((*ptr != 0) && (isdigit(*ptr))) {
756                                         msgnum = atol(ptr);
757                                         if (msgnum > 0L) {
758                                                 if (msgcount >= msglist_alloc) {
759                                                         msglist_alloc *= 2;
760                                                         msglist = realloc(msglist, sizeof(long) * msglist_alloc);
761                                                 }
762                                                 msglist[msgcount++] = msgnum;
763                                                 }
764                                         }
765                                         while ((*ptr != 0) && (isdigit(*ptr))) {
766                                                 ++ptr;
767                                         }
768                                 }
769                         }
770                         if (msgcount > 0) {
771                                 CtdlSaveMsgPointersInRoom(FRname, msglist, msgcount, 0, NULL, 1);
772                         }
773                         free(msglist);
774                         msglist = NULL;
775                         msglist_alloc = 0;
776                         syslog(LOG_DEBUG, "Imported %d messages.\n", msgcount);
777                         if (server_shutting_down) {
778                                 return;
779                 }
780         }
781
782         /*** FLOORS ***/
783         else if ((!strncasecmp(el, HKEY("f_"))) && 
784                  migr_floorrecord(data, el))
785                 ; /* Nothing to do anymore */
786
787         else if (!strcasecmp(el, "floor")) {
788                 CtdlPutFloor(&flbuf, floornum);
789                 syslog(LOG_INFO, "Imported floor #%d (%s)\n", floornum, flbuf.f_name);
790         }
791
792         /*** VISITS ***/
793         else if ((!strncasecmp(el, HKEY("v_"))) && 
794                  migr_visitrecord(data, el))
795                 ; /* Nothing to do anymore */
796         else if (!strcasecmp(el, "visit")) {
797                 put_visit(&vbuf);
798                 syslog(LOG_INFO, "Imported visit: %ld/%ld/%ld\n", vbuf.v_roomnum, vbuf.v_roomgen, vbuf.v_usernum);
799         }
800
801         /*** MESSAGES ***/
802         
803         else if (!strcasecmp(el, "msg_msgnum"))                 import_msgnum = atol(ChrPtr(migr_chardata));
804         else if (!strcasecmp(el, "msg_meta_refcount"))          smi.meta_refcount = atoi(ChrPtr(migr_chardata));
805         else if (!strcasecmp(el, "msg_meta_content_type"))      safestrncpy(smi.meta_content_type, ChrPtr(migr_chardata), sizeof smi.meta_content_type);
806
807         else if (!strcasecmp(el, "msg_text"))
808         {
809
810                 FlushStrBuf(migr_MsgData);
811                 StrBufDecodeBase64To(migr_MsgData, migr_MsgData);
812
813                 cdb_store(CDB_MSGMAIN,
814                           &import_msgnum,
815                           sizeof(long),
816                           ChrPtr(migr_MsgData), 
817                           StrLength(migr_MsgData) + 1);
818
819                 smi.meta_msgnum = import_msgnum;
820                 PutMetaData(&smi);
821
822                 syslog(LOG_INFO,
823                        "Imported message #%ld, size=%d, refcount=%d, content-type: %s\n",
824                        import_msgnum,
825                        StrLength(migr_MsgData),
826                        smi.meta_refcount,
827                        smi.meta_content_type);
828         }
829
830         /*** MORE GENERAL STUFF ***/
831
832         FlushStrBuf(migr_chardata);
833 }
834
835
836
837
838 /*
839  * Import begins here
840  */
841 void migr_do_import(void) {
842         StrBuf *Buf;
843         XML_Parser xp;
844         int Finished = 0;
845         
846         unbuffer_output();
847         migr_chardata = NewStrBufPlain(NULL, SIZ * 20);
848         migr_MsgData = NewStrBufPlain(NULL, SIZ * 20);
849         Buf = NewStrBufPlain(NULL, SIZ);
850         xp = XML_ParserCreate(NULL);
851         if (!xp) {
852                 cprintf("%d Failed to create XML parser instance\n", ERROR+INTERNAL_ERROR);
853                 return;
854         }
855         XML_SetElementHandler(xp, migr_xml_start, migr_xml_end);
856         XML_SetCharacterDataHandler(xp, migr_xml_chardata);
857
858         CC->dont_term = 1;
859
860         cprintf("%d sock it to me\n", SEND_LISTING);
861         unbuffer_output();
862
863         client_set_inbound_buf(SIZ * 10);
864
865         while (!Finished && client_read_random_blob(Buf, -1) >= 0) {
866                 if ((StrLength(Buf) > 4) &&
867                     !strcmp(ChrPtr(Buf) + StrLength(Buf) - 4, "000\n"))
868                 {
869                         Finished = 1;
870                         StrBufCutAt(Buf, StrLength(Buf) - 4, NULL);
871                 }
872                 if (server_shutting_down)
873                         break;  // Should we break or return?
874                 
875                 if (StrLength(Buf) == 0)
876                         continue;
877
878                 XML_Parse(xp, ChrPtr(Buf), StrLength(Buf), 0);
879                 FlushStrBuf(Buf);
880         }
881
882         XML_Parse(xp, "", 0, 1);
883         XML_ParserFree(xp);
884         FreeStrBuf(&Buf);
885         FreeStrBuf(&migr_chardata);
886         FreeStrBuf(&migr_MsgData);
887         rebuild_euid_index();
888         rebuild_usersbynumber();
889         CC->dont_term = 0;
890 }
891
892
893
894 /*
895  * Dump out the pathnames of directories which can be copied "as is"
896  */
897 void migr_do_listdirs(void) {
898         cprintf("%d Don't forget these:\n", LISTING_FOLLOWS);
899         cprintf("bio|%s\n",             ctdl_bio_dir);
900         cprintf("files|%s\n",           ctdl_file_dir);
901         cprintf("userpics|%s\n",        ctdl_usrpic_dir);
902         cprintf("messages|%s\n",        ctdl_message_dir);
903         cprintf("netconfigs|%s\n",      ctdl_netcfg_dir);
904         cprintf("keys|%s\n",            ctdl_key_dir);
905         cprintf("images|%s\n",          ctdl_image_dir);
906         cprintf("info|%s\n",            ctdl_info_dir);
907         cprintf("000\n");
908 }
909
910
911 /*
912  * Common code appears in this section
913  */
914
915
916 void cmd_migr(char *cmdbuf) {
917         char cmd[32];
918         
919         if (CtdlAccessCheck(ac_internal)) return;
920         
921         if (CtdlTrySingleUser())
922         {
923                 CtdlMakeTempFileName(migr_tempfilename1, sizeof migr_tempfilename1);
924                 CtdlMakeTempFileName(migr_tempfilename2, sizeof migr_tempfilename2);
925
926                 extract_token(cmd, cmdbuf, 0, '|', sizeof cmd);
927                 if (!strcasecmp(cmd, "export")) {
928                         migr_do_export();
929                 }
930                 else if (!strcasecmp(cmd, "import")) {
931                         migr_do_import();
932                 }
933                 else if (!strcasecmp(cmd, "listdirs")) {
934                         migr_do_listdirs();
935                 }
936                 else {
937                         cprintf("%d illegal command\n", ERROR + ILLEGAL_VALUE);
938                 }
939
940                 unlink(migr_tempfilename1);
941                 unlink(migr_tempfilename2);
942                 
943                 CtdlEndSingleUser();
944         }
945         else
946         {
947                 cprintf("%d The migrator is already running.\n", ERROR + RESOURCE_BUSY);
948         }
949 }
950
951
952 CTDL_MODULE_INIT(migrate)
953 {
954         if (!threading)
955         {
956                 CtdlRegisterProtoHook(cmd_migr, "MIGR", "Across-the-wire migration");
957         }
958         
959         /* return our module name for the log */
960         return "migrate";
961 }