Changed the naming convention of the setup wizard filename
[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 char *server_cookie = NULL;     /* our Cookie connection to the client */
44 int http_port = PORT_NUM;       /* Port to listen on */
45 char *ctdlhost = DEFAULT_HOST;  /* Host name or IP address of Citadel server */
46 char *ctdlport = DEFAULT_PORT;  /* Port number of Citadel server */
47 int setup_wizard = 0;           /* should we run the setup wizard? */
48 char wizard_filename[PATH_MAX]; /* location of file containing the last webcit version against which we ran setup wizard */
49 int running_as_daemon = 0;      /* should we deamonize on startup? */
50
51
52 /* #define DBG_PRINNT_HOOKS_AT_START */
53 #ifdef DBG_PRINNT_HOOKS_AT_START
54 extern HashList *HandlerHash;
55 const char foobuf[32];
56 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
57 #endif 
58 extern int dbg_analyze_msg;
59 extern int dbg_backtrace_template_errors;
60 extern int DumpTemplateI18NStrings;
61 extern StrBuf *I18nDump;
62 void InitTemplateCache(void);
63 extern int LoadTemplates;
64
65
66
67
68
69 /*
70  * Handle redirects to legacy web servers
71  */
72 void handle_redir(void) {
73         if (num_redir > 0) {
74                 int i;
75                 const char *req = ChrPtr(WC->Hdr->this_page);
76                 if (!req) {
77                         do_404();
78                         return;
79                 }
80                 if (req[0] == '/') ++req;
81                 syslog(9, "handle_redir() called; redirect this: %s", req);
82                 for (i=0; i<num_redir; ++i) {
83                         if (!strncmp(redir[i].urlpart, req, strlen(redir[i].urlpart))) {
84                                 char go_here[1024];
85                                 snprintf(go_here, sizeof go_here, redir[i].redirect_to, req);
86                                 syslog(9, "redirecting to: %s", go_here);
87                                 http_redirect(go_here);
88                                 return;
89                         }
90                 }
91         }
92         do_404();
93 }
94
95
96
97 /*
98  * load redirect strings (for supporting transition of legacy web servers to citadel on the same host)
99  */
100 void load_redirs(char *filename) {
101         char buf[1024];
102         int num_redir_alloc = num_redir;
103         FILE *fp = fopen(filename, "r");
104         if (!fp) {
105                 syslog(1, "Cannot open %s: %s", filename, strerror(errno));
106                 return;
107         }
108
109         while (fgets(buf, sizeof buf, fp) != NULL) {
110                 char *ch;
111
112                 buf[strlen(buf)-1] = 0;
113
114                 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                         if (!strcasecmp(redir[num_redir].urlpart, "home")) {
133                                 default_landing_page = redir[num_redir].redirect_to ;
134                         }
135                         ++num_redir;
136                 }
137
138         }
139         fclose(fp);
140 }
141
142
143
144 /*
145  * Here's where it all begins.
146  */
147 int main(int argc, char **argv)
148 {
149         uid_t UID = -1;
150         size_t basesize = 2;            /* how big should strbufs be on creation? */
151         pthread_t SessThread;           /* Thread descriptor */
152         pthread_attr_t attr;            /* Thread attributes */
153         int a;                          /* General-purpose variable */
154         char tracefile[PATH_MAX];
155         char ip_addr[256]="*";
156         int relh=0;
157         int home=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=1;
211                         break;
212                 case 'd':
213                         running_as_daemon = 1;
214                         break;
215                 case 'D':
216                         pidfile = strdup(optarg);
217                         running_as_daemon = 1;
218                         break;
219                 case 'B': /* Basesize */
220                         basesize = atoi(optarg);
221                         if (basesize > 2)
222                                 StartLibCitadel(basesize);
223                         break;
224                 case 'i':
225                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
226                         break;
227                 case 'p':
228                         http_port = atoi(optarg);
229                         if (http_port == 0) {
230                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
231                         }
232                         break;
233                 case 't':
234                         safestrncpy(tracefile, optarg, sizeof tracefile);
235                         rvfp = freopen(tracefile, "w", stdout);
236                         rvfp = freopen(tracefile, "w", stderr);
237                         rvfp = freopen(tracefile, "r", stdin);
238                         break;
239                 case 'T':
240                         LoadTemplates = atoi(optarg);
241                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
242                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
243                         break;
244                 case 'Z':
245                         DisableGzip = 1;
246                         break;
247                 case 'x':
248                         verbosity = atoi(optarg);
249                         break;
250                 case 'f':
251                         follow_xff = 1;
252                         break;
253                 case 'c':
254                         server_cookie = malloc(256);
255                         if (server_cookie != NULL) {
256                                 safestrncpy(server_cookie,
257                                        "Set-cookie: wcserver=",
258                                         256);
259                                 if (gethostname
260                                     (&server_cookie[strlen(server_cookie)],
261                                      200) != 0) {
262                                         syslog(2, "gethostname: %s", strerror(errno));
263                                         free(server_cookie);
264                                 }
265                         }
266                         break;
267 #ifdef HAVE_OPENSSL
268                 case 's':
269                         is_https = 1;
270                         break;
271                 case 'S':
272                         is_https = 1;
273                         ssl_cipher_list = strdup(optarg);
274                         break;
275 #endif
276                 case 'G':
277                         DumpTemplateI18NStrings = 1;
278                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
279                         I18nDumpFile = optarg;
280                         break;
281                 default:
282                         fprintf(stderr, "usage: webcit "
283                                 "[-i ip_addr] [-p http_port] "
284                                 "[-t tracefile] [-c] [-f] "
285                                 "[-T Templatedebuglevel] "
286                                 "[-d] [-Z] [-G i18ndumpfile] "
287 #ifdef HAVE_OPENSSL
288                                 "[-s] [-S cipher_suites]"
289 #endif
290                                 "[remotehost [remoteport]]\n");
291                         return 1;
292                 }
293
294         /* Start the logger */
295         openlog("webcit",
296                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
297                 LOG_DAEMON
298         );
299
300         if (optind < argc) {
301                 ctdlhost = argv[optind];
302                 if (++optind < argc)
303                         ctdlport = argv[optind];
304         }
305
306         /* daemonize, if we were asked to */
307         if (!DumpTemplateI18NStrings && running_as_daemon) {
308                 start_daemon(pidfile);
309         }
310         else {
311                 signal(SIGINT, graceful_shutdown);
312                 signal(SIGHUP, graceful_shutdown);
313         }
314
315         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
316         LoadIconDir(static_icon_dir);
317
318         /* Tell 'em who's in da house */
319         syslog(1, "%s", PACKAGE_STRING);
320         syslog(1, "Copyright (C) 1996-2011 by the citadel.org team");
321         syslog(1, " ");
322         syslog(1, "This program is open source software: you can redistribute it and/or");
323         syslog(1, "modify it under the terms of the GNU General Public License as published");
324         syslog(1, "by the Free Software Foundation, either version 3 of the License, or");
325         syslog(1, "(at your option) any later version.");
326         syslog(1, " ");
327         syslog(1, "This program is distributed in the hope that it will be useful,");
328         syslog(1, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
329         syslog(1, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
330         syslog(1, "GNU General Public License for more details.");
331         syslog(1, " ");
332         syslog(1, "You should have received a copy of the GNU General Public License");
333         syslog(1, "along with this program.  If not, see <http://www.gnu.org/licenses/>.");
334         syslog(1, " ");
335
336
337         /* initialize various subsystems */
338
339         initialise_modules();
340         InitTemplateCache();
341         if (DumpTemplateI18NStrings) {
342                 FILE *fd;
343                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
344                 if (StrLength(I18nDump) < 50) {
345                         syslog(1, "********************************************************************************\n");
346                         syslog(1, "*        No strings found in templates!  Are you sure they're there?           *\n");
347                         syslog(1, "********************************************************************************\n");
348                         return -1;
349                 }
350                 fd = fopen(I18nDumpFile, "w");
351                 if (fd == NULL) {
352                         syslog(1, "********************************************************************************\n");
353                         syslog(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
354                         syslog(1, "********************************************************************************\n");
355                         return -1;
356                 }
357                 rv = fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
358                 fclose(fd);
359                 return 0;
360         }
361
362
363         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
364         icalerror_errors_are_fatal = 0;
365
366         /* Use our own prefix on tzid's generated from system tzdata */
367         icaltimezone_set_tzid_prefix("/citadel.org/");
368
369         /*
370          * Set up a place to put thread-specific data.
371          * We only need a single pointer per thread - it points to the
372          * wcsession struct to which the thread is currently bound.
373          */
374         if (pthread_key_create(&MyConKey, NULL) != 0) {
375                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
376         }
377         InitialiseSemaphores ();
378
379         /*
380          * Set up a place to put thread-specific SSL data.
381          * We don't stick this in the wcsession struct because SSL starts
382          * up before the session is bound, and it gets torn down between
383          * transactions.
384          */
385 #ifdef HAVE_OPENSSL
386         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
387                 syslog(1, "Can't create TSD key: %s\n", strerror(errno));
388         }
389 #endif
390
391         /*
392          * Bind the server to our favorite port.
393          * There is no need to check for errors, because webcit_tcp_server()
394          * exits if it doesn't succeed.
395          */
396
397         if (!IsEmptyStr(uds_listen_path)) {
398                 syslog(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
399                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
400         }
401         else {
402                 syslog(2, "Attempting to bind to port %d...\n", http_port);
403                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
404         }
405         if (msock < 0)
406         {
407                 ShutDownWebcit();
408                 return -msock;
409         }
410
411         syslog(2, "Listening on socket %d\n", msock);
412         signal(SIGPIPE, SIG_IGN);
413
414         pthread_mutex_init(&SessionListMutex, NULL);
415
416         /*
417          * Start up the housekeeping thread
418          */
419         pthread_attr_init(&attr);
420         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
421         pthread_create(&SessThread, &attr,
422                        (void *(*)(void *)) housekeeping_loop, NULL);
423
424
425         /*
426          * If this is an HTTPS server, fire up SSL
427          */
428 #ifdef HAVE_OPENSSL
429         if (is_https) {
430                 init_ssl();
431         }
432 #endif
433         drop_root(UID);
434
435         /* Become a worker thread.  More worker threads will be spawned as they are needed. */
436         worker_entry();
437         ShutDownLibCitadel();
438         return 0;
439 }
440
441
442
443
444
445
446