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