* oldver is the version number of Citadel Server which was active on the previous...
[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-2017 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, cutuserkey(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  * Call this function as a ForEachUser backend in order to queue up
111  * user names, or call it with a null user to make it do the processing.
112  * This allows us to maintain the list as a static instead of passing
113  * pointers around.
114  */
115 void reindex_uids_backend(struct ctdluser *usbuf, void *data) {
116         static struct UserProcList *uplist = NULL;
117         struct UserProcList *ptr;
118         struct ctdluser us;
119
120         /* this is the calling mode where we add a user */
121
122         if (usbuf != NULL) {
123                 ptr = (struct UserProcList *) malloc(sizeof (struct UserProcList));
124                 if (ptr == NULL) {
125                         return;
126                 }
127
128                 safestrncpy(ptr->user, usbuf->fullname, sizeof ptr->user);
129                 ptr->next = uplist;
130                 uplist = ptr;
131                 return;
132         }
133
134         /* this is the calling mode where we do the processing */
135
136         while (uplist != NULL) {
137
138                 if (CtdlGetUserLock(&us, uplist->user) == 0) {
139                         syslog(LOG_DEBUG, "Processing <%s> (%d)", uplist->user, us.uid);
140                         if (us.uid == CTDLUID) {
141                                 us.uid = NATIVE_AUTH_UID;
142                         }
143                         CtdlPutUserLock(&us);
144                         if ((us.uid > 0) && (us.uid != NATIVE_AUTH_UID)) {              // if non-native auth , index by uid
145
146                                 syslog(LOG_DEBUG, "\033[31m attaching %d to %s \033[0m", us.uid , us.fullname);
147
148
149                                 StrBuf *claimed_id = NewStrBuf();
150                                 StrBufPrintf(claimed_id, "uid:%d", us.uid);
151                                 attach_extauth(&us, claimed_id);
152                                 FreeStrBuf(&claimed_id);
153                         }
154                 }
155
156                 ptr = uplist;
157                 uplist = uplist->next;
158                 free(ptr);
159         }
160 }
161
162 /*
163  * Build extauth index of all users with uid-based join (system auth, LDAP auth)
164  * Also changes all users with a uid of CTDLUID to NATIVE_AUTH_UID (-1)
165  */
166 void reindex_uids(void) {
167         syslog(LOG_WARNING, "upgrade: reindexing and applying uid changes");
168         ForEachUser(reindex_uids_backend, NULL);
169         reindex_uids_backend(NULL, NULL);
170         return;
171 }
172
173
174
175 /*
176  * These accounts may have been created by code that ran between mid 2008 and early 2011.
177  * If present they are no longer in use and may be deleted.
178  */
179 void remove_thread_users(void) {
180         char *deleteusers[] = {
181                 "SYS_checkpoint",
182                 "SYS_extnotify",
183                 "SYS_IGnet Queue",
184                 "SYS_indexer",
185                 "SYS_network",
186                 "SYS_popclient",
187                 "SYS_purger",
188                 "SYS_rssclient",
189                 "SYS_select_on_master",
190                 "SYS_SMTP Send"
191         };
192
193         int i;
194         struct ctdluser usbuf;
195         for (i=0; i<(sizeof(deleteusers)/sizeof(char *)); ++i) {
196                 if (CtdlGetUser(&usbuf, deleteusers[i]) == 0) {
197                         usbuf.axlevel = 0;
198                         strcpy(usbuf.password, "deleteme");
199                         CtdlPutUser(&usbuf);
200                         syslog(LOG_INFO,
201                                 "System user account <%s> is no longer in use and will be deleted.",
202                                 deleteusers[i]
203                         );
204                 }
205         }
206 }
207
208
209 /*
210  * Attempt to guess the name of the time zone currently in use
211  * on the underlying host system.
212  */
213 void guess_time_zone(void) {
214         FILE *fp;
215         char buf[PATH_MAX];
216
217         fp = popen(file_guesstimezone, "r");
218         if (fp) {
219                 if (fgets(buf, sizeof buf, fp) && (strlen(buf) > 2)) {
220                         buf[strlen(buf)-1] = 0;
221                         CtdlSetConfigStr("c_default_cal_zone", buf);
222                         syslog(LOG_INFO, "Configuring timezone: %s", buf);
223                 }
224                 fclose(fp);
225         }
226 }
227
228
229 /*
230  * Per-room callback function for ingest_old_roominfo_and_roompic_files()
231  *
232  * This is the second pass, where we process the list of rooms with info or pic files.
233  */
234 void iorarf_oneroom(char *roomname, char *infofile, char *picfile)
235 {
236         FILE *fp;
237         long data_length;
238         char *unencoded_data;
239         char *encoded_data;
240         long info_msgnum = 0;
241         long pic_msgnum = 0;
242         char subject[SIZ];
243
244         // Test for the presence of a legacy "room info file"
245         if (!IsEmptyStr(infofile)) {
246                 fp = fopen(infofile, "r");
247         }
248         else {
249                 fp = NULL;
250         }
251         if (fp) {
252                 fseek(fp, 0, SEEK_END);
253                 data_length = ftell(fp);
254
255                 if (data_length >= 1) {
256                         rewind(fp);
257                         unencoded_data = malloc(data_length);
258                         if (unencoded_data) {
259                                 fread(unencoded_data, data_length, 1, fp);
260                                 encoded_data = malloc((data_length * 2) + 100);
261                                 if (encoded_data) {
262                                         sprintf(encoded_data, "Content-type: text/plain\nContent-transfer-encoding: base64\n\n");
263                                         CtdlEncodeBase64(&encoded_data[strlen(encoded_data)], unencoded_data, data_length, 1);
264                                         snprintf(subject, sizeof subject, "Imported room banner for %s", roomname);
265                                         info_msgnum = quickie_message("Citadel", NULL, NULL, SYSCONFIGROOM, encoded_data, FMT_RFC822, subject);
266                                         free(encoded_data);
267                                 }
268                                 free(unencoded_data);
269                         }
270                 }
271                 fclose(fp);
272                 if (info_msgnum > 0) unlink(infofile);
273         }
274
275         // Test for the presence of a legacy "room picture file" and import it.
276         if (!IsEmptyStr(picfile)) {
277                 fp = fopen(picfile, "r");
278         }
279         else {
280                 fp = NULL;
281         }
282         if (fp) {
283                 fseek(fp, 0, SEEK_END);
284                 data_length = ftell(fp);
285
286                 if (data_length >= 1) {
287                         rewind(fp);
288                         unencoded_data = malloc(data_length);
289                         if (unencoded_data) {
290                                 fread(unencoded_data, data_length, 1, fp);
291                                 encoded_data = malloc((data_length * 2) + 100);
292                                 if (encoded_data) {
293                                         sprintf(encoded_data, "Content-type: image/gif\nContent-transfer-encoding: base64\n\n");
294                                         CtdlEncodeBase64(&encoded_data[strlen(encoded_data)], unencoded_data, data_length, 1);
295                                         snprintf(subject, sizeof subject, "Imported room icon for %s", roomname);
296                                         pic_msgnum = quickie_message("Citadel", NULL, NULL, SYSCONFIGROOM, encoded_data, FMT_RFC822, subject);
297                                         free(encoded_data);
298                                 }
299                                 free(unencoded_data);
300                         }
301                 }
302                 fclose(fp);
303                 if (pic_msgnum > 0) unlink(picfile);
304         }
305
306         // Now we have the message numbers of our new banner and icon.  Record them in the room record.
307         // NOTE: we are not deleting the old msgnum_info because that position in the record was previously
308         // a pointer to the highest message number which existed in the room when the info file was saved,
309         // and we don't want to delete messages that are not *actually* old banners.
310         struct ctdlroom qrbuf;
311         if (CtdlGetRoomLock(&qrbuf, roomname) == 0) {
312                 qrbuf.msgnum_info = info_msgnum;
313                 qrbuf.msgnum_pic = pic_msgnum;
314                 CtdlPutRoomLock(&qrbuf);
315         }
316
317 }
318
319
320 struct iorarf_list {
321         struct iorarf_list *next;
322         char name[ROOMNAMELEN];
323         char info[PATH_MAX];
324         char pic[PATH_MAX];
325 };
326
327
328 /*
329  * Per-room callback function for ingest_old_roominfo_and_roompic_files()
330  *
331  * This is the first pass, where the list of qualifying rooms is gathered.
332  */
333 void iorarf_backend(struct ctdlroom *qrbuf, void *data)
334 {
335         FILE *fp;
336         struct iorarf_list **iorarf_list = (struct iorarf_list **)data;
337
338         struct iorarf_list *i = malloc(sizeof(struct iorarf_list));
339         i->next = *iorarf_list;
340         strcpy(i->name, qrbuf->QRname);
341         strcpy(i->info, "");
342         strcpy(i->pic, "");
343
344         // Test for the presence of a legacy "room info file"
345         assoc_file_name(i->info, sizeof i->info, qrbuf, ctdl_info_dir);
346         fp = fopen(i->info, "r");
347         if (fp) {
348                 fclose(fp);
349         }
350         else {
351                 i->info[0] = 0;
352         }
353
354         // Test for the presence of a legacy "room picture file"
355         assoc_file_name(i->pic, sizeof i->pic, qrbuf, ctdl_image_dir);
356         fp = fopen(i->pic, "r");
357         if (fp) {
358                 fclose(fp);
359         }
360         else {
361                 i->pic[0] = 0;
362         }
363
364         if ( (!IsEmptyStr(i->info)) || (!IsEmptyStr(i->pic)) ) {
365                 *iorarf_list = i;
366         }
367         else {
368                 free(i);
369         }
370 }
371
372
373 /*
374  * Prior to Citadel Server version 902, room info and pictures (which comprise the
375  * displayed banner for each room) were stored in the filesystem.  If we are upgrading
376  * from version >000 to version >=902, ingest those files into the database.
377  */
378 void ingest_old_roominfo_and_roompic_files(void)
379 {
380         struct iorarf_list *il = NULL;
381
382         CtdlForEachRoom(iorarf_backend, &il);
383
384         struct iorarf_list *p;
385         while (il) {
386                 iorarf_oneroom(il->name, il->info, il->pic);
387                 p = il->next;
388                 free(il);
389                 il = p;
390         }
391
392         unlink(ctdl_info_dir);
393 }
394
395
396 /*
397  * For upgrades in which a new config setting appears for the first time, set default values.
398  * For new installations (oldver == 0) also set default values.
399  */
400 void update_config(void) {
401
402         if (oldver < 606) {
403                 CtdlSetConfigInt("c_rfc822_strict_from", 0);
404         }
405
406         if (oldver < 609) {
407                 CtdlSetConfigInt("c_purge_hour", 3);
408         }
409
410         if (oldver < 615) {
411                 CtdlSetConfigInt("c_ldap_port", 389);
412         }
413
414         if (oldver < 623) {
415                 CtdlSetConfigStr("c_ip_addr", "*");
416         }
417
418         if (oldver < 650) {
419                 CtdlSetConfigInt("c_enable_fulltext", 1);
420         }
421
422         if (oldver < 652) {
423                 CtdlSetConfigInt("c_auto_cull", 1);
424         }
425
426         if (oldver < 725) {
427                 CtdlSetConfigInt("c_xmpp_c2s_port", 5222);
428                 CtdlSetConfigInt("c_xmpp_s2s_port", 5269);
429         }
430
431         if (oldver < 830) {
432                 CtdlSetConfigInt("c_nntp_port", 119);
433                 CtdlSetConfigInt("c_nntps_port", 563);
434         }
435
436         if (IsEmptyStr(CtdlGetConfigStr("c_default_cal_zone"))) {
437                 guess_time_zone();
438         }
439 }
440
441
442 /*
443  * Helper function for move_inet_addrs_from_vcards_to_user_records()
444  *
445  * Call this function as a ForEachUser backend in order to queue up
446  * user names, or call it with a null user to make it do the processing.
447  * This allows us to maintain the list as a static instead of passing
448  * pointers around.
449  */
450 void miafvtur_backend(struct ctdluser *usbuf, void *data) {
451
452         struct miafvtur {
453                 char name[64];
454                 char emails[512];
455         };
456
457         static struct miafvtur *m = NULL;
458         static int num_m = 0;
459         static int alloc_m = 0;
460
461         /* this is the calling mode where we add a user */
462
463         if (usbuf != NULL) {
464                 char primary_inet_email[512] = { 0 };
465                 char other_inet_emails[512] = { 0 };
466                 struct vCard *v = vcard_get_user(usbuf);
467                 if (!v) return;
468                 extract_inet_email_addrs(primary_inet_email, sizeof primary_inet_email, other_inet_emails, sizeof other_inet_emails, v, 1);
469                 vcard_free(v);
470         
471                 if ( (IsEmptyStr(primary_inet_email)) && (IsEmptyStr(other_inet_emails)) ) {
472                         return;
473                 }
474
475                 if (num_m >= alloc_m) {
476                         if (alloc_m == 0) {
477                                 alloc_m = 100;
478                                 m = malloc(sizeof(struct miafvtur) * alloc_m);
479                         }
480                         else {
481                                 alloc_m *= 2;
482                                 m = realloc(m, (sizeof(struct miafvtur) * alloc_m));
483                         }
484                 }
485
486                 strcpy(m[num_m].name, usbuf->fullname);
487                 snprintf(m[num_m].emails, 512, "%s%s%s",
488                         (!IsEmptyStr(primary_inet_email) ? primary_inet_email : ""),
489                         ((!IsEmptyStr(primary_inet_email)&&(!IsEmptyStr(other_inet_emails))) ? "|" : ""),
490                         (!IsEmptyStr(other_inet_emails) ? other_inet_emails : "")
491                 );
492                 ++num_m;
493                 return;
494         }
495
496         /* this is the calling mode where we do the processing */
497
498         int i;
499         struct ctdluser u;
500
501         for (i=0; i<num_m; ++i) {
502                 syslog(LOG_DEBUG, "<%s> = <%s>", m[i].name, m[i].emails);
503                 if (CtdlGetUser(&u, m[i].name) == 0) {
504                         safestrncpy(u.emailaddrs, m[i].emails, sizeof u.emailaddrs);
505                         CtdlPutUser(&u);
506                 }
507         }
508         free(m);
509         num_m = 0;
510         alloc_m = 0;
511         return;
512 }
513
514
515 /*
516  * Prior to version 912 we kept a user's various Internet email addresses in their vCards.
517  * This function moves them over to the user record, which is where we keep them now.
518  */
519 void move_inet_addrs_from_vcards_to_user_records(void)
520 {
521         ForEachUser(miafvtur_backend, NULL);
522         miafvtur_backend(NULL, NULL);
523         CtdlRebuildDirectoryIndex();
524 }
525
526
527 /*
528  * Based on the server version number reported by the existing database,
529  * run in-place data format upgrades until everything is up to date.
530  */
531 void check_server_upgrades(void) {
532
533         oldver = CtdlGetConfigInt("MM_hosted_upgrade_level");
534         syslog(LOG_INFO, "Existing database version on disk is %d", oldver);
535         update_config();
536
537         if (oldver < REV_LEVEL) {
538                 syslog(LOG_WARNING, "Server hosted updates need to be processed at this time.  Please wait...");
539         }
540         else {
541                 return;
542         }
543
544         if ((oldver > 000) && (oldver < 591)) {
545                 syslog(LOG_EMERG, "This database is too old to be upgraded.  Citadel server will exit.");
546                 exit(EXIT_FAILURE);
547         }
548         if ((oldver > 000) && (oldver < 913)) {
549                 reindex_uids();
550         }
551         if ((oldver > 000) && (oldver < 659)) {
552                 rebuild_euid_index();
553         }
554         if (oldver < 735) {
555                 fix_sys_user_name();
556         }
557         if (oldver < 736) {
558                 rebuild_usersbynumber();
559         }
560         if (oldver < 790) {
561                 remove_thread_users();
562         }
563         if (oldver < 810) {
564                 struct ctdlroom QRoom;
565                 if (!CtdlGetRoom(&QRoom, SMTP_SPOOLOUT_ROOM)) {
566                         QRoom.QRdefaultview = VIEW_QUEUE;
567                         CtdlPutRoom(&QRoom);
568                 }
569         }
570
571         if ((oldver > 000) && (oldver < 902)) {
572                 ingest_old_roominfo_and_roompic_files();
573         }
574
575         if ((oldver > 000) && (oldver < 912)) {
576                 move_inet_addrs_from_vcards_to_user_records();
577         }
578
579         CtdlSetConfigInt("MM_hosted_upgrade_level", REV_LEVEL);
580
581         /*
582          * Negative values for maxsessions are not allowed.
583          */
584         if (CtdlGetConfigInt("c_maxsessions") < 0) {
585                 CtdlSetConfigInt("c_maxsessions", 0);
586         }
587
588         /* We need a system default message expiry policy, because this is
589          * the top level and there's no 'higher' policy to fall back on.
590          * By default, do not expire messages at all.
591          */
592         if (CtdlGetConfigInt("c_ep_mode") == 0) {
593                 CtdlSetConfigInt("c_ep_mode", EXPIRE_MANUAL);
594                 CtdlSetConfigInt("c_ep_value", 0);
595         }
596 }
597
598
599 CTDL_MODULE_UPGRADE(upgrade)
600 {
601         check_server_upgrades();
602         
603         /* return our module id for the Log */
604         return "upgrade";
605 }