de80290bbddd680bb4ae8502fcafcdaaa4d0bca7
[citadel.git] / citadel / server / config.c
1 // Read and write the system configuration database
2 //
3 // Copyright (c) 1987-2022 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <netdb.h>
13 //#include <crypt.h>
14 #include <sys/utsname.h>
15 #include <libcitadel.h>
16 #include <assert.h>
17 #include "config.h"
18 #include "ctdl_module.h"
19
20 long config_msgnum = 0;
21 HashList *ctdlconfig = NULL;    // new configuration
22
23
24 void config_warn_if_port_unset(char *key, int default_port) {
25         int p = CtdlGetConfigInt(key);
26         if ((p < -1) || (p == 0) || (p > UINT16_MAX)) {
27                 syslog(LOG_ERR, "config: setting %s is not -1 (disabled) or a valid TCP port - setting to default %d", key, default_port);
28                 CtdlSetConfigInt(key, default_port);
29         }
30 }
31
32
33 void config_warn_if_empty(char *key) {
34         if (IsEmptyStr(CtdlGetConfigStr(key))) {
35                 syslog(LOG_ERR, "config: setting %s is empty, but must not - check your config!", key);
36         }
37 }
38
39
40 void validate_config(void) {
41
42         // these shouldn't be empty
43         config_warn_if_empty("c_fqdn");
44         config_warn_if_empty("c_baseroom");
45         config_warn_if_empty("c_aideroom");
46         config_warn_if_empty("c_twitroom");
47         config_warn_if_empty("c_nodename");
48
49         // Sanity check for port bindings
50         config_warn_if_port_unset("c_smtp_port",        25);
51         config_warn_if_port_unset("c_pop3_port",        110);
52         config_warn_if_port_unset("c_imap_port",        143);
53         config_warn_if_port_unset("c_msa_port",         587);
54         config_warn_if_port_unset("c_port_number",      504);
55         config_warn_if_port_unset("c_smtps_port",       465);
56         config_warn_if_port_unset("c_pop3s_port",       995);
57         config_warn_if_port_unset("c_imaps_port",       993);
58         config_warn_if_port_unset("c_pftcpdict_port",   -1);
59         config_warn_if_port_unset("c_xmpp_c2s_port",    5222);
60         config_warn_if_port_unset("c_xmpp_s2s_port",    5269);
61         config_warn_if_port_unset("c_nntp_port",        119);
62         config_warn_if_port_unset("c_nntps_port",       563);
63
64         if (getpwuid(ctdluid) == NULL) {
65                 syslog(LOG_ERR, "config: uid (%d) does not exist ... citserver will run as root", ctdluid);
66         }
67 }
68
69
70 // The "host key" is a 100-byte random string that is used to do some persistent hashing.
71 // It must remain consistent throughout the lifetime of this Citadel installation
72 void generate_host_key(void) {
73         syslog(LOG_INFO, "config: generating a host key");
74         int len = 0;
75         char host_key[128];
76
77         while (len < 100) {
78                 do {
79                         host_key[len] = random() % 0x7F;
80                 } while (!isalnum(host_key[len]));
81                 host_key[++len] = 0;
82         }
83         CtdlSetConfigStr("host_key", host_key);
84 }
85
86
87 // Put some sane default values into our configuration.  Some will be overridden when we run setup.
88 void brand_new_installation_set_defaults(void) {
89
90         struct utsname my_utsname;
91         struct hostent *he;
92         char detected_hostname[256];
93
94         // Determine our host name, in case we need to use it as a default
95         uname(&my_utsname);
96
97         // set some sample/default values in place of blanks...
98         extract_token(detected_hostname, my_utsname.nodename, 0, '.', sizeof detected_hostname);
99         CtdlSetConfigStr("c_nodename", detected_hostname);
100
101         if ((he = gethostbyname(my_utsname.nodename)) != NULL) {
102                 CtdlSetConfigStr("c_fqdn", he->h_name);
103         }
104         else {
105                 CtdlSetConfigStr("c_fqdn", my_utsname.nodename);
106         }
107
108         CtdlSetConfigStr("c_humannode",         "Citadel Server");
109         CtdlSetConfigInt("c_initax",            4);
110         CtdlSetConfigStr("c_moreprompt",        "<more>");
111         CtdlSetConfigStr("c_twitroom",          "Trashcan");
112         CtdlSetConfigStr("c_baseroom",          BASEROOM);
113         CtdlSetConfigStr("c_aideroom",          "Aide");
114         CtdlSetConfigInt("c_sleeping",          900);
115
116         if (CtdlGetConfigInt("c_createax") == 0) {
117                 CtdlSetConfigInt("c_createax", 3);
118         }
119
120         // Default port numbers for various services
121         CtdlSetConfigInt("c_port_number",       504);
122         CtdlSetConfigInt("c_smtp_port",         25);
123         CtdlSetConfigInt("c_pop3_port",         110);
124         CtdlSetConfigInt("c_imap_port",         143);
125         CtdlSetConfigInt("c_msa_port",          587);
126         CtdlSetConfigInt("c_smtps_port",        465);
127         CtdlSetConfigInt("c_pop3s_port",        995);
128         CtdlSetConfigInt("c_imaps_port",        993);
129         CtdlSetConfigInt("c_pftcpdict_port",    -1);
130         CtdlSetConfigInt("c_xmpp_c2s_port",     5222);
131         CtdlSetConfigInt("c_xmpp_s2s_port",     5269);
132         CtdlSetConfigInt("c_nntp_port",         119);
133         CtdlSetConfigInt("c_nntps_port",        563);
134
135         // Prevent the "new installation, set defaults" behavior from occurring again
136         CtdlSetConfigLong("c_config_created_or_migrated", (long)time(NULL));
137 }
138
139
140 // Migrate a supplied legacy configuration to the new in-db format.
141 // No individual site should ever have to do this more than once.
142 void migrate_legacy_config(struct legacy_config *lconfig) {
143         CtdlSetConfigStr(       "c_nodename"            ,       lconfig->c_nodename             );
144         CtdlSetConfigStr(       "c_fqdn"                ,       lconfig->c_fqdn                 );
145         CtdlSetConfigStr(       "c_humannode"           ,       lconfig->c_humannode            );
146         CtdlSetConfigInt(       "c_creataide"           ,       lconfig->c_creataide            );
147         CtdlSetConfigInt(       "c_sleeping"            ,       lconfig->c_sleeping             );
148         CtdlSetConfigInt(       "c_initax"              ,       lconfig->c_initax               );
149         CtdlSetConfigInt(       "c_regiscall"           ,       lconfig->c_regiscall            );
150         CtdlSetConfigInt(       "c_twitdetect"          ,       lconfig->c_twitdetect           );
151         CtdlSetConfigStr(       "c_twitroom"            ,       lconfig->c_twitroom             );
152         CtdlSetConfigStr(       "c_moreprompt"          ,       lconfig->c_moreprompt           );
153         CtdlSetConfigInt(       "c_restrict"            ,       lconfig->c_restrict             );
154         CtdlSetConfigStr(       "c_site_location"       ,       lconfig->c_site_location        );
155         CtdlSetConfigStr(       "c_sysadm"              ,       lconfig->c_sysadm               );
156         CtdlSetConfigInt(       "c_maxsessions"         ,       lconfig->c_maxsessions          );
157         CtdlSetConfigStr(       "c_ip_addr"             ,       lconfig->c_ip_addr              );
158         CtdlSetConfigInt(       "c_port_number"         ,       lconfig->c_port_number          );
159         CtdlSetConfigInt(       "c_ep_mode"             ,       lconfig->c_ep.expire_mode       );
160         CtdlSetConfigInt(       "c_ep_value"            ,       lconfig->c_ep.expire_value      );
161         CtdlSetConfigInt(       "c_userpurge"           ,       lconfig->c_userpurge            );
162         CtdlSetConfigInt(       "c_roompurge"           ,       lconfig->c_roompurge            );
163         CtdlSetConfigStr(       "c_logpages"            ,       lconfig->c_logpages             );
164         CtdlSetConfigInt(       "c_createax"            ,       lconfig->c_createax             );
165         CtdlSetConfigLong(      "c_maxmsglen"           ,       lconfig->c_maxmsglen            );
166         CtdlSetConfigInt(       "c_min_workers"         ,       lconfig->c_min_workers          );
167         CtdlSetConfigInt(       "c_max_workers"         ,       lconfig->c_max_workers          );
168         CtdlSetConfigInt(       "c_pop3_port"           ,       lconfig->c_pop3_port            );
169         CtdlSetConfigInt(       "c_smtp_port"           ,       lconfig->c_smtp_port            );
170         CtdlSetConfigInt(       "c_rfc822_strict_from"  ,       lconfig->c_rfc822_strict_from   );
171         CtdlSetConfigInt(       "c_aide_zap"            ,       lconfig->c_aide_zap             );
172         CtdlSetConfigInt(       "c_imap_port"           ,       lconfig->c_imap_port            );
173         CtdlSetConfigLong(      "c_net_freq"            ,       lconfig->c_net_freq             );
174         CtdlSetConfigInt(       "c_disable_newu"        ,       lconfig->c_disable_newu         );
175         CtdlSetConfigInt(       "c_enable_fulltext"     ,       lconfig->c_enable_fulltext      );
176         CtdlSetConfigStr(       "c_baseroom"            ,       lconfig->c_baseroom             );
177         CtdlSetConfigStr(       "c_aideroom"            ,       lconfig->c_aideroom             );
178         CtdlSetConfigInt(       "c_purge_hour"          ,       lconfig->c_purge_hour           );
179         CtdlSetConfigInt(       "c_mbxep_mode"          ,       lconfig->c_mbxep.expire_mode    );
180         CtdlSetConfigInt(       "c_mbxep_value"         ,       lconfig->c_mbxep.expire_value   );
181         CtdlSetConfigStr(       "c_ldap_host"           ,       lconfig->c_ldap_host            );
182         CtdlSetConfigInt(       "c_ldap_port"           ,       lconfig->c_ldap_port            );
183         CtdlSetConfigStr(       "c_ldap_base_dn"        ,       lconfig->c_ldap_base_dn         );
184         CtdlSetConfigStr(       "c_ldap_bind_dn"        ,       lconfig->c_ldap_bind_dn         );
185         CtdlSetConfigStr(       "c_ldap_bind_pw"        ,       lconfig->c_ldap_bind_pw         );
186         CtdlSetConfigInt(       "c_msa_port"            ,       lconfig->c_msa_port             );
187         CtdlSetConfigInt(       "c_imaps_port"          ,       lconfig->c_imaps_port           );
188         CtdlSetConfigInt(       "c_pop3s_port"          ,       lconfig->c_pop3s_port           );
189         CtdlSetConfigInt(       "c_smtps_port"          ,       lconfig->c_smtps_port           );
190         CtdlSetConfigInt(       "c_allow_spoofing"      ,       lconfig->c_allow_spoofing       );
191         CtdlSetConfigInt(       "c_journal_email"       ,       lconfig->c_journal_email        );
192         CtdlSetConfigInt(       "c_journal_pubmsgs"     ,       lconfig->c_journal_pubmsgs      );
193         CtdlSetConfigStr(       "c_journal_dest"        ,       lconfig->c_journal_dest         );
194         CtdlSetConfigStr(       "c_default_cal_zone"    ,       lconfig->c_default_cal_zone     );
195         CtdlSetConfigInt(       "c_pftcpdict_port"      ,       lconfig->c_pftcpdict_port       );
196         CtdlSetConfigInt(       "c_auth_mode"           ,       lconfig->c_auth_mode            );
197         CtdlSetConfigInt(       "c_rbl_at_greeting"     ,       lconfig->c_rbl_at_greeting      );
198         CtdlSetConfigStr(       "c_pager_program"       ,       lconfig->c_pager_program        );
199         CtdlSetConfigInt(       "c_imap_keep_from"      ,       lconfig->c_imap_keep_from       );
200         CtdlSetConfigInt(       "c_xmpp_c2s_port"       ,       lconfig->c_xmpp_c2s_port        );
201         CtdlSetConfigInt(       "c_xmpp_s2s_port"       ,       lconfig->c_xmpp_s2s_port        );
202         CtdlSetConfigLong(      "c_pop3_fetch"          ,       lconfig->c_pop3_fetch           );
203         CtdlSetConfigLong(      "c_pop3_fastest"        ,       lconfig->c_pop3_fastest         );
204         CtdlSetConfigInt(       "c_spam_flag_only"      ,       lconfig->c_spam_flag_only       );
205         CtdlSetConfigInt(       "c_guest_logins"        ,       lconfig->c_guest_logins         );
206         CtdlSetConfigInt(       "c_nntp_port"           ,       lconfig->c_nntp_port            );
207         CtdlSetConfigInt(       "c_nntps_port"          ,       lconfig->c_nntps_port           );
208 }
209
210
211 // Called during the initialization of Citadel server.
212 // It verifies the system's integrity and reads citadel.config into memory.
213 void initialize_config_system(void) {
214         FILE *cfp;
215         int rv;
216         struct legacy_config lconfig;   // legacy configuration
217         ctdlconfig = NewHash(1, NULL);  // set up the real config system
218
219         // Ensure that we are linked to the correct version of libcitadel
220         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
221                 fprintf(stderr, "You are running libcitadel version %d\n", libcitadel_version_number());
222                 fprintf(stderr, "citserver was compiled against version %d\n", LIBCITADEL_VERSION_NUMBER);
223                 exit(CTDLEXIT_LIBCITADEL);
224         }
225
226         memset(&lconfig, 0, sizeof(struct legacy_config));
227         cfp = fopen(file_citadel_config, "rb");
228         if (cfp != NULL) {
229                 if (CtdlGetConfigLong("c_config_created_or_migrated") > 0) {
230                         fprintf(stderr, "Citadel Server found BOTH legacy and new configurations present.\n");
231                         fprintf(stderr, "Exiting to prevent data corruption.\n");
232                         exit(CTDLEXIT_CONFIG);
233                 }
234                 rv = fread((char *) &lconfig, sizeof(struct legacy_config), 1, cfp);
235                 if (rv != 1) {
236                         fprintf(stderr, 
237                                 "Warning: Found a legacy config file %s has unexpected size. \n",
238                                 file_citadel_config
239                         );
240                 }
241
242                 migrate_legacy_config(&lconfig);
243
244                 fclose(cfp);
245                 if (unlink(file_citadel_config) != 0) {
246                         fprintf(stderr, "Unable to remove legacy config file %s after migrating it.\n", file_citadel_config);
247                         fprintf(stderr, "Exiting to prevent data corruption.\n");
248                         exit(CTDLEXIT_CONFIG);
249                 }
250
251                 // Prevent migration/initialization from happening again.
252                 CtdlSetConfigLong("c_config_created_or_migrated", (long)time(NULL));
253
254         }
255
256         // New installation?  Set up configuration
257         if (CtdlGetConfigLong("c_config_created_or_migrated") <= 0) {
258                 brand_new_installation_set_defaults();
259         }
260
261         // Default maximum message length is 10 megabytes.  This is site
262         // configurable.  Also check to make sure the limit has not been
263         // set below 8192 bytes.
264         if (CtdlGetConfigLong("c_maxmsglen") <= 0)      CtdlSetConfigLong("c_maxmsglen", 10485760);
265         if (CtdlGetConfigLong("c_maxmsglen") < 8192)    CtdlSetConfigLong("c_maxmsglen", 8192);
266
267         // Default lower and upper limits on number of worker threads
268         if (CtdlGetConfigInt("c_min_workers") < 5)      CtdlSetConfigInt("c_min_workers", 5);   // min
269         if (CtdlGetConfigInt("c_max_workers") == 0)     CtdlSetConfigInt("c_max_workers", 256); // default max
270         if (CtdlGetConfigInt("c_max_workers") < CtdlGetConfigInt("c_min_workers")) {
271                 CtdlSetConfigInt("c_max_workers", CtdlGetConfigInt("c_min_workers"));           // max >= min
272         }
273
274         // Networking more than once every five minutes just isn't sane
275         if (CtdlGetConfigLong("c_net_freq") == 0)       CtdlSetConfigLong("c_net_freq", 3600);  // once per hour default
276         if (CtdlGetConfigLong("c_net_freq") < 300)      CtdlSetConfigLong("c_net_freq", 300);   // minimum 5 minutes
277
278         // Same goes for POP3
279         if (CtdlGetConfigLong("c_pop3_fetch") == 0)     CtdlSetConfigLong("c_pop3_fetch", 3600);        // once per hour default
280         if (CtdlGetConfigLong("c_pop3_fetch") < 300)    CtdlSetConfigLong("c_pop3_fetch", 300);         // 5 minutes min
281         if (CtdlGetConfigLong("c_pop3_fastest") == 0)   CtdlSetConfigLong("c_pop3_fastest", 3600);      // once per hour default
282         if (CtdlGetConfigLong("c_pop3_fastest") < 300)  CtdlSetConfigLong("c_pop3_fastest", 300);       // 5 minutes min
283
284         // LDAP sync frequency
285         if (CtdlGetConfigLong("c_ldap_sync_freq") == 0) CtdlSetConfigLong("c_ldap_sync_freq", 300);     // every 5 minutes default
286
287         // "create new user" only works with native authentication mode
288         if (CtdlGetConfigInt("c_auth_mode") != AUTHMODE_NATIVE) {
289                 CtdlSetConfigInt("c_disable_newu", 1);
290         }
291
292         // If we do not have a host key, generate one now, and save it.
293         if (IsEmptyStr(CtdlGetConfigStr("host_key"))) {
294                 generate_host_key();
295         }
296 }
297
298
299 // Called when Citadel server is shutting down.
300 // Clears out the config hash table.
301 void shutdown_config_system(void) {
302         DeleteHash(&ctdlconfig);
303 }
304
305
306 // Set a system config value.  Simple key/value here.
307 void CtdlSetConfigStr(char *key, char *value) {
308         int key_len = strlen(key);
309         int value_len = strlen(value);
310
311         // Save it in memory
312         Put(ctdlconfig, key, key_len, strdup(value), NULL);
313
314         // Also write it to the config database
315
316         int dbv_size = key_len + value_len + 2;
317         char *dbv = malloc(dbv_size);
318         strcpy(dbv, key);
319         strcpy(&dbv[key_len + 1], value);
320         cdb_store(CDB_CONFIG, key, key_len, dbv, dbv_size);
321         free(dbv);
322 }
323
324
325 // Set a numeric system config value (long integer)
326 void CtdlSetConfigLong(char *key, long value) {
327         char longstr[256];
328         sprintf(longstr, "%ld", value);
329         CtdlSetConfigStr(key, longstr);
330 }
331
332
333 // Set a numeric system config value (integer)
334 void CtdlSetConfigInt(char *key, int value) {
335         char intstr[256];
336         sprintf(intstr, "%d", value);
337         CtdlSetConfigStr(key, intstr);
338 }
339
340
341 // Delete a system config value.
342 void CtdlDelConfig(char *key) {
343         int key_len = strlen(key);
344
345         if (IsEmptyStr(key)) return;
346
347         // Delete from the database.
348         cdb_delete(CDB_CONFIG, key, key_len);
349
350         // Delete from the in-memory cache
351         HashPos *Pos = GetNewHashPos(ctdlconfig, 1);
352         if (GetHashPosFromKey(ctdlconfig, key, key_len, Pos)) {
353                 DeleteEntryFromHash(ctdlconfig, Pos);
354         }
355         DeleteHashPos(&Pos);
356
357         assert(Pos == NULL);    // no memory leaks allowed
358 }
359
360
361 // Fetch a system config value.  Caller does *not* own the returned value and may not alter it.
362 char *CtdlGetConfigStr(char *key) {
363         char *value = NULL;
364         struct cdbdata cdb;
365         int key_len = strlen(key);
366
367         if (IsEmptyStr(key)) return(NULL);
368
369         // First look in memory
370         if (GetHash(ctdlconfig, key, key_len, (void *)&value)) {
371                 return value;
372         }
373
374         // Then look in the database.
375         cdb = cdb_fetch(CDB_CONFIG, key, key_len);
376         if (cdb.ptr == NULL) {  // nope, not there either.
377                 return(NULL);
378         }
379
380         // Got it.  Save it in memory for the next fetch.
381         value = strdup(cdb.ptr + key_len + 1);          // The key was stored there too; skip past it
382         Put(ctdlconfig, key, key_len, value, NULL);
383         return value;
384 }
385
386
387 // Fetch a system config value - integer
388 int CtdlGetConfigInt(char *key) {
389         char *s = CtdlGetConfigStr(key);
390         if (s) return atoi(s);
391         return 0;
392 }
393
394
395 // Fetch a system config value - long integer
396 long CtdlGetConfigLong(char *key) {
397         char *s = CtdlGetConfigStr(key);
398         if (s) return atol(s);
399         return 0;
400 }
401
402
403 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
404         config_msgnum = msgnum;
405 }
406
407
408 // This is for fetching longer configuration sets which are stored in the message base.
409 char *CtdlGetSysConfig(char *sysconfname) {
410         char hold_rm[ROOMNAMELEN];
411         long msgnum = -1;
412         char *conf;
413         struct CtdlMessage *msg;
414         char buf[SIZ];
415         
416         strcpy(hold_rm, CC->room.QRname);
417         if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
418                 CtdlGetRoom(&CC->room, hold_rm);
419                 return NULL;
420         }
421
422         // The new way: hunt for the message number in the config database
423         msgnum = CtdlGetConfigLong(sysconfname);
424
425         // Legacy format: hunt through the local system configuration room for a message with a matching MIME type
426         if (msgnum <= 0) {
427                 begin_critical_section(S_CONFIG);
428                 config_msgnum = -1;
429                 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL, CtdlGetSysConfigBackend, NULL);
430                 msgnum = config_msgnum;
431                 end_critical_section(S_CONFIG);
432                 if (msgnum > 0) {
433                         CtdlSetConfigLong(sysconfname, msgnum);         // store it the new way so we don't have to do this again
434                 }
435         }
436
437         if (msgnum <= 0) {
438                 conf = NULL;
439         }
440         else {
441                 msg = CtdlFetchMessage(msgnum, 1);
442                 if (msg != NULL) {
443                         conf = strdup(msg->cm_fields[eMesageText]);
444                         CM_Free(msg);
445                 }
446                 else {
447                         conf = NULL;
448                 }
449         }
450
451         CtdlGetRoom(&CC->room, hold_rm);
452
453         if (conf != NULL) {             // Strip the MIME headers, leaving only the content
454                 do {
455                         extract_token(buf, conf, 0, '\n', sizeof buf);
456                         strcpy(conf, &conf[strlen(buf)+1]);
457                 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
458         }
459
460         return(conf);
461 }
462
463
464 // This is for storing longer configuration sets which are stored in the message base.
465 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
466         long old_msgnum = -1;
467         long new_msgnum = -1;
468
469         // Search for the previous copy of this config item, so we can delete it
470         old_msgnum = CtdlGetConfigLong(sysconfname);
471
472         // Go ahead and save it, and write the new msgnum to the config database so we can find it again
473         new_msgnum = CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 0);
474         if (new_msgnum > 0) {
475                 CtdlSetConfigLong(sysconfname, new_msgnum);
476
477                 // Now delete the old copy
478                 if (old_msgnum > 0) {
479                         CtdlDeleteMessages(SYSCONFIGROOM, &old_msgnum, 1, "");
480                 }
481         }
482 }