* fix multiple compiler warnings...
[citadel.git] / webcit / webserver.c
1 /*
2  * This contains a simple multithreaded TCP server manager.  It sits around
3  * waiting on the specified port for incoming HTTP connections.  When a
4  * connection is established, it calls context_loop() from context_loop.c.
5  *
6  * Copyright (c) 1996-2011 by the citadel.org developers.
7  * This program is released under the terms of the GNU General Public License v3.
8  *
9  */
10
11 #include "webcit.h"
12 #include "webserver.h"
13
14 #include "modules_init.h"
15 #ifndef HAVE_SNPRINTF
16 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
17 #endif
18
19
20 extern int msock;                       /* master listening socket */
21 extern int verbosity;           /* Logging level */
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 home_specified = 0;         /* did the user specify a homedir? */
26 int DisableGzip = 0;
27 struct redirector *redir = NULL;
28 int num_redir = 0;
29 extern pthread_mutex_t SessionListMutex;
30 extern pthread_key_t MyConKey;
31
32 extern void *housekeeping_loop(void);
33 extern int webcit_tcp_server(char *ip_addr, int port_number, int queue_len);
34 extern int webcit_uds_server(char *sockpath, int queue_len);
35 extern void graceful_shutdown_watcher(int signum);
36 extern void graceful_shutdown(int signum);
37 extern void start_daemon(char *pid_file);
38 extern void webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome);
39
40 extern void drop_root(uid_t UID);
41
42 char socket_dir[PATH_MAX];                      /* where to talk to our citadel server */
43
44 char *server_cookie = NULL;     /* our Cookie connection to the client */
45 int http_port = PORT_NUM;       /* Port to listen on */
46 char *ctdlhost = DEFAULT_HOST;  /* our name */
47 char *ctdlport = DEFAULT_PORT;  /* our Port */
48 int setup_wizard = 0;           /* should we run the setup wizard? \todo */
49 char wizard_filename[PATH_MAX]; /* where's the setup wizard? */
50 int running_as_daemon = 0;      /* should we deamonize on startup? */
51
52
53
54 /* #define DBG_PRINNT_HOOKS_AT_START */
55 #ifdef DBG_PRINNT_HOOKS_AT_START
56 extern HashList *HandlerHash;
57 const char foobuf[32];
58 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
59 #endif 
60 extern int dbg_analyze_msg;
61 extern int dbg_backtrace_template_errors;
62 extern int DumpTemplateI18NStrings;
63 extern StrBuf *I18nDump;
64 void InitTemplateCache(void);
65 extern int LoadTemplates;
66
67
68
69
70
71 /*
72  * Handle redirects to legacy web servers
73  */
74 void handle_redir(void) {
75         if (num_redir > 0) {
76                 int i;
77                 const char *req = ChrPtr(WC->Hdr->this_page);
78                 if (!req) {
79                         do_404();
80                         return;
81                 }
82                 if (req[0] == '/') ++req;
83                 syslog(9, "handle_redir() called; redirect this: %s", req);
84                 for (i=0; i<num_redir; ++i) {
85                         if (!strncmp(redir[i].urlpart, req, strlen(redir[i].urlpart))) {
86                                 char go_here[1024];
87                                 snprintf(go_here, sizeof go_here, redir[i].redirect_to, req);
88                                 syslog(9, "redirecting to: %s", go_here);
89                                 http_redirect(go_here);
90                                 return;
91                         }
92                 }
93         }
94         do_404();
95 }
96
97
98
99 /*
100  * load redirect strings (for supporting transition of legacy web servers to citadel on the same host)
101  */
102 void load_redirs(char *filename) {
103         char buf[1024];
104         int num_redir_alloc = num_redir;
105         FILE *fp = fopen(filename, "r");
106         if (!fp) {
107                 syslog(1, "Cannot open %s: %s", filename, strerror(errno));
108                 return;
109         }
110
111         while (fgets(buf, sizeof buf, fp) != NULL) {
112                 char *ch;
113
114                 buf[strlen(buf)-1] = 0;
115
116                 ch = strchr(buf, '#');
117                 if (ch) strcpy(ch, "");
118                 striplt(buf);
119                 if (!IsEmptyStr(buf)) {
120
121                         if (num_redir >= num_redir_alloc) {
122                                 if (num_redir_alloc == 0) {
123                                         num_redir_alloc = 10;
124                                 }
125                                 else {
126                                         num_redir_alloc = num_redir_alloc * 2;
127                                 }
128                                 redir = realloc(redir, sizeof(struct redirector) * num_redir_alloc );
129                         }
130         
131                         extract_token(redir[num_redir].urlpart, buf, 0, '|', sizeof(redir[num_redir].urlpart));
132                         extract_token(redir[num_redir].redirect_to, buf, 1, '|', sizeof(redir[num_redir].redirect_to));
133                         WebcitAddUrlHandler(redir[num_redir].urlpart, strlen(redir[num_redir].urlpart), "", 0, handle_redir, ANONYMOUS|COOKIEUNNEEDED|ISSTATIC);
134                         ++num_redir;
135                 }
136
137         }
138         fclose(fp);
139 }
140
141
142
143 /*
144  * Here's where it all begins.
145  */
146 int main(int argc, char **argv)
147 {
148         uid_t UID = -1;
149         size_t basesize = 2;            /* how big should strbufs be on creation? */
150         pthread_t SessThread;           /* Thread descriptor */
151         pthread_attr_t attr;            /* Thread attributes */
152         int a;                          /* General-purpose variable */
153         char tracefile[PATH_MAX];
154         char ip_addr[256]="*";
155         int relh=0;
156         int home=0;
157         int home_specified=0;
158         char relhome[PATH_MAX]="";
159         char webcitdir[PATH_MAX] = DATADIR;
160         char *pidfile = NULL;
161         char *hdir;
162         const char *basedir = NULL;
163         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
164         const char *I18nDumpFile = NULL;
165         FILE *rvfp = NULL;
166         int rv = 0;
167
168         WildFireInitBacktrace(argv[0], 2);
169
170         start_modules ();
171
172 #ifdef DBG_PRINNT_HOOKS_AT_START
173 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
174 #endif
175
176         /* Ensure that we are linked to the correct version of libcitadel */
177         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
178                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
179                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
180                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
181                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
182                 return(1);
183         }
184
185         strcpy(uds_listen_path, "");
186
187         /* Parse command line */
188 #ifdef HAVE_OPENSSL
189         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:dD:G:r:cfsS:Z")) != EOF)
190 #else
191         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:dD:G:r:cfZ")) != EOF)
192 #endif
193                 switch (a) {
194                 case 'u':
195                         UID = atol(optarg);
196                         break;
197                 case 'r':
198                         load_redirs(optarg);
199                         break;
200                 case 'h':
201                         hdir = strdup(optarg);
202                         relh=hdir[0]!='/';
203                         if (!relh) {
204                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
205                         }
206                         else {
207                                 safestrncpy(relhome, relhome, sizeof relhome);
208                         }
209                         /* free(hdir); TODO: SHOULD WE DO THIS? */
210                         home_specified = 1;
211                         home=1;
212                         break;
213                 case 'd':
214                         running_as_daemon = 1;
215                         break;
216                 case 'D':
217                         pidfile = strdup(optarg);
218                         running_as_daemon = 1;
219                         break;
220                 case 'B': /* Basesize */
221                         basesize = atoi(optarg);
222                         if (basesize > 2)
223                                 StartLibCitadel(basesize);
224                         break;
225                 case 'i':
226                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
227                         break;
228                 case 'p':
229                         http_port = atoi(optarg);
230                         if (http_port == 0) {
231                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
232                         }
233                         break;
234                 case 't':
235                         safestrncpy(tracefile, optarg, sizeof tracefile);
236                         rvfp = freopen(tracefile, "w", stdout);
237                         rvfp = freopen(tracefile, "w", stderr);
238                         rvfp = freopen(tracefile, "r", stdin);
239                         break;
240                 case 'T':
241                         LoadTemplates = atoi(optarg);
242                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
243                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
244                         break;
245                 case 'Z':
246                         DisableGzip = 1;
247                         break;
248                 case 'x':
249                         verbosity = atoi(optarg);
250                         break;
251                 case 'f':
252                         follow_xff = 1;
253                         break;
254                 case 'c':
255                         server_cookie = malloc(256);
256                         if (server_cookie != NULL) {
257                                 safestrncpy(server_cookie,
258                                        "Set-cookie: wcserver=",
259                                         256);
260                                 if (gethostname
261                                     (&server_cookie[strlen(server_cookie)],
262                                      200) != 0) {
263                                         syslog(2, "gethostname: %s", strerror(errno));
264                                         free(server_cookie);
265                                 }
266                         }
267                         break;
268 #ifdef HAVE_OPENSSL
269                 case 's':
270                         is_https = 1;
271                         break;
272                 case 'S':
273                         is_https = 1;
274                         ssl_cipher_list = strdup(optarg);
275                         break;
276 #endif
277                 case 'G':
278                         DumpTemplateI18NStrings = 1;
279                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
280                         I18nDumpFile = optarg;
281                         break;
282                 default:
283                         fprintf(stderr, "usage: webcit "
284                                 "[-i ip_addr] [-p http_port] "
285                                 "[-t tracefile] [-c] [-f] "
286                                 "[-T Templatedebuglevel] "
287                                 "[-d] [-Z] [-G i18ndumpfile] "
288 #ifdef HAVE_OPENSSL
289                                 "[-s] [-S cipher_suites]"
290 #endif
291                                 "[remotehost [remoteport]]\n");
292                         return 1;
293                 }
294
295         /* Start the logger */
296         openlog("webcit",
297                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
298                 LOG_DAEMON
299         );
300
301         if (optind < argc) {
302                 ctdlhost = argv[optind];
303                 if (++optind < argc)
304                         ctdlport = argv[optind];
305         }
306
307         /* daemonize, if we were asked to */
308         if (!DumpTemplateI18NStrings && running_as_daemon) {
309                 start_daemon(pidfile);
310         }
311         else {
312                 signal(SIGINT, graceful_shutdown);
313                 signal(SIGHUP, graceful_shutdown);
314         }
315
316         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
317         LoadIconDir(static_icon_dir);
318
319         /* Tell 'em who's in da house */
320         syslog(1, "%s", PACKAGE_STRING);
321         syslog(1, "Copyright (C) 1996-2011 by the citadel.org team");
322         syslog(1, " ");
323         syslog(1, "This program is open source software: you can redistribute it and/or");
324         syslog(1, "modify it under the terms of the GNU General Public License as published");
325         syslog(1, "by the Free Software Foundation, either version 3 of the License, or");
326         syslog(1, "(at your option) any later version.");
327         syslog(1, " ");
328         syslog(1, "This program is distributed in the hope that it will be useful,");
329         syslog(1, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
330         syslog(1, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
331         syslog(1, "GNU General Public License for more details.");
332         syslog(1, " ");
333         syslog(1, "You should have received a copy of the GNU General Public License");
334         syslog(1, "along with this program.  If not, see <http://www.gnu.org/licenses/>.");
335         syslog(1, " ");
336
337
338         /* initialize various subsystems */
339
340         initialise_modules();
341         InitTemplateCache();
342         if (DumpTemplateI18NStrings) {
343                 FILE *fd;
344                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
345                 if (StrLength(I18nDump) < 50) {
346                         syslog(1, "********************************************************************************\n");
347                         syslog(1, "*        No strings found in templates!  Are you sure they're there?           *\n");
348                         syslog(1, "********************************************************************************\n");
349                         return -1;
350                 }
351                 fd = fopen(I18nDumpFile, "w");
352                 if (fd == NULL) {
353                         syslog(1, "********************************************************************************\n");
354                         syslog(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
355                         syslog(1, "********************************************************************************\n");
356                         return -1;
357                 }
358                 rv = fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
359                 fclose(fd);
360                 return 0;
361         }
362
363
364         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
365         icalerror_errors_are_fatal = 0;
366
367         /* Use our own prefix on tzid's generated from system tzdata */
368         icaltimezone_set_tzid_prefix("/citadel.org/");
369
370         /*
371          * Set up a place to put thread-specific data.
372          * We only need a single pointer per thread - it points to the
373          * wcsession struct to which the thread is currently bound.
374          */
375         if (pthread_key_create(&MyConKey, NULL) != 0) {
376                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
377         }
378         InitialiseSemaphores ();
379
380         /*
381          * Set up a place to put thread-specific SSL data.
382          * We don't stick this in the wcsession struct because SSL starts
383          * up before the session is bound, and it gets torn down between
384          * transactions.
385          */
386 #ifdef HAVE_OPENSSL
387         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
388                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
389         }
390 #endif
391
392         /*
393          * Bind the server to our favorite port.
394          * There is no need to check for errors, because webcit_tcp_server()
395          * exits if it doesn't succeed.
396          */
397
398         if (!IsEmptyStr(uds_listen_path)) {
399                 syslog(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
400                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
401         }
402         else {
403                 syslog(2, "Attempting to bind to port %d...\n", http_port);
404                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
405         }
406         if (msock < 0)
407         {
408                 ShutDownWebcit();
409                 return -msock;
410         }
411
412         syslog(2, "Listening on socket %d\n", msock);
413         signal(SIGPIPE, SIG_IGN);
414
415         pthread_mutex_init(&SessionListMutex, NULL);
416
417         /*
418          * Start up the housekeeping thread
419          */
420         pthread_attr_init(&attr);
421         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
422         pthread_create(&SessThread, &attr,
423                        (void *(*)(void *)) housekeeping_loop, NULL);
424
425
426         /*
427          * If this is an HTTPS server, fire up SSL
428          */
429 #ifdef HAVE_OPENSSL
430         if (is_https) {
431                 init_ssl();
432         }
433 #endif
434         drop_root(UID);
435
436         /* Become a worker thread.  More worker threads will be spawned as they are needed. */
437         worker_entry();
438         ShutDownLibCitadel ();
439         return 0;
440 }
441
442
443
444
445
446
447