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