source: trunk/src/sh_unix.c@ 328

Last change on this file since 328 was 321, checked in by katerina, 14 years ago

Fix for ticket #240: The samhain_kmem kernel module should be loaded earlier

File size: 123.0 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 struct tm * cc;
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 cc = gmtime_r (xx, &aa);
2181#else
2182 cc = gmtime (xx);
2183 memcpy (&aa, cc, sizeof(struct tm));
2184#endif
2185
2186#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2187 cc = localtime_r (xx, &bb);
2188#else
2189 cc = localtime (xx);
2190 memcpy (&bb, cc, sizeof(struct tm));
2191#endif
2192
2193 /* Check for datum wrap-around.
2194 */
2195 if (aa.tm_year < bb.tm_year)
2196 sign = (-1);
2197 else if (aa.tm_mon < bb.tm_mon)
2198 sign = (-1);
2199 else if (aa.tm_mday < bb.tm_mday)
2200 sign = (-1);
2201 else if (bb.tm_year < aa.tm_year)
2202 sign = ( 1);
2203 else if (bb.tm_mon < aa.tm_mon)
2204 sign = ( 1);
2205 else if (bb.tm_mday < aa.tm_mday)
2206 sign = ( 1);
2207
2208 diff = aa.tm_hour * 60 + aa.tm_min;
2209 diff = (bb.tm_hour * 60 + bb.tm_min) - diff;
2210 diff = diff - (sign * 24 * 60); /* datum wrap-around correction */
2211 hh = diff / 60;
2212 mm = diff - (hh * 60);
2213 sprintf (tz, _("%+03d%02d"), hh, mm); /* known to fit */
2214
2215 SL_RETURN(tz, _("t_zone"));
2216}
2217
2218unsigned long sh_unix_longtime ()
2219{
2220 return ((unsigned long)time(NULL));
2221}
2222
2223#ifdef HAVE_GETTIMEOFDAY
2224unsigned long sh_unix_notime ()
2225{
2226 struct timeval tv;
2227
2228 gettimeofday (&tv, NULL);
2229
2230 return ((unsigned long)(tv.tv_sec + tv.tv_usec * 10835 + getpid() + getppid()));
2231
2232}
2233#endif
2234
2235static int count_dev_time = 0;
2236
2237void reset_count_dev_time(void)
2238{
2239 count_dev_time = 0;
2240 return;
2241}
2242
2243int sh_unix_settimeserver (const char * address)
2244{
2245
2246 SL_ENTER(_("sh_unix_settimeserver"));
2247
2248 if (address != NULL && count_dev_time < 2
2249 && sl_strlen(address) < SH_PATHBUF)
2250 {
2251 if (count_dev_time == 0)
2252 sl_strlcpy (sh.srvtime.name, address, SH_PATHBUF);
2253 else
2254 sl_strlcpy (sh.srvtime.alt, address, SH_PATHBUF);
2255
2256 ++count_dev_time;
2257 SL_RETURN((0), _("sh_unix_settimeserver"));
2258 }
2259 SL_RETURN((-1), _("sh_unix_settimeserver"));
2260}
2261
2262
2263#ifdef HAVE_NTIME
2264#define UNIXEPOCH 2208988800UL /* difference between Unix time and net time
2265 * The UNIX EPOCH starts in 1970.
2266 */
2267#include <sys/socket.h>
2268#include <netinet/in.h>
2269#include <arpa/inet.h>
2270#include <netdb.h>
2271#include <ctype.h>
2272#endif
2273
2274/* Timeserver service. */
2275/* define is missing on HP-UX 10.20 */
2276#ifndef IPPORT_TIMESERVER
2277#define IPPORT_TIMESERVER 37
2278#endif
2279
2280char * sh_unix_time (time_t thetime, char * buffer, size_t len)
2281{
2282
2283 int status;
2284 char AsciiTime[81]; /* local time */
2285 time_t time_now;
2286 struct tm * time_ptr;
2287#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2288 struct tm time_tm;
2289#endif
2290#ifdef SH_USE_XML
2291 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2292#else
2293 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2294#endif
2295
2296#ifdef HAVE_NTIME
2297 int fd; /* network file descriptor */
2298 u_char net_time[4]; /* remote time in network format */
2299 static int failerr = 0; /* no net time */
2300 int fail = 0; /* no net time */
2301 int errflag;
2302 char errmsg[256];
2303 char error_call[SH_MINIBUF];
2304 int error_num;
2305#endif
2306
2307 SL_ENTER(_("sh_unix_time"));
2308
2309#ifdef HAVE_NTIME
2310 if (thetime == 0)
2311 {
2312 if (sh.srvtime.name[0] == '\0')
2313 {
2314 fail = 1;
2315 (void) time (&time_now);
2316 }
2317 else /* have a timeserver address */
2318 {
2319 fd = connect_port_2 (sh.srvtime.name, sh.srvtime.alt,
2320 IPPORT_TIMESERVER,
2321 error_call, &error_num, errmsg, sizeof(errmsg));
2322 if (fd >= 0)
2323 {
2324 if (4 != read_port (fd, (char *) net_time, 4, &errflag, 2))
2325 {
2326 fail = 1;
2327 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2328 MSG_E_NLOST,
2329 _("time"), sh.srvtime.name);
2330 }
2331 sl_close_fd(FIL__, __LINE__, fd);
2332 }
2333 else
2334 {
2335 sh_error_handle ((-1), FIL__, __LINE__, error_num,
2336 MSG_E_NET, errmsg, error_call,
2337 _("time"), sh.srvtime.name);
2338 fail = 1;
2339 }
2340
2341 if (fail == 0)
2342 {
2343 unsigned long ltmp;
2344 UINT32 ttmp;
2345 memcpy(&ttmp, net_time, sizeof(UINT32)); ltmp = ttmp;
2346 time_now = ntohl(ltmp) - UNIXEPOCH;
2347 /* fprintf(stderr, "TIME IS %ld\n", time_now); */
2348 if (failerr == 1) {
2349 failerr = 0;
2350 sh_error_handle ((-1), FIL__, __LINE__, 0,
2351 MSG_E_NEST,
2352 _("time"), sh.srvtime.name);
2353 }
2354 }
2355 else
2356 {
2357 (void) time (&time_now);
2358 if (failerr == 0)
2359 {
2360 failerr = 1;
2361 sh_error_handle ((-1), FIL__, __LINE__, errflag,
2362 MSG_SRV_FAIL,
2363 _("time"), sh.srvtime.name);
2364 }
2365 }
2366 }
2367 }
2368 else
2369 {
2370 time_now = thetime;
2371 }
2372
2373 /* #ifdef HAVE_NTIME */
2374#else
2375
2376 if (thetime == 0)
2377 {
2378 (void) time (&time_now);
2379 }
2380 else
2381 {
2382 time_now = thetime;
2383 }
2384
2385 /* #ifdef HAVE_NTIME */
2386#endif
2387
2388 if (time_now == (-1) )
2389 {
2390 sl_strlcpy(buffer, _(deftime), len);
2391 SL_RETURN(buffer, _("sh_unix_time"));
2392 }
2393 else
2394 {
2395#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2396 time_ptr = localtime_r (&time_now, &time_tm);
2397#else
2398 time_ptr = localtime (&time_now);
2399#endif
2400 }
2401 if (time_ptr != NULL)
2402 {
2403 status = strftime (AsciiTime, sizeof(AsciiTime),
2404#ifdef SH_USE_XML
2405 _("%Y-%m-%dT%H:%M:%S%%s"),
2406#else
2407 _("[%Y-%m-%dT%H:%M:%S%%s]"),
2408#endif
2409 time_ptr);
2410
2411 sl_snprintf(buffer, len, AsciiTime, t_zone(&time_now));
2412
2413 if ( (status == 0) || (status == sizeof(AsciiTime)) )
2414 {
2415 sl_strlcpy(buffer, _(deftime), len);
2416 SL_RETURN( buffer, _("sh_unix_time"));
2417 }
2418 else
2419 {
2420 SL_RETURN(buffer, _("sh_unix_time"));
2421 }
2422 }
2423
2424 /* last resort
2425 */
2426 sl_strlcpy(buffer, _(deftime), len);
2427 SL_RETURN( buffer, _("sh_unix_time"));
2428}
2429
2430static int sh_unix_use_localtime = S_FALSE;
2431
2432/* whether to use localtime for file timesatams in logs
2433 */
2434int sh_unix_uselocaltime (const char * c)
2435{
2436 int i;
2437 SL_ENTER(_("sh_unix_uselocaltime"));
2438 i = sh_util_flagval(c, &(sh_unix_use_localtime));
2439
2440 SL_RETURN(i, _("sh_unix_uselocaltime"));
2441}
2442
2443char * sh_unix_gmttime (time_t thetime, char * buffer, size_t len)
2444{
2445
2446 int status;
2447
2448 struct tm * time_ptr;
2449#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS)
2450 struct tm time_tm;
2451#endif
2452 char AsciiTime[81]; /* GMT time */
2453#ifdef SH_USE_XML
2454 static char deftime[] = N_("0000-00-00T00:00:00"); /* default time */
2455#else
2456 static char deftime[] = N_("[0000-00-00T00:00:00]"); /* default time */
2457#endif
2458
2459 SL_ENTER(_("sh_unix_gmttime"));
2460
2461 if (sh_unix_use_localtime == S_FALSE)
2462 {
2463#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GMTIME_R)
2464 time_ptr = gmtime_r (&thetime, &time_tm);
2465#else
2466 time_ptr = gmtime (&thetime);
2467#endif
2468 }
2469 else
2470 {
2471#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_LOCALTIME_R)
2472 time_ptr = localtime_r (&thetime, &time_tm);
2473#else
2474 time_ptr = localtime (&thetime);
2475#endif
2476 }
2477 if (time_ptr != NULL)
2478 {
2479 status = strftime (AsciiTime, 80,
2480#ifdef SH_USE_XML
2481 _("%Y-%m-%dT%H:%M:%S"),
2482#else
2483 _("[%Y-%m-%dT%H:%M:%S]"),
2484#endif
2485 time_ptr);
2486
2487 if ( (status == 0) || (status == 80) )
2488 sl_strlcpy(buffer, _(deftime), len);
2489 else
2490 sl_strlcpy(buffer, AsciiTime, len);
2491 SL_RETURN( buffer, _("sh_unix_gmttime"));
2492 }
2493
2494 /* last resort
2495 */
2496 sl_strlcpy(buffer, _(deftime), len);
2497 SL_RETURN( buffer, _("sh_unix_gmttime"));
2498}
2499
2500
2501char * sh_unix_getUIDdir (int level, uid_t uid, char * out, size_t len)
2502{
2503 struct passwd * tempres;
2504 int status = 0;
2505
2506#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2507 struct passwd pwd;
2508 char * buffer;
2509#endif
2510 char errbuf[SH_ERRBUF_SIZE];
2511
2512 SL_ENTER(_("sh_unix_getUIDdir"));
2513
2514#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2515 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2516 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2517#else
2518 errno = 0;
2519 tempres = sh_getpwuid(uid);
2520 status = errno;
2521#endif
2522
2523 if (tempres == NULL) {
2524 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2525 sh_error_message(status, errbuf, sizeof(errbuf)),
2526 _("getpwuid"), (long) uid, _("completely missing"));
2527#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2528 SH_FREE(buffer);
2529#endif
2530 SL_RETURN( NULL, _("sh_unix_getUIDdir"));
2531 }
2532
2533 if (tempres->pw_dir != NULL) {
2534 sl_strlcpy(out, tempres->pw_dir, len);
2535#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2536 SH_FREE(buffer);
2537#endif
2538 SL_RETURN( out, _("sh_unix_getUIDdir"));
2539 } else {
2540 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2541 sh_error_message(status, errbuf, sizeof(errbuf)),
2542 _("getpwuid"), (long) uid, _("pw_dir"));
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
2550/* ------------------- Caching ----------------*/
2551#include "zAVLTree.h"
2552
2553#define CACHE_GID 0
2554#define CACHE_UID 1
2555
2556struct user_id {
2557 char * name;
2558 uid_t id;
2559 struct user_id * next;
2560};
2561
2562static struct user_id * uid_list = NULL;
2563static struct user_id * gid_list = NULL;
2564
2565SH_MUTEX_STATIC(mutex_cache, PTHREAD_MUTEX_INITIALIZER);
2566
2567static void sh_userid_free(struct user_id * item)
2568{
2569 while (item)
2570 {
2571 struct user_id * user = item;
2572 item = item->next;
2573
2574 SH_FREE(user->name);
2575 SH_FREE(user);
2576 }
2577 return;
2578}
2579
2580void sh_userid_destroy ()
2581{
2582 struct user_id * tmp_uid;
2583 struct user_id * tmp_gid;
2584
2585 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2586 tmp_gid = gid_list;
2587 gid_list = NULL;
2588 tmp_uid = uid_list;
2589 uid_list = NULL;
2590 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2591
2592 sh_userid_free(tmp_uid);
2593 sh_userid_free(tmp_gid);
2594 return;
2595}
2596
2597static void sh_userid_additem(struct user_id * list, struct user_id * item)
2598{
2599 while (list && list->next)
2600 list = list->next;
2601 list->next = item;
2602 return;
2603}
2604
2605static void sh_userid_add(uid_t id, char * username, int which)
2606{
2607 size_t len;
2608 struct user_id * user = SH_ALLOC(sizeof(struct user_id));
2609
2610 if (username)
2611 len = strlen(username) + 1;
2612 else
2613 len = 1;
2614
2615 user->name = SH_ALLOC(len);
2616 user->id = id;
2617 if (username)
2618 sl_strlcpy(user->name, username, len);
2619 else
2620 user->name[0] = '\0';
2621 user->next = NULL;
2622
2623 SH_MUTEX_LOCK(mutex_cache);
2624 if (which == CACHE_UID)
2625 {
2626 if (!uid_list)
2627 uid_list = user;
2628 else
2629 sh_userid_additem(uid_list, user);
2630 }
2631 else
2632 {
2633 if (!gid_list)
2634 gid_list = user;
2635 else
2636 sh_userid_additem(gid_list, user);
2637 }
2638 SH_MUTEX_UNLOCK(mutex_cache);
2639
2640 return;
2641}
2642
2643static char * sh_userid_search(struct user_id * list, uid_t id)
2644{
2645 while (list)
2646 {
2647 if (list->id == id)
2648 return list->name;
2649 list = list->next;
2650 }
2651 return NULL;
2652}
2653
2654static char * sh_userid_get (uid_t id, int which, char * out, size_t len)
2655{
2656 char * user = NULL;
2657
2658 SH_MUTEX_LOCK_UNSAFE(mutex_cache);
2659 if (which == CACHE_UID)
2660 user = sh_userid_search(uid_list, id);
2661 else
2662 user = sh_userid_search(gid_list, id);
2663 if (user)
2664 {
2665 sl_strlcpy(out, user, len);
2666 user = out;
2667 }
2668 SH_MUTEX_UNLOCK_UNSAFE(mutex_cache);
2669
2670 return user;
2671}
2672
2673/* --------- end caching code --------- */
2674
2675char * sh_unix_getUIDname (int level, uid_t uid, char * out, size_t len)
2676{
2677 struct passwd * tempres;
2678#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2679 struct passwd pwd;
2680 char * buffer;
2681#endif
2682 int status = 0;
2683 char errbuf[SH_ERRBUF_SIZE];
2684 char * tmp;
2685
2686 SL_ENTER(_("sh_unix_getUIDname"));
2687
2688 tmp = sh_userid_get(uid, CACHE_UID, out, len);
2689
2690 if (tmp)
2691 {
2692 if (tmp[0] != '\0')
2693 {
2694 SL_RETURN( out, _("sh_unix_getUIDname"));
2695 }
2696 else
2697 {
2698 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2699 }
2700 }
2701
2702#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETPWUID_R)
2703 buffer = SH_ALLOC(SH_PWBUF_SIZE);
2704 sh_getpwuid_r(uid, &pwd, buffer, SH_PWBUF_SIZE, &tempres);
2705#else
2706 errno = 0;
2707 tempres = sh_getpwuid(uid);
2708 status = errno;
2709#endif
2710
2711 if (tempres == NULL)
2712 {
2713 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2714 sh_error_message(status, errbuf, sizeof(errbuf)),
2715 _("getpwuid"), (long) uid, _("completely missing"));
2716#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2717 SH_FREE(buffer);
2718#endif
2719 sh_userid_add(uid, NULL, CACHE_UID);
2720 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2721 }
2722
2723
2724 if (tempres->pw_name != NULL)
2725 {
2726
2727 sl_strlcpy(out, tempres->pw_name, len);
2728 sh_userid_add(uid, out, CACHE_UID);
2729
2730#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2731 SH_FREE(buffer);
2732#endif
2733
2734 SL_RETURN( out, _("sh_unix_getUIDname"));
2735 }
2736 else
2737 {
2738 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_PWNULL,
2739 sh_error_message(status, errbuf, sizeof(errbuf)),
2740 _("getpwuid"), (long) uid, _("pw_user"));
2741#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2742 SH_FREE(buffer);
2743#endif
2744 SL_RETURN( NULL, _("sh_unix_getUIDname"));
2745 }
2746 /* notreached */
2747}
2748
2749char * sh_unix_getGIDname (int level, gid_t gid, char * out, size_t len)
2750{
2751 struct group * tempres;
2752 int status = 0;
2753
2754#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2755 struct group grp;
2756 char * buffer;
2757#endif
2758 char errbuf[SH_ERRBUF_SIZE];
2759 char * tmp;
2760
2761 SL_ENTER(_("sh_unix_getGIDname"));
2762
2763 tmp = sh_userid_get((uid_t)gid, CACHE_GID, out, len);
2764
2765 if (tmp)
2766 {
2767 if (tmp[0] != '\0')
2768 {
2769 SL_RETURN( out, _("sh_unix_getGIDname"));
2770 }
2771 else
2772 {
2773 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2774 }
2775 }
2776
2777#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2778 buffer = SH_ALLOC(SH_GRBUF_SIZE);
2779 status = sh_getgrgid_r(gid, &grp, buffer, SH_GRBUF_SIZE, &tempres);
2780#else
2781 errno = 0;
2782 tempres = sh_getgrgid(gid);
2783 status = errno;
2784#endif
2785
2786 if (tempres == NULL)
2787 {
2788 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2789 sh_error_message(status, errbuf, sizeof(errbuf)),
2790 _("getgrgid"), (long) gid, _("completely missing"));
2791
2792#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2793 SH_FREE(buffer);
2794#endif
2795
2796 sh_userid_add(gid, NULL, CACHE_GID);
2797 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2798 }
2799
2800 if (tempres->gr_name != NULL)
2801 {
2802
2803 sl_strlcpy(out, tempres->gr_name, len);
2804 sh_userid_add((uid_t)gid, out, CACHE_GID);
2805
2806#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2807 SH_FREE(buffer);
2808#endif
2809
2810 SL_RETURN( out, _("sh_unix_getGIDname"));
2811 }
2812 else
2813 {
2814 sh_error_handle (level, FIL__, __LINE__, EINVAL, MSG_E_GRNULL,
2815 sh_error_message(status, errbuf, sizeof(errbuf)),
2816 _("getgrgid"), (long) gid, _("gr_name"));
2817
2818#if defined(HAVE_PTHREAD) && defined (_POSIX_THREAD_SAFE_FUNCTIONS) && defined(HAVE_GETGRGID_R)
2819 SH_FREE(buffer);
2820#endif
2821
2822 SL_RETURN( NULL, _("sh_unix_getGIDname"));
2823 }
2824 /* notreached */
2825}
2826
2827int sh_unix_getUser ()
2828{
2829 char * p;
2830 uid_t seuid, sruid;
2831 char user[USER_MAX];
2832 char dir[SH_PATHBUF];
2833
2834 SL_ENTER(_("sh_unix_getUser"));
2835
2836 seuid = geteuid();
2837
2838 sh.effective.uid = seuid;
2839
2840 p = sh_unix_getUIDdir (SH_ERR_ERR, seuid, dir, sizeof(dir));
2841
2842 if (p == NULL)
2843 SL_RETURN((-1), _("sh_unix_getUser"));
2844 else
2845 {
2846 if (sl_strlen(p) >= SH_PATHBUF) {
2847 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2848 _("getpwuid"), (long) seuid, _("pw_home"));
2849 SL_RETURN((-1), _("sh_unix_getUser"));
2850 } else {
2851 sl_strlcpy ( sh.effective.home, p, SH_PATHBUF);
2852 }
2853 }
2854
2855 sruid = getuid();
2856
2857 sh.real.uid = sruid;
2858
2859 p = sh_unix_getUIDname (SH_ERR_ERR, sruid, user, sizeof(user));
2860 if (p == NULL)
2861 SL_RETURN((-1), _("sh_unix_getUser"));
2862 else
2863 {
2864 if (sl_strlen(p) >= USER_MAX) {
2865 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2866 _("getpwuid"), (long) sruid, _("pw_user"));
2867 SL_RETURN((-1), _("sh_unix_getUser"));
2868 } else {
2869 sl_strlcpy ( sh.real.user, p, USER_MAX);
2870 }
2871 }
2872
2873 p = sh_unix_getUIDdir (SH_ERR_ERR, sruid, dir, sizeof(dir));
2874
2875 if (p == NULL)
2876 SL_RETURN((-1), _("sh_unix_getUser"));
2877 else
2878 {
2879 if (sl_strlen(p) >= SH_PATHBUF) {
2880 sh_error_handle (SH_ERR_ERR, FIL__, __LINE__, EINVAL, MSG_E_PWLONG,
2881 _("getpwuid"), (long) sruid, _("pw_home"));
2882 SL_RETURN((-1), _("sh_unix_getUser"));
2883 } else {
2884 sl_strlcpy ( sh.real.home, p, SH_PATHBUF);
2885 }
2886 }
2887
2888 SL_RETURN((0), _("sh_unix_getUser"));
2889
2890 /* notreached */
2891}
2892
2893
2894int sh_unix_getline (SL_TICKET fd, char * line, int sizeofline)
2895{
2896 register int count;
2897 register int n = 0;
2898 char c;
2899
2900 SL_ENTER(_("sh_unix_getline"));
2901
2902 if (sizeofline < 2) {
2903 line[0] = '\0';
2904 SL_RETURN((0), _("sh_unix_getline"));
2905 }
2906
2907 --sizeofline;
2908
2909 while (n < sizeofline) {
2910
2911 count = sl_read (fd, &c, 1);
2912
2913 /* end of file
2914 */
2915 if (count < 1) {
2916 line[n] = '\0';
2917 n = -1;
2918 break;
2919 }
2920
2921 if (/* c != '\0' && */ c != '\n') {
2922 line[n] = c;
2923 ++n;
2924 } else if (c == '\n') {
2925 if (n > 0) {
2926 line[n] = '\0';
2927 break;
2928 } else {
2929 line[n] = '\n'; /* get newline only if only char on line */
2930 ++n;
2931 line[n] = '\0';
2932 break;
2933 }
2934 } else {
2935 line[n] = '\0';
2936 break;
2937 }
2938
2939 }
2940
2941
2942 line[sizeofline] = '\0'; /* make sure line is terminated */
2943 SL_RETURN((n), _("sh_unix_getline"));
2944}
2945
2946
2947#if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE)
2948
2949/**************************************************************
2950 *
2951 * --- FILE INFO ---
2952 *
2953 **************************************************************/
2954
2955#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
2956
2957#if defined(__linux__)
2958
2959/* --- Determine ext2fs file attributes. ---
2960 */
2961#include <sys/ioctl.h>
2962#if defined(HAVE_EXT2FS_EXT2_FS_H)
2963#include <ext2fs/ext2_fs.h>
2964#else
2965#include <linux/ext2_fs.h>
2966#endif
2967
2968/* __linux__ includes */
2969#endif
2970
2971static
2972int sh_unix_getinfo_attr (char * name,
2973 unsigned long * flags,
2974 char * c_attr,
2975 int fd, struct stat * buf)
2976{
2977
2978/* TAKEN FROM:
2979 *
2980 * lsattr.c - List file attributes on an ext2 file system
2981 *
2982 * Copyright (C) 1993, 1994 Remy Card <card@masi.ibp.fr>
2983 * Laboratoire MASI, Institut Blaise Pascal
2984 * Universite Pierre et Marie Curie (Paris VI)
2985 *
2986 * This file can be redistributed under the terms of the GNU General
2987 * Public License
2988 */
2989
2990#ifdef HAVE_STAT_FLAGS
2991
2992 SL_ENTER(_("sh_unix_getinfo_attr"));
2993
2994 *flags = 0;
2995
2996 /* cast to void to avoid compiler warning about unused parameters */
2997 (void) fd;
2998 (void) name;
2999
3000#ifdef UF_NODUMP
3001 if (buf->st_flags & UF_NODUMP) {
3002 *flags |= UF_NODUMP;
3003 c_attr[0] = 'd';
3004 }
3005#endif
3006#ifdef UF_IMMUTABLE
3007 if (buf->st_flags & UF_IMMUTABLE) {
3008 *flags |= UF_IMMUTABLE;
3009 c_attr[1] = 'i';
3010 }
3011#endif
3012#ifdef UF_APPEND
3013 if (buf->st_flags & UF_APPEND) {
3014 *flags |= UF_APPEND;
3015 c_attr[2] = 'a';
3016 }
3017#endif
3018#ifdef UF_NOUNLINK
3019 if (buf->st_flags & UF_NOUNLINK) {
3020 *flags |= UF_NOUNLINK;
3021 c_attr[3] = 'u';
3022 }
3023#endif
3024#ifdef UF_OPAQUE
3025 if (buf->st_flags & UF_OPAQUE) {
3026 *flags |= UF_OPAQUE;
3027 c_attr[4] = 'o';
3028 }
3029#endif
3030#ifdef SF_ARCHIVED
3031 if (buf->st_flags & SF_ARCHIVED) {
3032 *flags |= SF_ARCHIVED;
3033 c_attr[5] = 'R';
3034 }
3035
3036#endif
3037#ifdef SF_IMMUTABLE
3038 if (buf->st_flags & SF_IMMUTABLE) {
3039 *flags |= SF_IMMUTABLE;
3040 c_attr[6] = 'I';
3041 }
3042#endif
3043#ifdef SF_APPEND
3044 if (buf->st_flags & SF_APPEND) {
3045 *flags |= SF_APPEND;
3046 c_attr[7] = 'A';
3047 }
3048#endif
3049#ifdef SF_NOUNLINK
3050 if (buf->st_flags & SF_NOUNLINK) {
3051 *flags |= SF_NOUNLINK;
3052 c_attr[8] = 'U';
3053 }
3054#endif
3055
3056 /* ! HAVE_STAT_FLAGS */
3057#else
3058
3059#ifdef HAVE_EXT2_IOCTLS
3060 int /* fd, */ r, f;
3061
3062 SL_ENTER(_("sh_unix_getinfo_attr"));
3063
3064 *flags = 0;
3065 (void) buf;
3066
3067 /* open() -> aud_open() R.Wichmann
3068 fd = aud_open (FIL__, __LINE__, SL_YESPRIV, name, O_RDONLY|O_NONBLOCK, 0);
3069 */
3070
3071 if (fd == -1 || name == NULL)
3072 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3073
3074
3075 r = ioctl (fd, EXT2_IOC_GETFLAGS, &f);
3076 /* sl_close_fd (FIL__, __LINE__, fd); */
3077
3078 if (r == -1)
3079 SL_RETURN(-1, _("sh_unix_getinfo_attr"));
3080
3081 if (f == 0)
3082 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3083
3084 *flags = f;
3085
3086/* ! HAVE_EXT2_IOCTLS */
3087#else
3088
3089 SL_ENTER(_("sh_unix_getinfo_attr"));
3090
3091 *flags = 0; /* modified by R.Wichmann */
3092
3093/* ! HAVE_EXT2_IOCTLS */
3094#endif
3095/*
3096 * END
3097 *
3098 * lsattr.c - List file attributes on an ext2 file system
3099 */
3100
3101 if (*flags == 0)
3102 goto theend;
3103
3104#ifdef EXT2_SECRM_FL
3105 if ( (*flags & EXT2_SECRM_FL) != 0 ) c_attr[0] = 's';
3106#endif
3107#ifdef EXT2_UNRM_FL
3108 if ( (*flags & EXT2_UNRM_FL) != 0 ) c_attr[1] = 'u';
3109#endif
3110#ifdef EXT2_SYNC_FL
3111 if ( (*flags & EXT2_SYNC_FL) != 0 ) c_attr[2] = 'S';
3112#endif
3113#ifdef EXT2_IMMUTABLE_FL
3114 if ( (*flags & EXT2_IMMUTABLE_FL) != 0) c_attr[3] = 'i';
3115#endif
3116#ifdef EXT2_APPEND_FL
3117 if ( (*flags & EXT2_APPEND_FL) != 0 ) c_attr[4] = 'a';
3118#endif
3119#ifdef EXT2_NODUMP_FL
3120 if ( (*flags & EXT2_NODUMP_FL) != 0 ) c_attr[5] = 'd';
3121#endif
3122#ifdef EXT2_NOATIME_FL
3123 if ( (*flags & EXT2_NOATIME_FL) != 0) c_attr[6] = 'A';
3124#endif
3125#ifdef EXT2_COMPR_FL
3126 if ( (*flags & EXT2_COMPR_FL) != 0 ) c_attr[7] = 'c';
3127#endif
3128
3129#ifdef EXT2_TOPDIR_FL
3130 if ( (*flags & EXT2_TOPDIR_FL) != 0 ) c_attr[8] = 'T';
3131#endif
3132#ifdef EXT2_DIRSYNC_FL
3133 if ( (*flags & EXT2_DIRSYNC_FL) != 0 ) c_attr[9] = 'D';
3134#endif
3135#ifdef EXT2_NOTAIL_FL
3136 if ( (*flags & EXT2_NOTAIL_FL) != 0 ) c_attr[10] = 't';
3137#endif
3138#ifdef EXT2_JOURNAL_DATA_FL
3139 if ( (*flags & EXT2_JOURNAL_DATA_FL) != 0) c_attr[11] = 'j';
3140#endif
3141
3142 theend:
3143 /* ext2 */
3144#endif
3145
3146 c_attr[12] = '\0';
3147
3148 SL_RETURN(0, _("sh_unix_getinfo_attr"));
3149}
3150
3151/* defined(__linux__) || defined(HAVE_STAT_FLAGS) */
3152#endif
3153
3154/* determine file type
3155 */
3156static
3157int sh_unix_getinfo_type (struct stat * buf,
3158 ShFileType * type,
3159 char * c_mode)
3160{
3161 SL_ENTER(_("sh_unix_getinfo_type"));
3162
3163 if ( S_ISREG(buf->st_mode) ) {
3164 (*type) = SH_FILE_REGULAR;
3165 c_mode[0] = '-';
3166 }
3167 else if ( S_ISLNK(buf->st_mode) ) {
3168 (*type) = SH_FILE_SYMLINK;
3169 c_mode[0] = 'l';
3170 }
3171 else if ( S_ISDIR(buf->st_mode) ) {
3172 (*type) = SH_FILE_DIRECTORY;
3173 c_mode[0] = 'd';
3174 }
3175 else if ( S_ISCHR(buf->st_mode) ) {
3176 (*type) = SH_FILE_CDEV;
3177 c_mode[0] = 'c';
3178 }
3179 else if ( S_ISBLK(buf->st_mode) ) {
3180 (*type) = SH_FILE_BDEV;
3181 c_mode[0] = 'b';
3182 }
3183 else if ( S_ISFIFO(buf->st_mode) ) {
3184 (*type) = SH_FILE_FIFO;
3185 c_mode[0] = '|';
3186 }
3187 else if ( S_ISSOCK(buf->st_mode) ) {
3188 (*type) = SH_FILE_SOCKET;
3189 c_mode[0] = 's';
3190 }
3191 else if ( S_ISDOOR(buf->st_mode) ) {
3192 (*type) = SH_FILE_DOOR;
3193 c_mode[0] = 'D';
3194 }
3195 else if ( S_ISPORT(buf->st_mode) ) {
3196 (*type) = SH_FILE_PORT;
3197 c_mode[0] = 'P';
3198 }
3199 else {
3200 (*type) = SH_FILE_UNKNOWN;
3201 c_mode[0] = '?';
3202 }
3203
3204 SL_RETURN(0, _("sh_unix_getinfo_type"));
3205}
3206
3207int sh_unix_get_ftype(char * fullpath)
3208{
3209 char c_mode[CMODE_SIZE];
3210 struct stat buf;
3211 ShFileType type;
3212 int res;
3213
3214 SL_ENTER(_("sh_unix_get_ftype"));
3215
3216 res = retry_lstat(FIL__, __LINE__, fullpath, &buf);
3217
3218 if (res < 0)
3219 SL_RETURN(SH_FILE_UNKNOWN, _("sh_unix_getinfo_type"));
3220
3221 sh_unix_getinfo_type (&buf, &type, c_mode);
3222
3223 SL_RETURN(type, _("sh_unix_get_ftype"));
3224}
3225
3226
3227static
3228int sh_unix_getinfo_mode (struct stat *buf,
3229 unsigned int * mode,
3230 char * c_mode)
3231{
3232
3233 SL_ENTER(_("sh_unix_getinfo_mode"));
3234
3235 (*mode) = buf->st_mode;
3236
3237 /* make 'ls'-like string */
3238
3239 if ( (buf->st_mode & S_IRUSR) != 0 ) c_mode[1] = 'r';
3240 if ( (buf->st_mode & S_IWUSR) != 0 ) c_mode[2] = 'w';
3241 if ( (buf->st_mode & S_IXUSR) != 0 ) {
3242 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 's';
3243 else c_mode[3] = 'x';
3244 } else {
3245 if ((buf->st_mode & S_ISUID) != 0 ) c_mode[3] = 'S';
3246 }
3247
3248 if ( (buf->st_mode & S_IRGRP) != 0 ) c_mode[4] = 'r';
3249 if ( (buf->st_mode & S_IWGRP) != 0 ) c_mode[5] = 'w';
3250 if ( (buf->st_mode & S_IXGRP) != 0 ) {
3251 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 's';
3252 else c_mode[6] = 'x';
3253 } else {
3254 if ((buf->st_mode & S_ISGID) != 0 ) c_mode[6] = 'S';
3255 }
3256
3257 if ( (buf->st_mode & S_IROTH) != 0 ) c_mode[7] = 'r';
3258 if ( (buf->st_mode & S_IWOTH) != 0 ) c_mode[8] = 'w';
3259#ifdef S_ISVTX /* not POSIX */
3260 if ( (buf->st_mode & S_IXOTH) != 0 ) {
3261 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 't';
3262 else c_mode[9] = 'x';
3263 } else {
3264 if ((buf->st_mode & S_ISVTX) != 0 ) c_mode[9] = 'T';
3265 }
3266#else
3267 if ( (buf->st_mode & S_IXOTH) != 0 ) c_mode[9] = 'x';
3268#endif
3269
3270 SL_RETURN(0, _("sh_unix_getinfo_mode"));
3271}
3272
3273
3274long IO_Limit = 0;
3275
3276void sh_unix_io_pause ()
3277{
3278 long runtime;
3279 float someval;
3280 unsigned long sometime;
3281
3282 if (IO_Limit == 0)
3283 {
3284 return;
3285 }
3286 else
3287 {
3288 runtime = (long) (time(NULL) - sh.statistics.time_start);
3289
3290 if (runtime > 0 && (long)(sh.statistics.bytes_hashed/runtime) > IO_Limit)
3291 {
3292 someval = sh.statistics.bytes_hashed - (IO_Limit * runtime);
3293 someval /= (float) IO_Limit;
3294 if (someval < 1.0)
3295 {
3296 someval *= 1000; /* milliseconds in a second */
3297 sometime = (unsigned long) someval;
3298 retry_msleep(0, sometime);
3299 }
3300 else
3301 {
3302 sometime = (unsigned long) someval;
3303 retry_msleep (sometime, 0);
3304 }
3305 }
3306 }
3307 return;
3308}
3309
3310int sh_unix_set_io_limit (const char * c)
3311{
3312 long val;
3313
3314 SL_ENTER(_("sh_unix_set_io_limit"));
3315
3316 val = strtol (c, (char **)NULL, 10);
3317 if (val < 0)
3318 sh_error_handle ((-1), FIL__, __LINE__, EINVAL, MSG_EINVALS,
3319 _("set I/O limit"), c);
3320
3321 val = (val < 0 ? 0 : val);
3322
3323 IO_Limit = val * 1024;
3324 SL_RETURN( 0, _("sh_unix_set_io_limit"));
3325}
3326
3327/* obtain file info
3328 */
3329extern int flag_err_debug;
3330
3331#include "sh_ignore.h"
3332
3333int sh_unix_checksum_size (char * filename, struct stat * fbuf,
3334 char * fileHash, int alert_timeout, SL_TICKET fd)
3335{
3336 file_type * tmpFile;
3337 int status;
3338
3339 SL_ENTER(_("sh_unix_checksum_size"));
3340
3341 tmpFile = SH_ALLOC(sizeof(file_type));
3342 tmpFile->link_path = NULL;
3343
3344 if (sh.flag.checkSum != SH_CHECK_INIT)
3345 {
3346 /* lookup file in database */
3347 status = sh_hash_get_it (filename, tmpFile, NULL);
3348 if (status != 0) {
3349 goto out;
3350 }
3351 }
3352 else
3353 {
3354 tmpFile->size = fbuf->st_size;
3355 }
3356
3357 /* if last < current get checksum */
3358 if (tmpFile->size < fbuf->st_size)
3359 {
3360 char hashbuf[KEYBUF_SIZE];
3361 UINT64 local_length = (UINT64) (tmpFile->size < 0 ? 0 : tmpFile->size);
3362 sl_strlcpy(fileHash,
3363 sh_tiger_generic_hash (filename, fd, &(local_length),
3364 alert_timeout, hashbuf, sizeof(hashbuf)),
3365 KEY_LEN+1);
3366
3367 /* return */
3368 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3369 SH_FREE(tmpFile);
3370 SL_RETURN( 0, _("sh_unix_checksum_size"));
3371 }
3372
3373 out:
3374 if (tmpFile->link_path) SH_FREE(tmpFile->link_path);
3375 SH_FREE(tmpFile);
3376 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3377 SL_RETURN( -1, _("sh_unix_checksum_size"));
3378}
3379
3380int sh_unix_check_selinux = S_FALSE;
3381int sh_unix_check_acl = S_FALSE;
3382
3383#ifdef USE_ACL
3384
3385#include <sys/acl.h>
3386static char * sh_unix_getinfo_acl (char * path, int fd, struct stat * buf)
3387{
3388 /* system.posix_acl_access, system.posix_acl_default
3389 */
3390 char * out = NULL;
3391 char * collect = NULL;
3392 char * tmp;
3393 char * out_compact;
3394 ssize_t len;
3395 acl_t result;
3396
3397 SL_ENTER(_("sh_unix_getinfo_acl"));
3398
3399 result = (fd == -1) ?
3400 acl_get_file (path, ACL_TYPE_ACCESS) :
3401 acl_get_fd (fd);
3402
3403 if (result)
3404 {
3405 out = acl_to_text (result, &len);
3406 if (out && (len > 0)) {
3407 out_compact = sh_util_acl_compact (out, len);
3408 acl_free(out);
3409 if (out_compact)
3410 {
3411 collect = sh_util_strconcat (_("acl_access:"), out_compact, NULL);
3412 SH_FREE(out_compact);
3413 }
3414 }
3415 acl_free(result);
3416 }
3417
3418
3419 if ( S_ISDIR(buf->st_mode) )
3420 {
3421 result = acl_get_file (path, ACL_TYPE_DEFAULT);
3422
3423 if (result)
3424 {
3425 out = acl_to_text (result, &len);
3426 if (out && (len > 0)) {
3427 out_compact = sh_util_acl_compact (out, len);
3428 acl_free(out);
3429 if (out_compact) {
3430 if (collect) {
3431 tmp = sh_util_strconcat (_("acl_default:"),
3432 out_compact, ":", collect, NULL);
3433 SH_FREE(collect);
3434 }
3435 else {
3436 tmp = sh_util_strconcat (_("acl_default:"), out_compact, NULL);
3437 }
3438 SH_FREE(out_compact);
3439 collect = tmp;
3440 }
3441 }
3442 acl_free(result);
3443 }
3444 }
3445
3446 SL_RETURN((collect),_("sh_unix_getinfo_acl"));
3447}
3448#endif
3449
3450#ifdef USE_XATTR
3451
3452#include <attr/xattr.h>
3453static char * sh_unix_getinfo_xattr_int (char * path, int fd, char * name)
3454{
3455 char * out = NULL;
3456 char * tmp = NULL;
3457 size_t size = 256;
3458 ssize_t result;
3459
3460 SL_ENTER(_("sh_unix_getinfo_xattr_int"));
3461
3462 out = SH_ALLOC(size);
3463
3464 result = (fd == -1) ?
3465 lgetxattr (path, name, out, size-1) :
3466 fgetxattr (fd, name, out, size-1);
3467
3468 if (result == -1 && errno == ERANGE)
3469 {
3470 SH_FREE(out);
3471 result = (fd == -1) ?
3472 lgetxattr (path, name, NULL, 0) :
3473 fgetxattr (fd, name, NULL, 0);
3474 size = result + 1;
3475 out = SH_ALLOC(size);
3476 result = (fd == -1) ?
3477 lgetxattr (path, name, out, size-1) :
3478 fgetxattr (fd, name, out, size-1);
3479 }
3480
3481 if ((result > 0) && ((size_t)result < size))
3482 {
3483 out[size-1] = '\0';
3484 tmp = out;
3485 }
3486 else
3487 {
3488 SH_FREE(out);
3489 }
3490
3491 SL_RETURN((tmp),_("sh_unix_getinfo_xattr_int"));
3492}
3493
3494
3495static char * sh_unix_getinfo_xattr (char * path, int fd, struct stat * buf)
3496{
3497 /* system.posix_acl_access, system.posix_acl_default, security.selinux
3498 */
3499 char * tmp;
3500 char * out = NULL;
3501 char * collect = NULL;
3502
3503 SL_ENTER(_("sh_unix_getinfo_xattr"));
3504
3505#ifdef USE_ACL
3506 /*
3507 * we need the acl_get_fd/acl_get_file functions, getxattr will only
3508 * yield the raw bytes
3509 */
3510 if (sh_unix_check_acl == S_TRUE)
3511 {
3512 out = sh_unix_getinfo_acl(path, fd, buf);
3513
3514 if (out)
3515 {
3516 collect = out;
3517 }
3518 }
3519#else
3520 (void) buf;
3521#endif
3522
3523 if (sh_unix_check_selinux == S_TRUE)
3524 {
3525 out = sh_unix_getinfo_xattr_int(path, fd, _("security.selinux"));
3526
3527 if (out)
3528 {
3529 if (collect) {
3530 tmp = sh_util_strconcat(_("selinux:"), out, ":", collect, NULL);
3531 SH_FREE(collect);
3532 }
3533 else {
3534 tmp = sh_util_strconcat(_("selinux:"), out, NULL);
3535 }
3536 SH_FREE(out);
3537 collect = tmp;
3538 }
3539 }
3540
3541 SL_RETURN((collect),_("sh_unix_getinfo_xattr"));
3542}
3543#endif
3544
3545#ifdef USE_XATTR
3546int sh_unix_setcheckselinux (const char * c)
3547{
3548 int i;
3549 SL_ENTER(_("sh_unix_setcheckselinux"));
3550 i = sh_util_flagval(c, &(sh_unix_check_selinux));
3551
3552 SL_RETURN(i, _("sh_unix_setcheckselinux"));
3553}
3554#endif
3555
3556#ifdef USE_ACL
3557int sh_unix_setcheckacl (const char * c)
3558{
3559 int i;
3560 SL_ENTER(_("sh_unix_setcheckacl"));
3561 i = sh_util_flagval(c, &(sh_unix_check_acl));
3562
3563 SL_RETURN(i, _("sh_unix_setcheckacl"));
3564}
3565#endif
3566
3567#ifdef HAVE_LIBZ
3568#include <zlib.h>
3569#endif
3570
3571int sh_unix_getinfo (int level, char * filename, file_type * theFile,
3572 char * fileHash, int policy)
3573{
3574 char timestr[81];
3575 long runtim;
3576 struct stat buf;
3577 struct stat lbuf;
3578 struct stat fbuf;
3579 int stat_return;
3580 int stat_errno = 0;
3581
3582 ShFileType type;
3583 unsigned int mode;
3584 char * tmp;
3585 char * tmp2;
3586
3587 char * linknamebuf;
3588 int linksize;
3589
3590 extern int get_the_fd (SL_TICKET ticket);
3591
3592 SL_TICKET rval_open;
3593 int err_open = 0;
3594
3595 int fd;
3596 int fstat_return;
3597 int fstat_errno = 0;
3598 int try = 0;
3599
3600 sh_string * content = NULL;
3601
3602 time_t tend;
3603 time_t tstart;
3604
3605
3606 char * path = NULL;
3607
3608 int alert_timeout = 120;
3609
3610 path = theFile->fullpath;
3611
3612 SL_ENTER(_("sh_unix_getinfo"));
3613
3614 /* --- Stat the file, and get checksum. ---
3615 */
3616 tstart = time(NULL);
3617
3618 stat_return = retry_lstat (FIL__, __LINE__,
3619 path /* theFile->fullpath */, &buf);
3620
3621 if (stat_return)
3622 stat_errno = errno;
3623
3624 theFile->link_path = NULL;
3625
3626 try_again:
3627
3628 fd = -1;
3629 fstat_return = -1;
3630 rval_open = -1;
3631
3632 if (stat_return == 0 && S_ISREG(buf.st_mode))
3633 {
3634 rval_open = sl_open_fastread (FIL__, __LINE__,
3635 path /* theFile->fullpath */, SL_YESPRIV);
3636 if (SL_ISERROR(rval_open))
3637 {
3638 char * stale = sl_check_stale();
3639
3640 if (stale)
3641 {
3642 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, err_open, MSG_E_SUBGEN,
3643 stale, _("sh_unix_getinfo_open"));
3644 }
3645
3646 if (errno == EBADF && try == 0) /* obsolete, but we keep this, just in case */
3647 {
3648 ++try;
3649 goto try_again;
3650 }
3651 err_open = errno;
3652 }
3653
3654 alert_timeout = 120; /* this is per 8K block now ! */
3655
3656 if (path[1] == 'p' && path[5] == '/' && path[2] == 'r' &&
3657 path[3] == 'o' && path[4] == 'c' && path[0] == '/')
3658 {
3659 /* seven is magic */
3660 alert_timeout = 7;
3661 }
3662
3663 fd = get_the_fd(rval_open);
3664 }
3665
3666 tend = time(NULL);
3667
3668 /* An unprivileged user may slow lstat/open to a crawl
3669 * with clever path/symlink setup
3670 */
3671 if ((tend - tstart) > (time_t) /* 60 */ 6)
3672 {
3673 tmp2 = sh_util_safe_name (theFile->fullpath);
3674 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_TOOLATE,
3675 (long)(tend - tstart), tmp2);
3676 SH_FREE(tmp2);
3677 }
3678
3679 if (fd >= 0)
3680 {
3681 fstat_return = retry_fstat (FIL__, __LINE__, fd, &fbuf);
3682
3683 if (fstat_return)
3684 {
3685 char * stale;
3686
3687 fstat_errno = errno;
3688
3689 stale = sl_check_stale();
3690
3691 if (stale)
3692 {
3693 sh_error_handle(SH_ERR_ERR, FIL__, __LINE__, fstat_errno,
3694 MSG_E_SUBGEN,
3695 stale, _("sh_unix_getinfo_fstat"));
3696 }
3697
3698 if (try == 0) /* obsolete, but we keep this, just in case */
3699 {
3700 ++try;
3701 sl_close(rval_open);
3702 goto try_again;
3703 }
3704 }
3705 }
3706 else
3707 {
3708 fd = -1;
3709 }
3710
3711
3712 /* --- case 1: lstat failed ---
3713 */
3714 if (stat_return != 0)
3715 {
3716 stat_return = errno;
3717 if (!SL_ISERROR(rval_open))
3718 sl_close(rval_open);
3719 if (sh.flag.checkSum == SH_CHECK_INIT ||
3720 (sh_hash_have_it (theFile->fullpath) >= 0 &&
3721 (!SH_FFLAG_REPORTED_SET(theFile->file_reported))))
3722 {
3723 if (S_FALSE == sh_ignore_chk_del(theFile->fullpath)) {
3724 char errbuf[SH_ERRBUF_SIZE];
3725 uid_t euid;
3726 (void) sl_get_euid(&euid);
3727 tmp2 = sh_util_safe_name (theFile->fullpath);
3728 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3729 _("lstat"),
3730 sh_error_message (stat_errno, errbuf, sizeof(errbuf)),
3731 (long) euid,
3732 tmp2);
3733 SH_FREE(tmp2);
3734 }
3735 }
3736 SL_RETURN((-1),_("sh_unix_getinfo"));
3737 }
3738
3739 /* --- case 2: not a regular file ---
3740 */
3741 else if (! S_ISREG(buf.st_mode))
3742 {
3743 if (fileHash != NULL)
3744 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3745 }
3746
3747 /* --- case 3a: a regular file, fstat ok ---
3748 */
3749 else if (fstat_return == 0 &&
3750 buf.st_mode == fbuf.st_mode &&
3751 buf.st_ino == fbuf.st_ino &&
3752 buf.st_uid == fbuf.st_uid &&
3753 buf.st_gid == fbuf.st_gid &&
3754 buf.st_dev == fbuf.st_dev )
3755 {
3756 if (fileHash != NULL)
3757 {
3758 if ((theFile->check_mask & MODI_CHK) == 0 ||
3759 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3760 (UINT64) fbuf.st_mode, rval_open))
3761 {
3762 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3763 }
3764 else if ((theFile->check_mask & MODI_PREL) != 0 &&
3765 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3766 alert_timeout, theFile->fullpath))
3767 {
3768 if (0 != sh_prelink_run (theFile->fullpath,
3769 fileHash, alert_timeout))
3770 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3771 }
3772 else
3773 {
3774 char hashbuf[KEYBUF_SIZE];
3775 UINT64 length_nolim = TIGER_NOLIM;
3776
3777 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3778 {
3779 sl_init_content (rval_open, fbuf.st_size);
3780 }
3781
3782 sl_strlcpy(fileHash,
3783 sh_tiger_generic_hash (theFile->fullpath,
3784 rval_open, &length_nolim,
3785 alert_timeout,
3786 hashbuf, sizeof(hashbuf)),
3787 KEY_LEN+1);
3788
3789 content = sl_get_content(rval_open);
3790 content = sh_string_copy(content);
3791
3792 if ((theFile->check_mask & MODI_SGROW) != 0)
3793 {
3794 fbuf.st_size = (off_t) length_nolim;
3795 buf.st_size = fbuf.st_size;
3796 sl_rewind(rval_open);
3797 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3798 &fileHash[KEY_LEN + 1],
3799 alert_timeout, rval_open);
3800 }
3801 }
3802 }
3803 }
3804
3805 /* --- case 3b: a regular file, fstat ok, but different ---
3806 */
3807 else if (fstat_return == 0 && S_ISREG(fbuf.st_mode))
3808 {
3809 memcpy (&buf, &fbuf, sizeof( struct stat ));
3810
3811 if (fileHash != NULL)
3812 {
3813 if ((theFile->check_mask & MODI_CHK) == 0 ||
3814 sh_restrict_this(theFile->fullpath, (UINT64) fbuf.st_size,
3815 (UINT64) fbuf.st_mode, rval_open))
3816 {
3817 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3818 }
3819 else if (policy == SH_LEVEL_PRELINK &&
3820 S_TRUE == sh_prelink_iself(rval_open, fbuf.st_size,
3821 alert_timeout, theFile->fullpath))
3822 {
3823 if (0 != sh_prelink_run (theFile->fullpath,
3824 fileHash, alert_timeout))
3825 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3826 }
3827 else
3828 {
3829 char hashbuf[KEYBUF_SIZE];
3830 UINT64 length_nolim = TIGER_NOLIM;
3831
3832 if (MODI_TXT_ENABLED(theFile->check_mask) && fbuf.st_size < (10 * SH_TXT_MAX))
3833 {
3834 sl_init_content (rval_open, fbuf.st_size);
3835 }
3836
3837 sl_strlcpy(fileHash,
3838 sh_tiger_generic_hash (theFile->fullpath, rval_open,
3839 &length_nolim,
3840 alert_timeout,
3841 hashbuf, sizeof(hashbuf)),
3842 KEY_LEN + 1);
3843
3844 content = sl_get_content(rval_open);
3845 content = sh_string_copy(content);
3846
3847 if ((theFile->check_mask & MODI_SGROW) != 0)
3848 {
3849 fbuf.st_size = (off_t) length_nolim;
3850 buf.st_size = fbuf.st_size;
3851 sl_rewind(rval_open);
3852 sh_unix_checksum_size (theFile->fullpath, &fbuf,
3853 &fileHash[KEY_LEN + 1],
3854 alert_timeout, rval_open);
3855 }
3856 }
3857 }
3858 }
3859
3860 /* --- case 4: a regular file, fstat failed ---
3861 */
3862
3863 else /* fstat_return != 0 or !S_ISREG(fbuf.st_mode) or open() failed */
3864 {
3865 uid_t euid;
3866
3867 if (fileHash != NULL)
3868 sl_strlcpy(fileHash, SH_KEY_NULL, KEY_LEN+1);
3869
3870 if ((theFile->check_mask & MODI_CHK) != 0)
3871 {
3872 tmp2 = sh_util_safe_name (theFile->fullpath);
3873
3874
3875 if (fd >= 0 && fstat_return != 0)
3876 {
3877 char errbuf[SH_ERRBUF_SIZE];
3878 (void) sl_get_euid(&euid);
3879
3880 sh_error_handle (level, FIL__, __LINE__, stat_return, MSG_FI_STAT,
3881 _("fstat"),
3882 sh_error_message (fstat_errno, errbuf, sizeof(errbuf)),
3883 (long) euid,
3884 tmp2);
3885 }
3886 else if (fd >= 0 && !S_ISREG(fbuf.st_mode))
3887 {
3888 sh_error_handle (level, FIL__, __LINE__, fstat_errno,
3889 MSG_E_NOTREG, tmp2);
3890 }
3891 else
3892 {
3893 char errbuf[SH_ERRBUF_SIZE];
3894 char errbuf2[SH_ERRBUF_SIZE];
3895 sl_strlcpy(errbuf, sl_error_string(rval_open), sizeof(errbuf));
3896 sh_error_message(err_open, errbuf2, sizeof(errbuf2));
3897 sh_error_handle (level, FIL__, __LINE__, err_open,
3898 MSG_E_READ, errbuf, errbuf2, tmp2);
3899 }
3900 SH_FREE(tmp2);
3901 }
3902 }
3903
3904
3905 /* --- Determine file type. ---
3906 */
3907 memset (theFile->c_mode, '-', CMODE_SIZE-1);
3908 theFile->c_mode[CMODE_SIZE-1] = '\0';
3909
3910 memset (theFile->link_c_mode, '-', CMODE_SIZE-1);
3911 theFile->link_c_mode[CMODE_SIZE-1] = '\0';
3912
3913 sh_unix_getinfo_type (&buf, &type, theFile->c_mode);
3914 theFile->type = type;
3915
3916#if defined(__linux__) || defined(HAVE_STAT_FLAGS)
3917
3918 /* --- Determine file attributes. ---
3919 */
3920 memset (theFile->c_attributes, '-', ATTRBUF_SIZE);
3921 theFile->c_attributes[ATTRBUF_USED] = '\0';
3922 theFile->attributes = 0;
3923
3924#if (defined(__linux__) && (defined(HAVE_LINUX_EXT2_FS_H) || defined(HAVE_EXT2FS_EXT2_FS_H))) || defined(HAVE_STAT_FLAGS)
3925 if (theFile->c_mode[0] != 'c' && theFile->c_mode[0] != 'b' &&
3926 theFile->c_mode[0] != 'l' )
3927 sh_unix_getinfo_attr(theFile->fullpath,
3928 &theFile->attributes, theFile->c_attributes,
3929 fd, &buf);
3930#endif
3931#endif
3932
3933#if defined(USE_XATTR) && defined(USE_ACL)
3934 if (sh_unix_check_selinux == S_TRUE || sh_unix_check_acl == S_TRUE)
3935 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
3936#elif defined(USE_XATTR)
3937 if (sh_unix_check_selinux == S_TRUE)
3938 theFile->attr_string = sh_unix_getinfo_xattr (theFile->fullpath, fd, &buf);
3939#elif defined(USE_ACL)
3940 if (sh_unix_check_acl == S_TRUE)
3941 theFile->attr_string = sh_unix_getinfo_acl (theFile->fullpath, fd, &buf);
3942#else
3943 theFile->attr_string = NULL;
3944#endif
3945
3946 if (!SL_ISERROR(rval_open))
3947 sl_close(rval_open);
3948
3949
3950 /* --- I/O limit. ---
3951 */
3952 if (IO_Limit > 0)
3953 {
3954 runtim = (long) (time(NULL) - sh.statistics.time_start);
3955
3956 if (runtim > 0 && (long)(sh.statistics.bytes_hashed/runtim) > IO_Limit)
3957 retry_msleep(1, 0);
3958 }
3959
3960 /* --- Determine permissions. ---
3961 */
3962 sh_unix_getinfo_mode (&buf, &mode, theFile->c_mode);
3963
3964 /* --- Trivia. ---
3965 */
3966 theFile->dev = buf.st_dev;
3967 theFile->ino = buf.st_ino;
3968 theFile->mode = buf.st_mode;
3969 theFile->hardlinks = buf.st_nlink;
3970 theFile->owner = buf.st_uid;
3971 theFile->group = buf.st_gid;
3972 theFile->rdev = buf.st_rdev;
3973 theFile->size = buf.st_size;
3974 theFile->blksize = (unsigned long) buf.st_blksize;
3975 theFile->blocks = (unsigned long) buf.st_blocks;
3976 theFile->atime = buf.st_atime;
3977 theFile->mtime = buf.st_mtime;
3978 theFile->ctime = buf.st_ctime;
3979
3980
3981 /* --- Owner and group. ---
3982 */
3983
3984 if (NULL == sh_unix_getGIDname(SH_ERR_ALL, buf.st_gid, theFile->c_group, GROUP_MAX+1)) {
3985
3986 tmp2 = sh_util_safe_name (theFile->fullpath);
3987
3988 if (policy == SH_LEVEL_ALLIGNORE)
3989 {
3990 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
3991 MSG_FI_NOGRP,
3992 (long) buf.st_gid, tmp2);
3993 }
3994 else
3995 {
3996 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
3997 MSG_FI_NOGRP,
3998 (long) buf.st_gid, tmp2);
3999 }
4000 SH_FREE(tmp2);
4001 sl_snprintf(theFile->c_group, GROUP_MAX+1, "%d", (long) buf.st_gid);
4002 }
4003
4004
4005 if (NULL == sh_unix_getUIDname(SH_ERR_ALL, buf.st_uid, theFile->c_owner, USER_MAX+1)) {
4006
4007 tmp2 = sh_util_safe_name (theFile->fullpath);
4008
4009 if (policy == SH_LEVEL_ALLIGNORE)
4010 {
4011 sh_error_handle (SH_ERR_ALL, FIL__, __LINE__, ENOENT,
4012 MSG_FI_NOUSR,
4013 (long) buf.st_uid, tmp2);
4014 }
4015 else
4016 {
4017 sh_error_handle (ShDFLevel[SH_ERR_T_NAME], FIL__, __LINE__, ENOENT,
4018 MSG_FI_NOUSR,
4019 (long) buf.st_uid, tmp2);
4020 }
4021 SH_FREE(tmp2);
4022 sl_snprintf(theFile->c_owner, USER_MAX+1, "%d", (long) buf.st_uid);
4023 }
4024
4025 /* --- Output the file. ---
4026 */
4027 if (flag_err_debug == SL_TRUE)
4028 {
4029 tmp2 = sh_util_safe_name ((filename == NULL) ?
4030 theFile->fullpath : filename);
4031 (void) sh_unix_time(theFile->mtime, timestr, sizeof(timestr));
4032 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LIST,
4033 theFile->c_mode,
4034 theFile->hardlinks,
4035 theFile->c_owner,
4036 theFile->c_group,
4037 (unsigned long) theFile->size,
4038 timestr,
4039 tmp2);
4040 SH_FREE(tmp2);
4041 }
4042
4043 /* --- Check for links. ---
4044 */
4045 if (theFile->c_mode[0] == 'l')
4046 {
4047 linknamebuf = SH_ALLOC(PATH_MAX);
4048
4049 /* flawfinder: ignore */
4050 linksize = readlink (theFile->fullpath, linknamebuf, PATH_MAX-1);
4051
4052 if (linksize < (PATH_MAX-1) && linksize >= 0)
4053 linknamebuf[linksize] = '\0';
4054 else
4055 linknamebuf[PATH_MAX-1] = '\0';
4056
4057 if (linksize < 0)
4058 {
4059 char errbuf[SH_ERRBUF_SIZE];
4060 linksize = errno;
4061 tmp2 = sh_util_safe_name (theFile->fullpath);
4062 sh_error_handle (level, FIL__, __LINE__, linksize, MSG_FI_RDLNK,
4063 sh_error_message (linksize, errbuf, sizeof(errbuf)), tmp2);
4064 SH_FREE(tmp2);
4065 SH_FREE(linknamebuf);
4066 theFile->link_path = sh_util_strdup("-");
4067 SL_RETURN((-1),_("sh_unix_getinfo"));
4068 }
4069
4070 if (linknamebuf[0] == '/')
4071 {
4072 theFile->link_path = sh_util_strdup (linknamebuf);
4073 }
4074 else
4075 {
4076 tmp = sh_util_dirname(theFile->fullpath);
4077 if (tmp) {
4078 theFile->link_path = SH_ALLOC(PATH_MAX);
4079 sl_strlcpy (theFile->link_path, tmp, PATH_MAX);
4080 SH_FREE(tmp);
4081 } else {
4082 theFile->link_path = SH_ALLOC(PATH_MAX);
4083 theFile->link_path[0] = '\0';
4084 }
4085 /*
4086 * Only attach '/' if not root directory. Handle "//", which
4087 * according to POSIX is implementation-defined, and may be
4088 * different from "/" (however, three or more '/' will collapse
4089 * to one).
4090 */
4091 tmp = theFile->link_path; while (*tmp == '/') ++tmp;
4092 if (*tmp != '\0')
4093 {
4094 sl_strlcat (theFile->link_path, "/", PATH_MAX);
4095 }
4096 sl_strlcat (theFile->link_path, linknamebuf, PATH_MAX);
4097 }
4098
4099 /* stat the link
4100 */
4101 stat_return = retry_lstat (FIL__, __LINE__, theFile->link_path, &lbuf);
4102
4103 /* check for error
4104 */
4105 if (stat_return != 0)
4106 {
4107 stat_return = errno;
4108 tmp = sh_util_safe_name (theFile->fullpath);
4109 tmp2 = sh_util_safe_name (theFile->link_path);
4110 if (stat_return != ENOENT)
4111 {
4112 uid_t euid;
4113 char errbuf[SH_ERRBUF_SIZE];
4114
4115 (void) sl_get_euid(&euid);
4116 sh_error_handle (level, FIL__, __LINE__, stat_return,
4117 MSG_FI_STAT,
4118 _("lstat"),
4119 sh_error_message (stat_return,errbuf, sizeof(errbuf)),
4120 (long) euid,
4121 tmp2);
4122 }
4123 else
4124 {
4125 /* a dangling link -- everybody seems to have plenty of them
4126 */
4127 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_DLNK,
4128 tmp, tmp2);
4129 }
4130 theFile->linkisok = BAD;
4131 SH_FREE(tmp);
4132 SH_FREE(tmp2);
4133 SH_FREE(linknamebuf);
4134 /*
4135 * changed Tue Feb 10 16:16:13 CET 2004:
4136 * add dangling symlinks into database
4137 * SL_RETURN((-1),_("sh_unix_getinfo"));
4138 */
4139 theFile->linkmode = 0;
4140 SL_RETURN((0),_("sh_unix_getinfo"));
4141 }
4142
4143 theFile->linkisok = GOOD;
4144
4145
4146 /* --- Determine file type. ---
4147 */
4148 sh_unix_getinfo_type (&lbuf, &type, theFile->link_c_mode);
4149 theFile->type = type;
4150
4151 /* --- Determine permissions. ---
4152 */
4153 sh_unix_getinfo_mode (&lbuf, &mode, theFile->link_c_mode);
4154 theFile->linkmode = lbuf.st_mode;
4155
4156 /* --- Output the link. ---
4157 */
4158 if (theFile->linkisok == GOOD)
4159 {
4160 tmp2 = sh_util_safe_name (linknamebuf);
4161 sh_error_handle ((-1), FIL__, __LINE__, 0, MSG_FI_LLNK,
4162 theFile->link_c_mode, tmp2);
4163 SH_FREE(tmp2);
4164 }
4165 SH_FREE(linknamebuf);
4166 }
4167 else /* not a link */
4168 {
4169 if (content)
4170 {
4171#ifdef HAVE_LIBZ
4172 unsigned long clen;
4173 unsigned char * compressed;
4174#ifdef HAVE_COMPRESSBOUND
4175 clen = compressBound(sh_string_len(content));
4176#else
4177 if (sh_string_len(content) > 10*SH_TXT_MAX)
4178 clen = SH_TXT_MAX;
4179 else
4180 clen = 13 + (int)(1.0001*sh_string_len(content));
4181#endif
4182 compressed = SH_ALLOC(clen);
4183 if (Z_OK == compress(compressed, &clen,
4184 (unsigned char *) sh_string_str(content),
4185 sh_string_len(content)))
4186 {
4187 if (clen < SH_TXT_MAX)
4188 {
4189 sh_util_base64_enc_alloc (&(theFile->link_path),
4190 (char *) compressed, clen);
4191 }
4192 else
4193 {
4194 char tmsg[128];
4195 char * tpath = sh_util_safe_name (theFile->fullpath);
4196 sl_snprintf(tmsg, sizeof(tmsg),
4197 _("compressed file too large (%lu bytes)"),
4198 clen);
4199 sh_error_handle (SH_ERR_WARN, FIL__, __LINE__, -1,
4200 MSG_E_SUBGPATH, tmsg,
4201 _("sh_unix_getinfo"), tpath);
4202 SH_FREE(tpath);
4203 }
4204 }
4205 SH_FREE(compressed);
4206#endif
4207 sh_string_destroy(&content);
4208 }
4209 }
4210 SL_RETURN((0),_("sh_unix_getinfo"));
4211}
4212
4213/* #if defined (SH_WITH_CLIENT) || defined (SH_STANDALONE) */
4214#endif
4215
4216int sh_unix_unlock(char * lockfile, char * flag)
4217{
4218 int error = 0;
4219
4220 SL_ENTER(_("sh_unix_unlock"));
4221
4222 if (sh.flag.isdaemon == S_FALSE && flag == NULL)
4223 SL_RETURN((0),_("sh_unix_unlock"));
4224
4225 /* --- Logfile is not locked to us. ---
4226 */
4227 if (sh.flag.islocked == BAD && flag != NULL)
4228 SL_RETURN((-1),_("sh_unix_unlock"));
4229
4230 /* --- Check whether the directory is secure. ---
4231 */
4232 if (0 != tf_trust_check (lockfile, SL_YESPRIV))
4233 SL_RETURN((-1),_("sh_unix_unlock"));
4234
4235 /* --- Delete the lock file. ---
4236 */
4237 error = retry_aud_unlink (FIL__, __LINE__, lockfile);
4238
4239 if (error == 0)
4240 {
4241 if (flag != NULL)
4242 sh.flag.islocked = BAD; /* not locked anymore */
4243 }
4244 else if (flag != NULL)
4245 {
4246 char errbuf[SH_ERRBUF_SIZE];
4247 error = errno;
4248 sh_error_handle ((-1), FIL__, __LINE__, error, MSG_E_UNLNK,
4249 sh_error_message(error, errbuf, sizeof(errbuf)),
4250 lockfile);
4251 SL_RETURN((-1),_("sh_unix_unlock"));
4252 }
4253 SL_RETURN((0),_("sh_unix_unlock"));
4254}
4255
4256int sh_unix_check_piddir (char * pidpath)
4257{
4258 static struct stat buf;
4259 int status = 0;
4260 char * pid_dir;
4261
4262 SL_ENTER(_("sh_unix_check_piddir"));
4263
4264 pid_dir = sh_util_dirname (pidpath);
4265
4266 status = retry_lstat (FIL__, __LINE__, pid_dir, &buf);
4267
4268 if (status < 0 && errno == ENOENT)
4269 {
4270 status = mkdir (pid_dir, 0777);
4271 if (status < 0)
4272 {
4273 sh_error_handle ((-1), FIL__, __LINE__, status,
4274 MSG_E_SUBGEN,
4275 _("Cannot create PID directory"),
4276 _("sh_unix_check_piddir"));
4277 SH_FREE(pid_dir);
4278 SL_RETURN((-1),_("sh_unix_check_piddir"));
4279 }
4280 }
4281 else if (!S_ISDIR(buf.st_mode))
4282 {
4283 sh_error_handle ((-1), FIL__, __LINE__, status,
4284 MSG_E_SUBGEN,
4285 _("Path of PID directory refers to a non-directory object"),
4286 _("sh_unix_check_piddir"));
4287 SH_FREE(pid_dir);
4288 SL_RETURN((-1),_("sh_unix_check_piddir"));
4289 }
4290 SH_FREE(pid_dir);
4291 SL_RETURN((0),_("sh_unix_check_piddir"));
4292}
4293
4294int sh_unix_lock (char * lockfile, char * flag)
4295{
4296 int filed;
4297 int errnum;
4298 char myPid[64];
4299 SL_TICKET fd;
4300 extern int get_the_fd (SL_TICKET ticket);
4301
4302 SL_ENTER(_("sh_unix_lock"));
4303
4304 sprintf (myPid, "%ld\n", (long) sh.pid); /* known to fit */
4305
4306 if (flag == NULL) /* PID file, check for directory */
4307 {
4308 if (0 != sh_unix_check_piddir (lockfile))
4309 {
4310 SL_RETURN((-1),_("sh_unix_lock"));
4311 }
4312 }
4313
4314 fd = sl_open_safe_rdwr (FIL__, __LINE__,
4315 lockfile, SL_YESPRIV); /* fails if file exists */
4316
4317 if (!SL_ISERROR(fd))
4318 {
4319 errnum = sl_write (fd, myPid, sl_strlen(myPid));
4320 filed = get_the_fd(fd);
4321 fchmod (filed, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
4322 sl_close (fd);
4323
4324 if (!SL_ISERROR(errnum))
4325 {
4326 if (flag != NULL)
4327 sh.flag.islocked = GOOD;
4328 SL_RETURN((0),_("sh_unix_lock"));
4329 }
4330 }
4331
4332 TPT((0, FIL__, __LINE__, _("msg=<open pid file failed>\n")));
4333 if (flag != NULL)
4334 sh.flag.islocked = BAD;
4335 SL_RETURN((-1),_("sh_unix_lock"));
4336
4337 /* notreached */
4338}
4339
4340
4341/* check whether file is locked
4342 */
4343int sh_unix_test_and_lock (char * filename, char * lockfile)
4344{
4345 static struct stat buf;
4346 int status = 0;
4347
4348
4349 SL_TICKET fd;
4350 char line_in[128];
4351
4352 SL_ENTER(_("sh_unix_test_and_lock"));
4353
4354 status = retry_lstat (FIL__, __LINE__, lockfile, &buf);
4355
4356 /* --- No lock file found, try to lock. ---
4357 */
4358
4359 if (status < 0 && errno == ENOENT)
4360 {
4361 if (0 == sh_unix_lock (lockfile, filename))
4362 {
4363 if (filename != NULL)
4364 sh.flag.islocked = GOOD;
4365 SL_RETURN((0),_("sh_unix_test_and_lock"));
4366 }
4367 else
4368 {
4369 sh_error_handle ((-1), FIL__, __LINE__, status,
4370 MSG_E_SUBGEN,
4371 (filename == NULL) ? _("Cannot create PID file (1)") : _("Cannot create lock file (1)"),
4372 _("sh_unix_test_and_lock"));
4373 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4374 }
4375 }
4376 else if (status == 0 && buf.st_size == 0)
4377 {
4378 if (filename != NULL)
4379 sh.flag.islocked = GOOD;
4380 sh_unix_unlock (lockfile, filename);
4381 if (filename != NULL)
4382 sh.flag.islocked = BAD;
4383 if (0 == sh_unix_lock (lockfile, filename))
4384 {
4385 if (filename != NULL)
4386 sh.flag.islocked = GOOD;
4387 SL_RETURN((0),_("sh_unix_test_and_lock"));
4388 }
4389 else
4390 {
4391 sh_error_handle ((-1), FIL__, __LINE__, status,
4392 MSG_E_SUBGEN,
4393 (filename == NULL) ? _("Cannot create PID file (2)") : _("Cannot create lock file (2)"),
4394 _("sh_unix_test_and_lock"));
4395 SL_RETURN((-1),_("sh_unix_test_and_lock"));
4396 }
4397 }
4398
4399 /* --- Check on lock. ---
4400 */
4401
4402 if (status >= 0)
4403 {
4404 fd = sl_open_read (FIL__, __LINE__, lockfile, SL_YESPRIV);
4405 if (SL_ISERROR(fd))
4406 sh_error_handle ((-1), FIL__, __LINE__, fd,
4407 MSG_E_SUBGEN,
4408 (filename == NULL) ? _("Cannot open PID file for read") : _("Cannot open lock file for read"),
4409 _("sh_unix_test_and_lock"));
4410 }
4411 else
4412 fd = -1;
4413
4414 if (!SL_ISERROR(fd))
4415 {
4416 /* read the PID in the lock file
4417 */
4418 status = sl_read (fd, line_in, sizeof(line_in));
4419 line_in[sizeof(line_in)-1] = '\0';
4420
4421 /* convert to numeric
4422 */
4423 if (status > 0)
4424 {
4425 errno = 0;
4426 status = strtol(line_in, (char **)NULL, 10);
4427 if (errno == ERANGE || status <= 0)
4428 {
4429 sh_error_handle ((-1), FIL__, __LINE__, status,
4430 MSG_E_SUBGEN,
4431 (filename == NULL) ? _("Bad PID in PID file") : _("Bad PID in lock file"),
4432 _("sh_unix_test_and_lock"));
4433
4434 status = -1;
4435 }
4436 }
4437 else
4438 {
4439 sh_error_handle ((-1), FIL__, __LINE__, status,
4440 MSG_E_SUBGEN,
4441 (filename == NULL) ? _("Cannot read PID file") : _("Cannot read lock file"),
4442 _("sh_unix_test_and_lock"));
4443 }
4444 sl_close(fd);
4445
4446 if (status > 0 && (unsigned int) status == sh.pid)
4447 {
4448 if (filename != NULL)
4449 sh.flag.islocked = GOOD;
4450 SL_RETURN((0),_("sh_unix_test_and_lock"));
4451 }
4452
4453
4454 /* --- Check whether the process exists. ---
4455 */
4456 if (status > 0)
4457 {
4458 errno = 0;
4459 status = aud_kill (FIL__, __LINE__, status, 0);
4460
4461 /* Does not exist, so remove the stale lock
4462 * and create a new one.
4463 */
4464 if (status < 0 && errno == ESRCH)
4465 {
4466 if (filename != NULL)
4467 sh.flag.islocked = GOOD;
4468 if (0 != sh_unix_unlock(lockfile, filename) && (filename !=NULL))
4469 sh.flag.islocked = BAD;
4470 else
4471 {
4472 if (0 == sh_unix_lock (lockfile, filename))
4473 {
4474 if (filename != NULL)
4475 sh.flag.islocked = GOOD;
4476 SL_RETURN((0),_("sh_unix_test_and_lock"));
4477 }
4478 else
4479 {
4480 sh_error_handle ((-1), FIL__, __LINE__, status,
4481 MSG_E_SUBGEN,
4482 (filename == NULL) ? _("Cannot create PID file (3)") : _("Cannot create lock file (3)"),
4483 _("sh_unix_test_and_lock"));
4484 }
4485 if (filename != NULL)
4486 sh.flag.islocked = BAD;
4487 }
4488 }
4489 else
4490 {
4491 sh_error_handle ((-1), FIL__, __LINE__, status,
4492 MSG_E_SUBGEN,
4493 (filename == NULL) ? _("Cannot remove stale PID file, PID may be a running process") : _("Cannot remove stale lock file, PID may be a running process"),
4494 _("sh_unix_test_and_lock"));
4495 if (filename != NULL)
4496 sh.flag.islocked = BAD;
4497 }
4498 }
4499 }
4500 SL_RETURN((-1),_("sh_unix_testlock"));
4501}
4502
4503/* write the PID file
4504 */
4505int sh_unix_write_pid_file()
4506{
4507 return sh_unix_test_and_lock(NULL, sh.srvlog.alt);
4508}
4509
4510/* write lock for filename
4511 */
4512int sh_unix_write_lock_file(char * filename)
4513{
4514 size_t len;
4515 int res;
4516 char * lockfile;
4517
4518 if (filename == NULL)
4519 return (-1);
4520
4521 len = sl_strlen(filename);
4522 if (sl_ok_adds(len, 6))
4523 len += 6;
4524 lockfile = SH_ALLOC(len);
4525 sl_strlcpy(lockfile, filename, len);
4526 sl_strlcat(lockfile, _(".lock"), len);
4527 res = sh_unix_test_and_lock(filename, lockfile);
4528 SH_FREE(lockfile);
4529 return res;
4530}
4531
4532/* rm lock for filename
4533 */
4534int sh_unix_rm_lock_file(char * filename)
4535{
4536 size_t len;
4537 int res;
4538 char * lockfile;
4539
4540 if (filename == NULL)
4541 return (-1);
4542
4543 len = sl_strlen(filename);
4544 if (sl_ok_adds(len, 6))
4545 len += 6;
4546 lockfile = SH_ALLOC(len);
4547 sl_strlcpy(lockfile, filename, len);
4548 sl_strlcat(lockfile, _(".lock"), len);
4549
4550 res = sh_unix_unlock(lockfile, filename);
4551 SH_FREE(lockfile);
4552 return res;
4553}
4554
4555/* rm lock for filename
4556 */
4557int sh_unix_rm_pid_file()
4558{
4559 return sh_unix_unlock(sh.srvlog.alt, NULL);
4560}
4561
4562/* Test whether file exists
4563 */
4564int sh_unix_file_exists(char * path)
4565{
4566 struct stat buf;
4567
4568 SL_ENTER(_("sh_unix_file_exists"));
4569
4570 if (0 == retry_lstat(FIL__, __LINE__, path, &buf))
4571 SL_RETURN( S_TRUE, _("sh_unix_file_exists"));
4572 else
4573 SL_RETURN( S_FALSE, _("sh_unix_file_exists"));
4574}
4575
4576
4577/* Test whether file exists, is a character device, and allows read
4578 * access.
4579 */
4580int sh_unix_device_readable(int fd)
4581{
4582 struct stat buf;
4583
4584 SL_ENTER(_("sh_unix_device_readable"));
4585
4586 if (retry_fstat(FIL__, __LINE__, fd, &buf) == -1)
4587 SL_RETURN( (-1), _("sh_unix_device_readable"));
4588 else if ( S_ISCHR(buf.st_mode) && 0 != (S_IROTH & buf.st_mode) )
4589 SL_RETURN( (0), _("sh_unix_device_readable"));
4590 else
4591 SL_RETURN( (-1), _("sh_unix_device_readable"));
4592}
4593
4594static char preq[16];
4595
4596/* return true if database is remote
4597 */
4598int file_is_remote ()
4599{
4600 static int init = 0;
4601 struct stat buf;
4602
4603 SL_ENTER(_("file_is_remote"));
4604
4605 if (init == 0)
4606 {
4607 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4608 ++init;
4609 }
4610 if (0 == sl_strncmp (sh.data.path, preq, 15))
4611 {
4612 if (sh.data.path[15] != '\0') /* should be start of path */
4613 {
4614 if (0 == stat(&(sh.data.path[15]), &buf))
4615 {
4616 SL_RETURN( S_FALSE, _("file_is_remote"));
4617 }
4618 }
4619 SL_RETURN( S_TRUE, _("file_is_remote"));
4620 }
4621 SL_RETURN( S_FALSE, _("file_is_remote"));
4622}
4623
4624/* Return the path to the configuration/database file.
4625 */
4626char * file_path(char what, char flag)
4627{
4628 static int init = 0;
4629
4630 SL_ENTER(_("file_path"));
4631
4632 if (init == 0)
4633 {
4634 sl_strlcpy(preq, _("REQ_FROM_SERVER"), 16);
4635 ++init;
4636 }
4637
4638 switch (what)
4639 {
4640
4641 case 'C':
4642 if (0 == sl_strncmp (sh.conf.path, preq, 15))
4643 {
4644#if defined(SH_WITH_SERVER)
4645 if (sh.flag.isserver == S_TRUE && sl_strlen(sh.conf.path) == 15)
4646 SL_RETURN( NULL, _("file_path"));
4647 if (sh.flag.isserver == S_TRUE)
4648 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4649#endif
4650 if (flag == 'R')
4651 SL_RETURN( preq, _("file_path"));
4652 if (flag == 'I')
4653 {
4654 if (sl_strlen(sh.conf.path) == 15)
4655 SL_RETURN( NULL, _("file_path"));
4656 else
4657 SL_RETURN( &(sh.conf.path[15]), _("file_path"));
4658 }
4659 SL_RETURN ( preq, _("file_path"));
4660 }
4661 else
4662 SL_RETURN( sh.conf.path, _("file_path"));
4663 /* break; *//* unreachable */
4664
4665 case 'D':
4666 if (0 == sl_strncmp (sh.data.path, preq, 15))
4667 {
4668 if (flag == 'R')
4669 SL_RETURN( preq, _("file_path"));
4670 if (flag == 'W' && sl_strlen(sh.data.path) == 15)
4671 SL_RETURN (NULL, _("file_path"));
4672 if (flag == 'W')
4673 SL_RETURN( &(sh.data.path[15]), _("file_path"));
4674 }
4675 else
4676 SL_RETURN( sh.data.path, _("file_path"));
4677 break;
4678
4679 default:
4680 SL_RETURN( NULL, _("file_path"));
4681 }
4682
4683 return NULL; /* notreached */
4684}
4685/************************************************/
4686/**** Mlock Utilities ****/
4687/************************************************/
4688
4689#include <limits.h>
4690
4691int sh_unix_pagesize()
4692{
4693 int pagesize = 4096;
4694#if defined(_SC_PAGESIZE)
4695 pagesize = sysconf(_SC_PAGESIZE);
4696#elif defined(_SC_PAGE_SIZE)
4697 pagesize = sysconf(_SC_PAGE_SIZE);
4698#elif defined(HAVE_GETPAGESIZE)
4699 pagesize = getpagesize();
4700#elif defined(PAGESIZE)
4701 pagesize = PAGESIZE;
4702#endif
4703
4704 return ((pagesize > 0) ? pagesize : 4096);
4705}
4706
4707typedef struct sh_page_lt {
4708 unsigned long page_start;
4709 int page_refcount;
4710 char file[64];
4711 int line;
4712 struct sh_page_lt * next;
4713} sh_page_l;
4714
4715sh_page_l * sh_page_locked = NULL;
4716volatile int page_locking = 0;
4717
4718unsigned long sh_unix_lookup_page (void * in_addr, size_t len, int * num_pages)
4719{
4720 int pagesize = sh_unix_pagesize();
4721 unsigned long addr = (unsigned long) in_addr;
4722
4723 unsigned long pagebase;
4724 unsigned long pagediff;
4725 unsigned long pagenum = addr / pagesize;
4726
4727 SL_ENTER(_("sh_unix_lookup_page"));
4728#if 0
4729 fprintf(stderr, "mlock: --> base %ld, pagenum: %ld\n",
4730 addr, pagenum);
4731#endif
4732
4733 /* address of first page
4734 */
4735 pagebase = pagenum * pagesize;
4736
4737 /* number of pages
4738 */
4739 pagediff = (addr + len) - pagebase;
4740 pagenum = pagediff / pagesize;
4741 if (pagenum * pagesize < pagediff)
4742 ++pagenum;
4743
4744#if 0
4745 fprintf(stderr, "mlock: --> pagebase %ld, pagediff %ld, (addr + len) %ld\n",
4746 pagebase, pagediff, (addr + len));
4747#endif
4748
4749 *num_pages = pagenum;
4750 SL_RETURN((pagebase), _("sh_unix_lookup_page"));
4751}
4752
4753
4754#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4755
4756SH_MUTEX_STATIC(mutex_mlock,PTHREAD_MUTEX_INITIALIZER);
4757
4758int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4759{
4760 int num_pages;
4761 int status = 0;
4762 int pagesize;
4763 sh_page_l * page_list;
4764 unsigned long addr;
4765#ifdef TEST_MLOCK
4766 int i = 0;
4767#endif
4768
4769 SL_ENTER(_("sh_unix_mlock"));
4770
4771 /* There's no cancellation point here, except if tracing is on
4772 */
4773 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4774
4775 page_list = sh_page_locked;
4776
4777 if (0 != page_locking)
4778 {
4779 status = -1;
4780 goto exit_mlock;
4781 }
4782
4783 page_locking = 1;
4784
4785 pagesize = sh_unix_pagesize();
4786 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4787
4788#ifdef TEST_MLOCK
4789 fprintf(stderr, "mlock: addr %ld, base %ld, pages: %d, length %d\n",
4790 (unsigned long) in_addr, addr, num_pages, len);
4791#endif
4792
4793 /* increase refcount of locked pages
4794 * addr is first page; num_pages is #(consecutive pages) to lock
4795 */
4796
4797 while ((page_list != NULL) && (num_pages > 0))
4798 {
4799#ifdef TEST_MLOCK
4800 fprintf(stderr, "mlock: check page %d: %ld [%d]\n",
4801 i, page_list->page_start, page_list->page_refcount);
4802#endif
4803 if (page_list->page_start == addr)
4804 {
4805 page_list->page_refcount += 1;
4806 num_pages -= 1;
4807 addr += pagesize;
4808#ifdef TEST_MLOCK
4809 fprintf(stderr, "mlock: found page %d: %ld [%d], next page %ld\n",
4810 i, page_list->page_start, page_list->page_refcount, addr);
4811#endif
4812 }
4813#ifdef TEST_MLOCK
4814 ++i;
4815#endif
4816 page_list = page_list->next;
4817 }
4818
4819 /* mlock some more pages, if needed
4820 */
4821 while (num_pages > 0)
4822 {
4823#ifdef TEST_MLOCK
4824 fprintf(stderr, "mlock: lock page %d: mlock %ld [num_pages %d]\n",
4825 i, addr, num_pages);
4826 ++i;
4827#endif
4828 page_list = SH_ALLOC(sizeof(sh_page_l));
4829 page_list->page_start = addr;
4830 page_list->page_refcount = 1;
4831 sl_strlcpy(page_list->file, file, 64);
4832 page_list->line = line;
4833 status = mlock( (void *) addr, pagesize);
4834 if (status != 0)
4835 {
4836#ifdef TEST_MLOCK
4837 char errbuf[SH_ERRBUF_SIZE];
4838 fprintf(stderr, "mlock: error: %s\n",
4839 sh_error_message(errno, errbuf, sizeof(errbuf)));
4840#endif
4841 SH_FREE(page_list);
4842 page_locking = 0;
4843 goto exit_mlock;
4844 }
4845 page_list->next = sh_page_locked;
4846 sh_page_locked = page_list;
4847 num_pages -= 1;
4848 addr += pagesize;
4849 }
4850 page_locking = 0;
4851
4852 exit_mlock:
4853 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
4854
4855 SL_RETURN((status), _("sh_unix_mlock"));
4856}
4857#else
4858int sh_unix_mlock (const char * file, int line, void * in_addr, size_t len)
4859{
4860 (void) file; (void) line;
4861 (void) in_addr; (void) len;
4862 return -1;
4863}
4864#endif
4865
4866#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
4867int sh_unix_munlock (void * in_addr, size_t len)
4868{
4869 int num_pages;
4870 int unlocked;
4871 int status;
4872 int pagesize;
4873 sh_page_l * page_list;
4874 sh_page_l * page_last;
4875 unsigned long addr;
4876
4877 int test_count;
4878 int test_status;
4879 int test_pages;
4880
4881#ifdef TEST_MLOCK
4882 int i = 0;
4883#endif
4884
4885 SL_ENTER(_("sh_unix_munlock"));
4886
4887 /* There's no cancellation point here, except if tracing is on
4888 */
4889 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
4890
4891 unlocked = 0;
4892 status = 0;
4893 page_list = sh_page_locked;
4894
4895 if (0 != page_locking)
4896 {
4897 status = -1;
4898 goto exit_munlock;
4899 }
4900 page_locking = 1;
4901
4902 pagesize = sh_unix_pagesize();
4903 addr = sh_unix_lookup_page (in_addr, len, &num_pages);
4904
4905#ifdef TEST_MLOCK
4906 fprintf(stderr, "munlock: in_addr %ld, addr %ld, pages: %d, length %d\n",
4907 (unsigned long) in_addr, addr, num_pages, len);
4908#endif
4909
4910 test_pages = num_pages;
4911
4912 /* reduce refcount of locked pages
4913 * addr is first page; num_pages is #(consecutive pages) to lock
4914 */
4915 while ((page_list != NULL) && (num_pages > 0))
4916 {
4917#ifdef TEST_MLOCK
4918 fprintf(stderr, "munlock: page %d: %ld [%d]\n",
4919 i, page_list->page_start, page_list->page_refcount);
4920#endif
4921
4922 test_status = 0;
4923 for (test_count = 0; test_count < test_pages; ++test_count)
4924 {
4925 if (page_list->page_start == (addr + (test_count * pagesize)))
4926 {
4927 test_status = 1;
4928 break;
4929 }
4930 }
4931
4932 if (test_status == 1)
4933 {
4934 page_list->page_refcount -= 1;
4935 if (page_list->page_refcount == 0)
4936 {
4937 status = munlock ( (void *) addr, pagesize);
4938 ++unlocked;
4939 }
4940 num_pages -= 1;
4941#ifdef TEST_MLOCK
4942 fprintf(stderr,
4943 "munlock: page %d: %ld [refcount %d], refcount reduced\n",
4944 i, page_list->page_start, page_list->page_refcount);
4945#endif
4946 }
4947#ifdef TEST_MLOCK
4948 ++i;
4949#endif
4950 page_list = page_list->next;
4951 }
4952
4953#ifdef TEST_MLOCK
4954 i = 0;
4955#endif
4956
4957 if (unlocked > 0)
4958 {
4959 page_list = sh_page_locked;
4960 page_last = sh_page_locked;
4961
4962 while ((page_list != NULL) && (unlocked > 0))
4963 {
4964 if (page_list->page_refcount == 0)
4965 {
4966#ifdef TEST_MLOCK
4967 fprintf(stderr, "munlock: remove page %d: %ld [refcount %d]\n",
4968 i, page_list->page_start, page_list->page_refcount);
4969#endif
4970 if (page_last != page_list)
4971 {
4972 page_last->next = page_list->next;
4973 SH_FREE(page_list);
4974 page_list = page_last->next;
4975 }
4976 else
4977 {
4978 page_last = page_list->next;
4979 if (page_list == sh_page_locked)
4980 sh_page_locked = page_list->next;
4981 SH_FREE(page_list);
4982 page_list = page_last;
4983 }
4984 --unlocked;
4985 }
4986 else
4987 {
4988#ifdef TEST_MLOCK
4989 fprintf(stderr, "munlock: skip page %d: %ld [refcount %d]\n",
4990 i, page_list->page_start, page_list->page_refcount);
4991#endif
4992
4993 page_last = page_list;
4994 page_list = page_list->next;
4995 }
4996#ifdef TEST_MLOCK
4997 ++i;
4998#endif
4999 }
5000 }
5001
5002 page_locking = 0;
5003
5004 exit_munlock:
5005 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5006 SL_RETURN((status), _("sh_unix_munlock"));
5007}
5008#else
5009int sh_unix_munlock (void * in_addr, size_t len)
5010{
5011 (void) in_addr; (void) len;
5012 return -1;
5013}
5014#endif
5015
5016int sh_unix_count_mlock()
5017{
5018 int i = 0;
5019 char str[32][64];
5020 sh_page_l * page_list;
5021
5022 SL_ENTER(_("sh_unix_count_mlock"));
5023
5024#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5025 /* There's no cancellation point here, except if tracing is on
5026 */
5027 SH_MUTEX_LOCK_UNSAFE(mutex_mlock);
5028#endif
5029
5030 page_list = sh_page_locked;
5031
5032 while (page_list != NULL)
5033 {
5034#ifdef WITH_TPT
5035 if (i < 32)
5036 sl_snprintf(str[i], 64, _("file: %s line: %d page: %d"),
5037 page_list->file, page_list->line, i+1);
5038#endif
5039 page_list = page_list->next;
5040 ++i;
5041 }
5042
5043#if defined(HAVE_MLOCK) && !defined(HAVE_BROKEN_MLOCK)
5044 SH_MUTEX_UNLOCK_UNSAFE(mutex_mlock);
5045#endif
5046
5047#ifdef WITH_TPT
5048 {
5049 int j = 0;
5050 while (j < i && j < 32)
5051 {
5052 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, j, MSG_E_SUBGEN,
5053 str[j], _("sh_unix_count_mlock"));
5054 ++j;
5055 }
5056 }
5057#endif
5058
5059 sl_snprintf(str[0], 64, _("%d pages locked"), i);
5060 sh_error_handle(SH_ERR_INFO, FIL__, __LINE__, i, MSG_E_SUBGEN,
5061 str[0], _("sh_unix_count_mlock"));
5062 SL_RETURN((i), _("sh_unix_count_mlock"));
5063}
5064
5065/************************************************/
5066/************************************************/
5067/**** Stealth Utilities ****/
5068/************************************************/
5069/************************************************/
5070#ifdef SH_STEALTH
5071
5072void sh_unix_xor_code (char * str, int len)
5073{
5074 register int i;
5075
5076 for (i = 0; i < len; ++i) str[i] ^= (char) XOR_CODE;
5077 return;
5078}
5079
5080#if !defined(SH_STEALTH_MICRO)
5081
5082
5083int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5084 unsigned long * bytes_read);
5085unsigned long first_hex_block(SL_TICKET fd, unsigned long * max);
5086
5087/*
5088 * --- Get hidden data from a block of hex data. ---
5089 */
5090int sh_unix_getline_stealth (SL_TICKET fd, char * str, int len)
5091{
5092 int add_off = 0, llen;
5093 static unsigned long off_data = 0;
5094 static unsigned long max_data = 0;
5095 static unsigned long bytes_read = 0;
5096 static int stealth_init = BAD;
5097
5098 SL_ENTER(_("sh_unix_getline_stealth"));
5099
5100 if (str == NULL)
5101 {
5102 off_data = 0;
5103 max_data = 0;
5104 bytes_read = 0;
5105 stealth_init = BAD;
5106 SL_RETURN(0, _("sh_unix_getline_stealth"));
5107 }
5108
5109 /* --- Initialize. ---
5110 */
5111 if (stealth_init == BAD)
5112 {
5113 off_data = first_hex_block(fd, &max_data);
5114 if (off_data == 0)
5115 {
5116 dlog(1, FIL__, __LINE__,
5117 _("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"));
5118 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5119 _("Stealth config file."));
5120 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5121 }
5122 stealth_init = GOOD;
5123 max_data += off_data;
5124 }
5125
5126 /* --- Seek to proper position. ---
5127 */
5128 if (bytes_read >= max_data || add_off < 0)
5129 {
5130 dlog(1, FIL__, __LINE__,
5131 _("The capacity of the container image file for the stealth config file seems to be too small. Your config file is likely truncated.\n"));
5132 sh_error_handle ((-1), FIL__, __LINE__, EIO, MSG_P_NODATA,
5133 _("Stealth config file."));
5134 aud_exit (FIL__, __LINE__, EXIT_FAILURE);
5135 }
5136 sl_seek(fd, off_data);
5137
5138 /* --- Read one line. ---
5139 */
5140 add_off = hideout_hex_block(fd, (unsigned char *) str, len, &bytes_read);
5141 off_data += add_off;
5142
5143 llen = sl_strlen(str);
5144 SL_RETURN(llen, _("sh_unix_getline_stealth"));
5145}
5146
5147int hideout_hex_block(SL_TICKET fd, unsigned char * str, int len,
5148 unsigned long * bytes_read)
5149{
5150
5151 register int i, j, k;
5152 unsigned char c, e;
5153 register int num;
5154 unsigned char mask[9] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
5155 unsigned long here = 0;
5156 unsigned long retval = 0;
5157 unsigned long bread = 0;
5158
5159 SL_ENTER(_("hideout_hex_block"));
5160
5161 ASSERT_RET((len > 1), _("len > 1"), (0));
5162
5163 --len;
5164
5165 i = 0;
5166 while (i < len)
5167 {
5168 for (j = 0; j < 8; ++j)
5169 {
5170
5171 /* --- Get a low byte, modify, read back. ---
5172 */
5173 for (k = 0; k < 2; ++k)
5174 {
5175 /* -- Skip whitespace. ---
5176 */
5177 c = ' ';
5178 do {
5179 do {
5180 num = sl_read (fd, &c, 1);
5181 } while (num == 0 && errno == EINTR);
5182 if (num > 0)
5183 ++here;
5184 else if (num == 0)
5185 SL_RETURN((0), _("hideout_hex_block"));
5186 else
5187 SL_RETURN((-1), _("hideout_hex_block"));
5188 } while (c == '\n' || c == '\t' || c == '\r' ||
5189 c == ' ');
5190 }
5191
5192
5193 /* --- e is the value of the low byte. ---
5194 */
5195 e = (unsigned char) sh_util_hexchar( c );
5196 if ((e & mask[7]) != 0) /* bit is set */
5197 str[i] |= mask[j];
5198 else /* bit is not set */
5199 str[i] &= ~mask[j];
5200
5201 bread += 1;
5202 }
5203 if (str[i] == '\n') break;
5204 ++i;
5205 }
5206
5207 if (i != 0)
5208 str[i] = '\0';
5209 else
5210 str[i+1] = '\0'; /* keep newline and terminate */
5211 retval += here;
5212 *bytes_read += (bread/8);
5213
5214 SL_RETURN(retval, _("hideout_hex_block"));
5215}
5216
5217/* --- Get offset of first data block. ---
5218 */
5219unsigned long first_hex_block(SL_TICKET fd, unsigned long * max)
5220{
5221 unsigned int i;
5222 long num = 1;
5223 unsigned long lnum;
5224 char c;
5225 int nothex = 0;
5226 unsigned long retval = 0;
5227 unsigned int this_line = 0;
5228 char theline[SH_BUFSIZE];
5229
5230 SL_ENTER(_("first_hex_block"));
5231
5232 *max = 0;
5233
5234 while (1)
5235 {
5236 theline[0] = '\0';
5237 this_line = 0;
5238 c = '\0';
5239 while (c != '\n' && num > 0 && this_line < (sizeof(theline)-1))
5240 {
5241 do {
5242 num = sl_read (fd, &c, 1);
5243 } while (num == 0 && errno == EINTR);
5244 if (num > 0)
5245 theline[this_line] = c;
5246 else
5247 SL_RETURN((0), _("first_hex_block"));
5248 ++this_line;
5249 }
5250 theline[this_line] = '\0';
5251
5252 /* not only 'newline' */
5253 if (this_line > 60)
5254 {
5255 nothex = 0;
5256 i = 0;
5257 while (nothex == 0 && i < (this_line-1))
5258 {
5259 if (! isxdigit((int)theline[i])) nothex = 1;
5260 ++i;
5261 }
5262 if (nothex == 1) retval += this_line;
5263 }
5264 else
5265 {
5266 nothex = 1;
5267 retval += this_line;
5268 }
5269
5270 if (nothex == 0)
5271 {
5272 *max = 0;
5273 do {
5274 do {
5275 num = sl_read (fd, theline, SH_BUFSIZE);
5276 } while (num == 0 && errno == EINTR);
5277 if (num > 0)
5278 {
5279 lnum = (unsigned long) num;
5280 for (i = 0; i < lnum; ++i)
5281 {
5282 c = theline[i];
5283 if (c == '\n' || c == '\t' || c == '\r' || c == ' ')
5284 ;
5285 else if (!isxdigit((int)c))
5286 break;
5287 else
5288 *max += 1;
5289 }
5290 }
5291 } while (num > 0);
5292
5293 *max /= 16;
5294 SL_RETURN((retval), _("first_hex_block"));
5295 }
5296
5297 }
5298 /* SL_RETURN((0), _("first_hex_block")); *//* unreachable */
5299}
5300
5301 /* if !defined(SH_STEALTH_MICRO) */
5302#endif
5303
5304 /* ifdef SH_STEALTH */
5305#endif
5306
5307/*
5308 * anti-debugger code
5309 */
5310#if defined(SCREW_IT_UP)
5311volatile int sh_not_traced = 0;
5312
5313#ifdef HAVE_GETTIMEOFDAY
5314struct timeval save_tv;
5315#endif
5316
5317void sh_sigtrap_handler (int signum)
5318{
5319#ifdef HAVE_GETTIMEOFDAY
5320 struct timeval tv;
5321 long difftv;
5322
5323 gettimeofday(&tv, NULL);
5324 difftv = (tv.tv_sec - save_tv.tv_sec) * 1000000 +
5325 (tv.tv_usec - save_tv.tv_usec);
5326 if (difftv > 500000)
5327 raise(SIGKILL);
5328#endif
5329 sh_not_traced += signum;
5330 return;
5331}
5332#endif
Note: See TracBrowser for help on using the repository browser.