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