Readloop remove special cases
[citadel.git] / webcit / webserver.c
1 /*
2  * Copyright (c) 1996-2012 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 #ifndef HAVE_SNPRINTF
18 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
19 #endif
20
21 extern int msock;                               /* master listening socket */
22 extern char static_icon_dir[PATH_MAX];          /* where should we find our mime icons */
23 int is_https = 0;                               /* Nonzero if I am an HTTPS service */
24 int follow_xff = 0;                             /* Follow X-Forwarded-For: header? */
25 int DisableGzip = 0;
26 char *default_landing_page = NULL;
27 extern pthread_mutex_t SessionListMutex;
28 extern pthread_key_t MyConKey;
29
30 extern void *housekeeping_loop(void);
31 extern int webcit_tcp_server(char *ip_addr, int port_number, int queue_len);
32 extern int webcit_uds_server(char *sockpath, int queue_len);
33 extern void graceful_shutdown_watcher(int signum);
34 extern void graceful_shutdown(int signum);
35 extern void start_daemon(char *pid_file);
36 extern void webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome);
37 extern void worker_entry(void);
38 extern void drop_root(uid_t UID);
39
40 char socket_dir[PATH_MAX];      /* where to talk to our citadel server */
41 char *server_cookie = NULL;     /* our Cookie connection to the client */
42 int http_port = PORT_NUM;       /* Port to listen on */
43 char *ctdlhost = DEFAULT_HOST;  /* Host name or IP address of Citadel server */
44 char *ctdlport = DEFAULT_PORT;  /* Port number of Citadel server */
45 int setup_wizard = 0;           /* should we run the setup wizard? */
46 char wizard_filename[PATH_MAX]; /* location of file containing the last webcit version against which we ran setup wizard */
47 int running_as_daemon = 0;      /* should we deamonize on startup? */
48
49 /* #define DBG_PRINNT_HOOKS_AT_START */
50 #ifdef DBG_PRINNT_HOOKS_AT_START
51 extern HashList *HandlerHash;
52 const char foobuf[32];
53 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
54 #endif 
55 extern int dbg_analyze_msg;
56 extern int dbg_backtrace_template_errors;
57 extern int DumpTemplateI18NStrings;
58 extern StrBuf *I18nDump;
59 void InitTemplateCache(void);
60 extern int LoadTemplates;
61
62
63 /*
64  * Here's where it all begins.
65  */
66 int main(int argc, char **argv)
67 {
68         uid_t UID = -1;
69         size_t basesize = 2;            /* how big should strbufs be on creation? */
70         pthread_t SessThread;           /* Thread descriptor */
71         pthread_attr_t attr;            /* Thread attributes */
72         int a;                          /* General-purpose variable */
73         char ip_addr[256]="*";
74         int relh=0;
75         int home=0;
76         char relhome[PATH_MAX]="";
77         char webcitdir[PATH_MAX] = DATADIR;
78         char *pidfile = NULL;
79         char *hdir;
80         const char *basedir = NULL;
81         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
82         const char *I18nDumpFile = NULL;
83
84         WildFireInitBacktrace(argv[0], 2);
85
86         start_modules();
87
88 #ifdef DBG_PRINNT_HOOKS_AT_START
89 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
90 #endif
91
92         /* Ensure that we are linked to the correct version of libcitadel */
93         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
94                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
95                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
96                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
97                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
98                 return(1);
99         }
100
101         strcpy(uds_listen_path, "");
102
103         /* Parse command line */
104 #ifdef HAVE_OPENSSL
105         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfsS:Z")) != EOF)
106 #else
107         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:g:dD:G:cfZ")) != EOF)
108 #endif
109                 switch (a) {
110                 case 'u':
111                         UID = atol(optarg);
112                         break;
113                 case 'h':
114                         hdir = strdup(optarg);
115                         relh=hdir[0]!='/';
116                         if (!relh) {
117                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
118                         }
119                         else {
120                                 safestrncpy(relhome, relhome, sizeof relhome);
121                         }
122                         /* free(hdir); TODO: SHOULD WE DO THIS? */
123                         home=1;
124                         break;
125                 case 'd':
126                         running_as_daemon = 1;
127                         break;
128                 case 'D':
129                         pidfile = strdup(optarg);
130                         running_as_daemon = 1;
131                         break;
132                 case 'g':
133                         default_landing_page = strdup(optarg);
134                         break;
135                 case 'B': /* Basesize */
136                         basesize = atoi(optarg);
137                         if (basesize > 2)
138                                 StartLibCitadel(basesize);
139                         break;
140                 case 'i':
141                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
142                         break;
143                 case 'p':
144                         http_port = atoi(optarg);
145                         if (http_port == 0) {
146                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
147                         }
148                         break;
149                 case 't':
150                         /* no longer used, but ignored so old scripts don't break */
151                         break;
152                 case 'T':
153                         LoadTemplates = atoi(optarg);
154                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
155                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
156                         break;
157                 case 'Z':
158                         DisableGzip = 1;
159                         break;
160                 case 'x':
161                         /* no longer used, but ignored so old scripts don't break */
162                         break;
163                 case 'f':
164                         follow_xff = 1;
165                         break;
166                 case 'c':
167                         server_cookie = malloc(256);
168                         if (server_cookie != NULL) {
169                                 safestrncpy(server_cookie,
170                                        "Set-cookie: wcserver=",
171                                         256);
172                                 if (gethostname
173                                     (&server_cookie[strlen(server_cookie)],
174                                      200) != 0) {
175                                         syslog(2, "gethostname: %s", strerror(errno));
176                                         free(server_cookie);
177                                 }
178                         }
179                         break;
180 #ifdef HAVE_OPENSSL
181                 case 's':
182                         is_https = 1;
183                         break;
184                 case 'S':
185                         is_https = 1;
186                         ssl_cipher_list = strdup(optarg);
187                         break;
188 #endif
189                 case 'G':
190                         DumpTemplateI18NStrings = 1;
191                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
192                         I18nDumpFile = optarg;
193                         break;
194                 default:
195                         fprintf(stderr, "usage: webcit "
196                                 "[-i ip_addr] [-p http_port] "
197                                 "[-c] [-f] "
198                                 "[-T Templatedebuglevel] "
199                                 "[-d] [-Z] [-G i18ndumpfile] "
200 #ifdef HAVE_OPENSSL
201                                 "[-s] [-S cipher_suites]"
202 #endif
203                                 "[remotehost [remoteport]]\n");
204                         return 1;
205                 }
206
207         /* Start the logger */
208         openlog("webcit",
209                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
210                 LOG_DAEMON
211         );
212
213         if (optind < argc) {
214                 ctdlhost = argv[optind];
215                 if (++optind < argc)
216                         ctdlport = argv[optind];
217         }
218
219         /* daemonize, if we were asked to */
220         if (!DumpTemplateI18NStrings && running_as_daemon) {
221                 start_daemon(pidfile);
222         }
223         else {
224                 signal(SIGINT, graceful_shutdown);
225                 signal(SIGHUP, graceful_shutdown);
226         }
227
228         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
229         LoadIconDir(static_icon_dir);
230
231         /* Tell 'em who's in da house */
232         syslog(1, "%s", PACKAGE_STRING);
233         syslog(1, "Copyright (C) 1996-2012 by the citadel.org team");
234         syslog(1, " ");
235         syslog(1, "This program is open source software: you can redistribute it and/or");
236         syslog(1, "modify it under the terms of the GNU General Public License as published");
237         syslog(1, "by the Free Software Foundation, either version 3 of the License, or");
238         syslog(1, "(at your option) any later version.");
239         syslog(1, " ");
240         syslog(1, "This program is distributed in the hope that it will be useful,");
241         syslog(1, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
242         syslog(1, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
243         syslog(1, "GNU General Public License for more details.");
244         syslog(1, " ");
245         syslog(1, "You should have received a copy of the GNU General Public License");
246         syslog(1, "along with this program.  If not, see <http://www.gnu.org/licenses/>.");
247         syslog(1, " ");
248
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(1, "*******************************************************************\n");
260                         syslog(1, "*   No strings found in templates!  Are you sure they're there?   *\n");
261                         syslog(1, "*******************************************************************\n");
262                         return -1;
263                 }
264                 fd = fopen(I18nDumpFile, "w");
265                 if (fd == NULL) {
266                         syslog(1, "***********************************************\n");
267                         syslog(1, "*   unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
268                         syslog(1, "***********************************************\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(1, "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(1, "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(2, "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(2, "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(2, "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