db3a01aa9c9ce1f114e1445869b174ffe9626fc1
[citadel.git] / webcit / webserver.c
1 /*
2  * Copyright (c) 1996-2013 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 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.%02d\n",
93                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
94                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
95                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
96                 return(1);
97         }
98
99         strcpy(uds_listen_path, "");
100
101         /* Parse command line */
102 #ifdef HAVE_OPENSSL
103         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z")) != EOF)
104 #else
105         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfZ")) != EOF)
106 #endif
107                 switch (a) {
108                 case 'u':
109                         UID = atol(optarg);
110                         break;
111                 case 'h':
112                         hdir = strdup(optarg);
113                         relh=hdir[0]!='/';
114                         if (!relh) {
115                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
116                         }
117                         else {
118                                 safestrncpy(relhome, relhome, sizeof relhome);
119                         }
120                         /* free(hdir); TODO: SHOULD WE DO THIS? */
121                         home=1;
122                         break;
123                 case 'd':
124                         running_as_daemon = 1;
125                         break;
126                 case 'D':
127                         pidfile = strdup(optarg);
128                         running_as_daemon = 1;
129                         break;
130                 case 'g':
131                         default_landing_page = strdup(optarg);
132                         break;
133                 case 'B': /* Basesize */
134                         basesize = atoi(optarg);
135                         if (basesize > 2)
136                                 StartLibCitadel(basesize);
137                         break;
138                 case 'i':
139                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
140                         break;
141                 case 'p':
142                         http_port = atoi(optarg);
143                         if (http_port == 0) {
144                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
145                         }
146                         break;
147                 case 't':
148                         /* no longer used, but ignored so old scripts don't break */
149                         break;
150                 case 'T':
151                         LoadTemplates = atoi(optarg);
152                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
153                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
154                         break;
155                 case 'Z':
156                         DisableGzip = 1;
157                         break;
158                 case 'x':
159                         /* no longer used, but ignored so old scripts don't break */
160                         break;
161                 case 'f':
162                         follow_xff = 1;
163                         break;
164                 case 'c':
165                         server_cookie = malloc(256);
166                         if (server_cookie != NULL) {
167                                 safestrncpy(server_cookie,
168                                        "Set-cookie: wcserver=",
169                                         256);
170                                 if (gethostname
171                                     (&server_cookie[strlen(server_cookie)],
172                                      200) != 0) {
173                                         syslog(LOG_INFO, "gethostname: %s", strerror(errno));
174                                         free(server_cookie);
175                                 }
176                         }
177                         break;
178 #ifdef HAVE_OPENSSL
179                 case 's':
180                         is_https = 1;
181                         break;
182                 case 'S':
183                         is_https = 1;
184                         ssl_cipher_list = strdup(optarg);
185                         break;
186 #endif
187                 case 'G':
188                         DumpTemplateI18NStrings = 1;
189                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
190                         I18nDumpFile = optarg;
191                         break;
192                 default:
193                         fprintf(stderr, "usage: webcit "
194                                 "[-i ip_addr] [-p http_port] "
195                                 "[-c] [-f] "
196                                 "[-T Templatedebuglevel] "
197                                 "[-d] [-Z] [-G i18ndumpfile] "
198 #ifdef HAVE_OPENSSL
199                                 "[-s] [-S cipher_suites]"
200 #endif
201                                 "[remotehost [remoteport]]\n");
202                         return 1;
203                 }
204
205         /* Start the logger */
206         openlog("webcit",
207                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
208                 LOG_DAEMON
209         );
210
211         if (optind < argc) {
212                 ctdlhost = argv[optind];
213                 if (++optind < argc)
214                         ctdlport = argv[optind];
215         }
216
217         /* daemonize, if we were asked to */
218         if (!DumpTemplateI18NStrings && running_as_daemon) {
219                 start_daemon(pidfile);
220         }
221         else {
222                 signal(SIGINT, graceful_shutdown);
223                 signal(SIGHUP, graceful_shutdown);
224         }
225
226         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
227         LoadMimeBlacklist();
228         LoadIconDir(static_icon_dir);
229
230         /* Tell 'em who's in da house */
231         syslog(LOG_NOTICE, "%s", PACKAGE_STRING);
232         syslog(LOG_NOTICE, "Copyright (C) 1996-2013 by the citadel.org team");
233         syslog(LOG_NOTICE, " ");
234         syslog(LOG_NOTICE, "This program is open source software: you can redistribute it and/or");
235         syslog(LOG_NOTICE, "modify it under the terms of the GNU General Public License, version 3.");
236         syslog(LOG_NOTICE, " ");
237         syslog(LOG_NOTICE, "This program is distributed in the hope that it will be useful,");
238         syslog(LOG_NOTICE, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
239         syslog(LOG_NOTICE, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
240         syslog(LOG_NOTICE, "GNU General Public License for more details.");
241         syslog(LOG_NOTICE, " ");
242
243         /* initialize various subsystems */
244
245         initialise_modules();
246         initialise2_modules();
247         InitTemplateCache();
248         if (DumpTemplateI18NStrings) {
249                 FILE *fd;
250                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
251                 if (StrLength(I18nDump) < 50) {
252                         syslog(LOG_INFO, "*******************************************************************\n");
253                         syslog(LOG_INFO, "*   No strings found in templates!  Are you sure they're there?   *\n");
254                         syslog(LOG_INFO, "*******************************************************************\n");
255                         return -1;
256                 }
257                 fd = fopen(I18nDumpFile, "w");
258                 if (fd == NULL) {
259                         syslog(LOG_INFO, "***********************************************\n");
260                         syslog(LOG_INFO, "*   unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
261                         syslog(LOG_INFO, "***********************************************\n");
262                         return -1;
263                 }
264                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
265                 fclose(fd);
266                 return 0;
267         }
268
269         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
270         icalerror_errors_are_fatal = 0;
271
272         /* Use our own prefix on tzid's generated from system tzdata */
273         icaltimezone_set_tzid_prefix("/citadel.org/");
274
275         /*
276          * Set up a place to put thread-specific data.
277          * We only need a single pointer per thread - it points to the
278          * wcsession struct to which the thread is currently bound.
279          */
280         if (pthread_key_create(&MyConKey, NULL) != 0) {
281                 syslog(LOG_EMERG, "Can't create TSD key: %s", strerror(errno));
282         }
283         InitialiseSemaphores();
284
285         /*
286          * Set up a place to put thread-specific SSL data.
287          * We don't stick this in the wcsession struct because SSL starts
288          * up before the session is bound, and it gets torn down between
289          * transactions.
290          */
291 #ifdef HAVE_OPENSSL
292         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
293                 syslog(LOG_EMERG, "Can't create TSD key: %s", strerror(errno));
294         }
295 #endif
296
297         /*
298          * Bind the server to our favorite port.
299          * There is no need to check for errors, because webcit_tcp_server()
300          * exits if it doesn't succeed.
301          */
302
303         if (!IsEmptyStr(uds_listen_path)) {
304                 syslog(LOG_DEBUG, "Attempting to create listener socket at %s...", uds_listen_path);
305                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
306         }
307         else {
308                 syslog(LOG_DEBUG, "Attempting to bind to port %d...", http_port);
309                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
310         }
311         if (msock < 0)
312         {
313                 ShutDownWebcit();
314                 return -msock;
315         }
316
317         syslog(LOG_INFO, "Listening on socket %d", msock);
318         signal(SIGPIPE, SIG_IGN);
319
320         pthread_mutex_init(&SessionListMutex, NULL);
321
322         /*
323          * Start up the housekeeping thread
324          */
325         pthread_attr_init(&attr);
326         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
327         pthread_create(&SessThread, &attr, (void *(*)(void *)) housekeeping_loop, NULL);
328
329         /*
330          * If this is an HTTPS server, fire up SSL
331          */
332 #ifdef HAVE_OPENSSL
333         if (is_https) {
334                 init_ssl();
335         }
336 #endif
337         drop_root(UID);
338
339         /* Become a worker thread.  More worker threads will be spawned as they are needed. */
340         worker_entry();
341         ShutDownLibCitadel();
342         return 0;
343 }
344
345
346
347
348
349
350