source: trunk/src/sh_unix.c@ 171

Last change on this file since 171 was 171, checked in by katerina, 16 years ago

Include dnmalloc (ticket #108) and fix bugs #106 (EINPROGRESS) and #107 (compressBound).

File size: 113.2 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 thesignal, 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 (thesignal == 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(thesignal, 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 (const char * details,
464 const char * file, int line)
465{
466 char msg[128];
467 char str[128];
468 char * p;
469 int thesignal = 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 (thesignal, 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(void);
1063extern gid_t sl_trust_badgid(void);
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;
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 ddot = 0;
1635 for (i = 0; i < len; ++i)
1636 if (sh.host.name[i] == '.') ++ddot;
1637
1638 if (ddot == 0 && he1 != NULL)
1639 {
1640 dlog(1, FIL__, __LINE__,
1641 _("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"),
1642 hostname, sh.host.name);
1643 sl_strlcpy (sh.host.name,
1644 inet_ntoa (*(struct in_addr *) he1->h_addr),
1645 SH_PATHBUF);
1646 SL_RET0(_("sh_unix_localhost"));
1647 }
1648
1649 if (is_numeric(sh.host.name))
1650 {
1651 dlog(1, FIL__, __LINE__,
1652 _("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"),
1653 hostname, sh.host.name);
1654 }
1655
1656 SL_RET0(_("sh_unix_localhost"));
1657}
1658#else
1659void sh_unix_localhost()
1660{
1661 struct hostent * he1;
1662 int i;
1663 int ddot;
1664 int len;
1665 char hostname[1024];
1666
1667
1668 SL_ENTER(_("sh_unix_localhost"));
1669
1670 (void) gethostname (hostname, 1024);
1671 hostname[1023] = '\0';
1672
1673 SH_MUTEX_LOCK(mutex_resolv);
1674 he1 = sh_gethostbyname(hostname);
1675
1676 if (he1 != NULL)
1677 {
1678 sl_strlcpy (sh.host.name, sh_unix_h_name(he1), SH_PATHBUF);
1679 }
1680 SH_MUTEX_UNLOCK(mutex_resolv);
1681
1682 if (he1 == NULL)
1683 {
1684 dlog(1, FIL__, __LINE__,
1685 _("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"),
1686 hostname);
1687 sl_strlcpy (sh.host.name, _("localhost"), SH_PATHBUF);
1688 SL_RET0(_("sh_unix_localhost"));
1689 }
1690
1691 /* check whether it looks like a FQDN
1692 */
1693 len = sl_strlen(sh.host.name);
1694 ddot = 0;
1695 for (i = 0; i < len; ++i)
1696 if (sh.host.name[i] == '.') ++ddot;
1697 if (ddot == 0)
1698 {
1699 dlog(1, FIL__, __LINE__,
1700 _("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"),
1701 hostname, sh.host.name);
1702 sl_strlcpy (sh.host.name,
1703 inet_ntoa (*(struct in_addr *) he1->h_addr),
1704 SH_PATHBUF);
1705 SL_RET0(_("sh_unix_localhost"));
1706 }
1707
1708 if (is_numeric(sh.host.name))
1709 {
1710 dlog(1, FIL__, __LINE__,
1711 _("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"),
1712 hostname, sh.host.name);
1713 }
1714
1715 SL_RET0(_("sh_unix_localhost"));
1716}
1717#endif
1718
1719
1720void sh_unix_memlock()
1721{
1722 SL_ENTER(_("sh_unix_memlock"));
1723
1724 /* do this before dropping privileges
1725 */
1726#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
1727 if (skey->mlock_failed == SL_FALSE)
1728 {
1729 if ( (-1) == sh_unix_mlock( FIL__, __LINE__,
1730 (char *) skey, sizeof (sh_key_t)) )
1731 {
1732 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1733 skey->mlock_failed = SL_TRUE;
1734 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1735 }
1736 }
1737#else
1738 if (skey->mlock_failed == SL_FALSE)
1739 {
1740 SH_MUTEX_LOCK_UNSAFE(mutex_skey);
1741 skey->mlock_failed = SL_TRUE;
1742 SH_MUTEX_UNLOCK_UNSAFE(mutex_skey);
1743 }
1744#endif
1745
1746 SL_RET0(_("sh_unix_memlock"));
1747}
1748
1749#ifdef SH_WITH_SERVER
1750char * chroot_dir = NULL;
1751
1752int sh_unix_set_chroot(const char * str)
1753{
1754 size_t len;
1755 static int block = 0;
1756
1757 if (block == 1)
1758 return 0;
1759
1760 if (str && *str == '/')
1761 {
1762 len = strlen(str) + 1;
1763 chroot_dir = malloc(strlen(str) + 1); /* only once */
1764 if (!chroot_dir)
1765 {
1766 fprintf(stderr, _("%s: %d: Out of memory\n"), FIL__, __LINE__);
1767 return 1;
1768 }
1769 sl_strlcpy(chroot_dir, str, len);
1770 block = 1;
1771 return 0;
1772 }
1773 return 1;
1774}
1775
1776int sh_unix_chroot(void)
1777{
1778 int status;
1779
1780 if (chroot_dir != NULL)
1781 {
1782 status = retry_aud_chdir(FIL__, __LINE__, chroot_dir);
1783 if ( (-1) == status )
1784 {
1785 char errbuf[SH_ERRBUF_SIZE];
1786 status = errno;
1787 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1788 sh_error_message (status, errbuf, sizeof(errbuf)), chroot_dir);
1789 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1790 }
1791 /* flawfinder: ignore */
1792 return (chroot(chroot_dir));
1793 }
1794 return 0;
1795}
1796/* #ifdef SH_WITH_SERVER */
1797#else
1798int sh_unix_chroot(void) { return 0; }
1799#endif
1800
1801/* daemon mode
1802 */
1803static int block_setdeamon = 0;
1804
1805int sh_unix_setdeamon(const char * dummy)
1806{
1807 int res = 0;
1808
1809 SL_ENTER(_("sh_unix_setdeamon"));
1810
1811 if (block_setdeamon != 0)
1812 SL_RETURN((0),_("sh_unix_setdeamon"));
1813
1814 if (dummy == NULL)
1815 sh.flag.isdaemon = ON;
1816 else
1817 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1818
1819 if (sh.flag.opts == S_TRUE)
1820 block_setdeamon = 1;
1821
1822 SL_RETURN(res, _("sh_unix_setdeamon"));
1823}
1824#if defined(HAVE_LIBPRELUDE)
1825#include "sh_prelude.h"
1826#endif
1827
1828int sh_unix_setnodeamon(const char * dummy)
1829{
1830 int res = 0;
1831
1832 SL_ENTER(_("sh_unix_setnodeamon"));
1833
1834 if (block_setdeamon != 0)
1835 SL_RETURN((0),_("sh_unix_setmodeamon"));
1836
1837 if (dummy == NULL)
1838 sh.flag.isdaemon = OFF;
1839 else
1840 res = sh_util_flagval (dummy, &sh.flag.isdaemon);
1841
1842 if (sh.flag.opts == S_TRUE)
1843 block_setdeamon = 1;
1844
1845 SL_RETURN(res, _("sh_unix_setnodeamon"));
1846}
1847
1848int sh_unix_init(int goDaemon)
1849{
1850 int status;
1851 uid_t uid;
1852 pid_t oldpid = getpid();
1853#if defined(SH_WITH_SERVER)
1854 extern int sh_socket_open_int (void);
1855#endif
1856 char errbuf[SH_ERRBUF_SIZE];
1857
1858 SL_ENTER(_("sh_unix_init"));
1859
1860 /* fork twice, exit the parent process
1861 */
1862 if (goDaemon == 1) {
1863
1864 switch (aud_fork(FIL__, __LINE__)) {
1865 case 0: break; /* child process continues */
1866 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
1867 default: aud__exit(FIL__, __LINE__, 0); /* parent process exits */
1868 }
1869
1870 /* Child processes do not inherit page locks across a fork.
1871 * Error in next fork would return in this (?) thread of execution.
1872 */
1873 sh_unix_memlock();
1874
1875 setsid(); /* should not fail */
1876 sh.pid = (UINT64) getpid();
1877
1878 switch (aud_fork(FIL__, __LINE__)) {
1879 case 0: break; /* child process continues */
1880 case -1: SL_RETURN((-1),_("sh_unix_init")); /* error */
1881 default: aud__exit(FIL__, __LINE__, 0); /* parent process exits */
1882 }
1883
1884 /* Child processes do not inherit page locks across a fork.
1885 */
1886 sh_unix_memlock();
1887 sh.pid = (UINT64) getpid();
1888
1889 } else {
1890 setsid(); /* should not fail */
1891 }
1892
1893 /* set working directory
1894 */
1895#ifdef SH_PROFILE
1896 status = 0;
1897#else
1898 status = retry_aud_chdir(FIL__, __LINE__, "/");
1899#endif
1900 if ( (-1) == status )
1901 {
1902 status = errno;
1903 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_W_CHDIR,
1904 sh_error_message (status, errbuf, sizeof(errbuf)), "/");
1905 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1906 }
1907
1908 /* reset timers
1909 */
1910 sh_unix_resettimer();
1911
1912 /* signal handlers
1913 */
1914 sh_unix_resetsignals();
1915#if defined(SCREW_IT_UP)
1916 sh_sigtrap_prepare();
1917#endif
1918 sh_unix_siginstall (goDaemon);
1919
1920 /* set file creation mask
1921 */
1922 (void) umask (0); /* should not fail */
1923
1924 /* set resource limits to maximum, and
1925 * core dump size to zero
1926 */
1927 sh_unix_setlimits();
1928
1929 /* zero out the environment (like PATH='\0')
1930 */
1931 sh_unix_zeroenv();
1932
1933 if (goDaemon == 1)
1934 {
1935 /* Close first tree file descriptors
1936 */
1937 close (0); /* if running as daemon */
1938 close (1); /* if running as daemon */
1939 close (2); /* if running as daemon */
1940
1941 /* Enable full error logging
1942 */
1943 sh_error_only_stderr (S_FALSE);
1944
1945 /* open first three streams to /dev/null
1946 */
1947 status = aud_open(FIL__, __LINE__, SL_NOPRIV, _("/dev/null"), O_RDWR, 0);
1948 if (status < 0)
1949 {
1950 status = errno;
1951 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
1952 sh_error_message(status, errbuf, sizeof(errbuf)), _("open"));
1953 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1954 }
1955
1956 status = retry_aud_dup(FIL__, __LINE__, 0);
1957 if (status >= 0)
1958 retry_aud_dup(FIL__, __LINE__, 0);
1959
1960 if (status < 0)
1961 {
1962 status = errno;
1963 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
1964 sh_error_message(status, errbuf, sizeof(errbuf)), _("dup"));
1965 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1966 }
1967
1968 sh_error_enable_unsafe (S_TRUE);
1969#if defined(HAVE_LIBPRELUDE)
1970 sh_prelude_reset ();
1971#endif
1972
1973 /* --- wait until parent has exited ---
1974 */
1975 while (1 == 1)
1976 {
1977 errno = 0;
1978 if (0 > aud_kill (FIL__, __LINE__, oldpid, 0) && errno == ESRCH)
1979 {
1980 break;
1981 }
1982 retry_msleep(0, 1);
1983 }
1984
1985 /* write PID file
1986 */
1987 status = sh_unix_write_pid_file();
1988 if (status < 0)
1989 {
1990 sl_get_euid(&uid);
1991 sh_error_handle ((-1), FIL__, __LINE__, status, MSG_PIDFILE,
1992 (long) uid, sh.srvlog.alt);
1993 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
1994 }
1995#if defined(SH_WITH_SERVER)
1996 sh_socket_open_int ();
1997#endif
1998 }
1999 else
2000 {
2001 sh_error_enable_unsafe (S_TRUE);
2002#if defined(HAVE_LIBPRELUDE)
2003 sh_prelude_reset ();
2004#endif
2005#if defined(SH_WITH_SERVER)
2006 sh_socket_open_int ();
2007#endif
2008 }
2009
2010 /* chroot (this is a no-op if no chroot dir is specified
2011 */
2012 status = sh_unix_chroot();
2013 if (status < 0)
2014 {
2015 status = errno;
2016 sh_error_handle((-1), FIL__, __LINE__, status, MSG_E_SUBGEN,
2017 sh_error_message(status, errbuf, sizeof(errbuf)), _("chroot"));
2018 aud_exit(FIL__, __LINE__, EXIT_FAILURE);
2019 }
2020
2021 /* drop capabilities
2022 */
2023 sl_drop_cap();
2024
2025 SL_RETURN((0),_("sh_unix_init"));
2026}
2027
2028/********************************************************
2029 *
2030 * TIME
2031 *
2032 ********************************************************/
2033
2034/* Figure out the time offset of the current timezone
2035 * in a portable way.
2036 */
2037char * t_zone(const time_t * xx)
2038{
2039 struct tm aa;
2040 struct tm bb;
2041 struct tm * cc;
2042 int sign = 0;
2043 int diff = 0;
2044 int hh, mm;
2045 static char tz[64];
2046
2047 SL_ENTER(_("t_zone"));
2048
2049#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2050 cc = gmtime_r (xx, &aa);
2051#else
2052 cc = gmtime (xx);
2053 memcpy (&aa, cc, sizeof(struct tm));
2054#endif
2055
2056#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2057 cc = localtime_r (xx, &bb);
2058#else
2059 cc = localtime (xx);
2060 memcpy (&bb, cc, sizeof(struct tm));
2061#endif
2062
2063 /* Check for datum wrap-around.
2064 */
2065 if (aa.tm_year < bb.tm_year)
2066 sign = (-1);
2067 else if (aa.tm_mon < bb.tm_mon)
2068 sign = (-1);
2069 else if (aa.tm_mday < bb.tm_mday)
2070 sign = (-1);
2071 else if (bb.tm_year < aa.tm_year)
2072 sign = ( 1);
2073 else if (bb.tm_mon < aa.tm_mon)
2074 sign = ( 1);
2075 else if (bb.tm_mday < aa.tm_mday)
2076 sign = ( 1);
2077
2078 diff = aa.tm_hour * 60 + aa.tm_min;
2079 diff = (bb.tm_hour * 60 + bb.tm_min) - diff;
2080 diff = diff - (sign * 24 * 60); /* datum wrap-around correction */
2081 hh = diff / 60;
2082 mm = diff - (hh * 60);
2083 sprintf (tz, _("%+03d%02d"), hh, mm); /* known to fit */
2084
2085 SL_RETURN(tz, _("t_zone"));
2086}
2087
2088unsigned long sh_unix_longtime ()
2089{
2090 return ((unsigned long)time(NULL));
2091}
2092
2093#ifdef HAVE_GETTIMEOFDAY
2094unsigned long sh_unix_notime ()
2095{
2096 struct timeval tv;
2097
2098 gettimeofday (&tv, NULL);
2099
2100 return ((unsigned long)(tv.tv_sec + tv.tv_usec * 10835 + getpid() + getppid()));
2101
2102}
2103#endif
2104
2105static int count_dev_time = 0;
2106
2107void reset_count_dev_time(void)
2108{
2109 count_dev_time = 0;
2110 return;
2111}
2112
2113int sh_unix_settimeserver (const char * address)
2114{
2115
2116 SL_ENTER(_("sh_unix_settimeserver"));
2117
2118 if (address != NULL && count_dev_time < 2
2119 && sl_strlen(address) < SH_PATHBUF)
2120 {
2121 if (count_dev_time == 0)
2122 sl_strlcpy (sh.srvtime.name, address, SH_PATHBUF);
2123 else
2124 sl_strlcpy (sh.srvtime.alt, address, SH_PATHBUF);
2125
2126 ++count_dev_time;
2127 SL_RETURN((0), _("sh_unix_settimeserver"));
2128 }
2129 SL_RETURN((-1), _("sh_unix_settimeserver"));
2130}
2131
2132
2133#ifdef HAVE_NTIME
2134#define UNIXEPOCH 2208988800UL /* difference between Unix time and net time
2135 * The UNIX EPOCH starts in 1970.
2136 */
2137#include <sys/socket.h>
2138#include <netinet/in.h>
2139#include <arpa/inet.h>
2140#include <netdb.h>
2141#include <ctype.h>
2142#endif
2143
2144/* Timeserver service. */
2145/* define is missing on HP-UX 10.20 */
2146#ifndef IPPORT_TIMESERVER
2147#define IPPORT_TIMESERVER 37
2148#endif
2149
2150char * sh_unix_time (time_t thetime, char * buffer, size_t len)
2151{
2152
2153 int status;
2154 char AsciiTime[81]; /* local time */
2155 time_t time_now;
2156 struct tm * time_ptr;
2157#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2158 struct tm time_tm;
2159#endif
2160#ifdef SH_USE_XML
2161 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2162#else
2163 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2164#endif
2165
2166#ifdef HAVE_NTIME
2167 int fd; /* network file descriptor */
2168 u_char net_time[4]; /* remote time in network format */
2169 static int failerr = 0; /* no net time */
2170 int fail = 0; /* no net time */
2171 int errflag;
2172 char errmsg[256];
2173 char error_call[SH_MINIBUF];
2174 int error_num;
2175#endif
2176
2177 SL_ENTER(_("sh_unix_time"));
2178
2179#ifdef HAVE_NTIME
2180 if (thetime == 0)
2181 {
2182 if (sh.srvtime.name[0] == '\0')
2183 {
2184 fail = 1;
2185 (void) time (&time_now);
2186 }
2187 else /* have a timeserver address */
2188 {
2189 fd = connect_port_2 (sh.srvtime.name, sh.srvtime.alt,
2190 IPPORT_TIMESERVER,
2191 error_call, &error_num, errmsg, sizeof(errmsg));
2192 if (fd >= 0)
2193 {
2194 if (4 != read_port (fd, (char *) net_time, 4, &errflag, 2))
2195 {
2196 fail = 1;
2197 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2198 MSG_E_NLOST,
2199 _("time"), sh.srvtime.name);
2200 }
2201 close(fd);
2202 }
2203 else
2204 {
2205 sh_error_handle ((-1), FIL__, __LINE__, error_num,
2206 MSG_E_NET, errmsg, error_call,
2207 _("time"), sh.srvtime.name);
2208 fail = 1;
2209 }
2210
2211 if (fail == 0)
2212 {
2213 time_now = ntohl(* (long *) net_time) - UNIXEPOCH;
2214 /* fprintf(stderr, "TIME IS %ld\n", time_now); */
2215 if (failerr == 1) {
2216 failerr = 0;
2217 sh_error_handle ((-1), FIL__, __LINE__, 0,
2218 MSG_E_NEST,
2219 _("time"), sh.srvtime.name);
2220 }
2221 }
2222 else
2223 {
2224 (void) time (&time_now);
2225 if (failerr == 0)
2226 {
2227 failerr = 1;
2228 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2229 MSG_SRV_FAIL,
2230 _("time"), sh.srvtime.name);
2231 }
2232 }
2233 }
2234 }
2235 else
2236 {
2237 time_now = thetime;
2238 }
2239
2240 /* #ifdef HAVE_NTIME */
2241#else
2242
2243 if (thetime == 0)
2244 {
2245 (void) time (&time_now);
2246 }
2247 else
2248 {
2249 time_now = thetime;
2250 }
2251
2252 /* #ifdef HAVE_NTIME */
2253#endif
2254
2255 if (time_now == (-1) )
2256 {
2257 sl_strlcpy(buffer, _(deftime), len);
2258 SL_RETURN(buffer, _("sh_unix_time"));
2259 }
2260 else
2261 {
2262#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2263 time_ptr = localtime_r (&time_now, &time_tm);
2264#else
2265 time_ptr = localtime (&time_now);
2266#endif
2267 }
2268 if (time_ptr != NULL)
2269 {
2270 status = strftime (AsciiTime, sizeof(AsciiTime),
2271#ifdef SH_USE_XML
2272 _("%Y-%m-%dT%H:%M:%S%%s"),
2273#else
2274 _("[%Y-%m-%dT%H:%M:%S%%s]"),
2275#endif
2276 time_ptr);
2277
2278 sl_snprintf(buffer, len, AsciiTime, t_zone(&time_now));
2279
2280 if ( (status == 0) || (status == sizeof(AsciiTime)) )
2281 {
2282 sl_strlcpy(buffer, _(deftime), len);
2283 SL_RETURN( buffer, _("sh_unix_time"));
2284 }
2285 else
2286 {
2287 SL_RETURN(buffer, _("sh_unix_time"));
2288 }
2289 }
2290
2291 /* last resort
2292 */
2293 sl_strlcpy(buffer, _(deftime), len);
2294 SL_RETURN( buffer, _("sh_unix_time"));
2295}
2296
2297static int sh_unix_use_localtime = S_FALSE;
2298
2299/* whether to use localtime for file timesatams in logs
2300 */
2301int sh_unix_uselocaltime (const char * c)
2302{
2303 int i;
2304 SL_ENTER(_("sh_unix_uselocaltime"));
2305 i = sh_util_flagval(c, &(sh_unix_use_localtime));
2306
2307 SL_RETURN(i, _("sh_unix_uselocaltime"));
2308}
2309
2310char * sh_unix_gmttime (time_t thetime, char * buffer, size_t len)
2311{
2312
2313 int status;
2314
2315 struct tm * time_ptr;
2316#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS)
2317 struct tm time_tm;
2318#endif
2319 char AsciiTime[81]; /* GMT time */
2320#ifdef SH_USE_XML
2321 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2322#else
2323 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2324#endif
2325
2326 SL_ENTER(_("sh_unix_gmttime"));
2327
2328 if (sh_unix_use_localtime == S_FALSE)
2329 {
2330#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2331 time_ptr = gmtime_r (&thetime, &time_tm);
2332#else
2333 time_ptr = gmtime (&thetime);
2334#endif
2335 }
2336 else
2337 {
2338#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2339 time_ptr = localtime_r (&thetime, &time_tm);
2340#else
2341 time_ptr = localtime (&thetime);
2342#endif
2343 }
2344 if (time_ptr != NULL)
2345 {
2346 status = strftime (AsciiTime, 80,
2347#ifdef SH_USE_XML
2348 _("%Y-%m-%dT%H:%M:%S"),
2349#else
2350 _("[%Y-%m-%dT%H:%M:%S]"),
2351#endif
2352 time_ptr);
2353
2354 if ( (status == 0) || (status == 80) )
2355 sl_strlcpy(buffer, _(deftime), len);
2356 else
2357 sl_strlcpy(buffer, AsciiTime, len);
2358 SL_RETURN( buffer, _("sh_unix_gmttime"));
2359 }
2360
2361 /* last resort
2362 */
2363 sl_strlcpy(buffer, _(deftime), len);
2364 SL_RETURN( buffer, _("sh_unix_gmttime"));
2365}
2366
2367
2368char * sh_unix_getUIDdir (int level, uid_t uid, char * out, size_t len)
2369{
2370 struct passwd * tempres;
2371 int status = 0;
2372#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2373 struct passwd pwd;
2374 char buffer[SH_PWBUF_SIZE];
2375#endif
2376 char errbuf[SH_ERRBUF_SIZE];
2377
2378 SL_ENTER(_("sh_unix_getUIDdir"));
2379
2380#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2381 sh_getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &tempres);
2382#else
2383 errno = 0;
2384 tempres = sh_getpwuid(uid);
2385 status = errno;
2386#endif
2387
2388 if (tempres == NULL) {
2389 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2390 sh_error_message(status, errbuf, sizeof(errbuf)),
2391 _("getpwuid"), (long) uid, _("completely missing"));
2392 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2393 }
2394
2395 if (tempres->pw_dir != NULL) {
2396 sl_strlcpy(out, tempres->pw_dir, len);
2397 SL_RETURN( out, _("sh_unix_getUIDdir"));
2398 } else {
2399 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2400 sh_error_message(status, errbuf, sizeof(errbuf)),
2401 _("getpwuid"), (long) uid, _("pw_dir"));
2402 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2403 }
2404}
2405
2406SH_MUTEX_STATIC(mutex_getUIDname, PTHREAD_MUTEX_INITIALIZER);
2407
2408char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len)
2409{
2410 struct passwd * tempres;
2411#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2412 struct passwd pwd;
2413 char buffer[SH_PWBUF_SIZE];
2414#endif
2415 int status = 0;
2416 static uid_t old_uid;
2417 static char name[32] = { '\0' };
2418 char errbuf[SH_ERRBUF_SIZE];
2419
2420 SL_ENTER(_("sh_unix_getUIDname"));
2421
2422 if ((uid == old_uid) && (name[0] != '\0')) {
2423 out[0] = '\0';
2424 SH_MUTEX_LOCK_UNSAFE(mutex_getUIDname);
2425 if ((uid == old_uid) && (name[0] != '\0')) {
2426 sl_strlcpy(out, name, len);
2427 }
2428 SH_MUTEX_UNLOCK_UNSAFE(mutex_getUIDname);
2429 if (out[0] != '\0')
2430 SL_RETURN( out, _("sh_unix_getUIDname"));
2431 }
2432
2433#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2434 sh_getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &tempres);
2435#else
2436 errno = 0;
2437 tempres = sh_getpwuid(uid);
2438 status = errno;
2439#endif
2440
2441 if (tempres == NULL) {
2442 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2443 sh_error_message(status, errbuf, sizeof(errbuf)),
2444 _("getpwuid"), (long) uid, _("completely missing"));
2445 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2446 }
2447
2448
2449 if (tempres->pw_name != NULL) {
2450 SH_MUTEX_LOCK_UNSAFE(mutex_getUIDname);
2451 sl_strlcpy(name, tempres->pw_name, sizeof(name));
2452 old_uid = uid;
2453 sl_strlcpy(out, name, len);
2454 SH_MUTEX_UNLOCK_UNSAFE(mutex_getUIDname);
2455 SL_RETURN( out, _("sh_unix_getUIDname"));
2456 } else {
2457 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2458 sh_error_message(status, errbuf, sizeof(errbuf)),
2459 _("getpwuid"), (long) uid, _("pw_user"));
2460 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2461 }
2462}
2463
2464SH_MUTEX_STATIC(mutex_getGIDname, PTHREAD_MUTEX_INITIALIZER);
2465
2466char * sh_unix_getGIDname (int level, gid_t gid, char * out, size_t len)
2467{
2468 struct group * tempres;
2469 int status = 0;
2470 static gid_t old_gid;
2471 static char name[32] = { '\0' };
2472#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2473 struct group grp;
2474 char buffer[SH_GRBUF_SIZE];
2475#endif
2476 char errbuf[SH_ERRBUF_SIZE];
2477
2478
2479 SL_ENTER(_("sh_unix_getGIDname"));
2480
2481 if ((gid == old_gid) && (name[0] != '\0')) {
2482 out[0] = '\0';
2483 SH_MUTEX_LOCK_UNSAFE(mutex_getGIDname);
2484 if ((gid == old_gid) && (name[0] != '\0')) {
2485 sl_strlcpy(out, name, len);
2486 }
2487 SH_MUTEX_UNLOCK_UNSAFE(mutex_getGIDname);
2488 if (out[0] != '\0')
2489 SL_RETURN( out, _("sh_unix_getGIDname"));
2490 }
2491
2492#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2493 status = sh_getgrgid_r(gid, &grp, buffer, sizeof(buffer), &tempres);
2494#else
2495 errno = 0;
2496 tempres = sh_getgrgid(gid);
2497 status = errno;
2498#endif
2499
2500 if (tempres == NULL) {
2501 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2502 sh_error_message(status, errbuf, sizeof(errbuf)),
2503 _("getgrgid"), (long) gid, _("completely missing"));
2504
2505 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2506 }
2507
2508 if (tempres->gr_name != NULL) {
2509 SH_MUTEX_LOCK_UNSAFE(mutex_getGIDname);
2510 sl_strlcpy(name, tempres->gr_name, sizeof(name));
2511 old_gid = gid;
2512 sl_strlcpy(out, name, len);
2513 SH_MUTEX_UNLOCK_UNSAFE(mutex_getGIDname);
2514 SL_RETURN( out, _("sh_unix_getGIDname"));
2515 } else {
2516 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2517 sh_error_message(status, errbuf, sizeof(errbuf)),
2518 _("getgrgid"), (long) gid, _("gr_name"));
2519 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2520 }
2521}
2522
2523int sh_unix_getUser ()
2524{
2525 char * p;
2526 uid_t seuid, sruid;
2527 char user[USER_MAX];
2528 char dir[SH_PATHBUF];
2529
2530 SL_ENTER(_("sh_unix_getUser"));
2531
2532 seuid = geteuid();
2533
2534 sh.effective.uid = seuid;
2535
2536 p = sh_unix_getUIDdir (SH_ERR_ERR, seuid, dir, sizeof(dir));
2537
2538 if (p == NULL)
2539 SL_RETURN((-1), _("sh_unix_getUser"));
2540 else
2541 {
2542 if (sl_strlen(p) >= SH_PATHBUF) {
2543 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2544 _("getpwuid"), (long) seuid, _("pw_home"));
2545 SL_RETURN((-1), _("sh_unix_getUser"));
2546 } else {
2547 sl_strlcpy ( sh.effective.home, p, SH_PATHBUF);
2548 }
2549 }
2550
2551 sruid = getuid();
2552
2553 sh.real.uid = sruid;
2554
2555 p = sh_unix_getUIDname (SH_ERR_ERR, sruid, user, sizeof(user));
2556 if (p == NULL)
2557 SL_RETURN((-1), _("sh_unix_getUser"));
2558 else
2559 {
2560 if (sl_strlen(p) >= USER_MAX) {
2561 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2562 _("getpwuid"), (long) sruid, _("pw_user"));
2563 SL_RETURN((-1), _("sh_unix_getUser"));
2564 } else {
2565 sl_strlcpy ( sh.real.user, p, USER_MAX);
2566 }
2567 }
2568
2569 p = sh_unix_getUIDdir (SH_ERR_ERR, sruid, dir, sizeof(dir));
2570
2571 if (p == NULL)
2572 SL_RETURN((-1), _("sh_unix_getUser"));
2573 else
2574 {
2575 if (sl_strlen(p) >= SH_PATHBUF) {
2576 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2577 _("getpwuid"), (long) sruid, _("pw_home"));
2578 SL_RETURN((-1), _("sh_unix_getUser"));
2579 } else {
2580 sl_strlcpy ( sh.real.home, p, SH_PATHBUF);
2581 }
2582 }
2583
2584 SL_RETURN((0), _("sh_unix_getUser"));
2585
2586 /* notreached */
2587}
2588
2589
2590int sh_unix_getline (SL_TICKET fd, char * line, int sizeofline)
2591{
2592 register int count;
2593 register int n = 0;
2594 char c;
2595
2596 SL_ENTER(_("sh_unix_getline"));
2597
2598 if (sizeofline < 2) {
2599 line[0] = '\0';
2600 SL_RETURN((0), _("sh_unix_getline"));
2601 }
2602
2603 --sizeofline;
2604
2605 while (n < sizeofline) {
2606
2607 count = sl_read (fd, &c, 1);
2608
2609 /* end of file
2610 */
2611 if (count < 1) {
2612 line[n] = '\0';
2613 n = -1;
2614 break;
2615 }
2616
2617 if (/* c != '\0' && */ c != '\n') {
2618 line[n] = c;
2619 ++n;
2620 } else if (c == '\n') {
2621 if (n > 0) {
2622 line[n] = '\0';
2623 break;
2624 } else {
2625 line[n] = '\n'; /* get newline only if only char on line */
2626 ++n;
2627 line[n] = '\0';
2628 break;
2629 }
2630 } else {
2631 line[n] = '\0';
2632 break;
2633 }
2634
2635 }
2636
2637
2638 line[sizeofline] = '\0'; /* make sure line is terminated */
2639 SL_RETURN((n), _("sh_unix_getline"));
2640}
2641
2642
2643#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
2644
2645/**************************************************************
2646 *
2647 * --- FILE INFO ---
2648 *
2649 **************************************************************/
2650
2651#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
2652
2653#if defined(__linux__)
2654
2655/* --- Determine ext2fs file attributes. ---
2656 */
2657#include <sys/ioctl.h>
2658#if defined(HAVE_EXT2FS_EXT2_FS_H)
2659#include <ext2fs/ext2_fs.h>
2660#else
2661#include <linux/ext2_fs.h>
2662#endif
2663
2664/* __linux__ includes */
2665#endif
2666
2667static
2668int sh_unix_getinfo_attr (char * name,
2669 unsigned long * flags,
2670 char * c_attr,
2671 int fd, struct stat * buf)
2672{
2673
2674/* TAKEN FROM:
2675 *
2676 * lsattr.c - List file attributes on an ext2 file system
2677 *
2678 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
2679 * Laboratoire MASI, Institut Blaise Pascal
2680 * Universite Pierre et Marie Curie (Paris VI)
2681 *
2682 * This file can be redistributed under the terms of the GNU General
2683 * Public License
2684 */
2685
2686#ifdef HAVE_STAT_FLAGS
2687
2688 SL_ENTER(_("sh_unix_getinfo_attr"));
2689
2690 *flags = 0;
2691
2692 /* cast to void to avoid compiler warning about unused parameters */
2693 (void) fd;
2694 (void) name;
2695
2696#ifdef UF_NODUMP
2697 if (buf->st_flags & UF_NODUMP) {
2698 *flags |= UF_NODUMP;
2699 c_attr[0] = 'd';
2700 }
2701#endif
2702#ifdef UF_IMMUTABLE
2703 if (buf->st_flags & UF_IMMUTABLE) {
2704 *flags |= UF_IMMUTABLE;
2705 c_attr[1] = 'i';
2706 }
2707#endif
2708#ifdef UF_APPEND
2709 if (buf->st_flags & UF_APPEND) {
2710 *flags |= UF_APPEND;
2711 c_attr[2] = 'a';
2712 }
2713#endif
2714#ifdef UF_NOUNLINK
2715 if (buf->st_flags & UF_NOUNLINK) {
2716 *flags |= UF_NOUNLINK;
2717 c_attr[3] = 'u';
2718 }
2719#endif
2720#ifdef UF_OPAQUE
2721 if (buf->st_flags & UF_OPAQUE) {
2722 *flags |= UF_OPAQUE;
2723 c_attr[4] = 'o';
2724 }
2725#endif
2726#ifdef SF_ARCHIVED
2727 if (buf->st_flags & SF_ARCHIVED) {
2728 *flags |= SF_ARCHIVED;
2729 c_attr[5] = 'R';
2730 }
2731
2732#endif
2733#ifdef SF_IMMUTABLE
2734 if (buf->st_flags & SF_IMMUTABLE) {
2735 *flags |= SF_IMMUTABLE;
2736 c_attr[6] = 'I';
2737 }
2738#endif
2739#ifdef SF_APPEND
2740 if (buf->st_flags & SF_APPEND) {
2741 *flags |= SF_APPEND;
2742 c_attr[7] = 'A';
2743 }
2744#endif
2745#ifdef SF_NOUNLINK
2746 if (buf->st_flags & SF_NOUNLINK) {
2747 *flags |= SF_NOUNLINK;
2748 c_attr[8] = 'U';
2749 }
2750#endif
2751
2752 /* ! HAVE_STAT_FLAGS */
2753#else
2754
2755#ifdef HAVE_EXT2_IOCTLS
2756 int /* fd, */ r, f;
2757
2758 SL_ENTER(_("sh_unix_getinfo_attr"));
2759
2760 *flags = 0;
2761 (void) buf;
2762
2763 /* open() -> aud_open() R.Wichmann
2764 fd = aud_open (FIL__, __LINE__, SL_YESPRIV, name, O_RDONLY|O_NONBLOCK, 0);
2765 */
2766
2767 if (fd == -1 || name == NULL)
2768 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
2769
2770
2771 r = ioctl (fd, EXT2_IOC_GETFLAGS, &f);
2772 /* close (fd); */
2773
2774 if (r == -1)
2775 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
2776
2777 if (f == 0)
2778 SL_RETURN(0, _("sh_unix_getinfo_attr"));
2779
2780 *flags = f;
2781
2782/* ! HAVE_EXT2_IOCTLS */
2783#else
2784
2785 SL_ENTER(_("sh_unix_getinfo_attr"));
2786
2787 *flags = 0; /* modified by R.Wichmann */
2788
2789/* ! HAVE_EXT2_IOCTLS */
2790#endif
2791/*
2792 * END
2793 *
2794 * lsattr.c - List file attributes on an ext2 file system
2795 */
2796
2797 if (*flags == 0)
2798 goto theend;
2799
2800#ifdef EXT2_SECRM_FL
2801 if ( (*flags & EXT2_SECRM_FL) != 0 ) c_attr[0] = 's';
2802#endif
2803#ifdef EXT2_UNRM_FL
2804 if ( (*flags & EXT2_UNRM_FL) != 0 ) c_attr[1] = 'u';
2805#endif
2806#ifdef EXT2_SYNC_FL
2807 if ( (*flags & EXT2_SYNC_FL) != 0 ) c_attr[2] = 'S';
2808#endif
2809#ifdef EXT2_IMMUTABLE_FL
2810 if ( (*flags & EXT2_IMMUTABLE_FL) != 0) c_attr[3] = 'i';
2811#endif
2812#ifdef EXT2_APPEND_FL
2813 if ( (*flags & EXT2_APPEND_FL) != 0 ) c_attr[4] = 'a';
2814#endif
2815#ifdef EXT2_NODUMP_FL
2816 if ( (*flags & EXT2_NODUMP_FL) != 0 ) c_attr[5] = 'd';
2817#endif
2818#ifdef EXT2_NOATIME_FL
2819 if ( (*flags & EXT2_NOATIME_FL) != 0) c_attr[6] = 'A';
2820#endif
2821#ifdef EXT2_COMPR_FL
2822 if ( (*flags & EXT2_COMPR_FL) != 0 ) c_attr[7] = 'c';
2823#endif
2824
2825#ifdef EXT2_TOPDIR_FL
2826 if ( (*flags & EXT2_TOPDIR_FL) != 0 ) c_attr[8] = 'T';
2827#endif
2828#ifdef EXT2_DIRSYNC_FL
2829 if ( (*flags & EXT2_DIRSYNC_FL) != 0 ) c_attr[9] = 'D';
2830#endif
2831#ifdef EXT2_NOTAIL_FL
2832 if ( (*flags & EXT2_NOTAIL_FL) != 0 ) c_attr[10] = 't';
2833#endif
2834#ifdef EXT2_JOURNAL_DATA_FL
2835 if ( (*flags & EXT2_JOURNAL_DATA_FL) != 0) c_attr[11] = 'j';
2836#endif
2837
2838 theend:
2839 /* ext2 */
2840#endif
2841
2842 c_attr[12] = '\0';
2843
2844 SL_RETURN(0, _("sh_unix_getinfo_attr"));
2845}
2846#else
2847static
2848int sh_unix_getinfo_attr (char * name,
2849 unsigned long * flags,
2850 char * c_attr,
2851 int fd, struct stat * buf)
2852{
2853 return 0;
2854}
2855
2856/* defined(__linux__) || defined(HAVE_STAT_FLAGS) */
2857#endif
2858
2859/* determine file type
2860 */
2861static
2862int sh_unix_getinfo_type (struct stat * buf,
2863 ShFileType * type,
2864 char * c_mode)
2865{
2866 SL_ENTER(_("sh_unix_getinfo_type"));
2867
2868 if ( S_ISREG(buf->st_mode) ) {
2869 (*type) = SH_FILE_REGULAR;
2870 c_mode[0] = '-';
2871 }
2872 else if ( S_ISLNK(buf->st_mode) ) {
2873 (*type) = SH_FILE_SYMLINK;
2874 c_mode[0] = 'l';
2875 }
2876 else if ( S_ISDIR(buf->st_mode) ) {
2877 (*type) = SH_FILE_DIRECTORY;
2878 c_mode[0] = 'd';
2879 }
2880 else if ( S_ISCHR(buf->st_mode) ) {
2881 (*type) = SH_FILE_CDEV;
2882 c_mode[0] = 'c';
2883 }
2884 else if ( S_ISBLK(buf->st_mode) ) {
2885 (*type) = SH_FILE_BDEV;
2886 c_mode[0] = 'b';
2887 }
2888 else if ( S_ISFIFO(buf->st_mode) ) {
2889 (*type) = SH_FILE_FIFO;
2890 c_mode[0] = '|';
2891 }
2892 else if ( S_ISSOCK(buf->st_mode) ) {
2893 (*type) = SH_FILE_SOCKET;
2894 c_mode[0] = 's';
2895 }
2896 else if ( S_ISDOOR(buf->st_mode) ) {
2897 (*type) = SH_FILE_DOOR;
2898 c_mode[0] = 'D';
2899 }
2900 else if ( S_ISPORT(buf->st_mode) ) {
2901 (*type) = SH_FILE_PORT;
2902 c_mode[0] = 'P';
2903 }
2904 else {
2905 (*type) = SH_FILE_UNKNOWN;
2906 c_mode[0] = '?';
2907 }
2908
2909 SL_RETURN(0, _("sh_unix_getinfo_type"));
2910}
2911
2912int sh_unix_get_ftype(char * fullpath)
2913{
2914 char c_mode[CMODE_SIZE];
2915 struct stat buf;
2916 ShFileType type;
2917 int res;
2918
2919 SL_ENTER(_("sh_unix_get_ftype"));
2920
2921 res = retry_lstat(FIL__, __LINE__, fullpath, &buf);
2922
2923 if (res < 0)
2924 SL_RETURN(SH_FILE_UNKNOWN, _("sh_unix_getinfo_type"));
2925
2926 sh_unix_getinfo_type (&buf, &type, c_mode);
2927
2928 SL_RETURN(type, _("sh_unix_get_ftype"));
2929}
2930
2931
2932static
2933int sh_unix_getinfo_mode (struct stat *buf,
2934 unsigned int * mode,
2935 char * c_mode)
2936{
2937
2938 SL_ENTER(_("sh_unix_getinfo_mode"));
2939
2940 (*mode) = buf->st_mode;
2941
2942 /* make 'ls'-like string */
2943
2944 if ( (buf->st_mode & S_IRUSR) != 0 ) c_mode[1] = 'r';
2945 if ( (buf->st_mode & S_IWUSR) != 0 ) c_mode[2] = 'w';
2946 if ( (buf->st_mode & S_IXUSR) != 0 ) {
2947 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 's';
2948 else c_mode[3] = 'x';
2949 } else {
2950 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 'S';
2951 }
2952
2953 if ( (buf->st_mode & S_IRGRP) != 0 ) c_mode[4] = 'r';
2954 if ( (buf->st_mode & S_IWGRP) != 0 ) c_mode[5] = 'w';
2955 if ( (buf->st_mode & S_IXGRP) != 0 ) {
2956 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 's';
2957 else c_mode[6] = 'x';
2958 } else {
2959 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 'S';
2960 }
2961
2962 if ( (buf->st_mode & S_IROTH) != 0 ) c_mode[7] = 'r';
2963 if ( (buf->st_mode & S_IWOTH) != 0 ) c_mode[8] = 'w';
2964#ifdef S_ISVTX /* not POSIX */
2965 if ( (buf->st_mode & S_IXOTH) != 0 ) {
2966 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 't';
2967 else c_mode[9] = 'x';
2968 } else {
2969 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 'T';
2970 }
2971#else
2972 if ( (buf->st_mode & S_IXOTH) != 0 ) c_mode[9] = 'x';
2973#endif
2974
2975 SL_RETURN(0, _("sh_unix_getinfo_mode"));
2976}
2977
2978
2979long IO_Limit = 0;
2980
2981void sh_unix_io_pause ()
2982{
2983 long runtime;
2984 float someval;
2985 unsigned long sometime;
2986
2987 if (IO_Limit == 0)
2988 {
2989 return;
2990 }
2991 else
2992 {
2993 runtime = (long) (time(NULL) - sh.statistics.time_start);
2994
2995 if (runtime > 0 && (long)(sh.statistics.bytes_hashed/runtime) > IO_Limit)
2996 {
2997 someval = sh.statistics.bytes_hashed - (IO_Limit * runtime);
2998 someval /= (float) IO_Limit;
2999 if (someval < 1.0)
3000 {
3001 someval *= 1000; /* milliseconds in a second */
3002 sometime = (unsigned long) someval;
3003 retry_msleep(0, sometime);
3004 }
3005 else
3006 {
3007 sometime = (unsigned long) someval;
3008 retry_msleep (sometime, 0);
3009 }
3010 }
3011 }
3012 return;
3013}
3014
3015int sh_unix_set_io_limit (const char * c)
3016{
3017 long val;
3018
3019 SL_ENTER(_("sh_unix_set_io_limit"));
3020
3021 val = strtol (c, (char **)NULL, 10);
3022 if (val < 0)
3023 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
3024 _("set I/O limit"), c);
3025
3026 val = (val < 0 ? 0 : val);
3027
3028 IO_Limit = val * 1024;
3029 SL_RETURN( 0, _("sh_unix_set_io_limit"));
3030}
3031
3032/* obtain file info
3033 */
3034extern int flag_err_debug;
3035
3036#include "sh_ignore.h"
3037
3038int sh_unix_checksum_size (char * filename, struct stat * fbuf,
3039 char * fileHash, int alert_timeout, SL_TICKET fd)
3040{
3041 file_type tmpFile;
3042 int status;
3043
3044 SL_ENTER(_("sh_unix_checksum_size"));
3045
3046 tmpFile.link_path = NULL;
3047
3048 if (sh.flag.checkSum != SH_CHECK_INIT)
3049 {
3050 /* lookup file in database */
3051 status = sh_hash_get_it (filename, &tmpFile);
3052 if (status != 0) {
3053 goto out;
3054 }
3055 }
3056 else
3057 {
3058 tmpFile.size = fbuf->st_size;
3059 }
3060
3061 /* if last < current get checksum */
3062 if (tmpFile.size < fbuf->st_size)
3063 {
3064 char hashbuf[KEYBUF_SIZE];
3065 UINT64 local_length = (UINT64) (tmpFile.size < 0 ? 0 : tmpFile.size);
3066 sl_strlcpy(fileHash,
3067 sh_tiger_generic_hash (filename, fd, &(local_length),
3068 alert_timeout, hashbuf, sizeof(hashbuf)),
3069 KEY_LEN+1);
3070
3071 /* return */
3072 if (tmpFile.link_path) SH_FREE(tmpFile.link_path);
3073 SL_RETURN( 0, _("sh_unix_checksum_size"));
3074 }
3075
3076 out:
3077 if (tmpFile.link_path) SH_FREE(tmpFile.link_path);
3078 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3079 SL_RETURN( -1, _("sh_unix_checksum_size"));
3080}
3081
3082int sh_unix_check_selinux = S_FALSE;
3083int sh_unix_check_acl = S_FALSE;
3084
3085#ifdef USE_ACL
3086
3087#include <sys/acl.h>
3088static char * sh_unix_getinfo_acl (char * path, int fd, struct stat * buf)
3089{
3090 /* system.posix_acl_access, system.posix_acl_default
3091 */
3092 char * out = NULL;
3093 char * collect = NULL;
3094 char * tmp;
3095 char * out_compact;
3096 ssize_t len;
3097 acl_t result;
3098
3099 SL_ENTER(_("sh_unix_getinfo_acl"));
3100
3101 result = (fd == -1) ?
3102 acl_get_file (path, ACL_TYPE_ACCESS) :
3103 acl_get_fd (fd);
3104
3105 if (result)
3106 {
3107 out = acl_to_text (result, &len);
3108 if (out && (len > 0)) {
3109 out_compact = sh_util_acl_compact (out, len);
3110 acl_free(out);
3111 if (out_compact)
3112 {
3113 collect = sh_util_strconcat (_("acl_access:"), out_compact, NULL);
3114 SH_FREE(out_compact);
3115 }
3116 }
3117 acl_free(result);
3118 }
3119
3120
3121 if ( S_ISDIR(buf->st_mode) )
3122 {
3123 result = acl_get_file (path, ACL_TYPE_DEFAULT);
3124
3125 if (result)
3126 {
3127 out = acl_to_text (result, &len);
3128 if (out && (len > 0)) {
3129 out_compact = sh_util_acl_compact (out, len);
3130 acl_free(out);
3131 if (out_compact) {
3132 if (collect) {
3133 tmp = sh_util_strconcat (_("acl_default:"),
3134 out_compact, ":", collect, NULL);
3135 SH_FREE(collect);
3136 }
3137 else {
3138 tmp = sh_util_strconcat (_("acl_default:"), out_compact, NULL);
3139 }
3140 SH_FREE(out_compact);
3141 collect = tmp;
3142 }
3143 }
3144 acl_free(result);
3145 }
3146 }
3147
3148 SL_RETURN((collect),_("sh_unix_getinfo_acl"));
3149}
3150#endif
3151
3152#ifdef USE_XATTR
3153
3154#include <attr/xattr.h>
3155static char * sh_unix_getinfo_xattr_int (char * path, int fd, char * name)
3156{
3157 char * out = NULL;
3158 char * tmp = NULL;
3159 size_t size = 256;
3160 ssize_t result;
3161
3162 SL_ENTER(_("sh_unix_getinfo_xattr_int"));
3163
3164 out = SH_ALLOC(size);
3165
3166 result = (fd == -1) ?
3167 lgetxattr (path, name, out, size-1) :
3168 fgetxattr (fd, name, out, size-1);
3169
3170 if (result == -1 && errno == ERANGE)
3171 {
3172 SH_FREE(out);
3173 result = (fd == -1) ?
3174 lgetxattr (path, name, NULL, 0) :
3175 fgetxattr (fd, name, NULL, 0);
3176 size = result + 1;
3177 out = SH_ALLOC(size);
3178 result = (fd == -1) ?
3179 lgetxattr (path, name, out, size-1) :
3180 fgetxattr (fd, name, out, size-1);
3181 }
3182
3183 if ((result > 0) && ((size_t)result < size))
3184 {
3185 out[size-1] = '\0';
3186 tmp = out;
3187 }
3188 else
3189 {
3190 SH_FREE(out);
3191 }
3192
3193 SL_RETURN((tmp),_("sh_unix_getinfo_xattr_int"));
3194}
3195
3196
3197static char * sh_unix_getinfo_xattr (char * path, int fd, struct stat * buf)
3198{
3199 /* system.posix_acl_access, system.posix_acl_default, security.selinux
3200 */
3201 char * tmp;
3202 char * out = NULL;
3203 char * collect = NULL;
3204
3205 SL_ENTER(_("sh_unix_getinfo_xattr"));
3206
3207#ifdef USE_ACL
3208 /*
3209 * we need the acl_get_fd/acl_get_file functions, getxattr will only
3210 * yield the raw bytes
3211 */
3212 if (sh_unix_check_acl == S_TRUE)
3213 {
3214 out = sh_unix_getinfo_acl(path, fd, buf);
3215
3216 if (out)
3217 {
3218 collect = out;
3219 }
3220 }
3221#endif
3222
3223 if (sh_unix_check_selinux == S_TRUE)
3224 {
3225 out = sh_unix_getinfo_xattr_int(path, fd, _("security.selinux"));
3226
3227 if (out)
3228 {
3229 if (collect) {
3230 tmp = sh_util_strconcat(_("selinux:"), out, ":", collect, NULL);
3231 SH_FREE(collect);
3232 }
3233 else {
3234 tmp = sh_util_strconcat(_("selinux:"), out, NULL);
3235 }
3236 SH_FREE(out);
3237 collect = tmp;
3238 }
3239 }
3240
3241 SL_RETURN((collect),_("sh_unix_getinfo_xattr"));
3242}
3243#endif
3244
3245#ifdef USE_XATTR
3246int sh_unix_setcheckselinux (const char * c)
3247{
3248 int i;
3249 SL_ENTER(_("sh_unix_setcheckselinux"));
3250 i = sh_util_flagval(c, &(sh_unix_check_selinux));
3251
3252 SL_RETURN(i, _("sh_unix_setcheckselinux"));
3253}
3254#endif
3255
3256#ifdef USE_ACL
3257int sh_unix_setcheckacl (const char * c)
3258{
3259 int i;
3260 SL_ENTER(_("sh_unix_setcheckacl"));
3261 i = sh_util_flagval(c, &(sh_unix_check_acl));
3262
3263 SL_RETURN(i, _("sh_unix_setcheckacl"));
3264}
3265#endif
3266
3267#ifdef HAVE_LIBZ
3268#include <zlib.h>
3269#endif
3270
3271int sh_unix_getinfo (int level, char * filename, file_type * theFile,
3272 char * fileHash, int policy)
3273{
3274 char timestr[81];
3275 long runtim;
3276 struct stat buf;
3277 struct stat lbuf;
3278 struct stat fbuf;
3279 int stat_return;
3280
3281 ShFileType type;
3282 unsigned int mode;
3283 char * tmp;
3284 char * tmp2;
3285
3286 char * linknamebuf;
3287 int linksize;
3288
3289 extern int get_the_fd (SL_TICKET ticket);
3290
3291 SL_TICKET rval_open;
3292 int fd;
3293 int fstat_return;
3294 sh_string * content = NULL;
3295
3296 time_t tend;
3297 time_t tstart;
3298
3299
3300 char * path = NULL;
3301
3302 int alert_timeout = 120;
3303
3304 path = theFile->fullpath;
3305
3306 SL_ENTER(_("sh_unix_getinfo"));
3307
3308 /* --- Stat the file, and get checksum. ---
3309 */
3310 tstart = time(NULL);
3311
3312 stat_return = retry_lstat (FIL__, __LINE__,
3313 path /* theFile->fullpath */, &buf);
3314
3315 fd = -1;
3316 fstat_return = -1;
3317 rval_open = -1;
3318
3319 theFile->link_path = NULL;
3320
3321 if (stat_return == 0 && S_ISREG(buf.st_mode))
3322 {
3323 rval_open = sl_open_fastread (path /* theFile->fullpath */, SL_YESPRIV);
3324
3325 alert_timeout = 120; /* this is per 8K block now ! */
3326
3327 if (path[1] == 'p' && path[5] == '/' && path[2] == 'r' &&
3328 path[3] == 'o' && path[4] == 'c' && path[0] == '/')
3329 {
3330 /* seven is magic */
3331 alert_timeout = 7;
3332 }
3333
3334 fd = get_the_fd(rval_open);
3335 }
3336
3337 tend = time(NULL);
3338
3339 /* An unprivileged user may slow lstat/open to a crawl
3340 * with clever path/symlink setup
3341 */
3342 if ((tend - tstart) > (time_t) /* 60 */ 6)
3343 {
3344 tmp2 = sh_util_safe_name (theFile->fullpath);
3345 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_TOOLATE,
3346 (long)(tend - tstart), tmp2);
3347 SH_FREE(tmp2);
3348 }
3349
3350 if (fd >= 0)
3351 fstat_return = retry_fstat (FIL__, __LINE__, fd, &fbuf);
3352 else
3353 fd = -1;
3354
3355
3356 /* --- case 1: lstat failed ---
3357 */
3358 if (stat_return != 0)
3359 {
3360 stat_return = errno;
3361 if (!SL_ISERROR(rval_open))
3362 sl_close(rval_open);
3363 if (sh.flag.checkSum == SH_CHECK_INIT ||
3364 (sh_hash_have_it (theFile->fullpath) >= 0 &&
3365 (!SH_FFLAG_REPORTED_SET(theFile->file_reported))))
3366 {
3367 if (S_FALSE == sh_ignore_chk_del(theFile->fullpath)) {
3368 char errbuf[SH_ERRBUF_SIZE];
3369 tmp2 = sh_util_safe_name (theFile->fullpath);
3370 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_LSTAT,
3371 sh_error_message (stat_return, errbuf, sizeof(errbuf)),
3372 tmp2);
3373 SH_FREE(tmp2);
3374 }
3375 }
3376 SL_RETURN((-1),_("sh_unix_getinfo"));
3377 }
3378
3379 /* --- case 2: not a regular file ---
3380 */
3381 else if (! S_ISREG(buf.st_mode))
3382 {
3383 if (fileHash != NULL)
3384 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3385 }
3386
3387 /* --- case 3a: a regular file, fstat ok ---
3388 */
3389 else if (fstat_return == 0 &&
3390 buf.st_mode == fbuf.st_mode &&
3391 buf.st_ino == fbuf.st_ino &&
3392 buf.st_uid == fbuf.st_uid &&
3393 buf.st_gid == fbuf.st_gid &&
3394 buf.st_dev == fbuf.st_dev )
3395 {
3396 if (fileHash != NULL)
3397 {
3398 if ((theFile->check_mask & MODI_CHK) == 0)
3399 {
3400 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3401 }
3402 else if ((theFile->check_mask & MODI_PREL) != 0 &&
3403 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3404 alert_timeout, theFile->fullpath))
3405 {
3406 if (0 != sh_prelink_run (theFile->fullpath,
3407 fileHash, alert_timeout))
3408 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3409 }
3410 else
3411 {
3412 char hashbuf[KEYBUF_SIZE];
3413 UINT64 length_nolim = TIGER_NOLIM;
3414
3415 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3416 {
3417 sl_init_content (rval_open, fbuf.st_size);
3418 }
3419
3420 sl_strlcpy(fileHash,
3421 sh_tiger_generic_hash (theFile->fullpath,
3422 rval_open, &length_nolim,
3423 alert_timeout,
3424 hashbuf, sizeof(hashbuf)),
3425 KEY_LEN+1);
3426
3427 content = sl_get_content(rval_open);
3428 content = sh_string_copy(content);
3429
3430 if ((theFile->check_mask & MODI_SGROW) != 0)
3431 {
3432 fbuf.st_size = (off_t) length_nolim;
3433 buf.st_size = fbuf.st_size;
3434 sl_rewind(rval_open);
3435 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3436 &fileHash[KEY_LEN + 1],
3437 alert_timeout, rval_open);
3438 }
3439 }
3440 }
3441 }
3442
3443 /* --- case 3b: a regular file, fstat ok, but different ---
3444 */
3445 else if (fstat_return == 0 && S_ISREG(fbuf.st_mode))
3446 {
3447 memcpy (&buf, &fbuf, sizeof( struct stat ));
3448
3449 if (fileHash != NULL)
3450 {
3451 if ((theFile->check_mask & MODI_CHK) == 0)
3452 {
3453 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3454 }
3455 else if (policy == SH_LEVEL_PRELINK &&
3456 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3457 alert_timeout, theFile->fullpath))
3458 {
3459 if (0 != sh_prelink_run (theFile->fullpath,
3460 fileHash, alert_timeout))
3461 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3462 }
3463 else
3464 {
3465 char hashbuf[KEYBUF_SIZE];
3466 UINT64 length_nolim = TIGER_NOLIM;
3467
3468 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3469 {
3470 sl_init_content (rval_open, fbuf.st_size);
3471 }
3472
3473 sl_strlcpy(fileHash,
3474 sh_tiger_generic_hash (theFile->fullpath, rval_open,
3475 &length_nolim,
3476 alert_timeout,
3477 hashbuf, sizeof(hashbuf)),
3478 KEY_LEN + 1);
3479
3480 content = sl_get_content(rval_open);
3481 content = sh_string_copy(content);
3482
3483 if ((theFile->check_mask & MODI_SGROW) != 0)
3484 {
3485 fbuf.st_size = (off_t) length_nolim;
3486 buf.st_size = fbuf.st_size;
3487 sl_rewind(rval_open);
3488 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3489 &fileHash[KEY_LEN + 1],
3490 alert_timeout, rval_open);
3491 }
3492 }
3493 }
3494 }
3495
3496 /* --- case 4: a regular file, fstat failed ---
3497 */
3498
3499 else /* fstat_return != 0 or !S_ISREG(fbuf->st_mode) */
3500 {
3501 fstat_return = errno;
3502 if (fileHash != NULL)
3503 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3504
3505 if ((theFile->check_mask & MODI_CHK) != 0)
3506 {
3507 tmp2 = sh_util_safe_name (theFile->fullpath);
3508 sh_error_handle (level, FIL__, __LINE__, fstat_return, MSG_E_READ,
3509 tmp2);
3510 SH_FREE(tmp2);
3511 }
3512 }
3513
3514
3515 /* --- Determine file type. ---
3516 */
3517 memset (theFile->c_mode, '-', CMODE_SIZE-1);
3518 theFile->c_mode[CMODE_SIZE-1] = '\0';
3519
3520 memset (theFile->link_c_mode, '-', CMODE_SIZE-1);
3521 theFile->link_c_mode[CMODE_SIZE-1] = '\0';
3522
3523 sh_unix_getinfo_type (&buf, &type, theFile->c_mode);
3524 theFile->type = type;
3525
3526#if defined(__linux__) || defined(HAVE_STAT_FLAGS)
3527
3528 /* --- Determine file attributes. ---
3529 */
3530 memset (theFile->c_attributes, '-', ATTRBUF_SIZE);
3531 theFile->c_attributes[ATTRBUF_USED] = '\0';
3532 theFile->attributes = 0;
3533
3534 if (theFile->c_mode[0] != 'c' && theFile->c_mode[0] != 'b' &&
3535 theFile->c_mode[0] != 'l' )
3536 sh_unix_getinfo_attr(theFile->fullpath,
3537 &theFile->attributes, theFile->c_attributes,
3538 fd, &buf);
3539#endif
3540
3541#if defined(USE_XATTR) && defined(USE_ACL)
3542 if (sh_unix_check_selinux == S_TRUE || sh_unix_check_acl == S_TRUE)
3543 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
3544#elif defined(USE_XATTR)
3545 if (sh_unix_check_selinux == S_TRUE)
3546 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
3547#elif defined(USE_ACL)
3548 if (sh_unix_check_acl == S_TRUE)
3549 theFile->attr_string = sh_unix_getinfo_acl (theFile->fullpath, fd, &buf);
3550#else
3551 theFile->attr_string = NULL;
3552#endif
3553
3554 if (!SL_ISERROR(rval_open))
3555 sl_close(rval_open);
3556
3557
3558 /* --- I/O limit. ---
3559 */
3560 if (IO_Limit > 0)
3561 {
3562 runtim = (long) (time(NULL) - sh.statistics.time_start);
3563
3564 if (runtim > 0 && (long)(sh.statistics.bytes_hashed/runtim) > IO_Limit)
3565 retry_msleep(1, 0);
3566 }
3567
3568 /* --- Determine permissions. ---
3569 */
3570 sh_unix_getinfo_mode (&buf, &mode, theFile->c_mode);
3571
3572 /* --- Trivia. ---
3573 */
3574 theFile->dev = buf.st_dev;
3575 theFile->ino = buf.st_ino;
3576 theFile->mode = buf.st_mode;
3577 theFile->hardlinks = buf.st_nlink;
3578 theFile->owner = buf.st_uid;
3579 theFile->group = buf.st_gid;
3580 theFile->rdev = buf.st_rdev;
3581 theFile->size = buf.st_size;
3582 theFile->blksize = (unsigned long) buf.st_blksize;
3583 theFile->blocks = (unsigned long) buf.st_blocks;
3584 theFile->atime = buf.st_atime;
3585 theFile->mtime = buf.st_mtime;
3586 theFile->ctime = buf.st_ctime;
3587
3588
3589 /* --- Owner and group. ---
3590 */
3591
3592 if (NULL == sh_unix_getGIDname(SH_ERR_ALL, buf.st_gid, theFile->c_group, GROUP_MAX+1)) {
3593
3594 tmp2 = sh_util_safe_name (theFile->fullpath);
3595
3596 if (policy == SH_LEVEL_ALLIGNORE)
3597 {
3598 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
3599 MSG_FI_NOGRP,
3600 (long) buf.st_gid, tmp2);
3601 }
3602 else
3603 {
3604 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
3605 MSG_FI_NOGRP,
3606 (long) buf.st_gid, tmp2);
3607 }
3608 SH_FREE(tmp2);
3609 sl_snprintf(theFile->c_group, GROUP_MAX+1, "%d", (long) buf.st_gid);
3610 }
3611
3612
3613 if (NULL == sh_unix_getUIDname(SH_ERR_ALL, buf.st_uid, theFile->c_owner, USER_MAX+1)) {
3614
3615 tmp2 = sh_util_safe_name (theFile->fullpath);
3616
3617 if (policy == SH_LEVEL_ALLIGNORE)
3618 {
3619 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
3620 MSG_FI_NOUSR,
3621 (long) buf.st_uid, tmp2);
3622 }
3623 else
3624 {
3625 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
3626 MSG_FI_NOUSR,
3627 (long) buf.st_uid, tmp2);
3628 }
3629 SH_FREE(tmp2);
3630 sl_snprintf(theFile->c_owner, USER_MAX+1, "%d", (long) buf.st_uid);
3631 }
3632
3633 /* --- Output the file. ---
3634 */
3635 if (flag_err_debug == SL_TRUE)
3636 {
3637 tmp2 = sh_util_safe_name ((filename == NULL) ?
3638 theFile->fullpath : filename);
3639 (void) sh_unix_time(theFile->mtime, timestr, sizeof(timestr));
3640 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LIST,
3641 theFile->c_mode,
3642 theFile->hardlinks,
3643 theFile->c_owner,
3644 theFile->c_group,
3645 (unsigned long) theFile->size,
3646 timestr,
3647 tmp2);
3648 SH_FREE(tmp2);
3649 }
3650
3651 /* --- Check for links. ---
3652 */
3653 if (theFile->c_mode[0] == 'l')
3654 {
3655 linknamebuf = SH_ALLOC(PATH_MAX);
3656
3657 /* flawfinder: ignore */
3658 linksize = readlink (theFile->fullpath, linknamebuf, PATH_MAX-1);
3659
3660 if (linksize < (PATH_MAX-1) && linksize >= 0)
3661 linknamebuf[linksize] = '\0';
3662 else
3663 linknamebuf[PATH_MAX-1] = '\0';
3664
3665 if (linksize < 0)
3666 {
3667 char errbuf[SH_ERRBUF_SIZE];
3668 linksize = errno;
3669 tmp2 = sh_util_safe_name (theFile->fullpath);
3670 sh_error_handle (level, FIL__, __LINE__, linksize, MSG_FI_RDLNK,
3671 sh_error_message (linksize, errbuf, sizeof(errbuf)), tmp2);
3672 SH_FREE(tmp2);
3673 SH_FREE(linknamebuf);
3674 theFile->link_path = sh_util_strdup("-");
3675 SL_RETURN((-1),_("sh_unix_getinfo"));
3676 }
3677
3678 if (linknamebuf[0] == '/')
3679 {
3680 theFile->link_path = sh_util_strdup (linknamebuf);
3681 }
3682 else
3683 {
3684 tmp = sh_util_dirname(theFile->fullpath);
3685 if (tmp) {
3686 theFile->link_path = SH_ALLOC(PATH_MAX);
3687 sl_strlcpy (theFile->link_path, tmp, PATH_MAX);
3688 SH_FREE(tmp);
3689 } else {
3690 theFile->link_path = SH_ALLOC(PATH_MAX);
3691 theFile->link_path[0] = '\0';
3692 }
3693 /*
3694 * Only attach '/' if not root directory. Handle "//", which
3695 * according to POSIX is implementation-defined, and may be
3696 * different from "/" (however, three or more '/' will collapse
3697 * to one).
3698 */
3699 tmp = theFile->link_path; while (*tmp == '/') ++tmp;
3700 if (*tmp != '\0')
3701 {
3702 sl_strlcat (theFile->link_path, "/", PATH_MAX);
3703 }
3704 sl_strlcat (theFile->link_path, linknamebuf, PATH_MAX);
3705 }
3706
3707 /* stat the link
3708 */
3709 stat_return = retry_lstat (FIL__, __LINE__, theFile->link_path, &lbuf);
3710
3711 /* check for error
3712 */
3713 if (stat_return != 0)
3714 {
3715 stat_return = errno;
3716 tmp = sh_util_safe_name (theFile->fullpath);
3717 tmp2 = sh_util_safe_name (theFile->link_path);
3718 if (stat_return != ENOENT)
3719 {
3720 char errbuf[SH_ERRBUF_SIZE];
3721 sh_error_handle (level, FIL__, __LINE__, stat_return,
3722 MSG_FI_LSTAT,
3723 sh_error_message (stat_return,errbuf, sizeof(errbuf)),
3724 tmp2);
3725 }
3726 else
3727 {
3728 /* a dangling link -- everybody seems to have plenty of them
3729 */
3730 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_DLNK,
3731 tmp, tmp2);
3732 }
3733 theFile->linkisok = BAD;
3734 SH_FREE(tmp);
3735 SH_FREE(tmp2);
3736 SH_FREE(linknamebuf);
3737 /*
3738 * changed Tue Feb 10 16:16:13 CET 2004:
3739 * add dangling symlinks into database
3740 * SL_RETURN((-1),_("sh_unix_getinfo"));
3741 */
3742 theFile->linkmode = 0;
3743 SL_RETURN((0),_("sh_unix_getinfo"));
3744 }
3745
3746 theFile->linkisok = GOOD;
3747
3748
3749 /* --- Determine file type. ---
3750 */
3751 sh_unix_getinfo_type (&lbuf, &type, theFile->link_c_mode);
3752 theFile->type = type;
3753
3754 /* --- Determine permissions. ---
3755 */
3756 sh_unix_getinfo_mode (&lbuf, &mode, theFile->link_c_mode);
3757 theFile->linkmode = lbuf.st_mode;
3758
3759 /* --- Output the link. ---
3760 */
3761 if (theFile->linkisok == GOOD)
3762 {
3763 tmp2 = sh_util_safe_name (linknamebuf);
3764 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LLNK,
3765 theFile->link_c_mode, tmp2);
3766 SH_FREE(tmp2);
3767 }
3768 SH_FREE(linknamebuf);
3769 }
3770 else /* not a link */
3771 {
3772 if (content)
3773 {
3774#ifdef HAVE_LIBZ
3775 unsigned long clen;
3776 unsigned char * compressed;
3777#ifdef HAVE_COMPRESSBOUND
3778 clen = compressBound(sh_string_len(content));
3779#else
3780 if (sh_string_len(content) > 10*SH_TXT_MAX)
3781 clen = SH_TXT_MAX;
3782 else
3783 clen = 13 + (int)(1.0001*sh_string_len(content));
3784#endif
3785 compressed = SH_ALLOC(clen);
3786 if (Z_OK == compress(compressed, &clen,
3787 (unsigned char *) sh_string_str(content),
3788 sh_string_len(content)))
3789 {
3790 if (clen < SH_TXT_MAX)
3791 {
3792 sh_util_base64_enc_alloc (&(theFile->link_path),
3793 (char *) compressed, clen);
3794 }
3795 else
3796 {
3797 char tmsg[128];
3798 char * tpath = sh_util_safe_name (theFile->fullpath);
3799 sl_snprintf(tmsg, sizeof(tmsg),
3800 _("compressed file too large (%lu bytes)"),
3801 clen);
3802 sh_error_handle (SH_ERR_WARN, FIL__, __LINE__, -1,
3803 MSG_E_SUBGPATH, tmsg,
3804 _("sh_unix_getinfo"), tpath);
3805 SH_FREE(tpath);
3806 }
3807 }
3808 SH_FREE(compressed);
3809#endif
3810 sh_string_destroy(&content);
3811 }
3812 }
3813 SL_RETURN((0),_("sh_unix_getinfo"));
3814}
3815
3816/* #if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE) */
3817#endif
3818
3819int sh_unix_unlock(char * lockfile, char * flag)
3820{
3821 int error = 0;
3822
3823 SL_ENTER(_("sh_unix_unlock"));
3824
3825 if (sh.flag.isdaemon == S_FALSE && flag == NULL)
3826 SL_RETURN((0),_("sh_unix_unlock"));
3827
3828 /* --- Logfile is not locked to us. ---
3829 */
3830 if (sh.flag.islocked == BAD && flag != NULL)
3831 SL_RETURN((-1),_("sh_unix_unlock"));
3832
3833 /* --- Check whether the directory is secure. ---
3834 */
3835 if (0 != tf_trust_check (lockfile, SL_YESPRIV))
3836 SL_RETURN((-1),_("sh_unix_unlock"));
3837
3838 /* --- Delete the lock file. ---
3839 */
3840 error = retry_aud_unlink (FIL__, __LINE__, lockfile);
3841
3842 if (error == 0)
3843 {
3844 if (flag != NULL)
3845 sh.flag.islocked = BAD; /* not locked anymore */
3846 }
3847 else if (flag != NULL)
3848 {
3849 char errbuf[SH_ERRBUF_SIZE];
3850 error = errno;
3851 sh_error_handle ((-1), FIL__, __LINE__, error, MSG_E_UNLNK,
3852 sh_error_message(error, errbuf, sizeof(errbuf)),
3853 lockfile);
3854 SL_RETURN((-1),_("sh_unix_unlock"));
3855 }
3856 SL_RETURN((0),_("sh_unix_unlock"));
3857}
3858
3859int sh_unix_lock (char * lockfile, char * flag)
3860{
3861 int filed;
3862 int errnum;
3863 char myPid[64];
3864 SL_TICKET fd;
3865 extern int get_the_fd (SL_TICKET ticket);
3866
3867 SL_ENTER(_("sh_unix_lock"));
3868
3869 sprintf (myPid, "%ld\n", (long) sh.pid); /* known to fit */
3870
3871 fd = sl_open_safe_rdwr (lockfile, SL_YESPRIV); /* fails if file exists */
3872
3873 if (!SL_ISERROR(fd))
3874 {
3875 errnum = sl_write (fd, myPid, sl_strlen(myPid));
3876 filed = get_the_fd(fd);
3877 fchmod (filed, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
3878 sl_close (fd);
3879
3880 if (!SL_ISERROR(errnum))
3881 {
3882 if (flag != NULL)
3883 sh.flag.islocked = GOOD;
3884 SL_RETURN((0),_("sh_unix_lock"));
3885 }
3886 }
3887
3888 TPT((0, FIL__, __LINE__, _("msg=<open pid file failed>\n")));
3889 if (flag != NULL)
3890 sh.flag.islocked = BAD;
3891 SL_RETURN((-1),_("sh_unix_lock"));
3892
3893 /* notreached */
3894}
3895
3896
3897/* check whether file is locked
3898 */
3899int sh_unix_test_and_lock (char * filename, char * lockfile)
3900{
3901 static struct stat buf;
3902 int status = 0;
3903
3904
3905 SL_TICKET fd;
3906 char line_in[128];
3907
3908 SL_ENTER(_("sh_unix_test_and_lock"));
3909
3910 status = retry_lstat (FIL__, __LINE__, lockfile, &buf);
3911
3912 /* --- No lock file found, try to lock. ---
3913 */
3914
3915 if (status < 0 && errno == ENOENT)
3916 {
3917 if (0 == sh_unix_lock (lockfile, filename))
3918 {
3919 if (filename != NULL)
3920 sh.flag.islocked = GOOD;
3921 SL_RETURN((0),_("sh_unix_test_and_lock"));
3922 }
3923 else
3924 {
3925 sh_error_handle ((-1), FIL__, __LINE__, status,
3926 MSG_E_SUBGEN,
3927 (filename == NULL) ? _("Cannot create PID file") : _("Cannot create lock file"),
3928 _("sh_unix_test_and_lock"));
3929 SL_RETURN((-1),_("sh_unix_test_and_lock"));
3930 }
3931 }
3932 else if (status == 0 && buf.st_size == 0)
3933 {
3934 if (filename != NULL)
3935 sh.flag.islocked = GOOD;
3936 sh_unix_unlock (lockfile, filename);
3937 if (filename != NULL)
3938 sh.flag.islocked = BAD;
3939 if (0 == sh_unix_lock (lockfile, filename))
3940 {
3941 if (filename != NULL)
3942 sh.flag.islocked = GOOD;
3943 SL_RETURN((0),_("sh_unix_test_and_lock"));
3944 }
3945 else
3946 {
3947 sh_error_handle ((-1), FIL__, __LINE__, status,
3948 MSG_E_SUBGEN,
3949 (filename == NULL) ? _("Cannot create PID file") : _("Cannot create lock file"),
3950 _("sh_unix_test_and_lock"));
3951 SL_RETURN((-1),_("sh_unix_test_and_lock"));
3952 }
3953 }
3954
3955 /* --- Check on lock. ---
3956 */
3957
3958 if (status >= 0)
3959 {
3960 fd = sl_open_read (lockfile, SL_YESPRIV);
3961 if (SL_ISERROR(fd))
3962 sh_error_handle ((-1), FIL__, __LINE__, fd,
3963 MSG_E_SUBGEN,
3964 (filename == NULL) ? _("Cannot open PID file for read") : _("Cannot open lock file for read"),
3965 _("sh_unix_test_and_lock"));
3966 }
3967 else
3968 fd = -1;
3969
3970 if (!SL_ISERROR(fd))
3971 {
3972 /* read the PID in the lock file
3973 */
3974 status = sl_read (fd, line_in, sizeof(line_in));
3975 line_in[sizeof(line_in)-1] = '\0';
3976
3977 /* convert to numeric
3978 */
3979 if (status > 0)
3980 {
3981 errno = 0;
3982 status = strtol(line_in, (char **)NULL, 10);
3983 if (errno == ERANGE || status <= 0)
3984 {
3985 sh_error_handle ((-1), FIL__, __LINE__, status,
3986 MSG_E_SUBGEN,
3987 (filename == NULL) ? _("Bad PID in PID file") : _("Bad PID in lock file"),
3988 _("sh_unix_test_and_lock"));
3989
3990 status = -1;
3991 }
3992 }
3993 else
3994 {
3995 sh_error_handle ((-1), FIL__, __LINE__, status,
3996 MSG_E_SUBGEN,
3997 (filename == NULL) ? _("Cannot read PID file") : _("Cannot read lock file"),
3998 _("sh_unix_test_and_lock"));
3999 }
4000 sl_close(fd);
4001
4002 if (status > 0 && (unsigned int) status == sh.pid)
4003 {
4004 if (filename != NULL)
4005 sh.flag.islocked = GOOD;
4006 SL_RETURN((0),_("sh_unix_test_and_lock"));
4007 }
4008
4009
4010 /* --- Check whether the process exists. ---
4011 */
4012 if (status > 0)
4013 {
4014 errno = 0;
4015 status = aud_kill (FIL__, __LINE__, status, 0);
4016
4017 /* Does not exist, so remove the stale lock
4018 * and create a new one.
4019 */
4020 if (status < 0 && errno == ESRCH)
4021 {
4022 if (filename != NULL)
4023 sh.flag.islocked = GOOD;
4024 if (0 != sh_unix_unlock(lockfile, filename) && (filename !=NULL))
4025 sh.flag.islocked = BAD;
4026 else
4027 {
4028 if (0 == sh_unix_lock (lockfile, filename))
4029 {
4030 if (filename != NULL)
4031 sh.flag.islocked = GOOD;
4032 SL_RETURN((0),_("sh_unix_test_and_lock"));
4033 }
4034 else
4035 {
4036 sh_error_handle ((-1), FIL__, __LINE__, status,
4037 MSG_E_SUBGEN,
4038 (filename == NULL) ? _("Cannot create PID file") : _("Cannot create lock file"),
4039 _("sh_unix_test_and_lock"));
4040 }
4041 if (filename != NULL)
4042 sh.flag.islocked = BAD;
4043 }
4044 }
4045 else
4046 {
4047 sh_error_handle ((-1), FIL__, __LINE__, status,
4048 MSG_E_SUBGEN,
4049 (filename == NULL) ? _("Cannot remove stale PID file, PID may be a running process") : _("Cannot remove stale lock file, PID may be a running process"),
4050 _("sh_unix_test_and_lock"));
4051 if (filename != NULL)
4052 sh.flag.islocked = BAD;
4053 }
4054 }
4055 }
4056 SL_RETURN((-1),_("sh_unix_testlock"));
4057}
4058
4059/* write the PID file
4060 */
4061int sh_unix_write_pid_file()
4062{
4063 return sh_unix_test_and_lock(NULL, sh.srvlog.alt);
4064}
4065
4066/* write lock for filename
4067 */
4068int sh_unix_write_lock_file(char * filename)
4069{
4070 size_t len;
4071 int res;
4072 char * lockfile;
4073
4074 if (filename == NULL)
4075 return (-1);
4076
4077 len = sl_strlen(filename);
4078 if (sl_ok_adds(len, 6))
4079 len += 6;
4080 lockfile = SH_ALLOC(len);
4081 sl_strlcpy(lockfile, filename, len);
4082 sl_strlcat(lockfile, _(".lock"), len);
4083 res = sh_unix_test_and_lock(filename, lockfile);
4084 SH_FREE(lockfile);
4085 return res;
4086}
4087
4088/* rm lock for filename
4089 */
4090int sh_unix_rm_lock_file(char * filename)
4091{
4092 size_t len;
4093 int res;
4094 char * lockfile;
4095
4096 if (filename == NULL)
4097 return (-1);
4098
4099 len = sl_strlen(filename);
4100 if (sl_ok_adds(len, 6))
4101 len += 6;
4102 lockfile = SH_ALLOC(len);
4103 sl_strlcpy(lockfile, filename, len);
4104 sl_strlcat(lockfile, _(".lock"), len);
4105
4106 res = sh_unix_unlock(lockfile, filename);
4107 SH_FREE(lockfile);
4108 return res;
4109}
4110
4111/* rm lock for filename
4112 */
4113int sh_unix_rm_pid_file()
4114{
4115 return sh_unix_unlock(sh.srvlog.alt, NULL);
4116}
4117
4118/* Test whether file exists
4119 */
4120int sh_unix_file_exists(char * path)
4121{
4122 struct stat buf;
4123
4124 SL_ENTER(_("sh_unix_file_exists"));
4125
4126 if (-1 == retry_stat(FIL__, __LINE__, path, &buf))
4127 SL_RETURN( S_FALSE, _("sh_unix_file_exists"));
4128 else
4129 SL_RETURN( S_TRUE, _("sh_unix_file_exists"));
4130}
4131
4132
4133/* Test whether file exists, is a character device, and allows read
4134 * access.
4135 */
4136int sh_unix_device_readable(int fd)
4137{
4138 struct stat buf;
4139
4140 SL_ENTER(_("sh_unix_device_readable"));
4141
4142 if (retry_fstat(FIL__, __LINE__, fd, &buf) == -1)
4143 SL_RETURN( (-1), _("sh_unix_device_readable"));
4144 else if ( S_ISCHR(buf.st_mode) && 0 != (S_IROTH & buf.st_mode) )
4145 SL_RETURN( (0), _("sh_unix_device_readable"));
4146 else
4147 SL_RETURN( (-1), _("sh_unix_device_readable"));
4148}
4149
4150static char preq[16];
4151
4152/* return true if database is remote
4153 */
4154int file_is_remote ()
4155{
4156 static int init = 0;
4157 struct stat buf;
4158
4159 SL_ENTER(_("file_is_remote"));
4160
4161 if (init == 0)
4162 {
4163 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4164 ++init;
4165 }
4166 if (0 == sl_strncmp (sh.data.path, preq, 15))
4167 {
4168 if (sh.data.path[15] != '\0') /* should be start of path */
4169 {
4170 if (0 == stat(&(sh.data.path[15]), &buf))
4171 {
4172 SL_RETURN( S_FALSE, _("file_is_remote"));
4173 }
4174 }
4175 SL_RETURN( S_TRUE, _("file_is_remote"));
4176 }
4177 SL_RETURN( S_FALSE, _("file_is_remote"));
4178}
4179
4180/* Return the path to the configuration/database file.
4181 */
4182char * file_path(char what, char flag)
4183{
4184 static int init = 0;
4185
4186 SL_ENTER(_("file_path"));
4187
4188 if (init == 0)
4189 {
4190 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4191 ++init;
4192 }
4193
4194 switch (what)
4195 {
4196
4197 case 'C':
4198 if (0 == sl_strncmp (sh.conf.path, preq, 15))
4199 {
4200#if defined(SH_WITH_SERVER)
4201 if (sh.flag.isserver == S_TRUE && sl_strlen(sh.conf.path) == 15)
4202 SL_RETURN( NULL, _("file_path"));
4203 if (sh.flag.isserver == S_TRUE)
4204 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4205#endif
4206 if (flag == 'R')
4207 SL_RETURN( preq, _("file_path"));
4208 if (flag == 'I')
4209 {
4210 if (sl_strlen(sh.conf.path) == 15)
4211 SL_RETURN( NULL, _("file_path"));
4212 else
4213 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4214 }
4215 SL_RETURN ( preq, _("file_path"));
4216 }
4217 else
4218 SL_RETURN( sh.conf.path, _("file_path"));
4219 /* break; *//* unreachable */
4220
4221 case 'D':
4222 if (0 == sl_strncmp (sh.data.path, preq, 15))
4223 {
4224 if (flag == 'R')
4225 SL_RETURN( preq, _("file_path"));
4226 if (flag == 'W' && sl_strlen(sh.data.path) == 15)
4227 SL_RETURN (NULL, _("file_path"));
4228 if (flag == 'W')
4229 SL_RETURN( &(sh.data.path[15]), _("file_path"));
4230 }
4231 else
4232 SL_RETURN( sh.data.path, _("file_path"));
4233 break;
4234
4235 default:
4236 SL_RETURN( NULL, _("file_path"));
4237 }
4238
4239 return NULL; /* notreached */
4240}
4241/************************************************/
4242/**** Mlock Utilities ****/
4243/************************************************/
4244
4245#include <limits.h>
4246
4247int sh_unix_pagesize()
4248{
4249 int pagesize = 4096;
4250#if defined(_SC_PAGESIZE)
4251 pagesize = sysconf(_SC_PAGESIZE);
4252#elif defined(_SC_PAGE_SIZE)
4253 pagesize = sysconf(_SC_PAGE_SIZE);
4254#elif defined(HAVE_GETPAGESIZE)
4255 pagesize = getpagesize();
4256#elif defined(PAGESIZE)
4257 pagesize = PAGESIZE;
4258#endif
4259
4260 return ((pagesize > 0) ? pagesize : 4096);
4261}
4262
4263typedef struct sh_page_lt {
4264 unsigned long page_start;
4265 int page_refcount;
4266 char file[64];
4267 int line;
4268 struct sh_page_lt * next;
4269} sh_page_l;
4270
4271sh_page_l * sh_page_locked = NULL;
4272volatile int page_locking = 0;
4273
4274unsigned long sh_unix_lookup_page (void * in_addr, size_t len, int * num_pages)
4275{
4276 int pagesize = sh_unix_pagesize();
4277 unsigned long addr = (unsigned long) in_addr;
4278
4279 unsigned long pagebase;
4280 unsigned long pagediff;
4281 unsigned long pagenum = addr / pagesize;
4282
4283 SL_ENTER(_("sh_unix_lookup_page"));
4284#if 0
4285 fprintf(stderr, "mlock: --> base %ld, pagenum: %ld\n",
4286 addr, pagenum);
4287#endif
4288
4289 /* address of first page
4290 */
4291 pagebase = pagenum * pagesize;
4292
4293 /* number of pages
4294 */
4295 pagediff = (addr + len) - pagebase;
4296 pagenum = pagediff / pagesize;
4297 if (pagenum * pagesize < pagediff)
4298 ++pagenum;
4299
4300#if 0
4301 fprintf(stderr, "mlock: --> pagebase %ld, pagediff %ld, (addr + len) %ld\n",
4302 pagebase, pagediff, (addr + len));
4303#endif
4304
4305 *num_pages = pagenum;
4306 SL_RETURN((pagebase), _("sh_unix_lookup_page"));
4307}
4308
4309
4310#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4311
4312SH_MUTEX_STATIC(mutex_mlock,PTHREAD_MUTEX_INITIALIZER);
4313
4314int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4315{
4316 int num_pages;
4317 int status = 0;
4318 int pagesize;
4319 sh_page_l * page_list = sh_page_locked;
4320 unsigned long addr;
4321#ifdef TEST_MLOCK
4322 int i = 0;
4323#endif
4324
4325 SL_ENTER(_("sh_unix_mlock"));
4326
4327 /* There's no cancellation point here, except if tracing is on
4328 */
4329 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4330
4331 if (0 != page_locking)
4332 {
4333 status = -1;
4334 goto exit_mlock;
4335 }
4336
4337 page_locking = 1;
4338
4339 pagesize = sh_unix_pagesize();
4340 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4341
4342#ifdef TEST_MLOCK
4343 fprintf(stderr, "mlock: addr %ld, base %ld, pages: %d, length %d\n",
4344 (unsigned long) in_addr, addr, num_pages, len);
4345#endif
4346
4347 /* increase refcount of locked pages
4348 * addr is first page; num_pages is #(consecutive pages) to lock
4349 */
4350
4351 while ((page_list != NULL) && (num_pages > 0))
4352 {
4353#ifdef TEST_MLOCK
4354 fprintf(stderr, "mlock: check page %d: %ld [%d]\n",
4355 i, page_list->page_start, page_list->page_refcount);
4356#endif
4357 if (page_list->page_start == addr)
4358 {
4359 page_list->page_refcount += 1;
4360 num_pages -= 1;
4361 addr += pagesize;
4362#ifdef TEST_MLOCK
4363 fprintf(stderr, "mlock: found page %d: %ld [%d], next page %ld\n",
4364 i, page_list->page_start, page_list->page_refcount, addr);
4365#endif
4366 }
4367#ifdef TEST_MLOCK
4368 ++i;
4369#endif
4370 page_list = page_list->next;
4371 }
4372
4373 /* mlock some more pages, if needed
4374 */
4375 while (num_pages > 0)
4376 {
4377#ifdef TEST_MLOCK
4378 fprintf(stderr, "mlock: lock page %d: mlock %ld [num_pages %d]\n",
4379 i, addr, num_pages);
4380 ++i;
4381#endif
4382 page_list = SH_ALLOC(sizeof(sh_page_l));
4383 page_list->page_start = addr;
4384 page_list->page_refcount = 1;
4385 sl_strlcpy(page_list->file, file, 64);
4386 page_list->line = line;
4387 status = mlock( (void *) addr, pagesize);
4388 if (status != 0)
4389 {
4390#ifdef TEST_MLOCK
4391 char errbuf[SH_ERRBUF_SIZE];
4392 fprintf(stderr, "mlock: error: %s\n",
4393 sh_error_message(errno, errbuf, sizeof(errbuf)));
4394#endif
4395 SH_FREE(page_list);
4396 page_locking = 0;
4397 goto exit_mlock;
4398 }
4399 page_list->next = sh_page_locked;
4400 sh_page_locked = page_list;
4401 num_pages -= 1;
4402 addr += pagesize;
4403 }
4404 page_locking = 0;
4405
4406 exit_mlock:
4407 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
4408
4409 SL_RETURN((status), _("sh_unix_mlock"));
4410}
4411#else
4412int sh_unix_mlock (char * file, int line, void * in_addr, size_t len)
4413{
4414 (void) file; (void) line;
4415 (void) in_addr; (void) len;
4416 return -1;
4417}
4418#endif
4419
4420#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4421int sh_unix_munlock (void * in_addr, size_t len)
4422{
4423 int num_pages;
4424 int unlocked = 0;
4425 int status = 0;
4426 int pagesize;
4427 sh_page_l * page_list = sh_page_locked;
4428 sh_page_l * page_last;
4429 unsigned long addr;
4430
4431 int test_count;
4432 int test_status;
4433 int test_pages;
4434
4435#ifdef TEST_MLOCK
4436 int i = 0;
4437#endif
4438
4439 SL_ENTER(_("sh_unix_munlock"));
4440
4441 /* There's no cancellation point here, except if tracing is on
4442 */
4443 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4444
4445 if (0 != page_locking)
4446 {
4447 status = -1;
4448 goto exit_munlock;
4449 }
4450 page_locking = 1;
4451
4452 pagesize = sh_unix_pagesize();
4453 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4454
4455#ifdef TEST_MLOCK
4456 fprintf(stderr, "munlock: in_addr %ld, addr %ld, pages: %d, length %d\n",
4457 (unsigned long) in_addr, addr, num_pages, len);
4458#endif
4459
4460 test_pages = num_pages;
4461
4462 /* reduce refcount of locked pages
4463 * addr is first page; num_pages is #(consecutive pages) to lock
4464 */
4465 while ((page_list != NULL) && (num_pages > 0))
4466 {
4467#ifdef TEST_MLOCK
4468 fprintf(stderr, "munlock: page %d: %ld [%d]\n",
4469 i, page_list->page_start, page_list->page_refcount);
4470#endif
4471
4472 test_status = 0;
4473 for (test_count = 0; test_count < test_pages; ++test_count)
4474 {
4475 if (page_list->page_start == (addr + (test_count * pagesize)))
4476 {
4477 test_status = 1;
4478 break;
4479 }
4480 }
4481
4482 if (test_status == 1)
4483 {
4484 page_list->page_refcount -= 1;
4485 if (page_list->page_refcount == 0)
4486 {
4487 status = munlock ( (void *) addr, pagesize);
4488 ++unlocked;
4489 }
4490 num_pages -= 1;
4491#ifdef TEST_MLOCK
4492 fprintf(stderr,
4493 "munlock: page %d: %ld [refcount %d], refcount reduced\n",
4494 i, page_list->page_start, page_list->page_refcount);
4495#endif
4496 }
4497#ifdef TEST_MLOCK
4498 ++i;
4499#endif
4500 page_list = page_list->next;
4501 }
4502
4503#ifdef TEST_MLOCK
4504 i = 0;
4505#endif
4506
4507 if (unlocked > 0)
4508 {
4509 page_list = sh_page_locked;
4510 page_last = sh_page_locked;
4511
4512 while ((page_list != NULL) && (unlocked > 0))
4513 {
4514 if (page_list->page_refcount == 0)
4515 {
4516#ifdef TEST_MLOCK
4517 fprintf(stderr, "munlock: remove page %d: %ld [refcount %d]\n",
4518 i, page_list->page_start, page_list->page_refcount);
4519#endif
4520 if (page_last != page_list)
4521 {
4522 page_last->next = page_list->next;
4523 SH_FREE(page_list);
4524 page_list = page_last->next;
4525 }
4526 else
4527 {
4528 page_last = page_list->next;
4529 if (page_list == sh_page_locked)
4530 sh_page_locked = page_list->next;
4531 SH_FREE(page_list);
4532 page_list = page_last;
4533 }
4534 --unlocked;
4535 }
4536 else
4537 {
4538#ifdef TEST_MLOCK
4539 fprintf(stderr, "munlock: skip page %d: %ld [refcount %d]\n",
4540 i, page_list->page_start, page_list->page_refcount);
4541#endif
4542
4543 page_last = page_list;
4544 page_list = page_list->next;
4545 }
4546#ifdef TEST_MLOCK
4547 ++i;
4548#endif
4549 }
4550 }
4551
4552 page_locking = 0;
4553
4554 exit_munlock:
4555 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
4556 SL_RETURN((status), _("sh_unix_munlock"));
4557}
4558#else
4559int sh_unix_munlock (void * in_addr, size_t len)
4560{
4561 (void) in_addr; (void) len;
4562 return -1;
4563}
4564#endif
4565
4566int sh_unix_count_mlock()
4567{
4568 int i = 0;
4569 char str[128];
4570 sh_page_l * page_list = sh_page_locked;
4571
4572 SL_ENTER(_("sh_unix_count_mlock"));
4573 while (page_list != NULL)
4574 {
4575#ifdef WITH_TPT
4576 sl_snprintf(str, sizeof(str), _("file: %s line: %d page: %d"),
4577 page_list->file, page_list->line, i+1);
4578 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, i, MSG_E_SUBGEN,
4579 str, _("sh_unix_count_mlock"));
4580#endif
4581 page_list = page_list->next;
4582 ++i;
4583 }
4584 sl_snprintf(str, sizeof(str), _("%d pages locked"), i);
4585 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, i, MSG_E_SUBGEN,
4586 str, _("sh_unix_count_mlock"));
4587 SL_RETURN((i), _("sh_unix_count_mlock"));
4588}
4589
4590/************************************************/
4591/************************************************/
4592/**** Stealth Utilities ****/
4593/************************************************/
4594/************************************************/
4595#ifdef SH_STEALTH
4596
4597void sh_unix_xor_code (char * str, int len)
4598{
4599 register int i;
4600
4601 for (i = 0; i < len; ++i) str[i] ^= (char) XOR_CODE;
4602 return;
4603}
4604
4605#if !defined(SH_STEALTH_MICRO)
4606
4607
4608int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
4609 unsigned long * bytes_read);
4610unsigned long first_hex_block(SL_TICKET fd, unsigned long * max);
4611
4612/*
4613 * --- Get hidden data from a block of hex data. ---
4614 */
4615int sh_unix_getline_stealth (SL_TICKET fd, char * str, int len)
4616{
4617 int add_off = 0, llen;
4618 static unsigned long off_data = 0;
4619 static unsigned long max_data = 0;
4620 static unsigned long bytes_read = 0;
4621 static int stealth_init = BAD;
4622
4623 SL_ENTER(_("sh_unix_getline_stealth"));
4624
4625
4626 /* --- Initialize. ---
4627 */
4628 if (stealth_init == BAD)
4629 {
4630 off_data = first_hex_block(fd, &max_data);
4631 if (off_data == 0)
4632 {
4633 dlog(1, FIL__, __LINE__,
4634 _("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"));
4635 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
4636 _("Stealth config file."));
4637 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
4638 }
4639 stealth_init = GOOD;
4640 max_data += off_data;
4641 }
4642
4643 /* --- Seek to proper position. ---
4644 */
4645 if (bytes_read >= max_data || add_off < 0)
4646 {
4647 dlog(1, FIL__, __LINE__,
4648 _("The capacity of the container image file for the stealth config file seems to be too small. Your config file is likely truncated.\n"));
4649 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
4650 _("Stealth config file."));
4651 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
4652 }
4653 sl_seek(fd, off_data);
4654
4655 /* --- Read one line. ---
4656 */
4657 add_off = hideout_hex_block(fd, (unsigned char *) str, len, &bytes_read);
4658 off_data += add_off;
4659
4660 llen = sl_strlen(str);
4661 SL_RETURN(llen, _("sh_unix_getline_stealth"));
4662}
4663
4664int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
4665 unsigned long * bytes_read)
4666{
4667
4668 register int i, j, k;
4669 unsigned char c, e;
4670 register int num;
4671 unsigned char mask[9] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
4672 unsigned long here = 0;
4673 unsigned long retval = 0;
4674 unsigned long bread = 0;
4675
4676 SL_ENTER(_("hideout_hex_block"));
4677
4678 ASSERT_RET((len > 1), _("len > 1"), (0));
4679
4680 --len;
4681
4682 i = 0;
4683 while (i < len)
4684 {
4685 for (j = 0; j < 8; ++j)
4686 {
4687
4688 /* --- Get a low byte, modify, read back. ---
4689 */
4690 for (k = 0; k < 2; ++k)
4691 {
4692 /* -- Skip whitespace. ---
4693 */
4694 c = ' ';
4695 do {
4696 do {
4697 num = sl_read (fd, &c, 1);
4698 } while (num == 0 && errno == EINTR);
4699 if (num > 0)
4700 ++here;
4701 else if (num == 0)
4702 SL_RETURN((0), _("hideout_hex_block"));
4703 else
4704 SL_RETURN((-1), _("hideout_hex_block"));
4705 } while (c == '\n' || c == '\t' || c == '\r' ||
4706 c == ' ');
4707 }
4708
4709
4710 /* --- e is the value of the low byte. ---
4711 */
4712 e = (unsigned char) sh_util_hexchar( c );
4713 if ((e & mask[7]) != 0) /* bit is set */
4714 str[i] |= mask[j];
4715 else /* bit is not set */
4716 str[i] &= ~mask[j];
4717
4718 bread += 1;
4719 }
4720 if (str[i] == '\n') break;
4721 ++i;
4722 }
4723
4724 if (i != 0)
4725 str[i] = '\0';
4726 else
4727 str[i+1] = '\0'; /* keep newline and terminate */
4728 retval += here;
4729 *bytes_read += (bread/8);
4730
4731 SL_RETURN(retval, _("hideout_hex_block"));
4732}
4733
4734/* --- Get offset of first data block. ---
4735 */
4736unsigned long first_hex_block(SL_TICKET fd, unsigned long * max)
4737{
4738 unsigned int i;
4739 long num = 1;
4740 unsigned long lnum;
4741 char c;
4742 int nothex = 0;
4743 unsigned long retval = 0;
4744 unsigned int this_line = 0;
4745 char theline[SH_BUFSIZE];
4746
4747 SL_ENTER(_("first_hex_block"));
4748
4749 *max = 0;
4750
4751 while (1)
4752 {
4753 theline[0] = '\0';
4754 this_line = 0;
4755 c = '\0';
4756 while (c != '\n' && num > 0 && this_line < (sizeof(theline)-1))
4757 {
4758 do {
4759 num = sl_read (fd, &c, 1);
4760 } while (num == 0 && errno == EINTR);
4761 if (num > 0)
4762 theline[this_line] = c;
4763 else
4764 SL_RETURN((0), _("first_hex_block"));
4765 ++this_line;
4766 }
4767 theline[this_line] = '\0';
4768
4769 /* not only 'newline' */
4770 if (this_line > 60)
4771 {
4772 nothex = 0;
4773 i = 0;
4774 while (nothex == 0 && i < (this_line-1))
4775 {
4776 if (! isxdigit((int)theline[i])) nothex = 1;
4777 ++i;
4778 }
4779 if (nothex == 1) retval += this_line;
4780 }
4781 else
4782 {
4783 nothex = 1;
4784 retval += this_line;
4785 }
4786
4787 if (nothex == 0)
4788 {
4789 *max = 0;
4790 do {
4791 do {
4792 num = sl_read (fd, theline, SH_BUFSIZE);
4793 } while (num == 0 && errno == EINTR);
4794 if (num > 0)
4795 {
4796 lnum = (unsigned long) num;
4797 for (i = 0; i < lnum; ++i)
4798 {
4799 c = theline[i];
4800 if (c == '\n' || c == '\t' || c == '\r' || c == ' ')
4801 ;
4802 else if (!isxdigit((int)c))
4803 break;
4804 else
4805 *max += 1;
4806 }
4807 }
4808 } while (num > 0);
4809
4810 *max /= 16;
4811 SL_RETURN((retval), _("first_hex_block"));
4812 }
4813
4814 }
4815 /* SL_RETURN((0), _("first_hex_block")); *//* unreachable */
4816}
4817
4818 /* if !defined(SH_STEALTH_MICRO) */
4819#endif
4820
4821 /* ifdef SH_STEALTH */
4822#endif
4823
4824/*
4825 * anti-debugger code
4826 */
4827#if defined(SCREW_IT_UP)
4828volatile int sh_not_traced = 0;
4829
4830#ifdef HAVE_GETTIMEOFDAY
4831struct timeval save_tv;
4832#endif
4833
4834void sh_sigtrap_handler (int signum)
4835{
4836#ifdef HAVE_GETTIMEOFDAY
4837 struct timeval tv;
4838 long difftv;
4839
4840 gettimeofday(&tv, NULL);
4841 difftv = (tv.tv_sec - save_tv.tv_sec) * 1000000 +
4842 (tv.tv_usec - save_tv.tv_usec);
4843 if (difftv > 500000)
4844 _exit(6);
4845#endif
4846 sh_not_traced += signum;
4847 return;
4848}
4849#endif
Note: See TracBrowser for help on using the repository browser.