|
|
@@ -1,20 +1,71 @@
|
|
|
+#include "sandbox.h"
|
|
|
#include <sys/stat.h>
|
|
|
#include <stdlib.h>
|
|
|
#include <string.h>
|
|
|
#include <stdio.h>
|
|
|
#include <errno.h>
|
|
|
#include <time.h>
|
|
|
-#include "sandbox.h"
|
|
|
|
|
|
-int init_env(t_param *params)
|
|
|
+static char *check_file(const char *fname)
|
|
|
{
|
|
|
- char * path = params->tmppath = (char *) malloc(sizeof(*path) * (strlen(params->tmpdir) + 24));
|
|
|
+ const char *pos;
|
|
|
+ char *path = getenv("PATH");
|
|
|
+ char *dir;
|
|
|
+ char *fullpath = NULL;
|
|
|
+ int fullpath_len;
|
|
|
+ struct stat cmd_stat;
|
|
|
+
|
|
|
+ for (pos = fname; *pos && *pos != '/'; ++pos);
|
|
|
+ if (*pos && (stat(fname, &cmd_stat) == -1))
|
|
|
+ {
|
|
|
+ fprintf(stderr, "Cannot stat %s: %s\n", fname, strerror(errno));
|
|
|
+ return NULL;
|
|
|
+ }
|
|
|
+ else if (!*pos && !path)
|
|
|
+ {
|
|
|
+ fprintf(stderr, "Cannot stat %s: No such file or directory\n", fname);
|
|
|
+ return NULL;
|
|
|
+ }
|
|
|
+ if (!*pos)
|
|
|
+ for ((dir = strtok(path, ":")); dir; dir = strtok(NULL, ":"))
|
|
|
+ {
|
|
|
+ int len = strlen(dir);
|
|
|
+ if (fullpath == NULL || fullpath_len < len)
|
|
|
+ {
|
|
|
+ if (fullpath)
|
|
|
+ fullpath = realloc(fullpath, sizeof(*fullpath) * (strlen(fname) + 2 + len));
|
|
|
+ else
|
|
|
+ fullpath = malloc(sizeof(*fullpath) * (strlen(fname) + len +2));
|
|
|
+ fullpath_len = len;
|
|
|
+ }
|
|
|
+ sprintf(fullpath, "%s/%s", dir, fname);
|
|
|
+ if (stat(fullpath, &cmd_stat) != -1 && !S_ISDIR(cmd_stat.st_mode))
|
|
|
+ return fullpath;
|
|
|
+ }
|
|
|
+ if (S_ISDIR(cmd_stat.st_mode))
|
|
|
+ {
|
|
|
+ fprintf(stderr, "Cannot execute %s: is a directory\n", fname);
|
|
|
+ return NULL;
|
|
|
+ }
|
|
|
+ if (!fullpath && *pos)
|
|
|
+ fullpath = strdup(fname);
|
|
|
+ else if (!*pos)
|
|
|
+ {
|
|
|
+ free(fullpath);
|
|
|
+ fprintf(stderr, "Cannot execute %s: command not found\n", fname);
|
|
|
+ fullpath = NULL;
|
|
|
+ }
|
|
|
+ return fullpath;
|
|
|
+}
|
|
|
|
|
|
- /* TODO check if prog name exists */
|
|
|
- sprintf(path, "%s/sandbox_%ld:%d", params->tmpdir, time(NULL), getpid());
|
|
|
- if (mkdir(path, 0) == -1)
|
|
|
+int init_env(t_param *params)
|
|
|
+{
|
|
|
+ if ((params->cmdpath = check_file(params->cmd[0])) == NULL)
|
|
|
+ return -1;
|
|
|
+ asprintf(&(params->tmppath), "%s/sandbox_%ld:%d", params->tmpdir, time(NULL), getpid());
|
|
|
+ if (mkdir(params->tmppath, 0) == -1)
|
|
|
{
|
|
|
- fprintf(stderr, "Cannot create directory %s: %s\n", path, strerror(errno));
|
|
|
+ fprintf(stderr, "Cannot create directory %s: %s\n", params->tmppath, strerror(errno));
|
|
|
return -1;
|
|
|
}
|
|
|
return 0;
|
|
|
@@ -25,6 +76,7 @@ void release_env(t_param *params)
|
|
|
rmdir(params->tmppath);
|
|
|
|
|
|
free(params->tmppath);
|
|
|
+ free(params->cmdpath);
|
|
|
free(params);
|
|
|
}
|
|
|
|