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