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