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