Beispiel #1
0
str *realpath(str *filename) {
    /**
    Return the canonical path of the specified filename, eliminating any
    symbolic links encountered in the path.
    */
    list<str *> *bits;
    str *component, *newpath, *resolved;
    __ss_int __40, __41, i;

    if (isabs(filename)) {
        bits = ((new list<str *>(1, const_4)))->__add__((filename->split(const_4))->__slice__(1, 1, 0, 0));
    }
    else {
        bits = filename->split(const_4);
    }

    FAST_FOR(i,2,(len(bits)+1),1,40,41)
        component = joinl(bits->__slice__(3, 0, i, 0));
        if (islink(component)) {
            resolved = _resolve_link(component);
            if ((resolved==0)) {
                return abspath(joinl(((new list<str *>(1, component)))->__add__(bits->__slice__(1, i, 0, 0))));
            }
            else {
                newpath = joinl(((new list<str *>(1, resolved)))->__add__(bits->__slice__(1, i, 0, 0)));
                return realpath(newpath);
            }
        }
    END_FOR

    return abspath(filename);
}
Beispiel #2
0
/* return 1 if name found in one of the files
 *	  0 if name not found in one of the files
 *	  -1 if neither file exists
 */
extern int
lookup(char *cp, char *local, Biobuf **lfpp, char *global, Biobuf **gfpp)
{
	static String *file = 0;

	if (local) {
		if (file == 0)
			file = s_new();
		abspath(local, UPASLIB, s_restart(file));
		if (*lfpp != 0 || (*lfpp = sysopen(s_to_c(file), "r", 0)) != 0) {
			if (okfile(cp, *lfpp))
				return 1;
		} else
			local = 0;
	}
	if (global) {
		abspath(global, UPASLIB, s_restart(file));
		if (*gfpp != 0 || (*gfpp = sysopen(s_to_c(file), "r", 0)) != 0) {
			if (okfile(cp, *gfpp))
				return 1;
		} else
			global = 0;
	}
	return (local || global)? 0 : -1;
}
static int
in_original_tree (char* other_path)
{
  char* abs_src_path = abspath (NULL, src_path);
  char* abs_src_path_slash = path_concat (abs_src_path, "");
  char* abs_other_path = abspath (NULL, other_path);
  int ret_val =  !strncmp (abs_src_path_slash, abs_other_path, strlen (abs_src_path_slash));

  free (abs_src_path);
  free (abs_src_path_slash);
  free (abs_other_path);
  return ret_val;
}
Beispiel #4
0
void PassFilesToInstance(void)
{
    int argc = __argc;
    char **argv = __argv;
    AllowSetForegroundWindow(ASFW_ANY);
//	argv = CmdLineToC(&argc, GetCommandLineA());
    if (argv)
    {
        if (argc <= 1)
        {
            SendFileName("###TOP###");
        }
        else
        {
            int i;
            for (i=1; i < argc; i++)
            {
                char buf[260], *p = buf;
                strcpy(buf, argv[i]);
                while (isspace(*p)) p++;
                    if (*p != '/' && *p != '-')
                    {
                        abspath(p, NULL);
                        SendFileName(p);
                    }
            }
        }
    }
}
static char *
cvs_dir(char *working_directory)
{
    char temp[MAXPATHLEN];
    abspath(pathcat(temp, working_directory, "CVS"));
    return txtalloc(temp);
}
Beispiel #6
0
void
Project::RemoveSystemInclude(const char *path)
{
	if (!path)
		return;
	
	BString abspath(path);
	abspath.ReplaceFirst("<project>",fPath.GetFolder());
	
	if (abspath[0] != '/')
	{
		abspath.Prepend("/");
		abspath.Prepend(fPath.GetFolder());
	}
	
	STRACE(1,("%s: Attempting to remove system include %s\n",GetName(),path));
	for (int32 i = 0; i < fSystemIncludeList.CountItems(); i++)
	{
		BString *str = fSystemIncludeList.ItemAt(i);
		if (str && str->Compare(abspath) == 0)
		{
			STRACE(1,("%s: Removed %s\n",GetName(),path));
			fSystemIncludeList.RemoveItemAt(i);
			delete str;
			return;
		}
	}
}
Beispiel #7
0
CRYSTAX_LOCAL
driver_t *find_driver(const char *path)
{
    DBG("path=%s", path);

    if (path == NULL || *path == '\0')
        return NULL;

    scope_lock_t lock(mount_table_mutex);

    if (mount_table_pos == 0)
    {
        DBG("path=%s: no mount records registered, use SYSTEM driver", path);
        return system::driver_t::instance();
    }

    abspath_t abspath(path);
    size_t nlen = ::strlen(abspath.c_str());
    for (size_t i = mount_table_pos; i > 0; --i)
    {
        driver_t *d = mount_table[i - 1];
        size_t len = ::strlen(d->root().c_str());
        if (nlen >= len && ::strncmp(abspath.c_str(), d->root().c_str(), len) == 0)
        {
            DBG("path=%s: use driver %s (%s)", path, d->name(), d->info());
            return d;
        }
    }

    DBG("path=%s: no mount record found, use system driver", path);
    return system::driver_t::instance();
}
Beispiel #8
0
LString makeRelativePath(const LString &aAbs, const LString &aBase)
{
  fs::path abspath(aAbs.c_str());
  fs::path basepath(aBase.c_str());
  if (!abspath.is_complete() || !basepath.is_complete())
    return aAbs; // aAbs or aBase is not absolute path

  if (abspath.root_path()!=basepath.root_path())
    return aAbs; // root names are different; cannot make relative path

  fs::path::const_iterator iter1 = abspath.begin();
  fs::path::const_iterator iter1_end = abspath.end();
  fs::path::const_iterator iter2 = basepath.begin();
  fs::path::const_iterator iter2_end = basepath.end();

  for (; iter1!=iter1_end && iter2!=iter2_end ; ++iter1, ++iter2) {
    if (*iter1!=*iter2) break;
  }

  fs::path relpath;
  //if (iter1!=iter1_end && iter2!=iter2_end) {
    for (; iter2!=iter2_end; ++iter2)
      relpath /= "..";
    for (; iter1!=iter1_end; ++iter1)
      relpath /= *iter1;
  //}

  // string() will canonicalize the path separator to "/"
  //return relpath.file_string();
  return relpath.string();
}
Beispiel #9
0
/*
 *  rules are of the form:
 *	<reg exp> <String> <repl exp> [<repl exp>]
 */
extern int
getrules(void)
{
	Biobuf	*rfp;
	String	*line;
	String	*type;
	String	*file;

	file = abspath("rewrite", UPASLIB, (String *)0);
	rfp = sysopen(s_to_c(file), "r", 0);
	if(rfp == 0) {
		rulep = 0;
		return -1;
	}
	rlastp = 0;
	line = s_new();
	type = s_new();
	while(s_getline(rfp, s_restart(line)))
		if(getrule(line, type, thissys) && altthissys)
			getrule(s_restart(line), type, altthissys);
	s_free(type);
	s_free(line);
	s_free(file);
	sysclose(rfp);
	return 0;
}
Beispiel #10
0
void main()
{

	SetAddApplDir("kolibrios", abspath("install/kolibrios")+1);
	io.run("/sys/media/kiv", "\\S__/kolibrios/res/Wallpapers/In the wind there is longing.png");
	io.del("/sys/docpack");
	copyf(abspath("install/sys"), "/sys");
	RestartProcessByName("@icon", MULTIPLE);
	RestartProcessByName("@taskbar", SINGLE);
	RestartProcessByName("@docky", SINGLE);
	notify(T_END);
	io.run("/sys/tmpdisk", "a0s10");
	pause(50);
	copyf(abspath("install/tmp"), "/tmp0/1");
	ExitProcess();
}
Beispiel #11
0
static void mtllib(char *dirname, char *filename)
{
	char path[1024];
	char *line, *next;
	unsigned char *data;
	int len;
	char *s;

	data = load_file(abspath(path, dirname, filename, sizeof path), &len);
	if (!data) {
		warn("cannot load material library: '%s'", filename);
		return;
	}

	data[len-1] = 0; /* over-write final newline to zero-terminate */

	for (line = (char*)data; line; line = next) {
		next = strchr(line, '\n');
		if (next)
			*next++ = 0;

		s = strtok(line, SEP);
		if (!s) {
			continue;
		} else if (!strcmp(s, "newmtl")) {
			s = strtok(NULL, SEP);
			if (s) {
				strlcpy(mtl_map[mtl_count].name, s, sizeof mtl_map[0].name);
				mtl_map[mtl_count].material = 0;
				mtl_count++;
			}
		} else if (!strcmp(s, "map_Kd")) {
			s = strtok(NULL, SEP);
			if (s && mtl_count > 0) {
				mtl_map[mtl_count-1].material = load_texture(abspath(path, dirname, s, sizeof path), 1);
			}
		}
	}

	free(data);
}
Beispiel #12
0
void
cvslast(const char *working,	/* working directory (absolute) */
	const char *path,	/* pathname to check (may be relative) */
	const char **vers_,
	time_t * date_,
	const char **lock_)
{
    char temp[MAXPATHLEN];

    abspath(pathcat(temp, working, path));
    tryCVS(temp, vers_, date_, lock_);
}
Beispiel #13
0
int main(int argc, char **argv)
{
	int result;
	char testdir[MAXPATHLEN];
	char ironout[MAXPATHLEN];
	char origin[MAXPATHLEN];
	if (argc < 2) {
		printf("Usage: %s testdir\n", argv[0]);
		return 1;
	}
	mktempdir(TEMPDIR);
	getcwd(origin, MAXPATHLEN);
	abspath(testdir, argv[1]);
	abspath(ironout, "ironout");
	chdir(TEMPDIR);

	result = runtests(testdir, ironout);

	chdir(origin);
	rmtempdir(TEMPDIR, 1);
	return result;
}
Beispiel #14
0
// Converts a possibly relative path to an absolute one
std::string makeAbsolute(const std::string &path)
{
	// Check for a URL scheme
	if (path.empty() || path.find("://") != std::string::npos) {
		return path;
	}

	// Make path absolute
	std::string abspath(path);
	if (abspath[0] != '/') {
		abspath = cwd() + "/" + path;
	}

	return canonicalize(abspath);
}
Beispiel #15
0
bool ABSHandler::setUpBuildingEnvironment(const QString &package, const QString &p)
{
    QString path = p;

    if ( !path.endsWith( QChar( '/' ) ) ) {
        path.append( QChar( '/' ) );
    }

    path.append( package );

    QDir pathDir( path );
    if ( pathDir.exists() ) {
        cleanBuildingEnvironment( package, path );
    }

    if ( !pathDir.mkpath( path ) ) {
        return false;
    }

    QString abspath( getABSPath( package ) );

    if ( abspath.isEmpty() ) {
        qDebug() << "Couldn't find a matching ABS Dir!!";
        return false;
    }

    QDir absPDir( abspath );
    absPDir.setFilter( QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot | QDir::NoSymLinks );

    QFileInfoList Plist = absPDir.entryInfoList();

    for ( int i = 0; i < Plist.size(); ++i ) {
        QString dest( path );
        if ( !dest.endsWith( QChar( '/' ) ) )
            dest.append( QChar( '/' ) );
        dest.append( Plist.at( i ).fileName() );

        qDebug() << "Copying " << Plist.at( i ).absoluteFilePath() << " to " << dest;

        if ( !QFile::copy( Plist.at( i ).absoluteFilePath(), dest ) ) {
            return false;
        }
    }

    return true;
}
static int
WALK_FUNC(scan_tree)
{
    char tmp[BUFSIZ];
    char *s = pathcat(tmp, path, name);
    Stat_t sb;

    if (RCS_DEBUG)
	PRINTF("++ %s%sscan (%s, %s, %s%d)\n",
	       R_opt ? "R " : "",
	       L_opt ? "L " : "",
	       path, name, (sp == 0) ? "no-stat, " : "", level);

    if (!quiet || n_opt)
	track_wd(path);

    if (sp == 0) {
	if (R_opt && (level > 0)) {
	    Ignore(name, " (no such file)");
	}
    } else if (isDIR(sp->st_mode)) {
	abspath(s);		/* get rid of "." and ".." names */
	if (ignore_dir(s))
	    readable = -1;
	else if (sameleaf(s, rcs_dir(NULL, NULL))) {
	    if (R_opt) {
		(void) walktree(strcpy(user_wd, path),
				name, scan_archive, "r", level);
	    }
	    readable = -1;
	} else {
#ifdef	S_IFLNK
	    if (!L_opt
		&& (lstat(s, &sb) < 0 || isLINK(sb.st_mode))) {
		Ignore(name, " (is a link)");
		readable = -1;
	    }
#endif
	}
    } else if (!isFILE(sp->st_mode)) {
	Ignore(name, RCS_DEBUG ? " (not a file)" : "");
	readable = -1;
    }
    return (readable);
}
Beispiel #17
0
CRYSTAX_LOCAL
int mount(const char *source, const char *target, const char *fstype,
    unsigned long flags, const void *data)
{
    DBG("source=%s, target=%s, fstype=%s, flags=%lu, data=%p",
        source, target, fstype, flags, data);

    scope_lock_t lock(mount_table_mutex);

    if (mount_table_pos >= MOUNT_TABLE_SIZE)
    {
        ERR("too much mount calls performed (max %d)", (int)MOUNT_TABLE_SIZE);
        errno = ENFILE;
        return -1;
    }

    abspath_t abspath(target);

    // Found underlying driver
    driver_t *underlying = system::driver_t::instance();
    for (size_t i = mount_table_pos; i > 0; --i)
    {
        driver_t *prev = mount_table[i - 1];
        if (abspath.subpath(prev->root()))
        {
            underlying = prev;
            break;
        }
    }

    driver_t *driver = load_driver(source, abspath.c_str(), fstype, flags, data, underlying);
    if (!driver)
        return system_mount(source, target, fstype, flags, data);

    DBG("load driver: %s (%s), underlying: %s (%s)", driver->name(), driver->info(), underlying->name(), underlying->info());

    mount_table[mount_table_pos] = driver;

    ++mount_table_pos;

    return 0;
}
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	char	*rel;
	char	abs[FILENAME_MAX] = "";

	if( nrhs != 1  )
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}
        else if( ! mtlb_get_string( prhs[0], &rel ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }

	abspath( rel, abs );

	plhs[0] = mxCreateString( abs );
}
Beispiel #19
0
CRYSTAX_LOCAL
int umount(const char *target, int flags)
{
    DBG("target=%s, flags=%d", target, flags);

    if (target == NULL || *target == '\0')
    {
        ERR("empty target");
        errno = EINVAL;
        return -1;
    }

    scope_lock_t lock(mount_table_mutex);

    abspath_t abspath(target);
    for (size_t i = mount_table_pos; i > 0; --i)
    {
        driver_t *d = mount_table[i - 1];
        if (d->root().length() > abspath.length() && d->root().subpath(abspath))
        {
            ERR("unmount failed: %s busy", abspath.c_str());
            errno = EBUSY;
            return -1;
        }
        if (d->root() == abspath)
        {
            DBG("unmount target %s", abspath.c_str());
            unload_driver(d);
            // Shift above records
            for (size_t j = i - 1; j < (size_t)mount_table_pos - 1; ++j)
                mount_table[j] = mount_table[j + 1];
            --mount_table_pos;
            return 0;
        }
    }

    return system_umount2(target, flags);
}
Beispiel #20
0
/* read a message into a temp file, return an open fd to it in mp->fd */
static int
m_read_to_file(Biobuf *fp, message *mp)
{
	int fd;
	int n;
	String *file;
	char buf[4*1024];

	file = s_new();
	/*
	 *  create temp file to be removed on close
	 */
	abspath("mtXXXXXX", UPASTMP, file);
	mktemp(s_to_c(file));
	if((fd = syscreate(s_to_c(file), ORDWR|ORCLOSE, 0600))<0){
		s_free(file);
		return -1;
	}
	mp->tmp = file;

	/*
	 *  read the rest into the temp file
	 */
	while((n = Bread(fp, buf, sizeof(buf))) > 0){
		if(write(fd, buf, n) != n){
			close(fd);
			return -1;
		}
		mp->size += n;
		if(mp->size > MSGLIMIT){
			mp->size = -1;
			break;
		}
	}

	mp->fd = fd;
	return 0;
}
Beispiel #21
0
int main( int argc, char **argv ) {
	mpconfig	*control;
	char *path;
	FILE *pidlog=NULL;
	struct timeval tv;

	control=readConfig( );
	if( control == NULL ) {
		printf( "music directory needs to be set.\n" );
		printf( "It will be set up now\n" );
		path=(char *)falloc( MAXPATHLEN+1, 1 );
		while( 1 ) {
			printf( "Default music directory:" );
			fflush( stdout );
			memset( path, 0, MAXPATHLEN );
			fgets(path, MAXPATHLEN, stdin );
			path[strlen( path )-1]=0; /* cut off CR */
			abspath( path, getenv( "HOME" ), MAXPATHLEN );

			if( isDir( path ) ) {
				break;
			}
			else {
				printf( "%s is not a directory!\n", path );
			}
		}

		writeConfig( path );
		free( path );
		control=readConfig();
		if( control == NULL ) {
			printf( "Could not create config file!\n" );
			return 1;
		}
	}
	muteVerbosity();

	/* improve 'randomization' */
	gettimeofday( &tv,NULL );
	srand( (getpid()*tv.tv_usec)%RAND_MAX );

	switch( getArgs( argc, argv ) ) {
	case 0: /* no arguments given */
		break;

	case 1: /* stream - does this even make sense? */
		break;

	case 2: /* single file */
		break;

	case 3: /* directory */
		/* if no default directory is set, use the one given */
		if( control->musicdir == NULL ) {
			incDebug();
			addMessage( 0, "Setting default configuration values and initializing..." );
			setProfile( control );
			if( control->root == NULL ) {
				addMessage( 0, "No music found at %s!", control->musicdir );
				return -1;
			}
			addMessage( 0, "Initialization successful!" );
			writeConfig( argv[optind] );
			freeConfig( );
			return 0;
		}
		break;
	case 4: /* playlist */
		break;
	default:
		addMessage( 0, "Unknown argument!\n", argv[optind] );
		return -1;
	}

	snprintf( control->pidpath, MAXPATHLEN, "%s/.mixplay/mixplayd.pid", getenv("HOME") );
	if( access( control->pidpath, F_OK ) == 0 ) {
		addMessage( 0, "Mixplayd is already running!" );
		freeConfig();
		return -1;
	}

	signal(SIGINT, sigint );
	signal(SIGTERM, sigint );

	/* daemonization must happen before childs are created otherwise the pipes are cut */
	if( getDebug() == 0 ) {
		daemon( 0, 1 );
		openlog ("mixplayd", LOG_PID, LOG_DAEMON);
		control->isDaemon=1;
		pidlog=fopen( control->pidpath, "w");
		if( pidlog == NULL ) {
			addMessage( 0, "Cannot open %s!", control->pidpath );
			return -1;
		}
		fprintf( pidlog, "%i", getpid() );
		fclose(pidlog);
	}

	addUpdateHook( &s_updateHook );

	control->inUI=1;
	initAll( );
	#ifdef EPAPER
	sleep(1);
	if( control->status != mpc_quit ) {
		epSetup();
		addUpdateHook( &ep_updateHook );
	}
	#endif
	pthread_join( control->stid, NULL );
	pthread_join( control->rtid, NULL );
	control->inUI=0;
#ifdef EPAPER
	epExit();
#endif
	if( control->changed ) {
		writeConfig( NULL );
	}
	unlink(control->pidpath);
	addMessage( 0, "Daemon terminated" );
	freeConfig( );

	return 0;
}
Beispiel #22
0
/*
 * parse the next request line
 * returns:
 *	1 ok
 *	0 eof
 *	-1 error
 */
int
hparsereq(HConnect *c, int timeout)
{
	Strings ss;
	char *vs, *v, *search, *uri, *origuri, *extra;

	if(c->bin != nil){
		hfail(c, HInternal);
		return -1;
	}

	/*
	 * serve requests until a magic request.
	 * later requests have to come quickly.
	 * only works for http/1.1 or later.
	 */
	if(timeout)
		alarm(timeout);
	if(hgethead(c, 0) < 0)
		return -1;
	if(timeout)
		alarm(0);
	c->reqtime = time(nil);
	c->req.meth = getword(c);
	if(c->req.meth == nil){
		hfail(c, HSyntax);
		return -1;
	}
	uri = getword(c);
	if(uri == nil || strlen(uri) == 0){
		hfail(c, HSyntax);
		return -1;
	}
	v = getword(c);
	if(v == nil){
		if(strcmp(c->req.meth, "GET") != 0){
			hfail(c, HUnimp, c->req.meth);
			return -1;
		}
		c->req.vermaj = 0;
		c->req.vermin = 9;
	}else{
		vs = v;
		if(strncmp(vs, "HTTP/", 5) != 0){
			hfail(c, HUnkVers, vs);
			return -1;
		}
		vs += 5;
		c->req.vermaj = strtoul(vs, &vs, 10);
		if(*vs != '.' || c->req.vermaj != 1){
			hfail(c, HUnkVers, vs);
			return -1;
		}
		vs++;
		c->req.vermin = strtoul(vs, &vs, 10);
		if(*vs != '\0'){
			hfail(c, HUnkVers, vs);
			return -1;
		}

		extra = getword(c);
		if(extra != nil){
			hfail(c, HSyntax);
			return -1;
		}
	}

	/*
	 * the fragment is not supposed to be sent
	 * strip it 'cause some clients send it
	 */
	origuri = uri;
	uri = strchr(origuri, '#');
	if(uri != nil)
		*uri = 0;

	/*
	 * http/1.1 requires the server to accept absolute
	 * or relative uri's.  convert to relative with an absolute path
	 */
	if(http11(c)){
		ss = parseuri(c, origuri);
		uri = ss.s1;
		c->req.urihost = ss.s2;
		if(uri == nil){
			hfail(c, HBadReq, uri);
			return -1;
		}
		origuri = uri;
	}

	/*
	 * munge uri for search, protection, and magic
	 */
	ss = stripsearch(origuri);
	origuri = ss.s1;
	search = ss.s2;
	uri = hurlunesc(c, origuri);
	uri = abspath(c, uri, "/");
	if(uri == nil || uri[0] == '\0'){
		hfail(c, HNotFound, "no object specified");
		return -1;
	}

	c->req.uri = uri;
	c->req.search = search;
	if(search)
		c->req.searchpairs = hparsequery(c, hstrdup(c, search));

	return 1;
}
Beispiel #23
0
void myinit(int argc, char **argv)
{
  int    status, i;
  char * p;
  char * p_dbg;
  char * cmdline;
  char * v;
  const char *  rankA[] = {"PMI_RANK", "OMPI_COMM_WORLD_RANK", "MV2_COMM_WORLD_RANK", NULL}; 
  const char *  sizeA[] = {"PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", NULL}; 
  
  struct timeval tv;
  struct utsname u;

  uuid_t uuid;

  
  unsetenv("LD_PRELOAD");

  /* Stop tracking if XALT is turned off */
  p_dbg = getenv("XALT_TRACING");
  if (p_dbg && strcmp(p_dbg,"yes") == 0)
    {
      xalt_tracing = 1;
      errfd = dup(STDERR_FILENO);
    }
  
  v = getenv("XALT_EXECUTABLE_TRACKING");
  if (xalt_tracing)
    {
      abspath(path,sizeof(path));
      FULL_DEBUG3(stderr,"myinit(%s,%s):\n  Test for XALT_EXECUTABLE_TRACKING: \"%s\"\n", STR(STATE),path,(v != NULL) ? v : "(NULL)");
    }

  if (!v || strcmp(v,"yes") != 0)
    {
      FULL_DEBUG0(stderr,"  XALT_EXECUTABLE_TRACKING is off -> exiting\n\n");
      return;
    }

  v = getenv("__XALT_INITIAL_STATE__");
  FULL_DEBUG2(stderr,"  Test for __XALT_INITIAL_STATE__: \"%s\", STATE: \"%s\"\n", (v != NULL) ? v : "(NULL)", STR(STATE));
  /* Stop tracking if any myinit routine has been called */
  if (v && (strcmp(v,STR(STATE)) != 0))
    {
      FULL_DEBUG2(stderr," __XALT_INITIAL_STATE__ has a value: \"%s\" -> and it is different from STATE: \"%s\" exiting\n\n",v,STR(STATE));
      return;
    }

  /* Stop tracking if my mpi rank is not zero */
  my_rank = compute_value(rankA);
  FULL_DEBUG1(stderr,"  Test for rank == 0, rank: %ld\n",my_rank);
  if (my_rank > 0L)
    {
      FULL_DEBUG0(stderr," MPI Rank is not zero -> exiting\n\n");
      return;
    }

  my_size = compute_value(sizeA);
  if (my_size < 1L)
    my_size = 1L;

  errno = 0;
  if (uname(&u) != 0)
    {
      perror("uname");
      exit(EXIT_FAILURE);
    }

  /* Get full absolute path to executable */
  abspath(path,sizeof(path));
  reject_flag = reject(path, u.nodename);
  FULL_DEBUG3(stderr,"  Test for path and hostname, hostname: %s, path: %s, reject: %d\n", u.nodename, path, reject_flag);
  if (reject_flag)
    {
      FULL_DEBUG0(stderr,"  reject_flag is true -> exiting\n\n");
      return;
    }

  setenv("__XALT_INITIAL_STATE__",STR(STATE),1);
  errfd = dup(STDERR_FILENO);

  syshost = xalt_syshost();

  /* Build a json version of the user's command line. */

  /* Calculate size of buffer*/
  int sz = 0;
  for (i = 0; i < argc; ++i)
    sz += strlen(argv[i]);

  /* this size formula uses 3 facts:
   *   1) if every character was a utf-16 character that is four bytes converts to 12 (sz*3)
   *   2) Each entry has two quotes and a comma (argc*3)
   *   3) There are two square brackets and a null byte (+3)
   */

  sz = sz*3 + argc*3 + 3;

  usr_cmdline = (char *) malloc(sz);
  p	      = &usr_cmdline[0];
  *p++        = '[';
  for (i = 0; i < argc; ++i)
    {
      *p++ = '"';
      const char* qs  = xalt_quotestring(argv[i]);
      int         len = strlen(qs);
      memcpy(p,qs,len);
      p += len;
      *p++= '"';
      *p++= ',';
    }
  *--p = ']';
  *++p = '\0';
  if (p > &usr_cmdline[sz])
    {
      fprintf(stderr,"XALT: Failure in building user command line json string!\n");
      reject_flag = 1;
      return;
    }

  uuid_generate(uuid);
  uuid_unparse_lower(uuid,uuid_str);
  gettimeofday(&tv,NULL);
  start_time = tv.tv_sec + 1.e-6*tv.tv_usec;

  asprintf(&cmdline, "LD_LIBRARY_PATH=%s PATH=/usr/bin:/bin %s --syshost \"%s\" --start \"%.3f\" --end 0 --exec \"%s\" --ntasks %ld --uuid \"%s\" '%s'",
	   SYS_LD_LIB_PATH, PREFIX "/libexec/xalt_run_submission", syshost, start_time, path, my_size, uuid_str, usr_cmdline);
  
  DEBUG1(stderr, "  Start Tracking: %s\nEnd myinit()\n",cmdline);
  system(cmdline);
  free(cmdline);
}
Beispiel #24
0
int
setflabel(const char *path, m_label_t *label)
{
	labeld_data_t	call;
	labeld_data_t	*callp = &call;
	size_t	bufsize = sizeof (labeld_data_t);
	size_t	datasize;
	size_t	path_len;
	static char	cwd[MAXPATHLEN];
	char		canon[MAXPATHLEN];


	/*
	 * If path is relative and we haven't already determined the current
	 * working directory, do so now.  Calculating the working directory
	 * here lets us do the work once, instead of (potentially) repeatedly
	 * in realpath().
	 */
	if (*path != '/' && cwd[0] == '\0') {
		if (getcwd(cwd, MAXPATHLEN) == NULL) {
			cwd[0] = '\0';
			return (-1);
		}
	}
	/*
	 * Find an absolute pathname in the native file system name space that
	 * corresponds to path, stuffing it into canon.
	 */
	if (abspath(cwd, path, canon) < 0)
		return (-1);

	path_len = strlen(canon) + 1;

	datasize = CALL_SIZE(setfbcl_call_t, path_len - BUFSIZE);
	datasize += 2; /* PAD */

	if (datasize > bufsize) {
		if ((callp = (labeld_data_t *)malloc(datasize)) == NULL) {
			return (-1);
		}
		bufsize = datasize;
	}

	callp->callop = SETFLABEL;

	clcall.sl = *label;
	(void) strcpy(clcall.pathname, canon);

	if (__call_labeld(&callp, &bufsize, &datasize) == SUCCESS) {
		int err = callp->reterr;

		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/*
		 * reterr == 0, OK,
		 * reterr < 0, invalid binary label,
		 */
		if (err == 0) {
			if (clret.status > 0) {
				errno = clret.status;
				return (-1);
			} else {
				return (0);
			}
		} else if (err < 0) {
			err = 0;
		}
		errno = ECONNREFUSED;
		return (-1);
	} else {
		if (callp != &call) {
			/* free allocated buffer */
			free(callp);
		}
		/* server not present */
		errno = ECONNREFUSED;
		return (-1);
	}
}  /* setflabel */
Beispiel #25
0
static void RestoreFiles(struct xmlNode *input, PROJECTITEM *root, PROJECTITEM *parent)
{
    while (input)
    {
        if (IsNode(input, "FOLDER"))
        {
            struct xmlAttr *attribs = input->attribs;
            PROJECTITEM *folder = calloc(1, sizeof(PROJECTITEM));
            if (folder)
            {
                PROJECTITEM **ins = &parent->children;
                while (attribs)
                {
                    if (IsAttrib(attribs, "TITLE"))
                    {
                        strcpy(folder->displayName, attribs->value);
                    }
                    attribs = attribs->next;
                }
                while (*ins && (*ins)->type == PJ_FOLDER && stricmp((*ins)->displayName, folder->displayName) < 0)
                    ins = &(*ins)->next;
                folder->parent = parent;
                folder->type = PJ_FOLDER;
                folder->next = *ins;
                *ins = folder;
                RestoreFiles(input->children, root, folder);
            }
        }
        else if (IsNode(input, "FILE"))
        {
            struct xmlAttr *attribs = input->attribs;
            PROJECTITEM *file = calloc(1, sizeof(PROJECTITEM));
            if (file)
            {
                PROJECTITEM **ins = &parent->children;
                while (attribs)
                {
                    if (IsAttrib(attribs, "TITLE"))
                    {
                        strcpy(file->displayName, attribs->value);
                    }
                    else if (IsAttrib(attribs, "NAME"))
                    {
                        strcpy(file->realName, attribs->value);
                        abspath(file->realName, root->realName);
                    }
                    else if (IsAttrib(attribs, "CLEAN"))
                    {
                        file->clean = atoi(attribs->value);
                    }
                    attribs = attribs->next;
                }
                while (*ins && (*ins)->type == PJ_FOLDER)
                    ins = &(*ins)->next;
                while (*ins && stricmp((*ins)->displayName, file->displayName) < 0)
                    ins = &(*ins)->next;
                file->parent = parent;
                file->type = PJ_FILE;
                file->next = *ins;
                *ins = file;
                RestorePropsNested(input->children, root, file);
            }
        }
        input = input->next;
    }
}
Beispiel #26
0
/** If m_fullTest=true if checks that the files exists, otherwise just that path syntax looks valid
 *  @param value :: file name
 *  @returns An error message to display to users or an empty string on no error
 */
std::string FileValidator::checkValidity(const std::string &value) const
{
  // Check if the path is syntactically valid
  if( !Poco::Path().tryParse(value) )
  {
    return "Error in path syntax: \"" + value + "\".";
  }
  
  //Check the extension but just issue a warning if it is not one of the suggested values
  if (!(value.empty()))
  {
    if (!(this->endswith(value)))
    {
      //Dropped from warning to debug level as it was printing out on every search of the archive, even when successful. re #5998
      g_log.debug() << "Unrecognised extension in file \"" << value << "\"";
      if (!this->m_extensions.empty()) {
        g_log.debug() << " [ ";
        for (std::set<std::string>::const_iterator it = this->m_extensions.begin(); it != this->m_extensions.end(); ++it)
          g_log.debug() << *it << " ";
        g_log.debug() << "]";
      }
      g_log.debug() << "\"."  << std::endl;
    }
  }

  // create a variable for the absolute path to be used in error messages
  std::string abspath(value);
  if (!value.empty())
  {
    Poco::Path path(value);
    if (path.isAbsolute())
      abspath = path.toString();
  }

  //If the file is required to exist check it is there
  if ( m_testExist && ( value.empty() || !Poco::File(value).exists() ) )
  {
    return "File \"" + abspath + "\" not found";
  }

  //If the file is required to be writable...
  if (m_testCanWrite)
  {
    if (value.empty())
      return "Cannot write to empty filename";

    Poco::File file(value);
    // the check for writable is different for whether or not a version exists
    // this is taken from ConfigService near line 443
    if (file.exists())
    {
      try
      {
        if (!file.canWrite())
          return "File \"" + abspath + "\" cannot be written";
      }
      catch (std::exception &e)
      {
        g_log.information() << "Encountered exception while checking for writable: " << e.what();
      }
    }
    else // if the file doesn't exist try to temporarily create one
    {
      try
      {
        Poco::Path direc(value);
        if (direc.isAbsolute())
        {
          // see if file is writable
          if (Poco::File(direc).canWrite())
            return "";
          else
            return "Cannot write to file \"" + direc.toString() + "\"";
        }

        g_log.debug() << "Do not have enough information to validate \""
                      << abspath << "\"\n";
      }
      catch (std::exception &e)
      {
        g_log.information() << "Encountered exception while checking for writable: " << e.what();
      }
      catch (...) {
    	g_log.information() << "Unknown exception while checking for writable";
      }
    }
  }

  //Otherwise we are okay, file extensions are just a suggestion so no validation on them is necessary
  return "";
}
Beispiel #27
0
int grabComFilename(const int warn, const char far * const fnam)
{
    char *buf;
    size_t len;
    int rc;

    dprintf( ("[INIT: grabComFilename(%s)]\n", fnam) );
    if(!fnam)
        return 4;

    /* Copy the filename into the local heap */
    len = _fstrlen(fnam);
    if(len >= INT_MAX || len < 1) {
        /* no filename specified */
        if(warn)
            error_syntax(0);
        return 4;
    }

    if((buf = malloc(len + 1)) == 0) {
        if(warn) error_out_of_memory();
        return 4;
    }
    _fmemcpy((char far*)buf, fnam, len);
    buf[len] = '\0';

    if (buf[1] != ':' || buf[2] != '\\')
    {   char *p;

        /* expand the string for the user */
        p = abspath(buf, warn);
        free(buf);
        if((buf = p) == 0)
            return 4;
        if(warn)
            error_init_fully_qualified(buf);

        len = strlen(buf);
    }

    while(buf[len - 1] == '\\')
        --len;
    buf[len] = 0;

    if(dfnstat(buf) & DFN_DIRECTORY) {
        /* The user specified a directory, try if we can find the
          COMMAND.COM with the standard name in there */
        char *p;

        if((p = realloc(buf, len + sizeof(COM_NAME) + 1)) == 0) {
            if(warn) error_out_of_memory();
            free(buf);
            return 4;
        }
        buf = p;
        strcpy(&buf[len], "\\" COM_NAME);
    }


    if(0 != (rc = validResFile(buf))) {
        if(warn) switch(rc) {
            default:
#ifdef NDEBUG
                assert(0);
#endif
            case 1:
                error_open_file(buf);
                break;
            case 2:
                error_fcom_is_device(buf);
                break;
            case 3:
                error_fcom_invalid(buf);
                break;
            }

        free(buf);
        return rc;
    }

    free(ComPath);    /* Save the found file */
    ComPath = buf;
    dprintf(("[INIT: new resource file name: %s]\n", ComPath));

    isSwapFile = 0;
    buf = dfnfilename(ComPath);
    assert(buf);
    if((buf = strchr(buf, '.')) != 0
            && stricmp(buf, ".swp") == 0) {
        dprintf(("[INIT: VSpawn file found: %s]\n", ComPath));
        memcpy(++buf, "COM", 3);
        isSwapFile = buf - ComPath;
    }

    return 0;
}
Beispiel #28
0
int utime(const char *path,const struct utimbuf *times) {
	char apath[MAX_PATH_LEN];
	return syscall2(SYSCALL_UTIME,(ulong)abspath(apath,sizeof(apath),path),(ulong)times);
}
Beispiel #29
0
static void test_abspath(void) {
	char *p,path[MAX_PATH_LEN];

	test_caseStart("Testing abspath");

	setenv("CWD","/home/hrniels");

	p = abspath(path,sizeof(path),".");
	test_assertStr(p,"/home/hrniels/.");

	p = abspath(path,sizeof(path),"/");
	test_assertStr(p,"/");

	p = abspath(path,sizeof(path),"../..");
	test_assertStr(p,"/home/hrniels/../..");

	p = abspath(path,sizeof(path),"http://www.example.com");
	test_assertStr(p,"/dev/http/www.example.com");

	p = abspath(path,sizeof(path),"a://");
	test_assertStr(p,"/dev/a/");

	p = abspath(path,sizeof(path),"a:/");
	test_assertStr(p,"/home/hrniels/a:/");

	p = abspath(path,8,"/");
	test_assertStr(p,"/");

	p = abspath(path,8,"..");
	test_assertStr(p,"/home/h");

	p = abspath(path,8,"f://bar");
	test_assertStr(p,"/dev/f/");

	p = abspath(path,8,"foobar://bar");
	test_assertStr(p,"/dev/fo");

	p = abspath(path,2,"a://b");
	test_assertStr(p,"/");

	p = abspath(path,1,"a://b");
	test_assertStr(p,"");

	p = abspath(path,1,".");
	test_assertStr(p,"");

	test_caseSucceeded();
}
Beispiel #30
0
		const std::string PathInfo::getRelPath(const std::string AbsPath, const std::string Origin)
		{
			m_buffer = "";

			std::string abspath(AbsPath);
			std::string name = getName(AbsPath);
			std::string dir  = getDirectory(Origin);

			m_buffer = "";

			// AbsPath is already relative
			if (abspath.find(':') == std::string::npos)
			{
				m_buffer = abspath;
				return m_buffer.c_str();
			}

			// separated folders
			std::vector<std::string> fPath;
			std::vector<std::string> fOrigin;

			// split into folders
			doSplitPath(abspath, fPath);
			doSplitPath(dir, fOrigin);

			// nothing splitted
			if (fPath.empty()) return "";
			if (fOrigin.empty()) return "";

			// remove 'current dir'
			if (fPath[0] == ".") fPath.erase(fPath.begin());
			if (fOrigin[0] == ".") fOrigin.erase(fOrigin.begin());

			// remove filename
			if (name.size()) fPath.pop_back();

			// number of equal folders
			int equal;

			// count equal folders (from the beginning)
			for(equal = 0; ((equal < (int)fOrigin.size()) && (equal < (int)fPath.size())); equal++)
			{
				// get length
				int size1 = (int)fPath[equal].size();
				int size2 = (int)fOrigin[equal].size();

				// different folders found (length)
				if (size1 != size2)
				{
					break;
				}

				// different folders found (lexicographically)
				else if (_strnicmp(fPath[equal].c_str(), fOrigin[equal].c_str(), size1))
				{
					break;
				}
			}

			// different drives
			if (equal == 0)
			{
				m_buffer = abspath;
				return m_buffer.c_str();
			}

			// move up
			for(int up = equal; up < (int)fOrigin.size(); up++)
			{
				m_buffer += "..";
				m_buffer += separator;
			}

			// move down
			for(int dn = equal; dn < (int)fPath.size(); dn++)
			{
				m_buffer += fPath[dn];
				m_buffer += separator;
			}

			// add filename
			m_buffer += name;

			// current directory
			if (m_buffer.empty())
			{
				m_buffer = ".\\";
			}

			return m_buffer;
		}