示例#1
0
	void expand_data_paths() {
		expand_path(level_path_);
		expand_path(save_file_path_);
		expand_path(auto_save_file_path_);
		expand_path(preferences_path_);
		std::cerr << "EXPAND DATA PATHS\n";
	}
示例#2
0
int sge_get_path(const char *qualified_hostname, lList *lp, const char *cwd, const char *owner, 
                 const char *job_name, u_long32 job_number, 
                 u_long32 ja_task_number, int type,
                 char *pathstr, size_t pathstr_len) 
{
   lListElem *ep = NULL;
   const char *path = NULL, *host = NULL;

   DENTER(TOP_LAYER, "sge_get_path");

   *pathstr = '\0';

   /*
    * check if there's a path for this host
    */
   ep = lGetElemHost(lp, PN_host, qualified_hostname);
   if (ep != NULL) {
      path = expand_path(lGetString(ep, PN_path), job_number, 
         ja_task_number, job_name, owner, qualified_hostname);
      host = lGetHost(ep, PN_host);
   } else {
      /* 
       * hostname: wasn't set, look for a default 
       */
      for_each(ep, lp) {
         path = expand_path(lGetString(ep, PN_path), job_number, 
                            ja_task_number, job_name, owner, 
                            qualified_hostname);
         host = lGetHost(ep, PN_host);
         if (host == NULL) {
            break;
         }
      }
   }
示例#3
0
	void LoadMapFromVoodooTextFile(const string& text_file,
																 const string& image_pattern,
																 Map& map) {
		static const string kMagic = "#timeindex";
		static const string kPointsHeader = "# 3D Feature Points";
		sifstream in(expand_path(text_file));

		double Cx, Cy, Cz, Ax, Ay, Az, Hx, Hy, Hz, Vx, Vy, Vz, K3, K5;
		double sx, sy, Width, Height, ppx, ppy, f, fov;
		double H0x, H0y, H0z, V0x, V0y, V0z;

		DLOG << "WARNING: using first camera intrinsics for all cameras";
		int i = 0;
		Vec3 v;
		bool reading_points = false;
		boost::format image_fmt(image_pattern);
		while (!in.eof()) {
			if (reading_points) {
				in >> v[0] >> v[1] >> v[2];
				map.points.push_back(v);
			} else {
				string line;
				getline(in, line);
				if (line.substr(0,kMagic.size()) == kMagic) {
					int id = lexical_cast<int>(line.substr(kMagic.size()+1));
					in >> Cx >> Cy >> Cz >> Ax >> Ay >> Az
						 >> Hx >> Hy >> Hz >> Vx >> Vy >> Vz >> K3 >> K5
						 >> sx >> sy >> Width >> Height >> ppx >> ppy >> f >> fov
						 >> H0x >> H0y >> H0z >> V0x >> V0y >> V0z;
				
					string image_file = str(image_fmt % 21);//id);
					CHECK_PRED1(fs::exists, image_file);

					Mat3 C;
					C[0] = makeVector(f/sx, 0, ppx);
					C[1] = makeVector(0, f/sy, ppx);
					C[2] = makeVector(0, 0, 1);
					if (i == 0) {
						Vec2I image_size = GetImageSize(expand_path(image_file));
						map.camera.reset(new LinearCamera(C, image_size));
					}

					Mat3 R;
					R[0] = makeVector(H0x, H0z, H0y);
					R[1] = makeVector(V0x, V0z, V0y);
					R[2] = makeVector(Ax, Az, Ay);
					Vec3 t = makeVector(-Cx, -Cy, -Cz);
					SE3<> pose(SO3<>(R), t);

					map.AddFrame(new Frame(id, image_file, pose));

					i++;
				} else if (line.substr(0, kPointsHeader.size()) == kPointsHeader) {
示例#4
0
const char *find_config_file(void)
{
    char *path;
    int res;

    path = expand_path("~/.udisks-glue.conf");
    if (file_exists(path))
        return path;
    else
        free(path);

    char *xdg_config_home = getenv("XDG_CONFIG_HOME");
    if (!xdg_config_home)
        xdg_config_home = "~/.config";

    xdg_config_home = expand_path(xdg_config_home);
    res = asprintf(&path, "%s/udisks-glue/config", xdg_config_home);
    free(xdg_config_home);
    if (res == -1)
        perror("asprintf");
    else if (file_exists(path))
        return path;
    else
        free(path);

    path = expand_path(SYSCONFDIR "/udisks-glue.conf");
    if (file_exists(path))
        return path;
    else
        free(path);

    const char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS");
    if (!xdg_config_dirs)
        xdg_config_dirs = SYSCONFDIR "/xdg";

    char *buf = strdup(xdg_config_dirs);
    char *tok = strtok(buf, ":");
    while (tok != NULL) {
        tok = expand_path(tok);
        res = asprintf(&path, "%s/udisks-glue/config", tok);
        free(tok);
        if (res == -1)
            perror("asprintf");
        else if (file_exists(path))
            return path;
        else
            free(path);
        tok = strtok(NULL, ":");
    }
    free(buf);

    return NULL;
}
示例#5
0
文件: https.c 项目: demute/iPKCS11
void ssl_link_init(const char *_url)
{
    url = _url;
    CURLcode res;
    res = curl_global_init(CURL_GLOBAL_ALL);
    /* Check for errors */ 
    if(res != CURLE_OK) {
        fprintf(stderr, "curl_global_init() failed: %s\n",
                curl_easy_strerror(res));
        exit(1);
    }
    /* get a curl handle */ 
    handle = curl_easy_init();
    server_cert_file = expand_path(SERVER_CERT);
    client_cert_file = expand_path(CLIENT_CERT);
    client_key_file = expand_path(CLIENT_KEY);

    /* set up CURL */
    // curl_easy_setopt(handle, CURLOPT_CERTINFO, 1);
    // curl_easy_setopt(handle, CURLOPT_VERBOSE, 2);

    /* First set the URL that is about to receive our POST. */ 
    curl_easy_setopt(handle, CURLOPT_URL, url);

    /* define cert to be used */
    curl_easy_setopt(handle, CURLOPT_CAINFO, server_cert_file);

    /* define cert to be used */
    curl_easy_setopt(handle, CURLOPT_SSLKEY, client_key_file);

    /* define cert to be used */
    curl_easy_setopt(handle, CURLOPT_SSLCERT, client_cert_file);

    /* check that the certificate is valid */
    curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 1);

    /* ignore the host name (which in our case is probably an ip-address) */
    curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0);

    /* let curl write back data to our own function */
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);

    /* specify we want to POST data */ 
    curl_easy_setopt(handle, CURLOPT_POST, 1L);

    /* Content-type for POST */
    slist = curl_slist_append(slist, "Content-type: application/json");
    curl_easy_setopt(handle, CURLOPT_HTTPHEADER, slist);
}
示例#6
0
文件: common.c 项目: ltratt/extsmail
static int try_conf_path(const char *path)
{
    char *cnd_path = expand_path(path);
    if (cnd_path == NULL) {
        return -1;
    }

    yycin = fopen(cnd_path, "rt");
    free(cnd_path);
    if (yycin == NULL) {
        if (errno == ENOENT)
            return 1;
        return -1;
    }

    if (yycparse() != 0) {
        fclose(yycin);
        return -1;
    }

    fclose(yycin);
#if HAVE_YYLEX_DESTROY
    yyclex_destroy();
#endif

    return 0;
}
示例#7
0
/* Sets, unsets or changes the pathname and name for an icon.
 * Updates icons_hash and (re)stats the item.
 * If name is NULL then gets the leafname from pathname.
 * If pathname is NULL, frees everything.
 */
void icon_set_path(Icon *icon, const char *pathname, const char *name)
{
	if (icon->path)
	{
		icon_unhash_path(icon);
		icon->src_path = NULL;
		icon->path = NULL;

		diritem_free(icon->item);
		icon->item = NULL;
	}

	if (pathname)
	{
		if (g_utf8_validate(pathname, -1, NULL))
			icon->src_path = g_strdup(pathname);
		else
			icon->src_path = to_utf8(pathname);
		icon->path = expand_path(icon->src_path);

		icon_hash_path(icon);

		if (!name)
			name = g_basename(icon->src_path);

		icon->item = diritem_new(name);
		diritem_restat(icon->path, icon->item, NULL);
	}
}
示例#8
0
/*
 * As per open_path_mfile, but searching only for local filenames.
 * This is useful as we may avoid doing a full mfopen and loading
 * the entire file into memory.
 *
 * Returns the expanded pathname if found.
 *         NULL if not
 */
char *find_path(char *file, char *path) {
    char *newsearch;
    char *ele;
    char *outpath = NULL;

    /* Use path first */
    if (!path)
	path = getenv("RAWDATA");
    if (NULL == (newsearch = tokenise_search_path(path)))
	return NULL;
    
    for (ele = newsearch; *ele; ele += strlen(ele)+1) {
	char *ele2 = (*ele == '|') ? ele+1 : ele;

	if (!strncmp(ele2, "URL=", 4) ||
	    !strncmp(ele2, "http:", 5) ||
	    !strncmp(ele2, "ftp:", 4)) {
	    continue;
	} else {
	    outpath = expand_path(file, ele2);
	    if (is_file(outpath)) {
		free(newsearch);
		return outpath;
	    } else {
		free(outpath);
	    }
	} 
    }

    free(newsearch);

    return NULL;
}
示例#9
0
char* base_path(void) {

    static char base[MAX_PATH_LENGTH] = "";

    if (!base[0]) {

        expand_path(base, CVS_DIR);
    }

    return base;
}
示例#10
0
fsize_t vfu_dir_size( const char *s )
{
  char t[MAX_PATH];
  expand_path( s, t );
  size_cache_clean( t );
  str_fix_path( t );
  size_cache_clean( t );
  fsize_t size = __dir_size_process( t );
  size_cache_set( t, size );
  return size;
}
示例#11
0
文件: replace.c 项目: avkrotov/fdm
char *
replacepath(struct replpath *rp, struct strb *tags, struct mail *m,
    struct rmlist *rml, const char *home)
{
	char	*s, *t;

	s = replace(rp->str, tags, m, rml);
	if ((t = expand_path(s, home)) == NULL)
		return (s);
	xfree(s);
	return (t);
}
示例#12
0
/*
 * Searches for file in the directory 'dirname'. If it finds it, it opens
 * it. This also searches for compressed versions of the file in dirname
 * too.
 *
 * Returns mFILE pointer if found
 *         NULL if not
 */
static mFILE *find_file_dir(char *file, char *dirname) {
    char *path;
    mFILE *mf = NULL;

    path = expand_path(file, dirname);

    if (is_file(path))
	mf = mfopen(path, "rbm");

    free(path);
    return mf;
}
示例#13
0
文件: lua.c 项目: Cynede/hexchat
static script_info *create_script(char const *file)
{
	int base;
	char *filename_fs;
	lua_State *L;
	script_info *info = g_new0(script_info, 1);
	info->hooks = g_ptr_array_new_with_free_func((GDestroyNotify)free_hook);
	info->unload_hooks = g_ptr_array_new_with_free_func((GDestroyNotify)free_hook);
	info->filename = g_strdup(expand_path(file));
	L = luaL_newstate();
	info->state = L;
	if(!L)
	{
		hexchat_print(ph, "\00304Could not allocate memory for the script");
		destroy_script(info);
		return NULL;
	}
	prepare_state(L, info);
	lua_rawgeti(L, LUA_REGISTRYINDEX, info->traceback);
	base = lua_gettop(L);
	filename_fs = g_filename_from_utf8(info->filename, -1, NULL, NULL, NULL);
	if(!filename_fs)
	{
		hexchat_printf(ph, "Invalid filename: %s", info->filename);
		destroy_script(info);
		return NULL;
	}
	if(luaL_loadfile(L, filename_fs))
	{
		g_free(filename_fs);
		hexchat_printf(ph, "Lua syntax error: %s", luaL_optstring(L, -1, ""));
		destroy_script(info);
		return NULL;
	}
	g_free(filename_fs);
	info->status |= STATUS_ACTIVE;
	if(lua_pcall(L, 0, 0, base))
	{
		char const *error = lua_tostring(L, -1);
		hexchat_printf(ph, "Lua error: %s", error ? error : "(non-string error)");
		destroy_script(info);
		return NULL;
	}
	lua_pop(L, 1);
	if(!info->name)
	{
		hexchat_printf(ph, "Lua script didn't register with hexchat.register");
		destroy_script(info);
		return NULL;
	}
	return info;
}
示例#14
0
文件: display.c 项目: phschoen/tig
enum status_code
open_script(const char *path)
{
	if (is_script_executing())
		return error("Scripts cannot be run from scripts");

	char buf[SIZEOF_STR];

	if (!expand_path(buf, sizeof(buf), path))
		return error("Failed to expand path: %s", path);

	return io_open(&script_io, "%s", buf)
		? SUCCESS : error("Failed to open %s", buf);
}
示例#15
0
文件: data.cpp 项目: torandi/basejump
Data * Data::open(const char * filename) {
	const std::string real_path = expand_path(filename);
	if ( real_path == "" ){
		return nullptr;
	}

	size_t size;
	void * data = load_file(real_path.c_str(), size);
	if(data == nullptr){
		return nullptr;
	}

	return new Data(data, size);
}
示例#16
0
文件: lua.c 项目: Cynede/hexchat
static script_info *get_script_by_file(char const *filename)
{
	char const *expanded = expand_path(filename);
	guint i;
	for(i = 0; i < scripts->len; i++)
	{
		script_info *script = scripts->pdata[i];
		if(!strcmp(script->filename, expanded))
		{
			return script;
		}
	}

	return NULL;
}
示例#17
0
文件: ult_src.c 项目: Shivox/man-db
static char *find_include (const char *name, const char *path,
			   const char *include)
{
	char *ret;
	char *dirname;
	char *temp_file;

	/* Restore the original path from before ult_softlink() etc., in
	 * case it went outside the mantree.
	 */
	ret = xasprintf ("%s/%s", path, include);

	/* If the original path from above doesn't exist, try to create new
	 * path as if the "include" was relative to the current man page.
	 */
	if (access (ret, F_OK) == 0)
		return ret;

	dirname = dir_name (name);
	temp_file = xasprintf ("%s/%s", dirname, include);
	free (dirname);

	if (access (temp_file, F_OK) == 0) {
		/* Just plain include. */
		free (ret);
		ret = canonicalize_file_name (temp_file);
	} else {
		/* Try globbing - the file suffix might be missing. */
		char *temp_file_asterisk = xasprintf ("%s*", temp_file);
		char **candidate_files = expand_path (temp_file_asterisk);
		int i;

		free (temp_file_asterisk);
		if (access (candidate_files[0], F_OK) == 0) {
			free (ret);
			ret = canonicalize_file_name (candidate_files[0]);
		}
		for (i = 0; candidate_files[i]; i++)
			free (candidate_files[i]);
		free (candidate_files);
	}
	free (temp_file);

	return ret;
}
示例#18
0
文件: common.c 项目: demute/iPKCS11
FILE *myopen(char *path, const char *mode)
{
    char *filename = expand_path(path);

    struct stat info;
    FILE *ret;

    if(stat(filename, &info))
    {
        fprintf(stderr, "%s: %s\n", filename, strerror(errno));
        ret = NULL;
    }
    else
        ret = fopen(filename, mode);
    
    free(filename);
    return ret;
}
示例#19
0
VString size_cache_compose_key( const char *s, fsize_t size )
{
  const char *ps;
  char ss[MAX_PATH];
  expand_path( s, ss );
  ps = ss;
  
  char s_adler[16];
  char s_size[32];
  
  sprintf( s_size, "%012.0f", size ); //WARNING: THIS IS SIZE_CACHE_OFFSET
  sprintf( s_adler, "%08X", (unsigned int)str_adler32( ps ) );
  
  VString str;
  str = str + s_size + "|" + s_adler + "|" + ps;
  
  return str;
}
示例#20
0
int main(int c, char **v)
   {int i, dt, rv, nt, nc, fullpth;
    char fmt[80];
    char *tname;

    rv      = 0;
    dt      = 0;
    nt      = 1;
    fullpth = TRUE;
    for (i = 1; i < c; i++)
        {if (v[i][0] == '-')
            {switch (v[i][1])
                {case 'h':
                      help();
                      return(1);

                 case 'n':
                      nt = atoi(v[++i]);
                      break;

                 case 't':
                      dt = atoi(v[++i]);
                      break;

                 case 'w':
                      fullpth = FALSE;
                      break;};}
	 else
	    break;};

    if (i >= c)
       {tname = MAKE_N(char, PATH_MAX);
	nc = PATH_MAX - 1;
	snprintf(fmt, 80, "%%%ds", nc);

        while (scanf(fmt, tname) == 1)
           rv = expand_path(tname, fullpth, nt, dt, rv);

        FREE(tname);}
示例#21
0
文件: config-dialog.c 项目: gpg/gpgol
static int
load_config_value (HKEY hk, const char *path, const char *key, char **val)
{
    HKEY h;
    DWORD size=0, type;
    int ec;

    *val = NULL;
    if (hk == NULL)
	hk = HKEY_CURRENT_USER;
    ec = RegOpenKeyEx (hk, path, 0, KEY_READ, &h);
    if (ec != ERROR_SUCCESS)
	return -1;

    ec = RegQueryValueEx(h, key, NULL, &type, NULL, &size);
    if (ec != ERROR_SUCCESS) {
	RegCloseKey (h);
	return -1;
    }
    if (type == REG_EXPAND_SZ) {
	char tmp[256]; /* XXX: do not use a static buf */
	RegQueryValueEx (h, key, NULL, NULL, (BYTE*)tmp, &size);
	*val = expand_path (tmp);
    }
    else {
	*val = xcalloc(1, size+1);
	ec = RegQueryValueEx (h, key, NULL, &type, (BYTE*)*val, &size);
	if (ec != ERROR_SUCCESS) {
	    xfree (*val);
	    *val = NULL;
	    RegCloseKey (h);
	    return -1;
	}
    }
    RegCloseKey (h);
    return 0;
}
示例#22
0
int try_externals_path(const char *path)
{
    char *cnd_path = expand_path(path);
    if (cnd_path == NULL) {
        free(cnd_path);
        return -1;
    }

    // See whether the externals exists at 'path'.
    struct stat externals_st;
    if (stat(cnd_path, &externals_st) == -1) {
        free(cnd_path);
        return 1;
    }
    
    // Check that the user and group of the externals file match the
    // executing process.
    if (externals_st.st_uid != geteuid() || externals_st.st_gid != getegid()) {
        warnx("The user and / or group permissions of '%s' do not match the "
          "executing user", path);
        free(cnd_path);
        return -1;
    }

    yyein = fopen(cnd_path, "rt");
    if (yyein == NULL) {
        free(cnd_path);
        return -1;
    }
    free(cnd_path);
    
    if (yyeparse() != 0) {
        return -1;
    }
    
    return 0;
}
示例#23
0
  bool plan_heuristic::getSuggestions()  {
    if (!m_suggestions.empty()) {
      return true;
    }
    DREAL_LOG_INFO << "plan_heuristic::getSuggestions()";
    displayTrail();


    if (trail->size() > lastTrailEnd)
      pushTrailOnStack();

    bool suggestion_consistent = isStackConsistentWithSuggestion();



  bool found_path = false;
  bool path_possible = true;
  // bool suggest_defaults = true;

   if(!m_suggestions.empty() && suggestion_consistent)  {
     return true;
   } else if(!suggestion_consistent || backtracked)  {
     path_possible = unwind_path();
   }


   while (!found_path && path_possible) {
     if (path_possible) {
       found_path = expand_path();
     }
     if (!found_path) {
       path_possible = pbacktrack();
     }
   }

   if (m_decision_stack.size() == 0)
     return false;




    completeSuggestionsForTrail();

  //  for (int time = m_depth; time >= 0; time--) {
  //    DREAL_LOG_DEBUG << "Depth = " << time;
  //      for (auto & p : *time_event_enodes[time]) {
  //        Enode* ev = p.second;
  //        // ev->setDecPolarity(l_True);
  //        m_suggestions.push_back(ev);
  //      }
  //    }

  //    for (int time = 0; time <= m_depth; time++) {
  //      for (auto & p : *time_process_enodes[time]) {
  //        Enode* proc = p.second;
  //        // proc->setDecPolarity(l_True);
  //        m_suggestions.push_back(proc);
  //      }
  //    }

  //    for (int time = 0; time <= m_depth; time++) {
  //      for (auto & p : *time_act_enodes[time]) {
  //        Enode* proc = p.second;
  //        // proc->setDecPolarity(l_True);
  //        m_suggestions.push_back(proc);
  //      }
  //    }
  //    for (int time = 0; time <= m_depth; time++) {
  //      for (auto & p : *time_duract_enodes[time]) {
  //        Enode* proc = p.second;
  //        // proc->setDecPolarity(l_True);
  //        m_suggestions.push_back(proc);
  //      }
  //    }

      //  for (auto e : m_suggestions)  {
    DREAL_LOG_INFO << "plan_heuristic::getSuggestions(): Suggesting ";
      //                   << (e->getPolarity() == l_True ? "     " : "(not ")
      //                   << e
      //                   << (e->getPolarity() == l_True ? "" : ")")
      //                   << " = "
      //                   << (e->getDecPolarity() == l_True ?
      //                       " True" :
      //                       (e->getDecPolarity() == l_False ? " False" : " Unknown"))
      //                   << endl;
      //  }
    return true;
}
示例#24
0
文件: pop3user.c 项目: swhobbit/UUPC
KWBoolean
commandLoadMailbox(SMTPClient *client,
            struct _SMTPVerb* verb,
            char **operands)
{
   char xmitBuf[XMIT_LENGTH];

/*--------------------------------------------------------------------*/
/*                   Create the final mailbox name                    */
/*--------------------------------------------------------------------*/

   strncpy(client->transaction->mailboxName,
            client->clientName,
            sizeof client->transaction->mailboxName);

   client->transaction->mailboxName[8] = '\0';

   if (expand_path(client->transaction->mailboxName,
                    client->transaction->userp->homedir,
                    client->transaction->userp->homedir,
                    E_mailext) == NULL)
   {
      sprintf(xmitBuf,
              "Internal error, cannot determine mailbox location for %s",
              client->clientName);

      SMTPResponse(client, PR_ERROR_GENERIC, xmitBuf);
      setClientMode(client, P3_AUTHORIZATION);
      return KWFalse;
   }

/*--------------------------------------------------------------------*/
/*                Get any new mail from system mailbox                */
/*--------------------------------------------------------------------*/

   if (! IncludeNew(client->transaction->mailboxName,
                      client->clientName))
   {
      sprintf(xmitBuf,
              "Internal error, unable to append new mail to mailbox %s: %s",
              client->transaction->mailboxName,
              strerror(errno));
      SMTPResponse(client, PR_ERROR_GENERIC, xmitBuf);
      setClientMode(client, P3_AUTHORIZATION);
      return KWFalse;
   }

/*--------------------------------------------------------------------*/
/*         Load the mailbox information, with error checking          */
/*--------------------------------------------------------------------*/

   if (! popBoxLoad(client))
   {

      sprintf(xmitBuf,
              "Internal error, unable to load mailbox %s",
              client->transaction->mailboxName);

      SMTPResponse(client, PR_ERROR_GENERIC, xmitBuf);
      setClientMode(client, P3_AUTHORIZATION);
      return KWFalse;

   } /* if (! popBoxLoad(client)) */

/*--------------------------------------------------------------------*/
/*                     Report our mailbox is open                     */
/*--------------------------------------------------------------------*/

   sprintf(xmitBuf,
           "%s has %ld message(s) (%ld octets)",
           client->clientName,
           client->transaction->messageCount,
           getMessageOctetCount(client->transaction->top, NULL));

   SMTPResponse(client,
                verb->successResponse,
                xmitBuf);

   return KWTrue;

} /* commandLoadMailbox */
示例#25
0
void vfu_chdir( const char *a_new_dir )
{
  char t[MAX_PATH];
  VString target;
  if ( a_new_dir && a_new_dir[0] )
    {
    target = a_new_dir;
    str_fix_path( target );
    }
  else
    {
    target = vfu_hist_get( HID_CHDIR, 0 );
    if (!vfu_get_dir_name( "ChDir to? (TAB, PageUp, PageDown, ^X, ^A)",
                           target, 0 )) 
                           return; /* get_dir_name canceled */
    }
  /* get_dir_name confirmed */  
  /*
  if ( work_path[0] != target[0] && DirTreeChanged && opt.AutoTree ) SaveTree();
  */
  if ( work_mode == WM_ARCHIVE )
    {
    archive_name = "";
    archive_path = "";
    }
  
  vfu_hist_add( HID_CHDIR, work_path );
  char ch = work_path[0];
  if (opt.tree_cd)
    if (!dir_exist( target ))
      {
      int z = 0;
      if ( dir_tree.count() == 0 ) tree_load();
      mb.undef();
      z = tree_find( target, &mb );
      if (z > 1)
        {
        z = vfu_menu_box( 10, 5, "Change dir to..." );
        if (z > -1)
          target = mb.get(z);
        else
          return;
        }
      else
      if (z == 1)
        target = mb.get(0);
      }
  VString str = target; 
  str_cut_spc( str );
  #ifdef _TARGET_GO32_
    if ( str[0] == '/' )
      {
      str_ins_ch( str, 0, ':' );
      str_ins_ch( str, 0, work_path[0] );
      } else
    if ( str[1] == ':' && str[2] == 0 ) /* c: d: e: */
      {
      expand_path( str, t );
      str = t;
      }
    if ( str[1] == ':' && str[2] == '/' )
  #else /* _TARGET_GO32_ -> i.e. _TARGET_UNIX_ here*/
    if (str[0] == '/')
  #endif /* _TARGET_GO32_ */
    { /* root directory */
    target = str;
    }
  else
    {
    str = work_path + str;
    str_fix_path( str );
    target = str_reduce_path( str );
    }
  if (chdir( target ) != 0)
    {
    sprintf( t, "chdir: %s", target.data() );
    say1( t );
    say2errno();
    return;
    }
  else
    {
    work_path = target;
    if ( work_mode == WM_ARCHIVE ) 
      work_mode = WM_NORMAL;
    }
  if ( ch != work_path[0] ) tree_drop(); /* drop tree--it is for another drive*/
  vfu_read_files();
} 
示例#26
0
文件: main.c 项目: osxi/i3bgbar
int main(int argc, char **argv) {
    int opt;
    int option_index = 0;
    char *socket_path = getenv("I3SOCK");
    char *i3_default_sock_path = "/tmp/i3-ipc.sock";

    /* Initialize the standard config to use 0 as default */
    memset(&config, '\0', sizeof(config_t));

    static struct option long_opt[] = {
        { "socket",               required_argument, 0, 's' },
        { "bar_id",               required_argument, 0, 'b' },
        { "help",                 no_argument,       0, 'h' },
        { "version",              no_argument,       0, 'v' },
        { NULL,                   0,                 0, 0}
    };

    while ((opt = getopt_long(argc, argv, "b:s:hv", long_opt, &option_index)) != -1) {
        switch (opt) {
            case 's':
                socket_path = expand_path(optarg);
                break;
            case 'v':
                printf("i3bar version " I3_VERSION " © 2010-2014 Axel Wagner and contributors\n");
                exit(EXIT_SUCCESS);
                break;
            case 'b':
                config.bar_id = sstrdup(optarg);
                break;
            default:
                print_usage(argv[0]);
                exit(EXIT_SUCCESS);
                break;
        }
    }

    if (!config.bar_id) {
        /* TODO: maybe we want -f which will automatically ask i3 for the first
         * configured bar (and error out if there are too many)? */
        ELOG("No bar_id passed. Please let i3 start i3bar or specify --bar_id\n");
        exit(EXIT_FAILURE);
    }

    main_loop = ev_default_loop(0);

    char *atom_sock_path = init_xcb_early();

    if (socket_path == NULL) {
        socket_path = atom_sock_path;
    }

    if (socket_path == NULL) {
        ELOG("No Socket Path Specified, default to %s\n", i3_default_sock_path);
        socket_path = expand_path(i3_default_sock_path);
    }

    init_outputs();
    if (init_connection(socket_path)) {
        /* Request the bar configuration. When it arrives, we fill the config array. */
        i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG, config.bar_id);
    }

    /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main-loop.
     * We only need those watchers on the stack, so putting them on the stack saves us
     * some calls to free() */
    ev_signal *sig_term = smalloc(sizeof(ev_signal));
    ev_signal *sig_int = smalloc(sizeof(ev_signal));
    ev_signal *sig_hup = smalloc(sizeof(ev_signal));

    ev_signal_init(sig_term, &sig_cb, SIGTERM);
    ev_signal_init(sig_int, &sig_cb, SIGINT);
    ev_signal_init(sig_hup, &sig_cb, SIGHUP);

    ev_signal_start(main_loop, sig_term);
    ev_signal_start(main_loop, sig_int);
    ev_signal_start(main_loop, sig_hup);

    /* From here on everything should run smooth for itself, just start listening for
     * events. We stop simply stop the event-loop, when we are finished */
    ev_loop(main_loop, 0);

    kill_child();

    FREE(l_statusline_buffer);
    FREE(r_statusline_buffer);

    clean_xcb();
    ev_default_destroy();

    free_workspaces();

    return 0;
}
示例#27
0
文件: fs.c 项目: COLABORATI/firejail
// blacklist files or directoies by mounting empty files on top of them
void fs_blacklist(const char *homedir) {
	ProfileEntry *entry = cfg.profile;
	if (!entry)
		return;
		
	char *emptydir = create_empty_dir();
	char *emptyfile = create_empty_file();

	while (entry) {
		OPERATION op = OPERATION_MAX;
		char *ptr;

		// process blacklist command
		if (strncmp(entry->data, "bind", 4) == 0)  {
			char *dname1 = entry->data + 5;
			char *dname2 = split_comma(dname1);
			if (dname2 == NULL) {
				fprintf(stderr, "Error: second directory missing in bind command\n");
				entry = entry->next;
				continue;
			}
			struct stat s;
			if (stat(dname1, &s) == -1) {
				fprintf(stderr, "Error: cannot find directories for bind command\n");
				entry = entry->next;
				continue;
			}
			if (stat(dname2, &s) == -1) {
				fprintf(stderr, "Error: cannot find directories for bind command\n");
				entry = entry->next;
				continue;
			}
			
			// mount --bind olddir newdir
			if (arg_debug)
				printf("Mount-bind %s on top of %s\n", dname1, dname2);
			// preserve dname2 mode and ownership
			if (mount(dname1, dname2, NULL, MS_BIND|MS_REC, NULL) < 0)
				errExit("mount bind");
			/* coverity[toctou] */
			if (chown(dname2, s.st_uid, s.st_gid) == -1)
				errExit("mount-bind chown");
			/* coverity[toctou] */
			if (chmod(dname2, s.st_mode) == -1)
				errExit("mount-bind chmod");
				
			entry = entry->next;
			continue;
		}

		// process blacklist command
		if (strncmp(entry->data, "blacklist", 9) == 0)  {
			ptr = entry->data + 10;
			op = BLACKLIST_FILE;
		}
		else if (strncmp(entry->data, "read-only", 9) == 0) {
			ptr = entry->data + 10;
			op = MOUNT_READONLY;
		}			
		else if (strncmp(entry->data, "tmpfs", 5) == 0) {
			ptr = entry->data + 6;
			op = MOUNT_TMPFS;
		}			
		else {
			fprintf(stderr, "Error: invalid profile line %s\n", entry->data);
			entry = entry->next;
			continue;
		}

		// replace home macro in blacklist array
		char *new_name = NULL;
		if (strncmp(ptr, "${HOME}", 7) == 0) {
			if (asprintf(&new_name, "%s%s", homedir, ptr + 7) == -1)
				errExit("asprintf");
			ptr = new_name;
		}

		// expand path macro - look for the file in /bin, /usr/bin, /sbin and  /usr/sbin directories
		if (strncmp(ptr, "${PATH}", 7) == 0) {
			expand_path(op, "/bin", ptr + 7, emptydir, emptyfile);
			expand_path(op, "/sbin", ptr + 7, emptydir, emptyfile);
			expand_path(op, "/usr/bin", ptr + 7, emptydir, emptyfile);
			expand_path(op, "/usr/sbin", ptr + 7, emptydir, emptyfile);
		}
		else
			globbing(op, ptr, emptydir, emptyfile);

		if (new_name)
			free(new_name);
		entry = entry->next;
	}
}
示例#28
0
	void load_preferences()
	{
		std::string path;
		if(preferences_path_.empty()) {
#if defined( _WINDOWS )
		preferences_path_ = winPrefs.GetPreferencePath();
		save_file_path_ = winPrefs.GetSaveFilePath();
		auto_save_file_path_ = winPrefs.GetAutoSaveFilePath();
		path = preferences_path_;
#else
		path = PREFERENCES_PATH;
#endif // defined( _WINDOWS )
		} else {
			path = preferences_path_;
		}
		expand_path(path);
		if(!sys::file_exists(path + "preferences.cfg")) {
			return;
		}

		variant node;
		
		try {
			node = json::parse_from_file(path + "preferences.cfg");
		} catch(json::parse_error&) {
			return;
		}

		unique_user_id = node["user_id"].as_int(0);

		use_joystick_ = node["joystick"].as_bool(use_joystick_);
		variant show_control_rects = node["show_iphone_controls"];
		if(show_control_rects.is_null() == false) {
			show_iphone_controls_ = show_control_rects.as_bool(show_iphone_controls_);
		}

		no_sound_ = node["no_sound"].as_bool(no_sound_);
		no_music_ = node["no_music"].as_bool(no_music_);
		reverse_ab_ = node["reverse_ab"].as_bool(reverse_ab_);

		sound::set_music_volume(node["music_volume"].as_int(1000)/1000.0);
		sound::set_sound_volume(node["sound_volume"].as_int(1000)/1000.0);

		const variant registry_node = node["registry"];
		if(registry_node.is_null() == false) {
			game_registry::instance().set_contents(registry_node);
		}

		if(node["code_editor"].is_map()) {
			external_code_editor_ = node["code_editor"];
		}

#if !TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
		controls::set_sdlkey(controls::CONTROL_UP, static_cast<SDLKey>(node["key_up"].as_int(SDLK_UP)));
		controls::set_sdlkey(controls::CONTROL_DOWN, static_cast<SDLKey>(node["key_down"].as_int(SDLK_DOWN)));
		controls::set_sdlkey(controls::CONTROL_LEFT, static_cast<SDLKey>(node["key_left"].as_int(SDLK_LEFT)));
		controls::set_sdlkey(controls::CONTROL_RIGHT, static_cast<SDLKey>(node["key_right"].as_int(SDLK_RIGHT)));
		controls::set_sdlkey(controls::CONTROL_ATTACK, static_cast<SDLKey>(node["key_attack"].as_int(SDLK_d)));
		controls::set_sdlkey(controls::CONTROL_JUMP, static_cast<SDLKey>(node["key_jump"].as_int(SDLK_a)));
		controls::set_sdlkey(controls::CONTROL_TONGUE, static_cast<SDLKey>(node["key_tongue"].as_int(SDLK_s)));
#endif
	}
示例#29
0
int vfu_get_dir_name( const char *prompt, VString &target, int should_exist )
{ 
  int res = -1;
  /*
  #ifdef _TARGET_UNIX_
  leaveok(stdscr, FALSE);
  #endif
  */
  VArray dir_list;
   
  say1(prompt); 
  say2(""); 
  
  int pos = 0; 
  int page = 0;
  int ch = 0; 
  
  int insert = 1;
  int firsthit = 1;
  
  pos = str_len( target );

  //------------------------------------------------------------------
  
  con_cshow();
  say2( target, firsthit ? cINPUT2 : cINPUT );
  while(1) 
    {
    int mx = con_max_x() - 1;
    VString target_out = target;
    if ( (pos < page) || (pos+1 > page + mx) || (page > 0 && pos == page) ) 
      page = pos - mx / 2;
    if ( page < 0 ) page = 0;

    str_trim_left( target_out, page );
    str_sleft( target_out, mx );
    str_pad( target_out, -mx );
    if ( page > 0 )
      str_set_ch( target_out, 0, '<' );
    if ( str_len( target ) - page > mx )
      str_set_ch( target_out, mx-1, '>' );
    
    say2( target_out, firsthit ? cINPUT2 : cINPUT );
    con_xy( pos-page+1, con_max_y() );

    
    if (ch == 0) ch = con_getch();
    if (ch == '\\') ch = '/'; /* dos hack :)) */
    if ( ch == '/' && str_find( target, '/' ) == -1 && target[0] == '~' )
      {
      target = tilde_expand( target );
      str_fix_path( target );
      pos = str_len( target );
      ch = 0;
      }
      
    if ((ch == 8 || ch == KEY_BACKSPACE) && pos > 0) 
      { 
      pos--; 
      str_del( target, pos, 1 );
      } 
    else
    if (ch == KEY_CTRL_A && str_len( target ) > 0)
      {
      int z = str_len( target )-1;
      if ( str_get_ch(target, z) == '/' ) z--;
      while ( z > 0 && str_get_ch(target,z) != '/' ) z--;
      z++;
      str_sleft(target,z);
      pos = z;
      }
    else
    if ( ch == 9 && str_len( target ) > 0)
      { 
      int z; 
      dir_list.undef();
      VString dmain; /* main/base path */
      VString dtail; /* item that should be expanded/glob */
      
      dmain = str_file_path( target );
      dtail = str_file_name_ext( target );
      
      /*
      int lastslash = str_rfind(target, '/');
      if ( lastslash == -1 ) 
        {
        dmain = "";
        dtail = target;
        }
      else
        {
        dmain = target;
        dtail = target;
        str_sleft( dmain, lastslash+1 );
        str_trim_left( dtail, lastslash+1 );
        }
      */
      
      __glob_gdn( dmain, dtail, dir_list );
  
      z = dir_list.count()-1;
      if (dir_list.count()) 
        {
        if ( dir_list.count() > 1)
          {
          int mc = 0; /* match count        */
          int mi = 0; /* match letter index */
          while(4)
            {
            mc = 0;
            int li; /* counter */
            for ( li = 0; li < dir_list.count(); li++ )
              {
              if ( str_get_ch( dir_list[ 0], mi ) == 
                   str_get_ch( dir_list[li], mi ) )
                mc++;
              }
            if ( mc != dir_list.count() )
              break;
            mi++;
            }
          target.setn( dmain + dir_list[0], str_len( dmain ) + mi );
          pos = str_len( target );
          say2( target, cINPUT );
          con_xy( pos+1, con_max_y() );
          
          vfu_beep();
          ch = con_getch();
          if ( ch != 9 ) { dir_list.undef(); continue; }
          dir_list.sort();
          con_chide();
          z = vfu_menu_box( 10, 5, "Complete...", &dir_list );
          con_cshow();
          ch = 0;
          }
        else
          ch = 0;
        if ( z != -1 )
          {
          while( str_len( target ) > 0 && target[-1] != '/' )
            str_chop( target );
          target += dir_list[z];
          }
        
        pos = str_len( target );
        
        dir_list.undef();
        if (ch != 0) continue;
        }
      else
        { /* no match found -- cannot complete */
        vfu_beep();
        }
      } 
    else 
    if (ch == 13)
      { 
      res = 1;
      break; 
      } 
    else 
    if (ch == 27) 
      { 
      target = "";
      res = 0;
      break; 
      } 
    if (ch == KEY_CTRL_U)
      { 
      target = "";
      pos = 0;
      }
    else
    if (ch == KEY_CTRL_X)
      {
        char t[MAX_PATH];
        if ( target[0] == '~' )
          target = tilde_expand( target );
        expand_path( target, t );
        str_fix_path( t );
        target = t;
        pos = str_len( target );
      }
    else 
    if (ch >= 32 && ch <= 255 ) // && pos < 70) 
      { 
      if (firsthit) 
        {
        target = "";
        pos = 0;
        }
      if (!insert) str_del( target, pos, 1 );
      str_ins_ch( target, pos, ch );
      pos++;
      } else
    if( ch == KEY_LEFT  )
      {
      if (pos > 0)
        pos--;
      } else
    if( ch == KEY_RIGHT )
      {
      if (pos < str_len( target ))
        pos++;
      } else
    if ( ch == KEY_IC   ) insert = !insert; else
    if ( ch == KEY_HOME ) pos = 0; else
    if ( ch == KEY_END  ) pos = str_len(target); else
    if ( ch == KEY_DC  && pos < str_len(target) ) 
       str_del( target, pos, 1 ); else
    if ( ch == KEY_NPAGE || ch == KEY_PPAGE )
      {
      con_chide();
      int zz = vfu_hist_menu( 5, 5, ( ch == KEY_PPAGE ) ? "Dir Entry History" : "ChDir History", 
                              ( ch == KEY_PPAGE ) ? HID_GETDIR : HID_CHDIR );
      con_cshow();
      if (zz != -1)
        {
        const char* pc = vfu_hist_get( ( ch == KEY_PPAGE ) ? HID_GETDIR : HID_CHDIR, zz );
        if ( pc )
          {
          target = pc;
          pos = str_len( target );
          }
        }
      }
    ch = 0; 
    firsthit = 0;
    }
  con_chide();
  
  //------------------------------------------------------------------
  str_cut_spc( target );
  if ( res == 1 && target[0] == '~' )
    {
    target = tilde_expand( target );
    str_fix_path( target );
    }
/*  
  if ( target.len() > 0 )
    { 
    // well this tmp is kind of s... ama k'vo da pravi chovek :)
    // FIXME: dos version?
    if ( __ExpandGetDirName && target[0] != '/'
       #ifdef _TARGET_GO32_
       && !( target[1] == ':' && target[2] == '/' )
       #endif
       )
      target = CPath + target;
    StrFixPath( target ); // add trailing slash if not exist
    } 
*/    
  /*
  #ifdef _TARGET_UNIX_
  leaveok(stdscr, TRUE);
  #endif
  */
  if ( res == 1 && str_len( target ) > 0 && should_exist && !dir_exist( target ))
    {
    vfu_beep();
    int ch = tolower( vfu_ask( "Directory does not exist! Create? "
                               "( ENTER=Yes, ESC=cancel )",
                               "\033\rcC" ));
    if ( ch == 27 ) 
      {
      res = 0;
      target = ""; 
      }
    else
    if ( ch == 13 )
       if (make_path( target ))
         {
         if(tolower(
            vfu_ask( "Cannot create path! ( ESC=cancel, C=continue-anyway )", 
            "\033Cc" )) == 27)
            {
            res = 0;
            target = "";
            }
         }
    }
  
  say1(" "); 
  say2(" "); 
  if ( str_len( target ) > 0)
    {
    str_fix_path( target );
    vfu_hist_add( HID_GETDIR, target );
    }
    
  str_cut_spc( target );
  
  ASSERT( res == 0 || res == 1 );
  return res;
} 
示例#30
0
文件: preload.c 项目: dedeckeh/mwan
/**
 * @brief Verify if socket() should be redirected.
 *
 * Find the executable that is currently running and expand it's path, then
 * check the configuration file for an extry specifying this executable.
 * If a match is found, the command line arguments are string matched with
 * the config file, if an argument match is specified for the executable.
 *
 * If all the tests are positive, indicate that redirection is required.
 *
 * @return true if redirection is required.
 */
static int should_redirect_socket()
{
    char cmdline[256];
    int cmdlen;
    int fd= -1;
    int ret= -1;
    char qualified_path[PATH_MAX];
    int len;
    char current[PATH_MAX];
    struct stat st;
    FILE *config= NULL;
    char cmd[256];
    char *args;

    // check if an environment variable SO_MARK is defined and that
    // we can convert the first field to a hex number
    args= getenv("SO_MARK");
    if (args) {
        if (sscanf(args, "%x", &fwmark) == 1)
            return 1;
    }

    // quick check for config file
    if (access(PRELOAD_CONFIG, R_OK) != 0)
        goto err;

    // get ARGV[0] from proc
    fd= open("/proc/self/cmdline", O_RDONLY);
    if (fd == -1) {
        perror("open");
        goto err;
    }

    cmdlen= read(fd, cmdline, sizeof(cmdline)-1);
    close(fd);
    fd= -1;
    if (cmdlen <= 0) {
        perror("read");
        goto err;
    }
    cmdline[cmdlen] = 0; // NULL terminate
    len = strlen(cmdline);
    if (len+1 > cmdlen)
        args= NULL;
    else
        args= &cmdline[len+1];

    /* Is there a path component specified?
     * /xxxx
     * ../xxx
     * ./xx
     */
    if (cmdline[0] == '/' ||
            (cmdline[0] == '.' && (
                 (len >= 2 && cmdline[1] == '.' && cmdline[2] == '/') ||
                 (len >= 1 && cmdline[1] == '/'))
            )
       )
        ret= expand_path(cmdline, sizeof(qualified_path), qualified_path);
    else {
        // need to resolve via PATH
        char *path= getenv("PATH");
        char *pe;

        if (!path)
            goto err;

        while(path && path != '\0') {
            pe= strchr(path, ':');
            if (pe) {
                memcpy(current, path, pe-path);
                current[pe-path]= '\0';
                path= pe+1;

                // skip empty PATH part, ie. ::
                if (!strlen(current))
                    continue;
            } else {
                strcpy(current, path);
                path= NULL;
            }

            // append command to path component
            if (strlcat(current, "/", sizeof(current)) >= sizeof(current))
                goto err;
            if (strlcat(current, cmdline, sizeof(current)) >= sizeof(current))
                goto err;

            ret= expand_path(current, sizeof(qualified_path), qualified_path);
            if (ret == 0 && !access(qualified_path, X_OK) &&
                    !stat(qualified_path, &st) && S_ISREG(st.st_mode)) {

                // executable file found in the path
                ret= 0;
                break;
            }
        }

    }
    // nothing found or expansion failed
    if (ret)
        goto err;

    ret= -1;

    // rebuild commandline of executable by replacing the NUL bytes
    // by spaces
    if (args) {
        char *ptr = strchr(args, 0);
        while(ptr < &cmdline[cmdlen]) {
            *ptr= ' ';
            ptr = strchr(ptr, 0);
        }
    }

    // qualified_path contains the executable we need to check
    // now check versus local db.
    config= fopen(PRELOAD_CONFIG, "r");
    if (!config)
        goto err;

    while(!feof(config)) {
        int matchlen;
        char *p_match;
        char match[256];

        // read exe name and mark number
        if (fscanf(config, "%255s %x", cmd, &fwmark) != 2)
            goto err;

        // read rest of the line
        if (fgets(match, sizeof(match), config) == NULL)
            goto err;

        // strip trailing CR and whitespaces
        matchlen = strlen(match);
        while (matchlen && (match[matchlen-1] == '\n' || match[matchlen-1] == '\r' || match[matchlen-1] == ' '))
            match[--matchlen] = '\0';

        // skip leading spaces;
        p_match= match;
        while(p_match && *p_match == ' ') {
            p_match++;
            matchlen--;
        }

        // does command match what is specified in the config?
        if (!strcmp(qualified_path, cmd)) {

            // are the arguments also a match?
            if ( matchlen == 0 || (matchlen && strstr(args, p_match))) {
                ret= 0;
                break;
            }
        }
    }

err:
    if (config)
        fclose(config);

    if (fd != -1)
        close(fd);

    return ret == 0;
}