Example #1
0
int cloudfs_copy_object(const char *src, const char *dst)
{
  char *dst_encoded = curl_escape(dst, 0);
  curl_slist *headers = NULL;
  add_header(&headers, "X-Copy-From", src);
  add_header(&headers, "Content-Length", "0");
  int response = send_request("PUT", dst_encoded, NULL, NULL, headers);
  curl_free(dst_encoded);
  curl_slist_free_all(headers);
  return (response >= 200 && response < 300);
}
Example #2
0
int cloudfs_object_write_fp(const char *path, FILE *fp)
{
  char *encoded = curl_escape(path, 0);
  int response = send_request("GET", encoded, fp, NULL, NULL);
  curl_free(encoded);
  fflush(fp);
  if ((response >= 200 && response < 300) || ftruncate(fileno(fp), 0))
    return 1;
  rewind(fp);
  return 0;
}
// <FS:Ansariel> FIRE-10861: Fix Windlight settings order
// static
std::string LLWaterParamManager::escapeString(const std::string& str)
{
	// Don't use LLURI::escape() because it doesn't encode '-' characters
	// which may break handling of some system presets like "A-12AM".
	char* curl_str = curl_escape(str.c_str(), str.size());
	std::string escaped_str(curl_str);
	curl_free(curl_str);

	LLStringUtil::replaceString(escaped_str, "-", "%2D");
	LLStringUtil::replaceString(escaped_str, ".", "%2E");

	return escaped_str;
}
Example #4
0
/* Escapes URL strings */
static int lcurl_escape(lua_State* L)
{
	if (!lua_isnil(L, 1))
	{
		const char* s=luaL_checkstring(L, 1);
		lua_pushstring(L, curl_escape(s, (int)lua_strlen(L, 1)));
		return 1;
	} else
	{
		luaL_argerror(L, 1, "string parameter expected");
	}
	return 0;
}
Example #5
0
Common::String ConnectionManager::urlEncode(Common::String s) const {
	if (!_multi)
		return "";
#if LIBCURL_VERSION_NUM >= 0x070F04
	char *output = curl_easy_escape(_multi, s.c_str(), s.size());
#else
	char *output = curl_escape(s.c_str(), s.size());
#endif
	if (output) {
		Common::String result = output;
		curl_free(output);
		return result;
	}
	return "";
}
Example #6
0
	CURLcode HttpPullData::retrieveAerosol(const char* townName,const char* startYear,const char* startMonth,const char* startDay,PARSE_ACTION action){
		char* escTownName=(char *)curl_escape(townName,0);
		char* escStartYear=(char *)curl_escape(startYear,0);
		char* escStartMonth=(char *)curl_escape(startMonth,0);
		char* escStartDay=(char *)curl_escape(startDay,0);
		const char* freqRange= (action==GET_AEROSOL_UV)?"UVRSR":"MFRSR";
		char postThis[POST_LEN];
		buffer.clear();
		initAerosolServer();
		buffer.clear();
		sprintf(postThis,AEROSOL_POST_STR,escTownName,freqRange,escStartYear,escStartMonth,escStartDay);
	    curl_easy_setopt(curl, CURLOPT_URL, AEROSOL_POST_URL);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postThis);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postThis));
	    CURLcode res=curl_easy_perform(curl);
	    if (res != CURLE_OK) {
      		fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res));
    		return res;
    	}
	    int pos=buffer.find("</HTML>")+strlen("</HTML>");
	    buffer="<HTML><BODY>"+buffer.substr(pos,buffer.length());
	    parseHtml(buffer,0,action);
	    return res;
	}
Example #7
0
	CURLcode HttpPullData::retrieveOzone(const char* townName,const char* startYear,const char* startMonth,const char* startDay){
		char* escTownName=(char *)curl_escape(townName,0);
		char* escStartYear=(char *)curl_escape(startYear,0);
		char* escStartMonth=(char *)curl_escape(startMonth,0);
		char* escStartDay=(char *)curl_escape(startDay,0);
		char postThis[POST_LEN];
		buffer.clear();
		initOzoneServer();
		buffer_offset=buffer.length();
		buffer.clear();
		sprintf(postThis,OZONE_POST_STR,escTownName,escStartYear,escStartMonth,escStartDay);
	    curl_easy_setopt(curl, CURLOPT_URL, OZONE_POST_URL);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postThis);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postThis));
	    CURLcode res=curl_easy_perform(curl);
	    if (res != CURLE_OK) {
      		fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res));
    		return res;
    	}
	    int pos=buffer.find("</HTML>")+strlen("</HTML>");
	    buffer="<HTML><BODY>"+buffer.substr(pos,buffer.length());
	    parseHtml(buffer,0,GET_OZONE);
	    return res;
	}
// static
std::string LLWLParamManager::escapeString(const std::string& str)
{
	// Don't use LLURI::escape() because it doesn't encode '-' characters
	// which may break handling of some system presets like "A-12AM".
	char* curl_str = curl_escape(str.c_str(), str.size());
	std::string escaped_str(curl_str);
	curl_free(curl_str);

	// <FS:Ansariel> FIRE-10861: Fix Windlight settings order
	// And neither does cURL...
	LLStringUtil::replaceString(escaped_str, "-", "%2D");
	LLStringUtil::replaceString(escaped_str, ".", "%2E");
	// </FS:Ansariel>

	return escaped_str;
}
Example #9
0
int cloudfs_object_truncate(const char *path, off_t size)
{
  char *encoded = curl_escape(path, 0);
  int response;
  if (size == 0)
  {
    FILE *fp = fopen("/dev/null", "r");
    response = send_request("PUT", encoded, fp, NULL, NULL);
    fclose(fp);
  }
  else
  {//TODO: this is busted
    response = send_request("GET", encoded, NULL, NULL, NULL);
  }
  curl_free(encoded);
  return (response >= 200 && response < 300);
}
Example #10
0
void LLWLParamManager::loadPreset(const std::string & name)
{
	// bugfix for SL-46920: preventing filenames that break stuff.
	char * curl_str = curl_escape(name.c_str(), name.size());
	std::string escaped_filename(curl_str);
	curl_free(curl_str);
	curl_str = NULL;

	escaped_filename += ".xml";

	std::string pathName(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/skies", escaped_filename));
	llinfos << "Loading WindLight sky setting from " << pathName << llendl;

	llifstream presetsXML(pathName);

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

		LLPointer<LLSDParser> parser = new LLSDXMLParser();

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

		std::map<std::string, LLWLParamSet>::iterator mIt = mParamList.find(name);
		if(mIt == mParamList.end())
		{
			addParamSet(name, paramsData);
		}
		else 
		{
			setParamSet(name, paramsData);
		}
		presetsXML.close();
	} 
	else 
	{
		llwarns << "Can't find " << name << llendl;
		return;
	}

	getParamSet(name, mCurParams);

	propagateParameters();
}
bool LLWLParamManager::removeParamSet(const std::string& name, bool delete_from_disk)
{
	// remove from param list
	std::map<std::string, LLWLParamSet>::iterator mIt = mParamList.find(name);
	if(mIt != mParamList.end()) 
	{
		mParamList.erase(mIt);
	}

	F32 key;

	// remove all references
	bool stat = true;
	do 
	{
		// get it
		stat = mDay.getKey(name, key);
		if(stat == false) 
		{
			break;
		}

		// and remove
		stat = mDay.removeKey(key);

	} while(stat == true);
	
	if(delete_from_disk)
	{
		std::string path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/skies", ""));
		
		// use full curl escaped name
		char * curl_str = curl_escape(name.c_str(), name.size());
		std::string escaped_name(curl_str);
		curl_free(curl_str);
		curl_str = NULL;
		
		gDirUtilp->deleteFilesInDir(path_name, escaped_name + ".xml");
	}

	notifyObservers();

	return true;
}
Example #12
0
char *
http_client_uri_escape(const char *src)
{
#if GLIB_CHECK_VERSION(2,16,0)
	/* if GLib is recent enough, prefer that over CURL
	   functions */
	return g_uri_escape_string(src, NULL, false);
#else
	/* curl_escape() is deprecated, but for some reason,
	   curl_easy_escape() wants to have a CURL object, which we
	   don't have right now */
	char *tmp = curl_escape(src, 0);
	/* call g_strdup(), because the caller expects a pointer which
	   can be freed with g_free() */
	char *dest = g_strdup(tmp == NULL ? src : tmp);
	curl_free(tmp);
	return dest;
#endif
}
Example #13
0
	CURLcode HttpPullData::retrieveLoc(const char* townName){
		char* escTownName=(char *)curl_escape(townName,0);
		char postThis[POST_LEN];
		buffer.clear();
		initLocServer();
		buffer_offset=0;
		buffer.clear();
		sprintf(postThis,LOC_POST_STR,escTownName);
	    curl_easy_setopt(curl, CURLOPT_URL, LOC_POST_URL);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postThis);
	    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postThis));
	    CURLcode res=curl_easy_perform(curl);
	   	if (res != CURLE_OK) {
      		fprintf(stderr, "Curl perform failed: %s\n", curl_easy_strerror(res));
    		return res;
    	}
    	parseHtml(buffer,0,GET_LOCATION);
	    return res;
	}
Example #14
0
void LLWLDayCycle::saveDayCycle(const std::string & fileName)
{
	
	// bugfix for SL-46920: preventing filenames that break stuff.
	char * curl_str = curl_escape(fileName.c_str(), fileName.size());
	std::string escaped_filename(curl_str);
	curl_free(curl_str);
	curl_str = NULL;

	escaped_filename += ".xml";

	std::string pathName(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/days", escaped_filename));
	llinfos << "Saving Day Cycle preset from " << pathName << llendl;

	llofstream day_cycle_xml;
	day_cycle_xml.open(pathName.c_str());

	// That failed, try loading from the users area instead.
	if(!day_cycle_xml)
	{
		pathName=gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", escaped_filename);
		llinfos << "Saving User Day Cycle preset from " << pathName << llendl;
		day_cycle_xml.open(pathName.c_str());
	}

	LLSD day_data(LLSD::emptyArray());

	for(std::map<F32, std::string>::const_iterator mIt = mTimeMap.begin();
		mIt != mTimeMap.end();
		++mIt) 
	{
		LLSD key(LLSD::emptyArray());
		key.append(mIt->first);
		key.append(mIt->second);
		day_data.append(key);
	}

	LLPointer<LLSDFormatter> formatter = new LLSDXMLFormatter();
	formatter->format(day_data, day_cycle_xml, LLSDFormatter::OPTIONS_PRETTY);
	day_cycle_xml.close();
}
Example #15
0
void SmsGateway::sendSms(std::string &id, std::string &value)
{
    if (type_m == Clickatell)
    {
#ifdef HAVE_LIBCURL
        CURL *curl;
        CURLcode res;

        curl = curl_easy_init();
        if(curl)
        {
            char *escaped_value = curl_escape(value.c_str(), value.length());
            std::stringstream msg;
            msg << "http://api.clickatell.com/http/sendmsg?user="******"&password="******"&api_id=" << data_m;
            if (!from_m.empty())
                msg << "&from=" << from_m;
            msg << "&to=" << id << "&text=" << escaped_value;
            std::string url = msg.str();
            curl_free(escaped_value);
            //        curl_easy_setopt(curl, CURLOPT_VERBOSE, TRUE);
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            res = curl_easy_perform(curl);

            logger_m.infoStream() << "curl_easy_perform returned: " << res << endlog;
            if (res != 0)
                logger_m.infoStream() << "msg=" << curl_easy_strerror(res) << endlog;

            curl_easy_cleanup(curl);
        }
        else
            logger_m.errorStream() << "Unable to execute SendSmsAction. Curl not available" << endlog;
#endif
    }
    else
        logger_m.errorStream() << "Unable to send SMS, gateway not set." << endlog;
}
Example #16
0
void CloudPinyinAddInputRequest(FcitxCloudPinyin* cloudpinyin, const char* strPinyin)
{
    CURL* curl = CloudPinyinGetFreeCurlHandle(cloudpinyin);
    if (!curl)
        return;
    CurlQueue* queue = fcitx_utils_malloc0(sizeof(CurlQueue)), *head = cloudpinyin->pendingQueue;
    queue->curl = curl;
    queue->next = NULL;
    queue->type = RequestPinyin;
    queue->pinyin = strdup(strPinyin);
    queue->source = cloudpinyin->config.source;
    char* urlstring = curl_escape(strPinyin, strlen(strPinyin));
    char *url = NULL;
    if (engine[cloudpinyin->config.source].RequestKey)
        asprintf(&url, engine[cloudpinyin->config.source].RequestPinyin, cloudpinyin->key, urlstring);
    else
        asprintf(&url, engine[cloudpinyin->config.source].RequestPinyin, urlstring);
    curl_free(urlstring);

    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, queue);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CloudPinyinWriteFunction);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10l);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1l);

    free(url);

    /* push into pending queue */
    pthread_mutex_lock(&cloudpinyin->pendingQueueLock);
    while (head->next != NULL)
        head = head->next;
    head->next = queue;
    pthread_mutex_unlock(&cloudpinyin->pendingQueueLock);

    char c = 0;
    write(cloudpinyin->pipeNotify, &c, sizeof(char));
}
Example #17
0
static gpointer
search_thread(Data *data)
{
	XmrService *service = NULL;
	gchar *url;
	gchar *escape_keyword;
	GString *result_data;
	gint result;
	
	escape_keyword = curl_escape(data->keyword, 0);
	url = g_strdup_printf(XIAMI_SEARCH_URL"%s",escape_keyword);
	result_data = g_string_new("");
	
	service = xmr_service_new();
	result = xmr_service_get_url_data(service, url, result_data);
	g_object_unref(service);

	if (result == 0)
	{
		GList *list = parse_result_data(result_data->str);
		if (list)
			g_async_queue_push(data->plugin->event_queue, list);
	}

	g_mutex_lock(data->plugin->mutex);
	data->plugin->thread_count--;
	g_mutex_unlock(data->plugin->mutex);

	g_free(url);
	curl_free(escape_keyword);
	g_string_free(result_data, TRUE);
	g_free(data->keyword);
	g_free(data);

	return NULL;
}
Example #18
0
void LLPanelLogin::loadLoginPage()
{
	if (!sInstance) return;
	
	std::ostringstream oStr;

	std::string login_page = LLGridManager::getInstance()->getLoginPage();

	oStr << login_page;
	
	// Use the right delimeter depending on how LLURI parses the URL
	LLURI login_page_uri = LLURI(login_page);
	
	std::string first_query_delimiter = "&";
	if (login_page_uri.queryMap().size() == 0)
	{
		first_query_delimiter = "?";
	}

	// Language
	std::string language = LLUI::getLanguage();
	oStr << first_query_delimiter<<"lang=" << language;
	
	// First Login?
	if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
	{
		oStr << "&firstlogin=TRUE";
	}

	// Channel and Version
	std::string version = llformat("%s (%d)",
								   LLVersionInfo::getShortVersion().c_str(),
								   LLVersionInfo::getBuild());

	char* curl_channel ;
	char* curl_version = curl_escape(version.c_str(), 0);

	if(strcmp(LLVersionInfo::getChannel().c_str(), LL_CHANNEL))
	{
		curl_channel = curl_escape(LLVersionInfo::getChannel().c_str(), 0);
	}
	else //if LL_CHANNEL, direct it to "Second Life Beta Viewer".
	{
		curl_channel = curl_escape("Second Life Beta Viewer", 0);		
	}
	oStr << "&channel=" << curl_channel;
	oStr << "&version=" << curl_version;
	
	curl_free(curl_channel);
	curl_free(curl_version);

	// Grid
	char* curl_grid = curl_escape(LLGridManager::getInstance()->getGridLabel().c_str(), 0);
	oStr << "&grid=" << curl_grid;
	curl_free(curl_grid);
	
	// add OS info
	char * os_info = curl_escape(LLAppViewer::instance()->getOSInfo().getOSStringSimple().c_str(), 0);
	oStr << "&os=" << os_info;
	curl_free(os_info);
	
	gViewerWindow->setMenuBackgroundColor(false, !LLGridManager::getInstance()->isInProductionGrid());
	
	LLMediaCtrl* web_browser = sInstance->getChild<LLMediaCtrl>("login_html");
	if (web_browser->getCurrentNavUrl() != oStr.str())
	{
		web_browser->navigateTo( oStr.str(), "text/html" );
	}
}
Example #19
0
void LLWLDayCycle::loadDayCycle(const std::string & fileName)
{
	// clear the first few things
	mTimeMap.clear();

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

	escaped_filename += ".xml";

	std::string pathName(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight/days", escaped_filename));
	llinfos << "Loading Day Cycle preset from " << pathName << llendl;

	llifstream day_cycle_xml;
	day_cycle_xml.open(pathName.c_str());

	// That failed, try loading from the users area instead.
	if(!day_cycle_xml)
	{
		pathName=gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", escaped_filename);
		llinfos << "Loading User Day Cycle preset from " << pathName << llendl;
		day_cycle_xml.open(pathName.c_str());
	}

	if (day_cycle_xml)
	{
		// load and parse it
		LLSD day_data(LLSD::emptyArray());
		LLPointer<LLSDParser> parser = new LLSDXMLParser();
		parser->parse(day_cycle_xml, day_data, LLSDSerialize::SIZE_UNLIMITED);
		llinfos << "Loading day cycle into timeline..." << llendl;
		// add each key
		for(S32 i = 0; i < day_data.size(); ++i)
		{
			llinfos << "Loading value" << i << llendl;
			// make sure it's a two array
			if(day_data[i].size() != 2)
			{
				continue;
			}
			
			// check each param name exists in param manager
			bool success;
			LLWLParamSet pset;
			success = LLWLParamManager::instance()->getParamSet(day_data[i][1].asString(), pset);
			if(!success)
			{
				// alert the user
				LLSD args;
				args["SKY"] = day_data[i][1].asString();
				LLNotifications::instance().add("WLMissingSky", args);
				continue;
			}
			
			// then add the key
			addKey((F32)day_data[i][0].asReal(), day_data[i][1].asString());
		}

		day_cycle_xml.close();
	}
	else 
	{
		llwarns << "Can't find " << fileName << llendl;
		return;
	}
}
Example #20
0
/// communication
ParseError* ParseManager::request(CCHttpRequest::HttpRequestType op, 
								  const std::string &url, 
								  const char* buffer,
								  size_t size,
								  CCObject *receiver, 
								  SEL_CallFuncND selector,
								  const char* contentType,
								  bool setMasterKey,
								  void* param)
{
	ParseError* error = NULL;

	CCHttpRequest* request = new CCHttpRequest();

	std::vector<std::string> headers;

	request->setRequestType(op);

	std::string fullUrl;
	if (strncmp(url.c_str(), "http", 4) != 0)
	{
		fullUrl = "https://api.parse.com" + url;
	}
	else
	{
		fullUrl = url;
	}

	request->setUrl(fullUrl.c_str());

	request->setResponseCallback(receiver, selector);

	request->setUserData(param);

	CCHttpClient* client = CCHttpClient::getInstance();


	if (contentType)
	{
		headers.push_back(contentType);
	}
	switch(op)
	{
		case CCHttpRequest::kHttpGet:
			if (size > 0)
			{
				char* condition = curl_escape(buffer, size);
				request->setUrl((fullUrl + "?" + condition).c_str());
			}
			break;
		case CCHttpRequest::kHttpPost:
			if (contentType == 0)
			{
				headers.push_back("Content-Type: application/json");
			}
			if (size > 0)
			{
				request->setRequestData(buffer, size);
			}
			break;
		case CCHttpRequest::kHttpPut:
			if (contentType == 0)
			{
				headers.push_back("Content-Type: application/json");
			}
			if (size > 0)
			{
				request->setRequestData(buffer, size);
			}
			break;
		case CCHttpRequest::kHttpDelete:
			break;
	}

	headers.push_back(std::string("X-Parse-Application-Id: ") + this->_applicationId);
	if (setMasterKey)
	{
		headers.push_back(std::string("X-Parse-Master-Key: ") + this->_masterKey);
	}
	else
	{
		headers.push_back(std::string("X-Parse-REST-API-Key: ") + this->_apiKey);
	}
	request->setHeaders(headers);

	client->send(request);

	request->release();

	return error;
}
Example #21
0
/*
 * call-seq:
 *   field.to_str                                     => "name=value"
 *   field.to_s                                       => "name=value"
 * 
 * Obtain a String representation of this PostField in url-encoded 
 * format. This is used to construct the post data for non-multipart
 * POSTs.
 * 
 * Only content fields may be converted to strings.
 */
static VALUE ruby_curl_postfield_to_str(VALUE self) {
  // FIXME This is using the deprecated curl_escape func
  ruby_curl_postfield *rbcpf;
  VALUE result = Qnil;
  VALUE name = Qnil;
  
  Data_Get_Struct(self, ruby_curl_postfield, rbcpf);

    if (rbcpf->name != Qnil) {
      name = rbcpf->name;
      if (rb_type(name) == T_STRING) {
        name = rbcpf->name;
      } else if (rb_respond_to(name,rb_intern("to_s"))) {
        name = rb_funcall(name, rb_intern("to_s"), 0);
      }
      else {
        name = Qnil; // we can't handle this object
      }
    }
    if (name == Qnil) {
      rb_raise(eCurlErrInvalidPostField, "Cannot convert unnamed field to string %s:%d, make sure your field name responds_to :to_s", __FILE__, __LINE__);
    }

    char *tmpchrs = curl_escape(StringValuePtr(name), (int)RSTRING_LEN(name));
    
    if (!tmpchrs) {
      rb_raise(eCurlErrInvalidPostField, "Failed to url-encode name `%s'", tmpchrs);
    } else {
      VALUE tmpcontent = Qnil;
      VALUE escd_name = rb_str_new2(tmpchrs);
      curl_free(tmpchrs);
      
      if (rbcpf->content_proc != Qnil) {
        tmpcontent = rb_funcall(rbcpf->content_proc, idCall, 1, self);
      } else if (rbcpf->content != Qnil) {
        tmpcontent = rbcpf->content;
      } else if (rbcpf->local_file != Qnil) {
        tmpcontent = rbcpf->local_file;
      } else if (rbcpf->remote_file != Qnil) {
        tmpcontent = rbcpf->remote_file;
      } else {
        tmpcontent = rb_str_new2("");
      }
      if (TYPE(tmpcontent) != T_STRING) {
        if (rb_respond_to(tmpcontent, rb_intern("to_s"))) {
          tmpcontent = rb_funcall(tmpcontent, rb_intern("to_s"), 0);
        }
        else {
          rb_raise(rb_eRuntimeError, "postfield(%s) is not a string and does not respond_to to_s", RSTRING_PTR(escd_name) );
        }
      }
      //fprintf(stderr, "encoding content: %ld - %s\n", RSTRING_LEN(tmpcontent), RSTRING_PTR(tmpcontent) );
      tmpchrs = curl_escape(RSTRING_PTR(tmpcontent), (int)RSTRING_LEN(tmpcontent));
      if (!tmpchrs) {
        rb_raise(eCurlErrInvalidPostField, "Failed to url-encode content `%s'", tmpchrs);
      } else {
        VALUE escd_content = rb_str_new2(tmpchrs);
        curl_free(tmpchrs);
        
        result = escd_name;
        rb_str_cat(result, "=", 1);
        rb_str_concat(result, escd_content); 
      }
    }
  
  return result;
}
Example #22
0
int cloudfs_list_directory(const char *path, dir_entry **dir_list)
{
  char container[MAX_PATH_SIZE * 3] = "";
  char object[MAX_PATH_SIZE] = "";
  char last_subdir[MAX_PATH_SIZE] = "";
  int prefix_length = 0;
  int response = 0;
  int retval = 0;
  int entry_count = 0;

  *dir_list = NULL;
  xmlNode *onode = NULL, *anode = NULL, *text_node = NULL;
  xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL);
  if (!strcmp(path, "") || !strcmp(path, "/"))
  {
    path = "";
    strncpy(container, "/?format=xml", sizeof(container));
  }
  else
  {
    sscanf(path, "/%[^/]/%[^\n]", container, object);
    char *encoded_container = curl_escape(container, 0);
    char *encoded_object = curl_escape(object, 0);

    // The empty path doesn't get a trailing slash, everything else does
    char *trailing_slash;
    prefix_length = strlen(object);
    if (object[0] == 0)
      trailing_slash = "";
    else
    {
      trailing_slash = "/";
      prefix_length++;
    }

    snprintf(container, sizeof(container), "%s?format=xml&delimiter=/&prefix=%s%s",
              encoded_container, encoded_object, trailing_slash);
    curl_free(encoded_container);
    curl_free(encoded_object);
  }

  response = send_request("GET", container, NULL, xmlctx, NULL);
  xmlParseChunk(xmlctx, "", 0, 1);
  if (xmlctx->wellFormed && response >= 200 && response < 300)
  {
    xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc);
    for (onode = root_element->children; onode; onode = onode->next)
    {
      if (onode->type != XML_ELEMENT_NODE) continue;

      char is_object = !strcasecmp((const char *)onode->name, "object");
      char is_container = !strcasecmp((const char *)onode->name, "container");
      char is_subdir = !strcasecmp((const char *)onode->name, "subdir");

      if (is_object || is_container || is_subdir)
      {
        entry_count++;

        dir_entry *de = (dir_entry *)malloc(sizeof(dir_entry));
        de->next = NULL;
        de->size = 0;
        de->last_modified = time(NULL);
        if (is_container || is_subdir)
          de->content_type = strdup("application/directory");
        for (anode = onode->children; anode; anode = anode->next)
        {
          char *content = "<?!?>";
          for (text_node = anode->children; text_node; text_node = text_node->next)
            if (text_node->type == XML_TEXT_NODE)
              content = (char *)text_node->content;
          if (!strcasecmp((const char *)anode->name, "name"))
          {
            de->name = strdup(content + prefix_length);

            // Remove trailing slash
            char *slash = strrchr(de->name, '/');
            if (slash && (0 == *(slash + 1)))
              *slash = 0;

            if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0)
              de->full_name = NULL;
          }
          if (!strcasecmp((const char *)anode->name, "bytes"))
            de->size = strtoll(content, NULL, 10);
          if (!strcasecmp((const char *)anode->name, "content_type"))
          {
            de->content_type = strdup(content);
            char *semicolon = strchr(de->content_type, ';');
            if (semicolon)
              *semicolon = '\0';
          }
          if (!strcasecmp((const char *)anode->name, "last_modified"))
          {
            struct tm last_modified;
            strptime(content, "%FT%T", &last_modified);
            de->last_modified = mktime(&last_modified);
          }
        }
        de->isdir = de->content_type &&
            ((strstr(de->content_type, "application/folder") != NULL) ||
             (strstr(de->content_type, "application/directory") != NULL));
        if (de->isdir)
        {
          if (!strncasecmp(de->name, last_subdir, sizeof(last_subdir)))
          {
            cloudfs_free_dir_list(de);
            continue;
          }
          strncpy(last_subdir, de->name, sizeof(last_subdir));
        }
        de->next = *dir_list;
        *dir_list = de;
      }
      else
      {
        debugf("unknown element: %s", onode->name);
      }
    }
    retval = 1;
  }

  debugf("entry count: %d", entry_count);

  xmlFreeDoc(xmlctx->myDoc);
  xmlFreeParserCtxt(xmlctx);
  return retval;
}
void LLPanelLogin::loadLoginPage()
{
	if (!sInstance) return;
	
	std::ostringstream oStr;

	LLViewerLogin* vl = LLViewerLogin::getInstance();
	std::string login_page = vl->getLoginPageURI();
	if (login_page.empty())
	{
		login_page = sInstance->getString( "real_url" );
		vl->setLoginPageURI(login_page);
	}
	oStr << login_page;
	
	// Use the right delimeter depending on how LLURI parses the URL
	LLURI login_page_uri = LLURI(login_page);
	std::string first_query_delimiter = "&";
	if (login_page_uri.queryMap().size() == 0)
	{
		first_query_delimiter = "?";
	}

	// Language
	std::string language = LLUI::getLanguage();
	oStr << first_query_delimiter<<"lang=" << language;
	
	// First Login?
	if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
	{
		oStr << "&firstlogin=TRUE";
	}

	// Channel and Version
	std::string version = llformat("%d.%d.%d (%d)",
						LL_VERSION_MAJOR, LL_VERSION_MINOR, LL_VERSION_PATCH, LL_VIEWER_BUILD);

	char* curl_channel = curl_escape(LL_CHANNEL, 0);
	char* curl_version = curl_escape(version.c_str(), 0);
	char* curl_t = curl_escape(LLAppViewer::instance()->getWindowTitle().c_str(), 0);

	oStr << "&channel=" << curl_channel;
	oStr << "&version=" << curl_version;
	oStr << "&t=" << curl_t;
	if(LL_CHANNEL != EMERALD_RELEASE_CHANNEL)
		oStr << "&unsupported=1";

	curl_free(curl_channel);
	curl_free(curl_version);
	curl_free(curl_t);

	// grid=blah code was here. Due to the implementation of the Emerald login manager, sending
	// this information is a very bad idea. Don't do it.

	gViewerWindow->setMenuBackgroundColor(false, !LLViewerLogin::getInstance()->isInProductionGrid());
	gLoginMenuBarView->setBackgroundColor(gMenuBarView->getBackgroundColor());


#if USE_VIEWER_AUTH
	LLURLSimString::sInstance.parse();

	std::string location;
	std::string region;
	std::string password;
	
	if (LLURLSimString::parse())
	{
		std::ostringstream oRegionStr;
		location = "specify";
		oRegionStr << LLURLSimString::sInstance.mSimName << "/" << LLURLSimString::sInstance.mX << "/"
			 << LLURLSimString::sInstance.mY << "/"
			 << LLURLSimString::sInstance.mZ;
		region = oRegionStr.str();
	}
	else
	{
		if (gSavedSettings.getBOOL("LoginLastLocation"))
		{
			location = "last";
		}
		else
		{
			location = "home";
		}
	}
	
	std::string firstname, lastname;

    if(gSavedSettings.getLLSD("UserLoginInfo").size() == 3)
    {
        LLSD cmd_line_login = gSavedSettings.getLLSD("UserLoginInfo");
		firstname = cmd_line_login[0].asString();
		lastname = cmd_line_login[1].asString();
        password = cmd_line_login[2].asString();
    }
    	
	if (firstname.empty())
	{
		firstname = gSavedSettings.getString("FirstName");
	}
	
	if (lastname.empty())
	{
		lastname = gSavedSettings.getString("LastName");
	}
	
	char* curl_region = curl_escape(region.c_str(), 0);

	oStr <<"firstname=" << firstname <<
		"&lastname=" << lastname << "&location=" << location <<	"&region=" << curl_region;
	
	curl_free(curl_region);

	if (!password.empty())
	{
		oStr << "&password="******"&password=$1$" << password;
	}
	if (gAutoLogin)
	{
		oStr << "&auto_login=TRUE";
	}
	if (gSavedSettings.getBOOL("ShowStartLocation"))
	{
		oStr << "&show_start_location=TRUE";
	}	
	if (gSavedSettings.getBOOL("RememberPassword"))
	{
		oStr << "&remember_password=TRUE";
	}	
	BOOL show_server = sInstance ? sInstance->mShowServerCombo : FALSE;
	if (show_server || gSavedSettings.getBOOL("ForceShowGrid"))
	{
		oStr << "&show_grid=TRUE";
	}
#endif
	
	LLMediaCtrl* web_browser = sInstance->getChild<LLMediaCtrl>("login_html");
	
	// navigate to the "real" page 
	web_browser->navigateTo( oStr.str(), "text/html" );
}
Example #24
0
bool CFileBrowser::readDir_vlc(const std::string & dirname, CFileList* flist)
{
//	printf("readDir_vlc %s\n",dirname.c_str());
	std::string answer="";
	char *dir_escaped = curl_escape(dirname.substr(strlen(VLC_URI)).c_str(), 0);
	std::string url = m_baseurl;
	url += dir_escaped;
	curl_free(dir_escaped);
	std::cout << "[FileBrowser] vlc URL: " << url << std::endl;
	CURL *curl_handle;
	CURLcode httpres;
	/* init the curl session */
	curl_handle = curl_easy_init();
	/* timeout. 15 seconds should be enough */
	curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 15);
	/* specify URL to get */
	curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
	/* send all data to this function  */
	curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, CurlWriteToString);
	/* we pass our 'chunk' struct to the callback function */
	curl_easy_setopt(curl_handle, CURLOPT_FILE, (void *)&answer);
	/* Generate error if http error >= 400 occurs */
	curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1);
	/* error handling */
	char error[CURL_ERROR_SIZE];
	curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, error);
	/* get it! */
	httpres = curl_easy_perform(curl_handle);
	/* cleanup curl stuff */
	curl_easy_cleanup(curl_handle);

	// std::cout << "Answer:" << std::endl << "----------------" << std::endl << answer << std::endl;
	
	if (!answer.empty() && httpres == 0)
	{
		xmlDocPtr answer_parser = parseXml(answer.c_str());

		if (answer_parser != NULL) {
			xmlNodePtr element = xmlDocGetRootElement(answer_parser);
			element = element->xmlChildrenNode;
			char *ptr;
			if (element == NULL) {
				printf("[FileBrowser] vlc: Drive is not readable. Possibly no disc inserted\n");
				CFile file;
				file.Mode = S_IFDIR + 0777 ;
				file.Name = dirname + "..";
				file.Size = 0;
				file.Time = 0;
				flist->push_back(file);
			} else {
				while (element) {
					CFile file;
					ptr = xmlGetAttribute(element, (char *) "type");
					if (strcmp(ptr, "directory")==0)
						file.Mode = S_IFDIR + 0777 ;
					else
						file.Mode = S_IFREG + 0777 ;

					file.Name = dirname + xmlGetAttribute(element, (char *) "name");
					ptr = xmlGetAttribute(element, (char *) "size");
					if (ptr) 
						file.Size = atoi(ptr);
					else 
						file.Size = 0;
					file.Time = 0;

					element = element->xmlNextNode;
					flist->push_back(file);
				}
			}
			xmlFreeDoc(answer_parser);
			return true;
		}
	}
	
	/* since all CURL error messages use only US-ASCII characters, when can safely print them as if they were UTF-8 encoded */
	if (httpres == 22) {
	    strcat(error, "\nProbably wrong vlc version\nPlease use vlc 0.8.5 or higher");
	}
	DisplayErrorMessage(error); // UTF-8
	CFile file;

	file.Name = dirname + "..";
	file.Mode = S_IFDIR + 0777;
	file.Size = 0;
	file.Time = 0;
	flist->push_back(file);

	return false;
}
Example #25
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;
}
Example #26
0
void LLPanelLogin::loadLoginPage()
{
	if (!sInstance) return;
	

	std::string login_page = gHippoGridManager->getCurrentGrid()->getLoginPage();
	if (login_page.empty()) 
	{
		sInstance->setSiteIsAlive(false);
		return;
	}

	std::ostringstream oStr;
	oStr << login_page;
	
	// Use the right delimeter depending on how LLURI parses the URL
	LLURI login_page_uri = LLURI(login_page);
	std::string first_query_delimiter = "&";
	if (login_page_uri.queryMap().size() == 0)
	{
		first_query_delimiter = "?";
	}

	// Language
	std::string language = LLUI::getLanguage();
	oStr << first_query_delimiter<<"lang=" << language;
	
	// First Login?
	if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
	{
		oStr << "&firstlogin=TRUE";
	}

	// Channel and Version
	std::string version = llformat("%d.%d.%d %s",
		ViewerVersion::getImpMajorVersion(), ViewerVersion::getImpMinorVersion(),
		ViewerVersion::getImpPatchVersion(), ViewerVersion::getImpTestVersion().c_str() );

	char* curl_channel = curl_escape(gSavedSettings.getString("VersionChannelName").c_str(), 0);
	char* curl_version = curl_escape(version.c_str(), 0);

	oStr << "&channel=" << curl_channel;
	oStr << "&version=" << curl_version;

	curl_free(curl_channel);
	curl_free(curl_version);

	// Grid
	char* curl_grid = curl_escape(LLViewerLogin::getInstance()->getGridLabel().c_str(), 0);
	oStr << "&grid=" << curl_grid;
	curl_free(curl_grid);

	gViewerWindow->setMenuBackgroundColor(false, !LLViewerLogin::getInstance()->isInProductionGrid());
	//LLViewerLogin::getInstance()->setMenuColor();
	gLoginMenuBarView->setBackgroundColor(gMenuBarView->getBackgroundColor());


#if USE_VIEWER_AUTH
	LLURLSimString::sInstance.parse();

	std::string location;
	std::string region;
	std::string password;
	
	if (LLURLSimString::parse())
	{
		std::ostringstream oRegionStr;
		location = "specify";
		oRegionStr << LLURLSimString::sInstance.mSimName << "/" << LLURLSimString::sInstance.mX << "/"
			 << LLURLSimString::sInstance.mY << "/"
			 << LLURLSimString::sInstance.mZ;
		region = oRegionStr.str();
	}
	else
	{
		if (gSavedSettings.getBOOL("LoginLastLocation"))
		{
			location = "last";
		}
		else
		{
			location = "home";
		}
	}

	std::string firstname, lastname;

	if(gSavedSettings.getLLSD("UserLoginInfo").size() == 3)
	{
		LLSD cmd_line_login = gSavedSettings.getLLSD("UserLoginInfo");
		firstname = cmd_line_login[0].asString();
		lastname = cmd_line_login[1].asString();
		password = cmd_line_login[2].asString();
	}

	if (firstname.empty())
	{
		firstname = gSavedSettings.getString("FirstName");
	}
	
	if (lastname.empty())
	{
		lastname = gSavedSettings.getString("LastName");
	}
	
	char* curl_region = curl_escape(region.c_str(), 0);

	oStr <<"firstname=" << firstname <<
		"&lastname=" << lastname << "&location=" << location <<	"&region=" << curl_region;
	
	curl_free(curl_region);

	if (!password.empty())
	{
		oStr << "&password="******"&password=$1$" << password;
	}
	if (gAutoLogin)
	{
		oStr << "&auto_login=TRUE";
	}
	if (gSavedSettings.getBOOL("ShowStartLocation"))
	{
		oStr << "&show_start_location=TRUE";
	}	
	if (gSavedSettings.getBOOL("RememberPassword"))
	{
		oStr << "&remember_password=TRUE";
	}	
#ifndef	LL_RELEASE_FOR_DOWNLOAD
	oStr << "&show_grid=TRUE";
#else
	if (gSavedSettings.getBOOL("ForceShowGrid"))
		oStr << "&show_grid=TRUE";
#endif
#endif
	
	LLWebBrowserCtrl* web_browser = sInstance->getChild<LLWebBrowserCtrl>("login_html");
	
	// navigate to the "real" page 
	web_browser->navigateTo( oStr.str() );
}
Example #27
0
int list_directory(const char *path, dir_entry **dir_list)
{
  char container[MAX_PATH_SIZE * 3] = "";
  char object[MAX_PATH_SIZE] = "";
  int response = 0;
  int retval = 0;
  *dir_list = NULL;
  xmlNode *onode = NULL, *anode = NULL, *text_node = NULL;
  xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL);
  if (!strcmp(path, "") || !strcmp(path, "/"))
  {
    path = "";
    strncpy(container, "/?format=xml", sizeof(container));
  }
  else
  {
    sscanf(path, "/%[^/]/%[^\n]", container, object);
    char *encoded_container = curl_escape(container, 0);
    char *encoded_object = curl_escape(object, 0);
    snprintf(container, sizeof(container), "%s?format=xml&path=%s",
              encoded_container, encoded_object);
    curl_free(encoded_container);
    curl_free(encoded_object);
  }
  response = send_request("GET", container, NULL, xmlctx, NULL);
  xmlParseChunk(xmlctx, "", 0, 1);
  if (xmlctx->wellFormed && response >= 200 && response < 300)
  {
    xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc);
    for (onode = root_element->children; onode; onode = onode->next)
      if ((onode->type == XML_ELEMENT_NODE) &&
         (!strcasecmp((const char *)onode->name, "object") || !strcasecmp((const char *)onode->name, "container")))
      {
        dir_entry *de = (dir_entry *)malloc(sizeof(dir_entry));
        de->size = 0;
        de->last_modified = time(NULL);
        if (!strcasecmp((const char *)onode->name, "container"))
          de->content_type = strdup("application/directory");
        for (anode = onode->children; anode; anode = anode->next)
        {
          char *content = "<?!?>";
          for (text_node = anode->children; text_node; text_node = text_node->next)
            if (text_node->type == XML_TEXT_NODE)
              content = (char *)text_node->content;
          if (!strcasecmp((const char *)anode->name, "name"))
          {
            if (strrchr(content, '/'))
              de->name = strdup(strrchr(content, '/')+1);
            else
              de->name = strdup(content);
            if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0)
              de->full_name = NULL;
          }
          if (!strcasecmp((const char *)anode->name, "bytes"))
            de->size = strtoll(content, NULL, 10);
          if (!strcasecmp((const char *)anode->name, "content_type"))
          {
            de->content_type = strdup(content);
            char *semicolon = strchr(de->content_type, ';');
            if (semicolon)
              *semicolon = '\0';
          }
          if (!strcasecmp((const char *)anode->name, "last_modified"))
          {
            struct tm last_modified;
            strptime(content, "%FT%T", &last_modified);
            de->last_modified = mktime(&last_modified);
          }
        }
        de->isdir = de->content_type &&
            ((strstr(de->content_type, "application/folder") != NULL) ||
             (strstr(de->content_type, "application/directory") != NULL));
        de->next = *dir_list;
        *dir_list = de;
      }
    retval = 1;
  }
  xmlFreeDoc(xmlctx->myDoc);
  xmlFreeParserCtxt(xmlctx);
  return retval;
}