Modified the behavior of ForEachUser() to do the two phase load/perform cycle
[citadel.git] / citadel / modules / upgrade / serv_upgrade.c
1 /*
2  * Transparently handle the upgrading of server data formats.  If we see
3  * an existing version number of our database, we can make some intelligent
4  * guesses about what kind of data format changes need to be applied, and
5  * we apply them transparently.
6  *
7  * Copyright (c) 1987-2019 by the citadel.org team
8  *
9  * This program is open source software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License version 3.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17
18 #include "sysdep.h"
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <pwd.h>
25 #include <errno.h>
26 #include <sys/types.h>
27
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #include <sys/wait.h>
40 #include <string.h>
41 #include <limits.h>
42 #include <libcitadel.h>
43 #include "citadel.h"
44 #include "server.h"
45 #include "citserver.h"
46 #include "support.h"
47 #include "config.h"
48 #include "control.h"
49 #include "database.h"
50 #include "user_ops.h"
51 #include "msgbase.h"
52 #include "serv_upgrade.h"
53 #include "euidindex.h"
54 #include "ctdl_module.h"
55 #include "serv_vcard.h"
56 #include "internet_addressing.h"
57
58 /*
59  * oldver is the version number of Citadel Server which was active on the previous run of the program, learned from the system configuration.
60  * If we are running a new Citadel Server for the first time, oldver will be 0.
61  * We keep this value around for the entire duration of the program run because we'll need it during several stages of startup.
62  */
63 int oldver = 0;
64
65 /*
66  * Fix up the name for Citadel user 0 and try to remove any extra users with number 0
67  */
68 void fix_sys_user_name(void)
69 {
70         struct ctdluser usbuf;
71         char usernamekey[USERNAME_SIZE];
72
73         /** If we have a user called Citadel rename them to SYS_Citadel */
74         if (CtdlGetUser(&usbuf, "Citadel") == 0)
75         {
76                 rename_user("Citadel", "SYS_Citadel");
77         }
78
79         while (CtdlGetUserByNumber(&usbuf, 0) == 0)
80         {
81                 /* delete user with number 0 and no name */
82                 if (IsEmptyStr(usbuf.fullname)) {
83                         cdb_delete(CDB_USERS, "", 0);
84                 }
85                 else {
86                         /* temporarily set this user to -1 */
87                         usbuf.usernum = -1;
88                         CtdlPutUser(&usbuf);
89                 }
90         }
91
92         /* Make sure user SYS_* is user 0 */
93         while (CtdlGetUserByNumber(&usbuf, -1) == 0)
94         {
95                 if (strncmp(usbuf.fullname, "SYS_", 4))
96                 {       /* Delete any user 0 that doesn't start with SYS_ */
97                         makeuserkey(usernamekey, usbuf.fullname, cutusername(usbuf.fullname));
98                         cdb_delete(CDB_USERS, usernamekey, strlen(usernamekey));
99                 }
100                 else {
101                         usbuf.usernum = 0;
102                         CtdlPutUser(&usbuf);
103                 }
104         }
105 }
106
107
108 /* 
109  * Back end processing function for reindex_uids()
110  */
111 void reindex_uids_backend(char *username, void *data) {
112
113         struct ctdluser us;
114
115         if (CtdlGetUserLock(&us, username) == 0) {
116                 syslog(LOG_DEBUG, "Processing <%s> (%d)", us.fullname, us.uid);
117                 if (us.uid == CTDLUID) {
118                         us.uid = NATIVE_AUTH_UID;
119                 }
120                 CtdlPutUserLock(&us);
121                 if ((us.uid > 0) && (us.uid != NATIVE_AUTH_UID)) {              // if non-native auth , index by uid
122                         StrBuf *claimed_id = NewStrBuf();
123                         StrBufPrintf(claimed_id, "uid:%d", us.uid);
124                         attach_extauth(&us, claimed_id);
125                         FreeStrBuf(&claimed_id);
126                 }
127         }
128 }
129
130
131 /*
132  * Build extauth index of all users with uid-based join (system auth, LDAP auth)
133  * Also changes all users with a uid of CTDLUID to NATIVE_AUTH_UID (-1)
134  */
135 void reindex_uids(void) {
136         syslog(LOG_WARNING, "upgrade: reindexing and applying uid changes");
137         ForEachUser(reindex_uids_backend, NULL);
138         return;
139 }
140
141
142 /*
143  * These accounts may have been created by code that ran between mid 2008 and early 2011.
144  * If present they are no longer in use and may be deleted.
145  */
146 void remove_thread_users(void) {
147         char *deleteusers[] = {
148                 "SYS_checkpoint",
149                 "SYS_extnotify",
150                 "SYS_IGnet Queue",
151                 "SYS_indexer",
152                 "SYS_network",
153                 "SYS_popclient",
154                 "SYS_purger",
155                 "SYS_rssclient",
156                 "SYS_select_on_master",
157                 "SYS_SMTP Send"
158         };
159
160         int i;
161         struct ctdluser usbuf;
162         for (i=0; i<(sizeof(deleteusers)/sizeof(char *)); ++i) {
163                 if (CtdlGetUser(&usbuf, deleteusers[i]) == 0) {
164                         usbuf.axlevel = 0;
165                         strcpy(usbuf.password, "deleteme");
166                         CtdlPutUser(&usbuf);
167                         syslog(LOG_INFO,
168                                 "System user account <%s> is no longer in use and will be deleted.",
169                                 deleteusers[i]
170                         );
171                 }
172         }
173 }
174
175
176 /*
177  * Attempt to guess the name of the time zone currently in use
178  * on the underlying host system.
179  */
180 void guess_time_zone(void) {
181         FILE *fp;
182         char buf[PATH_MAX];
183
184         fp = popen(file_guesstimezone, "r");
185         if (fp) {
186                 if (fgets(buf, sizeof buf, fp) && (strlen(buf) > 2)) {
187                         buf[strlen(buf)-1] = 0;
188                         CtdlSetConfigStr("c_default_cal_zone", buf);
189                         syslog(LOG_INFO, "Configuring timezone: %s", buf);
190                 }
191                 fclose(fp);
192         }
193 }
194
195
196 /*
197  * Per-room callback function for ingest_old_roominfo_and_roompic_files()
198  *
199  * This is the second pass, where we process the list of rooms with info or pic files.
200  */
201 void iorarf_oneroom(char *roomname, char *infofile, char *picfile)
202 {
203         FILE *fp;
204         long data_length;
205         char *unencoded_data;
206         char *encoded_data;
207         long info_msgnum = 0;
208         long pic_msgnum = 0;
209         char subject[SIZ];
210
211         // Test for the presence of a legacy "room info file"
212         if (!IsEmptyStr(infofile)) {
213                 fp = fopen(infofile, "r");
214         }
215         else {
216                 fp = NULL;
217         }
218         if (fp) {
219                 fseek(fp, 0, SEEK_END);
220                 data_length = ftell(fp);
221
222                 if (data_length >= 1) {
223                         rewind(fp);
224                         unencoded_data = malloc(data_length);
225                         if (unencoded_data) {
226                                 fread(unencoded_data, data_length, 1, fp);
227                                 encoded_data = malloc((data_length * 2) + 100);
228                                 if (encoded_data) {
229                                         sprintf(encoded_data, "Content-type: text/plain\nContent-transfer-encoding: base64\n\n");
230                                         CtdlEncodeBase64(&encoded_data[strlen(encoded_data)], unencoded_data, data_length, 1);
231                                         snprintf(subject, sizeof subject, "Imported room banner for %s", roomname);
232                                         info_msgnum = quickie_message("Citadel", NULL, NULL, SYSCONFIGROOM, encoded_data, FMT_RFC822, subject);
233                                         free(encoded_data);
234                                 }
235                                 free(unencoded_data);
236                         }
237                 }
238                 fclose(fp);
239                 if (info_msgnum > 0) unlink(infofile);
240         }
241
242         // Test for the presence of a legacy "room picture file" and import it.
243         if (!IsEmptyStr(picfile)) {
244                 fp = fopen(picfile, "r");
245         }
246         else {
247                 fp = NULL;
248         }
249         if (fp) {
250                 fseek(fp, 0, SEEK_END);
251                 data_length = ftell(fp);
252
253                 if (data_length >= 1) {
254                         rewind(fp);
255                         unencoded_data = malloc(data_length);
256                         if (unencoded_data) {
257                                 fread(unencoded_data, data_length, 1, fp);
258                                 encoded_data = malloc((data_length * 2) + 100);
259                                 if (encoded_data) {
260                                         sprintf(encoded_data, "Content-type: image/gif\nContent-transfer-encoding: base64\n\n");
261                                         CtdlEncodeBase64(&encoded_data[strlen(encoded_data)], unencoded_data, data_length, 1);
262                                         snprintf(subject, sizeof subject, "Imported room icon for %s", roomname);
263                                         pic_msgnum = quickie_message("Citadel", NULL, NULL, SYSCONFIGROOM, encoded_data, FMT_RFC822, subject);
264                                         free(encoded_data);
265                                 }
266                                 free(unencoded_data);
267                         }
268                 }
269                 fclose(fp);
270                 if (pic_msgnum > 0) unlink(picfile);
271         }
272
273         // Now we have the message numbers of our new banner and icon.  Record them in the room record.
274         // NOTE: we are not deleting the old msgnum_info because that position in the record was previously
275         // a pointer to the highest message number which existed in the room when the info file was saved,
276         // and we don't want to delete messages that are not *actually* old banners.
277         struct ctdlroom qrbuf;
278         if (CtdlGetRoomLock(&qrbuf, roomname) == 0) {
279                 qrbuf.msgnum_info = info_msgnum;
280                 qrbuf.msgnum_pic = pic_msgnum;
281                 CtdlPutRoomLock(&qrbuf);
282         }
283
284 }
285
286
287 struct iorarf_list {
288         struct iorarf_list *next;
289         char name[ROOMNAMELEN];
290         char info[PATH_MAX];
291         char pic[PATH_MAX];
292 };
293
294
295 /*
296  * Per-room callback function for ingest_old_roominfo_and_roompic_files()
297  *
298  * This is the first pass, where the list of qualifying rooms is gathered.
299  */
300 void iorarf_backend(struct ctdlroom *qrbuf, void *data)
301 {
302         FILE *fp;
303         struct iorarf_list **iorarf_list = (struct iorarf_list **)data;
304
305         struct iorarf_list *i = malloc(sizeof(struct iorarf_list));
306         i->next = *iorarf_list;
307         strcpy(i->name, qrbuf->QRname);
308         strcpy(i->info, "");
309         strcpy(i->pic, "");
310
311         // Test for the presence of a legacy "room info file"
312         assoc_file_name(i->info, sizeof i->info, qrbuf, ctdl_info_dir);
313         fp = fopen(i->info, "r");
314         if (fp) {
315                 fclose(fp);
316         }
317         else {
318                 i->info[0] = 0;
319         }
320
321         // Test for the presence of a legacy "room picture file"
322         assoc_file_name(i->pic, sizeof i->pic, qrbuf, ctdl_image_dir);
323         fp = fopen(i->pic, "r");
324         if (fp) {
325                 fclose(fp);
326         }
327         else {
328                 i->pic[0] = 0;
329         }
330
331         if ( (!IsEmptyStr(i->info)) || (!IsEmptyStr(i->pic)) ) {
332                 *iorarf_list = i;
333         }
334         else {
335                 free(i);
336         }
337 }
338
339
340 /*
341  * Prior to Citadel Server version 902, room info and pictures (which comprise the
342  * displayed banner for each room) were stored in the filesystem.  If we are upgrading
343  * from version >000 to version >=902, ingest those files into the database.
344  */
345 void ingest_old_roominfo_and_roompic_files(void)
346 {
347         struct iorarf_list *il = NULL;
348
349         CtdlForEachRoom(iorarf_backend, &il);
350
351         struct iorarf_list *p;
352         while (il) {
353                 iorarf_oneroom(il->name, il->info, il->pic);
354                 p = il->next;
355                 free(il);
356                 il = p;
357         }
358
359         unlink(ctdl_info_dir);
360 }
361
362
363 /*
364  * For upgrades in which a new config setting appears for the first time, set default values.
365  * For new installations (oldver == 0) also set default values.
366  */
367 void update_config(void) {
368
369         if (oldver < 606) {
370                 CtdlSetConfigInt("c_rfc822_strict_from", 0);
371         }
372
373         if (oldver < 609) {
374                 CtdlSetConfigInt("c_purge_hour", 3);
375         }
376
377         if (oldver < 615) {
378                 CtdlSetConfigInt("c_ldap_port", 389);
379         }
380
381         if (oldver < 623) {
382                 CtdlSetConfigStr("c_ip_addr", "*");
383         }
384
385         if (oldver < 650) {
386                 CtdlSetConfigInt("c_enable_fulltext", 1);
387         }
388
389         if (oldver < 652) {
390                 CtdlSetConfigInt("c_auto_cull", 1);
391         }
392
393         if (oldver < 725) {
394                 CtdlSetConfigInt("c_xmpp_c2s_port", 5222);
395                 CtdlSetConfigInt("c_xmpp_s2s_port", 5269);
396         }
397
398         if (oldver < 830) {
399                 CtdlSetConfigInt("c_nntp_port", 119);
400                 CtdlSetConfigInt("c_nntps_port", 563);
401         }
402
403         if (IsEmptyStr(CtdlGetConfigStr("c_default_cal_zone"))) {
404                 guess_time_zone();
405         }
406 }
407
408
409 /*
410  * Helper function for move_inet_addrs_from_vcards_to_user_records()
411  *
412  * Call this function as a ForEachUser backend in order to queue up
413  * user names, or call it with a null user to make it do the processing.
414  * This allows us to maintain the list as a static instead of passing
415  * pointers around.
416  */
417 void miafvtur_backend(char *username, void *data) {
418         struct ctdluser usbuf;
419         char primary_inet_email[512] = { 0 };
420         char other_inet_emails[512] = { 0 };
421         char combined_inet_emails[512] = { 0 };
422
423         if (CtdlGetUser(&usbuf, username) != 0) {
424                 return;
425         }
426
427         struct vCard *v = vcard_get_user(&usbuf);
428         if (!v) return;
429         extract_inet_email_addrs(primary_inet_email, sizeof primary_inet_email, other_inet_emails, sizeof other_inet_emails, v, 1);
430         vcard_free(v);
431         
432         if ( (IsEmptyStr(primary_inet_email)) && (IsEmptyStr(other_inet_emails)) ) {
433                 return;
434         }
435
436         snprintf(combined_inet_emails, 512, "%s%s%s",
437                 (!IsEmptyStr(primary_inet_email) ? primary_inet_email : ""),
438                 ((!IsEmptyStr(primary_inet_email)&&(!IsEmptyStr(other_inet_emails))) ? "|" : ""),
439                 (!IsEmptyStr(other_inet_emails) ? other_inet_emails : "")
440         );
441
442         CtdlSetEmailAddressesForUser(usbuf.fullname, combined_inet_emails);
443 }
444
445
446 /*
447  * If our system still has a "refcount_adjustments.dat" sitting around from an old version, ingest it now.
448  */
449 int ProcessOldStyleAdjRefCountQueue(void)
450 {
451         int r;
452         FILE *fp;
453         struct arcq arcq_rec;
454         int num_records_processed = 0;
455
456         fp = fopen(file_arcq, "rb");
457         if (fp == NULL) {
458                 return(num_records_processed);
459         }
460
461         syslog(LOG_INFO, "msgbase: ingesting %s", file_arcq);
462
463         while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
464                 AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
465                 ++num_records_processed;
466         }
467
468         fclose(fp);
469         r = unlink(file_arcq);
470         if (r != 0) {
471                 syslog(LOG_ERR, "%s: %m", file_arcq);
472         }
473
474         return(num_records_processed);
475 }
476
477
478 /*
479  * Prior to version 912 we kept a user's various Internet email addresses in their vCards.
480  * This function moves them over to the user record, which is where we keep them now.
481  */
482 void move_inet_addrs_from_vcards_to_user_records(void)
483 {
484         ForEachUser(miafvtur_backend, NULL);
485         CtdlRebuildDirectoryIndex();
486 }
487
488
489 /*
490  * Based on the server version number reported by the existing database,
491  * run in-place data format upgrades until everything is up to date.
492  */
493 void pre_startup_upgrades(void) {
494
495         oldver = CtdlGetConfigInt("MM_hosted_upgrade_level");
496         syslog(LOG_INFO, "Existing database version on disk is %d", oldver);
497         update_config();
498
499         if (oldver < REV_LEVEL) {
500                 syslog(LOG_WARNING, "Running pre-startup database upgrades.");
501         }
502         else {
503                 return;
504         }
505
506         if ((oldver > 000) && (oldver < 591)) {
507                 syslog(LOG_EMERG, "This database is too old to be upgraded.  Citadel server will exit.");
508                 exit(EXIT_FAILURE);
509         }
510         if ((oldver > 000) && (oldver < 913)) {
511                 reindex_uids();
512         }
513         if ((oldver > 000) && (oldver < 659)) {
514                 rebuild_euid_index();
515         }
516         if (oldver < 735) {
517                 fix_sys_user_name();
518         }
519         if (oldver < 736) {
520                 rebuild_usersbynumber();
521         }
522         if (oldver < 790) {
523                 remove_thread_users();
524         }
525         if (oldver < 810) {
526                 struct ctdlroom QRoom;
527                 if (!CtdlGetRoom(&QRoom, SMTP_SPOOLOUT_ROOM)) {
528                         QRoom.QRdefaultview = VIEW_QUEUE;
529                         CtdlPutRoom(&QRoom);
530                 }
531         }
532
533         if ((oldver > 000) && (oldver < 902)) {
534                 ingest_old_roominfo_and_roompic_files();
535         }
536
537         CtdlSetConfigInt("MM_hosted_upgrade_level", REV_LEVEL);
538
539         /*
540          * Negative values for maxsessions are not allowed.
541          */
542         if (CtdlGetConfigInt("c_maxsessions") < 0) {
543                 CtdlSetConfigInt("c_maxsessions", 0);
544         }
545
546         /* We need a system default message expiry policy, because this is
547          * the top level and there's no 'higher' policy to fall back on.
548          * By default, do not expire messages at all.
549          */
550         if (CtdlGetConfigInt("c_ep_mode") == 0) {
551                 CtdlSetConfigInt("c_ep_mode", EXPIRE_MANUAL);
552                 CtdlSetConfigInt("c_ep_value", 0);
553         }
554 }
555
556
557 /*
558  * Based on the server version number reported by the existing database,
559  * run in-place data format upgrades until everything is up to date.
560  */
561 void post_startup_upgrades(void) {
562
563         syslog(LOG_INFO, "Existing database version on disk is %d", oldver);
564
565         if (oldver < REV_LEVEL) {
566                 syslog(LOG_WARNING, "Running post-startup database upgrades.");
567         }
568         else {
569                 return;
570         }
571
572         if ((oldver > 000) && (oldver < 912)) {
573                 move_inet_addrs_from_vcards_to_user_records();
574         }
575
576         if ((oldver > 000) && (oldver < 922)) {
577                 ProcessOldStyleAdjRefCountQueue();
578         }
579 }
580
581
582 CTDL_MODULE_UPGRADE(upgrade)
583 {
584         pre_startup_upgrades();
585         
586         /* return our module id for the Log */
587         return "upgrade";
588 }
589
590 CTDL_MODULE_INIT(upgrade)
591 {
592         if(!threading)
593         {
594                 move_inet_addrs_from_vcards_to_user_records();
595                 post_startup_upgrades();
596         }
597         
598         /* return our module name for the log */
599         return "upgrade";
600 }