indent -kr -i8 -brf -bbb -fnc -l132 -nce on all of webcit-classic
[citadel.git] / webcit / webserver.c
1 // Copyright (c) 1996-2022 by the citadel.org team
2 //
3 // This program is open source software.  You can redistribute it and/or
4 // modify it under the terms of the GNU General Public License version 3.
5 //
6 // This program is distributed in the hope that it will be useful,
7 // but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 // GNU General Public License for more details.
10
11 #include "webcit.h"
12 #include "webserver.h"
13 #include "modules_init.h"
14
15 extern int msock;               /* master listening socket */
16 extern char static_icon_dir[PATH_MAX];  /* where should we find our mime icons */
17 int is_https = 0;               /* Nonzero if I am an HTTPS service */
18 int follow_xff = 0;             /* Follow X-Forwarded-For: header? */
19 int DisableGzip = 0;
20 char *default_landing_page = NULL;
21 extern pthread_mutex_t SessionListMutex;
22
23 extern void *housekeeping_loop(void);
24 extern int webcit_tcp_server(char *ip_addr, int port_number, int queue_len);
25 extern int webcit_uds_server(char *sockpath, int queue_len);
26 extern void graceful_shutdown_watcher(int signum);
27 extern void graceful_shutdown(int signum);
28 extern void start_daemon(char *pid_file);
29 extern void webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome);
30 extern void worker_entry(void);
31 extern void drop_root(uid_t UID);
32
33 char socket_dir[PATH_MAX];      /* where to talk to our citadel server */
34 char *server_cookie = NULL;     /* our Cookie connection to the client */
35 int http_port = PORT_NUM;       /* Port to listen on */
36 int running_as_daemon = 0;      /* should we deamonize on startup? */
37 char *ctdl_dir = DEFAULT_CTDLDIR;       /* Directory where Citadel Server is running */
38
39 /* #define DBG_PRINNT_HOOKS_AT_START */
40 #ifdef DBG_PRINNT_HOOKS_AT_START
41 extern HashList *HandlerHash;
42 const char foobuf[32];
43 const char *nix(void *vptr) {
44         snprintf(foobuf, 32, "%0x", (long) vptr);
45         return foobuf;
46 }
47 #endif
48 extern int verbose;
49 extern int dbg_analyze_msg;
50 extern int dbg_backtrace_template_errors;
51 extern int DumpTemplateI18NStrings;
52 extern StrBuf *I18nDump;
53 void InitTemplateCache(void);
54 extern int LoadTemplates;
55
56 void LoadMimeBlacklist(void);
57
58 /*
59  * Here's where it all begins.
60  */
61 int main(int argc, char **argv) {
62         uid_t UID = -1;
63         pthread_t SessThread;   /* Thread descriptor */
64         pthread_attr_t attr;    /* Thread attributes */
65         int a;                  /* General-purpose variable */
66         char ip_addr[256] = "*";
67         int relh = 0;
68         int home = 0;
69         char relhome[PATH_MAX] = "";
70         char webcitdir[PATH_MAX] = DATADIR;
71         char *pidfile = NULL;
72         char *hdir;
73         const char *basedir = NULL;
74         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
75         const char *I18nDumpFile = NULL;
76         int max_log_level = LOG_INFO;
77
78         WildFireInitBacktrace(argv[0], 2);
79
80         start_modules();
81
82 #ifdef DBG_PRINNT_HOOKS_AT_START
83
84 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
85 #endif
86
87         /* Ensure that we are linked to the correct version of libcitadel */
88         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
89                 fprintf(stderr, " You are running libcitadel version %d\n", libcitadel_version_number());
90                 fprintf(stderr, "WebCit was compiled against version %d\n", LIBCITADEL_VERSION_NUMBER);
91                 return (1);
92         }
93
94         strcpy(uds_listen_path, "");
95
96         /* Parse command line */
97 #ifdef HAVE_OPENSSL
98         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z:v:")) != EOF)
99 #else
100         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfZ:v:")) != EOF)
101 #endif
102                 switch (a) {
103                 case 'u':
104                         UID = atol(optarg);
105                         break;
106                 case 'h':
107                         hdir = strdup(optarg);
108                         relh = hdir[0] != '/';
109                         if (!relh) {
110                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
111                         }
112                         else {
113                                 safestrncpy(relhome, relhome, sizeof relhome);
114                         }
115                         home = 1;
116                         break;
117                 case 'd':
118                         running_as_daemon = 1;
119                         break;
120                 case 'D':
121                         pidfile = strdup(optarg);
122                         running_as_daemon = 1;
123                         break;
124                 case 'g':
125                         default_landing_page = strdup(optarg);
126                         break;
127                 case 'B':       /* deprecated */
128                         break;
129                 case 'i':
130                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
131                         break;
132                 case 'p':
133                         http_port = atoi(optarg);
134                         if (http_port == 0) {
135                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
136                         }
137                         break;
138                 case 't':
139                         /* no longer used, but ignored so old scripts don't break */
140                         break;
141                 case 'T':
142                         LoadTemplates = atoi(optarg);
143                         dbg_analyze_msg = (LoadTemplates & (1 << 1)) != 0;
144                         dbg_backtrace_template_errors = (LoadTemplates & (1 << 2)) != 0;
145                         break;
146                 case 'Z':
147                         DisableGzip = 1;
148                         break;
149                 case 'x':
150                         max_log_level = atoi(optarg);
151                         break;
152                 case 'f':
153                         follow_xff = 1;
154                         break;
155                 case 'c':
156                         server_cookie = malloc(256);
157                         if (server_cookie != NULL) {
158                                 safestrncpy(server_cookie, "Set-cookie: wcserver=", 256);
159                                 if (gethostname(&server_cookie[strlen(server_cookie)], 200) != 0) {
160                                         syslog(LOG_INFO, "gethostname: %s", strerror(errno));
161                                         free(server_cookie);
162                                 }
163                         }
164                         break;
165 #ifdef HAVE_OPENSSL
166                 case 's':
167                         is_https = 1;
168                         break;
169                 case 'S':
170                         is_https = 1;
171                         ssl_cipher_list = strdup(optarg);
172                         break;
173 #endif
174                 case 'G':
175                         DumpTemplateI18NStrings = 1;
176                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
177                         I18nDumpFile = optarg;
178                         break;
179                 case 'v':
180                         verbose = 1;
181                         break;
182                 default:
183                         fprintf(stderr, "usage:\nwebcit "
184                                 "[-i ip_addr] [-p http_port] "
185                                 "[-c] [-f] "
186                                 "[-T Templatedebuglevel] "
187                                 "[-d] [-Z] [-G i18ndumpfile] "
188                                 "[-u uid] [-h homedirectory] " "[-D daemonizepid] [-v] " "[-g defaultlandingpage] "
189 #ifdef HAVE_OPENSSL
190                                 "[-s] [-S cipher_suites]"
191 #endif
192                                 "[citadel_server_directory]\n");
193                         return 1;
194                 }
195
196         /* Start the logger */
197         setlogmask(LOG_UPTO(max_log_level));
198         openlog("webcit", (running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR)), LOG_DAEMON);
199
200         while (optind < argc) {
201                 ctdl_dir = strdup(argv[optind]);
202                 ++optind;
203         }
204
205         /* daemonize, if we were asked to */
206         if (!DumpTemplateI18NStrings && running_as_daemon) {
207                 start_daemon(pidfile);
208         }
209         else {
210                 signal(SIGINT, graceful_shutdown);
211                 signal(SIGHUP, graceful_shutdown);
212         }
213
214         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
215         LoadMimeBlacklist();
216         LoadIconDir(static_icon_dir);
217
218         /* Tell 'em who's in da house */
219         syslog(LOG_NOTICE, "%s", PACKAGE_STRING);
220         syslog(LOG_NOTICE, "Copyright (C) 1996-2022 by the citadel.org team");
221         syslog(LOG_NOTICE, " ");
222         syslog(LOG_NOTICE, "This program is open source software: you can redistribute it and/or");
223         syslog(LOG_NOTICE, "modify it under the terms of the GNU General Public License, version 3.");
224         syslog(LOG_NOTICE, " ");
225         syslog(LOG_NOTICE, "This program is distributed in the hope that it will be useful,");
226         syslog(LOG_NOTICE, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
227         syslog(LOG_NOTICE, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
228         syslog(LOG_NOTICE, "GNU General Public License for more details.");
229         syslog(LOG_NOTICE, " ");
230
231         /* run from the webcit home directory */
232         if (chdir(webcitdir) != 0) {
233                 syslog(LOG_ERR, "webcit: %s: %m", webcitdir);
234                 exit(errno);
235         }
236
237         /* initialize various subsystems */
238         initialise_modules();
239         initialise2_modules();
240         InitTemplateCache();
241         if (DumpTemplateI18NStrings) {
242                 FILE *fd;
243                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
244                 if (StrLength(I18nDump) < 50) {
245                         syslog(LOG_INFO, "*******************************************************************\n");
246                         syslog(LOG_INFO, "*   No strings found in templates!  Are you sure they're there?   *\n");
247                         syslog(LOG_INFO, "*******************************************************************\n");
248                         return -1;
249                 }
250                 fd = fopen(I18nDumpFile, "w");
251                 if (fd == NULL) {
252                         syslog(LOG_INFO, "***********************************************\n");
253                         syslog(LOG_INFO, "*   unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
254                         syslog(LOG_INFO, "***********************************************\n");
255                         return -1;
256                 }
257                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
258                 fclose(fd);
259                 return 0;
260         }
261
262         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
263
264 #ifdef LIBICAL_ICAL_EXPORT      // cheap and sleazy way to detect libical >=2.0
265         icalerror_set_errors_are_fatal(0);
266 #else
267         icalerror_errors_are_fatal = 0;
268 #endif
269
270         /* Use our own prefix on tzid's generated from system tzdata */
271         icaltimezone_set_tzid_prefix("/citadel.org/");
272
273         /*
274          * Set up a place to put thread-specific data.
275          * We only need a single pointer per thread - it points to the
276          * wcsession struct to which the thread is currently bound.
277          */
278         if (pthread_key_create(&MyConKey, NULL) != 0) {
279                 syslog(LOG_ERR, "Can't create TSD key: %s", strerror(errno));
280         }
281         InitialiseSemaphores();
282
283         /*
284          * Set up a place to put thread-specific SSL data.
285          * We don't stick this in the wcsession struct because SSL starts
286          * up before the session is bound, and it gets torn down between
287          * transactions.
288          */
289 #ifdef HAVE_OPENSSL
290         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
291                 syslog(LOG_ERR, "Can't create TSD key: %s", strerror(errno));
292         }
293 #endif
294
295         /*
296          * Bind the server to our favorite port.
297          * There is no need to check for errors, because webcit_tcp_server()
298          * exits if it doesn't succeed.
299          */
300
301         if (!IsEmptyStr(uds_listen_path)) {
302                 syslog(LOG_DEBUG, "Attempting to create listener socket at %s...", uds_listen_path);
303                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
304         }
305         else {
306                 syslog(LOG_DEBUG, "Attempting to bind to port %d...", http_port);
307                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
308         }
309         if (msock < 0) {
310                 ShutDownWebcit();
311                 return -msock;
312         }
313
314         syslog(LOG_INFO, "Listening on socket %d", msock);
315         signal(SIGPIPE, SIG_IGN);
316
317         pthread_mutex_init(&SessionListMutex, NULL);
318
319         // Start up the housekeeping thread
320         pthread_attr_init(&attr);
321         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
322         pthread_create(&SessThread, &attr, (void *(*)(void *)) housekeeping_loop, NULL);
323
324         // If this is an HTTPS server, fire up SSL
325 #ifdef HAVE_OPENSSL
326         if (is_https) {
327                 init_ssl();
328         }
329 #endif
330         drop_root(UID);
331
332         // Become a worker thread.  More worker threads will be spawned as they are needed.
333         worker_entry();
334         ShutDownLibCitadel();
335         return 0;
336 }