source: trunk/src/sh_unix.c@ 133

Last change on this file since 133 was 133, checked in by rainer, 17 years ago

Reentrant checksum/hash functions.

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