source: trunk/src/sh_unix.c@ 139

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

More fixes for compile and runtime errors.

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