source: trunk/src/sh_unix.c@ 169

Last change on this file since 169 was 169, checked in by katerina, 17 years ago

Fixes for tickes #93 to #104 (yes, big commit, bad, bad,...).

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