603265eca352f4605b881b092b8cec54c760eb19
[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 DisableGzip = 0;
26 struct redirector *redir = NULL;
27 char *default_landing_page = 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 extern void worker_entry(void);
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                         if (!strcasecmp(redir[num_redir].urlpart, "home")) {
135                                 default_landing_page = redir[num_redir].redirect_to ;
136                         }
137                         ++num_redir;
138                 }
139
140         }
141         fclose(fp);
142 }
143
144
145
146 /*
147  * Here's where it all begins.
148  */
149 int main(int argc, char **argv)
150 {
151         uid_t UID = -1;
152         size_t basesize = 2;            /* how big should strbufs be on creation? */
153         pthread_t SessThread;           /* Thread descriptor */
154         pthread_attr_t attr;            /* Thread attributes */
155         int a;                          /* General-purpose variable */
156         char tracefile[PATH_MAX];
157         char ip_addr[256]="*";
158         int relh=0;
159         int home=0;
160         char relhome[PATH_MAX]="";
161         char webcitdir[PATH_MAX] = DATADIR;
162         char *pidfile = NULL;
163         char *hdir;
164         const char *basedir = NULL;
165         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
166         const char *I18nDumpFile = NULL;
167         FILE *rvfp = NULL;
168         int rv = 0;
169
170         WildFireInitBacktrace(argv[0], 2);
171
172         start_modules ();
173
174 #ifdef DBG_PRINNT_HOOKS_AT_START
175 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
176 #endif
177
178         /* Ensure that we are linked to the correct version of libcitadel */
179         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
180                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
181                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
182                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
183                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
184                 return(1);
185         }
186
187         strcpy(uds_listen_path, "");
188
189         /* Parse command line */
190 #ifdef HAVE_OPENSSL
191         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:dD:G:r:cfsS:Z")) != EOF)
192 #else
193         while ((a = getopt(argc, argv, "u:h:i:p:t:T:B:x:dD:G:r:cfZ")) != EOF)
194 #endif
195                 switch (a) {
196                 case 'u':
197                         UID = atol(optarg);
198                         break;
199                 case 'r':
200                         load_redirs(optarg);
201                         break;
202                 case 'h':
203                         hdir = strdup(optarg);
204                         relh=hdir[0]!='/';
205                         if (!relh) {
206                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
207                         }
208                         else {
209                                 safestrncpy(relhome, relhome, sizeof relhome);
210                         }
211                         /* free(hdir); TODO: SHOULD WE DO THIS? */
212                         home=1;
213                         break;
214                 case 'd':
215                         running_as_daemon = 1;
216                         break;
217                 case 'D':
218                         pidfile = strdup(optarg);
219                         running_as_daemon = 1;
220                         break;
221                 case 'B': /* Basesize */
222                         basesize = atoi(optarg);
223                         if (basesize > 2)
224                                 StartLibCitadel(basesize);
225                         break;
226                 case 'i':
227                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
228                         break;
229                 case 'p':
230                         http_port = atoi(optarg);
231                         if (http_port == 0) {
232                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
233                         }
234                         break;
235                 case 't':
236                         safestrncpy(tracefile, optarg, sizeof tracefile);
237                         rvfp = freopen(tracefile, "w", stdout);
238                         rvfp = freopen(tracefile, "w", stderr);
239                         rvfp = freopen(tracefile, "r", stdin);
240                         break;
241                 case 'T':
242                         LoadTemplates = atoi(optarg);
243                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
244                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
245                         break;
246                 case 'Z':
247                         DisableGzip = 1;
248                         break;
249                 case 'x':
250                         verbosity = atoi(optarg);
251                         break;
252                 case 'f':
253                         follow_xff = 1;
254                         break;
255                 case 'c':
256                         server_cookie = malloc(256);
257                         if (server_cookie != NULL) {
258                                 safestrncpy(server_cookie,
259                                        "Set-cookie: wcserver=",
260                                         256);
261                                 if (gethostname
262                                     (&server_cookie[strlen(server_cookie)],
263                                      200) != 0) {
264                                         syslog(2, "gethostname: %s", strerror(errno));
265                                         free(server_cookie);
266                                 }
267                         }
268                         break;
269 #ifdef HAVE_OPENSSL
270                 case 's':
271                         is_https = 1;
272                         break;
273                 case 'S':
274                         is_https = 1;
275                         ssl_cipher_list = strdup(optarg);
276                         break;
277 #endif
278                 case 'G':
279                         DumpTemplateI18NStrings = 1;
280                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
281                         I18nDumpFile = optarg;
282                         break;
283                 default:
284                         fprintf(stderr, "usage: webcit "
285                                 "[-i ip_addr] [-p http_port] "
286                                 "[-t tracefile] [-c] [-f] "
287                                 "[-T Templatedebuglevel] "
288                                 "[-d] [-Z] [-G i18ndumpfile] "
289 #ifdef HAVE_OPENSSL
290                                 "[-s] [-S cipher_suites]"
291 #endif
292                                 "[remotehost [remoteport]]\n");
293                         return 1;
294                 }
295
296         /* Start the logger */
297         openlog("webcit",
298                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
299                 LOG_DAEMON
300         );
301
302         if (optind < argc) {
303                 ctdlhost = argv[optind];
304                 if (++optind < argc)
305                         ctdlport = argv[optind];
306         }
307
308         /* daemonize, if we were asked to */
309         if (!DumpTemplateI18NStrings && running_as_daemon) {
310                 start_daemon(pidfile);
311         }
312         else {
313                 signal(SIGINT, graceful_shutdown);
314                 signal(SIGHUP, graceful_shutdown);
315         }
316
317         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
318         LoadIconDir(static_icon_dir);
319
320         /* Tell 'em who's in da house */
321         syslog(1, "%s", PACKAGE_STRING);
322         syslog(1, "Copyright (C) 1996-2011 by the citadel.org team");
323         syslog(1, " ");
324         syslog(1, "This program is open source software: you can redistribute it and/or");
325         syslog(1, "modify it under the terms of the GNU General Public License as published");
326         syslog(1, "by the Free Software Foundation, either version 3 of the License, or");
327         syslog(1, "(at your option) any later version.");
328         syslog(1, " ");
329         syslog(1, "This program is distributed in the hope that it will be useful,");
330         syslog(1, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
331         syslog(1, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
332         syslog(1, "GNU General Public License for more details.");
333         syslog(1, " ");
334         syslog(1, "You should have received a copy of the GNU General Public License");
335         syslog(1, "along with this program.  If not, see <http://www.gnu.org/licenses/>.");
336         syslog(1, " ");
337
338
339         /* initialize various subsystems */
340
341         initialise_modules();
342         InitTemplateCache();
343         if (DumpTemplateI18NStrings) {
344                 FILE *fd;
345                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
346                 if (StrLength(I18nDump) < 50) {
347                         syslog(1, "********************************************************************************\n");
348                         syslog(1, "*        No strings found in templates!  Are you sure they're there?           *\n");
349                         syslog(1, "********************************************************************************\n");
350                         return -1;
351                 }
352                 fd = fopen(I18nDumpFile, "w");
353                 if (fd == NULL) {
354                         syslog(1, "********************************************************************************\n");
355                         syslog(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
356                         syslog(1, "********************************************************************************\n");
357                         return -1;
358                 }
359                 rv = fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
360                 fclose(fd);
361                 return 0;
362         }
363
364
365         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
366         icalerror_errors_are_fatal = 0;
367
368         /* Use our own prefix on tzid's generated from system tzdata */
369         icaltimezone_set_tzid_prefix("/citadel.org/");
370
371         /*
372          * Set up a place to put thread-specific data.
373          * We only need a single pointer per thread - it points to the
374          * wcsession struct to which the thread is currently bound.
375          */
376         if (pthread_key_create(&MyConKey, NULL) != 0) {
377                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
378         }
379         InitialiseSemaphores ();
380
381         /*
382          * Set up a place to put thread-specific SSL data.
383          * We don't stick this in the wcsession struct because SSL starts
384          * up before the session is bound, and it gets torn down between
385          * transactions.
386          */
387 #ifdef HAVE_OPENSSL
388         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
389                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
390         }
391 #endif
392
393         /*
394          * Bind the server to our favorite port.
395          * There is no need to check for errors, because webcit_tcp_server()
396          * exits if it doesn't succeed.
397          */
398
399         if (!IsEmptyStr(uds_listen_path)) {
400                 syslog(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
401                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
402         }
403         else {
404                 syslog(2, "Attempting to bind to port %d...\n", http_port);
405                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
406         }
407         if (msock < 0)
408         {
409                 ShutDownWebcit();
410                 return -msock;
411         }
412
413         syslog(2, "Listening on socket %d\n", msock);
414         signal(SIGPIPE, SIG_IGN);
415
416         pthread_mutex_init(&SessionListMutex, NULL);
417
418         /*
419          * Start up the housekeeping thread
420          */
421         pthread_attr_init(&attr);
422         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
423         pthread_create(&SessThread, &attr,
424                        (void *(*)(void *)) housekeeping_loop, NULL);
425
426
427         /*
428          * If this is an HTTPS server, fire up SSL
429          */
430 #ifdef HAVE_OPENSSL
431         if (is_https) {
432                 init_ssl();
433         }
434 #endif
435         drop_root(UID);
436
437         /* Become a worker thread.  More worker threads will be spawned as they are needed. */
438         worker_entry();
439         ShutDownLibCitadel ();
440         return 0;
441 }
442
443
444
445
446
447
448