source: trunk/src/sh_unix.c@ 376

Last change on this file since 376 was 373, checked in by katerina, 13 years ago

Patch for ticket #265 (inotify). Handling of added subdirectories and file list rescan.

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