Idle cosmetic cleanup while I hunt for a real problem
[citadel.git] / webcit / webserver.c
1 /*
2  * Copyright (c) 1996-2011 by the citadel.org team
3  *
4  * This program is open source software.  You can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 3 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */
18
19 #include "webcit.h"
20 #include "webserver.h"
21
22 #include "modules_init.h"
23 #ifndef HAVE_SNPRINTF
24 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
25 #endif
26
27 extern int msock;                               /* master listening socket */
28 extern char static_icon_dir[PATH_MAX];          /* where should we find our mime icons */
29 int is_https = 0;                               /* Nonzero if I am an HTTPS service */
30 int follow_xff = 0;                             /* Follow X-Forwarded-For: header? */
31 int DisableGzip = 0;
32 char *default_landing_page = NULL;              /* FIXME we need to populate this somehow */
33 extern pthread_mutex_t SessionListMutex;
34 extern pthread_key_t MyConKey;
35
36 extern void *housekeeping_loop(void);
37 extern int webcit_tcp_server(char *ip_addr, int port_number, int queue_len);
38 extern int webcit_uds_server(char *sockpath, int queue_len);
39 extern void graceful_shutdown_watcher(int signum);
40 extern void graceful_shutdown(int signum);
41 extern void start_daemon(char *pid_file);
42 extern void webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome);
43 extern void worker_entry(void);
44 extern void drop_root(uid_t UID);
45
46 char socket_dir[PATH_MAX];      /* where to talk to our citadel server */
47 char *server_cookie = NULL;     /* our Cookie connection to the client */
48 int http_port = PORT_NUM;       /* Port to listen on */
49 char *ctdlhost = DEFAULT_HOST;  /* Host name or IP address of Citadel server */
50 char *ctdlport = DEFAULT_PORT;  /* Port number of Citadel server */
51 int setup_wizard = 0;           /* should we run the setup wizard? */
52 char wizard_filename[PATH_MAX]; /* location of file containing the last webcit version against which we ran setup wizard */
53 int running_as_daemon = 0;      /* should we deamonize on startup? */
54
55 /* #define DBG_PRINNT_HOOKS_AT_START */
56 #ifdef DBG_PRINNT_HOOKS_AT_START
57 extern HashList *HandlerHash;
58 const char foobuf[32];
59 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
60 #endif 
61 extern int dbg_analyze_msg;
62 extern int dbg_backtrace_template_errors;
63 extern int DumpTemplateI18NStrings;
64 extern StrBuf *I18nDump;
65 void InitTemplateCache(void);
66 extern int LoadTemplates;
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 ip_addr[256]="*";
80         int relh=0;
81         int home=0;
82         char relhome[PATH_MAX]="";
83         char webcitdir[PATH_MAX] = DATADIR;
84         char *pidfile = NULL;
85         char *hdir;
86         const char *basedir = NULL;
87         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
88         const char *I18nDumpFile = 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                         /* no longer used, but ignored so old scripts don't break */
158                         break;
159                 case 'T':
160                         LoadTemplates = atoi(optarg);
161                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
162                         dbg_backtrace_template_errors = (LoadTemplates && (1<<2)) != 0;
163                         break;
164                 case 'Z':
165                         DisableGzip = 1;
166                         break;
167                 case 'x':
168                         /* no longer used, but ignored so old scripts don't break */
169                         break;
170                 case 'f':
171                         follow_xff = 1;
172                         break;
173                 case 'c':
174                         server_cookie = malloc(256);
175                         if (server_cookie != NULL) {
176                                 safestrncpy(server_cookie,
177                                        "Set-cookie: wcserver=",
178                                         256);
179                                 if (gethostname
180                                     (&server_cookie[strlen(server_cookie)],
181                                      200) != 0) {
182                                         syslog(2, "gethostname: %s", strerror(errno));
183                                         free(server_cookie);
184                                 }
185                         }
186                         break;
187 #ifdef HAVE_OPENSSL
188                 case 's':
189                         is_https = 1;
190                         break;
191                 case 'S':
192                         is_https = 1;
193                         ssl_cipher_list = strdup(optarg);
194                         break;
195 #endif
196                 case 'G':
197                         DumpTemplateI18NStrings = 1;
198                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
199                         I18nDumpFile = optarg;
200                         break;
201                 default:
202                         fprintf(stderr, "usage: webcit "
203                                 "[-i ip_addr] [-p http_port] "
204                                 "[-c] [-f] "
205                                 "[-T Templatedebuglevel] "
206                                 "[-d] [-Z] [-G i18ndumpfile] "
207 #ifdef HAVE_OPENSSL
208                                 "[-s] [-S cipher_suites]"
209 #endif
210                                 "[remotehost [remoteport]]\n");
211                         return 1;
212                 }
213
214         /* Start the logger */
215         openlog("webcit",
216                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
217                 LOG_DAEMON
218         );
219
220         if (optind < argc) {
221                 ctdlhost = argv[optind];
222                 if (++optind < argc)
223                         ctdlport = argv[optind];
224         }
225
226         /* daemonize, if we were asked to */
227         if (!DumpTemplateI18NStrings && running_as_daemon) {
228                 start_daemon(pidfile);
229         }
230         else {
231                 signal(SIGINT, graceful_shutdown);
232                 signal(SIGHUP, graceful_shutdown);
233         }
234
235         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
236         LoadIconDir(static_icon_dir);
237
238         /* Tell 'em who's in da house */
239         syslog(1, "%s", PACKAGE_STRING);
240         syslog(1, "Copyright (C) 1996-2011 by the citadel.org team");
241         syslog(1, " ");
242         syslog(1, "This program is open source software: you can redistribute it and/or");
243         syslog(1, "modify it under the terms of the GNU General Public License as published");
244         syslog(1, "by the Free Software Foundation, either version 3 of the License, or");
245         syslog(1, "(at your option) any later version.");
246         syslog(1, " ");
247         syslog(1, "This program is distributed in the hope that it will be useful,");
248         syslog(1, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
249         syslog(1, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
250         syslog(1, "GNU General Public License for more details.");
251         syslog(1, " ");
252         syslog(1, "You should have received a copy of the GNU General Public License");
253         syslog(1, "along with this program.  If not, see <http://www.gnu.org/licenses/>.");
254         syslog(1, " ");
255
256
257         /* initialize various subsystems */
258
259         initialise_modules();
260         InitTemplateCache();
261         if (DumpTemplateI18NStrings) {
262                 FILE *fd;
263                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
264                 if (StrLength(I18nDump) < 50) {
265                         syslog(1, "*******************************************************************\n");
266                         syslog(1, "*   No strings found in templates!  Are you sure they're there?   *\n");
267                         syslog(1, "*******************************************************************\n");
268                         return -1;
269                 }
270                 fd = fopen(I18nDumpFile, "w");
271                 if (fd == NULL) {
272                         syslog(1, "***********************************************\n");
273                         syslog(1, "*   unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
274                         syslog(1, "***********************************************\n");
275                         return -1;
276                 }
277                 rv = fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
278                 fclose(fd);
279                 return 0;
280         }
281
282         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
283         icalerror_errors_are_fatal = 0;
284
285         /* Use our own prefix on tzid's generated from system tzdata */
286         icaltimezone_set_tzid_prefix("/citadel.org/");
287
288         /*
289          * Set up a place to put thread-specific data.
290          * We only need a single pointer per thread - it points to the
291          * wcsession struct to which the thread is currently bound.
292          */
293         if (pthread_key_create(&MyConKey, NULL) != 0) {
294                 syslog(1, "Can't create TSD key: %s", strerror(errno));
295         }
296         InitialiseSemaphores();
297
298         /*
299          * Set up a place to put thread-specific SSL data.
300          * We don't stick this in the wcsession struct because SSL starts
301          * up before the session is bound, and it gets torn down between
302          * transactions.
303          */
304 #ifdef HAVE_OPENSSL
305         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
306                 syslog(1, "Can't create TSD key: %s", strerror(errno));
307         }
308 #endif
309
310         /*
311          * Bind the server to our favorite port.
312          * There is no need to check for errors, because webcit_tcp_server()
313          * exits if it doesn't succeed.
314          */
315
316         if (!IsEmptyStr(uds_listen_path)) {
317                 syslog(2, "Attempting to create listener socket at %s...", uds_listen_path);
318                 msock = webcit_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
319         }
320         else {
321                 syslog(2, "Attempting to bind to port %d...", http_port);
322                 msock = webcit_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
323         }
324         if (msock < 0)
325         {
326                 ShutDownWebcit();
327                 return -msock;
328         }
329
330         syslog(2, "Listening on socket %d", msock);
331         signal(SIGPIPE, SIG_IGN);
332
333         pthread_mutex_init(&SessionListMutex, NULL);
334
335         /*
336          * Start up the housekeeping thread
337          */
338         pthread_attr_init(&attr);
339         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
340         pthread_create(&SessThread, &attr, (void *(*)(void *)) housekeeping_loop, NULL);
341
342         /*
343          * If this is an HTTPS server, fire up SSL
344          */
345 #ifdef HAVE_OPENSSL
346         if (is_https) {
347                 init_ssl();
348         }
349 #endif
350         drop_root(UID);
351
352         /* Become a worker thread.  More worker threads will be spawned as they are needed. */
353         worker_entry();
354         ShutDownLibCitadel();
355         return 0;
356 }
357
358
359
360
361
362
363