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