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