source: trunk/src/sh_unix.c@ 420

Last change on this file since 420 was 415, checked in by katerina, 12 years ago

Fixes for tickets #314, #315, #316, #317, #318, #319, #320, and #321.

File size: 128.6 KB
Line 
1/* SAMHAIN file system integrity testing */
2/* Copyright (C) 1999 Rainer Wichmann */
3/* */
4/* This program is free software; you can redistribute it */
5/* and/or modify */
6/* it under the terms of the GNU General Public License as */
7/* published by */
8/* the Free Software Foundation; either version 2 of the License, or */
9/* (at your option) any later version. */
10/* */
11/* This program is distributed in the hope that it will be useful, */
12/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
13/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
14/* GNU General Public License for more details. */
15/* */
16/* You should have received a copy of the GNU General Public License */
17/* along with this program; if not, write to the Free Software */
18/* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
19
20#include "config_xor.h"
21
22
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <ctype.h>
27#ifdef HAVE_LINUX_FS_H
28#include <linux/fs.h>
29#endif
30
31#ifdef HAVE_MEMORY_H
32#include <memory.h>
33#endif
34
35#ifdef HAVE_UNISTD_H
36#include <errno.h>
37#include <signal.h>
38#include <pwd.h>
39#include <grp.h>
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <sys/resource.h>
43#include <fcntl.h>
44#include <unistd.h>
45/* need to undef these, since the #define's may be picked up from
46 * linux/wait.h, and will clash with a typedef in sys/wait.h
47 */
48#undef P_ALL
49#undef P_PID
50#undef P_PGID
51#include <sys/wait.h>
52
53/*********************
54#ifdef HAVE_SYS_VFS_H
55#include <sys/vfs.h>
56#endif
57**********************/
58#endif
59
60#if TIME_WITH_SYS_TIME
61#include <sys/time.h>
62#include <time.h>
63#else
64#if HAVE_SYS_TIME_H
65#include <sys/time.h>
66#else
67#include <time.h>
68#endif
69#endif
70
71#ifdef HAVE_SYS_SELECT_H
72#include <sys/select.h>
73#endif
74
75#ifndef FD_SET
76#define NFDBITS 32
77#define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
78#define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
79#define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
80#endif /* !FD_SET */
81#ifndef FD_SETSIZE
82#define FD_SETSIZE 32
83#endif
84#ifndef FD_ZERO
85#define FD_ZERO(p) memset((char *)(p), '\0', sizeof(*(p)))
86#endif
87
88
89#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
90#include <sys/mman.h>
91#endif
92
93#include "samhain.h"
94#include "sh_error.h"
95#include "sh_unix.h"
96#include "sh_utils.h"
97#include "sh_mem.h"
98#include "sh_hash.h"
99#include "sh_tools.h"
100#include "sh_restrict.h"
101#include "sh_ipvx.h"
102#include "sh_tiger.h"
103#include "sh_prelink.h"
104#include "sh_pthread.h"
105
106/* moved here from far below
107 */
108#include <netdb.h>
109
110#define SH_NEED_PWD_GRP
111#define SH_NEED_GETHOSTBYXXX
112#include "sh_static.h"
113
114#ifndef HAVE_LSTAT
115#define lstat stat
116#endif
117
118#if defined(S_IFLNK) && !defined(S_ISLNK)
119#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
120#else
121#if !defined(S_ISLNK)
122#define S_ISLNK(mode) (0)
123#endif
124#endif
125
126#if defined(S_IFSOCK) && !defined(S_ISSOCK)
127#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
128#else
129#if !defined(S_ISSOCK)
130#define S_ISSOCK(mode) (0)
131#endif
132#endif
133
134#if defined(S_IFDOOR) && !defined(S_ISDOOR)
135#define S_ISDOOR(mode) (((mode) & S_IFMT) == S_IFDOOR)
136#else
137#if !defined(S_ISDOOR)
138#define S_ISDOOR(mode) (0)
139#endif
140#endif
141
142#if defined(S_IFPORT) && !defined(S_ISPORT)
143#define S_ISPORT(mode) (((mode) & S_IFMT) == S_IFPORT)
144#else
145#if !defined(S_ISPORT)
146#define S_ISPORT(mode) (0)
147#endif
148#endif
149
150#define SH_KEY_NULL _("000000000000000000000000000000000000000000000000")
151
152#undef FIL__
153#define FIL__ _("sh_unix.c")
154
155unsigned long mask_PRELINK = MASK_PRELINK_;
156unsigned long mask_USER0 = MASK_USER_;
157unsigned long mask_USER1 = MASK_USER_;
158unsigned long mask_USER2 = MASK_USER_;
159unsigned long mask_USER3 = MASK_USER_;
160unsigned long mask_USER4 = MASK_USER_;
161unsigned long mask_ALLIGNORE = MASK_ALLIGNORE_;
162unsigned long mask_ATTRIBUTES = MASK_ATTRIBUTES_;
163unsigned long mask_LOGFILES = MASK_LOGFILES_;
164unsigned long mask_LOGGROW = MASK_LOGGROW_;
165unsigned long mask_READONLY = MASK_READONLY_;
166unsigned long mask_NOIGNORE = MASK_NOIGNORE_;
167
168
169extern char **environ;
170
171int sh_unix_maskreset()
172{
173 mask_PRELINK = MASK_PRELINK_;
174 mask_USER0 = MASK_USER_;
175 mask_USER1 = MASK_USER_;
176 mask_USER2 = MASK_USER_;
177 mask_USER3 = MASK_USER_;
178 mask_USER4 = MASK_USER_;
179 mask_ALLIGNORE = MASK_ALLIGNORE_;
180 mask_ATTRIBUTES = MASK_ATTRIBUTES_;
181 mask_LOGFILES = MASK_LOGFILES_;
182 mask_LOGGROW = MASK_LOGGROW_;
183 mask_READONLY = MASK_READONLY_;
184 mask_NOIGNORE = MASK_NOIGNORE_;
185 return 0;
186}
187
188
189#ifdef SYS_SIGLIST_DECLARED
190/* extern const char * const sys_siglist[]; */
191#else
192char * sh_unix_siglist (int signum)
193{
194 switch (signum)
195 {
196#ifdef SIGHUP
197 case SIGHUP:
198 return _("Hangup");
199#endif
200#ifdef SIGINT
201 case SIGINT:
202 return _("Interrupt");
203#endif
204#ifdef SIGQUIT
205 case SIGQUIT:
206 return _("Quit");
207#endif
208#ifdef SIGILL
209 case SIGILL:
210 return _("Illegal instruction");
211#endif
212#ifdef SIGTRAP
213 case SIGTRAP:
214 return _("Trace/breakpoint trap");
215#endif
216#ifdef SIGABRT
217 case SIGABRT:
218 return _("IOT trap/Abort");
219#endif
220#ifdef SIGBUS
221 case SIGBUS:
222 return _("Bus error");
223#endif
224#ifdef SIGFPE
225 case SIGFPE:
226 return _("Floating point exception");
227#endif
228#ifdef SIGUSR1
229 case SIGUSR1:
230 return _("User defined signal 1");
231#endif
232#ifdef SIGSEGV
233 case SIGSEGV:
234 return _("Segmentation fault");
235#endif
236#ifdef SIGUSR2
237 case SIGUSR2:
238 return _("User defined signal 2");
239#endif
240#ifdef SIGPIPE
241 case SIGPIPE:
242 return _("Broken pipe");
243#endif
244#ifdef SIGALRM
245 case SIGALRM:
246 return _("Alarm clock");
247#endif
248#ifdef SIGTERM
249 case SIGTERM:
250 return _("Terminated");
251#endif
252#ifdef SIGSTKFLT
253 case SIGSTKFLT:
254 return _("Stack fault");
255#endif
256#ifdef SIGCHLD
257 case SIGCHLD:
258 return _("Child exited");
259#endif
260#ifdef SIGCONT
261 case SIGCONT:
262 return _("Continued");
263#endif
264#ifdef SIGSTOP
265 case SIGSTOP:
266 return _("Stopped");
267#endif
268#ifdef SIGTSTP
269 case SIGTSTP:
270 return _("Stop typed at tty");
271#endif
272#ifdef SIGTTIN
273 case SIGTTIN:
274 return _("Stopped (tty input)");
275#endif
276#ifdef SIGTTOU
277 case SIGTTOU:
278 return _("Stopped (tty output)");
279#endif
280#ifdef SIGURG
281 case SIGURG:
282 return _("Urgent condition");
283#endif
284#ifdef SIGXCPU
285 case SIGXCPU:
286 return _("CPU time limit exceeded");
287#endif
288#ifdef SIGXFSZ
289 case SIGXFSZ:
290 return _("File size limit exceeded");
291#endif
292#ifdef SIGVTALRM
293 case SIGVTALRM:
294 return _("Virtual time alarm");
295#endif
296#ifdef SIGPROF
297 case SIGPROF:
298 return _("Profile signal");
299#endif
300#ifdef SIGWINCH
301 case SIGWINCH:
302 return _("Window size changed");
303#endif
304#ifdef SIGIO
305 case SIGIO:
306 return _("Possible I/O");
307#endif
308#ifdef SIGPWR
309 case SIGPWR:
310 return _("Power failure");
311#endif
312#ifdef SIGUNUSED
313 case SIGUNUSED:
314 return _("Unused signal");
315#endif
316 }
317 return _("Unknown");
318}
319#endif
320
321
322/* Log from within a signal handler without using any
323 * functions that are not async signal safe.
324 *
325 * This is the safe_itoa helper function.
326 */
327char * safe_itoa(int i, char * str, int size)
328{
329 unsigned int u;
330 int iisneg = 0;
331 char *p = &str[size-1];
332
333 *p = '\0';
334 if (i < 0) {
335 iisneg = 1;
336 u = ((unsigned int)(-(1+i))) + 1;
337 } else {
338 u = i;
339 }
340 do {
341 --p;
342 *p = '0' + (u % 10);
343 u /= 10;
344 } while (u && (p != str));
345 if ((iisneg == 1) && (p != str)) {
346 --p;
347 *p = '-';
348 }
349 return p;
350}
351
352/* Log from within a signal handler without using any
353 * functions that are not async signal safe.
354 *
355 * This is the safe_logger function.
356 * Arguments: signal (signal number), method (0=logger, 1=stderr), thepid (pid)
357 */
358extern int OnlyStderr;
359
360int safe_logger (int thesignal, int method, char * details)
361{
362 unsigned int i = 0;
363 int status = -1;
364 struct stat buf;
365 pid_t newpid;
366 char str[128];
367 char * p;
368
369 char l0[64], l1[64], l2[64], l3[64];
370 char a0[32], a1[32], a2[32];
371 char e0[128];
372 char msg[128];
373
374 char * locations[] = { NULL, NULL, NULL, NULL, NULL };
375 char * envp[] = { NULL, NULL };
376 char * argp[] = { NULL, NULL, NULL, NULL, NULL };
377
378 pid_t thepid = getpid();
379
380 if ((sh.flag.isdaemon == S_FALSE) || (OnlyStderr == S_TRUE))
381 method = 1;
382
383 /* seems that solaris cc needs this way of initializing ...
384 */
385 locations[0] = l0;
386 locations[1] = l1;
387 locations[2] = l2;
388 locations[3] = l3;
389
390 envp[0] = e0;
391
392 argp[0] = a0;
393 argp[1] = a1;
394 argp[2] = a2;
395
396 sl_strlcpy(msg, _("samhain["), 128);
397 p = safe_itoa((int) thepid, str, 128);
398 if (p && *p)
399 sl_strlcat(msg, p, 128);
400 if (thesignal == 0)
401 {
402 if (details == NULL) {
403 sl_strlcat(msg, _("]: out of memory"), 128);
404 } else {
405 sl_strlcat(msg, _("]: "), 128);
406 sl_strlcat(msg, details, 128);
407 }
408 }
409 else
410 {
411 sl_strlcat(msg, _("]: exit on signal "), 128);
412 p = safe_itoa(thesignal, str, 128);
413 if (p && *p)
414 sl_strlcat(msg, p, 128);
415 }
416
417 if (method == 1) {
418#ifndef STDERR_FILENO
419#define STDERR_FILENO 2
420#endif
421 int retval = 0;
422 do {
423 retval = write(STDERR_FILENO, msg, strlen(msg));
424 } while (retval < 0 && errno == EINTR);
425 do {
426 retval = write(STDERR_FILENO, "\n", 1);
427 } while (retval < 0 && errno == EINTR);
428 return 0;
429 }
430
431 sl_strlcpy (l0, _("/usr/bin/logger"), 64);
432 sl_strlcpy (l1, _("/usr/sbin/logger"), 64);
433 sl_strlcpy (l2, _("/usr/ucb/logger"), 64);
434 sl_strlcpy (l3, _("/bin/logger"), 64);
435
436 sl_strlcpy (a0, _("logger"), 32);
437 sl_strlcpy (a1, _("-p"), 32);
438 sl_strlcpy (a2, _("daemon.alert"), 32);
439
440 sl_strlcpy (e0,
441 _("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/ucb:/usr/local/bin"),
442 128);
443
444 while (locations[i] != NULL) {
445 status = stat(locations[i], &buf);
446 if (status == 0)
447 break;
448 ++i;
449 }
450
451 if (locations[i] != NULL) {
452 argp[3] = msg;
453 newpid = fork();
454 if (newpid == 0) {
455 execve(locations[i], argp, envp);
456 _exit(1);
457 }
458 else if (newpid > 0) {
459 waitpid(newpid, &status, WUNTRACED);
460 }
461 }
462 return 0;
463}
464
465void safe_fatal (const char * details,
466 const char * file, int line)
467{
468 char msg[128];
469 char str[128];
470 char * p;
471 int thesignal = 0;
472 int method = 0;
473
474 p = safe_itoa((int) line, str, 128);
475 sl_strlcpy(msg, _("FATAL: "), 128);
476 sl_strlcat(msg, file, 128);
477 sl_strlcat(msg, ": ", 128);
478 if (p && (*p)) {
479 sl_strlcat(msg, p , 128);
480 sl_strlcat(msg, ": ", 128);
481 }
482 sl_strlcat(msg, details, 128);
483 (void) safe_logger (thesignal, method, msg);
484 raise(SIGKILL);
485}
486
487extern char sh_sig_msg[64];
488
489volatile int immediate_exit_normal = 0;
490
491#if defined(SA_SIGACTION_WORKS)
492static
493void sh_unix_sigexit (int mysignal, siginfo_t * signal_info, void * signal_add)
494#else
495static
496void sh_unix_sigexit (int mysignal)
497#endif
498{
499
500#if defined(SA_SIGACTION_WORKS)
501 if (signal_info != NULL && signal_info->si_code == SI_USER &&
502 mysignal != SIGTERM && mysignal != SIGINT)
503 {
504 return;
505 }
506
507 /* avoid compiler warning (unused var)
508 */
509 (void) signal_add;
510#endif
511
512 /*
513 * Block re-entry
514 */
515 if (immediate_exit_normal > 0)
516 {
517 ++immediate_exit_normal;
518 if ((skey != NULL) && (immediate_exit_normal == 2))
519 memset (skey, '\0', sizeof(sh_key_t));
520 if (immediate_exit_normal == 2)
521 {
522 int val_return;
523
524 do {
525 val_return = chdir ("/");
526 } while (val_return < 0 && errno == EINTR);
527
528 safe_logger (mysignal, 0, NULL);
529 }
530 raise(SIGKILL);
531 }
532 else
533 {
534 immediate_exit_normal = 1;
535 }
536
537#ifdef SYS_SIGLIST_DECLARED
538 strncpy (sh_sig_msg, sys_siglist[mysignal], 40);
539#else
540 strncpy (sh_sig_msg, sh_unix_siglist(mysignal), 40);
541#endif
542 sh_sig_msg[63] = '\0';
543
544 ++sig_raised;
545 ++sig_urgent;
546 sig_termfast = 1;
547 return;
548}
549
550volatile int immediate_exit_fast = 0;
551
552#if defined(SA_SIGACTION_WORKS)
553static
554void sh_unix_sigexit_fast (int mysignal, siginfo_t * signal_info,
555 void * signal_add)
556#else
557static
558void sh_unix_sigexit_fast (int mysignal)
559#endif
560{
561#if defined(SL_DEBUG) && (defined(USE_SYSTEM_MALLOC) || !defined(USE_MALLOC_LOCK))
562 int retval;
563#endif
564
565#if defined(SA_SIGACTION_WORKS)
566 if (signal_info != NULL && signal_info->si_code == SI_USER)
567 {
568 return;
569 }
570#endif
571
572 /* avoid compiler warning (unused var)
573 */
574#if defined(SA_SIGACTION_WORKS)
575 (void) signal_add;
576#endif
577
578 /* Check whether the heap is ok; otherwise _exit
579 */
580#if !defined(SL_DEBUG) || (!defined(USE_SYSTEM_MALLOC) && defined(USE_MALLOC_LOCK))
581 ++immediate_exit_fast;
582 if (skey != NULL && immediate_exit_fast < 2)
583 memset (skey, '\0', sizeof(sh_key_t));
584 if (immediate_exit_fast < 2)
585 safe_logger (mysignal, 0, NULL);
586 raise(SIGKILL);
587#else
588
589 /* debug code
590 */
591 if (immediate_exit_fast == 1)
592 {
593 ++immediate_exit_fast;
594 if (skey != NULL)
595 memset (skey, '\0', sizeof(sh_key_t));
596#ifdef WITH_MESSAGE_QUEUE
597 close_ipc ();
598#endif
599 safe_logger (mysignal, 0, NULL);
600 do {
601 retval = chdir ("/");
602 } while (retval < 0 && errno == EINTR);
603 raise(SIGFPE);
604 }
605 else if (immediate_exit_fast == 2)
606 {
607 do {
608 retval = chdir ("/");
609 } while (retval < 0 && errno == EINTR);
610 raise(SIGFPE);
611 }
612 else if (immediate_exit_fast != 0)
613 {
614 raise(SIGKILL);
615 }
616
617 ++immediate_exit_fast;
618
619 /* The FPE|BUS|SEGV|ILL signals leave the system in an undefined
620 * state, thus it is best to exit immediately.
621 */
622#ifdef SYS_SIGLIST_DECLARED
623 strncpy (sh_sig_msg, sys_siglist[mysignal], 40);
624#else
625 strncpy (sh_sig_msg, sh_unix_siglist(mysignal), 40);
626#endif
627 sh_sig_msg[63] = '\0';
628
629 sl_stack_print();
630
631 /* Try to push out an error message.
632 */
633 sh_error_handle ((-1), FIL__, __LINE__, mysignal, MSG_EXIT_NORMAL,
634 sh.prg_name, sh_sig_msg);
635
636 if (skey != NULL)
637 memset (skey, '\0', sizeof(sh_key_t));
638#ifdef WITH_MESSAGE_QUEUE
639 close_ipc ();
640#endif
641
642 do {
643 retval = chdir ("/");
644 } while (retval < 0 && errno == EINTR);
645
646 raise(SIGFPE);
647#endif
648}
649
650
651static
652void sh_unix_sigaction (int mysignal)
653{
654 ++sig_raised;
655#ifdef SIGUSR1
656 if (mysignal == SIGUSR1)
657 sig_debug_switch = 1;
658#endif
659#ifdef SIGUSR2
660 if (mysignal == SIGUSR2)
661 {
662 ++sig_suspend_switch;
663 ++sig_urgent;
664 }
665#endif
666#ifdef SIGHUP
667 if (mysignal == SIGHUP)
668 sig_config_read_again = 1;
669#endif
670#ifdef SIGTTOU
671 if (mysignal == SIGTTOU)
672 sig_force_check = 1;
673#endif
674#ifdef SIGTTIN
675 if (mysignal == SIGTTIN)
676 sig_fresh_trail = 1;
677#endif
678#ifdef SIGABRT
679 if (mysignal == SIGABRT)
680 sig_fresh_trail = 1;
681#endif
682#ifdef SIGQUIT
683 if (mysignal == SIGQUIT)
684 {
685 sig_terminate = 1;
686 ++sig_urgent;
687 }
688#endif
689#ifdef SIGTERM
690 if (mysignal == SIGTERM)
691 {
692 strncpy (sh_sig_msg, _("Terminated"), 40);
693 sig_termfast = 1;
694 ++sig_urgent;
695 }
696#endif
697
698 return;
699}
700
701void sh_unix_ign_sigpipe()
702{
703 struct sigaction ignact;
704
705 ignact.sa_handler = SIG_IGN; /* signal action */
706 sigemptyset( &ignact.sa_mask ); /* set an empty mask */
707 ignact.sa_flags = 0; /* init sa_flags */
708
709#ifdef SIGPIPE
710 retry_sigaction(FIL__, __LINE__, SIGPIPE, &ignact, NULL);
711#endif
712
713 return;
714}
715static
716void sh_unix_siginstall (int goDaemon)
717{
718 struct sigaction act, act_fast, act2, oldact, ignact;
719#if defined (SH_WITH_SERVER)
720 (void) goDaemon;
721#endif
722
723 SL_ENTER(_("sh_unix_siginstall"));
724
725 ignact.sa_handler = SIG_IGN; /* signal action */
726 sigemptyset( &ignact.sa_mask ); /* set an empty mask */
727 ignact.sa_flags = 0; /* init sa_flags */
728
729#if defined(SA_SIGACTION_WORKS)
730 act.sa_sigaction = &sh_unix_sigexit; /* signal action */
731#else
732 act.sa_handler = &sh_unix_sigexit; /* signal action */
733#endif
734
735 sigfillset ( &act.sa_mask ); /* set a full mask */
736
737
738 /* Block all but deadly signals.
739 */
740#ifdef SIGILL
741 sigdelset ( &act.sa_mask, SIGILL );
742#endif
743#ifndef SL_DEBUG
744#ifdef SIGFPE
745 sigdelset ( &act.sa_mask, SIGFPE );
746#endif
747#endif
748#ifdef SIGSEGV
749 sigdelset ( &act.sa_mask, SIGSEGV );
750#endif
751#ifdef SIGBUS
752 sigdelset ( &act.sa_mask, SIGBUS );
753#endif
754
755#if defined(SA_SIGACTION_WORKS)
756 act_fast.sa_sigaction = &sh_unix_sigexit_fast; /* signal action */
757#else
758 act_fast.sa_handler = &sh_unix_sigexit_fast; /* signal action */
759#endif
760
761 sigfillset ( &act_fast.sa_mask ); /* set a full mask */
762
763#ifdef SIGILL
764 sigdelset ( &act_fast.sa_mask, SIGILL );
765#endif
766#ifndef SL_DEBUG
767#ifdef SIGFPE
768 sigdelset ( &act_fast.sa_mask, SIGFPE );
769#endif
770#endif
771#ifdef SIGSEGV
772 sigdelset ( &act_fast.sa_mask, SIGSEGV );
773#endif
774#ifdef SIGBUS
775 sigdelset ( &act_fast.sa_mask, SIGBUS );
776#endif
777
778
779 /* Use siginfo to verify origin of signal, if possible.
780 */
781#if defined(SA_SIGACTION_WORKS)
782 act.sa_flags = SA_SIGINFO;
783 act_fast.sa_flags = SA_SIGINFO;
784#else
785 act.sa_flags = 0;
786 act_fast.sa_flags = 0;
787#endif
788
789 /* Do not block the signal from being received in its handler ...
790 * (is this a good or a bad idea ??).
791 */
792#if defined(SA_NOMASK)
793 act_fast.sa_flags |= SA_NOMASK;
794#elif defined(SA_NODEFER)
795 act_fast.sa_flags |= SA_NODEFER;
796#endif
797
798
799 act2.sa_handler = &sh_unix_sigaction; /* signal action */
800 sigemptyset( &act2.sa_mask ); /* set an empty mask */
801 act2.sa_flags = 0; /* init sa_flags */
802
803 /* signals to control the daemon */
804
805#ifdef SIGHUP
806 retry_sigaction(FIL__, __LINE__, SIGHUP, &act2, &oldact);
807#endif
808#ifdef SIGABRT
809 retry_sigaction(FIL__, __LINE__, SIGABRT, &act2, &oldact);
810#endif
811#ifdef SIGUSR1
812 retry_sigaction(FIL__, __LINE__, SIGUSR1, &act2, &oldact);
813#endif
814#ifdef SIGUSR2
815 retry_sigaction(FIL__, __LINE__, SIGUSR2, &act2, &oldact);
816#endif
817#ifdef SIGQUIT
818 retry_sigaction(FIL__, __LINE__, SIGQUIT, &act2, &oldact);
819#endif
820#ifdef SIGTERM
821 retry_sigaction(FIL__, __LINE__, SIGTERM, &act, &oldact);
822#endif
823
824 /* fatal signals that may cause termination */
825
826#ifdef SIGILL
827 retry_sigaction(FIL__, __LINE__, SIGILL, &act_fast, &oldact);
828#endif
829#ifndef SL_DEBUG
830#ifdef SIGFPE
831 retry_sigaction(FIL__, __LINE__, SIGFPE, &act_fast, &oldact);
832#endif
833#endif
834#ifdef SIGSEGV
835 retry_sigaction(FIL__, __LINE__, SIGSEGV, &act_fast, &oldact);
836#endif
837#ifdef SIGBUS
838 retry_sigaction(FIL__, __LINE__, SIGBUS, &act_fast, &oldact);
839#endif
840
841 /* other signals */
842
843#ifdef SIGINT
844 retry_sigaction(FIL__, __LINE__, SIGINT, &act, &oldact);
845#endif
846#ifdef SIGPIPE
847 retry_sigaction(FIL__, __LINE__, SIGPIPE, &ignact, &oldact);
848#endif
849#ifdef SIGALRM
850 retry_sigaction(FIL__, __LINE__, SIGALRM, &ignact, &oldact);
851#endif
852#ifdef SIGTSTP
853 retry_sigaction(FIL__, __LINE__, SIGTSTP, &ignact, &oldact);
854#endif
855
856#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
857#ifdef SIGTTOU
858 if (goDaemon == 1)
859 retry_sigaction(FIL__, __LINE__, SIGTTOU, &act2, &oldact);
860 else
861 retry_sigaction(FIL__, __LINE__, SIGTTOU, &ignact, &oldact);
862#endif
863#ifdef SIGTTIN
864 if (goDaemon == 1)
865 retry_sigaction(FIL__, __LINE__, SIGTTIN, &act2, &oldact);
866 else
867 retry_sigaction(FIL__, __LINE__, SIGTTIN, &ignact, &oldact);
868#endif
869#else
870#ifdef SIGTTOU
871 retry_sigaction(FIL__, __LINE__, SIGTTOU, &ignact, &oldact);
872#endif
873#ifdef SIGTTIN
874 retry_sigaction(FIL__, __LINE__, SIGTTIN, &ignact, &oldact);
875#endif
876#endif
877
878#ifdef SIGTRAP
879#if !defined(SCREW_IT_UP)
880 retry_sigaction(FIL__, __LINE__, SIGTRAP, &act, &oldact);
881#endif
882#endif
883
884#ifdef SIGPOLL
885 retry_sigaction(FIL__, __LINE__, SIGPOLL, &ignact, &oldact);
886#endif
887#if defined(SIGPROF) && !defined(SH_PROFILE)
888 retry_sigaction(FIL__, __LINE__, SIGPROF, &ignact, &oldact);
889#endif
890#ifdef SIGSYS
891 retry_sigaction(FIL__, __LINE__, SIGSYS, &act, &oldact);
892#endif
893#ifdef SIGURG
894 retry_sigaction(FIL__, __LINE__, SIGURG, &ignact, &oldact);
895#endif
896#if defined(SIGVTALRM) && !defined(SH_PROFILE)
897 retry_sigaction(FIL__, __LINE__, SIGVTALRM, &ignact, &oldact);
898#endif
899#ifdef SIGXCPU
900 retry_sigaction(FIL__, __LINE__, SIGXCPU, &act, &oldact);
901#endif
902#ifdef SIGXFSZ
903 retry_sigaction(FIL__, __LINE__, SIGXFSZ, &act, &oldact);
904#endif
905
906#ifdef SIGEMT
907 retry_sigaction(FIL__, __LINE__, SIGEMT, &ignact, &oldact);
908#endif
909#ifdef SIGSTKFLT
910 retry_sigaction(FIL__, __LINE__, SIGSTKFLT, &act, &oldact);
911#endif
912#ifdef SIGIO
913 retry_sigaction(FIL__, __LINE__, SIGIO, &ignact, &oldact);
914#endif
915#ifdef SIGPWR
916 retry_sigaction(FIL__, __LINE__, SIGPWR, &act, &oldact);
917#endif
918
919#ifdef SIGLOST
920 retry_sigaction(FIL__, __LINE__, SIGLOST, &ignact, &oldact);
921#endif
922#ifdef SIGUNUSED
923 retry_sigaction(FIL__, __LINE__, SIGUNUSED, &ignact, &oldact);
924#endif
925
926 SL_RET0(_("sh_unix_siginstall"));
927}
928
929/* ---------------------------------------------------------------- */
930
931/* checksum the own binary
932 */
933int sh_unix_self_hash (const char * c)
934{
935 char message[512];
936 char hashbuf[KEYBUF_SIZE];
937
938 SL_ENTER(_("sh_unix_self_hash"));
939
940 if (c == NULL)
941 {
942 sh.exec.path[0] = '\0';
943 SL_RETURN((0), _("sh_unix_self_hash"));
944 }
945 sl_strlcpy(sh.exec.path, c, SH_PATHBUF);
946
947 sl_strlcpy(sh.exec.hash,
948 sh_tiger_hash (c, TIGER_FILE, TIGER_NOLIM, hashbuf, sizeof(hashbuf)),
949 KEY_LEN+1);
950 sl_snprintf(message, 512, _("%s has checksum: %s"),
951 sh.exec.path, sh.exec.hash);
952 message[511] = '\0';
953 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, 0, MSG_E_SUBGEN,
954 message, _("sh_unix_self_hash"));
955 if (0 == sl_strcmp(sh.exec.hash, SH_KEY_NULL ))
956 {
957 dlog(1, FIL__, __LINE__,
958 _("Could not checksum my own executable because of the\nfollowing error: %s: %s\n\nPossible reasons include:\n Wrong path in configure file option SamhainPath=/path/to/executable\n No read permission for the effective UID: %d\n"),
959 sh.exec.path, sl_get_errmsg(), (int) sl_ret_euid());
960 sh_error_handle ((-1), FIL__, __LINE__, EACCES, MSG_NOACCESS,
961 (long) sh.real.uid, c);
962 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
963 }
964 SL_RETURN((0), _("sh_unix_self_hash"));
965}
966
967int sh_unix_self_check ()
968{
969 char newhash[KEY_LEN+1];
970 char message[512];
971 char hashbuf[KEYBUF_SIZE];
972
973 SL_ENTER(_("sh_unix_self_check"));
974 if (sh.exec.path == NULL || sh.exec.path[0] == '\0')
975 SL_RETURN((0), _("sh_unix_self_check"));
976
977 sl_strlcpy(newhash,
978 sh_tiger_hash (sh.exec.path, TIGER_FILE, TIGER_NOLIM, hashbuf, sizeof(hashbuf)),
979 KEY_LEN+1);
980 if (0 == sl_strncmp(sh.exec.hash,
981 newhash,
982 KEY_LEN))
983 SL_RETURN((0), _("sh_unix_self_check"));
984
985
986 dlog(1, FIL__, __LINE__,
987 _("The checksum of the executable: %s has changed since startup (%s -> %s).\n"),
988 sh.exec.path, sh.exec.hash, newhash);
989
990 sl_snprintf(message, 512,
991 _("The checksum of %s has changed since startup (%s -> %s)"),
992 sh.exec.path, sh.exec.hash, newhash);
993 message[511] = '\0';
994
995 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, 0, MSG_E_SUBGEN,
996 message, _("sh_unix_self_check"));
997 sh_error_handle ((-1), FIL__, __LINE__, EACCES, MSG_E_AUTH,
998 sh.exec.path);
999 SL_RETURN((-1), _("sh_unix_self_check"));
1000}
1001
1002
1003/* ---------------------------------------------------------------- */
1004
1005long sh_group_to_gid (const char * g, int * fail)
1006{
1007 struct group * w;
1008 gid_t gid = 0;
1009
1010#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1011 struct group grp;
1012 char * buffer;
1013#endif
1014
1015 *fail = -1;
1016
1017 if (g)
1018 {
1019 size_t i;
1020 size_t len = strlen(g);
1021
1022 *fail = 0;
1023
1024 for (i = 0; i < len; ++i)
1025 {
1026 char c = g[i];
1027
1028 if (!isdigit((int) c))
1029 goto is_a_name;
1030 }
1031 return atol(g);
1032
1033 is_a_name:
1034
1035#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1036 buffer = SH_ALLOC(SH_GRBUF_SIZE);
1037 sh_getgrnam_r(g, &grp, buffer, SH_GRBUF_SIZE, &w);
1038#else
1039 w = sh_getgrnam(g);
1040#endif
1041
1042 if (w == NULL)
1043 {
1044 char * tmp = sh_util_strdup(g);
1045 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
1046 _("sh_group_to_gid"), tmp);
1047 SH_FREE(tmp);
1048 *fail = -1;
1049 }
1050 else
1051 {
1052 gid = w->gr_gid;
1053 }
1054#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1055 SH_FREE(buffer);
1056#endif
1057 }
1058
1059 return gid;
1060}
1061
1062/* ---------------------------------------------------------------- */
1063
1064
1065/* added Tue Feb 22 10:36:44 NFT 2000 Rainer Wichmann */
1066static int tf_add_trusted_user_int(const char * c)
1067{
1068 struct passwd * w;
1069 int count;
1070 uid_t pwid = (uid_t)-1;
1071
1072#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1073 struct passwd pwd;
1074 char * buffer;
1075#endif
1076
1077 SL_ENTER(_("tf_add_trusted_user_int"));
1078
1079 /* First check for a user name.
1080 */
1081#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1082 buffer = SH_ALLOC(SH_PWBUF_SIZE);
1083 sh_getpwnam_r(c, &pwd, buffer, SH_PWBUF_SIZE, &w);
1084#else
1085 w = sh_getpwnam(c);
1086#endif
1087
1088 if ((w != NULL) && ((pwid = w->pw_uid) > 0))
1089 goto succe;
1090
1091 /* Failed, so check for a numerical value.
1092 */
1093 pwid = strtol(c, (char **)NULL, 10);
1094 if (pwid > 0 && pwid < 65535)
1095 goto succe;
1096
1097 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
1098 _("add trusted user"), c);
1099#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1100 SH_FREE(buffer);
1101#endif
1102 SL_RETURN((-1), _("tf_add_trusted_user_int"));
1103
1104 succe:
1105 count = sl_trust_add_user(pwid);
1106#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1107 SH_FREE(buffer);
1108#endif
1109 SL_RETURN((count), _("tf_add_trusted_user_int"));
1110}
1111
1112int tf_add_trusted_user(const char * c)
1113{
1114 int i;
1115 char * q;
1116 char * p = sh_util_strdup (c);
1117#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1118 char * saveptr;
1119#endif
1120
1121 SL_ENTER(_("tf_add_trusted_user"));
1122
1123#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1124 q = strtok_r(p, ", \t", &saveptr);
1125#else
1126 q = strtok(p, ", \t");
1127#endif
1128 if (!q)
1129 {
1130 SH_FREE(p);
1131 SL_RETURN((-1), _("tf_add_trusted_user"));
1132 }
1133 while (q)
1134 {
1135 i = tf_add_trusted_user_int(q);
1136 if (SL_ISERROR(i))
1137 {
1138 SH_FREE(p);
1139 SL_RETURN((i), _("tf_add_trusted_user"));
1140 }
1141#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1142 q = strtok_r(NULL, ", \t", &saveptr);
1143#else
1144 q = strtok(NULL, ", \t");
1145#endif
1146 }
1147 SH_FREE(p);
1148 SL_RETURN((0), _("tf_add_trusted_user"));
1149}
1150
1151extern uid_t sl_trust_baduid(void);
1152extern gid_t sl_trust_badgid(void);
1153
1154#if defined(HOST_IS_CYGWIN) || defined(__cygwin__) || defined(__CYGWIN32__) || defined(__CYGWIN__)
1155int tf_trust_check (const char * file, int mode)
1156{
1157 (void) file;
1158 (void) mode;
1159 return 0;
1160}
1161#else
1162int tf_trust_check (const char * file, int mode)
1163{
1164 char * tmp;
1165 char * tmp2;
1166 char * p;
1167 int status;
1168 int level;
1169 uid_t ff_euid = (uid_t) -1;
1170
1171 SL_ENTER(_("tf_trust_check"));
1172
1173 if (mode == SL_YESPRIV)
1174 sl_get_euid(&ff_euid);
1175 else
1176 sl_get_ruid(&ff_euid);
1177
1178#if defined(SH_WITH_SERVER)
1179 if (0 == sl_ret_euid()) /* privileges not dropped yet */
1180 {
1181#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1182 struct passwd pwd;
1183 char * buffer = SH_ALLOC(SH_PWBUF_SIZE);
1184 struct passwd * tempres;
1185 sh_getpwnam_r(DEFAULT_IDENT, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
1186#else
1187 struct passwd * tempres = sh_getpwnam(DEFAULT_IDENT);
1188#endif
1189
1190 if (!tempres)
1191 {
1192 dlog(1, FIL__, __LINE__,
1193 _("User %s does not exist. Please add the user to your system.\n"),
1194 DEFAULT_IDENT);
1195 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
1196 }
1197 else
1198 {
1199 ff_euid = tempres->pw_uid;
1200 }
1201#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1202 SH_FREE(buffer);
1203#endif
1204 }
1205#endif
1206
1207 status = sl_trustfile_euid(file, ff_euid);
1208
1209 if ( SL_ENONE != status)
1210 {
1211 if (status == SL_ESTAT)
1212 level = SH_ERR_ALL;
1213 else
1214 level = SH_ERR_ERR;
1215
1216 tmp = sh_util_safe_name (file);
1217 p = sl_trust_errfile();
1218 if (p && *p != '\0')
1219 {
1220 tmp2 = sh_util_safe_name (sl_trust_errfile());
1221 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST2,
1222 sl_error_string(status), tmp, tmp2);
1223 SH_FREE(tmp2);
1224 }
1225 else
1226 {
1227 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST1,
1228 sl_error_string(status), tmp);
1229 }
1230 SH_FREE(tmp);
1231
1232 if (status == SL_EBADUID || status == SL_EBADGID ||
1233 status == SL_EBADOTH || status == SL_ETRUNC ||
1234 status == SL_EINTERNAL )
1235 {
1236 switch (status) {
1237 case SL_EINTERNAL:
1238 dlog(1, FIL__, __LINE__,
1239 _("An internal error occured in the trustfile function.\n"));
1240 break;
1241 case SL_ETRUNC:
1242 tmp = sh_util_safe_name (file);
1243 dlog(1, FIL__, __LINE__,
1244 _("A filename truncation occured in the trustfile function.\nProbably the normalized filename for %s\nis too long. This may be due e.g. to deep or circular softlinks.\n"),
1245 tmp);
1246 SH_FREE(tmp);
1247 break;
1248 case SL_EBADOTH:
1249 tmp = sh_util_safe_name (file);
1250 p = sl_trust_errfile();
1251 dlog(1, FIL__, __LINE__,
1252 _("The path element: %s\nin the filename: %s is world writeable.\n"),
1253 p, tmp);
1254 SH_FREE(tmp);
1255 break;
1256 case SL_EBADUID:
1257 tmp = sh_util_safe_name (file);
1258 p = sl_trust_errfile();
1259 dlog(1, FIL__, __LINE__,
1260 _("The owner (UID = %ld) of the path element: %s\nin the filename: %s\nis not in the list of trusted users.\nTo fix the problem, you can:\n - run ./configure again with the option --with-trusted=0,...,UID\n where UID is the UID of the untrusted user, or\n - use the option TrustedUser=UID in the configuration file.\n"),
1261 (UID_CAST)sl_trust_baduid(), p, tmp);
1262 SH_FREE(tmp);
1263 break;
1264 case SL_EBADGID:
1265 tmp = sh_util_safe_name (file);
1266 p = sl_trust_errfile();
1267 dlog(1, FIL__, __LINE__,
1268 _("The path element: %s\nin the filename: %s\nis group writeable (GID = %ld), and at least one of the group\nmembers (UID = %ld) is not in the list of trusted users.\nTo fix the problem, you can:\n - run ./configure again with the option --with-trusted=0,...,UID\n where UID is the UID of the untrusted user, or\n - use the option TrustedUser=UID in the configuration file.\n"),
1269 p, tmp, (UID_CAST)sl_trust_badgid(),
1270 (UID_CAST)sl_trust_baduid());
1271 SH_FREE(tmp);
1272 break;
1273 default:
1274 break;
1275 }
1276
1277 SL_RETURN((-1), _("tf_trust_check"));
1278 }
1279 }
1280
1281 SL_RETURN((0), _("tf_trust_check"));
1282}
1283#endif
1284
1285#ifdef HAVE_INITGROUPS
1286#ifdef HOST_IS_OSF
1287int sh_unix_initgroups ( char * in_user, gid_t in_gid)
1288#else
1289int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1290#endif
1291{
1292 int status = -1;
1293 status = sh_initgroups (in_user, in_gid);
1294 if (status < 0)
1295 {
1296 if (errno == EPERM)
1297 return 0;
1298 if (errno == EINVAL)
1299 return 0;
1300 return -1;
1301 }
1302 return 0;
1303}
1304#else
1305int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1306{
1307 (void) in_user;
1308 (void) in_gid;
1309 return 0;
1310}
1311#endif
1312
1313#ifdef HAVE_INITGROUPS
1314char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len);
1315int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1316{
1317 int status = -1;
1318 char user[SH_MINIBUF];
1319
1320 SL_ENTER(_("sh_unix_initgroups2"));
1321
1322 if (NULL == sh_unix_getUIDname (SH_ERR_ERR, in_pid, user, sizeof(user)))
1323 SL_RETURN((-1), _("sh_unix_initgroups2"));
1324 status = sh_initgroups (user, in_gid);
1325 if (status < 0)
1326 {
1327 if (errno == EPERM)
1328 status = 0;
1329 if (errno == EINVAL)
1330 status = 0;
1331 }
1332 SL_RETURN((status), _("sh_unix_initgroups2"));
1333}
1334#else
1335int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1336{
1337 (void) in_pid;
1338 (void) in_gid;
1339 return 0;
1340}
1341#endif
1342
1343void sh_unix_closeall (int fd, int except, int inchild)
1344{
1345 int fdx = fd;
1346#ifdef _SC_OPEN_MAX
1347 int fdlimit = sysconf (_SC_OPEN_MAX);
1348#else
1349#ifdef OPEN_MAX
1350 int fdlimit = OPEN_MAX;
1351#else
1352 int fdlimit = _POSIX_OPEN_MAX;
1353#endif
1354#endif
1355
1356 SL_ENTER(_("sh_unix_closeall"));
1357
1358 /* can't happen - so fix it :-(
1359 */
1360 if (fdlimit < 0)
1361 fdlimit = 20; /* POSIX lower limit */
1362
1363 if (fdlimit > 65536)
1364 fdlimit = 65536;
1365
1366 if (!inchild)
1367 sl_dropall (fdx, except);
1368 else
1369 sl_dropall_dirty (fdx, except);
1370
1371 /* Close everything from fd (inclusive) up to fdlimit (exclusive).
1372 */
1373 while (fd < fdlimit)
1374 {
1375 if (fd == except)
1376 fd++;
1377 else if (slib_do_trace != 0 && fd == slib_trace_fd)
1378 fd++;
1379 else
1380 sl_close_fd(FIL__, __LINE__, fd++);
1381 }
1382
1383 SL_RET0(_("sh_unix_closeall"));
1384}
1385
1386static void sh_unix_setlimits(void)
1387{
1388 struct rlimit limits;
1389
1390 SL_ENTER(_("sh_unix_setlimits"));
1391
1392 limits.rlim_cur = RLIM_INFINITY;
1393 limits.rlim_max = RLIM_INFINITY;
1394
1395#ifdef RLIMIT_CPU
1396 setrlimit (RLIMIT_CPU, &limits);
1397#endif
1398#ifdef RLIMIT_FSIZE
1399 setrlimit (RLIMIT_FSIZE, &limits);
1400#endif
1401#ifdef RLIMIT_DATA
1402 setrlimit (RLIMIT_DATA, &limits);
1403#endif
1404#ifdef RLIMIT_STACK
1405 setrlimit (RLIMIT_STACK, &limits);
1406#endif
1407#ifdef RLIMIT_RSS
1408 setrlimit (RLIMIT_RSS, &limits);
1409#endif
1410#ifdef RLIMIT_NPROC
1411 setrlimit (RLIMIT_NPROC, &limits);
1412#endif
1413#ifdef RLIMIT_MEMLOCK
1414 setrlimit (RLIMIT_MEMLOCK, &limits);
1415#endif
1416
1417#if !defined(SL_DEBUG)
1418 /* no core dumps
1419 */
1420 limits.rlim_cur = 0;
1421 limits.rlim_max = 0;
1422#ifdef RLIMIT_CORE
1423 setrlimit (RLIMIT_CORE, &limits);
1424#endif
1425#else
1426#ifdef RLIMIT_CORE
1427 setrlimit (RLIMIT_CORE, &limits);
1428#endif
1429#endif
1430
1431 limits.rlim_cur = 1024;
1432 limits.rlim_max = 1024;
1433
1434#if defined(RLIMIT_NOFILE)
1435 setrlimit (RLIMIT_NOFILE, &limits);
1436#elif defined(RLIMIT_OFILE)
1437 setrlimit (RLIMIT_OFILE, &limits);
1438#endif
1439
1440 SL_RET0(_("sh_unix_setlimits"));
1441}
1442
1443static void sh_unix_copyenv(void)
1444{
1445 char ** env0 = environ;
1446 char ** env1;
1447 int envlen = 0;
1448 size_t len;
1449
1450 SL_ENTER(_("sh_unix_copyenv"));
1451
1452 while (env0 != NULL && env0[envlen] != NULL) {
1453 /* printf("%2d: %s\n", envlen, env0[envlen]); */
1454 ++envlen;
1455 }
1456 ++envlen;
1457
1458 /* printf("-> %2d: slots allocated\n", envlen); */
1459 env1 = malloc (sizeof(char *) * envlen); /* only once */
1460 if (env1 == NULL)
1461 {
1462 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1463 SL_RET0(_("sh_unix_copyenv"));
1464 }
1465 env0 = environ;
1466 envlen = 0;
1467
1468 while (env0 != NULL && env0[envlen] != NULL) {
1469 len = strlen(env0[envlen]) + 1;
1470 env1[envlen] = malloc (len); /* only once */
1471 if (env1[envlen] == NULL)
1472 {
1473 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1474 SL_RET0(_("sh_unix_copyenv"));
1475 }
1476 sl_strlcpy(env1[envlen], env0[envlen], len);
1477 ++envlen;
1478 }
1479 env1[envlen] = NULL;
1480
1481 environ = env1;
1482 SL_RET0(_("sh_unix_copyenv"));
1483}
1484
1485/* delete all environment variables
1486 */
1487static void sh_unix_zeroenv(void)
1488{
1489 char * c;
1490 char ** env;
1491
1492 SL_ENTER(_("sh_unix_zeroenv"));
1493
1494 sh_unix_copyenv();
1495 env = environ;
1496
1497 while (env != NULL && *env != NULL) {
1498 c = strchr ((*env), '=');
1499#ifdef WITH_MYSQL
1500 /*
1501 * Skip the MYSQL_UNIX_PORT environment variable; MySQL may need it.
1502 */
1503 if (0 == sl_strncmp((*env), _("MYSQL_UNIX_PORT="), 16))
1504 {
1505 ++(env);
1506 continue;
1507 }
1508 if (0 == sl_strncmp((*env), _("MYSQL_TCP_PORT="), 15))
1509 {
1510 ++(env);
1511 continue;
1512 }
1513 if (0 == sl_strncmp((*env), _("MYSQL_HOME="), 11))
1514 {
1515 ++(env);
1516 continue;
1517 }
1518#endif
1519#ifdef WITH_ORACLE
1520 /*
1521 * Skip the ORACLE_HOME and TNS_ADMIN environment variables;
1522 * Oracle may need them.
1523 */
1524 if (0 == sl_strncmp((*env), _("ORACLE_HOME="), 12))
1525 {
1526 ++(env);
1527 continue;
1528 }
1529 if (0 == sl_strncmp((*env), _("TNS_ADMIN="), 10))
1530 {
1531 ++(env);
1532 continue;
1533 }
1534#endif
1535 /*
1536 * Skip the TZ environment variable.
1537 */
1538 if (0 == sl_strncmp((*env), _("TZ="), 3))
1539 {
1540 ++(env);
1541 continue;
1542 }
1543 ++(env);
1544 if (c != NULL)
1545 {
1546 ++c;
1547 while ((*c) != '\0') {
1548 (*c) = '\0';
1549 ++c;
1550 }
1551 }
1552 }
1553
1554#ifdef HAVE_TZSET
1555 tzset();
1556#endif
1557
1558 SL_RET0(_("sh_unix_zeroenv"));
1559}
1560
1561
1562static void sh_unix_resettimer(void)
1563{
1564 struct itimerval this_timer;
1565
1566 SL_ENTER(_("sh_unix_resettimer"));
1567
1568 this_timer.it_value.tv_sec = 0;
1569 this_timer.it_value.tv_usec = 0;
1570
1571 this_timer.it_interval.tv_sec = 0;
1572 this_timer.it_interval.tv_usec = 0;
1573
1574 setitimer(ITIMER_REAL, &this_timer, NULL);
1575#if !defined(SH_PROFILE)
1576 setitimer(ITIMER_VIRTUAL, &this_timer, NULL);
1577 setitimer(ITIMER_PROF, &this_timer, NULL);
1578#endif
1579
1580 SL_RET0(_("sh_unix_resettimer"));
1581}
1582
1583static void sh_unix_resetsignals(void)
1584{
1585 int sig_num;
1586#ifdef NSIG
1587 int max_sig = NSIG;
1588#else
1589 int max_sig = 255;
1590#endif
1591 int test;
1592 int status;
1593 struct sigaction act;
1594#if !defined(SH_PROFILE)
1595 struct sigaction oldact;
1596#endif
1597
1598 sigset_t set_proc;
1599
1600 SL_ENTER(_("sh_unix_resetsignals"));
1601 /*
1602 * Reset the current signal mask (inherited from parent process).
1603 */
1604
1605 sigfillset(&set_proc);
1606
1607 do {
1608 errno = 0;
1609 test = SH_SETSIGMASK(SIG_UNBLOCK, &set_proc, NULL);
1610 } while (test < 0 && errno == EINTR);
1611
1612 /*
1613 * Reset signal handling.
1614 */
1615
1616 act.sa_handler = SIG_DFL; /* signal action */
1617 sigemptyset( &act.sa_mask ); /* set an empty mask */
1618 act.sa_flags = 0; /* init sa_flags */
1619
1620 for (sig_num = 1; sig_num <= max_sig; ++sig_num)
1621 {
1622#if !defined(SH_PROFILE)
1623 test = retry_sigaction(FIL__, __LINE__, sig_num, &act, &oldact);
1624#else
1625 test = 0;
1626#endif
1627 if ((test == -1) && (errno != EINVAL))
1628 {
1629 char errbuf[SH_ERRBUF_SIZE];
1630 status = errno;
1631 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_SIG,
1632 sh_error_message (status, errbuf, sizeof(errbuf)), sig_num);
1633 }
1634 }
1635
1636 SL_RET0(_("sh_unix_resetsignals"));
1637}
1638
1639/* Get the local hostname (FQDN)
1640 */
1641static char * sh_tolower (char * s)
1642{
1643 char * ret = s;
1644 if (s)
1645 {
1646 for (; *s; ++s)
1647 {
1648 *s = tolower((unsigned char) *s);
1649 }
1650 }
1651 return ret;
1652}
1653
1654
1655#include <sys/socket.h>
1656
1657/* Required for BSD
1658 */
1659#ifdef HAVE_NETINET_IN_H
1660#include <netinet/in.h>
1661#endif
1662
1663#include <arpa/inet.h>
1664
1665const char * sh_unix_h_name (struct hostent * host_entry)
1666{
1667 char ** p;
1668 if (strchr(host_entry->h_name, '.')) {
1669 return host_entry->h_name;
1670 } else {
1671 for (p = host_entry->h_aliases; *p; ++p) {
1672 if (strchr(*p, '.'))
1673 return *p;
1674 }
1675 }
1676 return host_entry->h_name;
1677}
1678
1679/* uname() on FreeBSD is broken, because the 'nodename' buf is too small
1680 * to hold a valid (leftmost) domain label.
1681 */
1682#if defined(HAVE_UNAME) && !defined(HOST_IS_FREEBSD)
1683#include <sys/utsname.h>
1684void sh_unix_localhost()
1685{
1686 struct utsname buf;
1687 int i;
1688 int ddot;
1689 int len;
1690 char * p;
1691 char hostname[256];
1692 char numeric[SH_IP_BUF];
1693 char * canonical;
1694
1695
1696 SL_ENTER(_("sh_unix_localhost"));
1697
1698 (void) uname (&buf);
1699 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1700 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1701 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1702 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1703
1704 /* Workaround for cases where nodename could be
1705 * a truncated FQDN.
1706 */
1707 if (strlen(buf.nodename) == (sizeof(buf.nodename)-1))
1708 {
1709 p = strchr(buf.nodename, '.');
1710 if (NULL != p) {
1711 *p = '\0';
1712 sl_strlcpy(hostname, buf.nodename, 256);
1713 } else {
1714#ifdef HAVE_GETHOSTNAME
1715 if (0 != gethostname(hostname, 256))
1716 {
1717 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1718 _("nodename returned by uname may be truncated"),
1719 _("sh_unix_localhost"));
1720 sl_strlcpy (hostname, buf.nodename, 256);
1721 }
1722 else
1723 {
1724 hostname[255] = '\0';
1725 }
1726#else
1727 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1728 _("nodename returned by uname may be truncated"),
1729 _("sh_unix_localhost"));
1730 sl_strlcpy(hostname, buf.nodename, 256);
1731#endif
1732 }
1733 }
1734 else
1735 {
1736 sl_strlcpy(hostname, buf.nodename, 256);
1737 }
1738
1739 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1740
1741 if (canonical == NULL)
1742 {
1743 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1744 sh_tolower (sh.host.name);
1745 }
1746 else
1747 {
1748 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1749 SH_FREE(canonical);
1750 }
1751
1752 /* check whether it looks like a FQDN
1753 */
1754 len = sl_strlen(sh.host.name);
1755 ddot = 0;
1756 for (i = 0; i < len; ++i)
1757 if (sh.host.name[i] == '.') ++ddot;
1758
1759 if (ddot == 0)
1760 {
1761 dlog(1, FIL__, __LINE__,
1762 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1763 hostname, sh.host.name);
1764 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1765 SL_RET0(_("sh_unix_localhost"));
1766 }
1767
1768 if (sh_ipvx_is_numeric(sh.host.name))
1769 {
1770 dlog(1, FIL__, __LINE__,
1771 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1772 hostname, sh.host.name);
1773 }
1774
1775 SL_RET0(_("sh_unix_localhost"));
1776}
1777
1778#else
1779
1780/*
1781 * --FreeBSD code
1782 */
1783#if defined(HAVE_UNAME)
1784#include <sys/utsname.h>
1785#endif
1786void sh_unix_localhost()
1787{
1788#if defined(HAVE_UNAME)
1789 struct utsname buf;
1790#endif
1791 int i;
1792 int ddot;
1793 int len;
1794 char hostname[1024];
1795 char numeric[SH_IP_BUF];
1796 char * canonical;
1797
1798 SL_ENTER(_("sh_unix_localhost"));
1799
1800#if defined(HAVE_UNAME)
1801 (void) uname (&buf);
1802 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1803 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1804 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1805 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1806#endif
1807
1808 (void) gethostname (hostname, 1024);
1809 hostname[1023] = '\0';
1810
1811 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1812
1813 if (canonical == NULL)
1814 {
1815 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1816 sh_tolower (sh.host.name);
1817 }
1818 else
1819 {
1820 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1821 SH_FREE(canonical);
1822 }
1823
1824 /* check whether it looks like a FQDN
1825 */
1826 len = sl_strlen(sh.host.name);
1827 ddot = 0;
1828 for (i = 0; i < len; ++i)
1829 if (sh.host.name[i] == '.') ++ddot;
1830 if (ddot == 0)
1831 {
1832 dlog(1, FIL__, __LINE__,
1833 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1834 hostname, sh.host.name);
1835 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1836 SL_RET0(_("sh_unix_localhost"));
1837 }
1838
1839 if (sh_ipvx_is_numeric(sh.host.name))
1840 {
1841 dlog(1, FIL__, __LINE__,
1842 _("According to uname, your nodename is %s, but your resolver\nlibrary cannot resolve this nodename to a FQDN.\nRather, it resolves this to %s.\nFor more information, see the entry about self-resolving under\n'Most frequently' in the FAQ that you will find in the docs/ subdirectory.\n"),
1843 hostname, sh.host.name);
1844 }
1845
1846 SL_RET0(_("sh_unix_localhost"));
1847}
1848#endif
1849
1850
1851void sh_unix_memlock()
1852{
1853 SL_ENTER(_("sh_unix_memlock"));
1854
1855 /* do this before dropping privileges
1856 */
1857#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
1858 if (skey->mlock_failed == SL_FALSE)
1859 {
1860 if ( (-1) == sh_unix_mlock( FIL__, __LINE__,
1861 (char *) skey, sizeof (sh_key_t)) )
1862 {
1863 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1864 skey->mlock_failed = SL_TRUE;
1865 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1866 }
1867 }
1868#else
1869 if (skey->mlock_failed == SL_FALSE)
1870 {
1871 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1872 skey->mlock_failed = SL_TRUE;
1873 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1874 }
1875#endif
1876
1877 SL_RET0(_("sh_unix_memlock"));
1878}
1879
1880#ifdef SH_WITH_SERVER
1881char * chroot_dir = NULL;
1882
1883int sh_unix_set_chroot(const char * str)
1884{
1885 size_t len;
1886 static int block = 0;
1887
1888 if (block == 1)
1889 return 0;
1890
1891 if (str && *str == '/')
1892 {
1893 len = strlen(str) + 1;
1894 chroot_dir = malloc(strlen(str) + 1); /* only once */
1895 if (!chroot_dir)
1896 {
1897 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1898 return 1;
1899 }
1900 sl_strlcpy(chroot_dir, str, len);
1901 block = 1;
1902 return 0;
1903 }
1904 return 1;
1905}
1906
1907int sh_unix_chroot(void)
1908{
1909 int status;
1910
1911 if (chroot_dir != NULL)
1912 {
1913 status = retry_aud_chdir(FIL__, __LINE__, chroot_dir);
1914 if ( (-1) == status )
1915 {
1916 char errbuf[SH_ERRBUF_SIZE];
1917 status = errno;
1918 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1919 sh_error_message (status, errbuf, sizeof(errbuf)), chroot_dir);
1920 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1921 }
1922 /* flawfinder: ignore */
1923 return (chroot(chroot_dir));
1924 }
1925 return 0;
1926}
1927/* #ifdef SH_WITH_SERVER */
1928#else
1929int sh_unix_chroot(void) { return 0; }
1930#endif
1931
1932/* daemon mode
1933 */
1934static int block_setdeamon = 0;
1935
1936int sh_unix_setdeamon(const char * dummy)
1937{
1938 int res = 0;
1939
1940 SL_ENTER(_("sh_unix_setdeamon"));
1941
1942 if (block_setdeamon != 0)
1943 SL_RETURN((0),_("sh_unix_setdeamon"));
1944
1945 if (dummy == NULL)
1946 sh.flag.isdaemon = ON;
1947 else
1948 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1949
1950 if (sh.flag.opts == S_TRUE)
1951 block_setdeamon = 1;
1952
1953 SL_RETURN(res, _("sh_unix_setdeamon"));
1954}
1955#if defined(HAVE_LIBPRELUDE)
1956#include "sh_prelude.h"
1957#endif
1958
1959int sh_unix_setnodeamon(const char * dummy)
1960{
1961 int res = 0;
1962
1963 SL_ENTER(_("sh_unix_setnodeamon"));
1964
1965 if (block_setdeamon != 0)
1966 SL_RETURN((0),_("sh_unix_setmodeamon"));
1967
1968 if (dummy == NULL)
1969 sh.flag.isdaemon = OFF;
1970 else
1971 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1972
1973 if (sh.flag.opts == S_TRUE)
1974 block_setdeamon = 1;
1975
1976 SL_RETURN(res, _("sh_unix_setnodeamon"));
1977}
1978
1979int sh_unix_init(int goDaemon)
1980{
1981 int status;
1982 uid_t uid;
1983 pid_t oldpid = getpid();
1984#if defined(SH_WITH_SERVER)
1985 extern int sh_socket_open_int (void);
1986#endif
1987 char errbuf[SH_ERRBUF_SIZE];
1988
1989 extern void sh_kill_sub();
1990
1991 SL_ENTER(_("sh_unix_init"));
1992
1993 /* fork twice, exit the parent process
1994 */
1995 if (goDaemon == 1) {
1996
1997 switch (aud_fork(FIL__, __LINE__)) {
1998 case 0: break; /* child process continues */
1999 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
2000 default: /* parent process exits */
2001 sh_kill_sub();
2002 aud__exit(FIL__, __LINE__, 0);
2003 }
2004
2005 /* Child processes do not inherit page locks across a fork.
2006 * Error in next fork would return in this (?) thread of execution.
2007 */
2008 sh_unix_memlock();
2009
2010 setsid(); /* should not fail */
2011 sh.pid = (UINT64) getpid();
2012
2013 switch (aud_fork(FIL__, __LINE__)) {
2014 case 0: break; /* child process continues */
2015 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
2016 default: /* parent process exits */
2017 sh_kill_sub();
2018 aud__exit(FIL__, __LINE__, 0);
2019 }
2020
2021 /* Child processes do not inherit page locks across a fork.
2022 */
2023 sh_unix_memlock();
2024 sh.pid = (UINT64) getpid();
2025
2026 } else {
2027 setsid(); /* should not fail */
2028 }
2029
2030 /* set working directory
2031 */
2032#ifdef SH_PROFILE
2033 status = 0;
2034#else
2035 status = retry_aud_chdir(FIL__, __LINE__, "/");
2036#endif
2037 if ( (-1) == status )
2038 {
2039 status = errno;
2040 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
2041 sh_error_message (status, errbuf, sizeof(errbuf)), "/");
2042 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2043 }
2044
2045 /* reset timers
2046 */
2047 sh_unix_resettimer();
2048
2049 /* signal handlers
2050 */
2051 sh_unix_resetsignals();
2052#if defined(SCREW_IT_UP)
2053 sh_sigtrap_prepare();
2054#endif
2055 sh_unix_siginstall (goDaemon);
2056
2057 /* set file creation mask
2058 */
2059 (void) umask (0); /* should not fail */
2060
2061 /* set resource limits to maximum, and
2062 * core dump size to zero
2063 */
2064 sh_unix_setlimits();
2065
2066 /* zero out the environment (like PATH='\0')
2067 */
2068 sh_unix_zeroenv();
2069
2070 if (goDaemon == 1)
2071 {
2072 /* Close first tree file descriptors
2073 */
2074 sl_close_fd (FIL__, __LINE__, 0); /* if running as daemon */
2075 sl_close_fd (FIL__, __LINE__, 1); /* if running as daemon */
2076 sl_close_fd (FIL__, __LINE__, 2); /* if running as daemon */
2077
2078 /* Enable full error logging
2079 */
2080 sh_error_only_stderr (S_FALSE);
2081
2082 /* open first three streams to /dev/null
2083 */
2084 status = aud_open(FIL__, __LINE__, SL_NOPRIV, _("/dev/null"), O_RDWR, 0);
2085 if (status < 0)
2086 {
2087 status = errno;
2088 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2089 sh_error_message(status, errbuf, sizeof(errbuf)), _("open"));
2090 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2091 }
2092
2093 status = retry_aud_dup(FIL__, __LINE__, 0);
2094 if (status >= 0)
2095 retry_aud_dup(FIL__, __LINE__, 0);
2096
2097 if (status < 0)
2098 {
2099 status = errno;
2100 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2101 sh_error_message(status, errbuf, sizeof(errbuf)), _("dup"));
2102 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2103 }
2104
2105 sh_error_enable_unsafe (S_TRUE);
2106#if defined(HAVE_LIBPRELUDE)
2107 sh_prelude_reset ();
2108#endif
2109
2110 /* --- wait until parent has exited ---
2111 */
2112 while (1 == 1)
2113 {
2114 errno = 0;
2115 if (0 > aud_kill (FIL__, __LINE__, oldpid, 0) && errno == ESRCH)
2116 {
2117 break;
2118 }
2119 retry_msleep(0, 1);
2120 }
2121
2122 /* write PID file
2123 */
2124 status = sh_unix_write_pid_file();
2125 if (status < 0)
2126 {
2127 sl_get_euid(&uid);
2128 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_PIDFILE,
2129 (long) uid, sh.srvlog.alt);
2130 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2131 }
2132#if defined(SH_WITH_SERVER)
2133 sh_socket_open_int ();
2134#endif
2135 }
2136 else
2137 {
2138 sh_error_enable_unsafe (S_TRUE);
2139#if defined(HAVE_LIBPRELUDE)
2140 sh_prelude_reset ();
2141#endif
2142#if defined(SH_WITH_SERVER)
2143 sh_socket_open_int ();
2144#endif
2145 }
2146
2147 /* chroot (this is a no-op if no chroot dir is specified
2148 */
2149 status = sh_unix_chroot();
2150 if (status < 0)
2151 {
2152 status = errno;
2153 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2154 sh_error_message(status, errbuf, sizeof(errbuf)), _("chroot"));
2155 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2156 }
2157
2158 /* drop capabilities
2159 */
2160 sl_drop_cap();
2161
2162 SL_RETURN((0),_("sh_unix_init"));
2163}
2164
2165/* --- run a command, securely --- */
2166
2167int sh_unix_run_command (const char * str)
2168{
2169 pid_t pid;
2170 char * arg[4];
2171 char * env[5];
2172 char * path = sh_util_strdup(_("/bin/sh"));
2173
2174 int status = -1;
2175
2176 arg[0] = sh_util_strdup(_("/bin/sh"));
2177 arg[1] = sh_util_strdup(_("-c"));
2178 arg[2] = sh_util_strdup(str);
2179 arg[3] = NULL;
2180
2181 env[0] = sh_util_strdup(_("PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/ucb"));
2182 env[1] = sh_util_strdup(_("SHELL=/bin/sh"));
2183 env[2] = sh_util_strdup(_("IFS= \t\n"));
2184 if (getenv("TZ")) { /* flawfinder: ignore */
2185 char * tz = sh_util_strdup(getenv("TZ")); /* flawfinder: ignore */
2186 size_t tzlen = strlen(tz);
2187 if (SL_TRUE == sl_ok_adds (4, tzlen)) {
2188 env[3] = SH_ALLOC(4+tzlen);
2189 sl_strlcpy(env[3], "TZ=", 4);
2190 sl_strlcat(env[3], tz , 4+tzlen);
2191 } else {
2192 env[3] = NULL;
2193 }
2194 } else {
2195 env[3] = NULL;
2196 }
2197 env[4] = NULL;
2198
2199 pid = fork();
2200
2201 if (pid == (pid_t)(-1))
2202 {
2203 return -1;
2204 }
2205
2206 else if (pid == 0) /* child */
2207 {
2208 memset(skey, 0, sizeof(sh_key_t));
2209 (void) umask(S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
2210 sh_unix_closeall (3, -1, SL_TRUE); /* in child process */
2211 execve(path, arg, env);
2212 _exit(EXIT_FAILURE);
2213 }
2214
2215 else /* parent */
2216 {
2217 int r;
2218
2219 while((r = waitpid(pid, &status, WUNTRACED)) != pid && r != -1) ;
2220
2221#if !defined(USE_UNO)
2222 if (r == -1 || !WIFEXITED(status))
2223 {
2224 status = -1;
2225 }
2226 else
2227 {
2228 status = WEXITSTATUS(status);
2229 }
2230#endif
2231 }
2232
2233 return status;
2234}
2235
2236/********************************************************
2237 *
2238 * TIME
2239 *
2240 ********************************************************/
2241
2242/* Figure out the time offset of the current timezone
2243 * in a portable way.
2244 */
2245char * t_zone(const time_t * xx)
2246{
2247 struct tm aa;
2248 struct tm bb;
2249
2250 int sign = 0;
2251 int diff = 0;
2252 int hh, mm;
2253 static char tz[64];
2254
2255 SL_ENTER(_("t_zone"));
2256
2257#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2258 gmtime_r (xx, &aa);
2259#else
2260 memcpy (&aa, gmtime(xx), sizeof(struct tm));
2261#endif
2262
2263#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2264 localtime_r (xx, &bb);
2265#else
2266 memcpy (&bb, localtime(xx), sizeof(struct tm));
2267#endif
2268
2269 /* Check for datum wrap-around.
2270 */
2271 if (aa.tm_year < bb.tm_year)
2272 sign = (-1);
2273 else if (aa.tm_mon < bb.tm_mon)
2274 sign = (-1);
2275 else if (aa.tm_mday < bb.tm_mday)
2276 sign = (-1);
2277 else if (bb.tm_year < aa.tm_year)
2278 sign = ( 1);
2279 else if (bb.tm_mon < aa.tm_mon)
2280 sign = ( 1);
2281 else if (bb.tm_mday < aa.tm_mday)
2282 sign = ( 1);
2283
2284 diff = aa.tm_hour * 60 + aa.tm_min;
2285 diff = (bb.tm_hour * 60 + bb.tm_min) - diff;
2286 diff = diff - (sign * 24 * 60); /* datum wrap-around correction */
2287 hh = diff / 60;
2288 mm = diff - (hh * 60);
2289 sprintf (tz, _("%+03d%02d"), hh, mm); /* known to fit */
2290
2291 SL_RETURN(tz, _("t_zone"));
2292}
2293
2294unsigned long sh_unix_longtime ()
2295{
2296 return ((unsigned long)time(NULL));
2297}
2298
2299#ifdef HAVE_GETTIMEOFDAY
2300unsigned long sh_unix_notime ()
2301{
2302 struct timeval tv;
2303
2304 gettimeofday (&tv, NULL);
2305
2306 return ((unsigned long)(tv.tv_sec + tv.tv_usec * 10835 + getpid() + getppid()));
2307
2308}
2309#endif
2310
2311static int count_dev_time = 0;
2312
2313void reset_count_dev_time(void)
2314{
2315 count_dev_time = 0;
2316 return;
2317}
2318
2319int sh_unix_settimeserver (const char * address)
2320{
2321
2322 SL_ENTER(_("sh_unix_settimeserver"));
2323
2324 if (address != NULL && count_dev_time < 2
2325 && sl_strlen(address) < SH_PATHBUF)
2326 {
2327 if (count_dev_time == 0)
2328 sl_strlcpy (sh.srvtime.name, address, SH_PATHBUF);
2329 else
2330 sl_strlcpy (sh.srvtime.alt, address, SH_PATHBUF);
2331
2332 ++count_dev_time;
2333 SL_RETURN((0), _("sh_unix_settimeserver"));
2334 }
2335 SL_RETURN((-1), _("sh_unix_settimeserver"));
2336}
2337
2338
2339#ifdef HAVE_NTIME
2340#define UNIXEPOCH 2208988800UL /* difference between Unix time and net time
2341 * The UNIX EPOCH starts in 1970.
2342 */
2343#include <sys/socket.h>
2344#include <netinet/in.h>
2345#include <arpa/inet.h>
2346#include <netdb.h>
2347#include <ctype.h>
2348#endif
2349
2350/* Timeserver service. */
2351/* define is missing on HP-UX 10.20 */
2352#ifndef IPPORT_TIMESERVER
2353#define IPPORT_TIMESERVER 37
2354#endif
2355
2356char * sh_unix_time (time_t thetime, char * buffer, size_t len)
2357{
2358
2359 int status;
2360 char AsciiTime[81]; /* local time */
2361 time_t time_now;
2362 struct tm * time_ptr;
2363#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2364 struct tm time_tm;
2365#endif
2366#ifdef SH_USE_XML
2367 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2368#else
2369 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2370#endif
2371
2372#ifdef HAVE_NTIME
2373 int fd; /* network file descriptor */
2374 u_char net_time[4]; /* remote time in network format */
2375 static int failerr = 0; /* no net time */
2376 int fail = 0; /* no net time */
2377 int errflag;
2378 char errmsg[256];
2379 char error_call[SH_MINIBUF];
2380 int error_num;
2381#endif
2382
2383 SL_ENTER(_("sh_unix_time"));
2384
2385#ifdef HAVE_NTIME
2386 if (thetime == 0)
2387 {
2388 if (sh.srvtime.name[0] == '\0')
2389 {
2390 fail = 1;
2391 (void) time (&time_now);
2392 }
2393 else /* have a timeserver address */
2394 {
2395 /* don't call timeserver more than once per second */
2396 static time_t time_old = 0;
2397 time_t time_new;
2398 static time_t time_saved = 0;
2399 (void) time (&time_new);
2400 if ((time_new == time_old) && (time_saved != 0))
2401 {
2402 time_now = time_saved;
2403 goto end;
2404 }
2405 time_old = time_new;
2406
2407
2408 fd = connect_port_2 (sh.srvtime.name, sh.srvtime.alt,
2409 IPPORT_TIMESERVER,
2410 error_call, &error_num, errmsg, sizeof(errmsg));
2411 if (fd >= 0)
2412 {
2413 if (4 != read_port (fd, (char *) net_time, 4, &errflag, 2))
2414 {
2415 fail = 1;
2416 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2417 MSG_E_NLOST,
2418 _("time"), sh.srvtime.name);
2419 }
2420 sl_close_fd(FIL__, __LINE__, fd);
2421 }
2422 else
2423 {
2424 sh_error_handle ((-1), FIL__, __LINE__, error_num,
2425 MSG_E_NET, errmsg, error_call,
2426 _("time"), sh.srvtime.name);
2427 fail = 1;
2428 }
2429
2430 if (fail == 0)
2431 {
2432 unsigned long ltmp;
2433 UINT32 ttmp;
2434 memcpy(&ttmp, net_time, sizeof(UINT32)); ltmp = ttmp;
2435 time_now = ntohl(ltmp) - UNIXEPOCH;
2436 time_saved = time_now;
2437
2438 if (failerr == 1) {
2439 failerr = 0;
2440 sh_error_handle ((-1), FIL__, __LINE__, 0,
2441 MSG_E_NEST,
2442 _("time"), sh.srvtime.name);
2443 }
2444 }
2445 else
2446 {
2447 (void) time (&time_now);
2448 time_saved = 0;
2449
2450 if (failerr == 0)
2451 {
2452 failerr = 1;
2453 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2454 MSG_SRV_FAIL,
2455 _("time"), sh.srvtime.name);
2456 }
2457 }
2458 end:
2459 ; /* 'label at end of compound statement' */
2460 }
2461 }
2462 else
2463 {
2464 time_now = thetime;
2465 }
2466
2467 /* #ifdef HAVE_NTIME */
2468#else
2469
2470 if (thetime == 0)
2471 {
2472 (void) time (&time_now);
2473 }
2474 else
2475 {
2476 time_now = thetime;
2477 }
2478
2479 /* #ifdef HAVE_NTIME */
2480#endif
2481
2482 if (time_now == (-1) )
2483 {
2484 sl_strlcpy(buffer, _(deftime), len);
2485 SL_RETURN(buffer, _("sh_unix_time"));
2486 }
2487 else
2488 {
2489#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2490 time_ptr = localtime_r (&time_now, &time_tm);
2491#else
2492 time_ptr = localtime (&time_now);
2493#endif
2494 }
2495 if (time_ptr != NULL)
2496 {
2497 status = strftime (AsciiTime, sizeof(AsciiTime),
2498#ifdef SH_USE_XML
2499 _("%Y-%m-%dT%H:%M:%S%%s"),
2500#else
2501 _("[%Y-%m-%dT%H:%M:%S%%s]"),
2502#endif
2503 time_ptr);
2504
2505 sl_snprintf(buffer, len, AsciiTime, t_zone(&time_now));
2506
2507 if ( (status == 0) || (status == sizeof(AsciiTime)) )
2508 {
2509 sl_strlcpy(buffer, _(deftime), len);
2510 SL_RETURN( buffer, _("sh_unix_time"));
2511 }
2512 else
2513 {
2514 SL_RETURN(buffer, _("sh_unix_time"));
2515 }
2516 }
2517
2518 /* last resort
2519 */
2520 sl_strlcpy(buffer, _(deftime), len);
2521 SL_RETURN( buffer, _("sh_unix_time"));
2522}
2523
2524static int sh_unix_use_localtime = S_FALSE;
2525
2526/* whether to use localtime for file timesatams in logs
2527 */
2528int sh_unix_uselocaltime (const char * c)
2529{
2530 int i;
2531 SL_ENTER(_("sh_unix_uselocaltime"));
2532 i = sh_util_flagval(c, &(sh_unix_use_localtime));
2533
2534 SL_RETURN(i, _("sh_unix_uselocaltime"));
2535}
2536
2537char * sh_unix_gmttime (time_t thetime, char * buffer, size_t len)
2538{
2539
2540 int status;
2541
2542 struct tm * time_ptr;
2543#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS)
2544 struct tm time_tm;
2545#endif
2546 char AsciiTime[81]; /* GMT time */
2547#ifdef SH_USE_XML
2548 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2549#else
2550 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2551#endif
2552
2553 SL_ENTER(_("sh_unix_gmttime"));
2554
2555 if (sh_unix_use_localtime == S_FALSE)
2556 {
2557#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2558 time_ptr = gmtime_r (&thetime, &time_tm);
2559#else
2560 time_ptr = gmtime (&thetime);
2561#endif
2562 }
2563 else
2564 {
2565#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2566 time_ptr = localtime_r (&thetime, &time_tm);
2567#else
2568 time_ptr = localtime (&thetime);
2569#endif
2570 }
2571 if (time_ptr != NULL)
2572 {
2573 status = strftime (AsciiTime, 80,
2574#ifdef SH_USE_XML
2575 _("%Y-%m-%dT%H:%M:%S"),
2576#else
2577 _("[%Y-%m-%dT%H:%M:%S]"),
2578#endif
2579 time_ptr);
2580
2581 if ( (status == 0) || (status == 80) )
2582 sl_strlcpy(buffer, _(deftime), len);
2583 else
2584 sl_strlcpy(buffer, AsciiTime, len);
2585 SL_RETURN( buffer, _("sh_unix_gmttime"));
2586 }
2587
2588 /* last resort
2589 */
2590 sl_strlcpy(buffer, _(deftime), len);
2591 SL_RETURN( buffer, _("sh_unix_gmttime"));
2592}
2593
2594
2595char * sh_unix_getUIDdir (int level, uid_t uid, char * out, size_t len)
2596{
2597 struct passwd * tempres;
2598 int status = 0;
2599
2600#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2601 struct passwd pwd;
2602 char * buffer;
2603#endif
2604 char errbuf[SH_ERRBUF_SIZE];
2605
2606 SL_ENTER(_("sh_unix_getUIDdir"));
2607
2608#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2609 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2610 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2611#else
2612 errno = 0;
2613 tempres = sh_getpwuid(uid);
2614 status = errno;
2615#endif
2616
2617 if (tempres == NULL) {
2618 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2619 sh_error_message(status, errbuf, sizeof(errbuf)),
2620 _("getpwuid"), (long) uid, _("completely missing"));
2621#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2622 SH_FREE(buffer);
2623#endif
2624 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2625 }
2626
2627 if (tempres->pw_dir != NULL) {
2628 sl_strlcpy(out, tempres->pw_dir, len);
2629#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2630 SH_FREE(buffer);
2631#endif
2632 SL_RETURN( out, _("sh_unix_getUIDdir"));
2633 } else {
2634 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2635 sh_error_message(status, errbuf, sizeof(errbuf)),
2636 _("getpwuid"), (long) uid, _("pw_dir"));
2637#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2638 SH_FREE(buffer);
2639#endif
2640 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2641 }
2642}
2643
2644/* ------------------- Caching ----------------*/
2645#include "zAVLTree.h"
2646
2647#define CACHE_GID 0
2648#define CACHE_UID 1
2649
2650struct user_id {
2651 char * name;
2652 uid_t id;
2653 struct user_id * next;
2654};
2655
2656static struct user_id * uid_list = NULL;
2657static struct user_id * gid_list = NULL;
2658
2659SH_MUTEX_STATIC(mutex_cache, PTHREAD_MUTEX_INITIALIZER);
2660
2661static void sh_userid_free(struct user_id * item)
2662{
2663 while (item)
2664 {
2665 struct user_id * user = item;
2666 item = item->next;
2667
2668 SH_FREE(user->name);
2669 SH_FREE(user);
2670 }
2671 return;
2672}
2673
2674void sh_userid_destroy ()
2675{
2676 struct user_id * tmp_uid;
2677 struct user_id * tmp_gid;
2678
2679 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2680 tmp_gid = gid_list;
2681 gid_list = NULL;
2682 tmp_uid = uid_list;
2683 uid_list = NULL;
2684 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2685
2686 sh_userid_free(tmp_uid);
2687 sh_userid_free(tmp_gid);
2688 return;
2689}
2690
2691static void sh_userid_additem(struct user_id * list, struct user_id * item)
2692{
2693 if (list)
2694 {
2695 while (list && list->next)
2696 list = list->next;
2697 list->next = item;
2698 }
2699 return;
2700}
2701
2702static void sh_userid_add(uid_t id, char * username, int which)
2703{
2704 size_t len;
2705 struct user_id * user = SH_ALLOC(sizeof(struct user_id));
2706
2707 if (username)
2708 len = strlen(username) + 1;
2709 else
2710 len = 1;
2711
2712 user->name = SH_ALLOC(len);
2713 user->id = id;
2714 if (username)
2715 sl_strlcpy(user->name, username, len);
2716 else
2717 user->name[0] = '\0';
2718 user->next = NULL;
2719
2720 SH_MUTEX_LOCK(mutex_cache);
2721 if (which == CACHE_UID)
2722 {
2723 if (!uid_list)
2724 uid_list = user;
2725 else
2726 sh_userid_additem(uid_list, user);
2727 }
2728 else
2729 {
2730 if (!gid_list)
2731 gid_list = user;
2732 else
2733 sh_userid_additem(gid_list, user);
2734 }
2735 SH_MUTEX_UNLOCK(mutex_cache);
2736
2737 return;
2738}
2739
2740static char * sh_userid_search(struct user_id * list, uid_t id)
2741{
2742 while (list)
2743 {
2744 if (list->id == id)
2745 return list->name;
2746 list = list->next;
2747 }
2748 return NULL;
2749}
2750
2751static char * sh_userid_get (uid_t id, int which, char * out, size_t len)
2752{
2753 char * user = NULL;
2754
2755 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2756 if (which == CACHE_UID)
2757 user = sh_userid_search(uid_list, id);
2758 else
2759 user = sh_userid_search(gid_list, id);
2760 if (user)
2761 {
2762 sl_strlcpy(out, user, len);
2763 user = out;
2764 }
2765 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2766
2767 return user;
2768}
2769
2770/* --------- end caching code --------- */
2771
2772char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len)
2773{
2774 struct passwd * tempres;
2775#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2776 struct passwd pwd;
2777 char * buffer;
2778#endif
2779 int status = 0;
2780 char errbuf[SH_ERRBUF_SIZE];
2781 char * tmp;
2782
2783 SL_ENTER(_("sh_unix_getUIDname"));
2784
2785 tmp = sh_userid_get(uid, CACHE_UID, out, len);
2786
2787 if (tmp)
2788 {
2789 if (tmp[0] != '\0')
2790 {
2791 SL_RETURN( out, _("sh_unix_getUIDname"));
2792 }
2793 else
2794 {
2795 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2796 }
2797 }
2798
2799#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2800 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2801 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2802#else
2803 errno = 0;
2804 tempres = sh_getpwuid(uid);
2805 status = errno;
2806#endif
2807
2808 if (tempres == NULL)
2809 {
2810 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2811 sh_error_message(status, errbuf, sizeof(errbuf)),
2812 _("getpwuid"), (long) uid, _("completely missing"));
2813#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2814 SH_FREE(buffer);
2815#endif
2816 sh_userid_add(uid, NULL, CACHE_UID);
2817 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2818 }
2819
2820
2821 if (tempres->pw_name != NULL)
2822 {
2823
2824 sl_strlcpy(out, tempres->pw_name, len);
2825 sh_userid_add(uid, out, CACHE_UID);
2826
2827#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2828 SH_FREE(buffer);
2829#endif
2830
2831 SL_RETURN( out, _("sh_unix_getUIDname"));
2832 }
2833 else
2834 {
2835 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2836 sh_error_message(status, errbuf, sizeof(errbuf)),
2837 _("getpwuid"), (long) uid, _("pw_user"));
2838#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2839 SH_FREE(buffer);
2840#endif
2841 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2842 }
2843 /* notreached */
2844}
2845
2846char * sh_unix_getGIDname (int level, gid_t gid, char * out, size_t len)
2847{
2848 struct group * tempres;
2849 int status = 0;
2850
2851#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2852 struct group grp;
2853 char * buffer;
2854#endif
2855 char errbuf[SH_ERRBUF_SIZE];
2856 char * tmp;
2857
2858 SL_ENTER(_("sh_unix_getGIDname"));
2859
2860 tmp = sh_userid_get((uid_t)gid, CACHE_GID, out, len);
2861
2862 if (tmp)
2863 {
2864 if (tmp[0] != '\0')
2865 {
2866 SL_RETURN( out, _("sh_unix_getGIDname"));
2867 }
2868 else
2869 {
2870 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2871 }
2872 }
2873
2874#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2875 buffer = SH_ALLOC(SH_GRBUF_SIZE);
2876 status = sh_getgrgid_r(gid, &grp, buffer, SH_GRBUF_SIZE, &tempres);
2877#else
2878 errno = 0;
2879 tempres = sh_getgrgid(gid);
2880 status = errno;
2881#endif
2882
2883 if (tempres == NULL)
2884 {
2885 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2886 sh_error_message(status, errbuf, sizeof(errbuf)),
2887 _("getgrgid"), (long) gid, _("completely missing"));
2888
2889#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2890 SH_FREE(buffer);
2891#endif
2892
2893 sh_userid_add(gid, NULL, CACHE_GID);
2894 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2895 }
2896
2897 if (tempres->gr_name != NULL)
2898 {
2899
2900 sl_strlcpy(out, tempres->gr_name, len);
2901 sh_userid_add((uid_t)gid, out, CACHE_GID);
2902
2903#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2904 SH_FREE(buffer);
2905#endif
2906
2907 SL_RETURN( out, _("sh_unix_getGIDname"));
2908 }
2909 else
2910 {
2911 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2912 sh_error_message(status, errbuf, sizeof(errbuf)),
2913 _("getgrgid"), (long) gid, _("gr_name"));
2914
2915#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2916 SH_FREE(buffer);
2917#endif
2918
2919 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2920 }
2921 /* notreached */
2922}
2923
2924int sh_unix_getUser ()
2925{
2926 char * p;
2927 uid_t seuid, sruid;
2928 char user[USER_MAX];
2929 char dir[SH_PATHBUF];
2930
2931 SL_ENTER(_("sh_unix_getUser"));
2932
2933 seuid = geteuid();
2934
2935 sh.effective.uid = seuid;
2936
2937 p = sh_unix_getUIDdir (SH_ERR_ERR, seuid, dir, sizeof(dir));
2938
2939 if (p == NULL)
2940 SL_RETURN((-1), _("sh_unix_getUser"));
2941 else
2942 {
2943 if (sl_strlen(p) >= SH_PATHBUF) {
2944 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2945 _("getpwuid"), (long) seuid, _("pw_home"));
2946 SL_RETURN((-1), _("sh_unix_getUser"));
2947 } else {
2948 sl_strlcpy ( sh.effective.home, p, SH_PATHBUF);
2949 }
2950 }
2951
2952 sruid = getuid();
2953
2954 sh.real.uid = sruid;
2955
2956 p = sh_unix_getUIDname (SH_ERR_ERR, sruid, user, sizeof(user));
2957 if (p == NULL)
2958 SL_RETURN((-1), _("sh_unix_getUser"));
2959 else
2960 {
2961 if (sl_strlen(p) >= USER_MAX) {
2962 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2963 _("getpwuid"), (long) sruid, _("pw_user"));
2964 SL_RETURN((-1), _("sh_unix_getUser"));
2965 } else {
2966 sl_strlcpy ( sh.real.user, p, USER_MAX);
2967 }
2968 }
2969
2970 p = sh_unix_getUIDdir (SH_ERR_ERR, sruid, dir, sizeof(dir));
2971
2972 if (p == NULL)
2973 SL_RETURN((-1), _("sh_unix_getUser"));
2974 else
2975 {
2976 if (sl_strlen(p) >= SH_PATHBUF) {
2977 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2978 _("getpwuid"), (long) sruid, _("pw_home"));
2979 SL_RETURN((-1), _("sh_unix_getUser"));
2980 } else {
2981 sl_strlcpy ( sh.real.home, p, SH_PATHBUF);
2982 }
2983 }
2984
2985 SL_RETURN((0), _("sh_unix_getUser"));
2986
2987 /* notreached */
2988}
2989
2990
2991int sh_unix_getline (SL_TICKET fd, char * line, int sizeofline)
2992{
2993 register int count;
2994 register int n = 0;
2995 char c;
2996
2997 SL_ENTER(_("sh_unix_getline"));
2998
2999 if (sizeofline < 2) {
3000 line[0] = '\0';
3001 SL_RETURN((0), _("sh_unix_getline"));
3002 }
3003
3004 --sizeofline;
3005
3006 while (n < sizeofline) {
3007
3008 count = sl_read (fd, &c, 1);
3009
3010 /* end of file
3011 */
3012 if (count < 1) {
3013 line[n] = '\0';
3014 n = -1;
3015 break;
3016 }
3017
3018 if (/* c != '\0' && */ c != '\n') {
3019 line[n] = c;
3020 ++n;
3021 } else if (c == '\n') {
3022 if (n > 0) {
3023 line[n] = '\0';
3024 break;
3025 } else {
3026 line[n] = '\n'; /* get newline only if only char on line */
3027 ++n;
3028 line[n] = '\0';
3029 break;
3030 }
3031 } else {
3032 line[n] = '\0';
3033 break;
3034 }
3035
3036 }
3037
3038
3039 line[sizeofline] = '\0'; /* make sure line is terminated */
3040 SL_RETURN((n), _("sh_unix_getline"));
3041}
3042
3043
3044#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
3045
3046/**************************************************************
3047 *
3048 * --- FILE INFO ---
3049 *
3050 **************************************************************/
3051
3052#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
3053
3054#if defined(__linux__)
3055
3056/* --- Determine ext2fs file attributes. ---
3057 */
3058#include <sys/ioctl.h>
3059#if defined(HAVE_EXT2FS_EXT2_FS_H)
3060#include <ext2fs/ext2_fs.h>
3061#else
3062#include <linux/ext2_fs.h>
3063#endif
3064
3065/* __linux__ includes */
3066#endif
3067
3068static
3069int sh_unix_getinfo_attr (char * name,
3070 unsigned long * flags,
3071 char * c_attr,
3072 int fd, struct stat * buf)
3073{
3074
3075/* TAKEN FROM:
3076 *
3077 * lsattr.c - List file attributes on an ext2 file system
3078 *
3079 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
3080 * Laboratoire MASI, Institut Blaise Pascal
3081 * Universite Pierre et Marie Curie (Paris VI)
3082 *
3083 * This file can be redistributed under the terms of the GNU General
3084 * Public License
3085 */
3086
3087#ifdef HAVE_STAT_FLAGS
3088
3089 SL_ENTER(_("sh_unix_getinfo_attr"));
3090
3091 *flags = 0;
3092
3093 /* cast to void to avoid compiler warning about unused parameters */
3094 (void) fd;
3095 (void) name;
3096
3097#ifdef UF_NODUMP
3098 if (buf->st_flags & UF_NODUMP) {
3099 *flags |= UF_NODUMP;
3100 c_attr[0] = 'd';
3101 }
3102#endif
3103#ifdef UF_IMMUTABLE
3104 if (buf->st_flags & UF_IMMUTABLE) {
3105 *flags |= UF_IMMUTABLE;
3106 c_attr[1] = 'i';
3107 }
3108#endif
3109#ifdef UF_APPEND
3110 if (buf->st_flags & UF_APPEND) {
3111 *flags |= UF_APPEND;
3112 c_attr[2] = 'a';
3113 }
3114#endif
3115#ifdef UF_NOUNLINK
3116 if (buf->st_flags & UF_NOUNLINK) {
3117 *flags |= UF_NOUNLINK;
3118 c_attr[3] = 'u';
3119 }
3120#endif
3121#ifdef UF_OPAQUE
3122 if (buf->st_flags & UF_OPAQUE) {
3123 *flags |= UF_OPAQUE;
3124 c_attr[4] = 'o';
3125 }
3126#endif
3127#ifdef SF_ARCHIVED
3128 if (buf->st_flags & SF_ARCHIVED) {
3129 *flags |= SF_ARCHIVED;
3130 c_attr[5] = 'R';
3131 }
3132
3133#endif
3134#ifdef SF_IMMUTABLE
3135 if (buf->st_flags & SF_IMMUTABLE) {
3136 *flags |= SF_IMMUTABLE;
3137 c_attr[6] = 'I';
3138 }
3139#endif
3140#ifdef SF_APPEND
3141 if (buf->st_flags & SF_APPEND) {
3142 *flags |= SF_APPEND;
3143 c_attr[7] = 'A';
3144 }
3145#endif
3146#ifdef SF_NOUNLINK
3147 if (buf->st_flags & SF_NOUNLINK) {
3148 *flags |= SF_NOUNLINK;
3149 c_attr[8] = 'U';
3150 }
3151#endif
3152
3153 /* ! HAVE_STAT_FLAGS */
3154#else
3155
3156#ifdef HAVE_EXT2_IOCTLS
3157 int /* fd, */ r, f;
3158
3159 SL_ENTER(_("sh_unix_getinfo_attr"));
3160
3161 *flags = 0;
3162 (void) buf;
3163
3164 /* open() -> aud_open() R.Wichmann
3165 fd = aud_open (FIL__, __LINE__, SL_YESPRIV, name, O_RDONLY|O_NONBLOCK, 0);
3166 */
3167
3168 if (fd == -1 || name == NULL)
3169 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3170
3171
3172 r = ioctl (fd, EXT2_IOC_GETFLAGS, &f);
3173 /* sl_close_fd (FIL__, __LINE__, fd); */
3174
3175 if (r == -1)
3176 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3177
3178 if (f == 0)
3179 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3180
3181 *flags = f;
3182
3183/* ! HAVE_EXT2_IOCTLS */
3184#else
3185
3186 SL_ENTER(_("sh_unix_getinfo_attr"));
3187
3188 *flags = 0; /* modified by R.Wichmann */
3189
3190/* ! HAVE_EXT2_IOCTLS */
3191#endif
3192/*
3193 * END
3194 *
3195 * lsattr.c - List file attributes on an ext2 file system
3196 */
3197
3198 if (*flags == 0)
3199 goto theend;
3200
3201#ifdef EXT2_SECRM_FL
3202 if ( (*flags & EXT2_SECRM_FL) != 0 ) c_attr[0] = 's';
3203#endif
3204#ifdef EXT2_UNRM_FL
3205 if ( (*flags & EXT2_UNRM_FL) != 0 ) c_attr[1] = 'u';
3206#endif
3207#ifdef EXT2_SYNC_FL
3208 if ( (*flags & EXT2_SYNC_FL) != 0 ) c_attr[2] = 'S';
3209#endif
3210#ifdef EXT2_IMMUTABLE_FL
3211 if ( (*flags & EXT2_IMMUTABLE_FL) != 0) c_attr[3] = 'i';
3212#endif
3213#ifdef EXT2_APPEND_FL
3214 if ( (*flags & EXT2_APPEND_FL) != 0 ) c_attr[4] = 'a';
3215#endif
3216#ifdef EXT2_NODUMP_FL
3217 if ( (*flags & EXT2_NODUMP_FL) != 0 ) c_attr[5] = 'd';
3218#endif
3219#ifdef EXT2_NOATIME_FL
3220 if ( (*flags & EXT2_NOATIME_FL) != 0) c_attr[6] = 'A';
3221#endif
3222#ifdef EXT2_COMPR_FL
3223 if ( (*flags & EXT2_COMPR_FL) != 0 ) c_attr[7] = 'c';
3224#endif
3225
3226#ifdef EXT2_TOPDIR_FL
3227 if ( (*flags & EXT2_TOPDIR_FL) != 0 ) c_attr[8] = 'T';
3228#endif
3229#ifdef EXT2_DIRSYNC_FL
3230 if ( (*flags & EXT2_DIRSYNC_FL) != 0 ) c_attr[9] = 'D';
3231#endif
3232#ifdef EXT2_NOTAIL_FL
3233 if ( (*flags & EXT2_NOTAIL_FL) != 0 ) c_attr[10] = 't';
3234#endif
3235#ifdef EXT2_JOURNAL_DATA_FL
3236 if ( (*flags & EXT2_JOURNAL_DATA_FL) != 0) c_attr[11] = 'j';
3237#endif
3238
3239 theend:
3240 /* ext2 */
3241#endif
3242
3243 c_attr[12] = '\0';
3244
3245 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3246}
3247
3248/* defined(__linux__) || defined(HAVE_STAT_FLAGS) */
3249#endif
3250
3251/* determine file type
3252 */
3253static
3254int sh_unix_getinfo_type (struct stat * buf,
3255 ShFileType * type,
3256 char * c_mode)
3257{
3258 SL_ENTER(_("sh_unix_getinfo_type"));
3259
3260 if ( S_ISREG(buf->st_mode) ) {
3261 (*type) = SH_FILE_REGULAR;
3262 c_mode[0] = '-';
3263 }
3264 else if ( S_ISLNK(buf->st_mode) ) {
3265 (*type) = SH_FILE_SYMLINK;
3266 c_mode[0] = 'l';
3267 }
3268 else if ( S_ISDIR(buf->st_mode) ) {
3269 (*type) = SH_FILE_DIRECTORY;
3270 c_mode[0] = 'd';
3271 }
3272 else if ( S_ISCHR(buf->st_mode) ) {
3273 (*type) = SH_FILE_CDEV;
3274 c_mode[0] = 'c';
3275 }
3276 else if ( S_ISBLK(buf->st_mode) ) {
3277 (*type) = SH_FILE_BDEV;
3278 c_mode[0] = 'b';
3279 }
3280 else if ( S_ISFIFO(buf->st_mode) ) {
3281 (*type) = SH_FILE_FIFO;
3282 c_mode[0] = '|';
3283 }
3284 else if ( S_ISSOCK(buf->st_mode) ) {
3285 (*type) = SH_FILE_SOCKET;
3286 c_mode[0] = 's';
3287 }
3288 else if ( S_ISDOOR(buf->st_mode) ) {
3289 (*type) = SH_FILE_DOOR;
3290 c_mode[0] = 'D';
3291 }
3292 else if ( S_ISPORT(buf->st_mode) ) {
3293 (*type) = SH_FILE_PORT;
3294 c_mode[0] = 'P';
3295 }
3296 else {
3297 (*type) = SH_FILE_UNKNOWN;
3298 c_mode[0] = '?';
3299 }
3300
3301 SL_RETURN(0, _("sh_unix_getinfo_type"));
3302}
3303
3304int sh_unix_get_ftype(char * fullpath)
3305{
3306 char c_mode[CMODE_SIZE];
3307 struct stat buf;
3308 ShFileType type;
3309 int res;
3310
3311 SL_ENTER(_("sh_unix_get_ftype"));
3312
3313 res = retry_lstat(FIL__, __LINE__, fullpath, &buf);
3314
3315 if (res < 0)
3316 SL_RETURN(SH_FILE_UNKNOWN, _("sh_unix_getinfo_type"));
3317
3318 sh_unix_getinfo_type (&buf, &type, c_mode);
3319
3320 SL_RETURN(type, _("sh_unix_get_ftype"));
3321}
3322
3323
3324static
3325int sh_unix_getinfo_mode (struct stat *buf,
3326 unsigned int * mode,
3327 char * c_mode)
3328{
3329
3330 SL_ENTER(_("sh_unix_getinfo_mode"));
3331
3332 (*mode) = buf->st_mode;
3333
3334 /* make 'ls'-like string */
3335
3336 if ( (buf->st_mode & S_IRUSR) != 0 ) c_mode[1] = 'r';
3337 if ( (buf->st_mode & S_IWUSR) != 0 ) c_mode[2] = 'w';
3338 if ( (buf->st_mode & S_IXUSR) != 0 ) {
3339 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 's';
3340 else c_mode[3] = 'x';
3341 } else {
3342 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 'S';
3343 }
3344
3345 if ( (buf->st_mode & S_IRGRP) != 0 ) c_mode[4] = 'r';
3346 if ( (buf->st_mode & S_IWGRP) != 0 ) c_mode[5] = 'w';
3347 if ( (buf->st_mode & S_IXGRP) != 0 ) {
3348 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 's';
3349 else c_mode[6] = 'x';
3350 } else {
3351 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 'S';
3352 }
3353
3354 if ( (buf->st_mode & S_IROTH) != 0 ) c_mode[7] = 'r';
3355 if ( (buf->st_mode & S_IWOTH) != 0 ) c_mode[8] = 'w';
3356#ifdef S_ISVTX /* not POSIX */
3357 if ( (buf->st_mode & S_IXOTH) != 0 ) {
3358 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 't';
3359 else c_mode[9] = 'x';
3360 } else {
3361 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 'T';
3362 }
3363#else
3364 if ( (buf->st_mode & S_IXOTH) != 0 ) c_mode[9] = 'x';
3365#endif
3366
3367 SL_RETURN(0, _("sh_unix_getinfo_mode"));
3368}
3369
3370
3371long IO_Limit = 0;
3372
3373void sh_unix_io_pause ()
3374{
3375 long runtime;
3376 float someval;
3377 unsigned long sometime;
3378
3379 if (IO_Limit == 0)
3380 {
3381 return;
3382 }
3383 else
3384 {
3385 runtime = (long) (time(NULL) - sh.statistics.time_start);
3386
3387 if (runtime > 0 && (long)(sh.statistics.bytes_hashed/runtime) > IO_Limit)
3388 {
3389 someval = sh.statistics.bytes_hashed - (IO_Limit * runtime);
3390 someval /= (float) IO_Limit;
3391 if (someval < 1.0)
3392 {
3393 someval *= 1000; /* milliseconds in a second */
3394 sometime = (unsigned long) someval;
3395 retry_msleep(0, sometime);
3396 }
3397 else
3398 {
3399 sometime = (unsigned long) someval;
3400 retry_msleep (sometime, 0);
3401 }
3402 }
3403 }
3404 return;
3405}
3406
3407int sh_unix_set_io_limit (const char * c)
3408{
3409 long val;
3410
3411 SL_ENTER(_("sh_unix_set_io_limit"));
3412
3413 val = strtol (c, (char **)NULL, 10);
3414 if (val < 0)
3415 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
3416 _("set I/O limit"), c);
3417
3418 val = (val < 0 ? 0 : val);
3419
3420 IO_Limit = val * 1024;
3421 SL_RETURN( 0, _("sh_unix_set_io_limit"));
3422}
3423
3424/* obtain file info
3425 */
3426extern int flag_err_debug;
3427
3428#include "sh_ignore.h"
3429
3430int sh_unix_checksum_size (char * filename, struct stat * fbuf,
3431 char * fileHash, int alert_timeout, SL_TICKET fd)
3432{
3433 file_type * tmpFile;
3434 int status;
3435
3436 SL_ENTER(_("sh_unix_checksum_size"));
3437
3438 tmpFile = SH_ALLOC(sizeof(file_type));
3439 tmpFile->link_path = NULL;
3440
3441 if (sh.flag.checkSum != SH_CHECK_INIT)
3442 {
3443 /* lookup file in database */
3444 status = sh_hash_get_it (filename, tmpFile, NULL);
3445 if (status != 0) {
3446 goto out;
3447 }
3448 }
3449 else
3450 {
3451 tmpFile->size = fbuf->st_size;
3452 }
3453
3454 /* if last < current get checksum */
3455 if (tmpFile->size < fbuf->st_size)
3456 {
3457 char hashbuf[KEYBUF_SIZE];
3458 UINT64 local_length = (UINT64) (tmpFile->size < 0 ? 0 : tmpFile->size);
3459 sl_strlcpy(fileHash,
3460 sh_tiger_generic_hash (filename, fd, &(local_length),
3461 alert_timeout, hashbuf, sizeof(hashbuf)),
3462 KEY_LEN+1);
3463
3464 /* return */
3465 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3466 SH_FREE(tmpFile);
3467 SL_RETURN( 0, _("sh_unix_checksum_size"));
3468 }
3469
3470 out:
3471 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3472 SH_FREE(tmpFile);
3473 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3474 SL_RETURN( -1, _("sh_unix_checksum_size"));
3475}
3476
3477int sh_unix_check_selinux = S_FALSE;
3478int sh_unix_check_acl = S_FALSE;
3479
3480#ifdef USE_ACL
3481
3482#include <sys/acl.h>
3483static char * sh_unix_getinfo_acl (char * path, int fd, struct stat * buf)
3484{
3485 /* system.posix_acl_access, system.posix_acl_default
3486 */
3487 char * out = NULL;
3488 char * collect = NULL;
3489 char * tmp;
3490 char * out_compact;
3491 ssize_t len;
3492 acl_t result;
3493
3494 SL_ENTER(_("sh_unix_getinfo_acl"));
3495
3496 result = (fd == -1) ?
3497 acl_get_file (path, ACL_TYPE_ACCESS) :
3498 acl_get_fd (fd);
3499
3500 if (result)
3501 {
3502 out = acl_to_text (result, &len);
3503 if (out && (len > 0)) {
3504 out_compact = sh_util_acl_compact (out, len);
3505 acl_free(out);
3506 if (out_compact)
3507 {
3508 collect = sh_util_strconcat (_("acl_access:"), out_compact, NULL);
3509 SH_FREE(out_compact);
3510 }
3511 }
3512 acl_free(result);
3513 }
3514
3515
3516 if ( S_ISDIR(buf->st_mode) )
3517 {
3518 result = acl_get_file (path, ACL_TYPE_DEFAULT);
3519
3520 if (result)
3521 {
3522 out = acl_to_text (result, &len);
3523 if (out && (len > 0)) {
3524 out_compact = sh_util_acl_compact (out, len);
3525 acl_free(out);
3526 if (out_compact) {
3527 if (collect) {
3528 tmp = sh_util_strconcat (_("acl_default:"),
3529 out_compact, ":", collect, NULL);
3530 SH_FREE(collect);
3531 }
3532 else {
3533 tmp = sh_util_strconcat (_("acl_default:"), out_compact, NULL);
3534 }
3535 SH_FREE(out_compact);
3536 collect = tmp;
3537 }
3538 }
3539 acl_free(result);
3540 }
3541 }
3542
3543 SL_RETURN((collect),_("sh_unix_getinfo_acl"));
3544}
3545#endif
3546
3547#ifdef USE_XATTR
3548
3549#include <attr/xattr.h>
3550static char * sh_unix_getinfo_xattr_int (char * path, int fd, char * name)
3551{
3552 char * out = NULL;
3553 char * tmp = NULL;
3554 size_t size = 256;
3555 ssize_t result;
3556
3557 SL_ENTER(_("sh_unix_getinfo_xattr_int"));
3558
3559 out = SH_ALLOC(size);
3560
3561 result = (fd == -1) ?
3562 lgetxattr (path, name, out, size-1) :
3563 fgetxattr (fd, name, out, size-1);
3564
3565 if (result == -1 && errno == ERANGE)
3566 {
3567 SH_FREE(out);
3568 result = (fd == -1) ?
3569 lgetxattr (path, name, NULL, 0) :
3570 fgetxattr (fd, name, NULL, 0);
3571 size = result + 1;
3572 out = SH_ALLOC(size);
3573 result = (fd == -1) ?
3574 lgetxattr (path, name, out, size-1) :
3575 fgetxattr (fd, name, out, size-1);
3576 }
3577
3578 if ((result > 0) && ((size_t)result < size))
3579 {
3580 out[size-1] = '\0';
3581 tmp = out;
3582 }
3583 else
3584 {
3585 SH_FREE(out);
3586 }
3587
3588 SL_RETURN((tmp),_("sh_unix_getinfo_xattr_int"));
3589}
3590
3591
3592static char * sh_unix_getinfo_xattr (char * path, int fd, struct stat * buf)
3593{
3594 /* system.posix_acl_access, system.posix_acl_default, security.selinux
3595 */
3596 char * tmp;
3597 char * out = NULL;
3598 char * collect = NULL;
3599
3600 SL_ENTER(_("sh_unix_getinfo_xattr"));
3601
3602#ifdef USE_ACL
3603 /*
3604 * we need the acl_get_fd/acl_get_file functions, getxattr will only
3605 * yield the raw bytes
3606 */
3607 if (sh_unix_check_acl == S_TRUE)
3608 {
3609 out = sh_unix_getinfo_acl(path, fd, buf);
3610
3611 if (out)
3612 {
3613 collect = out;
3614 }
3615 }
3616#else
3617 (void) buf;
3618#endif
3619
3620 if (sh_unix_check_selinux == S_TRUE)
3621 {
3622 out = sh_unix_getinfo_xattr_int(path, fd, _("security.selinux"));
3623
3624 if (out)
3625 {
3626 if (collect) {
3627 tmp = sh_util_strconcat(_("selinux:"), out, ":", collect, NULL);
3628 SH_FREE(collect);
3629 }
3630 else {
3631 tmp = sh_util_strconcat(_("selinux:"), out, NULL);
3632 }
3633 SH_FREE(out);
3634 collect = tmp;
3635 }
3636 }
3637
3638 SL_RETURN((collect),_("sh_unix_getinfo_xattr"));
3639}
3640#endif
3641
3642#ifdef USE_XATTR
3643int sh_unix_setcheckselinux (const char * c)
3644{
3645 int i;
3646 SL_ENTER(_("sh_unix_setcheckselinux"));
3647 i = sh_util_flagval(c, &(sh_unix_check_selinux));
3648
3649 SL_RETURN(i, _("sh_unix_setcheckselinux"));
3650}
3651#endif
3652
3653#ifdef USE_ACL
3654int sh_unix_setcheckacl (const char * c)
3655{
3656 int i;
3657 SL_ENTER(_("sh_unix_setcheckacl"));
3658 i = sh_util_flagval(c, &(sh_unix_check_acl));
3659
3660 SL_RETURN(i, _("sh_unix_setcheckacl"));
3661}
3662#endif
3663
3664#ifdef HAVE_LIBZ
3665#include <zlib.h>
3666#endif
3667
3668
3669static void * sh_dummy_filename;
3670static void * sh_dummy_tmp;
3671static void * sh_dummy_tmp2;
3672
3673int sh_unix_getinfo (int level, const char * filename, file_type * theFile,
3674 char * fileHash, int policy)
3675{
3676 char timestr[81];
3677 long runtim;
3678 struct stat buf;
3679 struct stat lbuf;
3680 struct stat fbuf;
3681 volatile int stat_return;
3682 volatile int stat_errno = 0;
3683
3684 ShFileType type;
3685 unsigned int mode;
3686 char * tmp;
3687 char * tmp2;
3688
3689 char * linknamebuf;
3690 volatile int linksize;
3691
3692 extern int get_the_fd (SL_TICKET ticket);
3693
3694 volatile SL_TICKET rval_open;
3695 volatile int err_open = 0;
3696
3697 volatile int fd;
3698 volatile int fstat_return;
3699 volatile int fstat_errno = 0;
3700 volatile int try = 0;
3701
3702 sh_string * content = NULL;
3703
3704 time_t tend;
3705 time_t tstart;
3706
3707
3708 char * path = NULL;
3709
3710 volatile int alert_timeout = 120;
3711
3712 path = theFile->fullpath;
3713
3714 SL_ENTER(_("sh_unix_getinfo"));
3715
3716 if (!MODI_INITIALIZED(theFile->check_mask))
3717 {
3718 tmp2 = sh_util_safe_name (theFile->fullpath);
3719 SH_MUTEX_LOCK(mutex_thread_nolog);
3720 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_E_SUBGPATH,
3721 _("Uninitialized check mask"), _("sh_unix_getinfo"),
3722 tmp2);
3723 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3724 SH_FREE(tmp2);
3725 }
3726
3727 /* Take the address to keep gcc from putting it into a register.
3728 * Avoids the 'clobbered by longjmp' warning.
3729 */
3730 sh_dummy_filename = (void *) &filename;
3731 sh_dummy_tmp = (void *) &tmp;
3732 sh_dummy_tmp2 = (void *) &tmp2;
3733
3734 /* --- Stat the file, and get checksum. ---
3735 */
3736 tstart = time(NULL);
3737
3738 stat_return = retry_lstat (FIL__, __LINE__,
3739 path /* theFile->fullpath */, &buf);
3740
3741 if (stat_return)
3742 stat_errno = errno;
3743
3744 theFile->link_path = NULL;
3745
3746 try_again:
3747
3748 fd = -1;
3749 fstat_return = -1;
3750 rval_open = -1;
3751
3752 if (stat_return == 0 && S_ISREG(buf.st_mode))
3753 {
3754 rval_open = sl_open_fastread (FIL__, __LINE__,
3755 path /* theFile->fullpath */, SL_YESPRIV);
3756 if (SL_ISERROR(rval_open))
3757 {
3758 char * stale = sl_check_stale();
3759
3760 if (stale)
3761 {
3762 SH_MUTEX_LOCK(mutex_thread_nolog);
3763 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, err_open, MSG_E_SUBGEN,
3764 stale, _("sh_unix_getinfo_open"));
3765 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3766 }
3767
3768 if (errno == EBADF && try == 0) /* obsolete, but we keep this, just in case */
3769 {
3770 ++try;
3771 goto try_again;
3772 }
3773 err_open = errno;
3774 }
3775
3776 alert_timeout = 120; /* this is per 8K block now ! */
3777
3778 if (path[1] == 'p' && path[5] == '/' && path[2] == 'r' &&
3779 path[3] == 'o' && path[4] == 'c' && path[0] == '/')
3780 {
3781 /* seven is magic */
3782 alert_timeout = 7;
3783 }
3784
3785 fd = get_the_fd(rval_open);
3786 }
3787
3788 tend = time(NULL);
3789
3790 /* An unprivileged user may slow lstat/open to a crawl
3791 * with clever path/symlink setup
3792 */
3793 if ((tend - tstart) > (time_t) /* 60 */ 6)
3794 {
3795 tmp2 = sh_util_safe_name (theFile->fullpath);
3796 SH_MUTEX_LOCK(mutex_thread_nolog);
3797 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_TOOLATE,
3798 (long)(tend - tstart), tmp2);
3799 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3800 SH_FREE(tmp2);
3801 }
3802
3803 if (fd >= 0)
3804 {
3805 fstat_return = retry_fstat (FIL__, __LINE__, fd, &fbuf);
3806
3807 if (fstat_return)
3808 {
3809 char * stale;
3810
3811 fstat_errno = errno;
3812
3813 stale = sl_check_stale();
3814
3815 if (stale)
3816 {
3817 SH_MUTEX_LOCK(mutex_thread_nolog);
3818 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, fstat_errno,
3819 MSG_E_SUBGEN,
3820 stale, _("sh_unix_getinfo_fstat"));
3821 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3822 }
3823
3824 if (try == 0) /* obsolete, but we keep this, just in case */
3825 {
3826 ++try;
3827 sl_close(rval_open);
3828 goto try_again;
3829 }
3830 }
3831 }
3832 else
3833 {
3834 fd = -1;
3835 }
3836
3837
3838 /* --- case 1: lstat failed ---
3839 */
3840 if (stat_return != 0)
3841 {
3842 stat_return = errno;
3843 if (!SL_ISERROR(rval_open))
3844 sl_close(rval_open);
3845 if (sh.flag.checkSum == SH_CHECK_INIT ||
3846 (sh_hash_have_it (theFile->fullpath) >= 0 &&
3847 (!SH_FFLAG_REPORTED_SET(theFile->file_reported))))
3848 {
3849 if (S_FALSE == sh_ignore_chk_del(theFile->fullpath)) {
3850 char errbuf[SH_ERRBUF_SIZE];
3851 uid_t euid;
3852 (void) sl_get_euid(&euid);
3853 tmp2 = sh_util_safe_name (theFile->fullpath);
3854 SH_MUTEX_LOCK(mutex_thread_nolog);
3855 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3856 _("lstat"),
3857 sh_error_message (stat_errno, errbuf, sizeof(errbuf)),
3858 (long) euid,
3859 tmp2);
3860 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3861 SH_FREE(tmp2);
3862 }
3863 }
3864 SL_RETURN((-1),_("sh_unix_getinfo"));
3865 }
3866
3867 /* --- case 2: not a regular file ---
3868 */
3869 else if (! S_ISREG(buf.st_mode))
3870 {
3871 if (fileHash != NULL)
3872 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3873 }
3874
3875 /* --- case 3a: a regular file, fstat ok ---
3876 */
3877 else if (fstat_return == 0 &&
3878 buf.st_mode == fbuf.st_mode &&
3879 buf.st_ino == fbuf.st_ino &&
3880 buf.st_uid == fbuf.st_uid &&
3881 buf.st_gid == fbuf.st_gid &&
3882 buf.st_dev == fbuf.st_dev )
3883 {
3884 if (fileHash != NULL)
3885 {
3886 if ((theFile->check_mask & MODI_CHK) == 0 ||
3887 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3888 (UINT64) fbuf.st_mode, rval_open))
3889 {
3890 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3891 }
3892 else if ((theFile->check_mask & MODI_PREL) != 0 &&
3893 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3894 alert_timeout, theFile->fullpath))
3895 {
3896 if (0 != sh_prelink_run (theFile->fullpath,
3897 fileHash, alert_timeout))
3898 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3899 }
3900 else
3901 {
3902 char hashbuf[KEYBUF_SIZE];
3903 UINT64 length_nolim = TIGER_NOLIM;
3904
3905 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3906 {
3907 sl_init_content (rval_open, fbuf.st_size);
3908 }
3909
3910 sl_strlcpy(fileHash,
3911 sh_tiger_generic_hash (theFile->fullpath,
3912 rval_open, &length_nolim,
3913 alert_timeout,
3914 hashbuf, sizeof(hashbuf)),
3915 KEY_LEN+1);
3916
3917 content = sl_get_content(rval_open);
3918 content = sh_string_copy(content);
3919
3920 if ((theFile->check_mask & MODI_SGROW) != 0)
3921 {
3922 fbuf.st_size = (off_t) length_nolim;
3923 buf.st_size = fbuf.st_size;
3924 sl_rewind(rval_open);
3925 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3926 &fileHash[KEY_LEN + 1],
3927 alert_timeout, rval_open);
3928 }
3929 }
3930 }
3931 }
3932
3933 /* --- case 3b: a regular file, fstat ok, but different ---
3934 */
3935 else if (fstat_return == 0 && S_ISREG(fbuf.st_mode))
3936 {
3937 memcpy (&buf, &fbuf, sizeof( struct stat ));
3938
3939 if (fileHash != NULL)
3940 {
3941 if ((theFile->check_mask & MODI_CHK) == 0 ||
3942 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3943 (UINT64) fbuf.st_mode, rval_open))
3944 {
3945 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3946 }
3947 else if (policy == SH_LEVEL_PRELINK &&
3948 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3949 alert_timeout, theFile->fullpath))
3950 {
3951 if (0 != sh_prelink_run (theFile->fullpath,
3952 fileHash, alert_timeout))
3953 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3954 }
3955 else
3956 {
3957 char hashbuf[KEYBUF_SIZE];
3958 UINT64 length_nolim = TIGER_NOLIM;
3959
3960 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3961 {
3962 sl_init_content (rval_open, fbuf.st_size);
3963 }
3964
3965 sl_strlcpy(fileHash,
3966 sh_tiger_generic_hash (theFile->fullpath, rval_open,
3967 &length_nolim,
3968 alert_timeout,
3969 hashbuf, sizeof(hashbuf)),
3970 KEY_LEN + 1);
3971
3972 content = sl_get_content(rval_open);
3973 content = sh_string_copy(content);
3974
3975 if ((theFile->check_mask & MODI_SGROW) != 0)
3976 {
3977 fbuf.st_size = (off_t) length_nolim;
3978 buf.st_size = fbuf.st_size;
3979 sl_rewind(rval_open);
3980 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3981 &fileHash[KEY_LEN + 1],
3982 alert_timeout, rval_open);
3983 }
3984 }
3985 }
3986 }
3987
3988 /* --- case 4: a regular file, fstat failed ---
3989 */
3990
3991 else /* fstat_return != 0 or !S_ISREG(fbuf.st_mode) or open() failed */
3992 {
3993 uid_t euid;
3994
3995 if (fileHash != NULL)
3996 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3997
3998 if ((theFile->check_mask & MODI_CHK) != 0)
3999 {
4000 tmp2 = sh_util_safe_name (theFile->fullpath);
4001
4002
4003 if (fd >= 0 && fstat_return != 0)
4004 {
4005 char errbuf[SH_ERRBUF_SIZE];
4006 (void) sl_get_euid(&euid);
4007
4008 SH_MUTEX_LOCK(mutex_thread_nolog);
4009 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
4010 _("fstat"),
4011 sh_error_message (fstat_errno, errbuf, sizeof(errbuf)),
4012 (long) euid,
4013 tmp2);
4014 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4015 }
4016 else if (fd >= 0 && !S_ISREG(fbuf.st_mode))
4017 {
4018 SH_MUTEX_LOCK(mutex_thread_nolog);
4019 sh_error_handle (level, FIL__, __LINE__, fstat_errno,
4020 MSG_E_NOTREG, tmp2);
4021 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4022 }
4023 else
4024 {
4025 char errbuf[SH_ERRBUF_SIZE];
4026 char errbuf2[SH_ERRBUF_SIZE];
4027 sl_strlcpy(errbuf, sl_error_string(rval_open), sizeof(errbuf));
4028 sh_error_message(err_open, errbuf2, sizeof(errbuf2));
4029 SH_MUTEX_LOCK(mutex_thread_nolog);
4030 sh_error_handle (level, FIL__, __LINE__, err_open,
4031 MSG_E_READ, errbuf, errbuf2, tmp2);
4032 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4033 }
4034 SH_FREE(tmp2);
4035 }
4036 }
4037
4038
4039 /* --- Determine file type. ---
4040 */
4041 memset (theFile->c_mode, '-', CMODE_SIZE-1);
4042 theFile->c_mode[CMODE_SIZE-1] = '\0';
4043
4044 memset (theFile->link_c_mode, '-', CMODE_SIZE-1);
4045 theFile->link_c_mode[CMODE_SIZE-1] = '\0';
4046
4047 sh_unix_getinfo_type (&buf, &type, theFile->c_mode);
4048 theFile->type = type;
4049
4050#if defined(__linux__) || defined(HAVE_STAT_FLAGS)
4051
4052 /* --- Determine file attributes. ---
4053 */
4054 memset (theFile->c_attributes, '-', ATTRBUF_SIZE);
4055 theFile->c_attributes[ATTRBUF_USED] = '\0';
4056 theFile->attributes = 0;
4057
4058#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
4059 if (theFile->c_mode[0] != 'c' && theFile->c_mode[0] != 'b' &&
4060 theFile->c_mode[0] != 'l' )
4061 sh_unix_getinfo_attr(theFile->fullpath,
4062 &theFile->attributes, theFile->c_attributes,
4063 fd, &buf);
4064#endif
4065#endif
4066
4067#if defined(USE_XATTR) && defined(USE_ACL)
4068 if (sh_unix_check_selinux == S_TRUE || sh_unix_check_acl == S_TRUE)
4069 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4070#elif defined(USE_XATTR)
4071 if (sh_unix_check_selinux == S_TRUE)
4072 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4073#elif defined(USE_ACL)
4074 if (sh_unix_check_acl == S_TRUE)
4075 theFile->attr_string = sh_unix_getinfo_acl (theFile->fullpath, fd, &buf);
4076#else
4077 theFile->attr_string = NULL;
4078#endif
4079
4080 if (!SL_ISERROR(rval_open))
4081 sl_close(rval_open);
4082
4083
4084 /* --- I/O limit. ---
4085 */
4086 if (IO_Limit > 0)
4087 {
4088 runtim = (long) (time(NULL) - sh.statistics.time_start);
4089
4090 if (runtim > 0 && (long)(sh.statistics.bytes_hashed/runtim) > IO_Limit)
4091 retry_msleep(1, 0);
4092 }
4093
4094 /* --- Determine permissions. ---
4095 */
4096 sh_unix_getinfo_mode (&buf, &mode, theFile->c_mode);
4097
4098 /* --- Trivia. ---
4099 */
4100 theFile->dev = buf.st_dev;
4101 theFile->ino = buf.st_ino;
4102 theFile->mode = buf.st_mode;
4103 theFile->hardlinks = buf.st_nlink;
4104 theFile->owner = buf.st_uid;
4105 theFile->group = buf.st_gid;
4106 theFile->rdev = buf.st_rdev;
4107 theFile->size = buf.st_size;
4108 theFile->blksize = (unsigned long) buf.st_blksize;
4109 theFile->blocks = (unsigned long) buf.st_blocks;
4110 theFile->atime = buf.st_atime;
4111 theFile->mtime = buf.st_mtime;
4112 theFile->ctime = buf.st_ctime;
4113
4114
4115 /* --- Owner and group. ---
4116 */
4117
4118 if (NULL == sh_unix_getGIDname(SH_ERR_ALL, buf.st_gid, theFile->c_group, GROUP_MAX+1)) {
4119
4120 tmp2 = sh_util_safe_name (theFile->fullpath);
4121
4122 if (policy == SH_LEVEL_ALLIGNORE)
4123 {
4124 SH_MUTEX_LOCK(mutex_thread_nolog);
4125 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4126 MSG_FI_NOGRP,
4127 (long) buf.st_gid, tmp2);
4128 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4129 }
4130 else
4131 {
4132 SH_MUTEX_LOCK(mutex_thread_nolog);
4133 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4134 MSG_FI_NOGRP,
4135 (long) buf.st_gid, tmp2);
4136 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4137 }
4138 SH_FREE(tmp2);
4139 sl_snprintf(theFile->c_group, GROUP_MAX+1, "%d", (long) buf.st_gid);
4140 }
4141
4142
4143 if (NULL == sh_unix_getUIDname(SH_ERR_ALL, buf.st_uid, theFile->c_owner, USER_MAX+1)) {
4144
4145 tmp2 = sh_util_safe_name (theFile->fullpath);
4146
4147 if (policy == SH_LEVEL_ALLIGNORE)
4148 {
4149 SH_MUTEX_LOCK(mutex_thread_nolog);
4150 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4151 MSG_FI_NOUSR,
4152 (long) buf.st_uid, tmp2);
4153 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4154 }
4155 else
4156 {
4157 SH_MUTEX_LOCK(mutex_thread_nolog);
4158 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4159 MSG_FI_NOUSR,
4160 (long) buf.st_uid, tmp2);
4161 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4162 }
4163 SH_FREE(tmp2);
4164 sl_snprintf(theFile->c_owner, USER_MAX+1, "%d", (long) buf.st_uid);
4165 }
4166
4167 /* --- Output the file. ---
4168 */
4169 if (flag_err_debug == SL_TRUE)
4170 {
4171 tmp2 = sh_util_safe_name ((filename == NULL) ?
4172 theFile->fullpath : filename);
4173 (void) sh_unix_time(theFile->mtime, timestr, sizeof(timestr));
4174 SH_MUTEX_LOCK(mutex_thread_nolog);
4175 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LIST,
4176 theFile->c_mode,
4177 theFile->hardlinks,
4178 theFile->c_owner,
4179 theFile->c_group,
4180 (unsigned long) theFile->size,
4181 timestr,
4182 tmp2);
4183 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4184 SH_FREE(tmp2);
4185 }
4186
4187 /* --- Check for links. ---
4188 */
4189 if (theFile->c_mode[0] == 'l')
4190 {
4191 linknamebuf = SH_ALLOC(PATH_MAX);
4192
4193 /* flawfinder: ignore */
4194 linksize = readlink (theFile->fullpath, linknamebuf, PATH_MAX-1);
4195
4196 if (linksize < (PATH_MAX-1) && linksize >= 0)
4197 linknamebuf[linksize] = '\0';
4198 else
4199 linknamebuf[PATH_MAX-1] = '\0';
4200
4201 if (linksize < 0)
4202 {
4203 char errbuf[SH_ERRBUF_SIZE];
4204 linksize = errno;
4205 tmp2 = sh_util_safe_name (theFile->fullpath);
4206 SH_MUTEX_LOCK(mutex_thread_nolog);
4207 sh_error_handle (level, FIL__, __LINE__, linksize, MSG_FI_RDLNK,
4208 sh_error_message (linksize, errbuf, sizeof(errbuf)), tmp2);
4209 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4210 SH_FREE(tmp2);
4211 SH_FREE(linknamebuf);
4212 theFile->link_path = sh_util_strdup("-");
4213 SL_RETURN((-1),_("sh_unix_getinfo"));
4214 }
4215
4216 if (linknamebuf[0] == '/')
4217 {
4218 theFile->link_path = sh_util_strdup (linknamebuf);
4219 }
4220 else
4221 {
4222 tmp = sh_util_dirname(theFile->fullpath);
4223 if (tmp) {
4224 theFile->link_path = SH_ALLOC(PATH_MAX);
4225 sl_strlcpy (theFile->link_path, tmp, PATH_MAX);
4226 SH_FREE(tmp);
4227 } else {
4228 theFile->link_path = SH_ALLOC(PATH_MAX);
4229 theFile->link_path[0] = '\0';
4230 }
4231 /*
4232 * Only attach '/' if not root directory. Handle "//", which
4233 * according to POSIX is implementation-defined, and may be
4234 * different from "/" (however, three or more '/' will collapse
4235 * to one).
4236 */
4237 tmp = theFile->link_path; while (*tmp == '/') ++tmp;
4238 if (*tmp != '\0')
4239 {
4240 sl_strlcat (theFile->link_path, "/", PATH_MAX);
4241 }
4242 sl_strlcat (theFile->link_path, linknamebuf, PATH_MAX);
4243 }
4244
4245 /* stat the link
4246 */
4247 stat_return = retry_lstat (FIL__, __LINE__, theFile->link_path, &lbuf);
4248
4249 /* check for error
4250 */
4251 if (stat_return != 0)
4252 {
4253 stat_return = errno;
4254 tmp = sh_util_safe_name (theFile->fullpath);
4255 tmp2 = sh_util_safe_name (theFile->link_path);
4256 if (stat_return != ENOENT)
4257 {
4258 uid_t euid;
4259 char errbuf[SH_ERRBUF_SIZE];
4260
4261 (void) sl_get_euid(&euid);
4262 SH_MUTEX_LOCK(mutex_thread_nolog);
4263 sh_error_handle (level, FIL__, __LINE__, stat_return,
4264 MSG_FI_STAT,
4265 _("lstat"),
4266 sh_error_message (stat_return,errbuf, sizeof(errbuf)),
4267 (long) euid,
4268 tmp2);
4269 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4270 }
4271 else
4272 {
4273 /* a dangling link -- everybody seems to have plenty of them
4274 */
4275 SH_MUTEX_LOCK(mutex_thread_nolog);
4276 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_DLNK,
4277 tmp, tmp2);
4278 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4279 }
4280 theFile->linkisok = BAD;
4281 SH_FREE(tmp);
4282 SH_FREE(tmp2);
4283 SH_FREE(linknamebuf);
4284 /*
4285 * changed Tue Feb 10 16:16:13 CET 2004:
4286 * add dangling symlinks into database
4287 * SL_RETURN((-1),_("sh_unix_getinfo"));
4288 */
4289 theFile->linkmode = 0;
4290 SL_RETURN((0),_("sh_unix_getinfo"));
4291 }
4292
4293 theFile->linkisok = GOOD;
4294
4295
4296 /* --- Determine file type. ---
4297 */
4298 sh_unix_getinfo_type (&lbuf, &type, theFile->link_c_mode);
4299 theFile->type = type;
4300
4301 /* --- Determine permissions. ---
4302 */
4303 sh_unix_getinfo_mode (&lbuf, &mode, theFile->link_c_mode);
4304 theFile->linkmode = lbuf.st_mode;
4305
4306 /* --- Output the link. ---
4307 */
4308 if (theFile->linkisok == GOOD)
4309 {
4310 tmp2 = sh_util_safe_name (linknamebuf);
4311 SH_MUTEX_LOCK(mutex_thread_nolog);
4312 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LLNK,
4313 theFile->link_c_mode, tmp2);
4314 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4315 SH_FREE(tmp2);
4316 }
4317 SH_FREE(linknamebuf);
4318 }
4319 else /* not a link, theFile->c_mode[0] != 'l' */
4320 {
4321 if (content)
4322 {
4323#ifdef HAVE_LIBZ
4324 unsigned long clen;
4325 unsigned char * compressed;
4326#ifdef HAVE_COMPRESSBOUND
4327 clen = compressBound(sh_string_len(content));
4328#else
4329 if (sh_string_len(content) > 10*SH_TXT_MAX)
4330 clen = SH_TXT_MAX;
4331 else
4332 clen = 13 + (int)(1.0001*sh_string_len(content));
4333#endif
4334 compressed = SH_ALLOC(clen);
4335 if (Z_OK == compress(compressed, &clen,
4336 (unsigned char *) sh_string_str(content),
4337 sh_string_len(content)))
4338 {
4339 if (clen < SH_TXT_MAX)
4340 {
4341 sh_util_base64_enc_alloc (&(theFile->link_path),
4342 (char *) compressed, clen);
4343 }
4344 else
4345 {
4346 char tmsg[128];
4347 char * tpath = sh_util_safe_name (theFile->fullpath);
4348 sl_snprintf(tmsg, sizeof(tmsg),
4349 _("compressed file too large (%lu bytes)"),
4350 clen);
4351 SH_MUTEX_LOCK(mutex_thread_nolog);
4352 sh_error_handle (SH_ERR_WARN, FIL__, __LINE__, -1,
4353 MSG_E_SUBGPATH, tmsg,
4354 _("sh_unix_getinfo"), tpath);
4355 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4356 SH_FREE(tpath);
4357 }
4358 }
4359 SH_FREE(compressed);
4360#endif
4361 sh_string_destroy(&content);
4362 }
4363 }
4364 SL_RETURN((0),_("sh_unix_getinfo"));
4365}
4366
4367/* #if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE) */
4368#endif
4369
4370int sh_unix_unlock(char * lockfile, char * flag)
4371{
4372 int error = 0;
4373
4374 SL_ENTER(_("sh_unix_unlock"));
4375
4376 if (sh.flag.isdaemon == S_FALSE && flag == NULL)
4377 SL_RETURN((0),_("sh_unix_unlock"));
4378
4379 /* --- Logfile is not locked to us. ---
4380 */
4381 if (sh.flag.islocked == BAD && flag != NULL)
4382 SL_RETURN((-1),_("sh_unix_unlock"));
4383
4384 /* --- Check whether the directory is secure. ---
4385 */
4386 if (0 != tf_trust_check (lockfile, SL_YESPRIV))
4387 SL_RETURN((-1),_("sh_unix_unlock"));
4388
4389 /* --- Delete the lock file. ---
4390 */
4391 error = retry_aud_unlink (FIL__, __LINE__, lockfile);
4392
4393 if (error == 0)
4394 {
4395 if (flag != NULL)
4396 sh.flag.islocked = BAD; /* not locked anymore */
4397 }
4398 else if (flag != NULL)
4399 {
4400 char errbuf[SH_ERRBUF_SIZE];
4401 error = errno;
4402 sh_error_handle ((-1), FIL__, __LINE__, error, MSG_E_UNLNK,
4403 sh_error_message(error, errbuf, sizeof(errbuf)),
4404 lockfile);
4405 SL_RETURN((-1),_("sh_unix_unlock"));
4406 }
4407 SL_RETURN((0),_("sh_unix_unlock"));
4408}
4409
4410int sh_unix_check_piddir (char * pidpath)
4411{
4412 static struct stat buf;
4413 int status = 0;
4414 char * pid_dir;
4415
4416 SL_ENTER(_("sh_unix_check_piddir"));
4417
4418 pid_dir = sh_util_dirname (pidpath);
4419
4420 status = retry_lstat (FIL__, __LINE__, pid_dir, &buf);
4421
4422 if (status < 0 && errno == ENOENT)
4423 {
4424 status = mkdir (pid_dir, 0777);
4425 if (status < 0)
4426 {
4427 sh_error_handle ((-1), FIL__, __LINE__, status,
4428 MSG_E_SUBGEN,
4429 _("Cannot create PID directory"),
4430 _("sh_unix_check_piddir"));
4431 SH_FREE(pid_dir);
4432 SL_RETURN((-1),_("sh_unix_check_piddir"));
4433 }
4434 }
4435 else if (!S_ISDIR(buf.st_mode))
4436 {
4437 sh_error_handle ((-1), FIL__, __LINE__, status,
4438 MSG_E_SUBGEN,
4439 _("Path of PID directory refers to a non-directory object"),
4440 _("sh_unix_check_piddir"));
4441 SH_FREE(pid_dir);
4442 SL_RETURN((-1),_("sh_unix_check_piddir"));
4443 }
4444 SH_FREE(pid_dir);
4445 SL_RETURN((0),_("sh_unix_check_piddir"));
4446}
4447
4448int sh_unix_lock (char * lockfile, char * flag)
4449{
4450 int filed;
4451 int errnum;
4452 char myPid[64];
4453 SL_TICKET fd;
4454 extern int get_the_fd (SL_TICKET ticket);
4455
4456 SL_ENTER(_("sh_unix_lock"));
4457
4458 sprintf (myPid, "%ld\n", (long) sh.pid); /* known to fit */
4459
4460 if (flag == NULL) /* PID file, check for directory */
4461 {
4462 if (0 != sh_unix_check_piddir (lockfile))
4463 {
4464 SL_RETURN((-1),_("sh_unix_lock"));
4465 }
4466 }
4467
4468 fd = sl_open_safe_rdwr (FIL__, __LINE__,
4469 lockfile, SL_YESPRIV); /* fails if file exists */
4470
4471 if (!SL_ISERROR(fd))
4472 {
4473 errnum = sl_write (fd, myPid, sl_strlen(myPid));
4474 filed = get_the_fd(fd);
4475 fchmod (filed, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
4476 sl_close (fd);
4477
4478 if (!SL_ISERROR(errnum))
4479 {
4480 if (flag != NULL)
4481 sh.flag.islocked = GOOD;
4482 SL_RETURN((0),_("sh_unix_lock"));
4483 }
4484 }
4485
4486 TPT((0, FIL__, __LINE__, _("msg=<open pid file failed>\n")));
4487 if (flag != NULL)
4488 sh.flag.islocked = BAD;
4489 SL_RETURN((-1),_("sh_unix_lock"));
4490
4491 /* notreached */
4492}
4493
4494
4495/* check whether file is locked
4496 */
4497int sh_unix_test_and_lock (char * filename, char * lockfile)
4498{
4499 static struct stat buf;
4500 int status = 0;
4501
4502
4503 SL_TICKET fd;
4504 char line_in[128];
4505
4506 SL_ENTER(_("sh_unix_test_and_lock"));
4507
4508 status = retry_lstat (FIL__, __LINE__, lockfile, &buf);
4509
4510 /* --- No lock file found, try to lock. ---
4511 */
4512
4513 if (status < 0 && errno == ENOENT)
4514 {
4515 if (0 == sh_unix_lock (lockfile, filename))
4516 {
4517 if (filename != NULL)
4518 sh.flag.islocked = GOOD;
4519 SL_RETURN((0),_("sh_unix_test_and_lock"));
4520 }
4521 else
4522 {
4523 sh_error_handle ((-1), FIL__, __LINE__, status,
4524 MSG_E_SUBGEN,
4525 (filename == NULL) ? _("Cannot create PID file (1)") : _("Cannot create lock file (1)"),
4526 _("sh_unix_test_and_lock"));
4527 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4528 }
4529 }
4530 else if (status == 0 && buf.st_size == 0)
4531 {
4532 if (filename != NULL)
4533 sh.flag.islocked = GOOD;
4534 sh_unix_unlock (lockfile, filename);
4535 if (filename != NULL)
4536 sh.flag.islocked = BAD;
4537 if (0 == sh_unix_lock (lockfile, filename))
4538 {
4539 if (filename != NULL)
4540 sh.flag.islocked = GOOD;
4541 SL_RETURN((0),_("sh_unix_test_and_lock"));
4542 }
4543 else
4544 {
4545 sh_error_handle ((-1), FIL__, __LINE__, status,
4546 MSG_E_SUBGEN,
4547 (filename == NULL) ? _("Cannot create PID file (2)") : _("Cannot create lock file (2)"),
4548 _("sh_unix_test_and_lock"));
4549 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4550 }
4551 }
4552
4553 /* --- Check on lock. ---
4554 */
4555
4556 if (status >= 0)
4557 {
4558 fd = sl_open_read (FIL__, __LINE__, lockfile, SL_YESPRIV);
4559 if (SL_ISERROR(fd))
4560 sh_error_handle ((-1), FIL__, __LINE__, fd,
4561 MSG_E_SUBGEN,
4562 (filename == NULL) ? _("Cannot open PID file for read") : _("Cannot open lock file for read"),
4563 _("sh_unix_test_and_lock"));
4564 }
4565 else
4566 fd = -1;
4567
4568 if (!SL_ISERROR(fd))
4569 {
4570 /* read the PID in the lock file
4571 */
4572 status = sl_read (fd, line_in, sizeof(line_in));
4573 line_in[sizeof(line_in)-1] = '\0';
4574
4575 /* convert to numeric
4576 */
4577 if (status > 0)
4578 {
4579 errno = 0;
4580 status = strtol(line_in, (char **)NULL, 10);
4581 if (errno == ERANGE || status <= 0)
4582 {
4583 sh_error_handle ((-1), FIL__, __LINE__, status,
4584 MSG_E_SUBGEN,
4585 (filename == NULL) ? _("Bad PID in PID file") : _("Bad PID in lock file"),
4586 _("sh_unix_test_and_lock"));
4587
4588 status = -1;
4589 }
4590 }
4591 else
4592 {
4593 sh_error_handle ((-1), FIL__, __LINE__, status,
4594 MSG_E_SUBGEN,
4595 (filename == NULL) ? _("Cannot read PID file") : _("Cannot read lock file"),
4596 _("sh_unix_test_and_lock"));
4597 }
4598 sl_close(fd);
4599
4600 if (status > 0 && (unsigned int) status == sh.pid)
4601 {
4602 if (filename != NULL)
4603 sh.flag.islocked = GOOD;
4604 SL_RETURN((0),_("sh_unix_test_and_lock"));
4605 }
4606
4607
4608 /* --- Check whether the process exists. ---
4609 */
4610 if (status > 0)
4611 {
4612 errno = 0;
4613 status = aud_kill (FIL__, __LINE__, status, 0);
4614
4615 /* Does not exist, so remove the stale lock
4616 * and create a new one.
4617 */
4618 if (status < 0 && errno == ESRCH)
4619 {
4620 if (filename != NULL)
4621 sh.flag.islocked = GOOD;
4622 if (0 != sh_unix_unlock(lockfile, filename) && (filename !=NULL))
4623 sh.flag.islocked = BAD;
4624 else
4625 {
4626 if (0 == sh_unix_lock (lockfile, filename))
4627 {
4628 if (filename != NULL)
4629 sh.flag.islocked = GOOD;
4630 SL_RETURN((0),_("sh_unix_test_and_lock"));
4631 }
4632 else
4633 {
4634 sh_error_handle ((-1), FIL__, __LINE__, status,
4635 MSG_E_SUBGEN,
4636 (filename == NULL) ? _("Cannot create PID file (3)") : _("Cannot create lock file (3)"),
4637 _("sh_unix_test_and_lock"));
4638 }
4639 if (filename != NULL)
4640 sh.flag.islocked = BAD;
4641 }
4642 }
4643 else
4644 {
4645 sh_error_handle ((-1), FIL__, __LINE__, status,
4646 MSG_E_SUBGEN,
4647 (filename == NULL) ? _("Cannot remove stale PID file, PID may be a running process") : _("Cannot remove stale lock file, PID may be a running process"),
4648 _("sh_unix_test_and_lock"));
4649 if (filename != NULL)
4650 sh.flag.islocked = BAD;
4651 }
4652 }
4653 }
4654 SL_RETURN((-1),_("sh_unix_testlock"));
4655}
4656
4657/* write the PID file
4658 */
4659int sh_unix_write_pid_file()
4660{
4661 return sh_unix_test_and_lock(NULL, sh.srvlog.alt);
4662}
4663
4664/* write lock for filename
4665 */
4666int sh_unix_write_lock_file(char * filename)
4667{
4668 size_t len;
4669 int res;
4670 char * lockfile;
4671
4672 if (filename == NULL)
4673 return (-1);
4674
4675 len = sl_strlen(filename);
4676 if (sl_ok_adds(len, 6))
4677 len += 6;
4678 lockfile = SH_ALLOC(len);
4679 sl_strlcpy(lockfile, filename, len);
4680 sl_strlcat(lockfile, _(".lock"), len);
4681 res = sh_unix_test_and_lock(filename, lockfile);
4682 SH_FREE(lockfile);
4683 return res;
4684}
4685
4686/* rm lock for filename
4687 */
4688int sh_unix_rm_lock_file(char * filename)
4689{
4690 size_t len;
4691 int res;
4692 char * lockfile;
4693
4694 if (filename == NULL)
4695 return (-1);
4696
4697 len = sl_strlen(filename);
4698 if (sl_ok_adds(len, 6))
4699 len += 6;
4700 lockfile = SH_ALLOC(len);
4701 sl_strlcpy(lockfile, filename, len);
4702 sl_strlcat(lockfile, _(".lock"), len);
4703
4704 res = sh_unix_unlock(lockfile, filename);
4705 SH_FREE(lockfile);
4706 return res;
4707}
4708
4709/* rm lock for filename
4710 */
4711int sh_unix_rm_pid_file()
4712{
4713 return sh_unix_unlock(sh.srvlog.alt, NULL);
4714}
4715
4716/* Test whether file exists
4717 */
4718int sh_unix_file_exists(char * path)
4719{
4720 struct stat buf;
4721
4722 SL_ENTER(_("sh_unix_file_exists"));
4723
4724 if (0 == retry_lstat(FIL__, __LINE__, path, &buf))
4725 SL_RETURN( S_TRUE, _("sh_unix_file_exists"));
4726 else
4727 SL_RETURN( S_FALSE, _("sh_unix_file_exists"));
4728}
4729
4730
4731/* Test whether file exists, is a character device, and allows read
4732 * access.
4733 */
4734int sh_unix_device_readable(int fd)
4735{
4736 struct stat buf;
4737
4738 SL_ENTER(_("sh_unix_device_readable"));
4739
4740 if (retry_fstat(FIL__, __LINE__, fd, &buf) == -1)
4741 SL_RETURN( (-1), _("sh_unix_device_readable"));
4742 else if ( S_ISCHR(buf.st_mode) && 0 != (S_IROTH & buf.st_mode) )
4743 SL_RETURN( (0), _("sh_unix_device_readable"));
4744 else
4745 SL_RETURN( (-1), _("sh_unix_device_readable"));
4746}
4747
4748static char preq[16];
4749
4750/* return true if database is remote
4751 */
4752int file_is_remote ()
4753{
4754 static int init = 0;
4755 struct stat buf;
4756
4757 SL_ENTER(_("file_is_remote"));
4758
4759 if (init == 0)
4760 {
4761 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4762 ++init;
4763 }
4764 if (0 == sl_strncmp (sh.data.path, preq, 15))
4765 {
4766 if (sh.data.path[15] != '\0') /* should be start of path */
4767 {
4768 if (0 == stat(&(sh.data.path[15]), &buf))
4769 {
4770 SL_RETURN( S_FALSE, _("file_is_remote"));
4771 }
4772 }
4773 SL_RETURN( S_TRUE, _("file_is_remote"));
4774 }
4775 SL_RETURN( S_FALSE, _("file_is_remote"));
4776}
4777
4778/* Return the path to the configuration/database file.
4779 */
4780char * file_path(char what, char flag)
4781{
4782 static int init = 0;
4783
4784 SL_ENTER(_("file_path"));
4785
4786 if (init == 0)
4787 {
4788 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4789 ++init;
4790 }
4791
4792 switch (what)
4793 {
4794
4795 case 'C':
4796 if (0 == sl_strncmp (sh.conf.path, preq, 15))
4797 {
4798#if defined(SH_WITH_SERVER)
4799 if (sh.flag.isserver == S_TRUE && sl_strlen(sh.conf.path) == 15)
4800 SL_RETURN( NULL, _("file_path"));
4801 if (sh.flag.isserver == S_TRUE)
4802 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4803#endif
4804 if (flag == 'R')
4805 SL_RETURN( preq, _("file_path"));
4806 if (flag == 'I')
4807 {
4808 if (sl_strlen(sh.conf.path) == 15)
4809 SL_RETURN( NULL, _("file_path"));
4810 else
4811 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4812 }
4813 SL_RETURN ( preq, _("file_path"));
4814 }
4815 else
4816 SL_RETURN( sh.conf.path, _("file_path"));
4817 /* break; *//* unreachable */
4818
4819 case 'D':
4820 if (0 == sl_strncmp (sh.data.path, preq, 15))
4821 {
4822 if (flag == 'R')
4823 SL_RETURN( preq, _("file_path"));
4824 if (flag == 'W' && sl_strlen(sh.data.path) == 15)
4825 SL_RETURN (NULL, _("file_path"));
4826 if (flag == 'W')
4827 SL_RETURN( &(sh.data.path[15]), _("file_path"));
4828 }
4829 else
4830 SL_RETURN( sh.data.path, _("file_path"));
4831 break;
4832
4833 default:
4834 SL_RETURN( NULL, _("file_path"));
4835 }
4836
4837 return NULL; /* notreached */
4838}
4839/************************************************/
4840/**** Mlock Utilities ****/
4841/************************************************/
4842
4843#include <limits.h>
4844
4845int sh_unix_pagesize()
4846{
4847 int pagesize = 4096;
4848#if defined(_SC_PAGESIZE)
4849 pagesize = sysconf(_SC_PAGESIZE);
4850#elif defined(_SC_PAGE_SIZE)
4851 pagesize = sysconf(_SC_PAGE_SIZE);
4852#elif defined(HAVE_GETPAGESIZE)
4853 pagesize = getpagesize();
4854#elif defined(PAGESIZE)
4855 pagesize = PAGESIZE;
4856#endif
4857
4858 return ((pagesize > 0) ? pagesize : 4096);
4859}
4860
4861typedef struct sh_page_lt {
4862 unsigned long page_start;
4863 int page_refcount;
4864 char file[64];
4865 int line;
4866 struct sh_page_lt * next;
4867} sh_page_l;
4868
4869sh_page_l * sh_page_locked = NULL;
4870volatile int page_locking = 0;
4871
4872unsigned long sh_unix_lookup_page (void * in_addr, size_t len, int * num_pages)
4873{
4874 int pagesize = sh_unix_pagesize();
4875 unsigned long addr = (unsigned long) in_addr;
4876
4877 unsigned long pagebase;
4878 unsigned long pagediff;
4879 unsigned long pagenum = addr / pagesize;
4880
4881 SL_ENTER(_("sh_unix_lookup_page"));
4882#if 0
4883 fprintf(stderr, "mlock: --> base %ld, pagenum: %ld\n",
4884 addr, pagenum);
4885#endif
4886
4887 /* address of first page
4888 */
4889 pagebase = pagenum * pagesize;
4890
4891 /* number of pages
4892 */
4893 pagediff = (addr + len) - pagebase;
4894 pagenum = pagediff / pagesize;
4895 if (pagenum * pagesize < pagediff)
4896 ++pagenum;
4897
4898#if 0
4899 fprintf(stderr, "mlock: --> pagebase %ld, pagediff %ld, (addr + len) %ld\n",
4900 pagebase, pagediff, (addr + len));
4901#endif
4902
4903 *num_pages = pagenum;
4904 SL_RETURN((pagebase), _("sh_unix_lookup_page"));
4905}
4906
4907
4908#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4909
4910SH_MUTEX_STATIC(mutex_mlock,PTHREAD_MUTEX_INITIALIZER);
4911
4912int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4913{
4914 int num_pages;
4915 int status = 0;
4916 int pagesize;
4917 sh_page_l * page_list;
4918 unsigned long addr;
4919#ifdef TEST_MLOCK
4920 int i = 0;
4921#endif
4922
4923 SL_ENTER(_("sh_unix_mlock"));
4924
4925 /* There's no cancellation point here, except if tracing is on
4926 */
4927 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4928
4929 page_list = sh_page_locked;
4930
4931 if (0 != page_locking)
4932 {
4933 status = -1;
4934 goto exit_mlock;
4935 }
4936
4937 page_locking = 1;
4938
4939 pagesize = sh_unix_pagesize();
4940 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4941
4942#ifdef TEST_MLOCK
4943 fprintf(stderr, "mlock: addr %ld, base %ld, pages: %d, length %d\n",
4944 (unsigned long) in_addr, addr, num_pages, len);
4945#endif
4946
4947 /* increase refcount of locked pages
4948 * addr is first page; num_pages is #(consecutive pages) to lock
4949 */
4950
4951 while ((page_list != NULL) && (num_pages > 0))
4952 {
4953#ifdef TEST_MLOCK
4954 fprintf(stderr, "mlock: check page %d: %ld [%d]\n",
4955 i, page_list->page_start, page_list->page_refcount);
4956#endif
4957 if (page_list->page_start == addr)
4958 {
4959 page_list->page_refcount += 1;
4960 num_pages -= 1;
4961 addr += pagesize;
4962#ifdef TEST_MLOCK
4963 fprintf(stderr, "mlock: found page %d: %ld [%d], next page %ld\n",
4964 i, page_list->page_start, page_list->page_refcount, addr);
4965#endif
4966 }
4967#ifdef TEST_MLOCK
4968 ++i;
4969#endif
4970 page_list = page_list->next;
4971 }
4972
4973 /* mlock some more pages, if needed
4974 */
4975 while (num_pages > 0)
4976 {
4977#ifdef TEST_MLOCK
4978 fprintf(stderr, "mlock: lock page %d: mlock %ld [num_pages %d]\n",
4979 i, addr, num_pages);
4980 ++i;
4981#endif
4982 page_list = SH_ALLOC(sizeof(sh_page_l));
4983 page_list->page_start = addr;
4984 page_list->page_refcount = 1;
4985 sl_strlcpy(page_list->file, file, 64);
4986 page_list->line = line;
4987 status = mlock( (void *) addr, pagesize);
4988 if (status != 0)
4989 {
4990#ifdef TEST_MLOCK
4991 char errbuf[SH_ERRBUF_SIZE];
4992 fprintf(stderr, "mlock: error: %s\n",
4993 sh_error_message(errno, errbuf, sizeof(errbuf)));
4994#endif
4995 SH_FREE(page_list);
4996 page_locking = 0;
4997 goto exit_mlock;
4998 }
4999 page_list->next = sh_page_locked;
5000 sh_page_locked = page_list;
5001 num_pages -= 1;
5002 addr += pagesize;
5003 }
5004 page_locking = 0;
5005
5006 exit_mlock:
5007 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5008
5009 SL_RETURN((status), _("sh_unix_mlock"));
5010}
5011#else
5012int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
5013{
5014 (void) file; (void) line;
5015 (void) in_addr; (void) len;
5016 return -1;
5017}
5018#endif
5019
5020#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5021int sh_unix_munlock (void * in_addr, size_t len)
5022{
5023 int num_pages;
5024 int unlocked;
5025 int status;
5026 int pagesize;
5027 sh_page_l * page_list;
5028 sh_page_l * page_last;
5029 unsigned long addr;
5030
5031 int test_count;
5032 int test_status;
5033 int test_pages;
5034
5035#ifdef TEST_MLOCK
5036 int i = 0;
5037#endif
5038
5039 SL_ENTER(_("sh_unix_munlock"));
5040
5041 /* There's no cancellation point here, except if tracing is on
5042 */
5043 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5044
5045 unlocked = 0;
5046 status = 0;
5047 page_list = sh_page_locked;
5048
5049 if (0 != page_locking)
5050 {
5051 status = -1;
5052 goto exit_munlock;
5053 }
5054 page_locking = 1;
5055
5056 pagesize = sh_unix_pagesize();
5057 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
5058
5059#ifdef TEST_MLOCK
5060 fprintf(stderr, "munlock: in_addr %ld, addr %ld, pages: %d, length %d\n",
5061 (unsigned long) in_addr, addr, num_pages, len);
5062#endif
5063
5064 test_pages = num_pages;
5065
5066 /* reduce refcount of locked pages
5067 * addr is first page; num_pages is #(consecutive pages) to lock
5068 */
5069 while ((page_list != NULL) && (num_pages > 0))
5070 {
5071#ifdef TEST_MLOCK
5072 fprintf(stderr, "munlock: page %d: %ld [%d]\n",
5073 i, page_list->page_start, page_list->page_refcount);
5074#endif
5075
5076 test_status = 0;
5077 for (test_count = 0; test_count < test_pages; ++test_count)
5078 {
5079 if (page_list->page_start == (addr + (test_count * pagesize)))
5080 {
5081 test_status = 1;
5082 break;
5083 }
5084 }
5085
5086 if (test_status == 1)
5087 {
5088 page_list->page_refcount -= 1;
5089 if (page_list->page_refcount == 0)
5090 {
5091 status = munlock ( (void *) addr, pagesize);
5092 ++unlocked;
5093 }
5094 num_pages -= 1;
5095#ifdef TEST_MLOCK
5096 fprintf(stderr,
5097 "munlock: page %d: %ld [refcount %d], refcount reduced\n",
5098 i, page_list->page_start, page_list->page_refcount);
5099#endif
5100 }
5101#ifdef TEST_MLOCK
5102 ++i;
5103#endif
5104 page_list = page_list->next;
5105 }
5106
5107#ifdef TEST_MLOCK
5108 i = 0;
5109#endif
5110
5111 if (unlocked > 0)
5112 {
5113 page_list = sh_page_locked;
5114 page_last = sh_page_locked;
5115
5116 while ((page_list != NULL) && (unlocked > 0))
5117 {
5118 if (page_list->page_refcount == 0)
5119 {
5120#ifdef TEST_MLOCK
5121 fprintf(stderr, "munlock: remove page %d: %ld [refcount %d]\n",
5122 i, page_list->page_start, page_list->page_refcount);
5123#endif
5124 if (page_last != page_list)
5125 {
5126 page_last->next = page_list->next;
5127 SH_FREE(page_list);
5128 page_list = page_last->next;
5129 }
5130 else
5131 {
5132 page_last = page_list->next;
5133 if (page_list == sh_page_locked)
5134 sh_page_locked = page_list->next;
5135 SH_FREE(page_list);
5136 page_list = page_last;
5137 }
5138 --unlocked;
5139 }
5140 else
5141 {
5142#ifdef TEST_MLOCK
5143 fprintf(stderr, "munlock: skip page %d: %ld [refcount %d]\n",
5144 i, page_list->page_start, page_list->page_refcount);
5145#endif
5146
5147 page_last = page_list;
5148 page_list = page_list->next;
5149 }
5150#ifdef TEST_MLOCK
5151 ++i;
5152#endif
5153 }
5154 }
5155
5156 page_locking = 0;
5157
5158 exit_munlock:
5159 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5160 SL_RETURN((status), _("sh_unix_munlock"));
5161}
5162#else
5163int sh_unix_munlock (void * in_addr, size_t len)
5164{
5165 (void) in_addr; (void) len;
5166 return -1;
5167}
5168#endif
5169
5170int sh_unix_count_mlock()
5171{
5172 int i = 0;
5173 char str[32][64];
5174 sh_page_l * page_list;
5175
5176 SL_ENTER(_("sh_unix_count_mlock"));
5177
5178#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5179 /* There's no cancellation point here, except if tracing is on
5180 */
5181 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5182#endif
5183
5184 page_list = sh_page_locked;
5185
5186 while (page_list != NULL)
5187 {
5188#ifdef WITH_TPT
5189 if (i < 32)
5190 sl_snprintf(str[i], 64, _("file: %s line: %d page: %d"),
5191 page_list->file, page_list->line, i+1);
5192#endif
5193 page_list = page_list->next;
5194 ++i;
5195 }
5196
5197#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5198 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5199#endif
5200
5201#ifdef WITH_TPT
5202 {
5203 int j = 0;
5204 while (j < i && j < 32)
5205 {
5206 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, j, MSG_E_SUBGEN,
5207 str[j], _("sh_unix_count_mlock"));
5208 ++j;
5209 }
5210 }
5211#endif
5212
5213 sl_snprintf(str[0], 64, _("%d pages locked"), i);
5214 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, i, MSG_E_SUBGEN,
5215 str[0], _("sh_unix_count_mlock"));
5216 SL_RETURN((i), _("sh_unix_count_mlock"));
5217}
5218
5219/************************************************/
5220/************************************************/
5221/**** Stealth Utilities ****/
5222/************************************************/
5223/************************************************/
5224#ifdef SH_STEALTH
5225
5226void sh_unix_xor_code (char * str, int len)
5227{
5228 register int i;
5229
5230 for (i = 0; i < len; ++i) str[i] ^= (char) XOR_CODE;
5231 return;
5232}
5233
5234#if !defined(SH_STEALTH_MICRO)
5235
5236
5237int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5238 unsigned long * bytes_read);
5239unsigned long first_hex_block(SL_TICKET fd, unsigned long * max);
5240
5241/*
5242 * --- Get hidden data from a block of hex data. ---
5243 */
5244int sh_unix_getline_stealth (SL_TICKET fd, char * str, int len)
5245{
5246 int add_off = 0, llen;
5247 static unsigned long off_data = 0;
5248 static unsigned long max_data = 0;
5249 static unsigned long bytes_read = 0;
5250 static int stealth_init = BAD;
5251
5252 SL_ENTER(_("sh_unix_getline_stealth"));
5253
5254 if (str == NULL)
5255 {
5256 off_data = 0;
5257 max_data = 0;
5258 bytes_read = 0;
5259 stealth_init = BAD;
5260 SL_RETURN(0, _("sh_unix_getline_stealth"));
5261 }
5262
5263 /* --- Initialize. ---
5264 */
5265 if (stealth_init == BAD)
5266 {
5267 off_data = first_hex_block(fd, &max_data);
5268 if (off_data == 0)
5269 {
5270 dlog(1, FIL__, __LINE__,
5271 _("The stealth config file does not contain any steganographically\nhidden data. This file must be an image file in _uncompressed_\npostscript format.\nTo hide data in it, use:\n samhain_stealth -s postscript_file orig_config_file\n mv postscript_file /path/to/config/file\n"));
5272 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5273 _("Stealth config file."));
5274 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5275 }
5276 stealth_init = GOOD;
5277 max_data += off_data;
5278 }
5279
5280 /* --- Seek to proper position. ---
5281 */
5282 if (bytes_read >= max_data || add_off < 0)
5283 {
5284 dlog(1, FIL__, __LINE__,
5285 _("The capacity of the container image file for the stealth config file seems to be too small. Your config file is likely truncated.\n"));
5286 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5287 _("Stealth config file."));
5288 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5289 }
5290 sl_seek(fd, off_data);
5291
5292 /* --- Read one line. ---
5293 */
5294 add_off = hideout_hex_block(fd, (unsigned char *) str, len, &bytes_read);
5295 off_data += add_off;
5296
5297 llen = sl_strlen(str);
5298 SL_RETURN(llen, _("sh_unix_getline_stealth"));
5299}
5300
5301int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5302 unsigned long * bytes_read)
5303{
5304
5305 register int i, j, k;
5306 unsigned char c, e;
5307 register int num;
5308 unsigned char mask[9] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
5309 unsigned long here = 0;
5310 unsigned long retval = 0;
5311 unsigned long bread = 0;
5312
5313 SL_ENTER(_("hideout_hex_block"));
5314
5315 ASSERT_RET((len > 1), _("len > 1"), (0));
5316
5317 --len;
5318
5319 i = 0;
5320 while (i < len)
5321 {
5322 for (j = 0; j < 8; ++j)
5323 {
5324
5325 /* --- Get a low byte, modify, read back. ---
5326 */
5327 for (k = 0; k < 2; ++k)
5328 {
5329 /* -- Skip whitespace. ---
5330 */
5331 c = ' ';
5332 do {
5333 do {
5334 num = sl_read (fd, &c, 1);
5335 } while (num == 0 && errno == EINTR);
5336 if (num > 0)
5337 ++here;
5338 else if (num == 0)
5339 SL_RETURN((0), _("hideout_hex_block"));
5340 else
5341 SL_RETURN((-1), _("hideout_hex_block"));
5342 } while (c == '\n' || c == '\t' || c == '\r' ||
5343 c == ' ');
5344 }
5345
5346
5347 /* --- e is the value of the low byte. ---
5348 */
5349 e = (unsigned char) sh_util_hexchar( c );
5350 if ((e & mask[7]) != 0) /* bit is set */
5351 str[i] |= mask[j];
5352 else /* bit is not set */
5353 str[i] &= ~mask[j];
5354
5355 bread += 1;
5356 }
5357 if (str[i] == '\n') break;
5358 ++i;
5359 }
5360
5361 if (i != 0)
5362 str[i] = '\0';
5363 else
5364 str[i+1] = '\0'; /* keep newline and terminate */
5365 retval += here;
5366 *bytes_read += (bread/8);
5367
5368 SL_RETURN(retval, _("hideout_hex_block"));
5369}
5370
5371/* --- Get offset of first data block. ---
5372 */
5373unsigned long first_hex_block(SL_TICKET fd, unsigned long * max)
5374{
5375 unsigned int i;
5376 long num = 1;
5377 unsigned long lnum;
5378 char c;
5379 int nothex = 0;
5380 unsigned long retval = 0;
5381 unsigned int this_line = 0;
5382 char theline[SH_BUFSIZE];
5383
5384 SL_ENTER(_("first_hex_block"));
5385
5386 *max = 0;
5387
5388 while (1)
5389 {
5390 theline[0] = '\0';
5391 this_line = 0;
5392 c = '\0';
5393 while (c != '\n' && num > 0 && this_line < (sizeof(theline)-1))
5394 {
5395 do {
5396 num = sl_read (fd, &c, 1);
5397 } while (num == 0 && errno == EINTR);
5398 if (num > 0)
5399 theline[this_line] = c;
5400 else
5401 SL_RETURN((0), _("first_hex_block"));
5402 ++this_line;
5403 }
5404 theline[this_line] = '\0';
5405
5406 /* not only 'newline' */
5407 if (this_line > 60)
5408 {
5409 nothex = 0;
5410 i = 0;
5411 while (nothex == 0 && i < (this_line-1))
5412 {
5413 if (! isxdigit((int)theline[i])) nothex = 1;
5414 ++i;
5415 }
5416 if (nothex == 1) retval += this_line;
5417 }
5418 else
5419 {
5420 nothex = 1;
5421 retval += this_line;
5422 }
5423
5424 if (nothex == 0)
5425 {
5426 *max = 0;
5427 do {
5428 do {
5429 num = sl_read (fd, theline, SH_BUFSIZE);
5430 } while (num == 0 && errno == EINTR);
5431 if (num > 0)
5432 {
5433 lnum = (unsigned long) num;
5434 for (i = 0; i < lnum; ++i)
5435 {
5436 c = theline[i];
5437 if (c == '\n' || c == '\t' || c == '\r' || c == ' ')
5438 ;
5439 else if (!isxdigit((int)c))
5440 break;
5441 else
5442 *max += 1;
5443 }
5444 }
5445 } while (num > 0);
5446
5447 *max /= 16;
5448 SL_RETURN((retval), _("first_hex_block"));
5449 }
5450
5451 }
5452 /* SL_RETURN((0), _("first_hex_block")); *//* unreachable */
5453}
5454
5455 /* if !defined(SH_STEALTH_MICRO) */
5456#endif
5457
5458 /* ifdef SH_STEALTH */
5459#endif
5460
5461/*
5462 * anti-debugger code
5463 */
5464#if defined(SCREW_IT_UP)
5465
5466#if defined(HAVE_PTHREAD)
5467
5468static pthread_key_t gSigtrapVariables_key;
5469static pthread_once_t gSigtrapVariables_key_once = PTHREAD_ONCE_INIT;
5470
5471static inline void make_gSigtrapVariables_key()
5472{
5473 (void) pthread_key_create(&gSigtrapVariables_key, free);
5474}
5475
5476struct sh_sigtrap_variables * sh_sigtrap_variables_get()
5477{
5478 void * ptr;
5479
5480 (void) pthread_once(&gSigtrapVariables_key_once, make_gSigtrapVariables_key);
5481
5482 ptr = pthread_getspecific(gSigtrapVariables_key);
5483 if (ptr == NULL) {
5484 ptr = malloc(sizeof(struct sh_sigtrap_variables));
5485 if (ptr == NULL) {
5486 return NULL;
5487 }
5488 (void) pthread_setspecific(gSigtrapVariables_key, ptr);
5489 }
5490
5491 return (struct sh_sigtrap_variables *) ptr;
5492}
5493
5494/* !defined(HAVE_PTHREAD) */
5495#else
5496
5497static struct sh_sigtrap_variables global_sigtrap_variables;
5498struct sh_sigtrap_variables * sh_sigtrap_variables_get()
5499{
5500 return &global_sigtrap_variables;
5501}
5502
5503#endif
5504
5505int sh_sigtrap_max_duration_set (const char * str)
5506{
5507 /* For security (prevent reloading with larger value)
5508 * this value can only be set once.
5509 */
5510 static int once = 0;
5511 int i;
5512
5513 SL_ENTER(_("sh_sigtrap_max_duration_set"));
5514
5515 i = atoi (str);
5516
5517 if (i >= 0 && once == 0)
5518 {
5519 sh.sigtrap_max_duration = i;
5520 once = 1;
5521 }
5522 else
5523 {
5524 SL_RETURN ((-1), _("sh_sigtrap_max_duration_set"));
5525 }
5526 SL_RETURN( (0), _("sh_sigtrap_max_duration_set"));
5527}
5528
5529void sh_sigtrap_handler (int signum)
5530{
5531 struct sh_sigtrap_variables * sigtrap_variables;
5532 sigtrap_variables = sh_sigtrap_variables_get();
5533 if (sigtrap_variables == NULL) {
5534 /* Perhaps, it's better to not die, and to continue using Samhain,
5535 even if this part does not work. */
5536 return;
5537 }
5538
5539#ifdef HAVE_GETTIMEOFDAY
5540 {
5541 struct timeval tv;
5542 long difftv;
5543
5544 gettimeofday(&tv, NULL);
5545 difftv = (tv.tv_sec - sigtrap_variables->save_tv.tv_sec) * 1000000 +
5546 (tv.tv_usec - sigtrap_variables->save_tv.tv_usec);
5547 if (difftv > sh.sigtrap_max_duration)
5548 raise(SIGKILL);
5549 }
5550#endif
5551
5552 sigtrap_variables->not_traced = signum;
5553 return;
5554}
5555#endif
Note: See TracBrowser for help on using the repository browser.