Example #1
0
int Gmkdir(const char *path, bool recursive, int perms) {
	if (path==NULL || path[0]==0) return -1;
	mode_t process_mask = umask(0); //is this really needed?
	if (!recursive) {
	   int r=G_mkdir(path, perms);
	   if (r!=0) 
	      GMessage("Warning: G_mkdir(%s) failed: %s\n", path, strerror(errno));
	   umask(process_mask);
	   return r;
	   }
	int plen=strlen(path);
	char* gpath=NULL;
	//make sure gpath ends with /
	if (path[plen-1]=='/') {
		gpath=Gstrdup(path);
	}
	else {
		GMALLOC(gpath, plen+2);
		strcpy(gpath,path);
		strcat(gpath, "/");
		++plen;
	}
	//char* ss=gpath+plen-1;
	char* psep = gpath+plen-1; //start at the last /
	GDynArray<char*> dirstack(4); // stack of directories that should be created
	while (psep>gpath && *(psep-1)=='/') --psep; //skip double slashes
    *psep='\0';
    int fexists=0;
	while ((fexists=fileExists(gpath))==0) {
      dirstack.Push(psep);
      do { --psep; } while (psep>gpath && *psep!='/');
      if (psep<=gpath) { psep=NULL; break; }
      while (psep>gpath && *(psep-1)=='/') --psep;
      *psep='\0';
	}
	if (psep) *psep='/';
	while (dirstack.Count()>0) {
		psep=dirstack.Pop();
		int mkdir_err=0;
		if ((mkdir_err=G_mkdir(gpath, perms))!=0) {
				GMessage("Warning: mkdir(%s) failed: %s\n", gpath, strerror(errno));
			GFREE(gpath);
			umask(process_mask);
			return -1;
		}
		*psep='/';
	}
	GFREE(gpath);
	umask(process_mask);
	return 0;
}
Example #2
0
int G__make_location(const char *location_name,
		     struct Cell_head *wind,
		     struct Key_Value *proj_info,
		     struct Key_Value *proj_units, FILE * report_file)
{
    char path[GPATH_MAX];
    int out_stat;

    /* Try to create the location directory, under the gisdbase. */
    sprintf(path, "%s/%s", G_gisdbase(), location_name);
    if (G_mkdir(path) != 0)
	return -1;

    /* Make the PERMANENT mapset. */
    sprintf(path, "%s/%s/%s", G_gisdbase(), location_name, "PERMANENT");
    if (G_mkdir(path) != 0)
	return -1;

    /* make these the new current location and mapset */
    G__setenv("LOCATION_NAME", location_name);
    G__setenv("MAPSET", "PERMANENT");

    /* Create the default, and current window files */
    G__put_window(wind, "", "DEFAULT_WIND");
    G__put_window(wind, "", "WIND");

    /* Write out the PROJ_INFO, and PROJ_UNITS if available. */
    if (proj_info != NULL) {
	G__file_name(path, "", "PROJ_INFO", "PERMANENT");
	G_write_key_value_file(path, proj_info, &out_stat);
	if (out_stat != 0)
	    return -2;
    }

    if (proj_units != NULL) {
	G__file_name(path, "", "PROJ_UNITS", "PERMANENT");
	G_write_key_value_file(path, proj_units, &out_stat);
	if (out_stat != 0)
	    return -2;
    }

    return 0;
}
Example #3
0
/* SETUP THE R.LE.PARA DIRECTORY */
static void get_pwd(void)
{
    DIR *dp;

    if (!(dp = opendir("r.le.para")))
	G_mkdir("r.le.para");
    else
	closedir(dp);
    return;

}
Example #4
0
/*!
 * \brief Get user's .grass/ config path directory
 *
 * Returns a pointer to a string which is the full path name of the
 * user's .grass/ config directory in their home directory.
 *
 * The path is not guaranteed to exist.
(should it be?  see possible TODO below)
 *
 * \return pointer to string
 * \return NULL on error
 */
const char *G_rc_path(void)
{
/* choose better name for fn? */
/* HB: making a complete bollocks of this, but to express the idea... */
    const char *rcpath = 0;

    sprintf(rcpath, "%s%c%s", G_home(), HOST_DIRSEP, RCDIR);

#ifdef POSSIBILITY
    /* create it if it doesn't exist */
#include <errno.h>
    int ret;
    ret = G_mkdir(rcpath);
    if (ret == -1 && errno != EEXIST)
	G_fatal_error(_("Failed to create directory [%s]"), rcpath);
#endif

    return G_store(rcpath);
}
Example #5
0
static char *_get_make_sock_path(void)
{
    char *path, *user, *lock;
    const char *prefix = "/tmp/grass6";
    int len, status;
    struct stat theStat;

    user = G_whoami();		/* Don't G_free () return value ever! */
    if (user == NULL)
	return NULL;
    else if (user[0] == '?') {	/* why's it do that? */
	return NULL;
    }

    if ((lock = getenv("GIS_LOCK")) == NULL)
	G_fatal_error(_("Unable to get GIS_LOCK environment variable value"));

    len = strlen(prefix) + strlen(user) + strlen(lock) + 3;
    path = G_malloc(len);

    sprintf(path, "%s-%s-%s", prefix, user, lock);

    if ((status = G_lstat(path, &theStat)) != 0) {
	status = G_mkdir(path);
    }
    else {
	if (!S_ISDIR(theStat.st_mode)) {
	    status = -1;	/* not a directory ?? */
	}
	else {
	    status = chmod(path, S_IRWXU);	/* fails if we don't own it */
	}
    }

    if (status) {		/* something's wrong if non-zero */
	G_free(path);
	path = NULL;
    }

    return path;
}
Example #6
0
int G__make_mapset(const char *gisdbase_name, const char *location_name,
		   const char *mapset_name)
{
    char path[GPATH_MAX];
    struct Cell_head default_window;

    /* Get location */
    if (location_name == NULL)
	location_name = G_location();

    /* Get GISDBASE */
    if (gisdbase_name == NULL)
	gisdbase_name = G_gisdbase();

    /* TODO: Should probably check that user specified location and gisdbase are valid */

    /* Make the mapset. */
    sprintf(path, "%s/%s/%s", gisdbase_name, location_name, mapset_name);
    if (G_mkdir(path) != 0)
	return -1;

    G__create_alt_env();

    /* Get PERMANENT default window */
    G__setenv("GISDBASE", gisdbase_name);
    G__setenv("LOCATION", location_name);
    G__setenv("MAPSET", "PERMANENT");
    G_get_default_window(&default_window);

    /* Change to the new mapset */
    G__setenv("MAPSET", mapset_name);

    /* Copy default window/regions to new mapset */
    G__put_window(&default_window, "", "WIND");

    /* And switch back to original environment */
    G__switch_env();

    return 0;
}
Example #7
0
/*!
   \brief Create element in the current mapset.

   Make the specified element in the current mapset
   will check for the existence of the element and
   do nothing if it is found so this routine
   can be called even if the element already exists.

   \param element element to be created in mapset

   \return 0 ?
   \return ?
 */
int G__make_mapset_element(const char *p_element)
{
    char path[GPATH_MAX];
    char *p;
    const char *element;

    element = p_element;
    if (*element == 0)
        return 0;

    G_file_name(p = path, NULL, NULL, G_mapset());
    while (*p)
        p++;
    /* add trailing slash if missing */
    --p;
    if (*p++ != '/') {
        *p++ = '/';
        *p = 0;
    }

    /* now append element, one directory at a time, to path */
    while (1) {
        if (*element == '/' || *element == 0) {
            *p = 0;
            if (access(path, 0) != 0) { /* directory not yet created */
                if (G_mkdir(path) != 0)
                    G_fatal_error(_("Unable to make mapset element %s (%s): %s"),
                                  p_element, path, strerror(errno));
            }
            if (access(path, 0) != 0)  /* directory not accessible */
                G_fatal_error(_("Unable to access mapset element %s (%s): %s"),
                              p_element, path, strerror(errno));
            if (*element == 0)
                return 1;
        }
        *p++ = *element++;
    }
}
Example #8
0
/**************************************************************************
 * _make_toplevel(): make user's toplevel config directory if it doesn't
 * already exist.  Adjust perms to 1700. Returns the toplevel directory
 * path [caller must G_free ()] on success, or NULL on failure
 *************************************************************************/

#ifndef __MINGW32__		/* TODO */
static char *_make_toplevel(void)
{
    size_t len;
    int status;

#ifdef __MINGW32__
    char *defaulthomedir = "c:";
    char *homedir = getenv("HOME");
#else
    uid_t me;
    struct passwd *my_passwd;
#endif
    struct stat buf;
    char *path;

    errno = 0;

    /* Query whatever database to get user's home dir */
#ifdef __MINGW32__
    if (NULL == homedir) {
	homedir = defaulthomedir;
    }

    len = strlen(homedir) + 8;	/* + "/.grass\0" */
    if (NULL == (path = G_calloc(1, len))) {
	return NULL;
    }
    sprintf(path, "%s%s", homedir, "/.grass");
#else
    me = getuid();
    my_passwd = getpwuid(me);
    if (my_passwd == NULL)
	return NULL;

    len = strlen(my_passwd->pw_dir) + 8;	/* + "/.grass\0" */
    if (NULL == (path = G_calloc(1, len)))
	return NULL;

    sprintf(path, "%s%s", my_passwd->pw_dir, "/.grass");
#endif

    status = G_lstat(path, &buf);

    /* If errno == ENOENT, the directory doesn't exist */
    if (status != 0) {
	if (errno == ENOENT) {
	    status = G_mkdir(path);

	    if (status != 0) {	/* mkdir failed */
		G_free(path);
		return NULL;
	    }

	    /* override umask settings, if possible */
	    chmod(path, S_IRWXU);

	    /* otherwise mkdir succeeded, we're done here */
	    return path;
	}

	/* other errors should not be defined ??? give up */
	G_free(path);
	return NULL;
    }
    /* implicit else */

    /* Examine the stat "buf" */
    /* It better be a directory */
    if (!S_ISDIR(buf.st_mode)) {	/* File, link, something else */
	errno = ENOTDIR;	/* element is not a directory, but should be */
	G_free(path);
	return NULL;
    }

    /* No read/write/execute ??? */
    if (!((S_IRUSR & buf.st_mode) &&
	  (S_IWUSR & buf.st_mode) && (S_IXUSR & buf.st_mode)
	)
	) {
	errno = EACCES;		/* Permissions error */
	G_free(path);
	return NULL;
    }

    /* We'll assume that if the user grants greater permissions
     * than we would, that they know what they're doing
     * -- so we're done here...
     */

    return path;
}
Example #9
0
/**************************************************************************
 * _make_sublevels(): creates subelements as necessary from the passed
 * "elems" string.  It returns the full path if successful or NULL
 * if it fails.  "elems" must not be NULL, zero length, or have any
 * elements that begin with a '.' or any occurrences of '//'.
 *************************************************************************/
static char *_make_sublevels(const char *elems)
{
    int i, status;
    char *cp, *path, *top, *ptr;
    struct stat buf;

    /* Get top level path */
    if (NULL == (top = _make_toplevel()))
	return NULL;

    /* Make a copy of elems */
    if (NULL == (cp = G_store(elems))) {
	G_free(top);
	return NULL;
    }

    /* Do element count, sanity checking and "splitting" */
    if ((i = _elem_count_split(cp)) < 1) {
	G_free(cp);
	G_free(top);
	return NULL;
    }

    /* Allocate our path to be large enough */
    if ((path = G_calloc(1, strlen(top) + strlen(elems) + 2)) == NULL) {
	G_free(top);
	G_free(cp);
	return NULL;
    }

    /* Now loop along adding directories if they don't exist
     * make sure the thing is a directory as well.
     * If there was a trailing '/' in the original "elem", it doesn't
     * make it into the returned path.
     */
    for (; i > 0; i--) {
	sprintf(path, "%s/%s", top, cp);
	errno = 0;
	status = G_lstat(path, &buf);
	if (status != 0) {
	    /* the element doesn't exist */
	    status = G_mkdir(path);
	    if (status != 0) {
		/* Some kind of problem... */
		G_free(top);
		G_free(cp);
		return NULL;
	    }
	    /* override umask settings, if possible */
	    chmod(path, S_IRWXU);
	}
	else {
	    /* Examine the stat "buf" */
	    /* It better be a directory */
	    if (!S_ISDIR(buf.st_mode)) {	/* File, link, something else */
		errno = ENOTDIR;	/* element is not a directory, but should be */
		G_free(path);
		return NULL;
	    }

	    /* No read/write/execute ??? */
	    if (!((S_IRUSR & buf.st_mode) &&
		  (S_IWUSR & buf.st_mode) && (S_IXUSR & buf.st_mode)
		)
		) {
		errno = EACCES;	/* Permissions error */
		G_free(path);
		return NULL;
	    }

	    /* okay continue ... */
	}

	ptr = strchr(cp, '\0');
	*ptr = '/';
    }

    /* All done, free memory */
    G_free(top);
    G_free(cp);

    return path;
}
Example #10
0
int G_recursive_copy(const char *src, const char *dst)
{
    DIR *dirp;
    struct stat sb;

    if (G_lstat(src, &sb) < 0)
	return 1;

    /* src is a file */
    if (!S_ISDIR(sb.st_mode)) {
	char buf[4096];
	int fd, fd2;
	size_t len, len2;

	if (G_lstat(dst, &sb) == 0 && S_ISDIR(sb.st_mode)) {
	    char path[GPATH_MAX];
	    const char *p = strrchr(src, '/');

	    /* src => dst/src */
	    sprintf(path, "%s/%s", dst, (p ? p + 1 : src));
	    return G_recursive_copy(src, path);
	}

	/* src => dst */
	if ((fd = open(src, O_RDONLY)) < 0)
	    return 1;

	if ((fd2 =
	     open(dst, O_CREAT | O_TRUNC | O_WRONLY,
		  sb.st_mode & 0777)) < 0) {
	    close(fd);
	    return 1;
	}

	while ((len = read(fd, buf, sizeof(buf))) > 0) {
	    while (len && (len2 = write(fd2, buf, len)) >= 0)
		len -= len2;
	}

	close(fd);
	close(fd2);

	return 0;
    }

    /* src is a directory */
    if (G_lstat(dst, &sb) < 0) {
	if (G_mkdir(dst))
	    return 1;
    }
    else
	/* if dst already exists and it's a file, try to remove it */
    if (!S_ISDIR(sb.st_mode)) {
	if (remove(dst) < 0 || G_mkdir(dst) < 0)
	    return 1;
    }

    dirp = opendir(src);
    if (!dirp)
	return 1;

    for (;;) {
	char path[GPATH_MAX], path2[GPATH_MAX];
	struct dirent *dp = readdir(dirp);

	if (!dp)
	    break;

	/* do not copy hidden files */
	if (dp->d_name[0] == '.')
	    continue;

	sprintf(path, "%s/%s", src, dp->d_name);
	sprintf(path2, "%s/%s", dst, dp->d_name);

	if (G_recursive_copy(path, path2) != 0)
	    return 1;
    }

    closedir(dirp);

    return 0;
}
Example #11
0
int db__driver_open_database(dbHandle * handle)
{
    const char *name;
    int len;
    dbConnection connection;
    char buf[1024];
    DIR *dir;
    struct dirent *ent;
    char **tokens;
    int no_tokens, n;

    G_debug(2, "DBF: db__driver_open_database() name = '%s'",
	    db_get_handle_dbname(handle));

    db.name[0] = '\0';
    db.tables = NULL;
    db.atables = 0;
    db.ntables = 0;

    db_get_connection(&connection);
    name = db_get_handle_dbname(handle);

    /* if name is empty use connection.databaseName */
    if (strlen(name) == 0) {
	name = connection.databaseName;
    }

    strcpy(db.name, name);

    /* open database dir and read table ( *.dbf files ) names 
     * to structure */

    /* parse variables in db.name if present */
    if (db.name[0] == '$') {
	tokens = G_tokenize(db.name, "/");
	no_tokens = G_number_of_tokens(tokens);
	db.name[0] = '\0';	/* re-init */

	for (n = 0; n < no_tokens; n++) {
	    G_debug(3, "tokens[%d] = %s", n, tokens[n]);
	    if (tokens[n][0] == '$') {
		G_strchg(tokens[n], '$', ' ');
		G_chop(tokens[n]);
		strcat(db.name, G__getenv(tokens[n]));
		G_debug(3, "   -> %s", G__getenv(tokens[n]));
	    }
	    else
		strcat(db.name, tokens[n]);

	    strcat(db.name, "/");
	}
	G_free_tokens(tokens);
    }

    G_debug(2, "db.name = %s", db.name);

    errno = 0;
    dir = opendir(db.name);
    if (dir == NULL) {
	if (errno == ENOENT) {
	    int status;

	    status = G_mkdir(db.name);
	    if (status != 0) {	/* mkdir failed */
		append_error("Cannot create dbf database: %s\n", name);
		report_error();
		return DB_FAILED;
	    }
	}
	else {			/* some other problem */
	    append_error("Cannot open dbf database: %s\n", name);
	    report_error();
	    return DB_FAILED;
	}
    }

    while ((ent = readdir(dir))) {
	len = strlen(ent->d_name) - 4;
	if ((len > 0) && (G_strcasecmp(ent->d_name + len, ".dbf") == 0)) {
	    strcpy(buf, ent->d_name);
	    buf[len] = '\0';
	    add_table(buf, ent->d_name);
	}
    }

    closedir(dir);
    return DB_OK;
}
Example #12
0
int main(int argc, char **argv)
{

    struct GModule *module;

    /* initialize the GRASS GIS system */
    G_gisinit(argv[0]);

    /* allocate space for the choice data structure */
    choice = (struct CHOICE *)G_calloc(1, sizeof(struct CHOICE));

    module = G_define_module();
    module->keywords = _("raster, landscape structure analysis, patch index");
    module->description =
	_("Contains a set of measures for attributes, diversity, texture, "
	  "juxtaposition, and edge.");

    /* call user_input to read in the parameters */
    user_input(argc, argv);

    /* display the parameter choices */
    fprintf(stdout, "\nPARAMETER CHOICES:\n");
    fprintf(stdout, "\tMAP:\t  %s\n", choice->fn);
    if (choice->wrum == 'r')
	fprintf(stdout, "\tREGION:\t  %s\n", choice->reg);

    fprintf(stdout, "\tSAMPLE:");
    if (choice->wrum == 'w')
	fprintf(stdout, "\t  whole map    \n");
    if (choice->wrum == 'm')
	fprintf(stdout, "\t  moving window\n");
    if (choice->wrum == 'u')
	fprintf(stdout, "\t  units        \n");
    if (choice->wrum == 'r')
	fprintf(stdout, "\t  regions      \n");

    if (choice->edgemap || choice->units || choice->z)
	fprintf(stdout, "\tOUTPUT MAPS:\n");
    if (choice->edgemap)
	fprintf(stdout, "\t\t  edge\n");
    if (choice->units)
	fprintf(stdout, "\t\t  units_x\n");
    if (choice->z)
	fprintf(stdout, "\t\t  zscores\n");

    if (choice->att[0]) {
	fprintf(stdout, "\tATTRIBUTE MEASURES:\n");
	if (choice->att[1])
	    fprintf(stdout, "\t\t  mean pixel attribute\n");
	if (choice->att[2])
	    fprintf(stdout, "\t\t  st. dev. pixel attribute\n");
	if (choice->att[3])
	    fprintf(stdout, "\t\t  minimum pixel attribute\n");
	if (choice->att[4])
	    fprintf(stdout, "\t\t  maximum pixel attribute\n");
    }

    if (choice->div[0]) {
	fprintf(stdout, "\tDIVERSITY MEASURES:\n");
	if (choice->div[1])
	    fprintf(stdout, "\t\t  richness\n");
	if (choice->div[2])
	    fprintf(stdout, "\t\t  Shannon\n");
	if (choice->div[3])
	    fprintf(stdout, "\t\t  dominance\n");
	if (choice->div[4])
	    fprintf(stdout, "\t\t  inverse Simpson\n");
    }

    if (choice->te2[0]) {
	fprintf(stdout, "\tTEXTURE METHOD:\n");
	if (choice->tex == 1)
	    fprintf(stdout, "\t\t  2N-H\n");
	else if (choice->tex == 2)
	    fprintf(stdout, "\t\t  2N-45\n");
	else if (choice->tex == 3)
	    fprintf(stdout, "\t\t  2N-V\n");
	else if (choice->tex == 4)
	    fprintf(stdout, "\t\t  2N-135\n");
	else if (choice->tex == 5)
	    fprintf(stdout, "\t\t  4N-HV\n");
	else if (choice->tex == 6)
	    fprintf(stdout, "\t\t  4N-DIAG\n");
	else if (choice->tex == 7)
	    fprintf(stdout, "\t\t  8N\n");
	fprintf(stdout, "\tTEXTURE MEASURES:\n");
	if (choice->te2[1])
	    fprintf(stdout, "\t\t  contagion\n");
	if (choice->te2[2])
	    fprintf(stdout, "\t\t  ang. sec. mom.\n");
	if (choice->te2[3])
	    fprintf(stdout, "\t\t  inv. diff. mom.\n");
	if (choice->te2[4])
	    fprintf(stdout, "\t\t  entropy\n");
	if (choice->te2[5])
	    fprintf(stdout, "\t\t  contrast\n");
    }

    if (choice->jux[0]) {
	fprintf(stdout, "\tJUXTAPOSITION MEASURES:\n");
	if (choice->jux[1])
	    fprintf(stdout, "\t\t  mean juxtaposition\n");
	if (choice->jux[2])
	    fprintf(stdout, "\t\t  standard deviation of juxtaposition\n");
    }

    if (choice->edg[0]) {
	fprintf(stdout, "\tEDGE MEASURES:\n");
	if (choice->edg[1])
	    fprintf(stdout, "\t\t  sum of edges\n");
	if (choice->edg[2])
	    fprintf(stdout, "\t\t  sum of edges by type\n");
    }

    /* if not moving window, setup the
       r.le.out subdirectory */

    if (choice->wrum != 'm')
	G_mkdir("r.le.out");

    texture_fore();
    G_free(choice);

    return (EXIT_SUCCESS);
}