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