Ejemplo n.º 1
0
static stringList_t _eval_path( string_t path,stringList_t stl_1 )
{
	string_t st ;
	const char * e ;
	char * ac ;
	if( StringStartsWith( path,"/" ) ){
		/*
		 * zuluCryptResolvePath_1() is defined in resolve_paths.c
		 */
		st = zuluCryptResolvePath_1( StringContent( path ) ) ;

		if( st != StringVoid ){
			stl_1 = StringListAppendString_1( stl_1,&st ) ;
		}
	}else if( StringStartsWith( path,"UUID=" ) ){
		/*
		 * check above did not find '/' character and we are in this block assuming the line uses UUID
		 */
		e = StringRemoveString( path,"\"" ) ;
		/*
		 * zuluCryptEvaluateDeviceTags() is defined in path_access.c
		 */
		ac = zuluCryptEvaluateDeviceTags( "UUID",e + 5 ) ;
		if( ac != NULL ){
			stl_1 = StringListAppend( stl_1,ac ) ;
			StringFree( ac ) ;
		}
	}
	return stl_1 ;
}
Ejemplo n.º 2
0
bool
WaypointReaderFS::VerifyFormat(TLineReader &reader)
{
  const TCHAR *line = reader.ReadLine();
  if (line == nullptr)
    return false;

  return StringStartsWith(line, _T("$FormatUTM")) ||
         StringStartsWith(line, _T("$FormatGEO"));
}
Ejemplo n.º 3
0
bool
WaypointReaderFS::VerifyFormat(TLineReader &reader)
{
  TCHAR* line = reader.read();
  if (line == NULL)
    return false;

  return StringStartsWith(line, _T("$FormatUTM")) ||
         StringStartsWith(line, _T("$FormatGEO"));
}
Ejemplo n.º 4
0
bool
WaypointReaderCompeGPS::VerifyFormat(TLineReader &reader)
{
  const TCHAR *line = reader.ReadLine();
  if (line == NULL)
    return false;

  // Ignore optional line with encoding information
  if (StringStartsWith(line, _T("B ")))
    if ((line = reader.ReadLine()) == NULL)
      return false;

  return StringStartsWith(line, _T("G  WGS 84"));
}
Ejemplo n.º 5
0
bool
NmeaReplay::ReadUntilRMC(NMEAInfo &data)
{
  char *buffer;

  while ((buffer = reader->ReadLine()) != NULL) {
    ParseLine(buffer, data);

    if (StringStartsWith(buffer, "$GPRMC") ||
        StringStartsWith(buffer, "$FLYSEN"))
      return true;
  }

  return false;
}
Ejemplo n.º 6
0
static string_t _root_device( const char * device,const char ** sys_device )
{
	size_t e ;
	ssize_t r ;
	string_t st = String( device ) ;
	if( StringStartsWithAtLeastOne( st,"/dev/sd","/dev/hd",NULL ) ){
		/*
		 * this path will convert something like: "/dev/sdc12" to "/dev/sdc".
		 * basically,it removes digits from the end of the string to give the root device
		 * required by tcplay's system volume or fde volume
		 */
		*sys_device = StringRemoveDigits( st ) ;
	}else if( StringStartsWith( st,"/dev/mmc" ) ){
		/*
		 * device path will be something like "/dev/mmcblk0p2" and what we want to do
		 * is cut off the string from p to end iwth "/dev/mmcblk0"
		 */
		r = StringIndexOfChar( st,0,'p' ) ;
		if( r != -1 ){
			e = StringLength( st ) - ( size_t )r ;
			*sys_device = StringRemoveRight( st,e ) ;
		}else{
			*sys_device = StringContent( st ) ;
		}
	}else{
		*sys_device = StringContent( st ) ;
	}
	return st ;
}
Ejemplo n.º 7
0
static int _fileSystemIsSupported( const char * fs )
{
	string_t           st  = StringGetFromVirtualFile( "/proc/filesystems" ) ;
	stringList_t       stl = StringListStringSplit( st,'\n' ) ;
	StringListIterator it  = StringListBegin( stl ) ;
	StringListIterator end = StringListEnd( stl ) ;
	string_t xt ;
	int r = 0 ;

	while( it != end ){

		xt = *it ;

		it++ ;

		if( !StringStartsWith( xt,"nodev" ) ){

			if( StringContains( xt,fs ) ){

				r = 1 ;
				break ;
			}
		}
	}

	StringDelete( &st ) ;
	StringListDelete( &stl ) ;
	return r ;
}
Ejemplo n.º 8
0
/*
 * this function will parse /etc/crypttab to see if it has any entries to be used as system partition.
 *
 * sample example of the file content this function was build on.
 *

 * secret /dev/sda15 none
 * secret_1 UUID=d2d210b8-0b1f-419f-9172-9d509ea9af0c none
 *
 */
stringList_t zuluCryptGetPartitionFromCrypttab( void )
{
	stringList_t stl   = StringListVoid ;
	stringList_t stl_1 = StringListVoid ;
	stringList_t stz ;

	string_t st  ;

	StringListIterator it  ;
	StringListIterator end ;

	st = StringGetFromFile( "/etc/crypttab" ) ;

	stl = StringListStringSplit( st,'\n' ) ;

	StringDelete( &st ) ;

	StringListGetIterators( stl,&it,&end ) ;

	while( it != end ){
		st = *it ;
		it++ ;
		if( !StringStartsWith( st,"#" ) ){
			stz = StringListStringSplit( st,' ' ) ;
			st = StringListStringAtSecondPlace( stz ) ;
			stl_1 = _eval_path( st,stl_1 ) ;
			StringListDelete( &stz ) ;
		}
	}

	StringListDelete( &stl ) ;
	return stl_1 ;
}
Ejemplo n.º 9
0
bool DataIndex::DecodeFromString(const std::string &str) {
    if (!StringStartsWith(str, kIndexBlockMagic)) {
        LOG(ERROR)<< "invalid data index header";
        return false;
    }
    block_info_.clear();
    const char *begin = str.c_str() + kIndexBlockMagic.size();
    const char *end = str.c_str() + str.size();
    while (begin < end) {
        DataBlockInfo info;
        info.offset = ReadInt64(&begin);
        info.data_size = ReadInt32(&begin);
        int key_len = ReadVint(&begin, end);
        info.key = std::string(begin, key_len);
        begin += key_len;
        block_info_.push_back(info);
    }
    // Check if the content is overflow
    if (begin > end) {
        LOG(ERROR) << "incomplete file, "
        << StringPrint("begin: %p, end: %p", begin, end);
        return false;
    }
    return true;
}
Ejemplo n.º 10
0
unsigned char CArchiveScanner::GetMetaFileClass(const std::string& filePath)
{

	unsigned char metaFileClass = 0;

	const std::string lowerFilePath = StringToLower(filePath);
	const std::string ext = FileSystem::GetExtension(lowerFilePath);

	// 1: what is commonly read from all archives when scanning through them
	// 2: what is less commoonly used, or only used when looking
	//    at a specific archive (for example when hosting Game-X)
	if (lowerFilePath == "mapinfo.lua") {                      // basic archive info
		metaFileClass = 1;
	} else if (lowerFilePath == "modinfo.lua") {               // basic archive info
		metaFileClass = 1;
//	} else if ((ext == "smf") || (ext == "sm3")) {             // to generate minimap
//		metaFileClass = 1;
	} else if (lowerFilePath == "modoptions.lua") {            // used by lobbies
		metaFileClass = 2;
	} else if (lowerFilePath == "engineoptions.lua") {         // used by lobbies
		metaFileClass = 2;
	} else if (lowerFilePath == "validmaps.lua") {             // used by lobbies
		metaFileClass = 2;
	} else if (lowerFilePath == "luaai.lua") {                 // used by lobbies
		metaFileClass = 2;
	} else if (StringStartsWith(lowerFilePath, "sidepics/")) { // used by lobbies
		metaFileClass = 2;
	} else if (StringStartsWith(lowerFilePath, "gamedata/")) { // used by lobbies
		metaFileClass = 2;
	} else if (lowerFilePath == "armor.txt") {                 // used by lobbies (disabled units list)
		metaFileClass = 2;
	} else if (lowerFilePath == "springignore.txt") {          // used by lobbies (disabled units list)
		metaFileClass = 2;
	} else if (StringStartsWith(lowerFilePath, "units/")) {    // used by lobbies (disabled units list)
		metaFileClass = 2;
	} else if (StringStartsWith(lowerFilePath, "features/")) { // used by lobbies (disabled units list)
		metaFileClass = 2;
	} else if (StringStartsWith(lowerFilePath, "weapons/")) {  // used by lobbies (disabled units list)
		metaFileClass = 2;
	}
	// Lobbies get the unit list from unitsync. Unitsync gets it by executing
	// gamedata/defs.lua, which loads units, features, weapons, move types
	// and armors (that is why armor.txt is in the list).

	return metaFileClass;
}
Ejemplo n.º 11
0
void Webserver::ProcessGcode(const char* gc)
{
	if (StringStartsWith(gc, "M30 "))		// delete SD card file
	{
		reprap.GetGCodes()->DeleteFile(&gc[4]);
	}
	else if (StringStartsWith(gc, "M23 "))	// select SD card file to print next
	{
		reprap.GetGCodes()->QueueFileToPrint(&gc[4]);
	}
	else if (StringStartsWith(gc, "M112") && !isdigit(gc[4]))	// emergency stop
	{
		reprap.EmergencyStop();
		gcodeReadIndex = gcodeWriteIndex;		// clear the buffer
		reprap.GetGCodes()->Reset();
	}
	else if (StringStartsWith(gc, "M503") && !isdigit(gc[4]))	// echo config.g file
	{
		FileStore *configFile = platform->GetFileStore(platform->GetSysDir(), platform->GetConfigFile(), false);
		if (configFile == NULL)
		{
			HandleReply("Configuration file not found", true);
		}
		else
		{
			char c;
			size_t i = 0;
			while (i < ARRAY_UPB(gcodeReply) && configFile->Read(c))
			{
				gcodeReply[i++] = c;
			}
			configFile->Close();
			gcodeReply[i] = 0;
			++seq;
		}
	}
	else if (StringStartsWith(gc, "M25") && !isDigit(gc[3]))	// pause SD card print
	{
		reprap.GetGCodes()->PauseSDPrint();
	}
	else
	{
		StoreGcodeData(gc, strlen(gc) + 1);
	}
}
Ejemplo n.º 12
0
bool
WaypointReaderOzi::VerifyFormat(TLineReader &reader)
{
  const TCHAR *line = reader.ReadLine();
  if (line == nullptr)
    return false;

  return StringStartsWith(line, _T("OziExplorer Waypoint File"));
}
Ejemplo n.º 13
0
bool HttpMessage::ParseVersion(const std::string& version_str)
{
    if (!StringStartsWith(version_str, "HTTP/"))
        return false;
    const std::string& ver = version_str.substr(5);
    int major, minor;
    if (StringScan(ver, "%d.%d", &major, &minor) != 2)
        return false;
    SetVersion(HttpVersion(major, minor));
    return true;
}
Ejemplo n.º 14
0
bool
WaypointReaderFS::ParseLine(const TCHAR *line, Waypoints &way_points)
{
  //$FormatGEO
  //ACONCAGU  S 32 39 12.00    W 070 00 42.00  6962  Aconcagua
  //BERGNEUS  N 51 03 07.02    E 007 42 22.02   488  Bergneustadt [A]
  //GOLDENGA  N 37 49 03.00    W 122 28 42.00   227  Golden Gate Bridge
  //REDSQUAR  N 55 45 15.00    E 037 37 12.00   123  Red Square
  //SYDNEYOP  S 33 51 25.02    E 151 12 54.96     5  Sydney Opera

  //$FormatUTM
  //Aconcagu 19H   0405124   6386692   6962  Aconcagua
  //Bergneus 32U   0409312   5656398    488  Bergneustadt [A]
  //Golden G 10S   0545914   4185695    227  Golden Gate Bridge
  //Red Squa 37U   0413390   6179582    123  Red Square
  //Sydney O 56H   0334898   6252272      5  Sydney Opera

  if (line[0] == '\0')
    return true;

  if (line[0] == _T('$')) {
    if (StringStartsWith(line, _T("$FormatUTM")))
      is_utm = true;
    return true;
  }

  // Determine the length of the line
  size_t len = _tcslen(line);
  // If less then 27 characters -> something is wrong -> cancel
  if (len < (is_utm ? 39 : 47))
    return false;

  GeoPoint location;
  if (!(is_utm
        ? ParseLocationUTM(line + 9, location)
        : ParseLocation(line + 10, location)))
    return false;

  Waypoint new_waypoint = factory.Create(location);

  if (!ParseString(line, new_waypoint.name, 8))
    return false;

  if (!ParseAltitude(line + (is_utm ? 32 : 41), new_waypoint.elevation) &&
      !factory.FallbackElevation(new_waypoint))
    return false;

  // Description (Characters 35-44)
  if (len > (is_utm ? 38 : 47))
    ParseString(line + (is_utm ? 38 : 47), new_waypoint.comment);

  way_points.Append(std::move(new_waypoint));
  return true;
}
Ejemplo n.º 15
0
TError TClient::ResolveRelativeName(const std::string &relative_name,
                                    std::string &absolute_name,
                                    bool resolve_meta) const {
    auto base = ClientContainer.lock();
    if (!base)
        return TError(EError::ContainerDoesNotExist, "Cannot find client container");
    std::string ns = base->GetPortoNamespace();

    /* FIXME get rid of this crap */
    if (!resolve_meta && (relative_name == DOT_CONTAINER ||
                          relative_name == PORTO_ROOT_CONTAINER ||
                          relative_name == ROOT_CONTAINER))
        return TError(EError::Permission, "System containers are read only");

    if (relative_name == ROOT_CONTAINER ||
            relative_name == PORTO_ROOT_CONTAINER)
        absolute_name = relative_name;
    else if (relative_name == SELF_CONTAINER)
        absolute_name = base->GetName();
    else if (StringStartsWith(relative_name,
                              std::string(SELF_CONTAINER) + "/")) {
        absolute_name = (base->IsRoot() ? "" : base->GetName() + "/") +
                        relative_name.substr(std::string(SELF_CONTAINER).length() + 1);
    } else if (StringStartsWith(relative_name,
                                std::string(PORTO_ROOT_CONTAINER) + "/")) {
        absolute_name = relative_name.substr(
                            std::string(PORTO_ROOT_CONTAINER).length() + 1);
        if (!StringStartsWith(absolute_name, ns))
            return TError(EError::Permission,
                          "Absolute container name out of current namespace");
    } else if (relative_name == DOT_CONTAINER) {
        size_t off = ns.rfind('/');
        if (off != std::string::npos)
            absolute_name = ns.substr(0, off);
        else
            absolute_name = PORTO_ROOT_CONTAINER;
    } else
        absolute_name = ns + relative_name;

    return TError::Success();
}
Ejemplo n.º 16
0
void ParticleEvolver::AddEvolutionStage(const TiXmlAttribute* attribute)
{
	auto v = ParseVector2f(attribute->Value());
	if (StringStartsWith("evol_red", attribute->Name()))
	{
		m_redEvolution.push_back(std::make_pair(v.x, (uint)v.y));
	}
	else if (StringStartsWith("evol_green", attribute->Name()))
	{
		m_greenEvolution.push_back(std::make_pair(v.x, (uint)v.y));
	}
	else if (StringStartsWith("evol_blue", attribute->Name()))
	{
		m_blueEvolution.push_back(std::make_pair(v.x, (uint)v.y));
	}
	else if (StringStartsWith("evol_alpha", attribute->Name()))
	{
		m_alphaEvolution.push_back(std::make_pair(v.x, (uint)v.y));
	}
	else if (StringStartsWith("evol_scaleX", attribute->Name()))
	{
		m_scaleEvolutionX.push_back(std::make_pair(v.x, v.y));
	}
	else if (StringStartsWith("evol_scaleY", attribute->Name()))
	{
		m_scaleEvolutionY.push_back(std::make_pair(v.x, v.y));
	}
}
Ejemplo n.º 17
0
bool GenericAgentConfigParseWarningOptions(GenericAgentConfig *config, const char *warning_options)
{
    if (strlen(warning_options) == 0)
    {
        return false;
    }

    if (strcmp("error", warning_options) == 0)
    {
        config->agent_specific.common.parser_warnings_error |= PARSER_WARNING_ALL;
        return true;
    }

    const char *options_start = warning_options;
    bool warnings_as_errors = false;

    if (StringStartsWith(warning_options, "error="))
    {
        options_start = warning_options + strlen("error=");
        warnings_as_errors = true;
    }

    StringSet *warnings_set = StringSetFromString(options_start, ',');
    StringSetIterator it = StringSetIteratorInit(warnings_set);
    const char *warning_str = NULL;
    while ((warning_str = StringSetIteratorNext(&it)))
    {
        int warning = ParserWarningFromString(warning_str);
        if (warning == -1)
        {
            Log(LOG_LEVEL_ERR, "Unrecognized warning '%s'", warning_str);
            StringSetDestroy(warnings_set);
            return false;
        }

        if (warnings_as_errors)
        {
            config->agent_specific.common.parser_warnings_error |= warning;
        }
        else
        {
            config->agent_specific.common.parser_warnings |= warning;
        }
    }

    StringSetDestroy(warnings_set);
    return true;
}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
  plan_tests(29);

  // Test StringIsEqual()

  ok1(StringIsEqual("", ""));
  ok1(!StringIsEqual("a", ""));
  ok1(!StringIsEqual("", "a"));
  ok1(StringIsEqual("aaa", "aaa"));
  ok1(!StringIsEqual("aaa", "a"));
  ok1(!StringIsEqual("aaa", "bbb"));
  ok1(!StringIsEqual("bbb", "aaa"));

  ok1(StringIsEqual("This is a funny test case!",
                    "This is a funny test case!"));

  ok1(StringIsEqual(_T(""), _T("")));
  ok1(!StringIsEqual(_T("a"), _T("")));
  ok1(!StringIsEqual(_T(""), _T("a")));
  ok1(StringIsEqual(_T("aaa"), _T("aaa")));
  ok1(!StringIsEqual(_T("aaa"), _T("a")));
  ok1(!StringIsEqual(_T("aaa"), _T("bbb")));
  ok1(!StringIsEqual(_T("bbb"), _T("aaa")));

  ok1(StringIsEqual(_T("This is a funny test case!"),
                    _T("This is a funny test case!")));

  // Test StringStartsWith()

  ok1(StringStartsWith(_T(""), _T("")));
  ok1(StringStartsWith(_T("a"), _T("")));
  ok1(!StringStartsWith(_T(""), _T("a")));
  ok1(StringStartsWith(_T("aaa"), _T("aaa")));
  ok1(StringStartsWith(_T("aaa"), _T("a")));
  ok1(!StringStartsWith(_T("bbb"), _T("aaa")));

  // Test StringAfterPrefix()

  ok1(StringIsEqual(StringAfterPrefix(_T(""), _T("")), _T("")));
  ok1(StringIsEqual(StringAfterPrefix(_T("a"), _T("")), _T("a")));
  ok1(StringAfterPrefix(_T(""), _T("a")) == NULL);
  ok1(StringIsEqual(StringAfterPrefix(_T("aaa"), _T("aaa")), _T("")));
  ok1(StringIsEqual(StringAfterPrefix(_T("aaa"), _T("a")), _T("aa")));
  ok1(StringAfterPrefix(_T("bbb"), _T("aaa")) == NULL);
  ok1(StringIsEqual(StringAfterPrefix(_T("This is a funny test case!"),
                                      _T("This is")),
                                      _T(" a funny test case!")));

  return exit_status();
}
Ejemplo n.º 19
0
int CArchiveScanner::GetMetaFileClass(const std::string& filePath)
{
	const std::string& lowerFilePath = StringToLower(filePath);
	// const std::string& ext = FileSystem::GetExtension(lowerFilePath);
	const auto it = metaFileClasses.find(lowerFilePath);

	if (it != metaFileClasses.end())
		return (it->second);

//	if ((ext == "smf") || (ext == "sm3")) // to generate minimap
//		return 1;

	for (const auto& p: metaDirClasses) {
		if (StringStartsWith(lowerFilePath, p.first))
			return (p.second);
	}

	return 0;
}
Ejemplo n.º 20
0
Element& Document::GetElement(const std::string& elementName, bool_t* exists)
{
    // Are they referencing an element in this document using 
    // a path / URI?    
    if (StringStartsWith(elementName, "#/"))
    {
        return this->GetElementByPath(elementName, exists);
    }
    
    if (this->rootElement != nullptr)
    {
        return this->rootElement->GetElement(elementName, exists);
    }
    else
    {
        if (exists != nullptr)
        {
            *exists = false;
        }
    }
    
    return this->GetUndefinedElement();
}
Ejemplo n.º 21
0
static stringList_t _zuluCryptAddLVMVolumes( stringList_t stl )
{
	struct dirent * entry ;

	string_t st ;
	string_t xt ;

	DIR * dir = opendir( "/dev/mapper/" ) ;

	if( dir != NULL ){

		st = String( "/dev/mapper/" ) ;

		while( ( entry = readdir( dir ) ) != NULL ){

			if( !StringAtLeastOneMatch_1( entry->d_name,".","..","control",NULL ) ){

				/*
				 * zuluCryptConvertIfPathIsLVM() is defined in ../lib/resolve_paths.c
				 */

				xt = zuluCryptConvertIfPathIsLVM( StringAppendAt( st,12,entry->d_name ) ) ;

				if( StringStartsWith( xt,"/dev/mapper/" ) ){

					StringDelete( &xt ) ;
				}else{
					stl = StringListAppendString_1( stl,&xt ) ;
				}
			}
		}
		StringDelete( &st ) ;
		closedir( dir ) ;
	}

	return stl ;
}
Ejemplo n.º 22
0
bool DataBlock::DecodeInternal(const std::string &str) {
    if (!StringStartsWith(str, kDataBlockMagic)) {
        LOG(INFO)<< "invalid data block header.";
        return false;
    }
    data_items_.clear();
    const char *begin = str.c_str() + kDataBlockMagic.size();
    const char *end = str.c_str() + str.length();
    while (begin < end) {
        int key_length = ReadInt32(&begin);
        int value_length = ReadInt32(&begin);
        std::string key = std::string(begin, key_length);
        begin += key_length;
        std::string value = std::string(begin, value_length);
        begin += value_length;
        data_items_.push_back(make_pair(key, value));
    }
    if (begin > end) {
        LOG(ERROR) << "not a complete data block, "
        << StringPrint("begin: %p, end: %p", begin, end);
        return false;
    }
    return true;
}
Ejemplo n.º 23
0
void CScriptDlg::UpdateList()
{
	m_Functions.SetRedraw(false);
	m_Functions.ResetContent();
	m_Functions.data.clear();

	if(!m_Dot)
	{
		for(PyInfoMap::iterator i = m_IntellMap.begin(); i!= m_IntellMap.end(); i++)
		{
			if(StringStartsWith(i->first, m_BeforeDotText))
			{
				PyInfoMapItem::iterator item = i->second.find(&m_Intell);
				if(item != i->second.end())
				{
					//Check if the name starts
					
					int list_item = m_Functions.AddString(i->first);

					m_Functions.data.push_back(functiondata());
					functiondata& listdata = m_Functions.data.back();

					listdata.m_IntellMap[item->first] = 1;
					listdata.m_InfoType[item->second] = 1;

					m_Functions.SetItemData(list_item, (DWORD)&listdata);
				}
			}
		}

		if(m_BeforeDotText != "")
			m_Functions.SetCurSel(0);

		m_Functions.SetRedraw(true);
		m_Functions.Invalidate();
	}

	else // first.second
	{
		PyInfoMap::iterator i = m_IntellMap.find(m_BeforeDotText);
		if(i == m_IntellMap.end())
		{
			// Add as new variable if we dont have it listed
			PyInfoVar* pVar = &m_Intell.variables[m_BeforeDotText];
			pVar->pParent = &m_Intell;
			pVar->name = m_BeforeDotText;

			PyInfoMapItem& Item = m_IntellMap[m_BeforeDotText];
			Item[&m_Intell] = PY_VARIABLE;

			i = m_IntellMap.find(m_BeforeDotText); 
		}

		PyInfoClass* pParent =  i->second.begin()->first;

		PyInfoVar* pVar = NULL;
		PyInfoClass* pClass = NULL;

		map<CString, PyInfoVar>::iterator v = pParent->variables.find(m_BeforeDotText);
		if(v != pParent->variables.end())
			pVar = &v->second;

		map<CString, PyInfoClass>::iterator c = pParent->classes.find(m_BeforeDotText);
		if(c != pParent->classes.end())
			pClass = &c->second;
		
		// We loop each string in our intellisense map, and with each string we loop 
		// which type it belongs to. Then we compare it
		if(pVar)
		{
			for(PyInfoMap::iterator i = m_IntellMap.begin(); i!= m_IntellMap.end(); i++)
			{
				//Check if the name starts
				if(StringStartsWith(i->first, m_AfterDotText))
				{	
					if(pVar->classtypes.size() == 0)
					{
						functiondata listdata;

						for(PyInfoMapItem::iterator item = i->second.begin(); item != i->second.end(); item++)
						{
							if(item->first == &m_Intell)
								continue;
							
							listdata.m_IntellMap[item->first] = 1;
							listdata.m_InfoType[item->second] = 1;
						}
						if(listdata.m_InfoType.size() > 0)
						{
							int list_item = m_Functions.AddString(i->first);

							m_Functions.data.push_back(listdata);
							functiondata& listdata = m_Functions.data.back();

							m_Functions.SetItemData(list_item, (DWORD)&listdata);
						}
					}
					else
					{
						functiondata listdata;

						for(map<PyInfoClass*,int>::iterator mi = pVar->classtypes.begin(); mi!= pVar->classtypes.end(); mi++)
						{
							PyInfoMapItem::iterator item = i->second.find(mi->first);
							if(item != i->second.end())
							{
								listdata.m_IntellMap[item->first] = 1;
								listdata.m_InfoType[item->second] = 1;
							}
						}

						if(listdata.m_InfoType.size() > 0)
						{
							int list_item = m_Functions.AddString(i->first);

							m_Functions.data.push_back(listdata);
							functiondata& listdata = m_Functions.data.back();

							m_Functions.SetItemData(list_item, (DWORD)&listdata);
						}
					}

				}
			}
		}
		else if(pClass)
		{
			for(PyInfoMap::iterator i = m_IntellMap.begin(); i!= m_IntellMap.end(); i++)
			{
				//Check if the name starts
				if(StringStartsWith(i->first, m_AfterDotText))
				{
					PyInfoMapItem::iterator item = i->second.find(pClass);
					if(item != i->second.end())
					{
						m_Functions.data.push_back(functiondata());
						functiondata& listdata = m_Functions.data.back();
		
						listdata.m_IntellMap[item->first] = 1;
						listdata.m_InfoType[item->second] = 1;
						
						int list_item = m_Functions.AddString(i->first);

						m_Functions.SetItemData(list_item, (DWORD)&listdata);		
					}
				}
			}
		}
		m_Functions.SetCurSel(0);
		m_Functions.SetRedraw(true);
		m_Functions.Invalidate();
	}
	UpdateHelpLine();
}
Ejemplo n.º 24
0
void CScriptDlg::InitPythonInfo()
{
	// First add some standard keywords into our intellisense
	CString keywords = KEYWORDS; // 
	keywords += " ";

	CString _keyword = "";
	for(int i = 0; i < keywords.GetLength(); i++)
	{
		char letter = keywords.GetAt(i);
		if(letter == ' ')
		{
			// Add our keyword
			PyInfoKeyword* key = &m_Intell.keywords[_keyword];
			key->name = _keyword;
			key->pParent = &m_Intell;

			m_IntellMap[_keyword][&m_Intell] = PY_KEYWORD;
			
			_keyword = "";
		}
		else 
			_keyword += letter;
	}
	
	// Now add operators
/*	m_IntellMap["+"][&m_Intell] = PY_OPERATOR;	
	m_IntellMap["*"][&m_Intell] = PY_OPERATOR;		
	m_IntellMap["/"][&m_Intell] = PY_OPERATOR;
	m_IntellMap["-"][&m_Intell] = PY_OPERATOR;
	m_IntellMap["="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["=="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["!="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["<"][&m_Intell] = PY_OPERATOR;
	m_IntellMap[">"][&m_Intell] = PY_OPERATOR;
	m_IntellMap["<="][&m_Intell] = PY_OPERATOR;
	m_IntellMap[">="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["("][&m_Intell] = PY_OPERATOR;
	m_IntellMap[")"][&m_Intell] = PY_OPERATOR;
	m_IntellMap["["][&m_Intell] = PY_OPERATOR;
	m_IntellMap["]"][&m_Intell] = PY_OPERATOR;
	m_IntellMap[":"][&m_Intell] = PY_OPERATOR;
	m_IntellMap["+="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["-="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["*="][&m_Intell] = PY_OPERATOR;
	m_IntellMap["/="][&m_Intell] = PY_OPERATOR;*/
	// Load info from file

	CPath Path;
	Path.SetToCurrentDirectory();
	
	CString FilePath;
	FilePath.Format("%sPyAutoC\\info.txt", Path.GetFullPath());
	
	CFile File(FilePath, CFile::modeRead);
	char* ReadIn = new char[File.GetLength() + 1];
	File.Read(ReadIn, File.GetLength());
	ReadIn[File.GetLength()] = '\0';	
	
	// Store details
	int Length = File.GetLength();
	CString Functions;
	Functions.Format("%s", ReadIn);	


	// Read in functions
	int Start = 0;
	int End = 0;

	list<CString> infoList;

	while(End = Functions.Find('\n', Start))
	{
		if(End == -1)
			End = Length+1;

		CString Function = Functions.Mid(Start, End - Start - 1);
		Start = End + 1;

		infoList.push_back(Function);

		if(End == Length+1)
			break;
	}

	// Make sure to close file
	File.Close();


/////////////////////////////////////////////

	list<CString>::iterator i;
	i = infoList.begin();


	for(;i!= infoList.end(); i++)
	{
		if(StringStartsWith(*i, "    class "))
		{
			CString className = ExtractKeyword( (*i).Mid(10) );
			
			if(!className.IsEmpty())
			{
				// Add a new class
				PyInfoClass* pClass = &m_Intell.classes[className];
				pClass->pParent = &m_Intell;
				pClass->name = className;

				m_IntellMap[className][&m_Intell] = PY_CLASS;

				i++;
				if(i != infoList.end()) 
				{
					if(StringStartsWith(*i, "     |  "))
					{
						pClass->help = (*i).Mid(8);
					}
			
					bool addFunctions = false;
					bool addVariables = false;
					for(i++; i!= infoList.end(); i++)
					{
						if(StringStartsWith(*i, "     |  Methods"))
						{
							addFunctions = true;
							addVariables = false;
						}
						else if(StringStartsWith(*i, "     |  Data"))
						{
							addFunctions = false;
							addVariables = true;
						}
						else if(StringStartsWith(*i, "     |  ----"))
						{
							addFunctions = false;
							addVariables = false;
						}
						else if(!StringStartsWith(*i, "     |"))
						{
							addFunctions = false;
							addVariables = false;
							break; // break out of our for loop - ie: finish processing this class
						}
						else if(!StringStartsWith(*i, "     |      "))
						{
							CString name = ExtractKeyword(*i);
							if(!name.IsEmpty())
							{
								if(addFunctions)
								{
									// Add a function to the class
									PyInfoFunc* pFunc = &pClass->functions[name];
									pFunc->pParent = pClass;
									pFunc->name = name;

									m_IntellMap[name][pClass] = PY_FUNCTION;
									i++;
									if(i != infoList.end()) 
									{
										pFunc->help = (*i).Mid(12);
									}
								}
								if(addVariables)
								{
									// Add a variable to the class
									PyInfoVar* pVar = &pClass->variables[name];
									pVar->pParent = pClass;
									pVar->name = name;

									m_IntellMap[name][pClass] = PY_VARIABLE;
									i++;
									if(i != infoList.end()) 
									{
										pVar->help = (*i).Mid(12);
									}
								}
							}
						}
					}
				}
			}
		} // if class
		
		// Main functions
		else if(StringStartsWith(*i, "    ") && !StringStartsWith(*i, "        "))
		{
			CString name = ExtractKeyword(*i);
			if(!name.IsEmpty())
			{
				PyInfoFunc* pFunc = &m_Intell.functions[name];
				pFunc->pParent = &m_Intell;
				pFunc->name = name;

				m_IntellMap[name][&m_Intell] = PY_FUNCTION;
				i++;
				if(i != infoList.end())
				{
					pFunc->help = (*i).Mid(8); 
				}
			}
		}
	}
	//////////////////////////////
	// Parsing of txt file complete

	InitPythonForObjects();

}
Ejemplo n.º 25
0
bool
WaypointReaderSeeYou::ParseLine(const TCHAR* line, Waypoints &waypoints)
{
  enum {
    iName = 0,
    iLatitude = 3,
    iLongitude = 4,
    iElevation = 5,
    iStyle = 6,
    iRWDir = 7,
    iRWLen = 8,
    iFrequency = 9,
    iDescription = 10,
  };

  if (first) {
    first = false;

    /* skip first line if it doesn't begin with a quotation character
       (usually the field order line) */
    if (line[0] != _T('\"'))
      return true;
  }

  // If (end-of-file or comment)
  if (StringIsEmpty(line) ||
      StringStartsWith(line, _T("*")))
    // -> return without error condition
    return true;

  TCHAR ctemp[4096];
  if (_tcslen(line) >= ARRAY_SIZE(ctemp))
    /* line too long for buffer */
    return false;

  // If task marker is reached ignore all following lines
  if (StringStartsWith(line, _T("-----Related Tasks-----")))
    ignore_following = true;
  if (ignore_following)
    return true;

  // Get fields
  const TCHAR *params[20];
  size_t n_params = ExtractParameters(line, ctemp, params,
                                      ARRAY_SIZE(params), true, _T('"'));

  // Check if the basic fields are provided
  if (iName >= n_params ||
      iLatitude >= n_params ||
      iLongitude >= n_params)
    return false;

  GeoPoint location;

  // Latitude (e.g. 5115.900N)
  if (!ParseAngle(params[iLatitude], location.latitude, true))
    return false;

  // Longitude (e.g. 00715.900W)
  if (!ParseAngle(params[iLongitude], location.longitude, false))
    return false;

  location.Normalize(); // ensure longitude is within -180:180

  Waypoint new_waypoint = factory.Create(location);

  // Name (e.g. "Some Turnpoint")
  if (*params[iName] == _T('\0'))
    return false;
  new_waypoint.name = params[iName];

  // Elevation (e.g. 458.0m)
  /// @todo configurable behaviour
  if ((iElevation >= n_params ||
      !ParseAltitude(params[iElevation], new_waypoint.elevation)) &&
      !factory.FallbackElevation(new_waypoint))
    return false;

  // Style (e.g. 5)
  if (iStyle < n_params)
    ParseStyle(params[iStyle], new_waypoint.type);

  new_waypoint.flags.turn_point = true;

  // Frequency & runway direction/length (for airports and landables)
  // and description (e.g. "Some Description")
  if (new_waypoint.IsLandable()) {
    if (iFrequency < n_params)
      new_waypoint.radio_frequency = RadioFrequency::Parse(params[iFrequency]);

    // Runway length (e.g. 546.0m)
    double rwlen = -1;
    if (iRWLen < n_params && ParseDistance(params[iRWLen], rwlen) &&
        rwlen > 0)
      new_waypoint.runway.SetLength(uround(rwlen));

    if (iRWDir < n_params && *params[iRWDir]) {
      TCHAR *end;
      int direction =_tcstol(params[iRWDir], &end, 10);
      if (end == params[iRWDir] || direction < 0 || direction > 360 ||
          (direction == 0 && rwlen <= 0))
        direction = -1;
      else if (direction == 360)
        direction = 0;
      if (direction >= 0)
        new_waypoint.runway.SetDirectionDegrees(direction);
    }
  }

  if (iDescription < n_params) {
    /*
     * This convention was introduced by the OpenAIP
     * project (http://www.openaip.net/), since no waypoint type
     * exists for thermal hotspots.
     */
    if (StringStartsWith(params[iDescription], _T("Hotspot")))
      new_waypoint.type = Waypoint::Type::THERMAL_HOTSPOT;

    new_waypoint.comment = params[iDescription];
  }

  waypoints.Append(std::move(new_waypoint));
  return true;
}
Ejemplo n.º 26
0
/* Map old-style regex-or-hostname to new-style host-or-domain.
 *
 * Old-style ACLs could include regexes to be matched against host
 * names; but new-style ones only support sub-domain matching.  If the
 * old-style host regex looks like ".*\.sub\.domain\.tld" we can take
 * it in as ".sub.domain.tld"; otherwise, we can only really map exact
 * match hostnames.  However, we know some old policy (including our
 * own masterfiles) had cases of .*sub.domain.tld and it's possible
 * that someone might include a new-style .sub.domain.tld by mistake
 * in an (old-style) accept list; so cope with these cases, too.
 *
 * @param sl The string-list to which to add entries.
 * @param host The name-or-regex to add to the ACL.
 * @return An index at which an entry was added to the list (there may
 * be another), or -1 if nothing added.
 */
static size_t DeRegexify(StrList **sl, const char *host)
{
    if (IsRegex(host))
    {
        if (host[strcspn(host, "({[|+?]})")] != '\0')
        {
            return -1; /* Not a regex we can sensibly massage; discard. */
        }
        bool skip[2] = { false, false }; /* { domain, host } passes below */
        const char *name = host;
        if (name[0] == '^') /* Was always implicit; but read as hint to intent. */
        {
            /* Default to skipping domain-form if anchored explicitly: */
            skip[0] = true; /* Over-ridden below if followed by .* of course. */
            name++;
        }
        if (StringStartsWith(name, ".*"))
        {
            skip[0] = false; /* Domain-form should match */
            name += 2;
        }
        if (StringStartsWith(name, "\\."))
        {
            /* Skip host-form, as the regex definitely wants something
             * before the given name. */
            skip[1] = true;
            name += 2;
        }
        if (strchr(name, '*') != NULL)
        {
            /* Can't handle a * later than the preamble. */
            return (size_t) -1;
        }

        if (name > host || NULL != strchr(host, '\\'))
        {
            /* 2: leading '.' and final '\0' */
            char copy[2 + strlen(name)], *c = copy;
            c++[0] = '.'; /* For domain-form; and copy+1 gives host-form. */
            /* Now copy the rest of the name, de-regex-ifying as we go: */
            for (const char *p = name; p[0] != '\0'; p++)
            {
                if (p[0] == '\\')
                {
                    p++;
                    if (p[0] != '.')
                    {
                        /* Regex includes a non-dot escape */
                        return (size_t) -1;
                    }
                }
#if 0
                else if (p[0] == '.')
                {
                    /* In principle, this is a special character; but
                     * it may just be an unescaped dot, so let it be. */
                }
#endif
                c++[0] = p[0];
            }
            assert(c < copy + sizeof(copy));
            c[0] = '\0';

            /* Now, for host then domain, add entry if suitable */
            int pass = 2;
            size_t ret = -1;
            while (pass > 0)
            {
                pass--;
                if (!skip[pass]) /* pass 0 is domain, pass 1 is host */
                {
                    ret = StrList_Append(sl, copy + pass);
                }
            }
            return ret;
        }
        /* IsRegex() but is actually so boring it's just a name ! */
    }
    /* Just a simple host name. */

    return StrList_Append(sl, host);
}
Ejemplo n.º 27
0
void Webserver::ParseClientLine()
{ 
  if(StringStartsWith(clientLine, "GET"))
  {
    ParseGetPost();
    postSeen = false;
    getSeen = true;
    if(!clientRequest[0])
      strncpy(clientRequest, INDEX_PAGE, STRING_LENGTH);
    return;
  }
  
  if(StringStartsWith(clientLine, "POST"))
  {
    ParseGetPost();
    InitialisePost();
    postSeen = true;
    getSeen = false;
    if(!clientRequest[0])
      strncpy(clientRequest, INDEX_PAGE, STRING_LENGTH);
    return;
  }
  
  int bnd;
  
  if(postSeen && ( (bnd = StringContains(clientLine, "boundary=")) >= 0) )
  {
    if(strlen(&clientLine[bnd]) >= POST_LENGTH - 4)
    {
      platform->Message(HOST_MESSAGE, "Post boundary buffer overflow.\n");
      return;
    }
    postBoundary[0] = '-';
    postBoundary[1] = '-';
    strncpy(&postBoundary[2], &clientLine[bnd], POST_LENGTH - 3);
    strncat(postBoundary, "--", POST_LENGTH);
    //Serial.print("Got boundary: ");
    //Serial.println(postBoundary);
    return;
  }
  
  if(receivingPost && StringStartsWith(clientLine, "Content-Disposition:"))
  {
    bnd = StringContains(clientLine, "filename=\"");
    if(bnd < 0)
    {
      platform->Message(HOST_MESSAGE, "Post disposition gives no filename.\n");
      return;
    }
    int i = 0;
    while(clientLine[bnd] && clientLine[bnd] != '"')
    {
      postFileName[i++] = clientLine[bnd++];
      if(i >= POST_LENGTH)
      {
        i = 0;
        platform->Message(HOST_MESSAGE, "Post filename buffer overflow.\n");
      }
    }
    postFileName[i] = 0;
    //Serial.print("Got file name: ");
    //Serial.println(postFileName);    
    return;
  }  
}
Ejemplo n.º 28
0
void Webserver::GetJsonResponse(const char* request)
{
  jsonPointer = 0;
  writing = true;
  
  if(StringStartsWith(request, "poll"))
  {
    strncpy(jsonResponse, "{\"poll\":[", STRING_LENGTH);
    if(reprap.GetGCodes()->PrintingAFile())
    	strncat(jsonResponse, "\"P\",", STRING_LENGTH); // Printing
    else
    	strncat(jsonResponse, "\"I\",", STRING_LENGTH); // Idle

    float liveCoordinates[DRIVES+1];
    reprap.GetMove()->LiveCoordinates(liveCoordinates);
    for(int8_t drive = 0; drive < AXES; drive++)
    {
    	strncat(jsonResponse, "\"", STRING_LENGTH);
    	strncat(jsonResponse, ftoa(0, liveCoordinates[drive], 2), STRING_LENGTH);
    	strncat(jsonResponse, "\",", STRING_LENGTH);
    }

    // FIXME: should loop through all Es

    strncat(jsonResponse, "\"", STRING_LENGTH);
    strncat(jsonResponse, ftoa(0, liveCoordinates[AXES], 4), STRING_LENGTH);
    strncat(jsonResponse, "\",", STRING_LENGTH);

    for(int8_t heater = 0; heater < HEATERS; heater++)
    {
      strncat(jsonResponse, "\"", STRING_LENGTH);
      strncat(jsonResponse, ftoa(0, reprap.GetHeat()->GetTemperature(heater), 1), STRING_LENGTH);
      if(heater < HEATERS - 1)
    	  strncat(jsonResponse, "\",", STRING_LENGTH);
      else
    	  strncat(jsonResponse, "\"", STRING_LENGTH);
    }

    strncat(jsonResponse, "]", STRING_LENGTH);

    // Send the Z probe value
    char scratch[SHORT_STRING_LENGTH+1];
    scratch[SHORT_STRING_LENGTH] = 0;
    if (platform->GetZProbeType() == 2)
    {
    	snprintf(scratch, SHORT_STRING_LENGTH, ",\"probe\":\"%d (%d)\"", (int)platform->ZProbe(), platform->ZProbeOnVal());
    }
    else
    {
    	snprintf(scratch, SHORT_STRING_LENGTH, ",\"probe\":\"%d\"", (int)platform->ZProbe());
    }
    strncat(jsonResponse, scratch, STRING_LENGTH);

    // Send the amount of buffer space available for gcodes
   	snprintf(scratch, SHORT_STRING_LENGTH, ",\"buff\":%u", GetReportedGcodeBufferSpace());
   	strncat(jsonResponse, scratch, STRING_LENGTH);

    // Send the home state. To keep the messages short, we send 1 for homed and 0 for not homed, instead of true and false.
    strncat(jsonResponse, ",\"hx\":", STRING_LENGTH);
    strncat(jsonResponse, (reprap.GetGCodes()->GetAxisIsHomed(0)) ? "1" : "0", STRING_LENGTH);
    strncat(jsonResponse, ",\"hy\":", STRING_LENGTH);
    strncat(jsonResponse, (reprap.GetGCodes()->GetAxisIsHomed(1)) ? "1" : "0", STRING_LENGTH);
    strncat(jsonResponse, ",\"hz\":", STRING_LENGTH);
    strncat(jsonResponse, (reprap.GetGCodes()->GetAxisIsHomed(2)) ? "1" : "0", STRING_LENGTH);

    // Send the response sequence number
    strncat(jsonResponse, ",\"seq\":", STRING_LENGTH);
	snprintf(scratch, SHORT_STRING_LENGTH, "%u", (unsigned int)seq);
	strncat(jsonResponse, scratch, STRING_LENGTH);

    // Send the response to the last command. Do this last because it is long and may need to be truncated.
    strncat(jsonResponse, ",\"resp\":\"", STRING_LENGTH);
    size_t jp = strnlen(jsonResponse, STRING_LENGTH);
    const char *p = gcodeReply;
    while (*p != 0 && jp < STRING_LENGTH - 2)	// leave room for the final '"}'
    {
    	char c = *p++;
    	char esc;
    	switch(c)
    	{
    	case '\r':
    		esc = 'r'; break;
    	case '\n':
    		esc = 'n'; break;
    	case '\t':
    		esc = 't'; break;
    	case '"':
    		esc = '"'; break;
    	case '\\':
    		esc = '\\'; break;
    	default:
    		esc = 0; break;
    	}
    	if (esc)
    	{
    		if (jp == STRING_LENGTH - 3)
    			break;
   			jsonResponse[jp++] = '\\';
   			jsonResponse[jp++] = esc;
    	}
    	else
    	{
    		jsonResponse[jp++] = c;
    	}
    }
    strncat(jsonResponse, "\"}", STRING_LENGTH);

    jsonResponse[STRING_LENGTH] = 0;
    JsonReport(true, request);
    return;
  }
  
  if(StringStartsWith(request, "gcode"))
  {
    LoadGcodeBuffer(&clientQualifier[6], true);
    char scratch[SHORT_STRING_LENGTH+1];
    scratch[SHORT_STRING_LENGTH] = 0;
    snprintf(scratch, SHORT_STRING_LENGTH, "{\"buff\":%u}", GetReportedGcodeBufferSpace());
   	strncat(jsonResponse, scratch, STRING_LENGTH);
    JsonReport(true, request);
    return;
  }
  
  if(StringStartsWith(request, "files"))
  {
    char* fileList = platform->GetMassStorage()->FileList(platform->GetGCodeDir(), false);
    strncpy(jsonResponse, "{\"files\":[", STRING_LENGTH);
    strncat(jsonResponse, fileList, STRING_LENGTH);
    strncat(jsonResponse, "]}", STRING_LENGTH);
    JsonReport(true, request);
    return;
  }
  
  if(StringStartsWith(request, "name"))
  {
    strncpy(jsonResponse, "{\"myName\":\"", STRING_LENGTH);
    strncat(jsonResponse, myName, STRING_LENGTH);
    strncat(jsonResponse, "\"}", STRING_LENGTH);
    JsonReport(true, request);
    return;
  }
  
  if(StringStartsWith(request, "password"))
  {
    CheckPassword();
    strncpy(jsonResponse, "{\"password\":\"", STRING_LENGTH);
    if(gotPassword)
      strncat(jsonResponse, "right", STRING_LENGTH);
    else
      strncat(jsonResponse, "wrong", STRING_LENGTH);
    strncat(jsonResponse, "\"}", STRING_LENGTH);
    JsonReport(true, request);
    return;
  }
  
  if(StringStartsWith(request, "axes"))
  {
    strncpy(jsonResponse, "{\"axes\":[", STRING_LENGTH);
    for(int8_t drive = 0; drive < AXES; drive++)
    {
      strncat(jsonResponse, "\"", STRING_LENGTH);
      strncat(jsonResponse, ftoa(0, platform->AxisLength(drive), 1), STRING_LENGTH);
      if(drive < AXES-1)
        strncat(jsonResponse, "\",", STRING_LENGTH);
      else
        strncat(jsonResponse, "\"", STRING_LENGTH);
    }
    strncat(jsonResponse, "]}", STRING_LENGTH);
    JsonReport(true, request);
    return;
  }
  
  JsonReport(false, request);
}
Ejemplo n.º 29
0
void Webserver::SendFile(const char* nameOfFileToSend)
{
  char sLen[SHORT_STRING_LENGTH];
  bool zip = false;
    
  if(StringStartsWith(nameOfFileToSend, KO_START))
    GetJsonResponse(&nameOfFileToSend[KO_FIRST]);
    
  if(jsonPointer < 0)
  {
    fileBeingSent = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
    if(fileBeingSent == NULL)
    {
      nameOfFileToSend = FOUR04_FILE;
      fileBeingSent = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false);
    }
    writing = (fileBeingSent != NULL);
  } 
  
  Network *net = platform->GetNetwork();
  net->Write("HTTP/1.1 200 OK\n");
  net->Write("Content-Type: ");
  
  if(StringEndsWith(nameOfFileToSend, ".png"))
	  net->Write("image/png\n");
  else if(StringEndsWith(nameOfFileToSend, ".ico"))
	  net->Write("image/x-icon\n");
  else if (jsonPointer >= 0)
	  net->Write("application/json\n");
  else if(StringEndsWith(nameOfFileToSend, ".js"))
	  net->Write("application/javascript\n");
  else if(StringEndsWith(nameOfFileToSend, ".css"))
	  net->Write("text/css\n");
  else if(StringEndsWith(nameOfFileToSend, ".htm") || StringEndsWith(nameOfFileToSend, ".html"))
	  net->Write("text/html\n");
  else if(StringEndsWith(nameOfFileToSend, ".zip"))
  {
	  net->Write("application/zip\n");
	  zip = true;
  } else
	  net->Write("application/octet-stream\n");

  if (jsonPointer >=0)
  {
	net->Write("Content-Length: ");
    snprintf(sLen, SHORT_STRING_LENGTH, "%d", strlen(jsonResponse));
    net->Write(sLen);
    net->Write("\n");
  }
    
  if(zip)
  {
	net->Write("Content-Encoding: gzip\n");
	net->Write("Content-Length: ");
    snprintf(sLen, SHORT_STRING_LENGTH, "%llu", fileBeingSent->Length());
    net->Write(sLen);
    net->Write("\n");
  }
    
  net->Write("Connection: close\n");
  net->Write('\n');
}
Ejemplo n.º 30
0
void Webserver::ProcessGcode(const char* gc)
{
  int8_t specialAction = 0;
  if(StringStartsWith(gc, "M30 "))
  {
	  specialAction = 1;
  }
  else if(StringStartsWith(gc, "M23 "))
  {
	  specialAction = 2;
  }
  else if(StringStartsWith(gc, "M112") && !isdigit(gc[4]))
  {
	  specialAction = 3;
  }
  else if(StringStartsWith(gc, "M503") && !isdigit(gc[4]))
  {
	  specialAction = 4;
  }
  
  if(specialAction != 0) // Delete or print a file?
  { 
    switch (specialAction)
    {
    case 1: // Delete
      reprap.GetGCodes()->DeleteFile(&gc[4]);
      break;

    case 2:	// print
      reprap.GetGCodes()->QueueFileToPrint(&gc[4]);
      break;

    case 3:
      reprap.EmergencyStop();
      break;

    case 4:
	  {
		FileStore *configFile = platform->GetFileStore(platform->GetSysDir(), platform->GetConfigFile(), false);
		if(configFile == NULL)
		{
		  HandleReply("Configuration file not found", true);
		}
		else
		{
		  char c;
		  size_t i = 0;
		  while(i < STRING_LENGTH && configFile->Read(c))
		  {
			gcodeReply[i++] = c;
		  }
		  configFile->Close();
		  gcodeReply[i] = 0;
		  ++seq;
		}
	  }
	  break;
    }
  }
  else
  {
	  // Copy the gcode to the buffer
	  size_t len = strlen(gc) + 1;		// number of characters to copy
	  if (len > GetGcodeBufferSpace())
	  {
		  platform->Message(HOST_MESSAGE, "Webserver: GCode buffer overflow.\n");
		  HandleReply("Webserver: GCode buffer overflow", true);
	  }
	  else
	  {
		  size_t remaining = gcodeBufLength - gcodeWriteIndex;
		  if (len <= remaining)
		  {
			  memcpy(&gcodeBuffer[gcodeWriteIndex], gc, len);
		  }
		  else
		  {
			  memcpy(&gcodeBuffer[gcodeWriteIndex], gc, remaining);
			  memcpy(gcodeBuffer, gc + remaining, len - remaining);
		  }
		  gcodeWriteIndex = (gcodeWriteIndex + len) % gcodeBufLength;
	  }
  }
}