shadow/lib/run_part.c
Serge Hallyn 2b22a6909d libsubid: don't print error messages on stderr by default
Closes #325

Add a new subid_init() function which can be used to specify the
stream on which error messages should be printed.  (If you want to
get fancy you can redirect that to memory :)  If subid_init() is
not called, use stderr.  If NULL is passed, then /dev/null will
be used.

This patch also fixes up the 'Prog', which previously had to be
defined by any program linking against libsubid.  Now, by default
in libsubid it will show (subid).  Once subid_init() is called,
it will use the first variable passed to subid_init().

Signed-off-by: Serge Hallyn <serge@hallyn.com>
2021-05-15 12:38:55 -05:00

103 lines
1.8 KiB
C

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <lib/prototypes.h>
int run_part (char *script_path, char *name, char *action)
{
int pid;
int wait_status;
int pid_status;
char *args[] = { script_path, NULL };
pid=fork();
if (pid==-1){
perror ("Could not fork");
return 1;
}
if (pid==0) {
setenv ("ACTION",action,1);
setenv ("SUBJECT",name,1);
execv (script_path,args);
perror ("execv");
exit(1);
}
pid_status = wait (&wait_status);
if (pid_status == pid) {
return (wait_status);
}
perror ("waitpid");
return (1);
}
int run_parts (char *directory, char *name, char *action)
{
struct dirent **namelist;
int scanlist;
int n;
int execute_result;
scanlist = scandir (directory, &namelist, 0, alphasort);
if (scanlist<0) {
return (0);
}
for (n=0; n<scanlist; n++) {
int path_length;
struct stat sb;
path_length=strlen(directory) + strlen(namelist[n]->d_name) + 2;
char *s = (char*)malloc(path_length);
if (!s) {
printf ("could not allocate memory\n");
for (; n<scanlist; n++) {
free (namelist[n]);
}
free (namelist);
return (1);
}
snprintf (s, path_length, "%s/%s", directory, namelist[n]->d_name);
execute_result = 0;
if (stat (s, &sb) == -1) {
perror ("stat");
free (s);
for (; n<scanlist; n++) {
free (namelist[n]);
}
free (namelist);
return (1);
}
if (S_ISREG (sb.st_mode) || S_ISLNK (sb.st_mode)) {
execute_result = run_part (s, name, action);
}
free (s);
if (execute_result!=0) {
fprintf (shadow_logfd,
"%s: did not exit cleanly.\n",
namelist[n]->d_name);
for (; n<scanlist; n++) {
free (namelist[n]);
}
break;
}
free (namelist[n]);
}
free (namelist);
return (execute_result);
}