#include <stdio.h>
#include <libmawk.h>
/*
Purpose: manipulate or deny opening specific files and commands
Run: ./app -f test.awk
*/
/* called any time the script wants to open a new file or command
(print redirection or getline);
return:
- orig_name of OK as is
- buff after filling in a new file name or command there
- another string const (won't be freed)
- NULL to deny opening the file/running the command */
const char *fn_rewrite(const char *orig_name, char *buff, int buff_size, int type)
{
switch (type) {
case F_IN:
/* wants to read - allow any read-only op */
return orig_name;
case F_TRUNC:
case F_APPEND:
/* wants to write a file - redirect to out.txt */
return "out.txt";
case PIPE_OUT:
case PIPE_IN:
{
static const char *wrapper = "echo '%s'"; /* unsafe: %s may contain '. */
/* run command - rewrite to use echo instead */
if (sizeof(orig_name) > buff_size - strlen(wrapper) - 2)
return NULL; /* too long, we can't easily wrap, deny */
sprintf(buff, wrapper, orig_name);
return buff;
}
default:
/* ...if the API changes in the future: deny! */
return NULL;
}
}
int main(int argc, char **argv)
{
mawk_state_t *m;
/* init a context in stages */
m = libmawk_initialize_stage1(); /* alloc context */
libmawk_initialize_stdio(m, 1, 1, 1);
m->file_name_rewrite = fn_rewrite; /* hook file name for rewriting */
m = libmawk_initialize_stage2(m, argc, argv); /* set up with no arguments */
m = libmawk_initialize_stage3(m); /* execute BEGIN */
if (m == NULL) {
fprintf(stderr, "libmawk_initialize failed, exiting\n");
return 1;
}
/* run END and free the context */
libmawk_uninitialize(m);
return 0;
}