BIG CHANGES: PAY ATTENTION
[citadel.git] / webcit / sysdep.c
1 /*
2  * WebCit "system dependent" code.
3  *
4  * Copyright (c) 1996-2021 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version 3.
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
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <syslog.h>
27 #include <sys/syslog.h>
28 #include <time.h>
29 #include <limits.h>
30 #include <sys/resource.h>
31 #include <netinet/in.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
34 #include <netdb.h>
35 #include <sys/un.h>
36 #include <string.h>
37 #include <pwd.h>
38 #include <errno.h>
39 #include <stdarg.h>
40 #include <grp.h>
41 #ifdef HAVE_PTHREAD_H
42 #include <pthread.h>
43 #endif
44 #include "webcit.h"
45 #include "sysdep.h"
46
47 #ifdef HAVE_SYS_SELECT_H
48 #include <sys/select.h>
49 #endif
50
51 #include "webserver.h"
52 #include "modules_init.h"
53 #if HAVE_BACKTRACE
54 #include <execinfo.h>
55 #endif
56
57 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
58 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
59 pthread_key_t MyReq;                            /* TSD key for MyReq() */
60 int msock;                      /* master listening socket */
61 int time_to_die = 0;            /* Nonzero if server is shutting down */
62
63 extern void *context_loop(ParsedHttpHdrs *Hdr);
64 extern void *housekeeping_loop(void);
65 extern void do_housekeeping(void);
66
67 char file_etc_mimelist[PATH_MAX]="";
68
69 char etc_dir[PATH_MAX];
70 char static_dir[PATH_MAX];              /* calculated on startup */
71 char static_local_dir[PATH_MAX];                /* calculated on startup */
72 char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
73 char  *static_dirs[]={                          /* needs same sort order as the web mapping */
74         "./static",
75         "./static.local",
76         "./tiny_mce",
77         "./static/webcit_icons"
78 };
79
80 int ExitPipe[2];
81 HashList *GZMimeBlackList = NULL; /* mimetypes which shouldn't be gzip compressed */
82
83 void LoadMimeBlacklist(void)
84 {
85         StrBuf *MimeBlackLine;
86         IOBuffer IOB;
87         eReadState state;
88         
89         memset(&IOB, 0, sizeof(IOBuffer));
90         IOB.fd = open(file_etc_mimelist, O_RDONLY);
91
92         IOB.Buf = NewStrBuf();
93         MimeBlackLine = NewStrBuf();
94         GZMimeBlackList = NewHash(1, NULL);
95
96         do
97         {
98                 state = StrBufChunkSipLine(MimeBlackLine, &IOB);
99
100                 switch (state)
101                 {
102                 case eMustReadMore:
103                         if (StrBuf_read_one_chunk_callback(IOB.fd, 0, &IOB) <= 0)
104                                 state = eReadFail;
105                         break;
106                 case eReadSuccess:
107                         if ((StrLength(MimeBlackLine) > 1) && 
108                             (*ChrPtr(MimeBlackLine) != '#'))
109                         {
110                                 Put(GZMimeBlackList, SKEY(MimeBlackLine),
111                                     (void*) 1, reference_free_handler);
112                         }
113                         FlushStrBuf(MimeBlackLine);
114                         break;
115                 case eReadFail:
116                         break;
117                 case eBufferNotEmpty:
118                         break;
119                 }
120         }
121         while (state != eReadFail);
122
123         close(IOB.fd);
124         
125         FreeStrBuf(&IOB.Buf);
126         FreeStrBuf(&MimeBlackLine);
127 }
128
129 void CheckGZipCompressionAllowed(const char *MimeType, long MLen)
130 {
131         void *v;
132
133         if (WC->Hdr->HR.gzip_ok)
134             WC->Hdr->HR.gzip_ok = GetHash(GZMimeBlackList, MimeType, MLen, &v) == 0;
135 }
136
137 void InitialiseSemaphores(void)
138 {
139         int i;
140
141         /* Set up a bunch of semaphores to be used for critical sections */
142         for (i=0; i<MAX_SEMAPHORES; ++i) {
143                 pthread_mutex_init(&Critters[i], NULL);
144         }
145
146         if (pipe(ExitPipe))
147         {
148                 syslog(LOG_WARNING, "Failed to open exit pipe: %d [%s]\n", 
149                        errno, 
150                        strerror(errno));
151                 
152                 exit(-1);
153         }
154 }
155
156 /*
157  * Obtain a semaphore lock to begin a critical section.
158  */
159 void begin_critical_section(int which_one)
160 {
161         pthread_mutex_lock(&Critters[which_one]);
162 }
163
164 /*
165  * Release a semaphore lock to end a critical section.
166  */
167 void end_critical_section(int which_one)
168 {
169         pthread_mutex_unlock(&Critters[which_one]);
170 }
171
172
173 void ShutDownWebcit(void)
174 {
175
176         DeleteHash(&GZMimeBlackList);
177         free_zone_directory ();
178         icaltimezone_release_zone_tab ();
179         icalmemory_free_ring ();
180         ShutDownLibCitadel ();
181         shutdown_modules ();
182 #ifdef HAVE_OPENSSL
183         if (is_https) {
184                 shutdown_ssl();
185         }
186 #endif
187 }
188
189 /*
190  * Entry point for worker threads
191  */
192 void worker_entry(void)
193 {
194         int ssock;
195         int i = 0;
196         int fail_this_transaction = 0;
197         ParsedHttpHdrs Hdr;
198
199         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
200         Hdr.HR.eReqType = eGET;
201         http_new_modules(&Hdr); 
202
203         do {
204                 /* Each worker thread blocks on accept() while waiting for something to do. */
205                 fail_this_transaction = 0;
206                 ssock = -1; 
207                 errno = EAGAIN;
208                 do {
209                         fd_set wset;
210                         --num_threads_executing;
211                         FD_ZERO(&wset);
212                         FD_SET(msock, &wset);
213                         FD_SET(ExitPipe[1], &wset);
214
215                         select(msock + 1, NULL, &wset, NULL, NULL);
216                         if (time_to_die)
217                                 break;
218
219                         ssock = accept(msock, NULL, 0);
220                         ++num_threads_executing;
221                         if (ssock < 0) fail_this_transaction = 1;
222                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
223
224                 if ((msock == -1)||(time_to_die))
225                 {/* ok, we're going down. */
226                         int shutdown = 0;
227
228                         /* The first thread to get here will have to do the cleanup.
229                          * Make sure it's really just one.
230                          */
231                         begin_critical_section(S_SHUTDOWN);
232                         if (msock == -1)
233                         {
234                                 msock = -2;
235                                 shutdown = 1;
236                         }
237                         end_critical_section(S_SHUTDOWN);
238                         if (shutdown == 1)
239                         {/* we're the one to cleanup the mess. */
240                                 http_destroy_modules(&Hdr);
241                                 syslog(LOG_DEBUG, "I'm master shutdown: tagging sessions to be killed.\n");
242                                 shutdown_sessions();
243                                 syslog(LOG_DEBUG, "master shutdown: waiting for others\n");
244                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
245                                 syslog(LOG_DEBUG, "master shutdown: cleaning up sessions\n");
246                                 do_housekeeping();
247                                 syslog(LOG_DEBUG, "master shutdown: cleaning up libical\n");
248
249                                 ShutDownWebcit();
250
251                                 syslog(LOG_DEBUG, "master shutdown exiting.\n");                                
252                                 exit(0);
253                         }
254                         break;
255                 }
256                 if (ssock < 0 ) continue;
257
258                 check_thread_pool_size();
259
260                 /* Now do something. */
261                 if (msock < 0) {
262                         if (ssock > 0) close (ssock);
263                         syslog(LOG_DEBUG, "in between.");
264                         pthread_exit(NULL);
265                 } else {
266                         /* Got it? do some real work! */
267                         /* Set the SO_REUSEADDR socket option */
268                         i = 1;
269                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
270
271                         /* If we are an HTTPS server, go crypto now. */
272 #ifdef HAVE_OPENSSL
273                         if (is_https) {
274                                 if (starttls(ssock) != 0) {
275                                         fail_this_transaction = 1;
276                                         close(ssock);
277                                 }
278                         }
279                         else 
280 #endif
281                         {
282                                 int fdflags; 
283                                 fdflags = fcntl(ssock, F_GETFL);
284                                 if (fdflags < 0)
285                                         syslog(LOG_WARNING, "unable to get server socket flags! %s \n",
286                                                 strerror(errno));
287                                 fdflags = fdflags | O_NONBLOCK;
288                                 if (fcntl(ssock, F_SETFL, fdflags) < 0)
289                                         syslog(LOG_WARNING, "unable to set server socket nonblocking flags! %s \n",
290                                                 strerror(errno));
291                         }
292
293                         if (fail_this_transaction == 0) {
294                                 Hdr.http_sock = ssock;
295
296                                 /* Perform an HTTP transaction... */
297                                 context_loop(&Hdr);
298
299                                 /* Shut down SSL/TLS if required... */
300 #ifdef HAVE_OPENSSL
301                                 if (is_https) {
302                                         endtls();
303                                 }
304 #endif
305
306                                 /* ...and close the socket. */
307                                 if (Hdr.http_sock > 0) {
308                                         lingering_close(ssock);
309                                 }
310                                 http_detach_modules(&Hdr);
311
312                         }
313
314                 }
315
316         } while (!time_to_die);
317
318         http_destroy_modules(&Hdr);
319         syslog(LOG_DEBUG, "Thread exiting.\n");
320         pthread_exit(NULL);
321 }
322
323
324 /*
325  * Shut us down the regular way.
326  * signum is the signal we want to forward
327  */
328 pid_t current_child;
329 void graceful_shutdown_watcher(int signum) {
330         syslog(LOG_INFO, "Watcher thread exiting.\n");
331         write(ExitPipe[0], HKEY("                              "));
332         kill(current_child, signum);
333         if (signum != SIGHUP)
334                 exit(0);
335 }
336
337
338 /*
339  * Shut us down the regular way.
340  * signum is the signal we want to forward
341  */
342 pid_t current_child;
343 void graceful_shutdown(int signum) {
344         FILE *FD;
345         int fd;
346
347         syslog(LOG_INFO, "WebCit is being shut down on signal %d.\n", signum);
348         fd = msock;
349         msock = -1;
350         time_to_die = 1;
351         FD=fdopen(fd, "a+");
352         fflush (FD);
353         fclose (FD);
354         close(fd);
355         write(ExitPipe[0], HKEY("                              "));
356 }
357
358
359 /*
360  * Start running as a daemon.
361  */
362 void start_daemon(char *pid_file) 
363 {
364         int status = 0;
365         pid_t child = 0;
366         FILE *fp;
367         int do_restart = 0;
368
369         current_child = 0;
370
371         /* Close stdin/stdout/stderr and replace them with /dev/null.
372          * We don't just call close() because we don't want these fd's
373          * to be reused for other files.
374          */
375         chdir("/");
376
377         signal(SIGHUP, SIG_IGN);
378         signal(SIGINT, SIG_IGN);
379         signal(SIGQUIT, SIG_IGN);
380
381         child = fork();
382         if (child != 0) {
383                 exit(0);
384         }
385
386         setsid();
387         umask(0);
388         freopen("/dev/null", "r", stdin);
389         freopen("/dev/null", "w", stdout);
390         freopen("/dev/null", "w", stderr);
391         signal(SIGTERM, graceful_shutdown_watcher);
392         signal(SIGHUP, graceful_shutdown_watcher);
393
394         do {
395                 current_child = fork();
396
397         
398                 if (current_child < 0) {
399                         perror("fork");
400                         ShutDownLibCitadel ();
401                         exit(errno);
402                 }
403         
404                 else if (current_child == 0) {  /* child process */
405                         signal(SIGHUP, graceful_shutdown);
406
407                         return; /* continue starting webcit. */
408                 }
409                 else { /* watcher process */
410                         if (pid_file) {
411                                 fp = fopen(pid_file, "w");
412                                 if (fp != NULL) {
413                                         fprintf(fp, "%d\n", getpid());
414                                         fclose(fp);
415                                 }
416                         }
417                         waitpid(current_child, &status, 0);
418                 }
419
420                 do_restart = 0;
421
422                 /* Did the main process exit with an actual exit code? */
423                 if (WIFEXITED(status)) {
424
425                         /* Exit code 0 means the watcher should exit */
426                         if (WEXITSTATUS(status) == 0) {
427                                 do_restart = 0;
428                         }
429
430                         /* Exit code 101-109 means the watcher should exit */
431                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
432                                 do_restart = 0;
433                         }
434
435                         /* Any other exit code means we should restart. */
436                         else {
437                                 do_restart = 1;
438                         }
439                 }
440
441                 /* Any other type of termination (signals, etc.) should also restart. */
442                 else {
443                         do_restart = 1;
444                 }
445
446         } while (do_restart);
447
448         if (pid_file) {
449                 unlink(pid_file);
450         }
451         ShutDownLibCitadel ();
452         exit(WEXITSTATUS(status));
453 }
454
455
456 /*
457  * Spawn an additional worker thread into the pool.
458  */
459 void spawn_another_worker_thread()
460 {
461         pthread_t SessThread;   /* Thread descriptor */
462         pthread_attr_t attr;    /* Thread attributes */
463         int ret;
464
465         ++num_threads_existing;
466         ++num_threads_executing;
467
468         /* set attributes for the new thread */
469         pthread_attr_init(&attr);
470         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
471
472         /*
473          * Our per-thread stacks need to be bigger than the default size,
474          * otherwise the MIME parser crashes on FreeBSD.
475          */
476         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
477                 syslog(LOG_WARNING, "pthread_attr_setstacksize: %s\n", strerror(ret));
478                 pthread_attr_destroy(&attr);
479         }
480
481         /* now create the thread */
482         if (pthread_create(&SessThread, &attr, (void *(*)(void *)) worker_entry, NULL) != 0) {
483                 syslog(LOG_WARNING, "Can't create thread: %s\n", strerror(errno));
484         }
485
486         /* free up the attributes */
487         pthread_attr_destroy(&attr);
488 }
489
490
491 void
492 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
493 {
494         char dirbuffer[PATH_MAX]="";
495         /* calculate all our path on a central place */
496     /* where to keep our config */
497         
498 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
499         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
500                          (home&!relh)?webcitdir:basedir, \
501              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
502              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
503                          relhome, \
504              (relhome[0]!='\0')?"/":"",\
505                          dirbuffer,\
506                          (dirbuffer[0]!='\0')?"/":"");
507         basedir=RUNDIR;
508         COMPUTE_DIRECTORY(socket_dir);
509         basedir=WWWDIR "/static";
510         COMPUTE_DIRECTORY(static_dir);
511         basedir=WWWDIR "/static/icons";
512         COMPUTE_DIRECTORY(static_icon_dir);
513         basedir=WWWDIR "/static.local";
514         COMPUTE_DIRECTORY(static_local_dir);
515         StripSlashes(static_dir, 1);
516         StripSlashes(static_icon_dir, 1);
517         StripSlashes(static_local_dir, 1);
518
519         basedir=ETCDIR;
520         COMPUTE_DIRECTORY(etc_dir);
521         StripSlashes(etc_dir, 1);
522         snprintf(file_etc_mimelist,
523                  sizeof file_etc_mimelist, 
524                  "%s/nogz-mimetypes.txt",
525                  etc_dir);
526
527         /* we should go somewhere we can leave our coredump, if enabled... */
528         syslog(LOG_INFO, "Changing directory to %s\n", socket_dir);
529         if (chdir(webcitdir) != 0) {
530                 perror("chdir");
531         }
532 }
533
534 void drop_root(uid_t UID)
535 {
536         struct passwd pw, *pwp = NULL;
537 #ifdef HAVE_GETPWUID_R
538         char pwbuf[SIZ];
539 #endif
540
541         /*
542          * Now that we've bound the sockets, change to the Citadel user id and its
543          * corresponding group ids
544          */
545         if (UID != -1) {
546                 
547 #ifdef HAVE_GETPWUID_R
548 #ifdef SOLARIS_GETPWUID
549                 pwp = getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf));
550 #else /* SOLARIS_GETPWUID */
551                 getpwuid_r(UID, &pw, pwbuf, sizeof(pwbuf), &pwp);
552 #endif /* SOLARIS_GETPWUID */
553 #else /* HAVE_GETPWUID_R */
554                 pwp = NULL;
555 #endif /* HAVE_GETPWUID_R */
556
557                 if (pwp == NULL)
558                         syslog(LOG_CRIT, "WARNING: getpwuid(%d): %s\n"
559                                 "Group IDs will be incorrect.\n", UID,
560                                 strerror(errno));
561                 else {
562                         initgroups(pw.pw_name, pw.pw_gid);
563                         if (setgid(pw.pw_gid))
564                                 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
565                                         strerror(errno));
566                 }
567                 syslog(LOG_INFO, "Changing uid to %ld\n", (long)UID);
568                 if (setuid(UID) != 0) {
569                         syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
570                 }
571 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
572                 prctl(PR_SET_DUMPABLE, 1);
573 #endif
574         }
575 }
576
577
578 /*
579  * print the actual stack frame.
580  */
581 void wc_backtrace(long LogLevel)
582 {
583 #ifdef HAVE_BACKTRACE
584         void *stack_frames[50];
585         size_t size, i;
586         char **strings;
587
588
589         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
590         strings = backtrace_symbols(stack_frames, size);
591         for (i = 0; i < size; i++) {
592                 if (strings != NULL)
593                         syslog(LogLevel, "%s\n", strings[i]);
594                 else
595                         syslog(LogLevel, "%p\n", stack_frames[i]);
596         }
597         free(strings);
598 #endif
599 }