Example #1
0
 void on_field(boost::string_ref const& s, error_code&)
 {
     flush();
     field_.append(s.data(), s.size());
 }
Example #2
0
GurlsOptionsList::GurlsOptionsList(std::string ExpName, bool usedefopt): GurlsOption(OptListOption), name(ExpName)
{
    table = new std::map<std::string, GurlsOption* >();

    (*table)["Name"] = new OptString(ExpName);

    if(usedefopt)
    {

        //		opt.combineclasses = @mean; % How to combine performance measure per class (mean/median/min/max?)
        (*table)["combineclasses"] = new OptFunction("mean");

        (*table)["name"] = new OptString(ExpName);
        (*table)["plotstr"] = new OptString(ExpName);

#ifdef USE_BINARY_ARCHIVES
        (*table)["savefile"] = new OptString(ExpName.append(".bin"));
#else
        (*table)["savefile"] = new OptString(ExpName.append(".txt"));
#endif
		
        (*table)["todisk"] = new OptNumber(1);
        // ================================================== Algorithm options

        //		opt.kernel.type = 'rbf';
        (*table)["singlelambda"] = new OptFunction("median");
        (*table)["predbagmethod"] = new OptString("vote");

        // NOTE: lambda is searched between
        // [min(eig_r, opt.smallnumber), eig_1],
        // where r = rank, eig_1 = max eig val.
        (*table)["smallnumber"] = new OptNumber(1e-8);

        // ================================================== Directory options
        (*table)["tmpdir"] = new OptString(ExpName);

        // ===================================================== Output options
        (*table)["savekernel"] = new OptNumber(1);
        (*table)["saveanalysis"] = new OptNumber(1);
        //		opt.hoperf = @perf_precrec;
        (*table)["ploteval"] = new OptString("acc");
        //		WARNING: this should be an array of strings...
        (*table)["perfeval"] = new OptString("acc");

        // ======================================================== Data option
        (*table)["nholdouts"] = new OptNumber(1);
        (*table)["hoproportion"] = new OptNumber(0.2);
        (*table)["hoperf"] = new OptString("macroavg");
//        (*table)["nlambda"] = new OptNumber(100);
        (*table)["nsigma"] =  new OptNumber(25);
        (*table)["nlambda"] = new OptNumber(20);
//        (*table)["nsigma"] =  new OptNumber(10);
        (*table)["eig_percentage"] = new OptNumber(5);


    // ======================================================== Pegasos option
        (*table)["subsize"]   = new OptNumber(50);
        (*table)["calibfile"] = new OptString("foo");
        (*table)["epochs"]   = new OptNumber(4);

        // ============================================================== Quiet
        // Currenty either 0 or 1; levels of verbosity may be implemented later;
        (*table)["verbose"] = new OptNumber(1);

        // ======================================================= Version info
        (*table)["version"] = new OptString("2.0");


        GurlsOptionsList * randfeats = new GurlsOptionsList("randfeats");
        randfeats->table->insert(pair<std::string,GurlsOption*>("D", new OptNumber(500)));
        randfeats->table->insert(pair<std::string,GurlsOption*>("samplesize", new OptNumber(100)));

        (*table)["randfeats"] = randfeats;

    }

}
 void CResourcePathDirector::setCommonResourcePath(std::string strOriginResPath)
 {
     m_strCommonResourcePath = strOriginResPath.append("/");
 }
Example #4
0
 static void apply( const Input& in, std::string& s )
 {
    s.append( in.begin(), in.size() );
 }
Example #5
0
int32 GetConfigIntDefault(std::string base, const char* name, int32 value)
{
    base.append(name);
    return sConfigMgr->GetIntDefault(base.c_str(), value);
}
Example #6
0
 inline void append_double_precision_pragma<double>(viennacl::ocl::context const & ctx, std::string & source)
 {
   source.append("#pragma OPENCL EXTENSION " + ctx.current_device().double_support_extension() + " : enable\n\n");
 }
Example #7
0
 virtual void sendImpl(const void *data, int size, int code, bool chunked) {
   m_response.clear();
   m_response.append((const char *)data, size);
   m_code = code;
 }
Example #8
0
std::string CSysInfo::GetOsPrettyNameWithVersion(void)
{
  static std::string osNameVer;
  if (!osNameVer.empty())
    return osNameVer;

#if defined (TARGET_WINDOWS)
  OSVERSIONINFOEXW osvi = {};

  osNameVer = "Windows ";
  if (sysGetVersionExWByRef(osvi))
  {
    switch (GetWindowsVersion())
    {
    case WindowsVersionVista:
      if (osvi.wProductType == VER_NT_WORKSTATION)
        osNameVer.append("Vista");
      else
        osNameVer.append("Server 2008");
      break;
    case WindowsVersionWin7:
      if (osvi.wProductType == VER_NT_WORKSTATION)
        osNameVer.append("7");
      else
        osNameVer.append("Server 2008 R2");
      break;
    case WindowsVersionWin8:
      if (osvi.wProductType == VER_NT_WORKSTATION)
        osNameVer.append("8");
      else
        osNameVer.append("Server 2012");
      break;
    case WindowsVersionWin8_1:
      if (osvi.wProductType == VER_NT_WORKSTATION)
        osNameVer.append("8.1");
      else
        osNameVer.append("Server 2012 R2");
      break;
    case WindowsVersionFuture:
      osNameVer.append("Unknown Future Version");
      break;
    default:
      osNameVer.append("Unknown version");
      break;
    }

    // Append Service Pack version if any
    if (osvi.wServicePackMajor > 0 || osvi.wServicePackMinor > 0)
    {
      osNameVer.append(StringUtils::Format(" SP%d", osvi.wServicePackMajor));
      if (osvi.wServicePackMinor > 0)
      {
        osNameVer.append(StringUtils::Format(".%d", osvi.wServicePackMinor));
      }
    }
  }
  else
    osNameVer.append(" unknown");
#elif defined(TARGET_FREEBSD) || defined(TARGET_DARWIN_IOS) || defined(TARGET_DARWIN_OSX)
  osNameVer = GetOsName() + " " + GetOsVersion();
#elif defined(TARGET_ANDROID)
  osNameVer = GetOsName() + " " + GetOsVersion() + " API level " +   StringUtils::Format("%d", CJNIBuild::SDK_INT);
#elif defined(TARGET_LINUX)
  osNameVer = getValueFromOs_release("PRETTY_NAME");
  if (osNameVer.empty())
  {
    osNameVer = getValueFromLsb_release(lsb_rel_description);
    std::string osName(GetOsName(true));
    if (!osName.empty() && osNameVer.find(osName) == std::string::npos)
      osNameVer = osName + osNameVer;
    if (osNameVer.empty())
      osNameVer = "Unknown Linux Distribution";
  }

  if (osNameVer.find(GetOsVersion()) == std::string::npos)
    osNameVer += " " + GetOsVersion();
#endif // defined(TARGET_LINUX)

  if (osNameVer.empty())
    osNameVer = "Unknown OS Unknown version";

  return osNameVer;

}
Example #9
0
void format(std::string& str, long value)
{
    char buffer[64];
    std::sprintf(buffer, "%ld", value);
    str.append(buffer);
}
Example #10
0
//proc char * buf
//if this buf ends a command~~ SEN_FLAG = TRUE
//string sentence
//string cmd_header
//iOfSen nOfSen just for examine
bool proc_buf(const char * buf, bool & SEN_FLAG, std::string & sentence, std::string & cmd_header, std::string & usr_name, int & nOfSen, int & iOfSen, bool & isINV)
{
	int i_f_brac = 0;
	int i_l_brac = -1;

	std::vector<int> v_space;

	//1st assumption: buf's content doesnt cross the border
	//2nd assumption: the sentences in a command has the same cmd header 
	//3rd assumption: there're only 2 types of REQ ~~ single REQ | compound REQ
	//4th assumption: compound REQ has a stereotype( has 2 digital page indexs ... username's upper limit is 20 )
	//5th assumption: compound REQ must have a sentence behind it

	//get i_f_brac and i_l_brac
	for( int i = 0; i < DEFAULT_BUFFER_LENGTH; i++ )
	{
		if( buf[i] == ']' )
		{
			i_l_brac = i;
			break;
		}
	}
	if( (buf[0] != '[') || (i_l_brac == DEFAULT_BUFFER_LENGTH-1) )
	{
		return false;
	}

	//judge whether this cammand is a single REQ~
	for( int i = i_f_brac; i < i_l_brac; i++ )
	{
		if( buf[i] == ' ' )
		{
			v_space.push_back(i);
		}
	}

	if( v_space.size()==0 )		//is a single REQ
	{
		SEN_FLAG = true;

		//make a replica of header~~
		char * header = new char [ i_l_brac - i_f_brac ];
		for(int i = 0; i < i_l_brac - i_f_brac - 1; i++)
		{
			header[i] = buf[ i_f_brac+1 + i ];
		}
		header[ i_l_brac-i_f_brac-1 ] = '\0';

		cmd_header.append(header);

		printf( "\n%s\n", cmd_header.c_str() );

		delete [] header;

		return true;
	}
	else if( v_space.size()==3 )		//is a compound REQ
	{
		//****seperate the buff****

		int i_sep[6] = { i_f_brac, v_space.at(0), v_space.at(1), v_space.at(2), i_l_brac, strlen(buf) };

		std::string g_cmd;
		std::string g_iPage;
		std::string g_nPage;
		std::string g_user;
		std::string g_sen;
		
		//char * cmd_str = new char [ i_sep[1]-i_sep[0] ];
		//char * iCUR_str = new char [ i_sep[2]-i_sep[1] ];
		//char * iALL_str = new char [ i_sep[3]-i_sep[2] ];
		//char * username_str = new char [ i_sep[4]-i_sep[3] ];
		//char * sen_str = new char [ i_sep[5]-i_sep[4] ];
		int iCUR = 0;
		int iALL = 0;

		//cmd_str
		for( int i = 0; i < i_sep[1]-i_sep[0] - 1; i++ )
		{
			//cmd_str[i] = buf[ i_sep[0]+1 + i ];
			g_cmd.push_back( buf[ i_sep[0]+1 + i ] );
		}
		//cmd_str[i_sep[1]-i_sep[0] - 1] = '\0';

		//iCUR_str
		for( int i = 0; i < i_sep[2]-i_sep[1] - 1; i++ )
		{
			//iCUR_str[i] = buf[ i_sep[1]+1 + i ];
			g_iPage.push_back( buf[ i_sep[1]+1 + i ] );
		}
		//iCUR_str[i_sep[2]-i_sep[1] - 1] = '\0';
		//iALL_str
		for( int i = 0; i < i_sep[3]-i_sep[2] - 1; i++ )
		{
			//iALL_str[i] = buf[ i_sep[2]+1 + i ];
			g_nPage.push_back( buf[ i_sep[2]+1 + i ] );
		}
		//iALL_str[i_sep[3]-i_sep[2] - 1] = '\0';
		//username_str
		for( int i = 0; i < i_sep[4]-i_sep[3] - 1; i++ )
		{
			//username_str[i] = buf[ i_sep[3]+1 + i ];
			g_user.push_back( buf[ i_sep[3]+1 + i ] );
		}
		//username_str[i_sep[4]-i_sep[3] - 1] = '\0';	
		//sen_str
		for( int i = 0; i < i_sep[5]-i_sep[4] - 1; i++ )
		{
			//sen_str[i] = buf[ i_sep[4]+1 + i ];
			g_sen.push_back( buf[ i_sep[4]+1 + i ] );
		}
		//sen_str[i_sep[5]-i_sep[4] - 1] = '\0';

		iCUR = atoi( g_iPage.c_str() );
		iALL = atoi( g_nPage.c_str() );
		

		//****VALIDATION****
		//whether this is an initialization?
		if( nOfSen == -1 && iOfSen == -1 )
		{
			iOfSen = iCUR;
			nOfSen = iALL;

			usr_name.append( g_user );
			cmd_header.append( g_cmd );
		}

		//clauses
		if( usr_name != g_user )
		{
			isINV = true;
		}
		if( nOfSen != iALL )
		{
			isINV = true;
		}
		if( (iOfSen != 1) && (iOfSen+1 != iCUR) )
		{
			isINV = true;
		}
		if( nOfSen != iALL )
		{
			isINV = true;
		}
		if( g_cmd != cmd_header )
		{
			isINV = true;
		}
		
		//**** return parameters ****
		iOfSen = iCUR;
		sentence.append( g_sen );

		printf( "\n%s (%d, %d) %d\n", g_cmd.c_str(), iOfSen, nOfSen, (int)isINV );
		//printf( "%s\n\n", sentence.c_str() );
		
		if( iOfSen == nOfSen )
		{
			SEN_FLAG = true;
			return true;
		}
		else
		{
			SEN_FLAG = false;
			return false;
		}
				

		//return true;
	}
	else
	{
		//this case would never happen
		return false;
	}

	return true;
}
Example #11
0
std::string CSysInfo::GetUserAgent()
{
  static std::string result;
  if (!result.empty())
    return result;

  result = "XBMC/" + g_infoManager.GetLabel(SYSTEM_BUILD_VERSION_SHORT) + " (";
#if defined(TARGET_WINDOWS)
  result += GetKernelName() + " " + GetKernelVersion();
  BOOL bIsWow = FALSE;
  if (IsWow64Process(GetCurrentProcess(), &bIsWow) && bIsWow)
      result.append("; WOW64");
  else
  {
    SYSTEM_INFO si = {};
    GetSystemInfo(&si);
    if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
      result.append("; Win64; x64");
    else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
      result.append("; Win64; IA64");
    else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM)
      result.append("; ARM");
  }
#elif defined(TARGET_DARWIN)
#if defined(TARGET_DARWIN_IOS)
  std::string iDevStr(GetModelName()); // device model name with number of model version
  size_t iDevStrDigit = iDevStr.find_first_of("0123456789");
  std::string iDev(iDevStr, 0, iDevStrDigit);  // device model name without number 
  if (iDevStrDigit == 0)
    iDev = "unknown";
  result += iDev + "; ";
  std::string iOSVerison(GetOsVersion());
  size_t lastDotPos = iOSVerison.rfind('.');
  if (lastDotPos != std::string::npos && iOSVerison.find('.') != lastDotPos
      && iOSVerison.find_first_not_of('0', lastDotPos + 1) == std::string::npos)
    iOSVerison.erase(lastDotPos);
  StringUtils::Replace(iOSVerison, '.', '_');
  if (iDev == "iPad" || iDev == "AppleTV")
    result += "CPU OS ";
  else
    result += "CPU iPhone OS ";
  result += iOSVerison + " like Mac OS X";
#else
  result += "Macintosh; ";
  std::string cpuFam(GetBuildTargetCpuFamily());
  if (cpuFam == "x86")
    result += "Intel ";
  else if (cpuFam == "PowerPC")
    result += "PPC ";
  result += "Mac OS X ";
  std::string OSXVersion(GetOsVersion());
  StringUtils::Replace(OSXVersion, '.', '_');
  result += OSXVersion;
#endif
#elif defined(TARGET_ANDROID)
  result += "Linux; Android ";
  std::string versionStr(GetOsVersion());
  const size_t verLen = versionStr.length();
  if (verLen >= 2 && versionStr.compare(verLen - 2, 2, ".0", 2) == 0)
    versionStr.erase(verLen - 2); // remove last ".0" if any
  result += versionStr;
  std::string deviceInfo(GetModelName());

  char buildId[PROP_VALUE_MAX];
  int propLen = __system_property_get("ro.build.id", buildId);
  if (propLen > 0 && propLen <= PROP_VALUE_MAX)
  {
    if (!deviceInfo.empty())
      deviceInfo += " ";
    deviceInfo += "Build/";
    deviceInfo.append(buildId, propLen);
  }

  if (!deviceInfo.empty())
    result += "; " + deviceInfo;
#elif defined(TARGET_POSIX)
  result += "X11; ";
  struct utsname un;
  if (uname(&un) == 0)
  {
    std::string cpuStr(un.machine);
    if (cpuStr == "x86_64" && GetXbmcBitness() == 32)
      cpuStr = "i686 (x86_64)";
    result += un.sysname;
    result += " ";
    result += cpuStr;
  }
  else
    result += "Unknown";
#else
  result += "Unknown";
#endif
  result += ")";
  // add fork ID here in form:
  // result += " XBMC_FORK_" + "forkname" + "/" + "1.0"; // default fork number is '1.0'
#ifdef TARGET_RASPBERRY_PI
  result += " XBMC_HW_RaspberryPi/1.0";
#elif defined (TARGET_DARWIN_IOS)
  std::string iDevVer;
  if (iDevStrDigit == std::string::npos)
    iDevVer = "0.0";
  else
    iDevVer.assign(iDevStr, iDevStrDigit, std::string::npos);
  StringUtils::Replace(iDevVer, ',', '.');
  result += " XBMC_HW_" + iDev + "/" + iDevVer;
#endif
  // add more device IDs here if needed. 
  // keep only one device ID in result! Form:
  // result += " XBMC_HW_" + "deviceID" + "/" + "1.0"; // '1.0' if device has no version

#if defined(TARGET_ANDROID)
  // Android has no CPU string by default, so add it as additional parameter
  struct utsname un1;
  if (uname(&un1) == 0)
  {
    std::string cpuStr(un1.machine);
    StringUtils::Replace(cpuStr, ' ', '_');
    result += " XBMC_CPU/" + cpuStr;
  }
#endif

  result += " XBMC_BITNESS/" + StringUtils::Format("%d", GetXbmcBitness());

  std::string fullVer(g_infoManager.GetLabel(SYSTEM_BUILD_VERSION));
  StringUtils::Replace(fullVer, ' ', '-');
  result += " Version/" + fullVer;

  return result;
}
Example #12
0
// Devuelve el jugador que va a usar el cliente
// Caso 1: Si el jugador NO está en uso se crea y se devuelve una copia del mismo
// Caso 2: Si el jugador SI está en uso y SI se encuentra "congelado", se cambia su condición y se devuelve una copia del mismo
// Caso 3: Si el jugador SI está en uso y NO se encuentra "congelado", se elige otro jugador que no se encuentre en uso, se crea y se devuelve una copia del mismo
ProxyModeloEntidad::stEntidad ModeloFactory::elegirProtagonista(ModeloNivel* modeloNivel,std::string& mote,std::string& nombreEntidadPersonaje,int& id){

	std::list<ModeloJugador*> listaEntidades = modeloNivel->getJugadores();
	std::list<std::string> listaJugadoresUsados;
	ProxyModeloEntidad::stEntidad stEntidad;
	ModeloJugador* pEntidad = NULL;
	bool moteEncontrado = false;

	for( std::list<ModeloJugador*>::iterator itEntidad = listaEntidades.begin() ; itEntidad != listaEntidades.end() ; itEntidad++ ){
		// Obtengo el nombre de jugador y entidad
		std::string moteJugador = (*itEntidad)->nombreJugador();
		std::string entidadPersonaje = (*itEntidad)->modeloEntidad()->nombreEntidad();
		
		// Guardo el nombre de la entidad usada
		listaJugadoresUsados.push_back(entidadPersonaje);
		
		// Comparo el nombre del jugador usado con el que me pide el usuario nuevo
		if( moteJugador.compare(mote) == 0 ){
			pEntidad = (*itEntidad);
			moteEncontrado = true;
		}
	}

	// NOTA: Observar que si encuentro al usuario, ya no me interesa el personaje que eligió el cliente, porque este ya se encuentra creado
	if( moteEncontrado == true ){		
		// Me fijo si está congelado o no
		if( pEntidad->estaDesconectado() == true){

			// Si está congelado y es el mismo nombre de usuario, lo descongelo y obtengo sus datos
			pEntidad->estaDesconectado(false);

			// Cargo la entidad
			stEntidad = pEntidad->stEntidad();
			pEntidad->cargarMatriz(stEntidad);

			// Como se está conectando de vuelta, le reasigno al socket de cliente el ID que tenia antes (stEntidad.id), para poder reconocerlo en el loop de juego
			pSocket->renombrarIdCliente(id,stEntidad.id);

			// Renombro el id pasado por referencia
			id = stEntidad.id;

			return stEntidad;

		}else{
			// Si no está congelado y es el mismo nombre de usuario, no lo puedo usar, así que busco otro personaje libre y lo creo
			std::string nombrePersonajeObtenido = this->obtenerPersonajeLibre(listaJugadoresUsados,nombreEntidadPersonaje);
			
			// Anexo el ID al mote para diferenciarlo del que ya está jugando
			std::stringstream ss;
			ss << id;
			mote.append(ss.str());
			
			nombreEntidadPersonaje = nombrePersonajeObtenido;	// Actualizo el nombre que va a tener el personaje
			this->crearJugador(modeloNivel,stEntidad,nombrePersonajeObtenido,mote,id);
			return stEntidad;
		}
	}else{
		// Si no encontré ese nombre entre los jugadores creo uno nuevo
		std::string nombrePersonajeObtenido = this->obtenerPersonajeLibre(listaJugadoresUsados,nombreEntidadPersonaje);
		nombreEntidadPersonaje = nombrePersonajeObtenido;	// Actualizo el nombre que va a tener el personaje
		this->crearJugador(modeloNivel,stEntidad,nombrePersonajeObtenido,mote,id);
		return stEntidad;
	}
	return stEntidad;
}
Example #13
0
void htmlrenderer::prepare_newline(std::string& line, int indent_level) {
	line = "";
	line.append(indent_level*2, ' ');
}
Example #14
0
 void on_value(boost::string_ref const& s, error_code&)
 {
     value_.append(s.data(), s.size());
 }
Example #15
0
static std::vector<std::string> listFiles(std::string path)
{
    std::vector<std::string> results;

#ifdef _WIN32
    if (path.back() != '/')
        path.append("/*");
    else
        path.append("*");

    //convert to wide chars for windows
    std::basic_string<TCHAR> wPath;
    wPath.assign(path.begin(), path.end());

    WIN32_FIND_DATA findData;
    HANDLE hFind = FindFirstFile(wPath.c_str(), &findData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        std::cout << "Failed to find file data, invalid file handle returned" << std::endl;
        return results;
    }

    do
    {
        if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) //not a directory
        {
            //convert from wide char
            std::basic_string<TCHAR> wName(findData.cFileName);
            std::string fileName;
            fileName.assign(wName.begin(), wName.end());
            results.push_back(fileName);
        }

    } while (FindNextFile(hFind, &findData) != 0);
    FindClose(hFind);

    return std::move(results);
#else
    if (path.back() != '/')
        path.append("/.");
    else
        path.append(".");

    struct dirent* dp;
    DIR* dir = opendir(path.c_str());

    if (dir)
    {
        while ((dp = readdir(dir)) != nullptr)
        {
            std::string workingPath(path);
            workingPath.append("/");
            workingPath.append((dp->d_name));

            struct stat buf;
            if (!stat(workingPath.c_str(), &buf))
            {
                if (!S_ISDIR(buf.st_mode))
                {
                    results.emplace_back(dp->d_name);
                }
            }
        }
        closedir(dir);
    }
    return std::move(results);
#endif //_WIN32
}
Example #16
0
void formatHex(std::string& str, unsigned long value)
{
    char buffer[64];
    std::sprintf(buffer, "%lX", value);
    str.append(buffer);
}
Example #17
0
int Parser::bufferParse(std::string &log_info, unsigned int max_packets) {
  unsigned int valid_len = m_len - m_restart_offset;
  uint8_t *p = m_buffer + m_restart_offset;
  unsigned int processed = 0;
  bool stopped = false;

  /* Is there anything to do? */
  if (!valid_len) {
    log_info.append("bufferParse() nothing to do; ");
    return 0;
  }

  /* If we don't care how many packets we process, then set the limit
   * above the range of possibility to avoid needing to check for zero
   * multiple times.
   */
  if (!max_packets)
    max_packets = m_size;

  /* If we're processing an oversize packet, then we will find its
   * data at the front of the buffer. We'll either consume our
   * entire buffer, or find the end of the oversize packet and
   * process the rest of the buffer as normal.
   */
  if (m_oversize_len) {
    unsigned int chunk_len;

    chunk_len = m_oversize_len;
    if (valid_len < chunk_len)
      chunk_len = valid_len;
    stopped = rxOversizePkt(nullptr, p, m_oversize_offset, chunk_len);
    m_oversize_offset += chunk_len;
    m_oversize_len -= chunk_len;
    valid_len -= chunk_len;
    p += chunk_len;

    /* Did we finish this packet? */
    if (!m_oversize_len)
      processed++;
  }

  while (valid_len >= PacketHeader::header_length() &&
         processed < max_packets && !stopped) {

    PacketHeader hdr(p);

    if (hdr.payload_length() % 4)
      throw invalid_packet("Payload length not "
                           "multiple of 4");

    if (m_max_size < hdr.packet_length()) {
      /* This packet is over the maximum limit; we'll
       * call the oversize handler with this first
       * chunk, consuming our entire buffer.
       */
      stopped = rxOversizePkt(&hdr, p, 0, valid_len);
      m_oversize_len = hdr.packet_length() - valid_len;
      m_oversize_offset = valid_len;
      valid_len = 0;
      break;
    }

    if (m_size < hdr.packet_length()) {
      /* This packet is too big to possibly fit in our
       * current buffer, so we need to grow. Once we've
       * resized, return to our caller as we obviously
       * don't have the full packet yet.
       */
      unsigned int new_size = m_size;
      uint8_t *new_buffer;

      do {
        new_size *= 2;
      } while (new_size < hdr.packet_length());

      if (new_size > m_max_size)
        new_size = m_max_size;

      new_buffer = new uint8_t[new_size];
      memcpy(new_buffer, p, valid_len);

      delete[] m_buffer;
      m_buffer = new_buffer;
      m_size = new_size;

      /* We moved the data to the front of the buffer as
       * part of the resize; account for that.
       */
      m_restart_offset = 0;
      m_len = valid_len;

      // log what we did...
      std::stringstream ss;
      ss << processed;
      log_info.append("bufferParse(): resized, processed ");
      log_info.append(ss.str());
      log_info.append(" packets; ");

      return processed;
    }

    if (valid_len < hdr.packet_length())
      break;

    Packet pkt(p, hdr.packet_length());

    p += hdr.packet_length();
    valid_len -= hdr.packet_length();

    stopped = rxPacket(pkt);
    processed++;

    // log failed packet parsing...!
    if (stopped) {
      std::stringstream ss;
      log_info.append("bufferParse(): rxPacket() returned error for type=");
      ss << pkt.type();
      log_info.append(ss.str());
      log_info.append(", stopped; ");
    }
  }

  /* We're done processing for this round. Update our position and/or
   * amount of buffered data so that we restart in the correct spot
   * on our next call.
   *
   * We only need to move data if we ran out of data to process --
   * ie, we processed fewer packets than requested without being
   * stopped by a callback. This moves any possible fragment of a
   * packet to the front, maximizing the room for more data. If this
   * occurs coincidentally with a stop request, the next call to
   * to bufferParse() will only see the fragment and stop, but that
   * should be rare.
   */
  if (valid_len) {
    if (!stopped && processed < max_packets) {
      if (p != m_buffer)
        memmove(m_buffer, p, valid_len);
      m_len = valid_len;
      m_restart_offset = 0;
    } else {
      /* We know that the offset will fit into an unsigned
       * int, as that is the type we use for the buffer size.
       */
      m_restart_offset = static_cast<unsigned int>(p - m_buffer);
    }
  } else {
    /* We used up the buffer. */
    m_len = 0;
    m_restart_offset = 0;
  }

  /* We need an 32 GB buffer before we can fit 2^31 packets, so
   * casting to int is safe here.
   */

  std::stringstream ss;
  int rc;

  if (stopped) {
    rc = -static_cast<int>(processed);
    // add to "stopped" log info...
    ss << processed;
    log_info.append("had parsed ");
    log_info.append(ss.str());
    log_info.append(" packets; ");
  } else {
    rc = static_cast<int>(processed);
    // create log info...
    ss << rc;
    log_info.append("bufferParse(): Done. Parsed ");
    log_info.append(ss.str());
    log_info.append(" packets; ");
  }

  return rc;
}
Example #18
0
void formatHex(std::string& str, UInt64 value)
{
    char buffer[64];
    std::sprintf(buffer, "%" I64_FMT "X", value);
    str.append(buffer);
}
ShaderCombiner::ShaderCombiner(Combiner & _color, Combiner & _alpha, const gDPCombine & _combine) : m_combine(_combine)
{
    char strCombiner[1024];
    m_nInputs = compileCombiner(_color, _alpha, strCombiner);

    if (usesTexture()) {
        strFragmentShader.assign(fragment_shader_header_common_variables);
        strFragmentShader.append(fragment_shader_header_common_functions);
    }
    else {
        strFragmentShader.assign(fragment_shader_header_common_variables_notex);
        strFragmentShader.append(fragment_shader_header_common_functions_notex);
    }
    strFragmentShader.append(fragment_shader_header_main);
    const bool bUseLod = usesLOD();
    if (bUseLod) {
        strFragmentShader.append("  lowp vec4 readtex0, readtex1; \n");
        strFragmentShader.append("  lowp float lod_frac = mipmap(readtex0, readtex1);	\n");
    } else {
        if (usesTile(0)) {
            strFragmentShader.append("  nCurrentTile = 0; \n");
            strFragmentShader.append("  lowp vec4 readtex0 = readTex(uTex0, vTexCoord0, uFbMonochrome[0], uFbFixedAlpha[0] != 0); \n");
        }
        if (usesTile(1)) {
            strFragmentShader.append("  nCurrentTile = 1; \n");
            strFragmentShader.append("  lowp vec4 readtex1 = readTex(uTex1, vTexCoord1, uFbMonochrome[1], uFbFixedAlpha[1] != 0); \n");
        }
    }
    const bool bUseHWLight = config.generalEmulation.enableHWLighting != 0 && GBI.isHWLSupported() && usesShadeColor();
    if (bUseHWLight)
        strFragmentShader.append("  calc_light(vNumLights, vShadeColor.rgb, input_color); \n");
    else
        strFragmentShader.append("  input_color = vShadeColor.rgb;\n");
    strFragmentShader.append("  vec_color = vec4(input_color, vShadeColor.a); \n");
    strFragmentShader.append(strCombiner);

    strFragmentShader.append(
        "  if (uEnableAlphaTest != 0) {				\n"
        "    lowp float alphaTestValue = (uAlphaCompareMode == 3 && alpha2 > 0.0) ? snoise() : uAlphaTestValue;	\n"
        "    if  (alpha2 < alphaTestValue) discard;	\n"
        "  }										\n"
    );

    if (!g_weakGLSL) {
        strFragmentShader.append(
            "  lowp int fogUsage = uFogUsage;			\n"
            "  if (fogUsage >= 256) fogUsage -= 256;	\n"
            "  if (fogUsage == 2) fragColor = vec4(color2, uFogColor.a);				\n"
            "  else if (fogUsage == 3) fragColor = uFogColor;							\n"
            "  else if (fogUsage == 4) fragColor = vec4(color2, uFogColor.a*alpha2);	\n"
            "  else fragColor = vec4(color2, alpha2);									\n"
        );
    } else
        strFragmentShader.append("  fragColor = vec4(color2, alpha2); \n");

    strFragmentShader.append(
        "  if (uFogUsage == 257) \n"
        "    fragColor.rgb = mix(fragColor.rgb, uFogColor.rgb, vFogFragCoord); \n"
        "  if (uGammaCorrectionEnabled != 0) \n"
        "    fragColor.rgb = pow(fragColor.rgb, vec3(1.0 / uGammaCorrectionLevel)); \n"
        "  gl_FragColor = fragColor; \n"
    );

    strFragmentShader.append(fragment_shader_end);

    if (config.generalEmulation.enableNoise == 0)
        strFragmentShader.append(fragment_shader_dummy_noise);

    if (bUseHWLight)
        strFragmentShader.append(fragment_shader_calc_light);
    if (bUseLod)
        strFragmentShader.append(fragment_shader_fake_mipmap);
    else if (usesTexture()) {
        if (config.texture.bilinearMode == BILINEAR_3POINT)
            strFragmentShader.append(fragment_shader_readtex_3point);
        else
            strFragmentShader.append(fragment_shader_readtex);
    }
    if (config.generalEmulation.enableNoise != 0)
        strFragmentShader.append(fragment_shader_noise);

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    const GLchar * strShaderData = strFragmentShader.data();
    glShaderSource(fragmentShader, 1, &strShaderData, NULL);
    glCompileShader(fragmentShader);
    if (!checkShaderCompileStatus(fragmentShader))
        LOG(LOG_ERROR, "Error in fragment shader:\n%s\n", strFragmentShader.data());

    m_program = glCreateProgram();
    _locate_attributes();
    if (usesTexture())
        glAttachShader(m_program, g_vertex_shader_object);
    else
        glAttachShader(m_program, g_vertex_shader_object_notex);
    glAttachShader(m_program, fragmentShader);
    glLinkProgram(m_program);
    assert(checkProgramLinkStatus(m_program));
    glDeleteShader(fragmentShader);
    _locateUniforms();
}
Example #20
0
void formatHex(std::string& str, int value)
{
    char buffer[64];
    std::sprintf(buffer, "%X", value);
    str.append(buffer);
}
void WindowsTcpSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException)
{
	SOCKET socket_fd = this->Connect();
	char buffer[BUFFER_SIZE];
	bool fullyWritten = false;
	string toSend = message;
	do
	{
		int byteWritten = send(socket_fd, toSend.c_str(), toSend.size(), 0);
		if(byteWritten == -1)
		{
			string message = "send() failed";
			int err = WSAGetLastError();
			switch(err)
			{
				case WSANOTINITIALISED:
				case WSAENETDOWN:
				case WSAEACCES:
				case WSAEINTR:
				case WSAEINPROGRESS:
				case WSAEFAULT:
				case WSAENETRESET:
				case WSAENOBUFS:
				case WSAENOTCONN:
				case WSAENOTSOCK:
				case WSAEOPNOTSUPP:
				case WSAESHUTDOWN:
				case WSAEWOULDBLOCK:
				case WSAEMSGSIZE:
				case WSAEHOSTUNREACH:
				case WSAEINVAL:
				case WSAECONNABORTED:
				case WSAECONNRESET:
				case WSAETIMEDOUT:
					message = GetErrorMessage(err);
					break;
			}
			closesocket(socket_fd);
			throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message);
		}
		else if(static_cast<unsigned int>(byteWritten) < toSend.size())
		{
			int len = toSend.size() - byteWritten;
			toSend = toSend.substr(byteWritten + sizeof(char), len);
		}
		else
			fullyWritten = true;
	} while(!fullyWritten);

	do
	{
		int nbytes = recv(socket_fd, buffer, BUFFER_SIZE, 0);
		if(nbytes == -1)
		{
			string message = "recv() failed";
			int err = WSAGetLastError();
			switch(err)
			{
				case WSANOTINITIALISED:
				case WSAENETDOWN:
				case WSAEFAULT:
				case WSAENOTCONN:
				case WSAEINTR:
				case WSAEINPROGRESS:
				case WSAENETRESET:
				case WSAENOTSOCK:
				case WSAEOPNOTSUPP:
				case WSAESHUTDOWN:
				case WSAEWOULDBLOCK:
				case WSAEMSGSIZE:
				case WSAEINVAL:
				case WSAECONNABORTED:
				case WSAETIMEDOUT:
				case WSAECONNRESET:
					message = GetErrorMessage(err);
					break;
			}
			closesocket(socket_fd);
			throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message);
		}
		else
		{
			string tmp;
			tmp.append(buffer, nbytes);
			result.append(buffer,nbytes);
		}

	} while(result.find(DELIMITER_CHAR) == string::npos);

	closesocket(socket_fd);
}
Example #22
0
void format(std::string& str, unsigned value)
{
    char buffer[64];
    std::sprintf(buffer, "%u", value);
    str.append(buffer);
}
Example #23
0
    /*
    ** Build Json string that represent this element.
    */
    void MongoElement::buildJsonString(std::string &con)
    {
        switch (_bsonElement.type())
        {
        /** double precision floating point value */
        case NumberDouble:
            con.append(QtUtils::toStdString<std::string>(QString::number(_bsonElement.Double(),'g',14)));
            break;

        /** character string, stored in utf8 */
        case String:
            {
            /*
            ** If you'll write:
            ** 
            **   int valsize    = element.valuesize();
            **   int strsize    = element.valuestrsize();
            **   int bytescount = qstrlen(element.valuestr());
            **  
            ** You'll get:
            **
            **   bytescount + 1 == strsize
            **   strsize + 4    == valsize
            **
            ** So:
            **   bytescount + 5 == valsize
            **
            */

                con.append(_bsonElement.valuestr(), _bsonElement.valuestrsize() - 1);
            }
            break;

        /** an embedded object */
        case Object:
            {
                MongoDocumentPtr doc = asDocument();
                doc->buildJsonString(con);
            }
            break;

        /** an embedded array */
        case Array:
            {
                MongoDocumentPtr doc = asDocument();
                doc->buildJsonString(con);
            }
            break;

        /** binary data */
        case BinData:
            {
                mongo::BinDataType binType = _bsonElement.binDataType();
                if (binType == mongo::newUUID || binType == mongo::bdtUUID) {
                    std::string uuid = HexUtils::formatUuid(_bsonElement, AppRegistry::instance().settingsManager()->uuidEncoding());
                    con.append(uuid);
                    break;
                }

                con.append("<binary>");
            }
            break;

        /** Undefined type */
        case Undefined:
            con.append("<undefined>");
            break;

        /** ObjectId */
        case jstOID:
            {
                std::string idValue = _bsonElement.OID().toString();
                char buff[256]={0};
                sprintf(buff,"ObjectId(\"%s\")",idValue.c_str());
                con.append(buff);
            }
            break;

        /** boolean type */
        case Bool:
            con.append(_bsonElement.Bool() ? "true" : "false");
            break;

        /** date type */
        case Date:
        {
            long long ms = (long long) _bsonElement.Date().millis;

            boost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));
            boost::posix_time::time_duration diff = boost::posix_time::millisec(ms);
            boost::posix_time::ptime time = epoch + diff;

            std::string date = miutil::isotimeString(time,false,AppRegistry::instance().settingsManager()->timeZone()==LocalTime);

            con.append(date);
            break;
        }

        /** null type */
        case jstNULL:
            con.append("<null>");
            break;

        /** regular expression, a pattern with options */
        case RegEx:
            {
                con.append("/" + std::string(_bsonElement.regex()) + "/");

                for ( const char *f = _bsonElement.regexFlags(); *f; ++f ) {
                    switch ( *f ) {
                    case 'g':
                    case 'i':
                    case 'm':
                            con+=*f;
                    default:
                        break;
                    }
                }
            }
            break;

        /** deprecated / will be redesigned */
        case DBRef:
            break;

        /** deprecated / use CodeWScope */
        case Code:
            con.append(_bsonElement._asCode());
            break;

        /** a programming language (e.g., Python) symbol */
        case Symbol:
            con.append(_bsonElement.valuestr(), _bsonElement.valuestrsize() - 1);
            break;

        /** javascript code that can execute on the database server, with SavedContext */
        case CodeWScope:
            {
                mongo::BSONObj scope = _bsonElement.codeWScopeObject();
                if (!scope.isEmpty() ) {
                    con.append(_bsonElement._asCode());
                    break;
                }
            }
            break;

        /** 32 bit signed integer */
        case NumberInt:
            {
                char num[16]={0};
                sprintf(num,"%d",_bsonElement.Int());
                con.append(num);
                break;
            }           

        /** Updated to a Date with value next OpTime on insert */
        case Timestamp:
            {
                Date_t date = _bsonElement.timestampTime();
                unsigned long long millis = date.millis;
                if ((long long)millis >= 0 &&
                    ((long long)millis/1000) < (std::numeric_limits<time_t>::max)()) {
                        con.append(date.toString());
                }
                break;
            }

        /** 64 bit integer */
        case NumberLong:
            {
                char num[32]={0};
                sprintf(num,"%lld",_bsonElement.Long());
                con.append(num);
                break; 
            }
        default:
            con.append("<unsupported>");
            break;
        }
    }
Example #24
0
std::string MakePath(std::string p_constPath, std::string p_path) {
	return p_constPath.append(p_path);
}
Example #25
0
std::string GetConfigStringDefault(std::string base, const char* name, const char* value)
{
    base.append(name);
    return sConfigMgr->GetStringDefault(base.c_str(), value);
}
Example #26
0
static void replaceIncludes(const char* filepath, const char* source, std::string& out)
{
    // Replace the #include "xxxx.xxx" with the sourced file contents of "filepath/xxxx.xxx"
    std::string str = source;
    size_t lastPos = 0;
    size_t headPos = 0;
    size_t fileLen = str.length();
    size_t tailPos = fileLen;
    while (headPos < fileLen)
    {
        lastPos = headPos;
        if (headPos == 0)
        {
            // find the first "#include"
            headPos = str.find("#include");
        }
        else
        {
            // find the next "#include"
            headPos = str.find("#include", headPos + 1);
        }

        // If "#include" is found
        if (headPos != std::string::npos)
        {
            // append from our last position for the legth (head - last position) 
            out.append(str.substr(lastPos,  headPos - lastPos));

            // find the start quote "
            size_t startQuote = str.find("\"", headPos) + 1;
            if (startQuote == std::string::npos)
            {
                // We have started an "#include" but missing the leading quote "
                GP_ERROR("Compile failed for shader '%s' missing leading \".", filepath);
                return;
            }
            // find the end quote "
            size_t endQuote = str.find("\"", startQuote);
            if (endQuote == std::string::npos)
            {
                // We have a start quote but missing the trailing quote "
                GP_ERROR("Compile failed for shader '%s' missing trailing \".", filepath);
                return;
            }

            // jump the head position past the end quote
            headPos = endQuote + 1;
            
            // File path to include and 'stitch' in the value in the quotes to the file path and source it.
            std::string filepathStr = filepath;
            std::string directoryPath = filepathStr.substr(0, filepathStr.rfind('/') + 1);
            size_t len = endQuote - (startQuote);
            std::string includeStr = str.substr(startQuote, len);
            directoryPath.append(includeStr);
            const char* includedSource = FileSystem::readAll(directoryPath.c_str());
            if (includedSource == NULL)
            {
                GP_ERROR("Compile failed for shader '%s' invalid filepath.", filepathStr.c_str());
                return;
            }
            else
            {
                // Valid file so lets attempt to see if we need to append anything to it too (recurse...)
                replaceIncludes(directoryPath.c_str(), includedSource, out);
                SAFE_DELETE_ARRAY(includedSource);
            }
        }
        else
        {
            // Append the remaining
            out.append(str.c_str(), lastPos, tailPos);
        }
    }
}
 virtual void write(const void *data, size_t size) override
 {
     result.append(static_cast<const char*>(data), size);
 }
bool LLPanelGroupGeneral::apply(std::string& mesg)
{
	BOOL has_power_in_group = gAgent.hasPowerInGroup(mGroupID,GP_GROUP_CHANGE_IDENTITY);

	if (has_power_in_group || mGroupID.isNull())
	{
		llinfos << "LLPanelGroupGeneral::apply" << llendl;

		// Check to make sure mature has been set
		if(mComboMature &&
		   mComboMature->getCurrentIndex() == DECLINE_TO_STATE)
		{
			LLNotifications::instance().add("SetGroupMature", LLSD(), LLSD(), 
											boost::bind(&LLPanelGroupGeneral::confirmMatureApply, this, _1, _2));
			return false;
		}

		if (mGroupID.isNull())
		{
			// Validate the group name length.
			S32 group_name_len = mGroupNameEditor->getText().size();
			if ( group_name_len < DB_GROUP_NAME_MIN_LEN 
				|| group_name_len > DB_GROUP_NAME_STR_LEN)
			{
				std::ostringstream temp_error;
				temp_error << "A group name must be between " << DB_GROUP_NAME_MIN_LEN
					<< " and " << DB_GROUP_NAME_STR_LEN << " characters.";
				mesg = temp_error.str();
				return false;
			}

			LLSD args;
			args["MESSAGE"] = mConfirmGroupCreateStr;
			LLNotifications::instance().add("GenericAlertYesCancel", args, LLSD(), boost::bind(&LLPanelGroupGeneral::createGroupCallback, this, _1, _2));

			return false;
		}

		LLGroupMgrGroupData* gdatap = LLGroupMgr::getInstance()->getGroupData(mGroupID);
		if (!gdatap)
		{
			// *TODO: Translate
			mesg = std::string("No group data found for group ");
			mesg.append(mGroupID.asString());
			return false;
		}
		bool can_change_ident = false;
		bool can_change_member_opts = false;
		can_change_ident = gAgent.hasPowerInGroup(mGroupID,GP_GROUP_CHANGE_IDENTITY);
		can_change_member_opts = gAgent.hasPowerInGroup(mGroupID,GP_MEMBER_OPTIONS);

		if (can_change_ident)
		{
			if (mEditCharter) gdatap->mCharter = mEditCharter->getText();
			if (mInsignia) gdatap->mInsigniaID = mInsignia->getImageAssetID();
			if (mComboMature)
			{
				if (!gAgent.isTeen())
				{
					gdatap->mMaturePublish = 
						mComboMature->getCurrentIndex() == MATURE_CONTENT;
				}
				else
				{
					gdatap->mMaturePublish = FALSE;
				}
			}
			if (mCtrlShowInGroupList) gdatap->mShowInList = mCtrlShowInGroupList->get();
		}

		if (can_change_member_opts)
		{
			if (mCtrlOpenEnrollment) gdatap->mOpenEnrollment = mCtrlOpenEnrollment->get();
			if (mCtrlEnrollmentFee && mSpinEnrollmentFee)
			{
				gdatap->mMembershipFee = (mCtrlEnrollmentFee->get()) ? 
					(S32) mSpinEnrollmentFee->get() : 0;
				// Set to the used value, and reset initial value used for isdirty check
				mSpinEnrollmentFee->set( (F32)gdatap->mMembershipFee );
			}
		}

		if (can_change_ident || can_change_member_opts)
		{
			LLGroupMgr::getInstance()->sendUpdateGroupInfo(mGroupID);
		}
	}

	BOOL receive_notices = false;
	BOOL list_in_profile = false;
	if (mCtrlReceiveNotices)
		receive_notices = mCtrlReceiveNotices->get();
	if (mCtrlListGroup) 
		list_in_profile = mCtrlListGroup->get();

	gAgent.setUserGroupFlags(mGroupID, receive_notices, list_in_profile);

	if (mCtrlReceiveChat)
	{
		bool receive_chat = mCtrlReceiveChat->get();
		gIMMgr->updateIgnoreGroup(mGroupID, !receive_chat);
		// Save here too in case we crash somewhere down the road -- MC
		gIMMgr->saveIgnoreGroup();
	}

	// Make sure we update the group list in our contacts list and our IMs -- MC
	if (gIMMgr)
	{
		// update the talk view
		gIMMgr->refresh();
	}
	gAgent.fireEvent(new LLEvent(&gAgent, "new group"), "");

	mChanged = FALSE;

	return true;
}
Example #29
0
/*++
* @method: oAuth::getOAuthHeader
*
* @description: this method builds OAuth header that should be used in HTTP requests to twitter
*
* @input: eType - HTTP request type
*         rawUrl - raw url of the HTTP request
*         rawData - HTTP data
*         includeOAuthVerifierPin - flag to indicate whether or not oauth_verifier needs to included
*                                   in OAuth header
*
* @output: oAuthHttpHeader - OAuth header
*
*--*/
bool oAuth::getOAuthHeader( const eOAuthHttpRequestType eType,
                            const std::string& rawUrl,
                            const std::string& rawData,
                            std::string& oAuthHttpHeader,
                            const bool includeOAuthVerifierPin )
{
    oAuthKeyValuePairs rawKeyValuePairs;
    std::string rawParams;
    std::string oauthSignature;
    std::string paramsSeperator;
    std::string pureUrl( rawUrl );

    /* Clear header string initially */
    oAuthHttpHeader.assign( "" );
    rawKeyValuePairs.clear();

    /* If URL itself contains ?key=value, then extract and put them in map */
    size_t nPos = rawUrl.find_first_of( "?" );
    if( std::string::npos != nPos )
    {
        /* Get only URL */
        pureUrl = rawUrl.substr( 0, nPos );

        /* Get only key=value data part */
        std::string dataPart = rawUrl.substr( nPos + 1 );

        /* This dataPart can contain many key value pairs: key1=value1&key2=value2&key3=value3 */
        size_t nSep = std::string::npos;
        size_t nPos2 = std::string::npos;
        std::string dataKeyVal;
        std::string dataKey;
        std::string dataVal;
        while( std::string::npos != ( nSep = dataPart.find_first_of("&") ) )
        {
            /* Extract first key=value pair */
            dataKeyVal = dataPart.substr( 0, nSep );

            /* Split them */
            nPos2 = dataKeyVal.find_first_of( "=" );
            if( std::string::npos != nPos2 )
            {
                dataKey = dataKeyVal.substr( 0, nPos2 );
                dataVal = dataKeyVal.substr( nPos2 + 1 );

                /* Put this key=value pair in map */
                rawKeyValuePairs[dataKey] = urlencode( dataVal );
            }
            dataPart = dataPart.substr( nSep + 1 );
        }

        /* For the last key=value */
        dataKeyVal = dataPart.substr( 0, nSep );
        
        /* Split them */
        nPos2 = dataKeyVal.find_first_of( "=" );
        if( std::string::npos != nPos2 )
        {
            dataKey = dataKeyVal.substr( 0, nPos2 );
            dataVal = dataKeyVal.substr( nPos2 + 1 );

            /* Put this key=value pair in map */
            rawKeyValuePairs[dataKey] = urlencode( dataVal );
        }
    }

    /* Build key-value pairs needed for OAuth request token, without signature */
    buildOAuthTokenKeyValuePairs( includeOAuthVerifierPin, rawData, std::string( "" ), rawKeyValuePairs, true );

    /* Get url encoded base64 signature using request type, url and parameters */
    getSignature( eType, pureUrl, rawKeyValuePairs, oauthSignature );

    /* Now, again build key-value pairs with signature this time */
    buildOAuthTokenKeyValuePairs( includeOAuthVerifierPin, std::string( "" ), oauthSignature, rawKeyValuePairs, false );

    /* Get OAuth header in string format */
    paramsSeperator = ",";
    getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, paramsSeperator );

    /* Build authorization header */
    oAuthHttpHeader.assign( oAuthLibDefaults::OAUTHLIB_AUTHHEADER_STRING );
    oAuthHttpHeader.append( rawParams );

    return ( oAuthHttpHeader.length() ) ? true : false;
}
Example #30
0
DWORD HttpClient::request(const std::wstring& url, const std::wstring& method
	, const std::vector<std::wstring>& headers, const std::string& body, std::string& resp_data)
{
	assert(NULL == m_hSession && NULL == m_hConnect && NULL == m_hRequest);

	std::wstring host_name;
	std::wstring url_path;
	URL_COMPONENTS url_comp = { 0 };
	url_comp.dwStructSize = sizeof(url_comp);

	host_name.resize(url.size());
	url_path.resize(url.size());

	url_comp.lpszHostName = const_cast<wchar_t*>(host_name.data());
	url_comp.dwHostNameLength = host_name.size();
	url_comp.lpszUrlPath = const_cast<wchar_t*>(url_path.data());
	url_comp.dwUrlPathLength = url_path.size();
	if (FALSE == ::WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &url_comp))
	{
		return ::GetLastError();
	}

	m_hSession = ::WinHttpOpen(m_user_agent.c_str()
		, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	if (NULL == m_hSession)
	{
		return ::GetLastError();
	}

	m_hConnect = ::WinHttpConnect(m_hSession, host_name.c_str(), url_comp.nPort, 0);
	if (NULL == m_hConnect)
	{
		return ::GetLastError();
	}

	DWORD flags = (INTERNET_SCHEME_HTTP == url_comp.nScheme ? 0 : WINHTTP_FLAG_SECURE);
	m_hRequest = ::WinHttpOpenRequest(m_hConnect, method.c_str(), url_path.c_str(),
		NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags);
	if (NULL == m_hRequest)
	{
		return ::GetLastError();
	}

	for (std::vector<std::wstring>::const_iterator it = headers.begin(); headers.end() != it; ++it)
	{
		::WinHttpAddRequestHeaders(m_hRequest, it->c_str(), (ULONG)-1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_COALESCE);
	}

	if (0 == method.compare(L"GET"))
	{
		::WinHttpSendRequest(m_hRequest, WINHTTP_NO_ADDITIONAL_HEADERS,
			0, WINHTTP_NO_REQUEST_DATA, 0,
			0, 0);
	}
	else if (0 == method.compare(L"POST"))
	{
		const void* body_data = reinterpret_cast<const void*>(body.c_str());
		::WinHttpSendRequest(m_hRequest, WINHTTP_NO_ADDITIONAL_HEADERS,
			0, const_cast<void*>(body_data), body.size(),
			body.size(), 0);
	}
	else if (0 == method.compare(L"PUT"))
	{
		const void* body_data = reinterpret_cast<const void*>(body.c_str());
		::WinHttpSendRequest(m_hRequest, WINHTTP_NO_ADDITIONAL_HEADERS,
			0, const_cast<void*>(body_data), body.size(),
			body.size(), 0);
	}

	if (ERROR_SUCCESS != ::GetLastError())
	{
		return ::GetLastError();
	}

	if (FALSE == ::WinHttpReceiveResponse(m_hRequest, NULL))
	{
		return ::GetLastError();
	}

	WCHAR status_code[16] = { 0 };
	DWORD buffer_length = _countof(status_code);
	if (FALSE == ::WinHttpQueryHeaders(m_hRequest, WINHTTP_QUERY_STATUS_CODE
		, WINHTTP_HEADER_NAME_BY_INDEX, status_code, &buffer_length
		, WINHTTP_NO_HEADER_INDEX))
	{
		return ::GetLastError();
	}

	DWORD size = 0;
	while (TRUE == ::WinHttpQueryDataAvailable(m_hRequest, &size))
	{
		if (0 == size)
		{
			break;
		}

		std::unique_ptr<char[]> buffer(new char[size]);
		if (NULL == buffer.get())
		{
			break;
		}

		DWORD lpdwNumberOfBytesRead = 0;
		if (TRUE == ::WinHttpReadData(m_hRequest, buffer.get(), size, &lpdwNumberOfBytesRead))
		{
			resp_data.append(buffer.get(), static_cast<size_t>(lpdwNumberOfBytesRead));
		}
		else
		{
			return ::GetLastError();
		}
	}

	const WCHAR ok_status_code[] = { L'2', L'0', L'0', L'\0' };
	if (0 != ::_wcsicmp(ok_status_code, status_code))
	{
		return EcHttpCodeError;
	}

	return ERROR_SUCCESS;
}