void AppWindow::on_drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context, 
	int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
	{
	
#ifdef DEBUG	
	std::cout << "ON_DRAG_DATA_RECEIVED: type: " << selection_data.get_data_type() << std::endl;
	std::cout << "ON_DRAG_DATA_RECEIVED: data: " << selection_data.get_data_as_string() << std::endl;
#endif // DEBUG

	if (selection_data.get_data_type() == "text/uri-list")
		{
		std::list<Glib::ustring> new_filenames = selection_data.get_uris();
			
		const std::list<Glib::ustring>::iterator begin = new_filenames.begin();
		const std::list<Glib::ustring>::iterator end = new_filenames.end();
		std::list<Glib::ustring>::iterator iter = new_filenames.begin();
		int counter = 0;
		
		while( iter != end )
			{
			// we erase the protocol in front of the filename
			if( (*iter).find(':') != std::string::npos )
				(*iter).erase(0, (*iter).find(':')+3);
			
			// unescape the URI
			char * tempfilename = curl_unescape( iter->c_str(), 0);
			(*iter) = tempfilename;
			// curl requires this to be freed like this
			curl_free( tempfilename );

#ifdef DEBUG			
	std::cout << "ON_DRAG_DATA_RECEIVED: URI: " << *iter << std::endl;
#endif // DEBUG

			iter++;
			counter++;
			}
		open_list( new_filenames, counter );
		}
	
	// if we're given plain text, maybe it's still an uri or a filename, we should better check
	// ImageManager.OpenFiles is safe anyway	
	else if( selection_data.get_data_type() == "text/plain" )
		{
			std::string data = selection_data.get_data_as_string();
			data.erase( data.find('\n') ); // erase any newlines, all we can do is one file
			// we erase the protocol in front of the filename
			if( data.find(':') != std::string::npos )
				data.erase(0, data.find(':')+3);
			
			// unescape the URI
			char * tempfilename = curl_unescape( data.c_str(), 0);
			data = tempfilename;
			// curl requires this to be freed like this
			curl_free( tempfilename );
			
			open_new_file( data );
		} 	
	context->drag_finish(true, false, time);
	}
std::vector<std::string> lggBeamMaps::getColorsFileNames()
{

	std::vector<std::string> names;	
	std::string path_name(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "beamsColors", ""));
	bool found = true;			
	while(found) 
	{
		std::string name;
		found = gDirUtilp->getNextFileInDir(path_name, "*.xml", name, false);
		if(found)
		{

			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			names.push_back(name);

			//LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			//loadPreset(unescaped_name,FALSE);
		}
	}
	std::string path_name2(gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "beamsColors", ""));
	found = true;			
	while(found) 
	{
		std::string name;
		found = gDirUtilp->getNextFileInDir(path_name2, "*.xml", name, false);
		if(found)
		{

			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			names.push_back(name);

			//LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			//loadPreset(unescaped_name,FALSE);
		}
	}
	return names;



}
void LLWaterParamManager::loadAllPresets(const std::string& file_name)
{
	std::string path_name(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/water", ""));
	LL_INFOS2("AppInit", "Shaders") << "Loading Default water settings from " << path_name << LL_ENDL;
			
	bool found = true;			
	LLDirIterator app_settings_iter(path_name, "*.xml");
	while(found) 
	{
		std::string name;
		found = app_settings_iter.next(name);
		if(found)
		{

			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			loadPreset(unescaped_name,FALSE);
		}
	}

	// And repeat for user presets, note the user presets will modify any system presets already loaded

	std::string path_name2(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/water", ""));
	LL_INFOS2("AppInit", "Shaders") << "Loading User water settings from " << path_name2 << LL_ENDL;
			
	found = true;			
	LLDirIterator user_settings_iter(path_name2, "*.xml");
	while(found) 
	{
		std::string name;
		found = user_settings_iter.next(name);
		if(found)
		{
			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			loadPreset(unescaped_name,FALSE);
		}
	}

}
void AscentDayCycleManager::loadPresets(const std::string& file_name)
{
	std::string path_name(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/days", ""));
	LL_INFOS2("AppInit", "Shaders") << "Loading Default Day Cycle preset from " << path_name << LL_ENDL;
			
	bool found = true;			
	while(found) 
	{
		std::string name;
		found = gDirUtilp->getNextFileInDir(path_name, "*.xml", name, false);
		if(found)
		{

			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			loadPreset(unescaped_name,FALSE);
		}
	}

	// And repeat for user presets, note the user presets will modify any system presets already loaded

	std::string path_name2(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", ""));
	LL_INFOS2("AppInit", "Shaders") << "Loading User Daycycle preset from " << path_name2 << LL_ENDL;
			
	found = true;			
	while(found) 
	{
		std::string name;
		found = gDirUtilp->getNextFileInDir(path_name2, "*.xml", name, false);
		if(found)
		{
			name=name.erase(name.length()-4);

			// bugfix for SL-46920: preventing filenames that break stuff.
			char * curl_str = curl_unescape(name.c_str(), name.size());
			std::string unescaped_name(curl_str);
			curl_free(curl_str);
			curl_str = NULL;

			LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			loadPreset(unescaped_name,FALSE);
		}
	}

}
Beispiel #5
0
url_func_result url_fragment(const char *url, char **result)
{
	url_func_result status;
	struct url_components components;

	assert(url);

	status = url_get_components(url, &components);
	if (status == URL_FUNC_OK) {
		if (!components.fragment) {
			status = URL_FUNC_FAILED;
		} else {
			char *frag = curl_unescape(components.fragment,
					strlen(components.fragment));
			if (!frag) {
				status = URL_FUNC_NOMEM;
			} else {
				*result = strdup(frag);
				if (!(*result))
					status = URL_FUNC_NOMEM;
				curl_free(frag);
			}
		}
	}

	url_destroy_components(&components);
	return status;
}
Beispiel #6
0
char *fmt_unescape(char *str)
{
    if (str == NULL)
        return NULL;

    return curl_unescape(str, 0);
}
char* debug_curl_unescape(char const* url, int length)
{
  char* ret;
  ret = curl_unescape(url, length);
  Dout(dc::curl, "curl_unescape(\"" << url << "\", " << length << ") = \"" << ret << '"');
  return ret;
}
Beispiel #8
0
/* deprecated */
int l_unescape(lua_State *L) {
  size_t length;
  const char *url = luaL_checklstring(L, 1, &length);
  char *rurl = curl_unescape(url, length);
  lua_pushstring(L, rurl);
  curl_free(rurl);
  return 1;
}
// static
std::string LLURLSimString::unescapeRegionName(std::string region_name)
{
	std::string result;
	char* curlstr = curl_unescape(region_name.c_str(), region_name.size());
	result = std::string(curlstr);
	curl_free(curlstr);
	return result;
}
Beispiel #10
0
char *
tr_http_unescape( const char * str, int len )
{
    char * tmp = curl_unescape( str, len );
    char * ret = tr_strdup( tmp );
    curl_free( tmp );
    return ret;
}
Beispiel #11
0
std::string unescape_name(const std::string& name)
{
	// bugfix for SL-46920: preventing filenames that break stuff.
	char * curl_str = curl_unescape(name.c_str(), name.size());
	std::string unescaped_name(curl_str);
	curl_free(curl_str);
	curl_str = NULL;

	return unescaped_name;
}
Beispiel #12
0
/* 
 * get_range_query
 *   Parses the GET|POST request and extracts the 'range query'
 *   string.
 * Args: 
 *   - FCGX_Request * (of the thread)
 *   - char * (location where the 'range query' is written)
 * Returns:
 *   - O (expand)
 *   - 1 (list)
 */
static int get_range_query(FCGX_Request *rq, char *query) {
  char *method = FCGX_GetParam("REQUEST_METHOD", rq->envp);
  char *script_name = FCGX_GetParam("SCRIPT_NAME", rq->envp);
  int list = -1;			/* list or expand? */
  char *decoded_url;

  /* accept only GET && POST */
  if(strcmp(method, "GET") != 0 && strcmp(method, "POST") != 0) {
    invalid_request(rq, "401", "Only GET || POST Request_Method Allowed");
  } else if (strcmp(method, "GET") == 0) {
    decoded_url = curl_unescape(FCGX_GetParam("QUERY_STRING", rq->envp), 0);
    strcpy(query, decoded_url);
    curl_free(decoded_url);
  } else if (strcmp(method, "POST") == 0) {
    /* TODO: i might have to loop this in while and do a strcat + realloc if i need to increase
       string length at runtime */
    FCGX_GetStr(query, QUERY_STR_SIZE, rq->in);
  }

  /* we have two cases here
   *  - /range/list?(.*)
   *  - /range/expand?(.*)
   * SCRIPT_NAME == /range/list || /range/expand
   * QUERY_STRING == (.*) (in our case query has it)
   * strtok() for SCRIPT_NAME and decide which kind it is, 
   * for QUERY_STRING is passed as is.
   */
  if (strlen(query) == 0) {
    invalid_request(rq, "402", "No Query String Found");
    return 0;
  }

  /* list ? */
  list = strcmp(script_name, "/range/list") == 0 ? 1 : -1;
  
  /* if not list, but is expand */
  if (list != 1 && strcmp(script_name, "/range/expand") == 0) 
    list = 0;
  
  /* neither list nor expand */
  if (list == -1) {
    invalid_request(rq, "403", "Expects /range/list?... or /range/expand?...");
    return 0;
  }
  
  /*
  FCGX_FPrintF(rq->out,
	       "Content-type: text/plain\r\n"
	       "foo: bar\r\n"
	       "\r\n");
  FCGX_FPrintF(rq->out, "List (%d) Query: (%s) Script: (%s)\n", list, query, script_name);
  */

  return list;
}
Beispiel #13
0
static char *url_to_path(const char *url)
{
	char *url_path = curl_unescape(url, 0);
	char *path;

	/* return the absolute path including leading / */
	path = strdup(url_path + (FILE_SCHEME_PREFIX_LEN - 1));
	curl_free(url_path);

	return path;
}
Beispiel #14
0
	strings_t
	Client::list(std::string remote_directory) noexcept
	{
		auto clientImpl = GetImpl(this);
		bool is_existed = this->check(remote_directory);
		if (!is_existed) return strings_t();

		bool is_directory = this->is_dir(remote_directory);
		if (!is_directory) return strings_t();
		auto target_urn = Urn(clientImpl->webdav_root, true) + remote_directory;
		target_urn = Urn(target_urn.path(), true);

		Header header = {
				"Accept: */*",
				"Depth: 1"
		};

		Data data = { 0, 0, 0 };

		Request request(clientImpl->options());

		auto url = clientImpl->webdav_hostname + target_urn.quote(request.handle);

		request.set(CURLOPT_CUSTOMREQUEST, "PROPFIND");
		request.set(CURLOPT_URL, url.c_str());
		request.set(CURLOPT_HTTPHEADER, (struct curl_slist *)header.handle);
		request.set(CURLOPT_HEADER, 0);
		request.set(CURLOPT_WRITEDATA, (size_t)&data);
		request.set(CURLOPT_WRITEFUNCTION, (size_t)Callback::Append::buffer);

		bool is_performed = request.perform();

		if (!is_performed) return strings_t();

		strings_t resources;

		pugi::xml_document document;
		document.load_buffer(data.buffer, (size_t)data.size);
		auto multistatus = document.select_single_node("d:multistatus").node();
		auto responses = multistatus.select_nodes("d:response");
		for(auto response : responses)
		{
			pugi::xml_node href = response.node().select_single_node("d:href").node();
			std::string encode_file_name = href.first_child().value();
			std::string resource_path = curl_unescape(encode_file_name.c_str(), (int) encode_file_name.length());
			auto target_path = target_urn.path();
			if (resource_path == target_path) continue;
			Urn resource_urn(resource_path);
			resources.push_back(resource_urn.name());
		}

		return resources;
	}
Beispiel #15
0
/* Unescapes URL encoding in strings */
static int lcurl_unescape(lua_State* L)
{
	if (!lua_isnil(L, 1))
	{
		const char* s=luaL_checkstring(L, 1);
		lua_pushstring(L, curl_unescape(s, (int)lua_strlen(L, 1)));
		return 1;
	} else
	{
		luaL_argerror(L, 1, "string parameter expected");
	}
	return 0;
}
Beispiel #16
0
/* exported interface documented in utils/url.h */
nserror url_unescape(const char *str, int length, char **result)
{
	char *curlstr;
	char *retstr;

	curlstr = curl_unescape(str, length);
	if (curlstr == NULL) {
		return NSERROR_NOMEM;
	}

	retstr = strdup(curlstr);
	curl_free(curlstr);

	if (retstr == NULL) {
		return NSERROR_NOMEM;
	}

	*result = retstr;
	return NSERROR_OK;
}
void AppWindow::on_drag_data_received(const Glib::RefPtr<Gdk::DragContext>& context, int x, int y, const Gtk::SelectionData& selection_data, guint info, guint time)
	{  
    // this is totally ridiculous, but so be it!
	// we erase the protocol in front of the filename
	// using std::string because Glib::ustring throws a conversion error for some reason
	std::string string_filename = selection_data.get_data_as_string();
	string_filename.erase(0, string_filename.find(':')+3); 

	//convert to char* and unescape
	char * temp_filename = curl_unescape( string_filename.c_str(), 0);
	string_filename = temp_filename;
	// curl requires this to be freed
	curl_free( temp_filename );
	
	//let's remove any \n and \r that are typical of URI's
	if ( string_filename.find('\n') != Glib::ustring::npos )
		string_filename.erase( string_filename.find('\n'), 1 );
	if ( string_filename.find('\r') != Glib::ustring::npos )
		string_filename.erase( string_filename.find('\r'), 1 );

	open_new_file( string_filename );
	context->drag_finish(false, false, time);
	}
// "inworldz://simname/x/y/z" -> "simname/x/y/z"
// (actually .*//foo -> foo)
// static
void LLURLSimString::setString(const std::string& sim_string)
{
	sInstance.mSimString.clear();
	sInstance.mSimName.clear();
	sInstance.mParseState = NOT_PARSED;
	if (sim_string == sLocationStringHome)
	{
		gSavedSettings.setBOOL("LoginLastLocation", FALSE);
	}
	else if (sim_string == sLocationStringLast)
	{
		gSavedSettings.setBOOL("LoginLastLocation", TRUE);
	}
	else
	{
		char* curlstr = curl_unescape(sim_string.c_str(), sim_string.size());
		std::string tstring = std::string(curlstr);
		curl_free(curlstr);
		std::string::size_type idx = tstring.find("//");
		idx = (idx == std::string::npos) ? 0 : idx+2;
		sInstance.mSimString = tstring.substr(idx);
	}
}
Beispiel #19
0
/*
 * Curl_file_connect() gets called from Curl_protocol_connect() to allow us to
 * do protocol-specific actions at connect-time.  We emulate a
 * connect-then-transfer protocol and "connect" to the file here
 */
CURLcode Curl_file_connect(struct connectdata *conn)
{
  char *real_path = curl_unescape(conn->path, 0);
  struct FILEPROTO *file;
  int fd;
#if defined(WIN32) || defined(MSDOS) || defined(__EMX__)
  int i;
  char *actual_path;
#endif

  if(!real_path)
    return CURLE_OUT_OF_MEMORY;

  file = (struct FILEPROTO *)calloc(sizeof(struct FILEPROTO), 1);
  if(!file) {
    free(real_path);
    return CURLE_OUT_OF_MEMORY;
  }

  conn->proto.file = file;

#if defined(WIN32) || defined(MSDOS) || defined(__EMX__)
  /* If the first character is a slash, and there's
     something that looks like a drive at the beginning of
     the path, skip the slash.  If we remove the initial
     slash in all cases, paths without drive letters end up
     relative to the current directory which isn't how
     browsers work.

     Some browsers accept | instead of : as the drive letter
     separator, so we do too.

     On other platforms, we need the slash to indicate an
     absolute pathname.  On Windows, absolute paths start
     with a drive letter.
  */
  actual_path = real_path;
  if ((actual_path[0] == '/') &&
      actual_path[1] &&
      (actual_path[2] == ':' || actual_path[2] == '|'))
  {
    actual_path[2] = ':';
    actual_path++;
  }

  /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
  for (i=0; actual_path[i] != '\0'; ++i)
    if (actual_path[i] == '/')
      actual_path[i] = '\\';

  fd = open(actual_path, O_RDONLY | O_BINARY);  /* no CR/LF translation! */
  file->path = actual_path;
#else
  fd = open(real_path, O_RDONLY);
  file->path = real_path;
#endif
  file->freepath = real_path; /* free this when done */

  if(!conn->data->set.upload && (fd == -1)) {
    failf(conn->data, "Couldn't open file %s", conn->path);
    Curl_file_done(conn, CURLE_FILE_COULDNT_READ_FILE);
    return CURLE_FILE_COULDNT_READ_FILE;
  }
  file->fd = fd;

  return CURLE_OK;
}
/* ****************************************************************************
*
* templateNotify - 
*
* This function performs the necessary substitutions according to the template of
* subscription to form the desired notification and send it to the endpoint specified
* in the subscription.
* 
* 
*/
static bool templateNotify
(
  const SubscriptionId&            subscriptionId,
  const ContextElement&            ce,
  const ngsiv2::HttpInfo&          httpInfo,
  const std::string&               tenant,
  const std::string&               xauthToken,
  const std::string&               fiwareCorrelator,
  RenderFormat                     renderFormat,
  const std::vector<std::string>&  attrsOrder
)
{
  Verb                                verb = httpInfo.verb;
  std::string                         method;
  std::string                         url;
  std::string                         payload;
  std::string                         mimeType;
  std::map<std::string, std::string>  qs;
  std::map<std::string, std::string>  headers;


  //
  // 1. Verb/Method
  //
  if (verb == NOVERB)
  {
    // Default verb/method is POST
    verb = POST;
  }
  method = verbName(verb);


  //
  // 2. URL
  //
  macroSubstitute(&url, httpInfo.url, ce);


  //
  // 3. Payload
  //
  if (httpInfo.payload == "")
  {
    NotifyContextRequest   ncr;
    ContextElementResponse cer;
    
    cer.contextElement = ce;
    ncr.subscriptionId = subscriptionId;
    ncr.contextElementResponseVector.push_back(&cer);
    payload  = ncr.toJson(renderFormat, attrsOrder);
    mimeType = "application/json";
  }
  else
  {
    macroSubstitute(&payload, httpInfo.payload, ce);
    char* pload  = curl_unescape(payload.c_str(), payload.length());
    payload      = pload;
    renderFormat = NGSI_V2_CUSTOM;
    mimeType     = "text/plain";  // May be overridden by 'Content-Type' in 'headers'
    free(pload);
  }


  //
  // 4. URI Params (Query Strings)
  //
  for (std::map<std::string, std::string>::const_iterator it = httpInfo.qs.begin(); it != httpInfo.qs.end(); ++it)
  {
    std::string key   = it->first;
    std::string value = it->second;

    macroSubstitute(&key,   it->first, ce);
    macroSubstitute(&value, it->second, ce);
    if ((value == "") || (key == ""))
    {
      // To avoid e.g '?a=&b=&c='
      continue;
    }
    qs[key] = value;
  }


  //
  // 5. HTTP Headers
  //
  for (std::map<std::string, std::string>::const_iterator it = httpInfo.headers.begin(); it != httpInfo.headers.end(); ++it)
  {
    std::string key   = it->first;
    std::string value = it->second;

    macroSubstitute(&key,   it->first, ce);
    macroSubstitute(&value, it->second, ce);

    if (key == "")
    {
      // To avoid empty header name
      continue;
    }

    headers[key] = value;
  }


  //
  // 6. Split URI in protocol, host, port and path
  //
  std::string  protocol;
  std::string  host;
  int          port;
  std::string  uriPath;

  if (!parseUrl(url, host, port, uriPath, protocol))
  {
    LM_E(("Runtime Error (not sending NotifyContextRequest: malformed URL: '%s')", httpInfo.url.c_str()));
    return false;
  }


  //
  // 7. Add URI params from template to uriPath
  //
  std::string  uri = uriPath;

  if (qs.size() != 0)
  {
    uri += "?";

    int ix = 0;
    for (std::map<std::string, std::string>::iterator it = qs.begin(); it != qs.end(); ++it)
    {
      if (ix != 0)
      {
        uri += "&";
      }

      uri += it->first + "=" + it->second;
      ++ix;
    }
  }


  //
  // 8. Send the request
  //
  //    NOTE: the HTTP headers are sent to httpRequestSend via parameter 'extraHeaders'
  //
  std::string  out;
  int          r;

  r = httpRequestSend(host,
                      port,
                      protocol,
                      method,
                      tenant,
                      ce.entityId.servicePath,
                      xauthToken,
                      uri,
                      mimeType,
                      payload,
                      fiwareCorrelator,
                      renderFormatToString(renderFormat),
                      true,                // Use Rush if CLI '--rush' allows it
                      true,                // wait for response
                      &out,
                      headers,
                      "application/json",  // Accept Format
                      -1);                 // Timeout in milliseconds, depends on CLI '-httpTimeout'

  if (r == 0)
  {
    statisticsUpdate(NotifyContextSent, JSON);
    alarmMgr.notificationErrorReset(url);
    return true;
  }

  return false;
}
Beispiel #21
0
	dict_t
	Client::info(std::string remote_resource) noexcept
	{
		auto clientImpl = GetImpl(this);
		auto root_urn = Urn(clientImpl->webdav_root, true);
		auto target_urn = root_urn + remote_resource;

		Header header = {
				"Accept: */*",
				"Depth: 1"
		};

		Data data = { 0, 0, 0 };

		Request request(clientImpl->options());

		auto url = clientImpl->webdav_hostname + target_urn.quote(request.handle);

		request.set(CURLOPT_CUSTOMREQUEST, "PROPFIND");
		request.set(CURLOPT_URL, url.c_str());
		request.set(CURLOPT_HTTPHEADER, (struct curl_slist *)header.handle);
		request.set(CURLOPT_WRITEDATA, (size_t)&data);
		request.set(CURLOPT_WRITEFUNCTION, (size_t)Callback::Append::buffer);

		bool is_performed = request.perform();

		if (!is_performed) return dict_t();

		pugi::xml_document document;
		document.load_buffer(data.buffer, (size_t)data.size);
		auto multistatus = document.select_single_node("d:multistatus").node();
		auto responses = multistatus.select_nodes("d:response");
		for (auto response : responses)
		{
			pugi::xml_node href = response.node().select_single_node("d:href").node();
			std::string encode_file_name = href.first_child().value();
			std::string resource_path = curl_unescape(encode_file_name.c_str(), (int)encode_file_name.length());
			auto target_path = target_urn.path();
			auto target_path_without_sep = std::string(target_path, 0, target_path.rfind("/")+1);
			auto resource_path_without_sep = std::string(resource_path, 0, resource_path.rfind("/")+1);
			if (resource_path_without_sep.compare(target_path_without_sep) == 0) {
				auto propstat = response.node().select_single_node("d:propstat").node();
				auto prop = propstat.select_single_node("d:prop").node();
				auto creation_date = prop.select_single_node("d:creationdate").node();
				auto display_name = prop.select_single_node("d:displayname").node();
				auto content_length = prop.select_single_node("d:getcontentlength").node();
				auto modified_date = prop.select_single_node("d:getlastmodified").node();
				auto resource_type = prop.select_single_node("d:resourcetype").node();

				dict_t information = {
						{"created", creation_date.first_child().value()},
						{"name", display_name.first_child().value()},
						{"size", content_length.first_child().value()},
						{"modified", modified_date.first_child().value()},
						{"type", resource_type.first_child().name()}
				};

				return information;
			}
		}

		return dict_t();
	}
Beispiel #22
0
PassRefPtr<ParsedCookie> CookieManager::parseOneCookie(const URL& url, const String& cookie)
{
    unsigned start = 0;
    unsigned end = cookie.length();

    double curTime = currentTime();
    RefPtr<ParsedCookie> res = ParsedCookie::create(curTime);

    res->setProtocol(url.protocol());

    unsigned tokenEnd = start; // Token end contains the position of the '=' or the end of a token
    unsigned pairEnd = start; // Pair end contains always the position of the ';'

    // Find the first ';' which is not double-quoted and the '=' (if they exist).
    bool foundEqual = false;
    while (pairEnd < end && cookie[pairEnd] != ';') {
        if (cookie[pairEnd] == '=') {
            if (tokenEnd == start) {
                tokenEnd = pairEnd;
                foundEqual = true;
            }
        } else if (cookie[pairEnd] == '"') {
            size_t secondQuotePosition = cookie.find('"', pairEnd + 1);
            if (secondQuotePosition != notFound && secondQuotePosition <= end) {
                pairEnd = secondQuotePosition + 1;
                continue;
            }
        }
        pairEnd++;
    }

    unsigned tokenStart = start;

    bool hasName = false; // This is a hack to avoid changing too much in this brutally brittle code.
    if (tokenEnd != start) {
        // There is a '=' so parse the NAME
        unsigned nameEnd = tokenEnd;

        // The tokenEnd is the position of the '=' so the nameEnd is one less
        nameEnd--;

        // Remove lightweight spaces.
        while (nameEnd && isLightweightSpace(cookie[nameEnd]))
            nameEnd--;

        while (tokenStart < nameEnd && isLightweightSpace(cookie[tokenStart]))
            tokenStart++;

        if (nameEnd + 1 <= tokenStart)
            LOG_ERROR_AND_RETURN("Empty name. Rejecting the cookie");

        String name = cookie.substring(tokenStart, nameEnd + 1 - start);
        res->setName(name);
        hasName = true;
    }

    // Now parse the VALUE
    tokenStart = tokenEnd + 1;
    if (!hasName)
        --tokenStart;

    // Skip lightweight spaces in our token
    while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
        tokenStart++;

    tokenEnd = pairEnd;
    while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
        tokenEnd--;

    String value;
    if (tokenEnd == tokenStart) {
        // Firefox accepts empty value so we will do the same
        value = String();
    } else
        value = cookie.substring(tokenStart, tokenEnd - tokenStart);

    if (hasName)
        res->setValue(value);
    else if (foundEqual)
        return ParsedCookie::create(curTime);
    else
        res->setName(value); // No NAME=VALUE, only NAME

    while (pairEnd < end) {
        // Switch to the next pair as pairEnd is on the ';' and fast-forward any lightweight spaces.
        pairEnd++;
        while (pairEnd < end && isLightweightSpace(cookie[pairEnd]))
            pairEnd++;

        tokenStart = pairEnd;
        tokenEnd = tokenStart; // initialize token end to catch first '='

        while (pairEnd < end && cookie[pairEnd] != ';') {
            if (tokenEnd == tokenStart && cookie[pairEnd] == '=')
                tokenEnd = pairEnd;
            pairEnd++;
        }

        // FIXME : should we skip lightweight spaces here ?

        unsigned length = tokenEnd - tokenStart;
        unsigned tokenStartSvg = tokenStart;

        String parsedValue;
        if (tokenStart != tokenEnd) {
            // There is an equal sign so remove lightweight spaces in VALUE
            tokenStart = tokenEnd + 1;
            while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
                tokenStart++;

            tokenEnd = pairEnd;
            while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
                tokenEnd--;

            parsedValue = cookie.substring(tokenStart, tokenEnd - tokenStart);
        } else {
            // If the parsedValue is empty, initialise it in case we need it
            parsedValue = String();
            // Handle a token without value.
            length = pairEnd - tokenStart;
        }

        // Detect which "cookie-av" is parsed
        // Look at the first char then parse the whole for performance issue
        switch (cookie[tokenStartSvg]) {
        case 'P':
        case 'p' : {
            if (length >= 4 && ((cookie.find("ath", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // We need the path to be decoded to match those returned from URL::path().
                // The path attribute may or may not include percent-encoded characters. Fortunately
                // if there are no percent-encoded characters, decoding the url is a no-op.
                res->setPath(curl_unescape(parsedValue.utf8().data(), parsedValue.length()));

                // We have to disable the following check because sites like Facebook and
                // Gmail currently do not follow the spec.

                // Check if path attribute is a prefix of the request URI.
                if (!url.path().startsWith(res->path()))
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path): it does not math the URL", cookie.ascii().data());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path)", cookie.ascii().data());
            break;
        }

        case 'D':
        case 'd' : {
            if (length >= 6 && ((cookie.find("omain", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                String host = url.host();

                // Check if the domain contains an embedded dot.
                size_t dotPosition = parsedValue.find(".", 1);
                if (dotPosition == notFound || dotPosition == parsedValue.length())
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not contain an embedded dot", cookie.ascii().data());

                if (isValidIPAddress(host)) {
                    if (parsedValue != host)
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());

                } else {
                    // If the domain does not start with a dot, add one for security checks and to distinguish it from host-only domains
                    // For example: ab.c.com dose not domain match b.c.com;
                    if (parsedValue[0] != '.')
                        parsedValue = "." + parsedValue;

                    host = "." + host;

                    if (!host.endsWith(parsedValue, false))
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not domain match the host (%s)", cookie.ascii().data(), host.ascii().data());
                }

                res->setDomain(parsedValue);
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());
            break;
        }

        case 'E' :
        case 'e' : {
            if (length >= 7 && ((cookie.find("xpires", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setExpiry(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (expires)", cookie.ascii().data());
            break;
        }

        case 'M' :
        case 'm' : {
            if (length >= 7 && ((cookie.find("ax-age", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setMaxAge(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (max-age)", cookie.ascii().data());
            break;
        }

        case 'C' :
        case 'c' : {
            if (length >= 7 && ((cookie.find("omment", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                // We do not have room for the comment part (and so do Mozilla) so just log the comment.
                LOG(Network, "Comment %s for ParsedCookie : %s\n", parsedValue.ascii().data(), cookie.ascii().data());
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (comment)", cookie.ascii().data());
            break;
        }

        case 'V' :
        case 'v' : {
            if (length >= 7 && ((cookie.find("ersion", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // Although the out-of-dated Cookie Spec(RFC2965, http://tools.ietf.org/html/rfc2965) defined
                // the value of version can only contain DIGIT, some random sites, e.g. https://devforums.apple.com
                // would use double quotation marks to quote the digit. So we need to get rid of them for compliance.
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                if (parsedValue.toInt() != 1)
                    LOG_ERROR_AND_RETURN("ParsedCookie version %d not supported (only support version=1)", parsedValue.toInt());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (version)", cookie.ascii().data());
            break;
        }

        case 'S' :
        case 's' : {
            // Secure is a standalone token ("Secure;")
            if (length >= 6 && ((cookie.find("ecure", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setSecureFlag(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (secure)", cookie.ascii().data());
            break;
        }
        case 'H':
        case 'h': {
            // HttpOnly is a standalone token ("HttpOnly;")
            if (length >= 8 && ((cookie.find("ttpOnly", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setIsHttpOnly(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (HttpOnly)", cookie.ascii().data());
            break;
        }

        default : {
            // If length == 0, we should be at the end of the cookie (case : ";\r") so ignore it
            if (length)
                LOG_ERROR_AND_RETURN("Invalid token for cookie %s", cookie.ascii().data());
            break;
        }
        }
    }

    // Check if the cookie is valid with respect to the size limit.
    if (res->isOverSizeLimit())
        LOG_ERROR_AND_RETURN("ParsedCookie %s is above the 4kb in length : REJECTED", cookie.ascii().data());

    // If no domain was provided, set it to the host
    if (!res->domain())
        res->setDomain(url.host());

    // According to the Cookie Specificaiton (RFC6265, section 4.1.2.4 and 5.2.4, http://tools.ietf.org/html/rfc6265),
    // If no path was provided or the first character of the path value is not '/', set it to the host's path
    //
    // REFERENCE
    // 4.1.2.4. The Path Attribute
    //
    // The scope of each cookie is limited to a set of paths, controlled by
    // the Path attribute. If the server omits the Path attribute, the user
    // agent will use the "directory" of the request-uri's path component as
    // the default value. (See Section 5.1.4 for more details.)
    // ...........
    // 5.2.4. The Path Attribute
    //
    // If the attribute-name case-insensitively matches the string "Path",
    // the user agent MUST process the cookie-av as follows.
    //
    // If the attribute-value is empty or if the first character of the
    // attribute-value is not %x2F ("/"):
    //
    // Let cookie-path be the default-path.
    //
    // Otherwise:
    //
    // Let cookie-path be the attribute-value.
    //
    // Append an attribute to the cookie-attribute-list with an attribute-
    // name of Path and an attribute-value of cookie-path.
    if (!res->path() || !res->path().length() || !res->path().startsWith("/", false)) {
        String path = url.string().substring(url.pathStart(), url.pathAfterLastSlash() - url.pathStart() - 1);
        if (path.isEmpty())
            path = "/";
        // Since this is reading the raw url string, it could contain percent-encoded sequences. We
        // want it to be comparable to the return value of url.path(), which is not percent-encoded,
        // so we must remove the escape sequences.
        res->setPath(curl_unescape(path.utf8().data(), path.length()));
    }

    return res;
}
Beispiel #23
0
int test(char *URL)
{
  const unsigned char a[] = {0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
                             0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe6, 0xf7};
  CURLcode res = CURLE_OK;
  char *ptr = NULL;
  int asize;
  int outlen;
  char *raw;

  (void)URL; /* we don't use this */

  if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    return TEST_ERR_MAJOR_BAD;
  }

  asize = (int)sizeof(a);
  ptr = curl_easy_escape(NULL, (char *)a, asize);
  printf("%s\n", ptr);
  if(ptr)
    curl_free(ptr);

  /* deprecated API */
  ptr = curl_escape((char *)a, asize);
  printf("%s\n", ptr);
  if(!ptr) {
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }

  raw = curl_easy_unescape(NULL, ptr, (int)strlen(ptr), &outlen);
  printf("outlen == %d\n", outlen);
  printf("unescape == original? %s\n",
         memcmp(raw, a, outlen) ? "no" : "YES");
  if(raw)
    curl_free(raw);

  /* deprecated API */
  raw = curl_unescape(ptr, (int)strlen(ptr));
  if(!raw) {
    res = TEST_ERR_MAJOR_BAD;
    goto test_cleanup;
  }
  outlen = (int)strlen(raw);
  printf("[old] outlen == %d\n", outlen);
  printf("[old] unescape == original? %s\n",
         memcmp(raw, a, outlen) ? "no" : "YES");
  if(raw)
    curl_free(raw);
  if(ptr)
    curl_free(ptr);

  /* weird input length */
  ptr = curl_easy_escape(NULL, (char *)a, -1);
  printf("escape -1 length: %s\n", ptr);

  /* weird input length */
  outlen = 2017; /* just a value */
  ptr = curl_easy_unescape(NULL, (char *)"moahahaha", -1, &outlen);
  printf("unescape -1 length: %s %d\n", ptr, outlen);

test_cleanup:
  if(ptr)
    curl_free(ptr);
  curl_global_cleanup();

  return (int)res;
}
Beispiel #24
0
struct gui_download_window *gui_download_window_create(download_context *ctx,
		struct gui_window *gui)
{
	const char *url = download_context_get_url(ctx);
	const char *mime_type = download_context_get_mime_type(ctx);
	const char *temp_name;
	char *scheme = NULL;
	char *filename = NULL;
	struct gui_download_window *dw;
	bool space_warning = false;
	os_error *error;
	url_func_result res;
	char *local_path;
	utf8_convert_ret err;
	size_t i, last_dot;

	dw = malloc(sizeof *dw);
	if (!dw) {
		warn_user("NoMemory", 0);
		return 0;
	}

	dw->ctx = ctx;
	dw->saved = false;
	dw->close_confirmed = false;
	dw->error = false;
	dw->query = QUERY_INVALID;
	dw->received = 0;
	dw->total_size = download_context_get_total_length(ctx);
	strncpy(dw->url, url, sizeof dw->url);
	dw->url[sizeof dw->url - 1] = 0;
	dw->status[0] = 0;
	gettimeofday(&dw->start_time, 0);
	dw->last_time = dw->start_time;
	dw->last_received = 0;
	dw->file_type = 0;
	dw->average_rate = 0;
	dw->average_points = 0;

	/* Get scheme from URL */
	res = url_scheme(url, &scheme);
	if (res == URL_FUNC_NOMEM) {
		warn_user("NoMemory", 0);
		free(dw);
		return 0;
	} else if (res == URL_FUNC_OK) {
		/* If we have a scheme and it's "file", then
		 * attempt to use the local filetype directly */
		if (strcasecmp(scheme, "file") == 0) {
			char *path = NULL;
			res = url_path(url, &path);
			if (res == URL_FUNC_NOMEM) {
				warn_user("NoMemory", 0);
				free(scheme);
				free(dw);
				return 0;
			} else if (res == URL_FUNC_OK) {
				char *raw_path = curl_unescape(path,
						strlen(path));
				if (raw_path == NULL) {
					warn_user("NoMemory", 0);
					free(path);
					free(scheme);
					free(dw);
					return 0;
				}
				dw->file_type =
					ro_filetype_from_unix_path(raw_path);
				curl_free(raw_path);
				free(path);
			}
		}

		free(scheme);
	}

	/* If we still don't have a filetype (i.e. failed reading local
	 * one or fetching a remote object), then use the MIME type */
	if (dw->file_type == 0) {
		/* convert MIME type to RISC OS file type */
		error = xmimemaptranslate_mime_type_to_filetype(mime_type,
				&(dw->file_type));
		if (error) {
			LOG(("xmimemaptranslate_mime_type_to_filetype: 0x%x: %s",
					error->errnum, error->errmess));
			warn_user("MiscError", error->errmess);
			dw->file_type = 0xffd;
		}
	}

	/* open temporary output file */
	temp_name = ro_gui_download_temp_name(dw);
	if (!ro_gui_download_check_space(dw, temp_name, NULL)) {
		/* issue a warning but continue with the download because the
		   user can save it to another medium whilst it's downloading */
		space_warning = true;
	}
	error = xosfind_openoutw(osfind_NO_PATH | osfind_ERROR_IF_DIR,
			temp_name, 0, &dw->file);
	if (error) {
		LOG(("xosfind_openoutw: 0x%x: %s",
				error->errnum, error->errmess));
		warn_user("SaveError", error->errmess);
		free(dw);
		return 0;
	}

	/* fill in download window icons */
	download_template->icons[ICON_DOWNLOAD_URL].data.indirected_text.text =
			dw->url;
	download_template->icons[ICON_DOWNLOAD_URL].data.indirected_text.size =
			sizeof dw->url;

	download_template->icons[ICON_DOWNLOAD_STATUS].data.indirected_text.
			text = dw->status;
	download_template->icons[ICON_DOWNLOAD_STATUS].data.indirected_text.
			size = sizeof dw->status;

	sprintf(dw->sprite_name, "file_%.3x", dw->file_type);
	if (!ro_gui_wimp_sprite_exists(dw->sprite_name))
		strcpy(dw->sprite_name, "file_xxx");
	download_template->icons[ICON_DOWNLOAD_ICON].data.indirected_sprite.id =
			(osspriteop_id) dw->sprite_name;

	/* Get a suitable path- and leafname for the download. */
	temp_name = download_context_get_filename(dw->ctx);

	if (temp_name == NULL)
		temp_name = messages_get("SaveObject");

	if (temp_name != NULL)
		filename = strdup(temp_name);

	if (filename == NULL) {
		LOG(("Failed to establish download filename."));
		warn_user("SaveError", error->errmess);
		free(dw);
		return 0;
	}

	for (i = 0, last_dot = (size_t) -1; filename[i] != '\0'; i++) {
		const char c = filename[i];

		if (c == '.') {
			last_dot = i;
			filename[i] = '/';
		} else if (c <= ' ' || strchr(":*#$&@^%\\", c) != NULL)
			filename[i] = '_';
	}

	if (option_strip_extensions && last_dot != (size_t) -1)
		filename[last_dot] = '\0';

	if (download_dir != NULL && strlen(download_dir) > 0)
		snprintf(dw->path, RO_DOWNLOAD_MAX_PATH_LEN, "%s.%s",
				download_dir, filename);
	else
		snprintf(dw->path, RO_DOWNLOAD_MAX_PATH_LEN, "%s",
				filename);

	err = utf8_to_local_encoding(dw->path, 0, &local_path);
	if (err != UTF8_CONVERT_OK) {
		/* badenc should never happen */
		assert(err != UTF8_CONVERT_BADENC);
		LOG(("utf8_to_local_encoding failed"));
		warn_user("NoMemory", 0);
		free(dw);
		return 0;
	}
	else {
		strncpy(dw->path, local_path, sizeof dw->path);
		free(local_path);
	}

	download_template->icons[ICON_DOWNLOAD_PATH].data.indirected_text.text =
			dw->path;
	download_template->icons[ICON_DOWNLOAD_PATH].data.indirected_text.size =
			sizeof dw->path;

	download_template->icons[ICON_DOWNLOAD_DESTINATION].data.
			indirected_text.text = dw->path;
	download_template->icons[ICON_DOWNLOAD_DESTINATION].data.
			indirected_text.size = sizeof dw->path;

	download_template->icons[ICON_DOWNLOAD_DESTINATION].flags |=
			wimp_ICON_DELETED;

	/* create and open the download window */
	error = xwimp_create_window(download_template, &dw->window);
	if (error) {
		LOG(("xwimp_create_window: 0x%x: %s",
				error->errnum, error->errmess));
		warn_user("WimpError", error->errmess);
		free(dw);
		return 0;
	}

	dw->prev = 0;
	dw->next = download_window_list;
	if (download_window_list)
		download_window_list->prev = dw;
	download_window_list = dw;

	ro_gui_download_update_status(dw);

	ro_gui_dialog_open(dw->window);

	ro_gui_wimp_event_set_user_data(dw->window, dw);
	ro_gui_wimp_event_register_mouse_click(dw->window, ro_gui_download_click);
	ro_gui_wimp_event_register_keypress(dw->window, ro_gui_download_keypress);
	ro_gui_wimp_event_register_close_window(dw->window, ro_gui_download_close);

	/* issue the warning now, so that it appears in front of the download
	 * window! */
	if (space_warning)
		warn_user("DownloadWarn", messages_get("NoDiscSpace"));

	return dw;
}
Beispiel #25
0
char *cg_net_uri_unescapestring(char *buf, int bufSize, CgString *retBuf)
{
#if defined(CG_HTTP_CURL)
	char *tmp;
#else
	int n;
	char hexStr[3];
	long hex;
	unsigned char c;
#endif
	int idx = 0;
#if defined(CG_USE_NET_URI_ESCAPESTRING_SKIP)
	int tmpIdx = 0;
#endif
	
	cg_log_debug_l4("Entering...\n");

	if (!retBuf)
		return NULL;

	/* Check if URI is already escaped */
	if (cg_net_uri_isescapedstring(buf + idx, bufSize) == TRUE) 
		return buf;
	
	/* We can safely assume that the non-path part is already escaped */
#if defined(CG_USE_NET_URI_ESCAPESTRING_SKIP)
	idx = cg_strstr(buf, CG_NET_URI_PROTOCOL_DELIM);
	if (idx > 0)
	{
		idx = idx + cg_strlen(CG_NET_URI_PROTOCOL_DELIM);
		tmpIdx = cg_strstr(buf + idx, CG_NET_URI_SLASH_DELIM);
		if (tmpIdx > 0)
			idx += tmpIdx + cg_strlen(CG_NET_URI_SLASH_DELIM);
	} else {
		idx = 0;
	}
#endif

	if (bufSize < 1)
		bufSize = cg_strlen(buf) + 1;	
	
#if defined(CG_HTTP_CURL)
	tmp = curl_unescape(buf + idx, 0);
	if (tmp == NULL)
		return NULL;
	cg_string_addvalue(retBuf, tmp);
	cg_log_debug_s("%s ==> %s\n", buf + idx, tmp);
	curl_free(tmp);
#else
	for (n=0; n<bufSize;) {
		c = (unsigned char)buf[n];
		if (buf[n] == '%' && cg_net_uri_isalphanumchar(buf[n+1]) && cg_net_uri_isalphanumchar(buf[n+2])) {
			hexStr[0] = buf[n+1];
			hexStr[1] = buf[n+2];
			hexStr[2] = '\0';
			hex = strtol(hexStr, NULL, 16);
			c = (unsigned char)hex;
			n += 3;
		}
		else
			n++;
		cg_string_naddvalue(retBuf, (char *)&c, 1);
	}
#endif
	
	cg_log_debug_l4("Leaving...\n");

	return cg_string_getvalue(retBuf);
}
Beispiel #26
0
void LLWLParamManager::loadPresets(const std::string& file_name)
{
	// if fileName exists, use legacy loading form the big file, otherwise, search the sky 
	// directory, and add the list
	if(file_name != "") 
	{
		std::string path_name(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight", file_name));
		LL_INFOS2("AppInit", "Shaders") << "Loading WindLight settings from " << path_name << LL_ENDL;

		llifstream presetsXML(path_name);
	
		if (presetsXML)
		{
			LLSD paramsData(LLSD::emptyMap());

			LLPointer<LLSDParser> parser = new LLSDXMLParser();

			parser->parse(presetsXML, paramsData, LLSDSerialize::SIZE_UNLIMITED);

			LLSD::map_const_iterator endParams = paramsData.endMap();
			for(LLSD::map_const_iterator curParams = paramsData.beginMap();
				curParams != endParams;
				++curParams)
			{
				addParamSet(curParams->first, curParams->second);
			}
		}
	}
	
	// otherwise, search the sky directory and find things there
	else
	{
		std::string path_name(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/skies", ""));
		LL_INFOS2("AppInit", "Shaders") << "Loading WindLight settings from " << path_name << LL_ENDL;
	
		//mParamList.clear();
		
		bool found = true;			
		while(found) 
		{
			std::string name;
			found = gDirUtilp->getNextFileInDir(path_name, "*.xml", name, false);

			LL_DEBUGS2("AppInit", "Shaders") << "name: " << name << LL_ENDL;
			
			// if we have one
			if(found) 
			{
				// bugfix for SL-46920: preventing filenames that break stuff.
				char * curl_str = curl_unescape(name.c_str(), name.size());
				std::string unescaped_name(curl_str);
				curl_free(curl_str);
				curl_str = NULL;

				// not much error checking here since we're getting rid of this
				std::string sky_name = unescaped_name.substr(0, unescaped_name.size() - 4);
			
				std::string cur_path(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/skies", name));
				LL_DEBUGS2("AppInit", "Shaders") << "Loading sky from " << cur_path << LL_ENDL;
				
				llifstream sky_xml(cur_path);
				if (sky_xml)
				{
					LLSD sky_data(LLSD::emptyMap());
					LLPointer<LLSDParser> parser = new LLSDXMLParser();
					parser->parse(sky_xml, sky_data, LLSDSerialize::SIZE_UNLIMITED);

					addParamSet(sky_name, sky_data);
					sky_xml.close();
				}
			}
		}
	}
}