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