source: trunk/src/sh_unix.c@ 394

Last change on this file since 394 was 383, checked in by katerina, 13 years ago

Fix for ticket #281 (warnings from clang static analyzer).

File size: 125.7 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
1005
1006/* added Tue Feb 22 10:36:44 NFT 2000 Rainer Wichmann */
1007static int tf_add_trusted_user_int(const char * c)
1008{
1009 struct passwd * w;
1010 int count;
1011 uid_t pwid = (uid_t)-1;
1012
1013#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1014 struct passwd pwd;
1015 char * buffer;
1016#endif
1017
1018 SL_ENTER(_("tf_add_trusted_user_int"));
1019
1020 /* First check for a user name.
1021 */
1022#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1023 buffer = SH_ALLOC(SH_PWBUF_SIZE);
1024 sh_getpwnam_r(c, &pwd, buffer, SH_PWBUF_SIZE, &w);
1025#else
1026 w = sh_getpwnam(c);
1027#endif
1028
1029 if ((w != NULL) && ((pwid = w->pw_uid) > 0))
1030 goto succe;
1031
1032 /* Failed, so check for a numerical value.
1033 */
1034 pwid = strtol(c, (char **)NULL, 10);
1035 if (pwid > 0 && pwid < 65535)
1036 goto succe;
1037
1038 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
1039 _("add trusted user"), c);
1040#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1041 SH_FREE(buffer);
1042#endif
1043 SL_RETURN((-1), _("tf_add_trusted_user_int"));
1044
1045 succe:
1046 count = sl_trust_add_user(pwid);
1047#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1048 SH_FREE(buffer);
1049#endif
1050 SL_RETURN((count), _("tf_add_trusted_user_int"));
1051}
1052
1053int tf_add_trusted_user(const char * c)
1054{
1055 int i;
1056 char * q;
1057 char * p = sh_util_strdup (c);
1058#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1059 char * saveptr;
1060#endif
1061
1062 SL_ENTER(_("tf_add_trusted_user"));
1063
1064#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1065 q = strtok_r(p, ", \t", &saveptr);
1066#else
1067 q = strtok(p, ", \t");
1068#endif
1069 if (!q)
1070 {
1071 SH_FREE(p);
1072 SL_RETURN((-1), _("tf_add_trusted_user"));
1073 }
1074 while (q)
1075 {
1076 i = tf_add_trusted_user_int(q);
1077 if (SL_ISERROR(i))
1078 {
1079 SH_FREE(p);
1080 SL_RETURN((i), _("tf_add_trusted_user"));
1081 }
1082#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_STRTOK_R)
1083 q = strtok_r(NULL, ", \t", &saveptr);
1084#else
1085 q = strtok(NULL, ", \t");
1086#endif
1087 }
1088 SH_FREE(p);
1089 SL_RETURN((0), _("tf_add_trusted_user"));
1090}
1091
1092extern uid_t sl_trust_baduid(void);
1093extern gid_t sl_trust_badgid(void);
1094
1095#if defined(HOST_IS_CYGWIN) || defined(__cygwin__) || defined(__CYGWIN32__) || defined(__CYGWIN__)
1096int tf_trust_check (const char * file, int mode)
1097{
1098 (void) file;
1099 (void) mode;
1100 return 0;
1101}
1102#else
1103int tf_trust_check (const char * file, int mode)
1104{
1105 char * tmp;
1106 char * tmp2;
1107 char * p;
1108 int status;
1109 int level;
1110 uid_t ff_euid = (uid_t) -1;
1111
1112 SL_ENTER(_("tf_trust_check"));
1113
1114 if (mode == SL_YESPRIV)
1115 sl_get_euid(&ff_euid);
1116 else
1117 sl_get_ruid(&ff_euid);
1118
1119#if defined(SH_WITH_SERVER)
1120 if (0 == sl_ret_euid()) /* privileges not dropped yet */
1121 {
1122#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1123 struct passwd pwd;
1124 char * buffer = SH_ALLOC(SH_PWBUF_SIZE);
1125 struct passwd * tempres;
1126 sh_getpwnam_r(DEFAULT_IDENT, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
1127#else
1128 struct passwd * tempres = sh_getpwnam(DEFAULT_IDENT);
1129#endif
1130
1131 if (!tempres)
1132 {
1133 dlog(1, FIL__, __LINE__,
1134 _("User %s does not exist. Please add the user to your system.\n"),
1135 DEFAULT_IDENT);
1136 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
1137 }
1138 else
1139 {
1140 ff_euid = tempres->pw_uid;
1141 }
1142#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWNAM_R)
1143 SH_FREE(buffer);
1144#endif
1145 }
1146#endif
1147
1148 status = sl_trustfile_euid(file, ff_euid);
1149
1150 if ( SL_ENONE != status)
1151 {
1152 if (status == SL_ESTAT)
1153 level = SH_ERR_ALL;
1154 else
1155 level = SH_ERR_ERR;
1156
1157 tmp = sh_util_safe_name (file);
1158 p = sl_trust_errfile();
1159 if (p && *p != '\0')
1160 {
1161 tmp2 = sh_util_safe_name (sl_trust_errfile());
1162 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST2,
1163 sl_error_string(status), tmp, tmp2);
1164 SH_FREE(tmp2);
1165 }
1166 else
1167 {
1168 sh_error_handle(level, FIL__, __LINE__, status, MSG_E_TRUST1,
1169 sl_error_string(status), tmp);
1170 }
1171 SH_FREE(tmp);
1172
1173 if (status == SL_EBADUID || status == SL_EBADGID ||
1174 status == SL_EBADOTH || status == SL_ETRUNC ||
1175 status == SL_EINTERNAL )
1176 {
1177 switch (status) {
1178 case SL_EINTERNAL:
1179 dlog(1, FIL__, __LINE__,
1180 _("An internal error occured in the trustfile function.\n"));
1181 break;
1182 case SL_ETRUNC:
1183 tmp = sh_util_safe_name (file);
1184 dlog(1, FIL__, __LINE__,
1185 _("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"),
1186 tmp);
1187 SH_FREE(tmp);
1188 break;
1189 case SL_EBADOTH:
1190 tmp = sh_util_safe_name (file);
1191 p = sl_trust_errfile();
1192 dlog(1, FIL__, __LINE__,
1193 _("The path element: %s\nin the filename: %s is world writeable.\n"),
1194 p, tmp);
1195 SH_FREE(tmp);
1196 break;
1197 case SL_EBADUID:
1198 tmp = sh_util_safe_name (file);
1199 p = sl_trust_errfile();
1200 dlog(1, FIL__, __LINE__,
1201 _("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"),
1202 (UID_CAST)sl_trust_baduid(), p, tmp);
1203 SH_FREE(tmp);
1204 break;
1205 case SL_EBADGID:
1206 tmp = sh_util_safe_name (file);
1207 p = sl_trust_errfile();
1208 dlog(1, FIL__, __LINE__,
1209 _("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"),
1210 p, tmp, (UID_CAST)sl_trust_badgid(),
1211 (UID_CAST)sl_trust_baduid());
1212 SH_FREE(tmp);
1213 break;
1214 default:
1215 break;
1216 }
1217
1218 SL_RETURN((-1), _("tf_trust_check"));
1219 }
1220 }
1221
1222 SL_RETURN((0), _("tf_trust_check"));
1223}
1224#endif
1225
1226#ifdef HAVE_INITGROUPS
1227#ifdef HOST_IS_OSF
1228int sh_unix_initgroups ( char * in_user, gid_t in_gid)
1229#else
1230int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1231#endif
1232{
1233 int status = -1;
1234 status = sh_initgroups (in_user, in_gid);
1235 if (status < 0)
1236 {
1237 if (errno == EPERM)
1238 return 0;
1239 if (errno == EINVAL)
1240 return 0;
1241 return -1;
1242 }
1243 return 0;
1244}
1245#else
1246int sh_unix_initgroups (const char * in_user, gid_t in_gid)
1247{
1248 (void) in_user;
1249 (void) in_gid;
1250 return 0;
1251}
1252#endif
1253
1254#ifdef HAVE_INITGROUPS
1255char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len);
1256int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1257{
1258 int status = -1;
1259 char user[SH_MINIBUF];
1260
1261 SL_ENTER(_("sh_unix_initgroups2"));
1262
1263 if (NULL == sh_unix_getUIDname (SH_ERR_ERR, in_pid, user, sizeof(user)))
1264 SL_RETURN((-1), _("sh_unix_initgroups2"));
1265 status = sh_initgroups (user, in_gid);
1266 if (status < 0)
1267 {
1268 if (errno == EPERM)
1269 status = 0;
1270 if (errno == EINVAL)
1271 status = 0;
1272 }
1273 SL_RETURN((status), _("sh_unix_initgroups2"));
1274}
1275#else
1276int sh_unix_initgroups2 (uid_t in_pid, gid_t in_gid)
1277{
1278 (void) in_pid;
1279 (void) in_gid;
1280 return 0;
1281}
1282#endif
1283
1284void sh_unix_closeall (int fd, int except, int inchild)
1285{
1286 int fdx = fd;
1287#ifdef _SC_OPEN_MAX
1288 int fdlimit = sysconf (_SC_OPEN_MAX);
1289#else
1290#ifdef OPEN_MAX
1291 int fdlimit = OPEN_MAX;
1292#else
1293 int fdlimit = _POSIX_OPEN_MAX;
1294#endif
1295#endif
1296
1297 SL_ENTER(_("sh_unix_closeall"));
1298
1299 /* can't happen - so fix it :-(
1300 */
1301 if (fdlimit < 0)
1302 fdlimit = 20; /* POSIX lower limit */
1303
1304 if (fdlimit > 65536)
1305 fdlimit = 65536;
1306
1307 if (!inchild)
1308 sl_dropall (fdx, except);
1309 else
1310 sl_dropall_dirty (fdx, except);
1311
1312 /* Close everything from fd (inclusive) up to fdlimit (exclusive).
1313 */
1314 while (fd < fdlimit)
1315 {
1316 if (fd == except)
1317 fd++;
1318 else if (slib_do_trace != 0 && fd == slib_trace_fd)
1319 fd++;
1320 else
1321 sl_close_fd(FIL__, __LINE__, fd++);
1322 }
1323
1324 SL_RET0(_("sh_unix_closeall"));
1325}
1326
1327static void sh_unix_setlimits(void)
1328{
1329 struct rlimit limits;
1330
1331 SL_ENTER(_("sh_unix_setlimits"));
1332
1333 limits.rlim_cur = RLIM_INFINITY;
1334 limits.rlim_max = RLIM_INFINITY;
1335
1336#ifdef RLIMIT_CPU
1337 setrlimit (RLIMIT_CPU, &limits);
1338#endif
1339#ifdef RLIMIT_FSIZE
1340 setrlimit (RLIMIT_FSIZE, &limits);
1341#endif
1342#ifdef RLIMIT_DATA
1343 setrlimit (RLIMIT_DATA, &limits);
1344#endif
1345#ifdef RLIMIT_STACK
1346 setrlimit (RLIMIT_STACK, &limits);
1347#endif
1348#ifdef RLIMIT_RSS
1349 setrlimit (RLIMIT_RSS, &limits);
1350#endif
1351#ifdef RLIMIT_NPROC
1352 setrlimit (RLIMIT_NPROC, &limits);
1353#endif
1354#ifdef RLIMIT_MEMLOCK
1355 setrlimit (RLIMIT_MEMLOCK, &limits);
1356#endif
1357
1358#if !defined(SL_DEBUG)
1359 /* no core dumps
1360 */
1361 limits.rlim_cur = 0;
1362 limits.rlim_max = 0;
1363#ifdef RLIMIT_CORE
1364 setrlimit (RLIMIT_CORE, &limits);
1365#endif
1366#else
1367#ifdef RLIMIT_CORE
1368 setrlimit (RLIMIT_CORE, &limits);
1369#endif
1370#endif
1371
1372 limits.rlim_cur = 1024;
1373 limits.rlim_max = 1024;
1374
1375#if defined(RLIMIT_NOFILE)
1376 setrlimit (RLIMIT_NOFILE, &limits);
1377#elif defined(RLIMIT_OFILE)
1378 setrlimit (RLIMIT_OFILE, &limits);
1379#endif
1380
1381 SL_RET0(_("sh_unix_setlimits"));
1382}
1383
1384static void sh_unix_copyenv(void)
1385{
1386 char ** env0 = environ;
1387 char ** env1;
1388 int envlen = 0;
1389 size_t len;
1390
1391 SL_ENTER(_("sh_unix_copyenv"));
1392
1393 while (env0 != NULL && env0[envlen] != NULL) {
1394 /* printf("%2d: %s\n", envlen, env0[envlen]); */
1395 ++envlen;
1396 }
1397 ++envlen;
1398
1399 /* printf("-> %2d: slots allocated\n", envlen); */
1400 env1 = malloc (sizeof(char *) * envlen); /* only once */
1401 if (env1 == NULL)
1402 {
1403 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1404 SL_RET0(_("sh_unix_copyenv"));
1405 }
1406 env0 = environ;
1407 envlen = 0;
1408
1409 while (env0 != NULL && env0[envlen] != NULL) {
1410 len = strlen(env0[envlen]) + 1;
1411 env1[envlen] = malloc (len); /* only once */
1412 if (env1[envlen] == NULL)
1413 {
1414 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1415 SL_RET0(_("sh_unix_copyenv"));
1416 }
1417 sl_strlcpy(env1[envlen], env0[envlen], len);
1418 ++envlen;
1419 }
1420 env1[envlen] = NULL;
1421
1422 environ = env1;
1423 SL_RET0(_("sh_unix_copyenv"));
1424}
1425
1426/* delete all environment variables
1427 */
1428static void sh_unix_zeroenv(void)
1429{
1430 char * c;
1431 char ** env;
1432
1433 SL_ENTER(_("sh_unix_zeroenv"));
1434
1435 sh_unix_copyenv();
1436 env = environ;
1437
1438 while (env != NULL && *env != NULL) {
1439 c = strchr ((*env), '=');
1440#ifdef WITH_MYSQL
1441 /*
1442 * Skip the MYSQL_UNIX_PORT environment variable; MySQL may need it.
1443 */
1444 if (0 == sl_strncmp((*env), _("MYSQL_UNIX_PORT="), 16))
1445 {
1446 ++(env);
1447 continue;
1448 }
1449 if (0 == sl_strncmp((*env), _("MYSQL_TCP_PORT="), 15))
1450 {
1451 ++(env);
1452 continue;
1453 }
1454 if (0 == sl_strncmp((*env), _("MYSQL_HOME="), 11))
1455 {
1456 ++(env);
1457 continue;
1458 }
1459#endif
1460#ifdef WITH_ORACLE
1461 /*
1462 * Skip the ORACLE_HOME environment variable; Oracle may need it.
1463 */
1464 if (0 == sl_strncmp((*env), _("ORACLE_HOME="), 12))
1465 {
1466 ++(env);
1467 continue;
1468 }
1469#endif
1470 /*
1471 * Skip the TZ environment variable.
1472 */
1473 if (0 == sl_strncmp((*env), _("TZ="), 3))
1474 {
1475 ++(env);
1476 continue;
1477 }
1478 ++(env);
1479 if (c != NULL)
1480 {
1481 ++c;
1482 while ((*c) != '\0') {
1483 (*c) = '\0';
1484 ++c;
1485 }
1486 }
1487 }
1488
1489#ifdef HAVE_TZSET
1490 tzset();
1491#endif
1492
1493 SL_RET0(_("sh_unix_zeroenv"));
1494}
1495
1496
1497static void sh_unix_resettimer(void)
1498{
1499 struct itimerval this_timer;
1500
1501 SL_ENTER(_("sh_unix_resettimer"));
1502
1503 this_timer.it_value.tv_sec = 0;
1504 this_timer.it_value.tv_usec = 0;
1505
1506 this_timer.it_interval.tv_sec = 0;
1507 this_timer.it_interval.tv_usec = 0;
1508
1509 setitimer(ITIMER_REAL, &this_timer, NULL);
1510#if !defined(SH_PROFILE)
1511 setitimer(ITIMER_VIRTUAL, &this_timer, NULL);
1512 setitimer(ITIMER_PROF, &this_timer, NULL);
1513#endif
1514
1515 SL_RET0(_("sh_unix_resettimer"));
1516}
1517
1518static void sh_unix_resetsignals(void)
1519{
1520 int sig_num;
1521#ifdef NSIG
1522 int max_sig = NSIG;
1523#else
1524 int max_sig = 255;
1525#endif
1526 int test;
1527 int status;
1528 struct sigaction act;
1529#if !defined(SH_PROFILE)
1530 struct sigaction oldact;
1531#endif
1532
1533 sigset_t set_proc;
1534
1535 SL_ENTER(_("sh_unix_resetsignals"));
1536 /*
1537 * Reset the current signal mask (inherited from parent process).
1538 */
1539
1540 sigfillset(&set_proc);
1541
1542 do {
1543 errno = 0;
1544 test = SH_SETSIGMASK(SIG_UNBLOCK, &set_proc, NULL);
1545 } while (test < 0 && errno == EINTR);
1546
1547 /*
1548 * Reset signal handling.
1549 */
1550
1551 act.sa_handler = SIG_DFL; /* signal action */
1552 sigemptyset( &act.sa_mask ); /* set an empty mask */
1553 act.sa_flags = 0; /* init sa_flags */
1554
1555 for (sig_num = 1; sig_num <= max_sig; ++sig_num)
1556 {
1557#if !defined(SH_PROFILE)
1558 test = retry_sigaction(FIL__, __LINE__, sig_num, &act, &oldact);
1559#else
1560 test = 0;
1561#endif
1562 if ((test == -1) && (errno != EINVAL))
1563 {
1564 char errbuf[SH_ERRBUF_SIZE];
1565 status = errno;
1566 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_SIG,
1567 sh_error_message (status, errbuf, sizeof(errbuf)), sig_num);
1568 }
1569 }
1570
1571 SL_RET0(_("sh_unix_resetsignals"));
1572}
1573
1574/* Get the local hostname (FQDN)
1575 */
1576static char * sh_tolower (char * s)
1577{
1578 char * ret = s;
1579 if (s)
1580 {
1581 for (; *s; ++s)
1582 {
1583 *s = tolower((unsigned char) *s);
1584 }
1585 }
1586 return ret;
1587}
1588
1589
1590#include <sys/socket.h>
1591
1592/* Required for BSD
1593 */
1594#ifdef HAVE_NETINET_IN_H
1595#include <netinet/in.h>
1596#endif
1597
1598#include <arpa/inet.h>
1599
1600const char * sh_unix_h_name (struct hostent * host_entry)
1601{
1602 char ** p;
1603 if (strchr(host_entry->h_name, '.')) {
1604 return host_entry->h_name;
1605 } else {
1606 for (p = host_entry->h_aliases; *p; ++p) {
1607 if (strchr(*p, '.'))
1608 return *p;
1609 }
1610 }
1611 return host_entry->h_name;
1612}
1613
1614/* uname() on FreeBSD is broken, because the 'nodename' buf is too small
1615 * to hold a valid (leftmost) domain label.
1616 */
1617#if defined(HAVE_UNAME) && !defined(HOST_IS_FREEBSD)
1618#include <sys/utsname.h>
1619void sh_unix_localhost()
1620{
1621 struct utsname buf;
1622 int i;
1623 int ddot;
1624 int len;
1625 char * p;
1626 char hostname[256];
1627 char numeric[SH_IP_BUF];
1628 char * canonical;
1629
1630
1631 SL_ENTER(_("sh_unix_localhost"));
1632
1633 (void) uname (&buf);
1634 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1635 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1636 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1637 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1638
1639 /* Workaround for cases where nodename could be
1640 * a truncated FQDN.
1641 */
1642 if (strlen(buf.nodename) == (sizeof(buf.nodename)-1))
1643 {
1644 p = strchr(buf.nodename, '.');
1645 if (NULL != p) {
1646 *p = '\0';
1647 sl_strlcpy(hostname, buf.nodename, 256);
1648 } else {
1649#ifdef HAVE_GETHOSTNAME
1650 if (0 != gethostname(hostname, 256))
1651 {
1652 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1653 _("nodename returned by uname may be truncated"),
1654 _("sh_unix_localhost"));
1655 sl_strlcpy (hostname, buf.nodename, 256);
1656 }
1657 else
1658 {
1659 hostname[255] = '\0';
1660 }
1661#else
1662 sh_error_handle(SH_ERR_WARN, FIL__, __LINE__, 0, MSG_E_SUBGEN,
1663 _("nodename returned by uname may be truncated"),
1664 _("sh_unix_localhost"));
1665 sl_strlcpy(hostname, buf.nodename, 256);
1666#endif
1667 }
1668 }
1669 else
1670 {
1671 sl_strlcpy(hostname, buf.nodename, 256);
1672 }
1673
1674 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1675
1676 if (canonical == NULL)
1677 {
1678 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1679 sh_tolower (sh.host.name);
1680 }
1681 else
1682 {
1683 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1684 SH_FREE(canonical);
1685 }
1686
1687 /* check whether it looks like a FQDN
1688 */
1689 len = sl_strlen(sh.host.name);
1690 ddot = 0;
1691 for (i = 0; i < len; ++i)
1692 if (sh.host.name[i] == '.') ++ddot;
1693
1694 if (ddot == 0)
1695 {
1696 dlog(1, FIL__, __LINE__,
1697 _("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"),
1698 hostname, sh.host.name);
1699 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1700 SL_RET0(_("sh_unix_localhost"));
1701 }
1702
1703 if (sh_ipvx_is_numeric(sh.host.name))
1704 {
1705 dlog(1, FIL__, __LINE__,
1706 _("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"),
1707 hostname, sh.host.name);
1708 }
1709
1710 SL_RET0(_("sh_unix_localhost"));
1711}
1712
1713#else
1714
1715/*
1716 * --FreeBSD code
1717 */
1718#if defined(HAVE_UNAME)
1719#include <sys/utsname.h>
1720#endif
1721void sh_unix_localhost()
1722{
1723#if defined(HAVE_UNAME)
1724 struct utsname buf;
1725#endif
1726 int i;
1727 int ddot;
1728 int len;
1729 char hostname[1024];
1730 char numeric[SH_IP_BUF];
1731 char * canonical;
1732
1733 SL_ENTER(_("sh_unix_localhost"));
1734
1735#if defined(HAVE_UNAME)
1736 (void) uname (&buf);
1737 /* flawfinder: ignore */ /* ff bug, ff sees system() */
1738 sl_strlcpy (sh.host.system, buf.sysname, SH_MINIBUF);
1739 sl_strlcpy (sh.host.release, buf.release, SH_MINIBUF);
1740 sl_strlcpy (sh.host.machine, buf.machine, SH_MINIBUF);
1741#endif
1742
1743 (void) gethostname (hostname, 1024);
1744 hostname[1023] = '\0';
1745
1746 canonical = sh_ipvx_canonical(hostname, numeric, sizeof(numeric));
1747
1748 if (canonical == NULL)
1749 {
1750 sl_strlcpy (sh.host.name, hostname, SH_PATHBUF);
1751 sh_tolower (sh.host.name);
1752 }
1753 else
1754 {
1755 sl_strlcpy (sh.host.name, canonical, SH_PATHBUF);
1756 SH_FREE(canonical);
1757 }
1758
1759 /* check whether it looks like a FQDN
1760 */
1761 len = sl_strlen(sh.host.name);
1762 ddot = 0;
1763 for (i = 0; i < len; ++i)
1764 if (sh.host.name[i] == '.') ++ddot;
1765 if (ddot == 0)
1766 {
1767 dlog(1, FIL__, __LINE__,
1768 _("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"),
1769 hostname, sh.host.name);
1770 sl_strlcpy (sh.host.name, numeric, SH_PATHBUF);
1771 SL_RET0(_("sh_unix_localhost"));
1772 }
1773
1774 if (sh_ipvx_is_numeric(sh.host.name))
1775 {
1776 dlog(1, FIL__, __LINE__,
1777 _("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"),
1778 hostname, sh.host.name);
1779 }
1780
1781 SL_RET0(_("sh_unix_localhost"));
1782}
1783#endif
1784
1785
1786void sh_unix_memlock()
1787{
1788 SL_ENTER(_("sh_unix_memlock"));
1789
1790 /* do this before dropping privileges
1791 */
1792#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
1793 if (skey->mlock_failed == SL_FALSE)
1794 {
1795 if ( (-1) == sh_unix_mlock( FIL__, __LINE__,
1796 (char *) skey, sizeof (sh_key_t)) )
1797 {
1798 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1799 skey->mlock_failed = SL_TRUE;
1800 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1801 }
1802 }
1803#else
1804 if (skey->mlock_failed == SL_FALSE)
1805 {
1806 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1807 skey->mlock_failed = SL_TRUE;
1808 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1809 }
1810#endif
1811
1812 SL_RET0(_("sh_unix_memlock"));
1813}
1814
1815#ifdef SH_WITH_SERVER
1816char * chroot_dir = NULL;
1817
1818int sh_unix_set_chroot(const char * str)
1819{
1820 size_t len;
1821 static int block = 0;
1822
1823 if (block == 1)
1824 return 0;
1825
1826 if (str && *str == '/')
1827 {
1828 len = strlen(str) + 1;
1829 chroot_dir = malloc(strlen(str) + 1); /* only once */
1830 if (!chroot_dir)
1831 {
1832 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1833 return 1;
1834 }
1835 sl_strlcpy(chroot_dir, str, len);
1836 block = 1;
1837 return 0;
1838 }
1839 return 1;
1840}
1841
1842int sh_unix_chroot(void)
1843{
1844 int status;
1845
1846 if (chroot_dir != NULL)
1847 {
1848 status = retry_aud_chdir(FIL__, __LINE__, chroot_dir);
1849 if ( (-1) == status )
1850 {
1851 char errbuf[SH_ERRBUF_SIZE];
1852 status = errno;
1853 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1854 sh_error_message (status, errbuf, sizeof(errbuf)), chroot_dir);
1855 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1856 }
1857 /* flawfinder: ignore */
1858 return (chroot(chroot_dir));
1859 }
1860 return 0;
1861}
1862/* #ifdef SH_WITH_SERVER */
1863#else
1864int sh_unix_chroot(void) { return 0; }
1865#endif
1866
1867/* daemon mode
1868 */
1869static int block_setdeamon = 0;
1870
1871int sh_unix_setdeamon(const char * dummy)
1872{
1873 int res = 0;
1874
1875 SL_ENTER(_("sh_unix_setdeamon"));
1876
1877 if (block_setdeamon != 0)
1878 SL_RETURN((0),_("sh_unix_setdeamon"));
1879
1880 if (dummy == NULL)
1881 sh.flag.isdaemon = ON;
1882 else
1883 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1884
1885 if (sh.flag.opts == S_TRUE)
1886 block_setdeamon = 1;
1887
1888 SL_RETURN(res, _("sh_unix_setdeamon"));
1889}
1890#if defined(HAVE_LIBPRELUDE)
1891#include "sh_prelude.h"
1892#endif
1893
1894int sh_unix_setnodeamon(const char * dummy)
1895{
1896 int res = 0;
1897
1898 SL_ENTER(_("sh_unix_setnodeamon"));
1899
1900 if (block_setdeamon != 0)
1901 SL_RETURN((0),_("sh_unix_setmodeamon"));
1902
1903 if (dummy == NULL)
1904 sh.flag.isdaemon = OFF;
1905 else
1906 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1907
1908 if (sh.flag.opts == S_TRUE)
1909 block_setdeamon = 1;
1910
1911 SL_RETURN(res, _("sh_unix_setnodeamon"));
1912}
1913
1914int sh_unix_init(int goDaemon)
1915{
1916 int status;
1917 uid_t uid;
1918 pid_t oldpid = getpid();
1919#if defined(SH_WITH_SERVER)
1920 extern int sh_socket_open_int (void);
1921#endif
1922 char errbuf[SH_ERRBUF_SIZE];
1923
1924 extern void sh_kill_sub();
1925
1926 SL_ENTER(_("sh_unix_init"));
1927
1928 /* fork twice, exit the parent process
1929 */
1930 if (goDaemon == 1) {
1931
1932 switch (aud_fork(FIL__, __LINE__)) {
1933 case 0: break; /* child process continues */
1934 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
1935 default: /* parent process exits */
1936 sh_kill_sub();
1937 aud__exit(FIL__, __LINE__, 0);
1938 }
1939
1940 /* Child processes do not inherit page locks across a fork.
1941 * Error in next fork would return in this (?) thread of execution.
1942 */
1943 sh_unix_memlock();
1944
1945 setsid(); /* should not fail */
1946 sh.pid = (UINT64) getpid();
1947
1948 switch (aud_fork(FIL__, __LINE__)) {
1949 case 0: break; /* child process continues */
1950 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
1951 default: /* parent process exits */
1952 sh_kill_sub();
1953 aud__exit(FIL__, __LINE__, 0);
1954 }
1955
1956 /* Child processes do not inherit page locks across a fork.
1957 */
1958 sh_unix_memlock();
1959 sh.pid = (UINT64) getpid();
1960
1961 } else {
1962 setsid(); /* should not fail */
1963 }
1964
1965 /* set working directory
1966 */
1967#ifdef SH_PROFILE
1968 status = 0;
1969#else
1970 status = retry_aud_chdir(FIL__, __LINE__, "/");
1971#endif
1972 if ( (-1) == status )
1973 {
1974 status = errno;
1975 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1976 sh_error_message (status, errbuf, sizeof(errbuf)), "/");
1977 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1978 }
1979
1980 /* reset timers
1981 */
1982 sh_unix_resettimer();
1983
1984 /* signal handlers
1985 */
1986 sh_unix_resetsignals();
1987#if defined(SCREW_IT_UP)
1988 sh_sigtrap_prepare();
1989#endif
1990 sh_unix_siginstall (goDaemon);
1991
1992 /* set file creation mask
1993 */
1994 (void) umask (0); /* should not fail */
1995
1996 /* set resource limits to maximum, and
1997 * core dump size to zero
1998 */
1999 sh_unix_setlimits();
2000
2001 /* zero out the environment (like PATH='\0')
2002 */
2003 sh_unix_zeroenv();
2004
2005 if (goDaemon == 1)
2006 {
2007 /* Close first tree file descriptors
2008 */
2009 sl_close_fd (FIL__, __LINE__, 0); /* if running as daemon */
2010 sl_close_fd (FIL__, __LINE__, 1); /* if running as daemon */
2011 sl_close_fd (FIL__, __LINE__, 2); /* if running as daemon */
2012
2013 /* Enable full error logging
2014 */
2015 sh_error_only_stderr (S_FALSE);
2016
2017 /* open first three streams to /dev/null
2018 */
2019 status = aud_open(FIL__, __LINE__, SL_NOPRIV, _("/dev/null"), O_RDWR, 0);
2020 if (status < 0)
2021 {
2022 status = errno;
2023 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2024 sh_error_message(status, errbuf, sizeof(errbuf)), _("open"));
2025 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2026 }
2027
2028 status = retry_aud_dup(FIL__, __LINE__, 0);
2029 if (status >= 0)
2030 retry_aud_dup(FIL__, __LINE__, 0);
2031
2032 if (status < 0)
2033 {
2034 status = errno;
2035 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2036 sh_error_message(status, errbuf, sizeof(errbuf)), _("dup"));
2037 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2038 }
2039
2040 sh_error_enable_unsafe (S_TRUE);
2041#if defined(HAVE_LIBPRELUDE)
2042 sh_prelude_reset ();
2043#endif
2044
2045 /* --- wait until parent has exited ---
2046 */
2047 while (1 == 1)
2048 {
2049 errno = 0;
2050 if (0 > aud_kill (FIL__, __LINE__, oldpid, 0) && errno == ESRCH)
2051 {
2052 break;
2053 }
2054 retry_msleep(0, 1);
2055 }
2056
2057 /* write PID file
2058 */
2059 status = sh_unix_write_pid_file();
2060 if (status < 0)
2061 {
2062 sl_get_euid(&uid);
2063 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_PIDFILE,
2064 (long) uid, sh.srvlog.alt);
2065 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2066 }
2067#if defined(SH_WITH_SERVER)
2068 sh_socket_open_int ();
2069#endif
2070 }
2071 else
2072 {
2073 sh_error_enable_unsafe (S_TRUE);
2074#if defined(HAVE_LIBPRELUDE)
2075 sh_prelude_reset ();
2076#endif
2077#if defined(SH_WITH_SERVER)
2078 sh_socket_open_int ();
2079#endif
2080 }
2081
2082 /* chroot (this is a no-op if no chroot dir is specified
2083 */
2084 status = sh_unix_chroot();
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)), _("chroot"));
2090 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2091 }
2092
2093 /* drop capabilities
2094 */
2095 sl_drop_cap();
2096
2097 SL_RETURN((0),_("sh_unix_init"));
2098}
2099
2100/* --- run a command, securely --- */
2101
2102int sh_unix_run_command (const char * str)
2103{
2104 pid_t pid;
2105 char * arg[4];
2106 char * env[5];
2107 char * path = sh_util_strdup(_("/bin/sh"));
2108
2109 int status = -1;
2110
2111 arg[0] = sh_util_strdup(_("/bin/sh"));
2112 arg[1] = sh_util_strdup(_("-c"));
2113 arg[2] = sh_util_strdup(str);
2114 arg[3] = NULL;
2115
2116 env[0] = sh_util_strdup(_("PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/ucb"));
2117 env[1] = sh_util_strdup(_("SHELL=/bin/sh"));
2118 env[2] = sh_util_strdup(_("IFS= \t\n"));
2119 if (getenv("TZ")) { /* flawfinder: ignore */
2120 char * tz = sh_util_strdup(getenv("TZ")); /* flawfinder: ignore */
2121 size_t tzlen = strlen(tz);
2122 if (SL_TRUE == sl_ok_adds (4, tzlen)) {
2123 env[3] = SH_ALLOC(4+tzlen);
2124 sl_strlcpy(env[3], "TZ=", 4);
2125 sl_strlcat(env[3], tz , 4+tzlen);
2126 } else {
2127 env[3] = NULL;
2128 }
2129 } else {
2130 env[3] = NULL;
2131 }
2132 env[4] = NULL;
2133
2134 pid = fork();
2135
2136 if (pid == (pid_t)(-1))
2137 {
2138 return -1;
2139 }
2140
2141 else if (pid == 0) /* child */
2142 {
2143 memset(skey, 0, sizeof(sh_key_t));
2144 (void) umask(S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
2145 sh_unix_closeall (3, -1, SL_TRUE); /* in child process */
2146 execve(path, arg, env);
2147 _exit(EXIT_FAILURE);
2148 }
2149
2150 else /* parent */
2151 {
2152 int r;
2153
2154 while((r = waitpid(pid, &status, WUNTRACED)) != pid && r != -1) ;
2155
2156#if !defined(USE_UNO)
2157 if (r == -1 || !WIFEXITED(status))
2158 {
2159 status = -1;
2160 }
2161 else
2162 {
2163 status = WEXITSTATUS(status);
2164 }
2165#endif
2166 }
2167
2168 return status;
2169}
2170
2171/********************************************************
2172 *
2173 * TIME
2174 *
2175 ********************************************************/
2176
2177/* Figure out the time offset of the current timezone
2178 * in a portable way.
2179 */
2180char * t_zone(const time_t * xx)
2181{
2182 struct tm aa;
2183 struct tm bb;
2184
2185 int sign = 0;
2186 int diff = 0;
2187 int hh, mm;
2188 static char tz[64];
2189
2190 SL_ENTER(_("t_zone"));
2191
2192#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2193 gmtime_r (xx, &aa);
2194#else
2195 memcpy (&aa, gmtime(xx), sizeof(struct tm));
2196#endif
2197
2198#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2199 localtime_r (xx, &bb);
2200#else
2201 memcpy (&bb, localtime(xx), sizeof(struct tm));
2202#endif
2203
2204 /* Check for datum wrap-around.
2205 */
2206 if (aa.tm_year < bb.tm_year)
2207 sign = (-1);
2208 else if (aa.tm_mon < bb.tm_mon)
2209 sign = (-1);
2210 else if (aa.tm_mday < bb.tm_mday)
2211 sign = (-1);
2212 else if (bb.tm_year < aa.tm_year)
2213 sign = ( 1);
2214 else if (bb.tm_mon < aa.tm_mon)
2215 sign = ( 1);
2216 else if (bb.tm_mday < aa.tm_mday)
2217 sign = ( 1);
2218
2219 diff = aa.tm_hour * 60 + aa.tm_min;
2220 diff = (bb.tm_hour * 60 + bb.tm_min) - diff;
2221 diff = diff - (sign * 24 * 60); /* datum wrap-around correction */
2222 hh = diff / 60;
2223 mm = diff - (hh * 60);
2224 sprintf (tz, _("%+03d%02d"), hh, mm); /* known to fit */
2225
2226 SL_RETURN(tz, _("t_zone"));
2227}
2228
2229unsigned long sh_unix_longtime ()
2230{
2231 return ((unsigned long)time(NULL));
2232}
2233
2234#ifdef HAVE_GETTIMEOFDAY
2235unsigned long sh_unix_notime ()
2236{
2237 struct timeval tv;
2238
2239 gettimeofday (&tv, NULL);
2240
2241 return ((unsigned long)(tv.tv_sec + tv.tv_usec * 10835 + getpid() + getppid()));
2242
2243}
2244#endif
2245
2246static int count_dev_time = 0;
2247
2248void reset_count_dev_time(void)
2249{
2250 count_dev_time = 0;
2251 return;
2252}
2253
2254int sh_unix_settimeserver (const char * address)
2255{
2256
2257 SL_ENTER(_("sh_unix_settimeserver"));
2258
2259 if (address != NULL && count_dev_time < 2
2260 && sl_strlen(address) < SH_PATHBUF)
2261 {
2262 if (count_dev_time == 0)
2263 sl_strlcpy (sh.srvtime.name, address, SH_PATHBUF);
2264 else
2265 sl_strlcpy (sh.srvtime.alt, address, SH_PATHBUF);
2266
2267 ++count_dev_time;
2268 SL_RETURN((0), _("sh_unix_settimeserver"));
2269 }
2270 SL_RETURN((-1), _("sh_unix_settimeserver"));
2271}
2272
2273
2274#ifdef HAVE_NTIME
2275#define UNIXEPOCH 2208988800UL /* difference between Unix time and net time
2276 * The UNIX EPOCH starts in 1970.
2277 */
2278#include <sys/socket.h>
2279#include <netinet/in.h>
2280#include <arpa/inet.h>
2281#include <netdb.h>
2282#include <ctype.h>
2283#endif
2284
2285/* Timeserver service. */
2286/* define is missing on HP-UX 10.20 */
2287#ifndef IPPORT_TIMESERVER
2288#define IPPORT_TIMESERVER 37
2289#endif
2290
2291char * sh_unix_time (time_t thetime, char * buffer, size_t len)
2292{
2293
2294 int status;
2295 char AsciiTime[81]; /* local time */
2296 time_t time_now;
2297 struct tm * time_ptr;
2298#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2299 struct tm time_tm;
2300#endif
2301#ifdef SH_USE_XML
2302 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2303#else
2304 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2305#endif
2306
2307#ifdef HAVE_NTIME
2308 int fd; /* network file descriptor */
2309 u_char net_time[4]; /* remote time in network format */
2310 static int failerr = 0; /* no net time */
2311 int fail = 0; /* no net time */
2312 int errflag;
2313 char errmsg[256];
2314 char error_call[SH_MINIBUF];
2315 int error_num;
2316#endif
2317
2318 SL_ENTER(_("sh_unix_time"));
2319
2320#ifdef HAVE_NTIME
2321 if (thetime == 0)
2322 {
2323 if (sh.srvtime.name[0] == '\0')
2324 {
2325 fail = 1;
2326 (void) time (&time_now);
2327 }
2328 else /* have a timeserver address */
2329 {
2330 /* don't call timeserver more than once per second */
2331 static time_t time_old = 0;
2332 time_t time_new;
2333 static time_t time_saved = 0;
2334 (void) time (&time_new);
2335 if ((time_new == time_old) && (time_saved != 0))
2336 {
2337 time_now = time_saved;
2338 goto end;
2339 }
2340 time_old = time_new;
2341
2342
2343 fd = connect_port_2 (sh.srvtime.name, sh.srvtime.alt,
2344 IPPORT_TIMESERVER,
2345 error_call, &error_num, errmsg, sizeof(errmsg));
2346 if (fd >= 0)
2347 {
2348 if (4 != read_port (fd, (char *) net_time, 4, &errflag, 2))
2349 {
2350 fail = 1;
2351 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2352 MSG_E_NLOST,
2353 _("time"), sh.srvtime.name);
2354 }
2355 sl_close_fd(FIL__, __LINE__, fd);
2356 }
2357 else
2358 {
2359 sh_error_handle ((-1), FIL__, __LINE__, error_num,
2360 MSG_E_NET, errmsg, error_call,
2361 _("time"), sh.srvtime.name);
2362 fail = 1;
2363 }
2364
2365 if (fail == 0)
2366 {
2367 unsigned long ltmp;
2368 UINT32 ttmp;
2369 memcpy(&ttmp, net_time, sizeof(UINT32)); ltmp = ttmp;
2370 time_now = ntohl(ltmp) - UNIXEPOCH;
2371 time_saved = time_now;
2372
2373 if (failerr == 1) {
2374 failerr = 0;
2375 sh_error_handle ((-1), FIL__, __LINE__, 0,
2376 MSG_E_NEST,
2377 _("time"), sh.srvtime.name);
2378 }
2379 }
2380 else
2381 {
2382 (void) time (&time_now);
2383 time_saved = 0;
2384
2385 if (failerr == 0)
2386 {
2387 failerr = 1;
2388 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2389 MSG_SRV_FAIL,
2390 _("time"), sh.srvtime.name);
2391 }
2392 }
2393 end:
2394 ; /* 'label at end of compound statement' */
2395 }
2396 }
2397 else
2398 {
2399 time_now = thetime;
2400 }
2401
2402 /* #ifdef HAVE_NTIME */
2403#else
2404
2405 if (thetime == 0)
2406 {
2407 (void) time (&time_now);
2408 }
2409 else
2410 {
2411 time_now = thetime;
2412 }
2413
2414 /* #ifdef HAVE_NTIME */
2415#endif
2416
2417 if (time_now == (-1) )
2418 {
2419 sl_strlcpy(buffer, _(deftime), len);
2420 SL_RETURN(buffer, _("sh_unix_time"));
2421 }
2422 else
2423 {
2424#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2425 time_ptr = localtime_r (&time_now, &time_tm);
2426#else
2427 time_ptr = localtime (&time_now);
2428#endif
2429 }
2430 if (time_ptr != NULL)
2431 {
2432 status = strftime (AsciiTime, sizeof(AsciiTime),
2433#ifdef SH_USE_XML
2434 _("%Y-%m-%dT%H:%M:%S%%s"),
2435#else
2436 _("[%Y-%m-%dT%H:%M:%S%%s]"),
2437#endif
2438 time_ptr);
2439
2440 sl_snprintf(buffer, len, AsciiTime, t_zone(&time_now));
2441
2442 if ( (status == 0) || (status == sizeof(AsciiTime)) )
2443 {
2444 sl_strlcpy(buffer, _(deftime), len);
2445 SL_RETURN( buffer, _("sh_unix_time"));
2446 }
2447 else
2448 {
2449 SL_RETURN(buffer, _("sh_unix_time"));
2450 }
2451 }
2452
2453 /* last resort
2454 */
2455 sl_strlcpy(buffer, _(deftime), len);
2456 SL_RETURN( buffer, _("sh_unix_time"));
2457}
2458
2459static int sh_unix_use_localtime = S_FALSE;
2460
2461/* whether to use localtime for file timesatams in logs
2462 */
2463int sh_unix_uselocaltime (const char * c)
2464{
2465 int i;
2466 SL_ENTER(_("sh_unix_uselocaltime"));
2467 i = sh_util_flagval(c, &(sh_unix_use_localtime));
2468
2469 SL_RETURN(i, _("sh_unix_uselocaltime"));
2470}
2471
2472char * sh_unix_gmttime (time_t thetime, char * buffer, size_t len)
2473{
2474
2475 int status;
2476
2477 struct tm * time_ptr;
2478#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS)
2479 struct tm time_tm;
2480#endif
2481 char AsciiTime[81]; /* GMT time */
2482#ifdef SH_USE_XML
2483 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2484#else
2485 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2486#endif
2487
2488 SL_ENTER(_("sh_unix_gmttime"));
2489
2490 if (sh_unix_use_localtime == S_FALSE)
2491 {
2492#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2493 time_ptr = gmtime_r (&thetime, &time_tm);
2494#else
2495 time_ptr = gmtime (&thetime);
2496#endif
2497 }
2498 else
2499 {
2500#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2501 time_ptr = localtime_r (&thetime, &time_tm);
2502#else
2503 time_ptr = localtime (&thetime);
2504#endif
2505 }
2506 if (time_ptr != NULL)
2507 {
2508 status = strftime (AsciiTime, 80,
2509#ifdef SH_USE_XML
2510 _("%Y-%m-%dT%H:%M:%S"),
2511#else
2512 _("[%Y-%m-%dT%H:%M:%S]"),
2513#endif
2514 time_ptr);
2515
2516 if ( (status == 0) || (status == 80) )
2517 sl_strlcpy(buffer, _(deftime), len);
2518 else
2519 sl_strlcpy(buffer, AsciiTime, len);
2520 SL_RETURN( buffer, _("sh_unix_gmttime"));
2521 }
2522
2523 /* last resort
2524 */
2525 sl_strlcpy(buffer, _(deftime), len);
2526 SL_RETURN( buffer, _("sh_unix_gmttime"));
2527}
2528
2529
2530char * sh_unix_getUIDdir (int level, uid_t uid, char * out, size_t len)
2531{
2532 struct passwd * tempres;
2533 int status = 0;
2534
2535#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2536 struct passwd pwd;
2537 char * buffer;
2538#endif
2539 char errbuf[SH_ERRBUF_SIZE];
2540
2541 SL_ENTER(_("sh_unix_getUIDdir"));
2542
2543#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2544 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2545 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2546#else
2547 errno = 0;
2548 tempres = sh_getpwuid(uid);
2549 status = errno;
2550#endif
2551
2552 if (tempres == NULL) {
2553 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2554 sh_error_message(status, errbuf, sizeof(errbuf)),
2555 _("getpwuid"), (long) uid, _("completely missing"));
2556#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2557 SH_FREE(buffer);
2558#endif
2559 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2560 }
2561
2562 if (tempres->pw_dir != NULL) {
2563 sl_strlcpy(out, tempres->pw_dir, len);
2564#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2565 SH_FREE(buffer);
2566#endif
2567 SL_RETURN( out, _("sh_unix_getUIDdir"));
2568 } else {
2569 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2570 sh_error_message(status, errbuf, sizeof(errbuf)),
2571 _("getpwuid"), (long) uid, _("pw_dir"));
2572#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2573 SH_FREE(buffer);
2574#endif
2575 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2576 }
2577}
2578
2579/* ------------------- Caching ----------------*/
2580#include "zAVLTree.h"
2581
2582#define CACHE_GID 0
2583#define CACHE_UID 1
2584
2585struct user_id {
2586 char * name;
2587 uid_t id;
2588 struct user_id * next;
2589};
2590
2591static struct user_id * uid_list = NULL;
2592static struct user_id * gid_list = NULL;
2593
2594SH_MUTEX_STATIC(mutex_cache, PTHREAD_MUTEX_INITIALIZER);
2595
2596static void sh_userid_free(struct user_id * item)
2597{
2598 while (item)
2599 {
2600 struct user_id * user = item;
2601 item = item->next;
2602
2603 SH_FREE(user->name);
2604 SH_FREE(user);
2605 }
2606 return;
2607}
2608
2609void sh_userid_destroy ()
2610{
2611 struct user_id * tmp_uid;
2612 struct user_id * tmp_gid;
2613
2614 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2615 tmp_gid = gid_list;
2616 gid_list = NULL;
2617 tmp_uid = uid_list;
2618 uid_list = NULL;
2619 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2620
2621 sh_userid_free(tmp_uid);
2622 sh_userid_free(tmp_gid);
2623 return;
2624}
2625
2626static void sh_userid_additem(struct user_id * list, struct user_id * item)
2627{
2628 if (list)
2629 {
2630 while (list && list->next)
2631 list = list->next;
2632 list->next = item;
2633 }
2634 return;
2635}
2636
2637static void sh_userid_add(uid_t id, char * username, int which)
2638{
2639 size_t len;
2640 struct user_id * user = SH_ALLOC(sizeof(struct user_id));
2641
2642 if (username)
2643 len = strlen(username) + 1;
2644 else
2645 len = 1;
2646
2647 user->name = SH_ALLOC(len);
2648 user->id = id;
2649 if (username)
2650 sl_strlcpy(user->name, username, len);
2651 else
2652 user->name[0] = '\0';
2653 user->next = NULL;
2654
2655 SH_MUTEX_LOCK(mutex_cache);
2656 if (which == CACHE_UID)
2657 {
2658 if (!uid_list)
2659 uid_list = user;
2660 else
2661 sh_userid_additem(uid_list, user);
2662 }
2663 else
2664 {
2665 if (!gid_list)
2666 gid_list = user;
2667 else
2668 sh_userid_additem(gid_list, user);
2669 }
2670 SH_MUTEX_UNLOCK(mutex_cache);
2671
2672 return;
2673}
2674
2675static char * sh_userid_search(struct user_id * list, uid_t id)
2676{
2677 while (list)
2678 {
2679 if (list->id == id)
2680 return list->name;
2681 list = list->next;
2682 }
2683 return NULL;
2684}
2685
2686static char * sh_userid_get (uid_t id, int which, char * out, size_t len)
2687{
2688 char * user = NULL;
2689
2690 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2691 if (which == CACHE_UID)
2692 user = sh_userid_search(uid_list, id);
2693 else
2694 user = sh_userid_search(gid_list, id);
2695 if (user)
2696 {
2697 sl_strlcpy(out, user, len);
2698 user = out;
2699 }
2700 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2701
2702 return user;
2703}
2704
2705/* --------- end caching code --------- */
2706
2707char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len)
2708{
2709 struct passwd * tempres;
2710#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2711 struct passwd pwd;
2712 char * buffer;
2713#endif
2714 int status = 0;
2715 char errbuf[SH_ERRBUF_SIZE];
2716 char * tmp;
2717
2718 SL_ENTER(_("sh_unix_getUIDname"));
2719
2720 tmp = sh_userid_get(uid, CACHE_UID, out, len);
2721
2722 if (tmp)
2723 {
2724 if (tmp[0] != '\0')
2725 {
2726 SL_RETURN( out, _("sh_unix_getUIDname"));
2727 }
2728 else
2729 {
2730 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2731 }
2732 }
2733
2734#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2735 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2736 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2737#else
2738 errno = 0;
2739 tempres = sh_getpwuid(uid);
2740 status = errno;
2741#endif
2742
2743 if (tempres == NULL)
2744 {
2745 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2746 sh_error_message(status, errbuf, sizeof(errbuf)),
2747 _("getpwuid"), (long) uid, _("completely missing"));
2748#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2749 SH_FREE(buffer);
2750#endif
2751 sh_userid_add(uid, NULL, CACHE_UID);
2752 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2753 }
2754
2755
2756 if (tempres->pw_name != NULL)
2757 {
2758
2759 sl_strlcpy(out, tempres->pw_name, len);
2760 sh_userid_add(uid, out, CACHE_UID);
2761
2762#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2763 SH_FREE(buffer);
2764#endif
2765
2766 SL_RETURN( out, _("sh_unix_getUIDname"));
2767 }
2768 else
2769 {
2770 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2771 sh_error_message(status, errbuf, sizeof(errbuf)),
2772 _("getpwuid"), (long) uid, _("pw_user"));
2773#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2774 SH_FREE(buffer);
2775#endif
2776 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2777 }
2778 /* notreached */
2779}
2780
2781char * sh_unix_getGIDname (int level, gid_t gid, char * out, size_t len)
2782{
2783 struct group * tempres;
2784 int status = 0;
2785
2786#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2787 struct group grp;
2788 char * buffer;
2789#endif
2790 char errbuf[SH_ERRBUF_SIZE];
2791 char * tmp;
2792
2793 SL_ENTER(_("sh_unix_getGIDname"));
2794
2795 tmp = sh_userid_get((uid_t)gid, CACHE_GID, out, len);
2796
2797 if (tmp)
2798 {
2799 if (tmp[0] != '\0')
2800 {
2801 SL_RETURN( out, _("sh_unix_getGIDname"));
2802 }
2803 else
2804 {
2805 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2806 }
2807 }
2808
2809#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2810 buffer = SH_ALLOC(SH_GRBUF_SIZE);
2811 status = sh_getgrgid_r(gid, &grp, buffer, SH_GRBUF_SIZE, &tempres);
2812#else
2813 errno = 0;
2814 tempres = sh_getgrgid(gid);
2815 status = errno;
2816#endif
2817
2818 if (tempres == NULL)
2819 {
2820 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2821 sh_error_message(status, errbuf, sizeof(errbuf)),
2822 _("getgrgid"), (long) gid, _("completely missing"));
2823
2824#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2825 SH_FREE(buffer);
2826#endif
2827
2828 sh_userid_add(gid, NULL, CACHE_GID);
2829 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2830 }
2831
2832 if (tempres->gr_name != NULL)
2833 {
2834
2835 sl_strlcpy(out, tempres->gr_name, len);
2836 sh_userid_add((uid_t)gid, out, CACHE_GID);
2837
2838#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2839 SH_FREE(buffer);
2840#endif
2841
2842 SL_RETURN( out, _("sh_unix_getGIDname"));
2843 }
2844 else
2845 {
2846 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2847 sh_error_message(status, errbuf, sizeof(errbuf)),
2848 _("getgrgid"), (long) gid, _("gr_name"));
2849
2850#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2851 SH_FREE(buffer);
2852#endif
2853
2854 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2855 }
2856 /* notreached */
2857}
2858
2859int sh_unix_getUser ()
2860{
2861 char * p;
2862 uid_t seuid, sruid;
2863 char user[USER_MAX];
2864 char dir[SH_PATHBUF];
2865
2866 SL_ENTER(_("sh_unix_getUser"));
2867
2868 seuid = geteuid();
2869
2870 sh.effective.uid = seuid;
2871
2872 p = sh_unix_getUIDdir (SH_ERR_ERR, seuid, dir, sizeof(dir));
2873
2874 if (p == NULL)
2875 SL_RETURN((-1), _("sh_unix_getUser"));
2876 else
2877 {
2878 if (sl_strlen(p) >= SH_PATHBUF) {
2879 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2880 _("getpwuid"), (long) seuid, _("pw_home"));
2881 SL_RETURN((-1), _("sh_unix_getUser"));
2882 } else {
2883 sl_strlcpy ( sh.effective.home, p, SH_PATHBUF);
2884 }
2885 }
2886
2887 sruid = getuid();
2888
2889 sh.real.uid = sruid;
2890
2891 p = sh_unix_getUIDname (SH_ERR_ERR, sruid, user, sizeof(user));
2892 if (p == NULL)
2893 SL_RETURN((-1), _("sh_unix_getUser"));
2894 else
2895 {
2896 if (sl_strlen(p) >= USER_MAX) {
2897 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2898 _("getpwuid"), (long) sruid, _("pw_user"));
2899 SL_RETURN((-1), _("sh_unix_getUser"));
2900 } else {
2901 sl_strlcpy ( sh.real.user, p, USER_MAX);
2902 }
2903 }
2904
2905 p = sh_unix_getUIDdir (SH_ERR_ERR, sruid, dir, sizeof(dir));
2906
2907 if (p == NULL)
2908 SL_RETURN((-1), _("sh_unix_getUser"));
2909 else
2910 {
2911 if (sl_strlen(p) >= SH_PATHBUF) {
2912 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2913 _("getpwuid"), (long) sruid, _("pw_home"));
2914 SL_RETURN((-1), _("sh_unix_getUser"));
2915 } else {
2916 sl_strlcpy ( sh.real.home, p, SH_PATHBUF);
2917 }
2918 }
2919
2920 SL_RETURN((0), _("sh_unix_getUser"));
2921
2922 /* notreached */
2923}
2924
2925
2926int sh_unix_getline (SL_TICKET fd, char * line, int sizeofline)
2927{
2928 register int count;
2929 register int n = 0;
2930 char c;
2931
2932 SL_ENTER(_("sh_unix_getline"));
2933
2934 if (sizeofline < 2) {
2935 line[0] = '\0';
2936 SL_RETURN((0), _("sh_unix_getline"));
2937 }
2938
2939 --sizeofline;
2940
2941 while (n < sizeofline) {
2942
2943 count = sl_read (fd, &c, 1);
2944
2945 /* end of file
2946 */
2947 if (count < 1) {
2948 line[n] = '\0';
2949 n = -1;
2950 break;
2951 }
2952
2953 if (/* c != '\0' && */ c != '\n') {
2954 line[n] = c;
2955 ++n;
2956 } else if (c == '\n') {
2957 if (n > 0) {
2958 line[n] = '\0';
2959 break;
2960 } else {
2961 line[n] = '\n'; /* get newline only if only char on line */
2962 ++n;
2963 line[n] = '\0';
2964 break;
2965 }
2966 } else {
2967 line[n] = '\0';
2968 break;
2969 }
2970
2971 }
2972
2973
2974 line[sizeofline] = '\0'; /* make sure line is terminated */
2975 SL_RETURN((n), _("sh_unix_getline"));
2976}
2977
2978
2979#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
2980
2981/**************************************************************
2982 *
2983 * --- FILE INFO ---
2984 *
2985 **************************************************************/
2986
2987#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
2988
2989#if defined(__linux__)
2990
2991/* --- Determine ext2fs file attributes. ---
2992 */
2993#include <sys/ioctl.h>
2994#if defined(HAVE_EXT2FS_EXT2_FS_H)
2995#include <ext2fs/ext2_fs.h>
2996#else
2997#include <linux/ext2_fs.h>
2998#endif
2999
3000/* __linux__ includes */
3001#endif
3002
3003static
3004int sh_unix_getinfo_attr (char * name,
3005 unsigned long * flags,
3006 char * c_attr,
3007 int fd, struct stat * buf)
3008{
3009
3010/* TAKEN FROM:
3011 *
3012 * lsattr.c - List file attributes on an ext2 file system
3013 *
3014 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
3015 * Laboratoire MASI, Institut Blaise Pascal
3016 * Universite Pierre et Marie Curie (Paris VI)
3017 *
3018 * This file can be redistributed under the terms of the GNU General
3019 * Public License
3020 */
3021
3022#ifdef HAVE_STAT_FLAGS
3023
3024 SL_ENTER(_("sh_unix_getinfo_attr"));
3025
3026 *flags = 0;
3027
3028 /* cast to void to avoid compiler warning about unused parameters */
3029 (void) fd;
3030 (void) name;
3031
3032#ifdef UF_NODUMP
3033 if (buf->st_flags & UF_NODUMP) {
3034 *flags |= UF_NODUMP;
3035 c_attr[0] = 'd';
3036 }
3037#endif
3038#ifdef UF_IMMUTABLE
3039 if (buf->st_flags & UF_IMMUTABLE) {
3040 *flags |= UF_IMMUTABLE;
3041 c_attr[1] = 'i';
3042 }
3043#endif
3044#ifdef UF_APPEND
3045 if (buf->st_flags & UF_APPEND) {
3046 *flags |= UF_APPEND;
3047 c_attr[2] = 'a';
3048 }
3049#endif
3050#ifdef UF_NOUNLINK
3051 if (buf->st_flags & UF_NOUNLINK) {
3052 *flags |= UF_NOUNLINK;
3053 c_attr[3] = 'u';
3054 }
3055#endif
3056#ifdef UF_OPAQUE
3057 if (buf->st_flags & UF_OPAQUE) {
3058 *flags |= UF_OPAQUE;
3059 c_attr[4] = 'o';
3060 }
3061#endif
3062#ifdef SF_ARCHIVED
3063 if (buf->st_flags & SF_ARCHIVED) {
3064 *flags |= SF_ARCHIVED;
3065 c_attr[5] = 'R';
3066 }
3067
3068#endif
3069#ifdef SF_IMMUTABLE
3070 if (buf->st_flags & SF_IMMUTABLE) {
3071 *flags |= SF_IMMUTABLE;
3072 c_attr[6] = 'I';
3073 }
3074#endif
3075#ifdef SF_APPEND
3076 if (buf->st_flags & SF_APPEND) {
3077 *flags |= SF_APPEND;
3078 c_attr[7] = 'A';
3079 }
3080#endif
3081#ifdef SF_NOUNLINK
3082 if (buf->st_flags & SF_NOUNLINK) {
3083 *flags |= SF_NOUNLINK;
3084 c_attr[8] = 'U';
3085 }
3086#endif
3087
3088 /* ! HAVE_STAT_FLAGS */
3089#else
3090
3091#ifdef HAVE_EXT2_IOCTLS
3092 int /* fd, */ r, f;
3093
3094 SL_ENTER(_("sh_unix_getinfo_attr"));
3095
3096 *flags = 0;
3097 (void) buf;
3098
3099 /* open() -> aud_open() R.Wichmann
3100 fd = aud_open (FIL__, __LINE__, SL_YESPRIV, name, O_RDONLY|O_NONBLOCK, 0);
3101 */
3102
3103 if (fd == -1 || name == NULL)
3104 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3105
3106
3107 r = ioctl (fd, EXT2_IOC_GETFLAGS, &f);
3108 /* sl_close_fd (FIL__, __LINE__, fd); */
3109
3110 if (r == -1)
3111 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3112
3113 if (f == 0)
3114 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3115
3116 *flags = f;
3117
3118/* ! HAVE_EXT2_IOCTLS */
3119#else
3120
3121 SL_ENTER(_("sh_unix_getinfo_attr"));
3122
3123 *flags = 0; /* modified by R.Wichmann */
3124
3125/* ! HAVE_EXT2_IOCTLS */
3126#endif
3127/*
3128 * END
3129 *
3130 * lsattr.c - List file attributes on an ext2 file system
3131 */
3132
3133 if (*flags == 0)
3134 goto theend;
3135
3136#ifdef EXT2_SECRM_FL
3137 if ( (*flags & EXT2_SECRM_FL) != 0 ) c_attr[0] = 's';
3138#endif
3139#ifdef EXT2_UNRM_FL
3140 if ( (*flags & EXT2_UNRM_FL) != 0 ) c_attr[1] = 'u';
3141#endif
3142#ifdef EXT2_SYNC_FL
3143 if ( (*flags & EXT2_SYNC_FL) != 0 ) c_attr[2] = 'S';
3144#endif
3145#ifdef EXT2_IMMUTABLE_FL
3146 if ( (*flags & EXT2_IMMUTABLE_FL) != 0) c_attr[3] = 'i';
3147#endif
3148#ifdef EXT2_APPEND_FL
3149 if ( (*flags & EXT2_APPEND_FL) != 0 ) c_attr[4] = 'a';
3150#endif
3151#ifdef EXT2_NODUMP_FL
3152 if ( (*flags & EXT2_NODUMP_FL) != 0 ) c_attr[5] = 'd';
3153#endif
3154#ifdef EXT2_NOATIME_FL
3155 if ( (*flags & EXT2_NOATIME_FL) != 0) c_attr[6] = 'A';
3156#endif
3157#ifdef EXT2_COMPR_FL
3158 if ( (*flags & EXT2_COMPR_FL) != 0 ) c_attr[7] = 'c';
3159#endif
3160
3161#ifdef EXT2_TOPDIR_FL
3162 if ( (*flags & EXT2_TOPDIR_FL) != 0 ) c_attr[8] = 'T';
3163#endif
3164#ifdef EXT2_DIRSYNC_FL
3165 if ( (*flags & EXT2_DIRSYNC_FL) != 0 ) c_attr[9] = 'D';
3166#endif
3167#ifdef EXT2_NOTAIL_FL
3168 if ( (*flags & EXT2_NOTAIL_FL) != 0 ) c_attr[10] = 't';
3169#endif
3170#ifdef EXT2_JOURNAL_DATA_FL
3171 if ( (*flags & EXT2_JOURNAL_DATA_FL) != 0) c_attr[11] = 'j';
3172#endif
3173
3174 theend:
3175 /* ext2 */
3176#endif
3177
3178 c_attr[12] = '\0';
3179
3180 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3181}
3182
3183/* defined(__linux__) || defined(HAVE_STAT_FLAGS) */
3184#endif
3185
3186/* determine file type
3187 */
3188static
3189int sh_unix_getinfo_type (struct stat * buf,
3190 ShFileType * type,
3191 char * c_mode)
3192{
3193 SL_ENTER(_("sh_unix_getinfo_type"));
3194
3195 if ( S_ISREG(buf->st_mode) ) {
3196 (*type) = SH_FILE_REGULAR;
3197 c_mode[0] = '-';
3198 }
3199 else if ( S_ISLNK(buf->st_mode) ) {
3200 (*type) = SH_FILE_SYMLINK;
3201 c_mode[0] = 'l';
3202 }
3203 else if ( S_ISDIR(buf->st_mode) ) {
3204 (*type) = SH_FILE_DIRECTORY;
3205 c_mode[0] = 'd';
3206 }
3207 else if ( S_ISCHR(buf->st_mode) ) {
3208 (*type) = SH_FILE_CDEV;
3209 c_mode[0] = 'c';
3210 }
3211 else if ( S_ISBLK(buf->st_mode) ) {
3212 (*type) = SH_FILE_BDEV;
3213 c_mode[0] = 'b';
3214 }
3215 else if ( S_ISFIFO(buf->st_mode) ) {
3216 (*type) = SH_FILE_FIFO;
3217 c_mode[0] = '|';
3218 }
3219 else if ( S_ISSOCK(buf->st_mode) ) {
3220 (*type) = SH_FILE_SOCKET;
3221 c_mode[0] = 's';
3222 }
3223 else if ( S_ISDOOR(buf->st_mode) ) {
3224 (*type) = SH_FILE_DOOR;
3225 c_mode[0] = 'D';
3226 }
3227 else if ( S_ISPORT(buf->st_mode) ) {
3228 (*type) = SH_FILE_PORT;
3229 c_mode[0] = 'P';
3230 }
3231 else {
3232 (*type) = SH_FILE_UNKNOWN;
3233 c_mode[0] = '?';
3234 }
3235
3236 SL_RETURN(0, _("sh_unix_getinfo_type"));
3237}
3238
3239int sh_unix_get_ftype(char * fullpath)
3240{
3241 char c_mode[CMODE_SIZE];
3242 struct stat buf;
3243 ShFileType type;
3244 int res;
3245
3246 SL_ENTER(_("sh_unix_get_ftype"));
3247
3248 res = retry_lstat(FIL__, __LINE__, fullpath, &buf);
3249
3250 if (res < 0)
3251 SL_RETURN(SH_FILE_UNKNOWN, _("sh_unix_getinfo_type"));
3252
3253 sh_unix_getinfo_type (&buf, &type, c_mode);
3254
3255 SL_RETURN(type, _("sh_unix_get_ftype"));
3256}
3257
3258
3259static
3260int sh_unix_getinfo_mode (struct stat *buf,
3261 unsigned int * mode,
3262 char * c_mode)
3263{
3264
3265 SL_ENTER(_("sh_unix_getinfo_mode"));
3266
3267 (*mode) = buf->st_mode;
3268
3269 /* make 'ls'-like string */
3270
3271 if ( (buf->st_mode & S_IRUSR) != 0 ) c_mode[1] = 'r';
3272 if ( (buf->st_mode & S_IWUSR) != 0 ) c_mode[2] = 'w';
3273 if ( (buf->st_mode & S_IXUSR) != 0 ) {
3274 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 's';
3275 else c_mode[3] = 'x';
3276 } else {
3277 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 'S';
3278 }
3279
3280 if ( (buf->st_mode & S_IRGRP) != 0 ) c_mode[4] = 'r';
3281 if ( (buf->st_mode & S_IWGRP) != 0 ) c_mode[5] = 'w';
3282 if ( (buf->st_mode & S_IXGRP) != 0 ) {
3283 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 's';
3284 else c_mode[6] = 'x';
3285 } else {
3286 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 'S';
3287 }
3288
3289 if ( (buf->st_mode & S_IROTH) != 0 ) c_mode[7] = 'r';
3290 if ( (buf->st_mode & S_IWOTH) != 0 ) c_mode[8] = 'w';
3291#ifdef S_ISVTX /* not POSIX */
3292 if ( (buf->st_mode & S_IXOTH) != 0 ) {
3293 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 't';
3294 else c_mode[9] = 'x';
3295 } else {
3296 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 'T';
3297 }
3298#else
3299 if ( (buf->st_mode & S_IXOTH) != 0 ) c_mode[9] = 'x';
3300#endif
3301
3302 SL_RETURN(0, _("sh_unix_getinfo_mode"));
3303}
3304
3305
3306long IO_Limit = 0;
3307
3308void sh_unix_io_pause ()
3309{
3310 long runtime;
3311 float someval;
3312 unsigned long sometime;
3313
3314 if (IO_Limit == 0)
3315 {
3316 return;
3317 }
3318 else
3319 {
3320 runtime = (long) (time(NULL) - sh.statistics.time_start);
3321
3322 if (runtime > 0 && (long)(sh.statistics.bytes_hashed/runtime) > IO_Limit)
3323 {
3324 someval = sh.statistics.bytes_hashed - (IO_Limit * runtime);
3325 someval /= (float) IO_Limit;
3326 if (someval < 1.0)
3327 {
3328 someval *= 1000; /* milliseconds in a second */
3329 sometime = (unsigned long) someval;
3330 retry_msleep(0, sometime);
3331 }
3332 else
3333 {
3334 sometime = (unsigned long) someval;
3335 retry_msleep (sometime, 0);
3336 }
3337 }
3338 }
3339 return;
3340}
3341
3342int sh_unix_set_io_limit (const char * c)
3343{
3344 long val;
3345
3346 SL_ENTER(_("sh_unix_set_io_limit"));
3347
3348 val = strtol (c, (char **)NULL, 10);
3349 if (val < 0)
3350 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
3351 _("set I/O limit"), c);
3352
3353 val = (val < 0 ? 0 : val);
3354
3355 IO_Limit = val * 1024;
3356 SL_RETURN( 0, _("sh_unix_set_io_limit"));
3357}
3358
3359/* obtain file info
3360 */
3361extern int flag_err_debug;
3362
3363#include "sh_ignore.h"
3364
3365int sh_unix_checksum_size (char * filename, struct stat * fbuf,
3366 char * fileHash, int alert_timeout, SL_TICKET fd)
3367{
3368 file_type * tmpFile;
3369 int status;
3370
3371 SL_ENTER(_("sh_unix_checksum_size"));
3372
3373 tmpFile = SH_ALLOC(sizeof(file_type));
3374 tmpFile->link_path = NULL;
3375
3376 if (sh.flag.checkSum != SH_CHECK_INIT)
3377 {
3378 /* lookup file in database */
3379 status = sh_hash_get_it (filename, tmpFile, NULL);
3380 if (status != 0) {
3381 goto out;
3382 }
3383 }
3384 else
3385 {
3386 tmpFile->size = fbuf->st_size;
3387 }
3388
3389 /* if last < current get checksum */
3390 if (tmpFile->size < fbuf->st_size)
3391 {
3392 char hashbuf[KEYBUF_SIZE];
3393 UINT64 local_length = (UINT64) (tmpFile->size < 0 ? 0 : tmpFile->size);
3394 sl_strlcpy(fileHash,
3395 sh_tiger_generic_hash (filename, fd, &(local_length),
3396 alert_timeout, hashbuf, sizeof(hashbuf)),
3397 KEY_LEN+1);
3398
3399 /* return */
3400 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3401 SH_FREE(tmpFile);
3402 SL_RETURN( 0, _("sh_unix_checksum_size"));
3403 }
3404
3405 out:
3406 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3407 SH_FREE(tmpFile);
3408 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3409 SL_RETURN( -1, _("sh_unix_checksum_size"));
3410}
3411
3412int sh_unix_check_selinux = S_FALSE;
3413int sh_unix_check_acl = S_FALSE;
3414
3415#ifdef USE_ACL
3416
3417#include <sys/acl.h>
3418static char * sh_unix_getinfo_acl (char * path, int fd, struct stat * buf)
3419{
3420 /* system.posix_acl_access, system.posix_acl_default
3421 */
3422 char * out = NULL;
3423 char * collect = NULL;
3424 char * tmp;
3425 char * out_compact;
3426 ssize_t len;
3427 acl_t result;
3428
3429 SL_ENTER(_("sh_unix_getinfo_acl"));
3430
3431 result = (fd == -1) ?
3432 acl_get_file (path, ACL_TYPE_ACCESS) :
3433 acl_get_fd (fd);
3434
3435 if (result)
3436 {
3437 out = acl_to_text (result, &len);
3438 if (out && (len > 0)) {
3439 out_compact = sh_util_acl_compact (out, len);
3440 acl_free(out);
3441 if (out_compact)
3442 {
3443 collect = sh_util_strconcat (_("acl_access:"), out_compact, NULL);
3444 SH_FREE(out_compact);
3445 }
3446 }
3447 acl_free(result);
3448 }
3449
3450
3451 if ( S_ISDIR(buf->st_mode) )
3452 {
3453 result = acl_get_file (path, ACL_TYPE_DEFAULT);
3454
3455 if (result)
3456 {
3457 out = acl_to_text (result, &len);
3458 if (out && (len > 0)) {
3459 out_compact = sh_util_acl_compact (out, len);
3460 acl_free(out);
3461 if (out_compact) {
3462 if (collect) {
3463 tmp = sh_util_strconcat (_("acl_default:"),
3464 out_compact, ":", collect, NULL);
3465 SH_FREE(collect);
3466 }
3467 else {
3468 tmp = sh_util_strconcat (_("acl_default:"), out_compact, NULL);
3469 }
3470 SH_FREE(out_compact);
3471 collect = tmp;
3472 }
3473 }
3474 acl_free(result);
3475 }
3476 }
3477
3478 SL_RETURN((collect),_("sh_unix_getinfo_acl"));
3479}
3480#endif
3481
3482#ifdef USE_XATTR
3483
3484#include <attr/xattr.h>
3485static char * sh_unix_getinfo_xattr_int (char * path, int fd, char * name)
3486{
3487 char * out = NULL;
3488 char * tmp = NULL;
3489 size_t size = 256;
3490 ssize_t result;
3491
3492 SL_ENTER(_("sh_unix_getinfo_xattr_int"));
3493
3494 out = SH_ALLOC(size);
3495
3496 result = (fd == -1) ?
3497 lgetxattr (path, name, out, size-1) :
3498 fgetxattr (fd, name, out, size-1);
3499
3500 if (result == -1 && errno == ERANGE)
3501 {
3502 SH_FREE(out);
3503 result = (fd == -1) ?
3504 lgetxattr (path, name, NULL, 0) :
3505 fgetxattr (fd, name, NULL, 0);
3506 size = result + 1;
3507 out = SH_ALLOC(size);
3508 result = (fd == -1) ?
3509 lgetxattr (path, name, out, size-1) :
3510 fgetxattr (fd, name, out, size-1);
3511 }
3512
3513 if ((result > 0) && ((size_t)result < size))
3514 {
3515 out[size-1] = '\0';
3516 tmp = out;
3517 }
3518 else
3519 {
3520 SH_FREE(out);
3521 }
3522
3523 SL_RETURN((tmp),_("sh_unix_getinfo_xattr_int"));
3524}
3525
3526
3527static char * sh_unix_getinfo_xattr (char * path, int fd, struct stat * buf)
3528{
3529 /* system.posix_acl_access, system.posix_acl_default, security.selinux
3530 */
3531 char * tmp;
3532 char * out = NULL;
3533 char * collect = NULL;
3534
3535 SL_ENTER(_("sh_unix_getinfo_xattr"));
3536
3537#ifdef USE_ACL
3538 /*
3539 * we need the acl_get_fd/acl_get_file functions, getxattr will only
3540 * yield the raw bytes
3541 */
3542 if (sh_unix_check_acl == S_TRUE)
3543 {
3544 out = sh_unix_getinfo_acl(path, fd, buf);
3545
3546 if (out)
3547 {
3548 collect = out;
3549 }
3550 }
3551#else
3552 (void) buf;
3553#endif
3554
3555 if (sh_unix_check_selinux == S_TRUE)
3556 {
3557 out = sh_unix_getinfo_xattr_int(path, fd, _("security.selinux"));
3558
3559 if (out)
3560 {
3561 if (collect) {
3562 tmp = sh_util_strconcat(_("selinux:"), out, ":", collect, NULL);
3563 SH_FREE(collect);
3564 }
3565 else {
3566 tmp = sh_util_strconcat(_("selinux:"), out, NULL);
3567 }
3568 SH_FREE(out);
3569 collect = tmp;
3570 }
3571 }
3572
3573 SL_RETURN((collect),_("sh_unix_getinfo_xattr"));
3574}
3575#endif
3576
3577#ifdef USE_XATTR
3578int sh_unix_setcheckselinux (const char * c)
3579{
3580 int i;
3581 SL_ENTER(_("sh_unix_setcheckselinux"));
3582 i = sh_util_flagval(c, &(sh_unix_check_selinux));
3583
3584 SL_RETURN(i, _("sh_unix_setcheckselinux"));
3585}
3586#endif
3587
3588#ifdef USE_ACL
3589int sh_unix_setcheckacl (const char * c)
3590{
3591 int i;
3592 SL_ENTER(_("sh_unix_setcheckacl"));
3593 i = sh_util_flagval(c, &(sh_unix_check_acl));
3594
3595 SL_RETURN(i, _("sh_unix_setcheckacl"));
3596}
3597#endif
3598
3599#ifdef HAVE_LIBZ
3600#include <zlib.h>
3601#endif
3602
3603
3604static void * sh_dummy_filename;
3605static void * sh_dummy_tmp;
3606static void * sh_dummy_tmp2;
3607
3608int sh_unix_getinfo (int level, const char * filename, file_type * theFile,
3609 char * fileHash, int policy)
3610{
3611 char timestr[81];
3612 long runtim;
3613 struct stat buf;
3614 struct stat lbuf;
3615 struct stat fbuf;
3616 volatile int stat_return;
3617 volatile int stat_errno = 0;
3618
3619 ShFileType type;
3620 unsigned int mode;
3621 char * tmp;
3622 char * tmp2;
3623
3624 char * linknamebuf;
3625 volatile int linksize;
3626
3627 extern int get_the_fd (SL_TICKET ticket);
3628
3629 volatile SL_TICKET rval_open;
3630 volatile int err_open = 0;
3631
3632 volatile int fd;
3633 volatile int fstat_return;
3634 volatile int fstat_errno = 0;
3635 volatile int try = 0;
3636
3637 sh_string * content = NULL;
3638
3639 time_t tend;
3640 time_t tstart;
3641
3642
3643 char * path = NULL;
3644
3645 volatile int alert_timeout = 120;
3646
3647 path = theFile->fullpath;
3648
3649 SL_ENTER(_("sh_unix_getinfo"));
3650
3651 if (!MODI_INITIALIZED(theFile->check_mask))
3652 {
3653 tmp2 = sh_util_safe_name (theFile->fullpath);
3654 SH_MUTEX_LOCK(mutex_thread_nolog);
3655 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_E_SUBGPATH,
3656 _("Uninitialized check mask"), _("sh_unix_getinfo"),
3657 tmp2);
3658 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3659 SH_FREE(tmp2);
3660 }
3661
3662 /* Take the address to keep gcc from putting it into a register.
3663 * Avoids the 'clobbered by longjmp' warning.
3664 */
3665 sh_dummy_filename = (void *) &filename;
3666 sh_dummy_tmp = (void *) &tmp;
3667 sh_dummy_tmp2 = (void *) &tmp2;
3668
3669 /* --- Stat the file, and get checksum. ---
3670 */
3671 tstart = time(NULL);
3672
3673 stat_return = retry_lstat (FIL__, __LINE__,
3674 path /* theFile->fullpath */, &buf);
3675
3676 if (stat_return)
3677 stat_errno = errno;
3678
3679 theFile->link_path = NULL;
3680
3681 try_again:
3682
3683 fd = -1;
3684 fstat_return = -1;
3685 rval_open = -1;
3686
3687 if (stat_return == 0 && S_ISREG(buf.st_mode))
3688 {
3689 rval_open = sl_open_fastread (FIL__, __LINE__,
3690 path /* theFile->fullpath */, SL_YESPRIV);
3691 if (SL_ISERROR(rval_open))
3692 {
3693 char * stale = sl_check_stale();
3694
3695 if (stale)
3696 {
3697 SH_MUTEX_LOCK(mutex_thread_nolog);
3698 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, err_open, MSG_E_SUBGEN,
3699 stale, _("sh_unix_getinfo_open"));
3700 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3701 }
3702
3703 if (errno == EBADF && try == 0) /* obsolete, but we keep this, just in case */
3704 {
3705 ++try;
3706 goto try_again;
3707 }
3708 err_open = errno;
3709 }
3710
3711 alert_timeout = 120; /* this is per 8K block now ! */
3712
3713 if (path[1] == 'p' && path[5] == '/' && path[2] == 'r' &&
3714 path[3] == 'o' && path[4] == 'c' && path[0] == '/')
3715 {
3716 /* seven is magic */
3717 alert_timeout = 7;
3718 }
3719
3720 fd = get_the_fd(rval_open);
3721 }
3722
3723 tend = time(NULL);
3724
3725 /* An unprivileged user may slow lstat/open to a crawl
3726 * with clever path/symlink setup
3727 */
3728 if ((tend - tstart) > (time_t) /* 60 */ 6)
3729 {
3730 tmp2 = sh_util_safe_name (theFile->fullpath);
3731 SH_MUTEX_LOCK(mutex_thread_nolog);
3732 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_TOOLATE,
3733 (long)(tend - tstart), tmp2);
3734 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3735 SH_FREE(tmp2);
3736 }
3737
3738 if (fd >= 0)
3739 {
3740 fstat_return = retry_fstat (FIL__, __LINE__, fd, &fbuf);
3741
3742 if (fstat_return)
3743 {
3744 char * stale;
3745
3746 fstat_errno = errno;
3747
3748 stale = sl_check_stale();
3749
3750 if (stale)
3751 {
3752 SH_MUTEX_LOCK(mutex_thread_nolog);
3753 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, fstat_errno,
3754 MSG_E_SUBGEN,
3755 stale, _("sh_unix_getinfo_fstat"));
3756 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3757 }
3758
3759 if (try == 0) /* obsolete, but we keep this, just in case */
3760 {
3761 ++try;
3762 sl_close(rval_open);
3763 goto try_again;
3764 }
3765 }
3766 }
3767 else
3768 {
3769 fd = -1;
3770 }
3771
3772
3773 /* --- case 1: lstat failed ---
3774 */
3775 if (stat_return != 0)
3776 {
3777 stat_return = errno;
3778 if (!SL_ISERROR(rval_open))
3779 sl_close(rval_open);
3780 if (sh.flag.checkSum == SH_CHECK_INIT ||
3781 (sh_hash_have_it (theFile->fullpath) >= 0 &&
3782 (!SH_FFLAG_REPORTED_SET(theFile->file_reported))))
3783 {
3784 if (S_FALSE == sh_ignore_chk_del(theFile->fullpath)) {
3785 char errbuf[SH_ERRBUF_SIZE];
3786 uid_t euid;
3787 (void) sl_get_euid(&euid);
3788 tmp2 = sh_util_safe_name (theFile->fullpath);
3789 SH_MUTEX_LOCK(mutex_thread_nolog);
3790 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3791 _("lstat"),
3792 sh_error_message (stat_errno, errbuf, sizeof(errbuf)),
3793 (long) euid,
3794 tmp2);
3795 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3796 SH_FREE(tmp2);
3797 }
3798 }
3799 SL_RETURN((-1),_("sh_unix_getinfo"));
3800 }
3801
3802 /* --- case 2: not a regular file ---
3803 */
3804 else if (! S_ISREG(buf.st_mode))
3805 {
3806 if (fileHash != NULL)
3807 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3808 }
3809
3810 /* --- case 3a: a regular file, fstat ok ---
3811 */
3812 else if (fstat_return == 0 &&
3813 buf.st_mode == fbuf.st_mode &&
3814 buf.st_ino == fbuf.st_ino &&
3815 buf.st_uid == fbuf.st_uid &&
3816 buf.st_gid == fbuf.st_gid &&
3817 buf.st_dev == fbuf.st_dev )
3818 {
3819 if (fileHash != NULL)
3820 {
3821 if ((theFile->check_mask & MODI_CHK) == 0 ||
3822 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3823 (UINT64) fbuf.st_mode, rval_open))
3824 {
3825 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3826 }
3827 else if ((theFile->check_mask & MODI_PREL) != 0 &&
3828 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3829 alert_timeout, theFile->fullpath))
3830 {
3831 if (0 != sh_prelink_run (theFile->fullpath,
3832 fileHash, alert_timeout))
3833 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3834 }
3835 else
3836 {
3837 char hashbuf[KEYBUF_SIZE];
3838 UINT64 length_nolim = TIGER_NOLIM;
3839
3840 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3841 {
3842 sl_init_content (rval_open, fbuf.st_size);
3843 }
3844
3845 sl_strlcpy(fileHash,
3846 sh_tiger_generic_hash (theFile->fullpath,
3847 rval_open, &length_nolim,
3848 alert_timeout,
3849 hashbuf, sizeof(hashbuf)),
3850 KEY_LEN+1);
3851
3852 content = sl_get_content(rval_open);
3853 content = sh_string_copy(content);
3854
3855 if ((theFile->check_mask & MODI_SGROW) != 0)
3856 {
3857 fbuf.st_size = (off_t) length_nolim;
3858 buf.st_size = fbuf.st_size;
3859 sl_rewind(rval_open);
3860 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3861 &fileHash[KEY_LEN + 1],
3862 alert_timeout, rval_open);
3863 }
3864 }
3865 }
3866 }
3867
3868 /* --- case 3b: a regular file, fstat ok, but different ---
3869 */
3870 else if (fstat_return == 0 && S_ISREG(fbuf.st_mode))
3871 {
3872 memcpy (&buf, &fbuf, sizeof( struct stat ));
3873
3874 if (fileHash != NULL)
3875 {
3876 if ((theFile->check_mask & MODI_CHK) == 0 ||
3877 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3878 (UINT64) fbuf.st_mode, rval_open))
3879 {
3880 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3881 }
3882 else if (policy == SH_LEVEL_PRELINK &&
3883 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3884 alert_timeout, theFile->fullpath))
3885 {
3886 if (0 != sh_prelink_run (theFile->fullpath,
3887 fileHash, alert_timeout))
3888 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3889 }
3890 else
3891 {
3892 char hashbuf[KEYBUF_SIZE];
3893 UINT64 length_nolim = TIGER_NOLIM;
3894
3895 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3896 {
3897 sl_init_content (rval_open, fbuf.st_size);
3898 }
3899
3900 sl_strlcpy(fileHash,
3901 sh_tiger_generic_hash (theFile->fullpath, rval_open,
3902 &length_nolim,
3903 alert_timeout,
3904 hashbuf, sizeof(hashbuf)),
3905 KEY_LEN + 1);
3906
3907 content = sl_get_content(rval_open);
3908 content = sh_string_copy(content);
3909
3910 if ((theFile->check_mask & MODI_SGROW) != 0)
3911 {
3912 fbuf.st_size = (off_t) length_nolim;
3913 buf.st_size = fbuf.st_size;
3914 sl_rewind(rval_open);
3915 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3916 &fileHash[KEY_LEN + 1],
3917 alert_timeout, rval_open);
3918 }
3919 }
3920 }
3921 }
3922
3923 /* --- case 4: a regular file, fstat failed ---
3924 */
3925
3926 else /* fstat_return != 0 or !S_ISREG(fbuf.st_mode) or open() failed */
3927 {
3928 uid_t euid;
3929
3930 if (fileHash != NULL)
3931 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3932
3933 if ((theFile->check_mask & MODI_CHK) != 0)
3934 {
3935 tmp2 = sh_util_safe_name (theFile->fullpath);
3936
3937
3938 if (fd >= 0 && fstat_return != 0)
3939 {
3940 char errbuf[SH_ERRBUF_SIZE];
3941 (void) sl_get_euid(&euid);
3942
3943 SH_MUTEX_LOCK(mutex_thread_nolog);
3944 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3945 _("fstat"),
3946 sh_error_message (fstat_errno, errbuf, sizeof(errbuf)),
3947 (long) euid,
3948 tmp2);
3949 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3950 }
3951 else if (fd >= 0 && !S_ISREG(fbuf.st_mode))
3952 {
3953 SH_MUTEX_LOCK(mutex_thread_nolog);
3954 sh_error_handle (level, FIL__, __LINE__, fstat_errno,
3955 MSG_E_NOTREG, tmp2);
3956 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3957 }
3958 else
3959 {
3960 char errbuf[SH_ERRBUF_SIZE];
3961 char errbuf2[SH_ERRBUF_SIZE];
3962 sl_strlcpy(errbuf, sl_error_string(rval_open), sizeof(errbuf));
3963 sh_error_message(err_open, errbuf2, sizeof(errbuf2));
3964 SH_MUTEX_LOCK(mutex_thread_nolog);
3965 sh_error_handle (level, FIL__, __LINE__, err_open,
3966 MSG_E_READ, errbuf, errbuf2, tmp2);
3967 SH_MUTEX_UNLOCK(mutex_thread_nolog);
3968 }
3969 SH_FREE(tmp2);
3970 }
3971 }
3972
3973
3974 /* --- Determine file type. ---
3975 */
3976 memset (theFile->c_mode, '-', CMODE_SIZE-1);
3977 theFile->c_mode[CMODE_SIZE-1] = '\0';
3978
3979 memset (theFile->link_c_mode, '-', CMODE_SIZE-1);
3980 theFile->link_c_mode[CMODE_SIZE-1] = '\0';
3981
3982 sh_unix_getinfo_type (&buf, &type, theFile->c_mode);
3983 theFile->type = type;
3984
3985#if defined(__linux__) || defined(HAVE_STAT_FLAGS)
3986
3987 /* --- Determine file attributes. ---
3988 */
3989 memset (theFile->c_attributes, '-', ATTRBUF_SIZE);
3990 theFile->c_attributes[ATTRBUF_USED] = '\0';
3991 theFile->attributes = 0;
3992
3993#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
3994 if (theFile->c_mode[0] != 'c' && theFile->c_mode[0] != 'b' &&
3995 theFile->c_mode[0] != 'l' )
3996 sh_unix_getinfo_attr(theFile->fullpath,
3997 &theFile->attributes, theFile->c_attributes,
3998 fd, &buf);
3999#endif
4000#endif
4001
4002#if defined(USE_XATTR) && defined(USE_ACL)
4003 if (sh_unix_check_selinux == S_TRUE || sh_unix_check_acl == S_TRUE)
4004 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4005#elif defined(USE_XATTR)
4006 if (sh_unix_check_selinux == S_TRUE)
4007 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
4008#elif defined(USE_ACL)
4009 if (sh_unix_check_acl == S_TRUE)
4010 theFile->attr_string = sh_unix_getinfo_acl (theFile->fullpath, fd, &buf);
4011#else
4012 theFile->attr_string = NULL;
4013#endif
4014
4015 if (!SL_ISERROR(rval_open))
4016 sl_close(rval_open);
4017
4018
4019 /* --- I/O limit. ---
4020 */
4021 if (IO_Limit > 0)
4022 {
4023 runtim = (long) (time(NULL) - sh.statistics.time_start);
4024
4025 if (runtim > 0 && (long)(sh.statistics.bytes_hashed/runtim) > IO_Limit)
4026 retry_msleep(1, 0);
4027 }
4028
4029 /* --- Determine permissions. ---
4030 */
4031 sh_unix_getinfo_mode (&buf, &mode, theFile->c_mode);
4032
4033 /* --- Trivia. ---
4034 */
4035 theFile->dev = buf.st_dev;
4036 theFile->ino = buf.st_ino;
4037 theFile->mode = buf.st_mode;
4038 theFile->hardlinks = buf.st_nlink;
4039 theFile->owner = buf.st_uid;
4040 theFile->group = buf.st_gid;
4041 theFile->rdev = buf.st_rdev;
4042 theFile->size = buf.st_size;
4043 theFile->blksize = (unsigned long) buf.st_blksize;
4044 theFile->blocks = (unsigned long) buf.st_blocks;
4045 theFile->atime = buf.st_atime;
4046 theFile->mtime = buf.st_mtime;
4047 theFile->ctime = buf.st_ctime;
4048
4049
4050 /* --- Owner and group. ---
4051 */
4052
4053 if (NULL == sh_unix_getGIDname(SH_ERR_ALL, buf.st_gid, theFile->c_group, GROUP_MAX+1)) {
4054
4055 tmp2 = sh_util_safe_name (theFile->fullpath);
4056
4057 if (policy == SH_LEVEL_ALLIGNORE)
4058 {
4059 SH_MUTEX_LOCK(mutex_thread_nolog);
4060 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4061 MSG_FI_NOGRP,
4062 (long) buf.st_gid, tmp2);
4063 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4064 }
4065 else
4066 {
4067 SH_MUTEX_LOCK(mutex_thread_nolog);
4068 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4069 MSG_FI_NOGRP,
4070 (long) buf.st_gid, tmp2);
4071 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4072 }
4073 SH_FREE(tmp2);
4074 sl_snprintf(theFile->c_group, GROUP_MAX+1, "%d", (long) buf.st_gid);
4075 }
4076
4077
4078 if (NULL == sh_unix_getUIDname(SH_ERR_ALL, buf.st_uid, theFile->c_owner, USER_MAX+1)) {
4079
4080 tmp2 = sh_util_safe_name (theFile->fullpath);
4081
4082 if (policy == SH_LEVEL_ALLIGNORE)
4083 {
4084 SH_MUTEX_LOCK(mutex_thread_nolog);
4085 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4086 MSG_FI_NOUSR,
4087 (long) buf.st_uid, tmp2);
4088 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4089 }
4090 else
4091 {
4092 SH_MUTEX_LOCK(mutex_thread_nolog);
4093 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4094 MSG_FI_NOUSR,
4095 (long) buf.st_uid, tmp2);
4096 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4097 }
4098 SH_FREE(tmp2);
4099 sl_snprintf(theFile->c_owner, USER_MAX+1, "%d", (long) buf.st_uid);
4100 }
4101
4102 /* --- Output the file. ---
4103 */
4104 if (flag_err_debug == SL_TRUE)
4105 {
4106 tmp2 = sh_util_safe_name ((filename == NULL) ?
4107 theFile->fullpath : filename);
4108 (void) sh_unix_time(theFile->mtime, timestr, sizeof(timestr));
4109 SH_MUTEX_LOCK(mutex_thread_nolog);
4110 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LIST,
4111 theFile->c_mode,
4112 theFile->hardlinks,
4113 theFile->c_owner,
4114 theFile->c_group,
4115 (unsigned long) theFile->size,
4116 timestr,
4117 tmp2);
4118 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4119 SH_FREE(tmp2);
4120 }
4121
4122 /* --- Check for links. ---
4123 */
4124 if (theFile->c_mode[0] == 'l')
4125 {
4126 linknamebuf = SH_ALLOC(PATH_MAX);
4127
4128 /* flawfinder: ignore */
4129 linksize = readlink (theFile->fullpath, linknamebuf, PATH_MAX-1);
4130
4131 if (linksize < (PATH_MAX-1) && linksize >= 0)
4132 linknamebuf[linksize] = '\0';
4133 else
4134 linknamebuf[PATH_MAX-1] = '\0';
4135
4136 if (linksize < 0)
4137 {
4138 char errbuf[SH_ERRBUF_SIZE];
4139 linksize = errno;
4140 tmp2 = sh_util_safe_name (theFile->fullpath);
4141 SH_MUTEX_LOCK(mutex_thread_nolog);
4142 sh_error_handle (level, FIL__, __LINE__, linksize, MSG_FI_RDLNK,
4143 sh_error_message (linksize, errbuf, sizeof(errbuf)), tmp2);
4144 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4145 SH_FREE(tmp2);
4146 SH_FREE(linknamebuf);
4147 theFile->link_path = sh_util_strdup("-");
4148 SL_RETURN((-1),_("sh_unix_getinfo"));
4149 }
4150
4151 if (linknamebuf[0] == '/')
4152 {
4153 theFile->link_path = sh_util_strdup (linknamebuf);
4154 }
4155 else
4156 {
4157 tmp = sh_util_dirname(theFile->fullpath);
4158 if (tmp) {
4159 theFile->link_path = SH_ALLOC(PATH_MAX);
4160 sl_strlcpy (theFile->link_path, tmp, PATH_MAX);
4161 SH_FREE(tmp);
4162 } else {
4163 theFile->link_path = SH_ALLOC(PATH_MAX);
4164 theFile->link_path[0] = '\0';
4165 }
4166 /*
4167 * Only attach '/' if not root directory. Handle "//", which
4168 * according to POSIX is implementation-defined, and may be
4169 * different from "/" (however, three or more '/' will collapse
4170 * to one).
4171 */
4172 tmp = theFile->link_path; while (*tmp == '/') ++tmp;
4173 if (*tmp != '\0')
4174 {
4175 sl_strlcat (theFile->link_path, "/", PATH_MAX);
4176 }
4177 sl_strlcat (theFile->link_path, linknamebuf, PATH_MAX);
4178 }
4179
4180 /* stat the link
4181 */
4182 stat_return = retry_lstat (FIL__, __LINE__, theFile->link_path, &lbuf);
4183
4184 /* check for error
4185 */
4186 if (stat_return != 0)
4187 {
4188 stat_return = errno;
4189 tmp = sh_util_safe_name (theFile->fullpath);
4190 tmp2 = sh_util_safe_name (theFile->link_path);
4191 if (stat_return != ENOENT)
4192 {
4193 uid_t euid;
4194 char errbuf[SH_ERRBUF_SIZE];
4195
4196 (void) sl_get_euid(&euid);
4197 SH_MUTEX_LOCK(mutex_thread_nolog);
4198 sh_error_handle (level, FIL__, __LINE__, stat_return,
4199 MSG_FI_STAT,
4200 _("lstat"),
4201 sh_error_message (stat_return,errbuf, sizeof(errbuf)),
4202 (long) euid,
4203 tmp2);
4204 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4205 }
4206 else
4207 {
4208 /* a dangling link -- everybody seems to have plenty of them
4209 */
4210 SH_MUTEX_LOCK(mutex_thread_nolog);
4211 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_DLNK,
4212 tmp, tmp2);
4213 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4214 }
4215 theFile->linkisok = BAD;
4216 SH_FREE(tmp);
4217 SH_FREE(tmp2);
4218 SH_FREE(linknamebuf);
4219 /*
4220 * changed Tue Feb 10 16:16:13 CET 2004:
4221 * add dangling symlinks into database
4222 * SL_RETURN((-1),_("sh_unix_getinfo"));
4223 */
4224 theFile->linkmode = 0;
4225 SL_RETURN((0),_("sh_unix_getinfo"));
4226 }
4227
4228 theFile->linkisok = GOOD;
4229
4230
4231 /* --- Determine file type. ---
4232 */
4233 sh_unix_getinfo_type (&lbuf, &type, theFile->link_c_mode);
4234 theFile->type = type;
4235
4236 /* --- Determine permissions. ---
4237 */
4238 sh_unix_getinfo_mode (&lbuf, &mode, theFile->link_c_mode);
4239 theFile->linkmode = lbuf.st_mode;
4240
4241 /* --- Output the link. ---
4242 */
4243 if (theFile->linkisok == GOOD)
4244 {
4245 tmp2 = sh_util_safe_name (linknamebuf);
4246 SH_MUTEX_LOCK(mutex_thread_nolog);
4247 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LLNK,
4248 theFile->link_c_mode, tmp2);
4249 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4250 SH_FREE(tmp2);
4251 }
4252 SH_FREE(linknamebuf);
4253 }
4254 else /* not a link */
4255 {
4256 if (content)
4257 {
4258#ifdef HAVE_LIBZ
4259 unsigned long clen;
4260 unsigned char * compressed;
4261#ifdef HAVE_COMPRESSBOUND
4262 clen = compressBound(sh_string_len(content));
4263#else
4264 if (sh_string_len(content) > 10*SH_TXT_MAX)
4265 clen = SH_TXT_MAX;
4266 else
4267 clen = 13 + (int)(1.0001*sh_string_len(content));
4268#endif
4269 compressed = SH_ALLOC(clen);
4270 if (Z_OK == compress(compressed, &clen,
4271 (unsigned char *) sh_string_str(content),
4272 sh_string_len(content)))
4273 {
4274 if (clen < SH_TXT_MAX)
4275 {
4276 sh_util_base64_enc_alloc (&(theFile->link_path),
4277 (char *) compressed, clen);
4278 }
4279 else
4280 {
4281 char tmsg[128];
4282 char * tpath = sh_util_safe_name (theFile->fullpath);
4283 sl_snprintf(tmsg, sizeof(tmsg),
4284 _("compressed file too large (%lu bytes)"),
4285 clen);
4286 SH_MUTEX_LOCK(mutex_thread_nolog);
4287 sh_error_handle (SH_ERR_WARN, FIL__, __LINE__, -1,
4288 MSG_E_SUBGPATH, tmsg,
4289 _("sh_unix_getinfo"), tpath);
4290 SH_MUTEX_UNLOCK(mutex_thread_nolog);
4291 SH_FREE(tpath);
4292 }
4293 }
4294 SH_FREE(compressed);
4295#endif
4296 sh_string_destroy(&content);
4297 }
4298 }
4299 SL_RETURN((0),_("sh_unix_getinfo"));
4300}
4301
4302/* #if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE) */
4303#endif
4304
4305int sh_unix_unlock(char * lockfile, char * flag)
4306{
4307 int error = 0;
4308
4309 SL_ENTER(_("sh_unix_unlock"));
4310
4311 if (sh.flag.isdaemon == S_FALSE && flag == NULL)
4312 SL_RETURN((0),_("sh_unix_unlock"));
4313
4314 /* --- Logfile is not locked to us. ---
4315 */
4316 if (sh.flag.islocked == BAD && flag != NULL)
4317 SL_RETURN((-1),_("sh_unix_unlock"));
4318
4319 /* --- Check whether the directory is secure. ---
4320 */
4321 if (0 != tf_trust_check (lockfile, SL_YESPRIV))
4322 SL_RETURN((-1),_("sh_unix_unlock"));
4323
4324 /* --- Delete the lock file. ---
4325 */
4326 error = retry_aud_unlink (FIL__, __LINE__, lockfile);
4327
4328 if (error == 0)
4329 {
4330 if (flag != NULL)
4331 sh.flag.islocked = BAD; /* not locked anymore */
4332 }
4333 else if (flag != NULL)
4334 {
4335 char errbuf[SH_ERRBUF_SIZE];
4336 error = errno;
4337 sh_error_handle ((-1), FIL__, __LINE__, error, MSG_E_UNLNK,
4338 sh_error_message(error, errbuf, sizeof(errbuf)),
4339 lockfile);
4340 SL_RETURN((-1),_("sh_unix_unlock"));
4341 }
4342 SL_RETURN((0),_("sh_unix_unlock"));
4343}
4344
4345int sh_unix_check_piddir (char * pidpath)
4346{
4347 static struct stat buf;
4348 int status = 0;
4349 char * pid_dir;
4350
4351 SL_ENTER(_("sh_unix_check_piddir"));
4352
4353 pid_dir = sh_util_dirname (pidpath);
4354
4355 status = retry_lstat (FIL__, __LINE__, pid_dir, &buf);
4356
4357 if (status < 0 && errno == ENOENT)
4358 {
4359 status = mkdir (pid_dir, 0777);
4360 if (status < 0)
4361 {
4362 sh_error_handle ((-1), FIL__, __LINE__, status,
4363 MSG_E_SUBGEN,
4364 _("Cannot create PID directory"),
4365 _("sh_unix_check_piddir"));
4366 SH_FREE(pid_dir);
4367 SL_RETURN((-1),_("sh_unix_check_piddir"));
4368 }
4369 }
4370 else if (!S_ISDIR(buf.st_mode))
4371 {
4372 sh_error_handle ((-1), FIL__, __LINE__, status,
4373 MSG_E_SUBGEN,
4374 _("Path of PID directory refers to a non-directory object"),
4375 _("sh_unix_check_piddir"));
4376 SH_FREE(pid_dir);
4377 SL_RETURN((-1),_("sh_unix_check_piddir"));
4378 }
4379 SH_FREE(pid_dir);
4380 SL_RETURN((0),_("sh_unix_check_piddir"));
4381}
4382
4383int sh_unix_lock (char * lockfile, char * flag)
4384{
4385 int filed;
4386 int errnum;
4387 char myPid[64];
4388 SL_TICKET fd;
4389 extern int get_the_fd (SL_TICKET ticket);
4390
4391 SL_ENTER(_("sh_unix_lock"));
4392
4393 sprintf (myPid, "%ld\n", (long) sh.pid); /* known to fit */
4394
4395 if (flag == NULL) /* PID file, check for directory */
4396 {
4397 if (0 != sh_unix_check_piddir (lockfile))
4398 {
4399 SL_RETURN((-1),_("sh_unix_lock"));
4400 }
4401 }
4402
4403 fd = sl_open_safe_rdwr (FIL__, __LINE__,
4404 lockfile, SL_YESPRIV); /* fails if file exists */
4405
4406 if (!SL_ISERROR(fd))
4407 {
4408 errnum = sl_write (fd, myPid, sl_strlen(myPid));
4409 filed = get_the_fd(fd);
4410 fchmod (filed, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
4411 sl_close (fd);
4412
4413 if (!SL_ISERROR(errnum))
4414 {
4415 if (flag != NULL)
4416 sh.flag.islocked = GOOD;
4417 SL_RETURN((0),_("sh_unix_lock"));
4418 }
4419 }
4420
4421 TPT((0, FIL__, __LINE__, _("msg=<open pid file failed>\n")));
4422 if (flag != NULL)
4423 sh.flag.islocked = BAD;
4424 SL_RETURN((-1),_("sh_unix_lock"));
4425
4426 /* notreached */
4427}
4428
4429
4430/* check whether file is locked
4431 */
4432int sh_unix_test_and_lock (char * filename, char * lockfile)
4433{
4434 static struct stat buf;
4435 int status = 0;
4436
4437
4438 SL_TICKET fd;
4439 char line_in[128];
4440
4441 SL_ENTER(_("sh_unix_test_and_lock"));
4442
4443 status = retry_lstat (FIL__, __LINE__, lockfile, &buf);
4444
4445 /* --- No lock file found, try to lock. ---
4446 */
4447
4448 if (status < 0 && errno == ENOENT)
4449 {
4450 if (0 == sh_unix_lock (lockfile, filename))
4451 {
4452 if (filename != NULL)
4453 sh.flag.islocked = GOOD;
4454 SL_RETURN((0),_("sh_unix_test_and_lock"));
4455 }
4456 else
4457 {
4458 sh_error_handle ((-1), FIL__, __LINE__, status,
4459 MSG_E_SUBGEN,
4460 (filename == NULL) ? _("Cannot create PID file (1)") : _("Cannot create lock file (1)"),
4461 _("sh_unix_test_and_lock"));
4462 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4463 }
4464 }
4465 else if (status == 0 && buf.st_size == 0)
4466 {
4467 if (filename != NULL)
4468 sh.flag.islocked = GOOD;
4469 sh_unix_unlock (lockfile, filename);
4470 if (filename != NULL)
4471 sh.flag.islocked = BAD;
4472 if (0 == sh_unix_lock (lockfile, filename))
4473 {
4474 if (filename != NULL)
4475 sh.flag.islocked = GOOD;
4476 SL_RETURN((0),_("sh_unix_test_and_lock"));
4477 }
4478 else
4479 {
4480 sh_error_handle ((-1), FIL__, __LINE__, status,
4481 MSG_E_SUBGEN,
4482 (filename == NULL) ? _("Cannot create PID file (2)") : _("Cannot create lock file (2)"),
4483 _("sh_unix_test_and_lock"));
4484 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4485 }
4486 }
4487
4488 /* --- Check on lock. ---
4489 */
4490
4491 if (status >= 0)
4492 {
4493 fd = sl_open_read (FIL__, __LINE__, lockfile, SL_YESPRIV);
4494 if (SL_ISERROR(fd))
4495 sh_error_handle ((-1), FIL__, __LINE__, fd,
4496 MSG_E_SUBGEN,
4497 (filename == NULL) ? _("Cannot open PID file for read") : _("Cannot open lock file for read"),
4498 _("sh_unix_test_and_lock"));
4499 }
4500 else
4501 fd = -1;
4502
4503 if (!SL_ISERROR(fd))
4504 {
4505 /* read the PID in the lock file
4506 */
4507 status = sl_read (fd, line_in, sizeof(line_in));
4508 line_in[sizeof(line_in)-1] = '\0';
4509
4510 /* convert to numeric
4511 */
4512 if (status > 0)
4513 {
4514 errno = 0;
4515 status = strtol(line_in, (char **)NULL, 10);
4516 if (errno == ERANGE || status <= 0)
4517 {
4518 sh_error_handle ((-1), FIL__, __LINE__, status,
4519 MSG_E_SUBGEN,
4520 (filename == NULL) ? _("Bad PID in PID file") : _("Bad PID in lock file"),
4521 _("sh_unix_test_and_lock"));
4522
4523 status = -1;
4524 }
4525 }
4526 else
4527 {
4528 sh_error_handle ((-1), FIL__, __LINE__, status,
4529 MSG_E_SUBGEN,
4530 (filename == NULL) ? _("Cannot read PID file") : _("Cannot read lock file"),
4531 _("sh_unix_test_and_lock"));
4532 }
4533 sl_close(fd);
4534
4535 if (status > 0 && (unsigned int) status == sh.pid)
4536 {
4537 if (filename != NULL)
4538 sh.flag.islocked = GOOD;
4539 SL_RETURN((0),_("sh_unix_test_and_lock"));
4540 }
4541
4542
4543 /* --- Check whether the process exists. ---
4544 */
4545 if (status > 0)
4546 {
4547 errno = 0;
4548 status = aud_kill (FIL__, __LINE__, status, 0);
4549
4550 /* Does not exist, so remove the stale lock
4551 * and create a new one.
4552 */
4553 if (status < 0 && errno == ESRCH)
4554 {
4555 if (filename != NULL)
4556 sh.flag.islocked = GOOD;
4557 if (0 != sh_unix_unlock(lockfile, filename) && (filename !=NULL))
4558 sh.flag.islocked = BAD;
4559 else
4560 {
4561 if (0 == sh_unix_lock (lockfile, filename))
4562 {
4563 if (filename != NULL)
4564 sh.flag.islocked = GOOD;
4565 SL_RETURN((0),_("sh_unix_test_and_lock"));
4566 }
4567 else
4568 {
4569 sh_error_handle ((-1), FIL__, __LINE__, status,
4570 MSG_E_SUBGEN,
4571 (filename == NULL) ? _("Cannot create PID file (3)") : _("Cannot create lock file (3)"),
4572 _("sh_unix_test_and_lock"));
4573 }
4574 if (filename != NULL)
4575 sh.flag.islocked = BAD;
4576 }
4577 }
4578 else
4579 {
4580 sh_error_handle ((-1), FIL__, __LINE__, status,
4581 MSG_E_SUBGEN,
4582 (filename == NULL) ? _("Cannot remove stale PID file, PID may be a running process") : _("Cannot remove stale lock file, PID may be a running process"),
4583 _("sh_unix_test_and_lock"));
4584 if (filename != NULL)
4585 sh.flag.islocked = BAD;
4586 }
4587 }
4588 }
4589 SL_RETURN((-1),_("sh_unix_testlock"));
4590}
4591
4592/* write the PID file
4593 */
4594int sh_unix_write_pid_file()
4595{
4596 return sh_unix_test_and_lock(NULL, sh.srvlog.alt);
4597}
4598
4599/* write lock for filename
4600 */
4601int sh_unix_write_lock_file(char * filename)
4602{
4603 size_t len;
4604 int res;
4605 char * lockfile;
4606
4607 if (filename == NULL)
4608 return (-1);
4609
4610 len = sl_strlen(filename);
4611 if (sl_ok_adds(len, 6))
4612 len += 6;
4613 lockfile = SH_ALLOC(len);
4614 sl_strlcpy(lockfile, filename, len);
4615 sl_strlcat(lockfile, _(".lock"), len);
4616 res = sh_unix_test_and_lock(filename, lockfile);
4617 SH_FREE(lockfile);
4618 return res;
4619}
4620
4621/* rm lock for filename
4622 */
4623int sh_unix_rm_lock_file(char * filename)
4624{
4625 size_t len;
4626 int res;
4627 char * lockfile;
4628
4629 if (filename == NULL)
4630 return (-1);
4631
4632 len = sl_strlen(filename);
4633 if (sl_ok_adds(len, 6))
4634 len += 6;
4635 lockfile = SH_ALLOC(len);
4636 sl_strlcpy(lockfile, filename, len);
4637 sl_strlcat(lockfile, _(".lock"), len);
4638
4639 res = sh_unix_unlock(lockfile, filename);
4640 SH_FREE(lockfile);
4641 return res;
4642}
4643
4644/* rm lock for filename
4645 */
4646int sh_unix_rm_pid_file()
4647{
4648 return sh_unix_unlock(sh.srvlog.alt, NULL);
4649}
4650
4651/* Test whether file exists
4652 */
4653int sh_unix_file_exists(char * path)
4654{
4655 struct stat buf;
4656
4657 SL_ENTER(_("sh_unix_file_exists"));
4658
4659 if (0 == retry_lstat(FIL__, __LINE__, path, &buf))
4660 SL_RETURN( S_TRUE, _("sh_unix_file_exists"));
4661 else
4662 SL_RETURN( S_FALSE, _("sh_unix_file_exists"));
4663}
4664
4665
4666/* Test whether file exists, is a character device, and allows read
4667 * access.
4668 */
4669int sh_unix_device_readable(int fd)
4670{
4671 struct stat buf;
4672
4673 SL_ENTER(_("sh_unix_device_readable"));
4674
4675 if (retry_fstat(FIL__, __LINE__, fd, &buf) == -1)
4676 SL_RETURN( (-1), _("sh_unix_device_readable"));
4677 else if ( S_ISCHR(buf.st_mode) && 0 != (S_IROTH & buf.st_mode) )
4678 SL_RETURN( (0), _("sh_unix_device_readable"));
4679 else
4680 SL_RETURN( (-1), _("sh_unix_device_readable"));
4681}
4682
4683static char preq[16];
4684
4685/* return true if database is remote
4686 */
4687int file_is_remote ()
4688{
4689 static int init = 0;
4690 struct stat buf;
4691
4692 SL_ENTER(_("file_is_remote"));
4693
4694 if (init == 0)
4695 {
4696 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4697 ++init;
4698 }
4699 if (0 == sl_strncmp (sh.data.path, preq, 15))
4700 {
4701 if (sh.data.path[15] != '\0') /* should be start of path */
4702 {
4703 if (0 == stat(&(sh.data.path[15]), &buf))
4704 {
4705 SL_RETURN( S_FALSE, _("file_is_remote"));
4706 }
4707 }
4708 SL_RETURN( S_TRUE, _("file_is_remote"));
4709 }
4710 SL_RETURN( S_FALSE, _("file_is_remote"));
4711}
4712
4713/* Return the path to the configuration/database file.
4714 */
4715char * file_path(char what, char flag)
4716{
4717 static int init = 0;
4718
4719 SL_ENTER(_("file_path"));
4720
4721 if (init == 0)
4722 {
4723 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4724 ++init;
4725 }
4726
4727 switch (what)
4728 {
4729
4730 case 'C':
4731 if (0 == sl_strncmp (sh.conf.path, preq, 15))
4732 {
4733#if defined(SH_WITH_SERVER)
4734 if (sh.flag.isserver == S_TRUE && sl_strlen(sh.conf.path) == 15)
4735 SL_RETURN( NULL, _("file_path"));
4736 if (sh.flag.isserver == S_TRUE)
4737 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4738#endif
4739 if (flag == 'R')
4740 SL_RETURN( preq, _("file_path"));
4741 if (flag == 'I')
4742 {
4743 if (sl_strlen(sh.conf.path) == 15)
4744 SL_RETURN( NULL, _("file_path"));
4745 else
4746 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4747 }
4748 SL_RETURN ( preq, _("file_path"));
4749 }
4750 else
4751 SL_RETURN( sh.conf.path, _("file_path"));
4752 /* break; *//* unreachable */
4753
4754 case 'D':
4755 if (0 == sl_strncmp (sh.data.path, preq, 15))
4756 {
4757 if (flag == 'R')
4758 SL_RETURN( preq, _("file_path"));
4759 if (flag == 'W' && sl_strlen(sh.data.path) == 15)
4760 SL_RETURN (NULL, _("file_path"));
4761 if (flag == 'W')
4762 SL_RETURN( &(sh.data.path[15]), _("file_path"));
4763 }
4764 else
4765 SL_RETURN( sh.data.path, _("file_path"));
4766 break;
4767
4768 default:
4769 SL_RETURN( NULL, _("file_path"));
4770 }
4771
4772 return NULL; /* notreached */
4773}
4774/************************************************/
4775/**** Mlock Utilities ****/
4776/************************************************/
4777
4778#include <limits.h>
4779
4780int sh_unix_pagesize()
4781{
4782 int pagesize = 4096;
4783#if defined(_SC_PAGESIZE)
4784 pagesize = sysconf(_SC_PAGESIZE);
4785#elif defined(_SC_PAGE_SIZE)
4786 pagesize = sysconf(_SC_PAGE_SIZE);
4787#elif defined(HAVE_GETPAGESIZE)
4788 pagesize = getpagesize();
4789#elif defined(PAGESIZE)
4790 pagesize = PAGESIZE;
4791#endif
4792
4793 return ((pagesize > 0) ? pagesize : 4096);
4794}
4795
4796typedef struct sh_page_lt {
4797 unsigned long page_start;
4798 int page_refcount;
4799 char file[64];
4800 int line;
4801 struct sh_page_lt * next;
4802} sh_page_l;
4803
4804sh_page_l * sh_page_locked = NULL;
4805volatile int page_locking = 0;
4806
4807unsigned long sh_unix_lookup_page (void * in_addr, size_t len, int * num_pages)
4808{
4809 int pagesize = sh_unix_pagesize();
4810 unsigned long addr = (unsigned long) in_addr;
4811
4812 unsigned long pagebase;
4813 unsigned long pagediff;
4814 unsigned long pagenum = addr / pagesize;
4815
4816 SL_ENTER(_("sh_unix_lookup_page"));
4817#if 0
4818 fprintf(stderr, "mlock: --> base %ld, pagenum: %ld\n",
4819 addr, pagenum);
4820#endif
4821
4822 /* address of first page
4823 */
4824 pagebase = pagenum * pagesize;
4825
4826 /* number of pages
4827 */
4828 pagediff = (addr + len) - pagebase;
4829 pagenum = pagediff / pagesize;
4830 if (pagenum * pagesize < pagediff)
4831 ++pagenum;
4832
4833#if 0
4834 fprintf(stderr, "mlock: --> pagebase %ld, pagediff %ld, (addr + len) %ld\n",
4835 pagebase, pagediff, (addr + len));
4836#endif
4837
4838 *num_pages = pagenum;
4839 SL_RETURN((pagebase), _("sh_unix_lookup_page"));
4840}
4841
4842
4843#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4844
4845SH_MUTEX_STATIC(mutex_mlock,PTHREAD_MUTEX_INITIALIZER);
4846
4847int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4848{
4849 int num_pages;
4850 int status = 0;
4851 int pagesize;
4852 sh_page_l * page_list;
4853 unsigned long addr;
4854#ifdef TEST_MLOCK
4855 int i = 0;
4856#endif
4857
4858 SL_ENTER(_("sh_unix_mlock"));
4859
4860 /* There's no cancellation point here, except if tracing is on
4861 */
4862 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4863
4864 page_list = sh_page_locked;
4865
4866 if (0 != page_locking)
4867 {
4868 status = -1;
4869 goto exit_mlock;
4870 }
4871
4872 page_locking = 1;
4873
4874 pagesize = sh_unix_pagesize();
4875 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4876
4877#ifdef TEST_MLOCK
4878 fprintf(stderr, "mlock: addr %ld, base %ld, pages: %d, length %d\n",
4879 (unsigned long) in_addr, addr, num_pages, len);
4880#endif
4881
4882 /* increase refcount of locked pages
4883 * addr is first page; num_pages is #(consecutive pages) to lock
4884 */
4885
4886 while ((page_list != NULL) && (num_pages > 0))
4887 {
4888#ifdef TEST_MLOCK
4889 fprintf(stderr, "mlock: check page %d: %ld [%d]\n",
4890 i, page_list->page_start, page_list->page_refcount);
4891#endif
4892 if (page_list->page_start == addr)
4893 {
4894 page_list->page_refcount += 1;
4895 num_pages -= 1;
4896 addr += pagesize;
4897#ifdef TEST_MLOCK
4898 fprintf(stderr, "mlock: found page %d: %ld [%d], next page %ld\n",
4899 i, page_list->page_start, page_list->page_refcount, addr);
4900#endif
4901 }
4902#ifdef TEST_MLOCK
4903 ++i;
4904#endif
4905 page_list = page_list->next;
4906 }
4907
4908 /* mlock some more pages, if needed
4909 */
4910 while (num_pages > 0)
4911 {
4912#ifdef TEST_MLOCK
4913 fprintf(stderr, "mlock: lock page %d: mlock %ld [num_pages %d]\n",
4914 i, addr, num_pages);
4915 ++i;
4916#endif
4917 page_list = SH_ALLOC(sizeof(sh_page_l));
4918 page_list->page_start = addr;
4919 page_list->page_refcount = 1;
4920 sl_strlcpy(page_list->file, file, 64);
4921 page_list->line = line;
4922 status = mlock( (void *) addr, pagesize);
4923 if (status != 0)
4924 {
4925#ifdef TEST_MLOCK
4926 char errbuf[SH_ERRBUF_SIZE];
4927 fprintf(stderr, "mlock: error: %s\n",
4928 sh_error_message(errno, errbuf, sizeof(errbuf)));
4929#endif
4930 SH_FREE(page_list);
4931 page_locking = 0;
4932 goto exit_mlock;
4933 }
4934 page_list->next = sh_page_locked;
4935 sh_page_locked = page_list;
4936 num_pages -= 1;
4937 addr += pagesize;
4938 }
4939 page_locking = 0;
4940
4941 exit_mlock:
4942 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
4943
4944 SL_RETURN((status), _("sh_unix_mlock"));
4945}
4946#else
4947int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4948{
4949 (void) file; (void) line;
4950 (void) in_addr; (void) len;
4951 return -1;
4952}
4953#endif
4954
4955#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4956int sh_unix_munlock (void * in_addr, size_t len)
4957{
4958 int num_pages;
4959 int unlocked;
4960 int status;
4961 int pagesize;
4962 sh_page_l * page_list;
4963 sh_page_l * page_last;
4964 unsigned long addr;
4965
4966 int test_count;
4967 int test_status;
4968 int test_pages;
4969
4970#ifdef TEST_MLOCK
4971 int i = 0;
4972#endif
4973
4974 SL_ENTER(_("sh_unix_munlock"));
4975
4976 /* There's no cancellation point here, except if tracing is on
4977 */
4978 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4979
4980 unlocked = 0;
4981 status = 0;
4982 page_list = sh_page_locked;
4983
4984 if (0 != page_locking)
4985 {
4986 status = -1;
4987 goto exit_munlock;
4988 }
4989 page_locking = 1;
4990
4991 pagesize = sh_unix_pagesize();
4992 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4993
4994#ifdef TEST_MLOCK
4995 fprintf(stderr, "munlock: in_addr %ld, addr %ld, pages: %d, length %d\n",
4996 (unsigned long) in_addr, addr, num_pages, len);
4997#endif
4998
4999 test_pages = num_pages;
5000
5001 /* reduce refcount of locked pages
5002 * addr is first page; num_pages is #(consecutive pages) to lock
5003 */
5004 while ((page_list != NULL) && (num_pages > 0))
5005 {
5006#ifdef TEST_MLOCK
5007 fprintf(stderr, "munlock: page %d: %ld [%d]\n",
5008 i, page_list->page_start, page_list->page_refcount);
5009#endif
5010
5011 test_status = 0;
5012 for (test_count = 0; test_count < test_pages; ++test_count)
5013 {
5014 if (page_list->page_start == (addr + (test_count * pagesize)))
5015 {
5016 test_status = 1;
5017 break;
5018 }
5019 }
5020
5021 if (test_status == 1)
5022 {
5023 page_list->page_refcount -= 1;
5024 if (page_list->page_refcount == 0)
5025 {
5026 status = munlock ( (void *) addr, pagesize);
5027 ++unlocked;
5028 }
5029 num_pages -= 1;
5030#ifdef TEST_MLOCK
5031 fprintf(stderr,
5032 "munlock: page %d: %ld [refcount %d], refcount reduced\n",
5033 i, page_list->page_start, page_list->page_refcount);
5034#endif
5035 }
5036#ifdef TEST_MLOCK
5037 ++i;
5038#endif
5039 page_list = page_list->next;
5040 }
5041
5042#ifdef TEST_MLOCK
5043 i = 0;
5044#endif
5045
5046 if (unlocked > 0)
5047 {
5048 page_list = sh_page_locked;
5049 page_last = sh_page_locked;
5050
5051 while ((page_list != NULL) && (unlocked > 0))
5052 {
5053 if (page_list->page_refcount == 0)
5054 {
5055#ifdef TEST_MLOCK
5056 fprintf(stderr, "munlock: remove page %d: %ld [refcount %d]\n",
5057 i, page_list->page_start, page_list->page_refcount);
5058#endif
5059 if (page_last != page_list)
5060 {
5061 page_last->next = page_list->next;
5062 SH_FREE(page_list);
5063 page_list = page_last->next;
5064 }
5065 else
5066 {
5067 page_last = page_list->next;
5068 if (page_list == sh_page_locked)
5069 sh_page_locked = page_list->next;
5070 SH_FREE(page_list);
5071 page_list = page_last;
5072 }
5073 --unlocked;
5074 }
5075 else
5076 {
5077#ifdef TEST_MLOCK
5078 fprintf(stderr, "munlock: skip page %d: %ld [refcount %d]\n",
5079 i, page_list->page_start, page_list->page_refcount);
5080#endif
5081
5082 page_last = page_list;
5083 page_list = page_list->next;
5084 }
5085#ifdef TEST_MLOCK
5086 ++i;
5087#endif
5088 }
5089 }
5090
5091 page_locking = 0;
5092
5093 exit_munlock:
5094 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5095 SL_RETURN((status), _("sh_unix_munlock"));
5096}
5097#else
5098int sh_unix_munlock (void * in_addr, size_t len)
5099{
5100 (void) in_addr; (void) len;
5101 return -1;
5102}
5103#endif
5104
5105int sh_unix_count_mlock()
5106{
5107 int i = 0;
5108 char str[32][64];
5109 sh_page_l * page_list;
5110
5111 SL_ENTER(_("sh_unix_count_mlock"));
5112
5113#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5114 /* There's no cancellation point here, except if tracing is on
5115 */
5116 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5117#endif
5118
5119 page_list = sh_page_locked;
5120
5121 while (page_list != NULL)
5122 {
5123#ifdef WITH_TPT
5124 if (i < 32)
5125 sl_snprintf(str[i], 64, _("file: %s line: %d page: %d"),
5126 page_list->file, page_list->line, i+1);
5127#endif
5128 page_list = page_list->next;
5129 ++i;
5130 }
5131
5132#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5133 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5134#endif
5135
5136#ifdef WITH_TPT
5137 {
5138 int j = 0;
5139 while (j < i && j < 32)
5140 {
5141 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, j, MSG_E_SUBGEN,
5142 str[j], _("sh_unix_count_mlock"));
5143 ++j;
5144 }
5145 }
5146#endif
5147
5148 sl_snprintf(str[0], 64, _("%d pages locked"), i);
5149 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, i, MSG_E_SUBGEN,
5150 str[0], _("sh_unix_count_mlock"));
5151 SL_RETURN((i), _("sh_unix_count_mlock"));
5152}
5153
5154/************************************************/
5155/************************************************/
5156/**** Stealth Utilities ****/
5157/************************************************/
5158/************************************************/
5159#ifdef SH_STEALTH
5160
5161void sh_unix_xor_code (char * str, int len)
5162{
5163 register int i;
5164
5165 for (i = 0; i < len; ++i) str[i] ^= (char) XOR_CODE;
5166 return;
5167}
5168
5169#if !defined(SH_STEALTH_MICRO)
5170
5171
5172int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5173 unsigned long * bytes_read);
5174unsigned long first_hex_block(SL_TICKET fd, unsigned long * max);
5175
5176/*
5177 * --- Get hidden data from a block of hex data. ---
5178 */
5179int sh_unix_getline_stealth (SL_TICKET fd, char * str, int len)
5180{
5181 int add_off = 0, llen;
5182 static unsigned long off_data = 0;
5183 static unsigned long max_data = 0;
5184 static unsigned long bytes_read = 0;
5185 static int stealth_init = BAD;
5186
5187 SL_ENTER(_("sh_unix_getline_stealth"));
5188
5189 if (str == NULL)
5190 {
5191 off_data = 0;
5192 max_data = 0;
5193 bytes_read = 0;
5194 stealth_init = BAD;
5195 SL_RETURN(0, _("sh_unix_getline_stealth"));
5196 }
5197
5198 /* --- Initialize. ---
5199 */
5200 if (stealth_init == BAD)
5201 {
5202 off_data = first_hex_block(fd, &max_data);
5203 if (off_data == 0)
5204 {
5205 dlog(1, FIL__, __LINE__,
5206 _("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"));
5207 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5208 _("Stealth config file."));
5209 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5210 }
5211 stealth_init = GOOD;
5212 max_data += off_data;
5213 }
5214
5215 /* --- Seek to proper position. ---
5216 */
5217 if (bytes_read >= max_data || add_off < 0)
5218 {
5219 dlog(1, FIL__, __LINE__,
5220 _("The capacity of the container image file for the stealth config file seems to be too small. Your config file is likely truncated.\n"));
5221 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5222 _("Stealth config file."));
5223 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5224 }
5225 sl_seek(fd, off_data);
5226
5227 /* --- Read one line. ---
5228 */
5229 add_off = hideout_hex_block(fd, (unsigned char *) str, len, &bytes_read);
5230 off_data += add_off;
5231
5232 llen = sl_strlen(str);
5233 SL_RETURN(llen, _("sh_unix_getline_stealth"));
5234}
5235
5236int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5237 unsigned long * bytes_read)
5238{
5239
5240 register int i, j, k;
5241 unsigned char c, e;
5242 register int num;
5243 unsigned char mask[9] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
5244 unsigned long here = 0;
5245 unsigned long retval = 0;
5246 unsigned long bread = 0;
5247
5248 SL_ENTER(_("hideout_hex_block"));
5249
5250 ASSERT_RET((len > 1), _("len > 1"), (0));
5251
5252 --len;
5253
5254 i = 0;
5255 while (i < len)
5256 {
5257 for (j = 0; j < 8; ++j)
5258 {
5259
5260 /* --- Get a low byte, modify, read back. ---
5261 */
5262 for (k = 0; k < 2; ++k)
5263 {
5264 /* -- Skip whitespace. ---
5265 */
5266 c = ' ';
5267 do {
5268 do {
5269 num = sl_read (fd, &c, 1);
5270 } while (num == 0 && errno == EINTR);
5271 if (num > 0)
5272 ++here;
5273 else if (num == 0)
5274 SL_RETURN((0), _("hideout_hex_block"));
5275 else
5276 SL_RETURN((-1), _("hideout_hex_block"));
5277 } while (c == '\n' || c == '\t' || c == '\r' ||
5278 c == ' ');
5279 }
5280
5281
5282 /* --- e is the value of the low byte. ---
5283 */
5284 e = (unsigned char) sh_util_hexchar( c );
5285 if ((e & mask[7]) != 0) /* bit is set */
5286 str[i] |= mask[j];
5287 else /* bit is not set */
5288 str[i] &= ~mask[j];
5289
5290 bread += 1;
5291 }
5292 if (str[i] == '\n') break;
5293 ++i;
5294 }
5295
5296 if (i != 0)
5297 str[i] = '\0';
5298 else
5299 str[i+1] = '\0'; /* keep newline and terminate */
5300 retval += here;
5301 *bytes_read += (bread/8);
5302
5303 SL_RETURN(retval, _("hideout_hex_block"));
5304}
5305
5306/* --- Get offset of first data block. ---
5307 */
5308unsigned long first_hex_block(SL_TICKET fd, unsigned long * max)
5309{
5310 unsigned int i;
5311 long num = 1;
5312 unsigned long lnum;
5313 char c;
5314 int nothex = 0;
5315 unsigned long retval = 0;
5316 unsigned int this_line = 0;
5317 char theline[SH_BUFSIZE];
5318
5319 SL_ENTER(_("first_hex_block"));
5320
5321 *max = 0;
5322
5323 while (1)
5324 {
5325 theline[0] = '\0';
5326 this_line = 0;
5327 c = '\0';
5328 while (c != '\n' && num > 0 && this_line < (sizeof(theline)-1))
5329 {
5330 do {
5331 num = sl_read (fd, &c, 1);
5332 } while (num == 0 && errno == EINTR);
5333 if (num > 0)
5334 theline[this_line] = c;
5335 else
5336 SL_RETURN((0), _("first_hex_block"));
5337 ++this_line;
5338 }
5339 theline[this_line] = '\0';
5340
5341 /* not only 'newline' */
5342 if (this_line > 60)
5343 {
5344 nothex = 0;
5345 i = 0;
5346 while (nothex == 0 && i < (this_line-1))
5347 {
5348 if (! isxdigit((int)theline[i])) nothex = 1;
5349 ++i;
5350 }
5351 if (nothex == 1) retval += this_line;
5352 }
5353 else
5354 {
5355 nothex = 1;
5356 retval += this_line;
5357 }
5358
5359 if (nothex == 0)
5360 {
5361 *max = 0;
5362 do {
5363 do {
5364 num = sl_read (fd, theline, SH_BUFSIZE);
5365 } while (num == 0 && errno == EINTR);
5366 if (num > 0)
5367 {
5368 lnum = (unsigned long) num;
5369 for (i = 0; i < lnum; ++i)
5370 {
5371 c = theline[i];
5372 if (c == '\n' || c == '\t' || c == '\r' || c == ' ')
5373 ;
5374 else if (!isxdigit((int)c))
5375 break;
5376 else
5377 *max += 1;
5378 }
5379 }
5380 } while (num > 0);
5381
5382 *max /= 16;
5383 SL_RETURN((retval), _("first_hex_block"));
5384 }
5385
5386 }
5387 /* SL_RETURN((0), _("first_hex_block")); *//* unreachable */
5388}
5389
5390 /* if !defined(SH_STEALTH_MICRO) */
5391#endif
5392
5393 /* ifdef SH_STEALTH */
5394#endif
5395
5396/*
5397 * anti-debugger code
5398 */
5399#if defined(SCREW_IT_UP)
5400volatile int sh_not_traced = 0;
5401
5402#ifdef HAVE_GETTIMEOFDAY
5403struct timeval save_tv;
5404#endif
5405
5406void sh_sigtrap_handler (int signum)
5407{
5408#ifdef HAVE_GETTIMEOFDAY
5409 struct timeval tv;
5410 long difftv;
5411
5412 gettimeofday(&tv, NULL);
5413 difftv = (tv.tv_sec - save_tv.tv_sec) * 1000000 +
5414 (tv.tv_usec - save_tv.tv_usec);
5415 if (difftv > 500000)
5416 raise(SIGKILL);
5417#endif
5418 sh_not_traced += signum;
5419 return;
5420}
5421#endif
Note: See TracBrowser for help on using the repository browser.