Example #1
0
inline void removeNonDigits(const String& in, String& out)
{removeNonDigits(in.data(), in.length(), out);}
Example #2
0
size_t Print::print(const String &s)
{
  return write(s.c_str(), s.length());
}
Example #3
0
bool ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){
  (void) len;
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Parse Form: Boundary: ");
  DEBUG_OUTPUT.print(boundary);
  DEBUG_OUTPUT.print(" Length: ");
  DEBUG_OUTPUT.println(len);
#endif
  String line;
  int retry = 0;
  do {
    line = client.readStringUntil('\r');
    ++retry;
  } while (line.length() == 0 && retry < 3);

  client.readStringUntil('\n');
  //start reading the form
  if (line == ("--"+boundary)){
    RequestArgument* postArgs = new RequestArgument[32];
    int postArgsLen = 0;
    while(1){
      String argName;
      String argValue;
      String argType;
      String argFilename;
      bool argIsFile = false;

      line = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (line.length() > 19 && line.substring(0, 19).equalsIgnoreCase("Content-Disposition")){
        int nameStart = line.indexOf('=');
        if (nameStart != -1){
          argName = line.substring(nameStart+2);
          nameStart = argName.indexOf('=');
          if (nameStart == -1){
            argName = argName.substring(0, argName.length() - 1);
          } else {
            argFilename = argName.substring(nameStart+2, argName.length() - 1);
            argName = argName.substring(0, argName.indexOf('"'));
            argIsFile = true;
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("PostArg FileName: ");
            DEBUG_OUTPUT.println(argFilename);
#endif
            //use GET to set the filename if uploading using blob
            if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename");
          }
#ifdef DEBUG_ESP_HTTP_SERVER
          DEBUG_OUTPUT.print("PostArg Name: ");
          DEBUG_OUTPUT.println(argName);
#endif
          argType = "text/plain";
          line = client.readStringUntil('\r');
          client.readStringUntil('\n');
          if (line.length() > 12 && line.substring(0, 12).equalsIgnoreCase("Content-Type")){
            argType = line.substring(line.indexOf(':')+2);
            //skip next line
            client.readStringUntil('\r');
            client.readStringUntil('\n');
          }
#ifdef DEBUG_ESP_HTTP_SERVER
          DEBUG_OUTPUT.print("PostArg Type: ");
          DEBUG_OUTPUT.println(argType);
#endif
          if (!argIsFile){
            while(1){
              line = client.readStringUntil('\r');
              client.readStringUntil('\n');
              if (line.startsWith("--"+boundary)) break;
              if (argValue.length() > 0) argValue += "\n";
              argValue += line;
            }
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("PostArg Value: ");
            DEBUG_OUTPUT.println(argValue);
            DEBUG_OUTPUT.println();
#endif

            RequestArgument& arg = postArgs[postArgsLen++];
            arg.key = argName;
            arg.value = argValue;

            if (line == ("--"+boundary+"--")){
#ifdef DEBUG_ESP_HTTP_SERVER
              DEBUG_OUTPUT.println("Done Parsing POST");
#endif
              break;
            }
          } else {
            _currentUpload.status = UPLOAD_FILE_START;
            _currentUpload.name = argName;
            _currentUpload.filename = argFilename;
            _currentUpload.type = argType;
            _currentUpload.totalSize = 0;
            _currentUpload.currentSize = 0;
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("Start File: ");
            DEBUG_OUTPUT.print(_currentUpload.filename);
            DEBUG_OUTPUT.print(" Type: ");
            DEBUG_OUTPUT.println(_currentUpload.type);
#endif
            if(_currentHandler && _currentHandler->canUpload(_currentUri))
              _currentHandler->upload(*this, _currentUri, _currentUpload);
            _currentUpload.status = UPLOAD_FILE_WRITE;
            uint8_t argByte = _uploadReadByte(client);
readfile:
            while(argByte != 0x0D){
              if (!client.connected()) return _parseFormUploadAborted();
              _uploadWriteByte(argByte);
              argByte = _uploadReadByte(client);
            }

            argByte = _uploadReadByte(client);
            if (!client.connected()) return _parseFormUploadAborted();
            if (argByte == 0x0A){
              argByte = _uploadReadByte(client);
              if (!client.connected()) return _parseFormUploadAborted();
              if ((char)argByte != '-'){
                //continue reading the file
                _uploadWriteByte(0x0D);
                _uploadWriteByte(0x0A);
                goto readfile;
              } else {
                argByte = _uploadReadByte(client);
                if (!client.connected()) return _parseFormUploadAborted();
                if ((char)argByte != '-'){
                  //continue reading the file
                  _uploadWriteByte(0x0D);
                  _uploadWriteByte(0x0A);
                  _uploadWriteByte((uint8_t)('-'));
                  goto readfile;
                }
              }

              uint8_t endBuf[boundary.length()];
              client.readBytes(endBuf, boundary.length());

              if (strstr((const char*)endBuf, boundary.c_str()) != NULL){
                if(_currentHandler && _currentHandler->canUpload(_currentUri))
                  _currentHandler->upload(*this, _currentUri, _currentUpload);
                _currentUpload.totalSize += _currentUpload.currentSize;
                _currentUpload.status = UPLOAD_FILE_END;
                if(_currentHandler && _currentHandler->canUpload(_currentUri))
                  _currentHandler->upload(*this, _currentUri, _currentUpload);
#ifdef DEBUG_ESP_HTTP_SERVER
                DEBUG_OUTPUT.print("End File: ");
                DEBUG_OUTPUT.print(_currentUpload.filename);
                DEBUG_OUTPUT.print(" Type: ");
                DEBUG_OUTPUT.print(_currentUpload.type);
                DEBUG_OUTPUT.print(" Size: ");
                DEBUG_OUTPUT.println(_currentUpload.totalSize);
#endif
                line = client.readStringUntil(0x0D);
                client.readStringUntil(0x0A);
                if (line == "--"){
#ifdef DEBUG_ESP_HTTP_SERVER
                  DEBUG_OUTPUT.println("Done Parsing POST");
#endif
                  break;
                }
                continue;
              } else {
                _uploadWriteByte(0x0D);
                _uploadWriteByte(0x0A);
                _uploadWriteByte((uint8_t)('-'));
                _uploadWriteByte((uint8_t)('-'));
                uint32_t i = 0;
                while(i < boundary.length()){
                  _uploadWriteByte(endBuf[i++]);
                }
                argByte = _uploadReadByte(client);
                goto readfile;
              }
            } else {
              _uploadWriteByte(0x0D);
              goto readfile;
            }
            break;
          }
        }
      }
    }

    int iarg;
    int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;
    for (iarg = 0; iarg < totalArgs; iarg++){
      RequestArgument& arg = postArgs[postArgsLen++];
      arg.key = _currentArgs[iarg].key;
      arg.value = _currentArgs[iarg].value;
    }
    if (_currentArgs) delete[] _currentArgs;
    _currentArgs = new RequestArgument[postArgsLen];
    for (iarg = 0; iarg < postArgsLen; iarg++){
      RequestArgument& arg = _currentArgs[iarg];
      arg.key = postArgs[iarg].key;
      arg.value = postArgs[iarg].value;
    }
    _currentArgCount = iarg;
    if (postArgs) delete[] postArgs;
    return true;
  }
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Error: line: ");
  DEBUG_OUTPUT.println(line);
#endif
  return false;
}
Example #4
0
void ProxySerial::print(String s) { 
    for (uint8_t i=0; i<s.length(); i++)         {
        //  _checkSpeed();  
        _proxyPort->print(s.charAt(i));
    }
}
 bool BrazilianStemmer::isIndexable(const String& term)
 {
     return (term.length() < 30) && (term.length() > 2);
 }
// Helper function to determine whether text is a single word.
static bool isASingleWord(const String& text)
{
    TextBreakIterator* it = wordBreakIterator(text, 0, text.length());
    return it && it->next() == static_cast<int>(text.length());
}
Example #7
0
    virtual void report(const SearchReport& report, const char *context) {
        String ctx = context;
        String key = report.key.c_str();
        String prefix = "";

        prefix = ctx;
        prefix += ".";

        key = prefix + key;
        if (key.substr(0,1)==".") {
            key = key.substr(1,key.length());
        }

        if (!present.check(key.c_str())) {
            present.put(key.c_str(),"present");
            order.addString(key.c_str());
        }

        if (report.isFound) {
            actual.put(key.c_str(),report.value);
        }

        if (report.isComment==true) {
            comment.put(key.c_str(),report.value);
            return;
        }

        if (report.isDefault==true) {
            fallback.put(key.c_str(),report.value);
            return;
        }

        if (comment.check(key.c_str())) {
            if (!reported.check(key.c_str())) {
                if (report.isFound) {
                    String hasValue = report.value.c_str();
                    if (hasValue.length()>35) {
                        hasValue = hasValue.substr(0,30) + " ...";
                    }
                    printf("Checking \"%s\": = %s (%s)\n", key.c_str(),
                           hasValue.c_str(),
                           comment.check(key.c_str(),
                                         Value("")).toString().c_str());
                } else {
                    reported.put(key.c_str(),1);
                    bool hasDefault = fallback.check(key.c_str());
                    String defString = "";
                    if (hasDefault) {
                        defString += " ";
                        defString += "(default ";
                        String theDefault =
                            fallback.find(key.c_str()).toString().c_str();
                        if (theDefault=="") {
                            defString += "is blank";
                        } else {
                            defString += theDefault;
                        }
                        defString += ")";
                    }
                    printf("Checking \"%s\": %s%s\n", key.c_str(),
                           comment.check(key.c_str(),
                                         Value("")).toString().c_str(),
                           defString.c_str());
                }
            }
        }
    }
Example #8
0
void SubString::operator=(const String& s)
{
        if (sl == s.length()) strncpy(sp,s.p,sl);
        else replace(s.p,s.len);
}
Example #9
0
int
hstcpcli::response_recv(size_t& num_flds_r)
{
  if (error_code < 0) {
    return error_code;
  }
  clear_error();
  if (num_req_bufd > 0 || num_req_sent == 0 || num_req_rcvd > 0 ||
    response_end_offset != 0) {
    close();
    return set_error(-1, "response_recv: protocol out of sync");
  }
  cur_row_offset = 0;
  num_flds_r = num_flds = 0;
  if (fd.get() < 0) {
    return set_error(-1, "read: closed");
  }
  size_t offset = 0;
  while (true) {
    const char *const lbegin = readbuf.begin() + offset;
    const char *const lend = readbuf.end();
    if (lbegin < lend)
    {
      const char *const nl = memchr_char(lbegin, '\n', lend - lbegin);
      if (nl != 0) {
        offset += (nl + 1) - lbegin;
        break;
      }
      offset += lend - lbegin;
    }
    if (read_more() <= 0) {
      close();
      error_code = -1;
      return error_code;
    }
  }
  response_end_offset = offset;
  --num_req_sent;
  ++num_req_rcvd;
  char *start = readbuf.begin();
  char *const finish = start + response_end_offset - 1;
  const size_t resp_code = read_ui32(start, finish);
  skip_one(start, finish);
  num_flds_r = num_flds = read_ui32(start, finish);
  if (resp_code != 0) {
    skip_one(start, finish);
    char *const err_begin = start;
    read_token(start, finish);
    char *const err_end = start;
    String e = String(err_begin, err_end - err_begin, &my_charset_bin);
    if (!e.length()) {
      e = String("unknown_error", &my_charset_bin);
    }
    return set_error(resp_code, e);
  }
  cur_row_offset = start - readbuf.begin();
  DBG(fprintf(stderr, "[%s] ro=%zu eol=%zu\n",
    String(readbuf.begin(), readbuf.begin() + response_end_offset)
      .c_str(),
    cur_row_offset, response_end_offset));
  DBG(fprintf(stderr, "RES 0\n"));
  if (flds.max_element < num_flds)
  {
    if (allocate_dynamic(&flds, num_flds))
      return set_error(-1, "out of memory");
  }
  flds.elements = num_flds;
  return 0;
}
Example #10
0
void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
{
    if (text.isEmpty())
        return;

    if (undoable)
    {
        undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
    }
    else
    {
        Position pos (this, insertPos);
        const int firstAffectedLine = pos.getLineNumber();
        int lastAffectedLine = firstAffectedLine + 1;

        CodeDocumentLine* const firstLine = lines [firstAffectedLine];
        String textInsideOriginalLine (text);

        if (firstLine != nullptr)
        {
            const int index = pos.getIndexInLine();
            textInsideOriginalLine = firstLine->line.substring (0, index)
                                     + textInsideOriginalLine
                                     + firstLine->line.substring (index);
        }

        maximumLineLength = -1;
        Array <CodeDocumentLine*> newLines;
        CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
        jassert (newLines.size() > 0);

        CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
        newFirstLine->lineStartInFile = firstLine != nullptr ? firstLine->lineStartInFile : 0;
        lines.set (firstAffectedLine, newFirstLine);

        if (newLines.size() > 1)
        {
            for (int i = 1; i < newLines.size(); ++i)
            {
                CodeDocumentLine* const l = newLines.getUnchecked (i);
                lines.insert (firstAffectedLine + i, l);
            }

            lastAffectedLine = lines.size();
        }

        int i, lineStart = newFirstLine->lineStartInFile;
        for (i = firstAffectedLine; i < lines.size(); ++i)
        {
            CodeDocumentLine* const l = lines.getUnchecked (i);
            l->lineStartInFile = lineStart;
            lineStart += l->lineLength;
        }

        checkLastLineStatus();

        const int newTextLength = text.length();
        for (i = 0; i < positionsToMaintain.size(); ++i)
        {
            CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);

            if (p->getPosition() >= insertPos)
                p->setPosition (p->getPosition() + newTextLength);
        }

        sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
    }
}
String TextCheckingHelper::findFirstMisspellingOrBadGrammar(bool checkGrammar, bool& outIsSpelling, int& outFirstFoundOffset, GrammarDetail& outGrammarDetail)
{
    if (!unifiedTextCheckerEnabled())
        return emptyString();

    String firstFoundItem;
    String misspelledWord;
    String badGrammarPhrase;
    
    // Initialize out parameters; these will be updated if we find something to return.
    outIsSpelling = true;
    outFirstFoundOffset = 0;
    outGrammarDetail.location = -1;
    outGrammarDetail.length = 0;
    outGrammarDetail.guesses.clear();
    outGrammarDetail.userDescription = emptyString();
    
    // Expand the search range to encompass entire paragraphs, since text checking needs that much context.
    // Determine the character offset from the start of the paragraph to the start of the original search range,
    // since we will want to ignore results in this area.
    Ref<Range> paragraphRange = m_range->cloneRange();
    setStart(paragraphRange.ptr(), startOfParagraph(m_range->startPosition()));
    int totalRangeLength = TextIterator::rangeLength(paragraphRange.ptr());
    setEnd(paragraphRange.ptr(), endOfParagraph(m_range->startPosition()));
    
    Ref<Range> offsetAsRange = Range::create(paragraphRange->startContainer().document(), paragraphRange->startPosition(), m_range->startPosition());
    int rangeStartOffset = TextIterator::rangeLength(offsetAsRange.ptr());
    int totalLengthProcessed = 0;
    
    bool firstIteration = true;
    bool lastIteration = false;
    while (totalLengthProcessed < totalRangeLength) {
        // Iterate through the search range by paragraphs, checking each one for spelling and grammar.
        int currentLength = TextIterator::rangeLength(paragraphRange.ptr());
        int currentStartOffset = firstIteration ? rangeStartOffset : 0;
        int currentEndOffset = currentLength;
        if (inSameParagraph(paragraphRange->startPosition(), m_range->endPosition())) {
            // Determine the character offset from the end of the original search range to the end of the paragraph,
            // since we will want to ignore results in this area.
            RefPtr<Range> endOffsetAsRange = Range::create(paragraphRange->startContainer().document(), paragraphRange->startPosition(), m_range->endPosition());
            currentEndOffset = TextIterator::rangeLength(endOffsetAsRange.get());
            lastIteration = true;
        }
        if (currentStartOffset < currentEndOffset) {
            String paragraphString = plainText(paragraphRange.ptr());
            if (paragraphString.length() > 0) {
                bool foundGrammar = false;
                int spellingLocation = 0;
                int grammarPhraseLocation = 0;
                int grammarDetailLocation = 0;
                unsigned grammarDetailIndex = 0;
                
                Vector<TextCheckingResult> results;
                TextCheckingTypeMask checkingTypes = checkGrammar ? (TextCheckingTypeSpelling | TextCheckingTypeGrammar) : TextCheckingTypeSpelling;
                VisibleSelection currentSelection;
                if (Frame* frame = paragraphRange->ownerDocument().frame())
                    currentSelection = frame->selection().selection();
                checkTextOfParagraph(*m_client->textChecker(), paragraphString, checkingTypes, results, currentSelection);

                for (auto& result : results) {
                    if (result.type == TextCheckingTypeSpelling && result.location >= currentStartOffset && result.location + result.length <= currentEndOffset) {
                        ASSERT(result.length > 0);
                        ASSERT(result.location >= 0);
                        spellingLocation = result.location;
                        misspelledWord = paragraphString.substring(result.location, result.length);
                        ASSERT(misspelledWord.length());
                        break;
                    }
                    if (checkGrammar && result.type == TextCheckingTypeGrammar && result.location < currentEndOffset && result.location + result.length > currentStartOffset) {
                        ASSERT(result.length > 0);
                        ASSERT(result.location >= 0);
                        // We can't stop after the first grammar result, since there might still be a spelling result after
                        // it begins but before the first detail in it, but we can stop if we find a second grammar result.
                        if (foundGrammar)
                            break;
                        for (unsigned j = 0; j < result.details.size(); j++) {
                            const GrammarDetail* detail = &result.details[j];
                            ASSERT(detail->length > 0);
                            ASSERT(detail->location >= 0);
                            if (result.location + detail->location >= currentStartOffset && result.location + detail->location + detail->length <= currentEndOffset && (!foundGrammar || result.location + detail->location < grammarDetailLocation)) {
                                grammarDetailIndex = j;
                                grammarDetailLocation = result.location + detail->location;
                                foundGrammar = true;
                            }
                        }
                        if (foundGrammar) {
                            grammarPhraseLocation = result.location;
                            outGrammarDetail = result.details[grammarDetailIndex];
                            badGrammarPhrase = paragraphString.substring(result.location, result.length);
                            ASSERT(badGrammarPhrase.length());
                        }
                    }
                }

                if (!misspelledWord.isEmpty() && (!checkGrammar || badGrammarPhrase.isEmpty() || spellingLocation <= grammarDetailLocation)) {
                    int spellingOffset = spellingLocation - currentStartOffset;
                    if (!firstIteration) {
                        RefPtr<Range> paragraphOffsetAsRange = Range::create(paragraphRange->startContainer().document(), m_range->startPosition(), paragraphRange->startPosition());
                        spellingOffset += TextIterator::rangeLength(paragraphOffsetAsRange.get());
                    }
                    outIsSpelling = true;
                    outFirstFoundOffset = spellingOffset;
                    firstFoundItem = misspelledWord;
                    break;
                }
                if (checkGrammar && !badGrammarPhrase.isEmpty()) {
                    int grammarPhraseOffset = grammarPhraseLocation - currentStartOffset;
                    if (!firstIteration) {
                        RefPtr<Range> paragraphOffsetAsRange = Range::create(paragraphRange->startContainer().document(), m_range->startPosition(), paragraphRange->startPosition());
                        grammarPhraseOffset += TextIterator::rangeLength(paragraphOffsetAsRange.get());
                    }
                    outIsSpelling = false;
                    outFirstFoundOffset = grammarPhraseOffset;
                    firstFoundItem = badGrammarPhrase;
                    break;
                }
            }
        }
        if (lastIteration || totalLengthProcessed + currentLength >= totalRangeLength)
            break;
        VisiblePosition newParagraphStart = startOfNextParagraph(paragraphRange->endPosition());
        setStart(paragraphRange.ptr(), newParagraphStart);
        setEnd(paragraphRange.ptr(), endOfParagraph(newParagraphStart));
        firstIteration = false;
        totalLengthProcessed += currentLength;
    }
    return firstFoundItem;
}
Example #12
0
void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const {


	Vector<String> lines = p_code.split("\n");
	List<int> indent_stack;

	for(int i=0;i<lines.size();i++) {

		String l = lines[i];
		int tc=0;
		for(int j=0;j<l.length();j++) {
			if (l[j]==' ' || l[j]=='\t') {

				tc++;
			} else {
				break;
			}
		}


		String st = l.substr(tc,l.length()).strip_edges();
		if (st=="" || st.begins_with("#"))
			continue; //ignore!

		int ilevel=0;
		if (indent_stack.size()) {
			ilevel=indent_stack.back()->get();
		}

		if (tc>ilevel) {
			indent_stack.push_back(tc);
		} else if (tc<ilevel) {
			while(indent_stack.size() && indent_stack.back()->get()>tc) {
				indent_stack.pop_back();
			}

			if (indent_stack.size() && indent_stack.back()->get()!=tc)
				indent_stack.push_back(tc); //this is not right but gets the job done
		}

		if (i>=p_from_line) {

			l="";
			for(int j=0;j<indent_stack.size();j++)
				l+="\t";
			l+=st;


		} else if (i>p_to_line) {
			break;
		}

		//print_line(itos(indent_stack.size())+","+itos(tc)+": "+l);
		lines[i]=l;
	}

	p_code="";
	for(int i=0;i<lines.size();i++) {
		if (i>0)
			p_code+="\n";
		p_code+=lines[i];
	}

}
Example #13
0
void PropertyWindow::SetProperty()
{
	if(property->GetOption().second!=-1 && textField->GetText().length() > 0)
	{
		String value = textField->GetText();
		try {
			switch(properties[property->GetOption().second].Type)
			{
				case StructProperty::Integer:
				case StructProperty::ParticleType:
				{
					int v;
					if(value.length() > 2 && value.BeginsWith("0x"))
					{
						//0xC0FFEE
						v = value.Substr(2).ToNumber<unsigned int>(Format::Hex());
					}
					else if(value.length() > 1 && value.BeginsWith("#"))
					{
						//#C0FFEE
						v = value.Substr(1).ToNumber<unsigned int>(Format::Hex());
					}
					else
					{
						int type;
						if ((type = sim->GetParticleType(value.ToUtf8())) != -1)
						{
							v = type;

#ifdef DEBUG
							std::cout << "Got type from particle name" << std::endl;
#endif
						}
						else
						{
							v = value.ToNumber<int>();
						}
					}

					if (properties[property->GetOption().second].Name == "type" && (v < 0 || v >= PT_NUM || !sim->elements[v].Enabled))
					{
						new ErrorMessage("Could not set property", "Invalid particle type");
						return;
					}

#ifdef DEBUG
					std::cout << "Got int value " << v << std::endl;
#endif

					tool->propValue.Integer = v;
					break;
				}
				case StructProperty::UInteger:
				{
					unsigned int v;
					if(value.length() > 2 && value.BeginsWith("0x"))
					{
						//0xC0FFEE
						v = value.Substr(2).ToNumber<unsigned int>(Format::Hex());
					}
					else if(value.length() > 1 && value.BeginsWith("#"))
					{
						//#C0FFEE
						v = value.Substr(1).ToNumber<unsigned int>(Format::Hex());
					}
					else
					{
						v = value.ToNumber<unsigned int>();
					}
#ifdef DEBUG
					std::cout << "Got uint value " << v << std::endl;
#endif
					tool->propValue.UInteger = v;
					break;
				}
				case StructProperty::Float:
				{
					if (value.EndsWith("C"))
					{
						float v = value.SubstrFromEnd(1).ToNumber<float>();
						tool->propValue.Float = v + 273.15;
					}
					else if(value.EndsWith("F"))
					{
						float v = value.SubstrFromEnd(1).ToNumber<float>();
						tool->propValue.Float = (v-32.0f)*5/9+273.15f;
					}
					else
					{
						tool->propValue.Float = value.ToNumber<float>();
					}
#ifdef DEBUG
					std::cout << "Got float value " << tool->propValue.Float << std::endl;
#endif
				}
					break;
				default:
					new ErrorMessage("Could not set property", "Invalid property");
					return;
			}
			tool->propOffset = properties[property->GetOption().second].Offset;
			tool->propType = properties[property->GetOption().second].Type;
		} catch (const std::exception& ex) {
			new ErrorMessage("Could not set property", "Invalid value provided");
			return;
		}
		Client::Ref().SetPref("Prop.Type", property->GetOption().second);
		Client::Ref().SetPrefUnicode("Prop.Value", textField->GetText());
	}
}
Example #14
0
float XBeeReader::stringToFloat(String input){
  char buff[input.length()];
  input.toCharArray(buff, input.length());
  return atof(buff);
}
Example #15
0
void CookieManager::getRawCookies(Vector<RefPtr<ParsedCookie> > &stackOfCookies, const URL& requestURL, CookieFilter filter) const
{
    // Force a sync load of the database
    if (!m_syncedWithDatabase && !m_privateMode)
        m_cookieBackingStore->openAndLoadDatabaseSynchronously(cookieJar());

    CookieLog("CookieManager - getRawCookies - processing url with domain - %s & protocol: %s & path: %s\n", requestURL.host().utf8().data(), requestURL.protocol().utf8().data(), requestURL.path().utf8().data());

    const bool invalidScheme = shouldIgnoreScheme(requestURL.protocol());
    const bool specialCaseForWebWorks = invalidScheme && m_shouldDumpAllCookies;
    const bool isConnectionSecure = requestURL.protocolIs("https") || requestURL.protocolIs("wss") || specialCaseForWebWorks;

    Vector<RefPtr<ParsedCookie> > cookieCandidates;
    Vector<CookieMap*> protocolsToSearch;

    // Special Case: If a server sets a "secure" cookie over a non-secure channel and tries to access the cookie
    // over a secure channel, it will not succeed because the secure protocol isn't mapped to the insecure protocol yet.
    // Set the map to the non-secure version, so it'll search the mapping for a secure cookie.
    CookieMap* targetMap = m_managerMap.get(requestURL.protocol());
    if (!targetMap && isConnectionSecure) {
        CookieLog("CookieManager - special case: secure protocol are not linked yet.");
        if (requestURL.protocolIs("https"))
            targetMap = m_managerMap.get("http");
        else if (requestURL.protocolIs("wss"))
            targetMap = m_managerMap.get("ws");
    }

    // Decide which scheme tree we should look at.
    // Return on invalid schemes. cookies are currently disabled on file and local.
    // We only want to enable them for WebWorks that enabled a special flag.
    if (specialCaseForWebWorks)
        copyValuesToVector(m_managerMap, protocolsToSearch);
    else if (invalidScheme)
        return;
    else {
        protocolsToSearch.append(targetMap);
        // FIXME: this is a hack for webworks apps; RFC 6265 says "Cookies do not provide isolation by scheme"
        // so we should not be checking protocols at all. See PR 135595
        if (m_shouldDumpAllCookies) {
            protocolsToSearch.append(m_managerMap.get("file"));
            protocolsToSearch.append(m_managerMap.get("local"));
        }
    }

    Vector<String> delimitedHost;

    // IP addresses are stored in a particular format (due to ipv6). Reduce the ip address so we can match
    // it with the one in memory.
    BlackBerry::Platform::String canonicalIP = BlackBerry::Platform::getCanonicalIPFormat(requestURL.host());
    if (!canonicalIP.empty())
        delimitedHost.append(String(canonicalIP.c_str()));
    else
        requestURL.host().lower().split(".", true, delimitedHost);

    // Go through all the protocol trees that we need to search for
    // and get all cookies that are valid for this domain
    for (size_t k = 0; k < protocolsToSearch.size(); k++) {
        CookieMap* currentMap = protocolsToSearch[k];

        // if no cookies exist for this protocol, break right away
        if (!currentMap)
            continue;

        CookieLog("CookieManager - looking at protocol map %s \n", currentMap->getName().utf8().data());

        // Special case for local and files - because WebApps expect to get ALL cookies from the backing-store on local protocol
        if (specialCaseForWebWorks) {
            CookieLog("CookieManager - special case find in protocol map - %s\n", currentMap->getName().utf8().data());
            currentMap->getAllChildCookies(&cookieCandidates);
        } else {
            // Get cookies from the null domain map
            currentMap->getAllCookies(&cookieCandidates);

            // Get cookies from Host-only cookies
            if (canonicalIP.empty()) {
                CookieLog("CookieManager - looking for host-only cookies for host - %s", requestURL.host().utf8().data());
                CookieMap* hostMap = currentMap->getSubdomainMap(requestURL.host());
                if (hostMap)
                    hostMap->getAllCookies(&cookieCandidates);
            }

            // Get cookies from the valid domain maps
            int i = delimitedHost.size() - 1;
            while (i >= 0) {
                CookieLog("CookieManager - finding %s in currentmap\n", delimitedHost[i].utf8().data());
                currentMap = currentMap->getSubdomainMap(delimitedHost[i]);
                // if this subdomain/domain does not exist in our mapping then we simply exit
                if (!currentMap) {
                    CookieLog("CookieManager - cannot find next map exiting the while loop.\n");
                    break;
                }
                CookieLog("CookieManager - found the map, grabbing cookies from this map\n");
                currentMap->getAllCookies(&cookieCandidates);
                i--;
            }
        }
    }

    CookieLog("CookieManager - there are %d cookies in candidate\n", cookieCandidates.size());

    for (size_t i = 0; i < cookieCandidates.size(); ++i) {
        RefPtr<ParsedCookie> cookie = cookieCandidates[i];

        // According to the path-matches rules in RFC6265, section 5.1.4,
        // we should add a '/' at the end of cookie-path for comparison if the cookie-path is not end with '/'.
        String path = cookie->path();
        CookieLog("CookieManager - comparing cookie path %s (len %d) to request path %s (len %d)", path.utf8().data(), path.length(), requestURL.path().utf8().data(), path.length());
        if (!equalIgnoringCase(path, requestURL.path()) && !path.endsWith("/", false))
            path = path + "/";

        // Only secure connections have access to secure cookies. Unless specialCaseForWebWorks is true.
        // Get the cookies filtering out HttpOnly cookies if requested.
        if (requestURL.path().startsWith(path, false) && (isConnectionSecure || !cookie->isSecure()) && (filter == WithHttpOnlyCookies || !cookie->isHttpOnly())) {
            CookieLog("CookieManager - cookie chosen - %s\n", cookie->toString().utf8().data());
            cookie->setLastAccessed(currentTime());
            stackOfCookies.append(cookie);
        }
    }

    std::stable_sort(stackOfCookies.begin(), stackOfCookies.end(), cookieSorter);
}
//-----------------------------------------------------------------------------
void GLSLProgramProcessor::bindSubShaders(Program* program, GpuProgramPtr pGpuProgram)
{
	if (program->getDependencyCount() > 0)
	{
		// Get all attached shaders so we do not attach shaders twice.
		// maybe GLSLProgram should take care of that ( prevent add duplicate shaders )
		String attachedShaders = pGpuProgram->getParameter("attach");
		String subShaderDef = "";

		for (unsigned int i=0; i < program->getDependencyCount(); ++i)
		{
			// Here we append _VS and _FS to the library shaders (so max each lib shader
			// is compiled twice once as vertex and once as fragment shader)
			String subShaderName = program->getDependency(i);
			if (program->getType() == GPT_VERTEX_PROGRAM)
			{
				subShaderName += "_VS";
			}
			else
			{
				subShaderName += "_FS";
			}					

			// Check if the library shader already compiled
			if(!HighLevelGpuProgramManager::getSingleton().resourceExists(subShaderName))
			{
				// Create the library shader
				HighLevelGpuProgramPtr pSubGpuProgram = HighLevelGpuProgramManager::getSingleton().createProgram(subShaderName,
					ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TargetLanguage, program->getType());

				// Set the source name
				String sourceName = program->getDependency(i) + "." + TargetLanguage;
				pSubGpuProgram->setSourceFile(sourceName);

				// If we have compile errors than stop processing
				if (pSubGpuProgram->hasCompileError())
				{
					OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
						"Could not compile shader library from the source file: " + sourceName, 
						"GLSLProgramProcessor::bindSubShaders" );	
				}

				mLibraryPrograms.push_back(subShaderName);
			}

			// Check if the lib shader already attached to this shader
			if (attachedShaders.find(subShaderName) == String::npos)
			{
				// Append the shader name to subShaders
				subShaderDef += subShaderName + " ";
			}
		}

		// Check if we have something to attach
		if (subShaderDef.length() > 0)
		{
			pGpuProgram->setParameter("attach", subShaderDef);
		}
	}
	
}
Example #17
0
void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_data) {



	if (p_msg=="debug_enter") {

		Array msg;
		msg.push_back("get_stack_dump");
		ppeer->put_var(msg);
		ERR_FAIL_COND(p_data.size()!=2);
		bool can_continue=p_data[0];
		String error = p_data[1];
		step->set_disabled(!can_continue);
		next->set_disabled(!can_continue);
		reason->set_text(error);
		reason->set_tooltip(error);
		breaked=true;
		dobreak->set_disabled(true);
		docontinue->set_disabled(false);
		emit_signal("breaked",true,can_continue);
		OS::get_singleton()->move_window_to_foreground();
		tabs->set_current_tab(0);

	} else if (p_msg=="debug_exit") {

		breaked=false;
		step->set_disabled(true);
		next->set_disabled(true);
		reason->set_text("");
		reason->set_tooltip("");
		back->set_disabled(true);
		forward->set_disabled(true);
		dobreak->set_disabled(false);
		docontinue->set_disabled(true);
		emit_signal("breaked",false,false);
		//tabs->set_current_tab(0);

	} else if (p_msg=="message:click_ctrl") {

		clicked_ctrl->set_text(p_data[0]);
		clicked_ctrl_type->set_text(p_data[1]);

	} else if (p_msg=="message:scene_tree") {

		scene_tree->clear();
		Map<int,TreeItem*> lv;

		for(int i=0;i<p_data.size();i+=3) {

			TreeItem *p;
			int level = p_data[i];
			if (level==0) {
				p = NULL;
			} else {
				ERR_CONTINUE(!lv.has(level-1));
				p=lv[level-1];
			}

			TreeItem *it = scene_tree->create_item(p);
			it->set_text(0,p_data[i+1]);
			if (has_icon(p_data[i+2],"EditorIcons"))
				it->set_icon(0,get_icon(p_data[i+2],"EditorIcons"));
			lv[level]=it;
		}

		le_clear->set_disabled(false);
		le_set->set_disabled(false);

	} else if (p_msg=="message:video_mem") {

		vmem_tree->clear();
		TreeItem* root=vmem_tree->create_item();

		int total=0;

		for(int i=0;i<p_data.size();i+=4) {

			TreeItem *it = vmem_tree->create_item(root);
			String type=p_data[i+1];
			int bytes=p_data[i+3].operator int();
			it->set_text(0,p_data[i+0]); //path
			it->set_text(1,type); //type
			it->set_text(2,p_data[i+2]); //type
			it->set_text(3,String::humanize_size(bytes)); //type
			total+=bytes;

			if (has_icon(type,"EditorIcons"))
				it->set_icon(0,get_icon(type,"EditorIcons"));
		}

		vmem_total->set_tooltip("Bytes: "+itos(total));
		vmem_total->set_text(String::humanize_size(total));

	} else if (p_msg=="stack_dump") {

		stack_dump->clear();
		TreeItem *r = stack_dump->create_item();

		for(int i=0;i<p_data.size();i++) {

			Dictionary d = p_data[i];
			ERR_CONTINUE(!d.has("function"));
			ERR_CONTINUE(!d.has("file"));
			ERR_CONTINUE(!d.has("line"));
			ERR_CONTINUE(!d.has("id"));
			TreeItem *s = stack_dump->create_item(r);
			d["frame"]=i;
			s->set_metadata(0,d);

//			String line = itos(i)+" - "+String(d["file"])+":"+itos(d["line"])+" - at func: "+d["function"];
			String line = itos(i)+" - "+String(d["file"])+":"+itos(d["line"]);
			s->set_text(0,line);

			if (i==0)
				s->select(0);
		}
	} else if (p_msg=="stack_frame_vars") {


		variables->clear();



		int ofs =0;
		int mcount = p_data[ofs];

		ofs++;
		for(int i=0;i<mcount;i++) {

			String n = p_data[ofs+i*2+0];
			Variant v = p_data[ofs+i*2+1];

			if (n.begins_with("*")) {

				n=n.substr(1,n.length());
			}

			variables->add_property("members/"+n,v);
		}
		ofs+=mcount*2;

		mcount = p_data[ofs];

		ofs++;
		for(int i=0;i<mcount;i++) {

			String n = p_data[ofs+i*2+0];
			Variant v = p_data[ofs+i*2+1];

			if (n.begins_with("*")) {

				n=n.substr(1,n.length());
			}


			variables->add_property("locals/"+n,v);
		}

		variables->update();
		inspector->edit(variables);

	} else if (p_msg=="output") {

		//OUT
		for(int i=0;i<p_data.size();i++) {

			String t = p_data[i];
			//LOG

			if (EditorNode::get_log()->is_hidden()) {
				log_forced_visible=true;
				EditorNode::get_log()->show();
			}
			EditorNode::get_log()->add_message(t);

		}

	} else if (p_msg=="performance") {
		Array arr = p_data[0];
		Vector<float> p;
		p.resize(arr.size());
		for(int i=0;i<arr.size();i++) {
			p[i]=arr[i];
			if (i<perf_items.size()) {
				perf_items[i]->set_text(1,rtos(p[i]));
				if (p[i]>perf_max[i])
					perf_max[i]=p[i];
			}

		}
		perf_history.push_front(p);
		perf_draw->update();

	} else if (p_msg=="error") {

		Array err = p_data[0];

		Array vals;
		vals.push_back(err[0]);
		vals.push_back(err[1]);
		vals.push_back(err[2]);
		vals.push_back(err[3]);

		bool warning = err[9];
		bool e;
		String time = String("%d:%02d:%02d:%04d").sprintf(vals,&e);
		String txt=time+" - "+String(err[8]);

		String tooltip="Type:"+String(warning?"Warning":"Error");
		tooltip+="\nDescription: "+String(err[8]);
		tooltip+="\nTime: "+time;
		tooltip+="\nC Error: "+String(err[7]);
		tooltip+="\nC Source: "+String(err[5])+":"+String(err[6]);
		tooltip+="\nC Function: "+String(err[4]);



		error_list->add_item(txt,EditorNode::get_singleton()->get_gui_base()->get_icon(warning?"Warning":"Error","EditorIcons"));
		error_list->set_item_tooltip( error_list->get_item_count() -1,tooltip );

		int scc = p_data[1];

		Array stack;
		stack.resize(scc);
		for(int i=0;i<scc;i++) {
			stack[i]=p_data[2+i];
		}

		error_list->set_item_metadata( error_list->get_item_count() -1,stack );

		error_count++;
		/*
		int count = p_data[1];

		Array cstack;

		OutputError oe = errors.front()->get();

		packet_peer_stream->put_var(oe.hr);
		packet_peer_stream->put_var(oe.min);
		packet_peer_stream->put_var(oe.sec);
		packet_peer_stream->put_var(oe.msec);
		packet_peer_stream->put_var(oe.source_func);
		packet_peer_stream->put_var(oe.source_file);
		packet_peer_stream->put_var(oe.source_line);
		packet_peer_stream->put_var(oe.error);
		packet_peer_stream->put_var(oe.error_descr);
		packet_peer_stream->put_var(oe.warning);
		packet_peer_stream->put_var(oe.callstack);
		*/
	} else if (p_msg=="kill_me") {

		editor->call_deferred("stop_child_process");
	}

}
Example #18
0
bool
SuifPrinterModule::parse_and_print(ostream& output, const ObjectWrapper &obj,
				   const LString &name, const String &str, 
				   int _indent, int deref = 0)
{
  const Address what = obj.get_address();
  const MetaClass *type = obj.get_meta_class();
  //  ObjectWrapper obj(what, type);
  //output << "str:deref = " << deref << endl;
  int l_sep = list_separator;
  if (str.length() == 0) {
    return false;
  }
  if (deref)
    _indent -= istep;
  int str_length = str.length();
  bool need_indent = false;
  bool first_field = true;
  for (int i = 0; i < str_length; ++i) {
    if (str[i] != '%') {
      // If there are less than 2 extra stars don't print anything but the
      // fields.
      if (deref < 2) {
	// Need to check for \n and take care of indentation here
	switch(str[i]) {
	case '\n':
	  output << str[i];
	  if (str[i+1]) {
	    need_indent = true;
	    indent(output, _indent);
	  }
	  break;
	case '\t': indent(output, istep); break;
	case '\b': _indent -= istep; break;
	default: output << str[i];
	}
      }
    }
    else {
      ++i;
      if (str[i] == '%') {
	// Double % means print out a '%'
	output << '%';
      }
      else {
	// This has to be cleaned up a bit ...
	//int field_deref = deref?deref-1:0;
	int field_deref = 0;
	char buff[256];
	int j = 0;
	char c = str[i++];
	if (c == '*') {
	  ++field_deref;
	  while ((c = str[i++]) == '*')
	    ++ field_deref;
	}
	while (isalnum(c) || c == '_') {
	  buff[j++] = c;
	  c = str[i++];
	}
	i -= 2;
	buff[j] = 0;
	// Now retrieve the particular field and print it.
	if (!strcmp(buff, "Cl")) {
	  output << type->get_instance_name() << '('
		 << type->get_meta_class_id() << ") ";
	}
	else if (!strcmp(buff, "ii")) { // Deal with printing IInteger
	  IInteger *ii = (IInteger *)what;
	  output << ii->to_String().c_str();
	}
	else if (!strcmp(buff, "i")) { // Deal with printing int
	  output << *(int*)what;
	}
	else if (!strcmp(buff, "f")) { // float
	  output << *(float*)what;
	}
	else if (!strcmp(buff, "d")) { // double
	  output << *(double*)what;
	}
	else if (!strcmp(buff, "c")) { // char
	  output << *(char*)what;
	}
	else if (!strcmp(buff, "b")) { // byte
	  output << (int)*(char*)what;
	}
	else if (!strcmp(buff, "B")) { // bool
	  output << *(bool*)what;
	}
	else if (!strcmp(buff, "ls")) { // Deal with printing LStrings
	  LString str = *(LString*) what;
	  output << str;
	}
	else if (!strcmp(buff, "s")) { // Deal with printing Strings
	  String str = *(String*) what;
	  output << str;
	}
	else if (!strcmp(buff, "n")) { // Deal with name of field
	  if (!deref)
	    output << name;
	}
	else if (!strcmp(buff, "P")) {
	  if (obj.is_null())
	    output << "NULL";
	  else {
	    PointerWrapper ptr_obj(obj);
	    ObjectWrapper base_obj = ptr_obj.dereference();
	    if (ptr_obj.get_meta_class()->is_owning_pointer()) {
	      size_t ref = retrieve_tag(obj.get_object());
	      output << "t" << ref<< ": ";
	      print2(output, base_obj, emptyLString, 
		     _indent+istep, field_deref);
	    }
	    else {
	      print_pointer(output, ptr_obj, emptyLString, _indent, deref);
	    }
	  }
	}
	else if (!strcmp(buff, "R")) { // print the ref #
	  if (!what)
	    output << "NULL";
	  else {
	    //  PointerMetaClass *p = (PointerMetaClass*) type;
	    //  const Address baseAddr = *(Address*) type;
	    //ObjectWrapper obj(what, type);
	    size_t ref = retrieve_tag(obj);
	    output << "t" << ref<< ": ";
	  }
	}
	else if (!strcmp(buff, "LS")) {
	  list_separator = ' ';
	}
	else if (!strcmp(buff, "LN")) {
	  list_separator = '\n';
	}
	else if (!strcmp(buff, "LC")) {
	  list_separator = ',';
	}
	else if (!strcmp(buff, "ANNOTES")) {
	  // Special CASE for handling ANNOTATIONS
	  AggregateWrapper agg(obj);
	  LString field_name("_annotes");
	  FieldDescription *f = agg.get_field_description(field_name);
	  if (!f)
	    cerr << type->get_meta_class(what)->get_class_name()
		 << ":No field '" << field_name << "' found to print!!!\n";
	  else {
	    // Now we need to get the field offset and increment 'what'
	    if (field_deref != 0)
	      cerr << "Extra '*' for %ANNOTES\n";
	    FieldWrapper field = agg.get_field(field_name);
	    if (need_indent) {
	      indent(output, istep);
	      need_indent = false;
	    }
	    char old_sep = list_separator;
	    list_separator = '\n';
	    print2(output, 
		   field.get_object(),
		   field_name, _indent+istep,
		   1);
	    list_separator = old_sep;
	  }
	}
	else if (j) {
	  // Retrieve the field mentioned
	  // The following cast works as we should reach here only if it
	  // is not an elementary or pointer type.
	  AggregateWrapper agg(obj);
	  char *bf = buff;
	  LString field_name(bf);
	  FieldDescription *f = agg.get_field_description(field_name);
	  if (!f)
	    cerr << type->get_meta_class(what)->get_class_name()
		 << ":No field '" << field_name << "' found to print!!!\n";
	  else {
	    // Now we need to get the field offset and increment 'what'
	    if (deref)
	      if (!first_field) output << ' ';
	      else first_field = false;
	    FieldWrapper field = agg.get_field(field_name);
	    //char *f_add = (char*)what + f->get_offset();
	    //indent(output, _indent+istep);
	    if (need_indent) {
	      indent(output, istep);
	      need_indent = false;
	    }
	    if (deref && !field_deref)
	      field_deref = deref - 1;
	    //output << "\tstr:field_deref = " << field_deref << endl;
	    print2(output, 
		   field.get_object(),
		   field_name, _indent+istep,
		   field_deref);
	  }
	}
      }
    }
  }
  list_separator = l_sep;
  return true;
}
Example #19
0
void XMLHttpRequest::send(const String& body, ExceptionCode& ec)
{
    if (!initSend(ec))
        return;

    if (!body.isNull() && m_method != "GET" && m_method != "HEAD" && m_url.protocolInHTTPFamily()) {
        String contentType = getRequestHeader("Content-Type");
        if (contentType.isEmpty()) {
#if ENABLE(DASHBOARD_SUPPORT)
            if (usesDashboardBackwardCompatibilityMode())
                setRequestHeaderInternal("Content-Type", "application/x-www-form-urlencoded");
            else
#endif
                setRequestHeaderInternal("Content-Type", "application/xml");
        } else {
            replaceCharsetInMediaType(contentType, "UTF-8");
            m_requestHeaders.set("Content-Type", contentType);
        }

        m_requestEntityBody = FormData::create(UTF8Encoding().encode(body.characters(), body.length(), EntitiesForUnencodables));
        if (m_upload)
            m_requestEntityBody->setAlwaysStream(true);
    }

    createRequest(ec);
}
Example #20
0
void AppPushServer::handle_http_post( const HttpServer::Request & request , HttpServer::Response & response )
{
    response.set_status( HttpServer::HTTP_STATUS_BAD_REQUEST );

    //.........................................................................
    // If the path is /push, they are initiating a push. Otherwise, they are
    // pushing a file.

    String path = request.get_path();

    if ( path != "/push" )
    {
        if ( ! current_push_path )
        {
            return;
        }

        if ( path != String( current_push_path ) )
        {
            return;
        }

        handle_push_file( request , response );

        return;
    }


    //.........................................................................
    // Check the content type

    if ( request.get_content_type() != "application/json" )
    {
        return;
    }

    //.........................................................................
    // Get the body of the request

    const HttpServer::Request::Body & body( request.get_body() );

    if ( 0 == body.get_length() || 0 == body.get_data() )
    {
        return;
    }

    FreeLater free_later;

    //.........................................................................
    // Parse the body

    String app_contents;

    FileInfo::List file_list;

#if 1

    using namespace JSON;

    Object root = Parser::parse( body.get_data() , body.get_length() ).as<Object>();

    app_contents = root[ "app" ].as<String>();

    if ( app_contents.empty() )
    {
        return;
    }

    Array files = root[ "files" ].as<Array>();

    if ( files.empty() )
    {
        return;
    }

    for ( Array::Vector::iterator it = files.begin(); it != files.end(); ++it )
    {
        Array & parts = it->as<Array>();

        if ( parts.size() < 3 )
        {
            return;
        }

        FileInfo info;

        info.name = parts[ 0 ].as<String>();
        info.md5 = parts[ 1 ].as<String>();
        info.size = parts[ 2 ].as<long long>();

        if ( info.name.empty() || info.md5.empty() )
        {
            return;
        }

        file_list.push_back( info );
    }

#else

    JsonParser * parser = json_parser_new();

    if ( ! parser )
    {
        return;
    }

    free_later( parser , g_object_unref );

    if ( ! json_parser_load_from_data( parser , body.get_data() , body.get_length() , 0 ) )
    {
        return;
    }

    JsonNode * root = json_parser_get_root( parser );

    if ( ! root )
    {
        return;
    }

    if ( JSON_NODE_TYPE( root ) != JSON_NODE_OBJECT )
    {
        return;
    }

    JsonObject * object = json_node_get_object( root );

    if ( ! object )
    {
        return;
    }

    // The root node should be an object that has a member called 'app'
    // which is a string and has the contents of the app file.
    // It should also have an array member called 'files'. This is an
    // array of 3 element arrays. Each one has the file name, the md5
    // hash of the file and the size of the file.

    JsonNode * app = json_object_get_member( object , "app" );
    JsonNode * files = json_object_get_member( object , "files" );

    if ( ! app || ! files )
    {
        return;
    }

    if ( JSON_NODE_TYPE( app ) != JSON_NODE_VALUE || JSON_NODE_TYPE( files ) != JSON_NODE_ARRAY )
    {
        return;
    }

    app_contents = json_node_get_string( app );

    JsonArray * files_array = json_node_get_array( files );

    if ( ! files_array )
    {
        return;
    }

    for( guint i = 0; i < json_array_get_length( files_array ); ++i )
    {
        JsonNode * element = json_array_get_element( files_array , i );

        if ( element && JSON_NODE_TYPE( element ) == JSON_NODE_ARRAY )
        {
            if ( JsonArray * file_parts = json_node_get_array( element ) )
            {
                if ( json_array_get_length( file_parts ) >= 3 )
                {
                    JsonNode * file_name_node = json_array_get_element( file_parts , 0 );
                    JsonNode * hash_node = json_array_get_element( file_parts , 1 );
                    JsonNode * size_node = json_array_get_element( file_parts , 2 );

                    if ( JSON_NODE_TYPE( file_name_node ) == JSON_NODE_VALUE &&
                            JSON_NODE_TYPE( hash_node ) == JSON_NODE_VALUE &&
                            JSON_NODE_TYPE( size_node ) == JSON_NODE_VALUE )
                    {
                        FileInfo info;

                        info.name = json_node_get_string( file_name_node );
                        info.md5 = json_node_get_string( hash_node );
                        info.size = json_node_get_int( size_node );

                        file_list.push_back( info );
                    }
                }
            }
        }
    }

#endif

    if ( file_list.empty() )
    {
        return;
    }

    //.........................................................................
    // Now we have app_contents and file_list

    try
    {
        PushInfo push_info = compare_files( app_contents , file_list );

        push_info.debug = root[ "debug" ].is<bool>() ? root[ "debug" ].as<bool>() : false;

        // Stop any other push that is going on

        if ( current_push_path )
        {
            g_free( current_push_path );

            current_push_path = 0;
        }

        if ( push_info.target_files.empty() )
        {
            // The app is up to date, we can just launch it

            current_push_info = push_info;

            bool ok = launch_it();

            set_response( response , true , ! ok , "Nothing changed." );
        }
        else
        {
            // Make a new push path

            GTimeVal t;

            g_get_current_time( & t );

            String s = Util::format( "%ld:%ld:%s" , t.tv_sec , t.tv_usec , push_info.metadata.id.c_str() );

            GChecksum * ck = g_checksum_new( G_CHECKSUM_MD5 );

            g_checksum_update( ck , ( const guchar * ) s.c_str() , s.length() );

            current_push_path = g_strdup_printf( "/push/%s" , g_checksum_get_string( ck ) );

            g_checksum_free( ck );

            current_push_info = push_info;

            set_response( response , false , false , "" , push_info.target_files.front().source.name , current_push_path );
        }
    }
    catch( const String & e )
    {
        set_response( response , true , true , e );
    }
}
Example #21
0
	static String FormatStopwatch(int64 us, const String& format)
	{
		String result, keyPattern;

		if (us < 0)
		{
			result.push_back(L'-');

			us = -us;
		}

		bool inQuot = false;

		wchar previousChar = L'\0';

		for (size_t i = 0; i < format.length(); ++i)
		{
			const wchar ch = format[i];

			if (IsAlpha(ch))
			{
				if (inQuot)
				{
					result.push_back(ch);
				}
				else
				{
					if (keyPattern.isEmpty() || ch == previousChar)
					{
						keyPattern.push_back(ch);
					}
					else
					{
						result.append(GetFormattedElement(us, keyPattern));
						keyPattern.clear();
						keyPattern.push_back(ch);
					}
				}
			}
			else
			{
				if (!keyPattern.isEmpty())
				{
					result.append(GetFormattedElement(us, keyPattern));
					keyPattern.clear();
				}

				if (ch == L'\'')
				{
					if (format[i + 1] == L'\'')
					{
						result.push_back(L'\'');

						++i;

						continue;
					}

					inQuot = !inQuot;
				}
				else
				{
					result.push_back(ch);
				}
			}

			previousChar = ch;
		}

		if (!keyPattern.isEmpty())
		{
			result.append(GetFormattedElement(us, keyPattern));
		}

		return result;
	}
Example #22
0
RES TranslationLoaderPO::load(const String &p_path, const String& p_original_path, Error *r_error) {

	if (r_error)
		*r_error=ERR_CANT_OPEN;

	FileAccess *f=FileAccess::open(p_path,FileAccess::READ);
	ERR_FAIL_COND_V(!f,RES());

	String l = f->get_line();

	enum Status {

		STATUS_NONE,
		STATUS_READING_ID,
		STATUS_READING_STRING,
	};

	Status status=STATUS_NONE;

	String msg_id;
	String msg_str;
	String config;
	if (r_error)
		*r_error=ERR_FILE_CORRUPT;

	Ref<Translation> translation = Ref<Translation>( memnew( Translation ));
	int line = 1;

	while(true) {

		String l = f->get_line();

		if (f->eof_reached()) {

			if ( status == STATUS_READING_STRING) {

				if (msg_id!="")
					translation->add_message(msg_id,msg_str);
				else if (config=="")
					config=msg_str;
				break;

			} else if ( status==STATUS_NONE)
				break;

			memdelete(f);
			ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: ");
			ERR_FAIL_V(RES());
		}

		l=l.strip_edges();

		if (l.begins_with("msgid")) {

			if (status==STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+" nexpected 'msgid', was expecting 'msgstr' while parsing: ");
				ERR_FAIL_V(RES());
			}

			if (msg_id!="")
				translation->add_message(msg_id,msg_str);
			else if (config=="")
				config=msg_str;

			l=l.substr(5,l.length()).strip_edges();
			status=STATUS_READING_ID;
			msg_id="";
			msg_str="";
		}

		if (l.begins_with("msgstr")) {

			if (status!=STATUS_READING_ID) {

				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
				ERR_FAIL_V(RES());
			}

			l=l.substr(6,l.length()).strip_edges();
			status=STATUS_READING_STRING;
		}

		if (l=="" || l.begins_with("#")) {
			line++;
			continue; //nothing to read or comment
		}

		if (!l.begins_with("\"") || status==STATUS_NONE) {
			//not a string? failure!
			ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: ");
			ERR_FAIL_V(RES());

		}

		l=l.substr(1,l.length());
		//find final quote
		int end_pos=-1;
		for(int i=0;i<l.length();i++) {

			if (l[i]=='"' && (i==0 || l[i-1]!='\\')) {
				end_pos=i;
				break;
			}
		}

		if (end_pos==-1) {
			ERR_EXPLAIN(p_path+":"+itos(line)+" Expected '\"' at end of message while parsing file: ");
			ERR_FAIL_V(RES());
		}

		l=l.substr(0,end_pos);
		l=l.c_unescape();


		if (status==STATUS_READING_ID)
			msg_id+=l;
		else
			msg_str+=l;

		line++;
	}


	f->close();
	memdelete(f);

	if (config=="") {
		ERR_EXPLAIN("No config found in file: "+p_path);
		ERR_FAIL_V(RES());
	}

	Vector<String> configs = config.split("\n");
	for(int i=0;i<configs.size();i++) {

		String c = configs[i].strip_edges();
		int p = c.find(":");
		if (p==-1)
			continue;
		String prop = c.substr(0,p).strip_edges();
		String value = c.substr(p+1,c.length()).strip_edges();

		if (prop=="X-Language") {
			translation->set_locale(value);
		}
	}

	if (r_error)
		*r_error=OK;

	return translation;

}
 String BrazilianStemmer::removeSuffix(const String& value, const String& toRemove)
 {
     if (value.empty() || toRemove.empty() || !checkSuffix(value, toRemove))
         return value;
     return value.substr(0, value.length() - toRemove.length());
 }
Example #24
0
public String strStr(String haystack, String needle) {
    if(haystack==null || needle==null) return null;
    if(haystack.length()==0){
        return needle.length()==0?"":null;
    }
    if(needle.length()==0) return haystack;
    if(haystack.length()<needle.length()) return null;

 int base = 29;
 long patternHash = 0;
    long tempBase = 1;

    for(int i=needle.length()-1; i>=0; i--){
     patternHash += (int)needle.charAt(i)*tempBase;
     tempBase *= base;
    }

    long hayHash = 0;
    tempBase = 1;
    for(int i=needle.length()-1; i>=0; i--){
     hayHash += (int)haystack.charAt(i)*tempBase;
     tempBase *= base;
    }
    tempBase /= base;

    if(hayHash == patternHash){
     return haystack;
    }

    for(int i=needle.length(); i<haystack.length(); i++){
     hayHash = (hayHash - (int)haystack.charAt(i-needle.length())*tempBase)*base+(int)haystack.charAt(i);
        if(hayHash == patternHash){
      return haystack.substring(i-needle.length()+1);
     }
    }
    return null;
} 
Example #25
0
MainLoop *test(TestType p_type) {

	List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();

	if (cmdlargs.empty()) {
		//try editor!
		return NULL;
	}

	String test = cmdlargs.back()->get();

	FileAccess *fa = FileAccess::open(test, FileAccess::READ);

	if (!fa) {
		ERR_EXPLAIN("Could not open file: " + test);
		ERR_FAIL_V(NULL);
	}

	Vector<uint8_t> buf;
	int flen = fa->get_len();
	buf.resize(fa->get_len() + 1);
	fa->get_buffer(&buf[0], flen);
	buf[flen] = 0;

	String code;
	code.parse_utf8((const char *)&buf[0]);

	Vector<String> lines;
	int last = 0;

	for (int i = 0; i <= code.length(); i++) {

		if (code[i] == '\n' || code[i] == 0) {

			lines.push_back(code.substr(last, i - last));
			last = i + 1;
		}
	}

	if (p_type == TEST_TOKENIZER) {

		GDScriptTokenizerText tk;
		tk.set_code(code);
		int line = -1;
		while (tk.get_token() != GDScriptTokenizer::TK_EOF) {

			String text;
			if (tk.get_token() == GDScriptTokenizer::TK_IDENTIFIER)
				text = "'" + tk.get_token_identifier() + "' (identifier)";
			else if (tk.get_token() == GDScriptTokenizer::TK_CONSTANT) {
				Variant c = tk.get_token_constant();
				if (c.get_type() == Variant::STRING)
					text = "\"" + String(c) + "\"";
				else
					text = c;

				text = text + " (" + Variant::get_type_name(c.get_type()) + " constant)";
			} else if (tk.get_token() == GDScriptTokenizer::TK_ERROR)
				text = "ERROR: " + tk.get_token_error();
			else if (tk.get_token() == GDScriptTokenizer::TK_NEWLINE)
				text = "newline (" + itos(tk.get_token_line()) + ") + indent: " + itos(tk.get_token_line_indent());
			else if (tk.get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC)
				text = "'" + String(GDScriptFunctions::get_func_name(tk.get_token_built_in_func())) + "' (built-in function)";
			else
				text = tk.get_token_name(tk.get_token());

			if (tk.get_token_line() != line) {
				int from = line + 1;
				line = tk.get_token_line();

				for (int i = from; i <= line; i++) {
					int l = i - 1;
					if (l >= 0 && l < lines.size()) {
						print_line("\n" + itos(i) + ": " + lines[l] + "\n");
					}
				}
			}
			print_line("\t(" + itos(tk.get_token_column()) + "): " + text);
			tk.advance();
		}
	}

	if (p_type == TEST_PARSER) {

		GDScriptParser parser;
		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
			memdelete(fa);
			return NULL;
		}

		const GDScriptParser::Node *root = parser.get_parse_tree();
		ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, NULL);
		const GDScriptParser::ClassNode *cnode = static_cast<const GDScriptParser::ClassNode *>(root);

		_parser_show_class(cnode, 0, lines);
	}

	if (p_type == TEST_COMPILER) {

		GDScriptParser parser;

		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
			memdelete(fa);
			return NULL;
		}

		GDScript *script = memnew(GDScript);

		GDScriptCompiler gdc;
		err = gdc.compile(&parser, script);
		if (err) {

			print_line("Compile Error:\n" + itos(gdc.get_error_line()) + ":" + itos(gdc.get_error_column()) + ":" + gdc.get_error());
			memdelete(script);
			return NULL;
		}

		Ref<GDScript> gds = Ref<GDScript>(script);

		Ref<GDScript> current = gds;

		while (current.is_valid()) {

			print_line("** CLASS **");
			_disassemble_class(current, lines);

			current = current->get_base();
		}

	} else if (p_type == TEST_BYTECODE) {

		Vector<uint8_t> buf = GDScriptTokenizerBuffer::parse_code_string(code);
		String dst = test.get_basename() + ".gdc";
		FileAccess *fw = FileAccess::open(dst, FileAccess::WRITE);
		fw->store_buffer(buf.ptr(), buf.size());
		memdelete(fw);
	}

	memdelete(fa);

	return NULL;
}
Example #26
0
// send headers out over the given socket
// "reconnect" flag gives permission to reconnect to the socket on write error
// - this allows us to re-open the proxy connection on pconns if squid's end has
// timed out but the client's end hasn't. not much use with NTLM, since squid
// will throw a 407 and restart negotiation, but works well with basic & others.
void HTTPHeader::out(Socket * peersock, Socket * sock, int sendflag, bool reconnect) throw(std::exception)
{
	String l;  // for amalgamating to avoid conflict with the Nagel algorithm

	if (sendflag == __DGHEADER_SENDALL || sendflag == __DGHEADER_SENDFIRSTLINE) {
		if (header.size() > 0) {
			l = header.front() + "\n";
#ifdef DGDEBUG
			std::cout << "headertoclient:" << l << std::endl;
#endif
			// first reconnect loop - send first line
			while (true) {
				if (!(*sock).writeToSocket(l.toCharArray(), l.length(), 0, timeout)) {
					// reconnect & try again if we've been told to
					if (reconnect) {
						// don't try more than once
#ifdef DGDEBUG
						std::cout << "Proxy connection broken (1); trying to re-establish..." << std::endl;
						syslog(LOG_ERR,"Proxy connection broken (1); trying to re-establish...");
#endif
						reconnect = false;
						sock->reset();
						int rc = sock->connect(o.proxy_ip, o.proxy_port);
						if (rc)
							throw std::exception();
						continue;
					}
					throw std::exception();
				}
				// if we got here, we succeeded, so break the reconnect loop
				break;
			}
		}
		if (sendflag == __DGHEADER_SENDFIRSTLINE) {
			return;
		}
	}

	l = "";

	for (std::deque<String>::iterator i = header.begin() + 1; i != header.end(); i++) {
		l += (*i) + "\n";
	}
	l += "\r\n";

#ifdef DGDEBUG
	std::cout << "headertoclient:" << l << std::endl;
#endif

	// second reconnect loop
	while (true) {
		// send header to the output stream
		// need exception for bad write

		if (!(*sock).writeToSocket(l.toCharArray(), l.length(), 0, timeout)) {
			// reconnect & try again if we've been told to
			if (reconnect) {
				// don't try more than once
#ifdef DGDEBUG
				std::cout << "Proxy connection broken (2); trying to re-establish..." << std::endl;
				syslog(LOG_ERR,"Proxy connection broken (2); trying to re-establish...");
#endif
				reconnect = false;
				sock->reset();
				int rc = sock->connect(o.proxy_ip, o.proxy_port);
				if (rc)
					throw std::exception();
				// include the first line on the retry
				l = header.front() + "\n" + l;
				continue;
			}
			throw std::exception();
		}
		// if we got here, we succeeded, so break the reconnect loop
		break;
	}

	if ((!requestType().startsWith("HTTP")) && (pcontentlength != NULL)) {
		if (postdatalen > 0) {
#ifdef DGDEBUG
			std::cout << "Sending initial POST data chunk" << std::endl;
#endif
			// Re-add the chopped off \n, if necessary
			if (postdatachopped) {
#ifdef DGDEBUG
				std::cout << "Re-adding newline to POST data (postdatalen " << postdatalen << ")" << std::endl;
#endif
				postdata[postdatalen-1] = '\n';
				postdata[postdatalen] = '\0';
			}
			sock->writeToSockete(postdata, postdatalen, 0, timeout);
		}
#ifdef DGDEBUG
		std::cout << "Opening tunnel for remainder of POST data" << std::endl;
#endif
		FDTunnel fdt;
		off_t remaining = contentLength() - postdatalen;
		if (remaining < 0)
			throw std::runtime_error("No POST data left to send!?");
		fdt.tunnel(*peersock, *sock, false, remaining, true);
	}
}
Example #27
0
void ESP8266WebServer::_parseArguments(String data) {
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("args: ");
  DEBUG_OUTPUT.println(data);
#endif
  if (_currentArgs)
    delete[] _currentArgs;
  _currentArgs = 0;
  if (data.length() == 0) {
    _currentArgCount = 0;
    _currentArgs = new RequestArgument[1];
    return;
  }
  _currentArgCount = 1;

  for (int i = 0; i < (int)data.length(); ) {
    i = data.indexOf('&', i);
    if (i == -1)
      break;
    ++i;
    ++_currentArgCount;
  }
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("args count: ");
  DEBUG_OUTPUT.println(_currentArgCount);
#endif

  _currentArgs = new RequestArgument[_currentArgCount+1];
  int pos = 0;
  int iarg;
  for (iarg = 0; iarg < _currentArgCount;) {
    int equal_sign_index = data.indexOf('=', pos);
    int next_arg_index = data.indexOf('&', pos);
#ifdef DEBUG_ESP_HTTP_SERVER
    DEBUG_OUTPUT.print("pos ");
    DEBUG_OUTPUT.print(pos);
    DEBUG_OUTPUT.print("=@ ");
    DEBUG_OUTPUT.print(equal_sign_index);
    DEBUG_OUTPUT.print(" &@ ");
    DEBUG_OUTPUT.println(next_arg_index);
#endif
    if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) {
#ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print("arg missing value: ");
      DEBUG_OUTPUT.println(iarg);
#endif
      if (next_arg_index == -1)
        break;
      pos = next_arg_index + 1;
      continue;
    }
    RequestArgument& arg = _currentArgs[iarg];
    arg.key = data.substring(pos, equal_sign_index);
    arg.value = urlDecode(data.substring(equal_sign_index + 1, next_arg_index));
#ifdef DEBUG_ESP_HTTP_SERVER
    DEBUG_OUTPUT.print("arg ");
    DEBUG_OUTPUT.print(iarg);
    DEBUG_OUTPUT.print(" key: ");
    DEBUG_OUTPUT.print(arg.key);
    DEBUG_OUTPUT.print(" value: ");
    DEBUG_OUTPUT.println(arg.value);
#endif
    ++iarg;
    if (next_arg_index == -1)
      break;
    pos = next_arg_index + 1;
  }
  _currentArgCount = iarg;
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("args count: ");
  DEBUG_OUTPUT.println(_currentArgCount);
#endif

}
Example #28
0
// Does a regexp search and replace.
// urlRegExp Code originally from from Ton Gorter 2004
bool HTTPHeader::regExp(String& line, std::deque<RegExp>& regexp_list, std::deque<String>& replacement_list) {
	RegExp *re;
	String replacement;
	String repstr;
	String newLine;
	bool linemodified = false;
	unsigned int i;
	unsigned int j, k;
	unsigned int s = regexp_list.size();
	unsigned int matches, submatches;
	unsigned int match;
	unsigned int srcoff;
	unsigned int nextoffset;
	unsigned int matchlen;
	unsigned int oldlinelen;

	// iterate over our list of precompiled regexes
	for (i = 0; i < s; i++) {
		newLine = "";
		re = &(regexp_list[i]);
		if (re->match(line.toCharArray())) {
			repstr = replacement_list[i];
			matches = re->numberOfMatches();

			srcoff = 0;

			for (j = 0; j < matches; j++) {
				nextoffset = re->offset(j);
				matchlen = re->length(j);
				
				// copy next chunk of unmodified data
				if (nextoffset > srcoff) {
					newLine += line.subString(srcoff, nextoffset - srcoff);
					srcoff = nextoffset;
				}

				// Count number of submatches (brackets) in replacement string
				for (submatches = 0; j+submatches+1 < matches; submatches++)
					if (re->offset(j+submatches+1) + re->length(j+submatches+1) > srcoff + matchlen)
						break;

				// \1 and $1 replacement
				replacement = "";
				for (k = 0; k < repstr.length(); k++) {
					// find \1..\9 and $1..$9 and fill them in with submatched strings
					if ((repstr[k] == '\\' || repstr[k] == '$') && repstr[k+1] >= '1' && repstr[k+1] <= '9') {
						match = repstr[++k] - '0';
						if (match <= submatches) {
							replacement += re->result(j + match).c_str();
						}
					} else {
						// unescape \\ and \$, and add non-backreference characters to string
						if (repstr[k] == '\\' && (repstr[k+1] == '\\' || repstr[k+1] == '$'))
							k++;
						replacement += repstr.subString(k, 1);
					}
				}
				
				// copy filled in replacement string
				newLine += replacement;
				srcoff += matchlen;
				j += submatches;
			}
			oldlinelen = line.length();
			if (srcoff < oldlinelen) {
				newLine += line.subString(srcoff, oldlinelen - srcoff);
			}
#ifdef DGDEBUG
			std::cout << "Line modified! (" << line << " -> " << newLine << ")" << std::endl;
#endif
			// copy newLine into line and continue with other regexes
			line = newLine;
			linemodified = true;
		}
	}
	
	return linemodified;
}
Example #29
0
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');
  //reset header value
  for (int i = 0; i < _headerKeysCount; ++i) {
    _currentHeaders[i].value =String();
   }

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG_ESP_HTTP_SERVER
    DEBUG_OUTPUT.print("Invalid request: ");
    DEBUG_OUTPUT.println(req);
#endif
    return false;
  }

  String methodStr = req.substring(0, addr_start);
  String url = req.substring(addr_start + 1, addr_end);
  String versionEnd = req.substring(addr_end + 8);
  _currentVersion = atoi(versionEnd.c_str());
  String searchStr = "";
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = url.substring(hasSearch + 1);
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  _chunked = false;

  HTTPMethod method = HTTP_GET;
  if (methodStr == "POST") {
    method = HTTP_POST;
  } else if (methodStr == "DELETE") {
    method = HTTP_DELETE;
  } else if (methodStr == "OPTIONS") {
    method = HTTP_OPTIONS;
  } else if (methodStr == "PUT") {
    method = HTTP_PUT;
  } else if (methodStr == "PATCH") {
    method = HTTP_PATCH;
  }
  _currentMethod = method;

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("method: ");
  DEBUG_OUTPUT.print(methodStr);
  DEBUG_OUTPUT.print(" url: ");
  DEBUG_OUTPUT.print(url);
  DEBUG_OUTPUT.print(" search: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  //attach handler
  RequestHandler* handler;
  for (handler = _firstHandler; handler; handler = handler->next()) {
    if (handler->canHandle(_currentMethod, _currentUri))
      break;
  }
  _currentHandler = handler;

  String formData;
  // below is needed only when POST type request
  if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
    String boundaryStr;
    String headerName;
    String headerValue;
    bool isForm = false;
    bool isEncoded = false;
    uint32_t contentLength = 0;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 1);
      headerValue.trim();
       _collectHeader(headerName.c_str(),headerValue.c_str());

      #ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print("headerName: ");
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print("headerValue: ");
      DEBUG_OUTPUT.println(headerValue);
      #endif

      if (headerName.equalsIgnoreCase("Content-Type")){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("application/x-www-form-urlencoded")){
          isForm = false;
          isEncoded = true;
        } else if (headerValue.startsWith("multipart/")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName.equalsIgnoreCase("Content-Length")){
        contentLength = headerValue.toInt();
      } else if (headerName.equalsIgnoreCase("Host")){
        _hostHeader = headerValue;
      }
    }

    if (!isForm){
      size_t plainLength;
      char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT);
      if (plainLength < contentLength) {
      	free(plainBuf);
      	return false;
      }
      if (contentLength > 0) {
        if (searchStr != "") searchStr += '&';
        if(isEncoded){
          //url encoded form
          String decoded = urlDecode(plainBuf);
          size_t decodedLen = decoded.length();
          memcpy(plainBuf, decoded.c_str(), decodedLen);
          plainBuf[decodedLen] = 0;
          searchStr += plainBuf;
        }
        _parseArguments(searchStr);
        if(!isEncoded){
          //plain post json or other data
          RequestArgument& arg = _currentArgs[_currentArgCount++];
          arg.key = "plain";
          arg.value = String(plainBuf);
        }

  #ifdef DEBUG_ESP_HTTP_SERVER
        DEBUG_OUTPUT.print("Plain: ");
        DEBUG_OUTPUT.println(plainBuf);
  #endif
        free(plainBuf);
      }
    }

    if (isForm){
      _parseArguments(searchStr);
      if (!_parseForm(client, boundaryStr, contentLength)) {
        return false;
      }
    }
  } else {
    String headerName;
    String headerValue;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      _collectHeader(headerName.c_str(),headerValue.c_str());

	  #ifdef DEBUG_ESP_HTTP_SERVER
	  DEBUG_OUTPUT.print("headerName: ");
	  DEBUG_OUTPUT.println(headerName);
	  DEBUG_OUTPUT.print("headerValue: ");
	  DEBUG_OUTPUT.println(headerValue);
	  #endif

	  if (headerName.equalsIgnoreCase("Host")){
        _hostHeader = headerValue;
      }
    }
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Request: ");
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(" Arguments: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  return true;
}
Example #30
0
EError CRegExp::setStructs(SRegInfo *&re, const String &expr, int &retPos)
{
SRegInfo *next, *temp;

  retPos = 0;
  if (!expr.length()) return EOK;
  retPos = -1;

  next = re;
  for(int i = 0; i < expr.length(); i++){
    // simple character
    if (extend && Character::isWhitespace(expr[i])) continue;
    // context return
    if (expr[i] == ')'){
      retPos = i;
      break;
    };
    // next element
    if (i != 0){
      next->next = new SRegInfo;
      next->next->parent = next->parent;
      next->next->prev = next;
      next = next->next;
    };
    // Escape symbol
    if (expr[i] == '\\'){
      String *br_name;
      int blen;
      switch (expr[i+1]){
        case 'd':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReDigit;
          break;
        case 'D':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReNDigit;
          break;
        case 'w':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReWordSymb;
          break;
        case 'W':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReNWordSymb;
          break;
        case 's':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReWSpace;
          break;
        case 'S':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReNWSpace;
          break;
        case 'u':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReUCase;
          break;
        case 'l':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReNUCase;
          break;
        case 't':
          next->op = ReSymb;
          next->un.symbol = '\t';
          break;
        case 'n':
          next->op = ReSymb;
          next->un.symbol = '\n';
          break;
        case 'r':
          next->op = ReSymb;
          next->un.symbol = '\r';
          break;
        case 'b':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReWBound;
          break;
        case 'B':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReNWBound;
          break;
        case 'c':
          next->op = ReMetaSymb;
          next->un.metaSymbol = RePreNW;
          break;
#ifdef COLORERMODE
        case 'm':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReStart;
          break;
        case 'M':
          next->op = ReMetaSymb;
          next->un.metaSymbol = ReEnd;
          break;
#ifndef NAMED_MATCHES_IN_HASH
        case 'y':
        case 'Y':
          next->op = (expr[i+1] =='y'?ReBkTrace:ReBkTraceN);
          next->param0 = UnicodeTools::getHex(expr[i+2]);
          if (next->param0 != -1){
            i++;
          }else{
            next->op = (expr[i+1] =='y'?ReBkTraceName:ReBkTraceNName);
            br_name = UnicodeTools::getCurlyContent(expr, i+2);
            if (br_name == null) return ESYNTAX;
            if (!backRE){
              delete br_name;
              return EERROR;
            }
            next->param0 = backRE->getBracketNo(br_name);
            blen = br_name->length();
            delete br_name;
            if (next->param0 == -1) return ESYNTAX;
            i += blen+2;
          };
          break;
#endif // COLORERMODE
#endif // NAMED_MATCHES_IN_HASH

        case 'p':  // \p{name}
          next->op = ReBkBrackName;
          br_name = UnicodeTools::getCurlyContent(expr, i+2);
          if (br_name == null) return ESYNTAX;
          blen = br_name->length();
#ifndef NAMED_MATCHES_IN_HASH
          next->param0 = getBracketNo(br_name);
          delete br_name;
          if (next->param0 == -1) return ESYNTAX;
#else
          if(br_name->length() && namedMatches && !namedMatches->getItem(br_name)){
            delete br_name;
            return EBRACKETS;
          };
          next->param0 = 0;
          next->namedata = new SString(br_name);
          delete br_name;
#endif
          i += blen+2;
          break;
        default:
          next->op = ReBkBrack;
          next->param0 = UnicodeTools::getHex(expr[i+1]);
          if (next->param0 < 0 || next->param0 > 9){
            int retEnd;
            next->op = ReSymb;
            next->un.symbol = UnicodeTools::getEscapedChar(expr, i, retEnd);
            if (next->un.symbol == BAD_WCHAR) return ESYNTAX;
            i = retEnd-1;
          };
          break;
      };
      i++;
      continue;
    };

    if (expr[i] == '.'){
      next->op = ReMetaSymb;
      next->un.metaSymbol = ReAnyChr;
      continue;
    };
    if (expr[i] == '^'){
      next->op = ReMetaSymb;
      next->un.metaSymbol = ReSoL;
      continue;
    };
    if (expr[i] == '$'){
      next->op = ReMetaSymb;
      next->un.metaSymbol = ReEoL;
      continue;
    };
#ifdef COLORERMODE
    if (expr[i] == '~'){
      next->op = ReMetaSymb;
      next->un.metaSymbol = ReSoScheme;
      continue;
    };
#endif

    next->un.param = 0;
    next->param0 = 0;

    if (expr.length() > i+2){
      if (expr[i] == '?' && expr[i+1] == '#' &&
          expr[i+2] >= '0' && expr[i+2] <= '9'){
        next->op = ReBehind;
        next->param0 = UnicodeTools::getHex(expr[i+2]);
        i += 2;
        continue;
      };
      if (expr[i] == '?' && expr[i+1] == '~' &&
          expr[i+2]>='0' && expr[i+2]<='9'){
        next->op = ReNBehind;
        next->param0 = UnicodeTools::getHex(expr[i+2]);
        i += 2;
        continue;
      };
    };
    if (expr.length() > i+1){
      if (expr[i] == '*' && expr[i+1] == '?'){
        next->op = ReNGRangeN;
        next->s = 0;
        i++;
        continue;
      };
      if (expr[i] == '+' && expr[i+1] == '?'){
        next->op = ReNGRangeN;
        next->s = 1;
        i++;
        continue;
      };
      if (expr[i] == '?' && expr[i+1] == '='){
        next->op = ReAhead;
        i++;
        continue;
      };
      if (expr[i] == '?' && expr[i+1] == '!'){
        next->op = ReNAhead;
        i++;
        continue;
      };
      if (expr[i] == '?' && expr[i+1] == '?'){
        next->op = ReNGRangeNM;
        next->s = 0;
        next->e = 1;
        i++;
        continue;
      };
    };

    if (expr[i] == '*'){
      next->op = ReRangeN;
      next->s = 0;
      continue;
    };
    if (expr[i] == '+'){
      next->op = ReRangeN;
      next->s = 1;
      continue;
    };
    if (expr[i] == '?'){
      next->op = ReRangeNM;
      next->s = 0;
      next->e = 1;
      continue;
    };
    if (expr[i] == '|'){
      next->op = ReOr;
      continue;
    };

    // {n,m}
    if (expr[i] == '{'){
      int st = i+1;
      int en = -1;
      int comma = -1;
      bool nonGreedy = false;
      int j;
      for (j = i; j < expr.length(); j++){
        if (expr.length() > j+1 && expr[j] == '}' && expr[j+1] == '?'){
          en = j;
          nonGreedy = true;
          j++;
          break;
        };
        if (expr[j] == '}'){
          en = j;
          break;
        };
        if (expr[j] == ',') comma = j;
      };
      if (en == -1) return EBRACKETS;
      if (comma == -1) comma = en;
	  DString dse(&expr, st, comma-st);
      next->s = UnicodeTools::getNumber(&dse);
      if (comma != en) {
		  DString dse2(&expr, comma+1, en-comma-1);
		  next->e = UnicodeTools::getNumber(&dse2);
	  }
      else next->e = next->s;
      if (next->e == -1) return EOP;
      next->un.param = 0;
      if (en - comma == 1) next->e = -1;
      if (next->e == -1) next->op = nonGreedy ? ReNGRangeN : ReRangeN;
      else next->op = nonGreedy ? ReNGRangeNM : ReRangeNM;
      i = j;
      continue;
    };
    // ( ... )
    if (expr[i] == '('){
      bool namedBracket = false;
      // perl-like "uncaptured" brackets
      if (expr.length() >= i+2 && expr[i+1] == '?' && expr[i+2] == ':'){
        next->op = ReNamedBrackets;
        next->param0 = -1;
        namedBracket = true;
        i += 3;
      } else if (expr.length() > i+2 && expr[i+1] == '?' && expr[i+2] == '{'){
        // named bracket
        next->op = ReNamedBrackets;
        namedBracket = true;
        String *s_curly = UnicodeTools::getCurlyContent(expr, i+2);
        if (s_curly == null) return EBRACKETS;
        SString *br_name = new SString(s_curly);
        delete s_curly;
        int blen = br_name->length();
        if (blen == 0){
          next->param0 = -1;
          delete br_name;
        }else{
#ifndef NAMED_MATCHES_IN_HASH
#ifdef CHECKNAMES
          if (getBracketNo(br_name) != -1){
            delete br_name;
            return EBRACKETS;
          };
#endif
          if (cnMatch < NAMED_MATCHES_NUM){
            next->param0 = cnMatch;
            brnames[cnMatch] = br_name;
            cnMatch++;
          }else delete br_name;
#else
#ifdef CHECKNAMES
          if(br_name->length() && namedMatches && namedMatches->getItem(br_name)){
            delete br_name;
            return EBRACKETS;
          };
#endif
          next->param0 = 0;
          next->namedata = br_name;
          if (namedMatches){
            SMatch mt = {-1, -1};
            namedMatches->setItem(br_name, mt);
          };
#endif
        };
        i += blen+4;
      }else{
        next->op = ReBrackets;
        if (cMatch < MATCHES_NUM){
          next->param0 = cMatch;
          cMatch++;
        };
        i += 1;
      };
      next->un.param = new SRegInfo;
      next->un.param->parent = next;
      int endPos;
      EError err = setStructs(next->un.param, DString(&expr, i), endPos);
      if (endPos == expr.length()-i) return EBRACKETS;
      if (err) return err;
      i += endPos;
      continue;
    };

    // [] [^]
    if (expr[i] == '['){
      int endPos;
      CharacterClass *cc = CharacterClass::createCharClass(expr, i, &endPos);
      if (cc == null) return EENUM;
//      next->op = (exprn[i] == ReEnumS) ? ReEnum : ReNEnum;
      next->op = ReEnum;
      next->un.charclass = cc;
      i = endPos;
      continue;
    };
    if (expr[i] == ')' || expr[i] == ']' || expr[i] == '}') return EBRACKETS;
    next->op = ReSymb;
    next->un.symbol = expr[i];
  };

  // operators fixes
  for(next = re; next; next = next->next){
    // makes words from symbols
    SRegInfo *reword = next;
    SRegInfo *reafterword = next;
    SRegInfo *resymb;
    int wsize = 0;
    for (resymb = next;resymb && resymb->op == ReSymb; resymb = resymb->next, wsize++);
    if (resymb && resymb->op > ReBlockOps && resymb->op < ReSymbolOps){
      wsize--;
      resymb = resymb->prev;
    };
    if (wsize > 1){
      reafterword = resymb;
      resymb = reword;
      wchar *wcword = new wchar[wsize];
      for(int idx = 0; idx < wsize; idx++){
        wcword[idx] = resymb->un.symbol;
        SRegInfo *retmp = resymb;
        resymb = resymb->next;
        retmp->next = null;
        if (idx > 0) delete retmp;
      };
      reword->op = ReWord;
      reword->un.word = new SString(DString(wcword, 0, wsize));
      delete[] wcword;
      reword->next = reafterword;
      if (reafterword) reafterword->prev = reword;
      next = reword;
      continue;
    };

    // adds empty alternative
    while (next->op == ReOr){
      temp = new SRegInfo;
      temp->parent = next->parent;
      // |foo|bar
      if (!next->prev){
        temp->next = next;
        next->prev = temp;
        continue;
      };
      // foo||bar
      if (next->next && next->next->op == ReOr){
        temp->prev = next;
        temp->next = next->next;
        if (next->next) next->next->prev = temp;
        next->next = temp;
        continue;
      };
      // foo|bar|
      if (!next->next){
        temp->prev = next;
        temp->next = 0;
        next->next = temp;
        continue;
      };
      // foo|bar|*
      if (next->next->op > ReBlockOps && next->next->op < ReSymbolOps){
        temp->prev = next;
        temp->next = next->next;
        next->next->prev = temp;
        next->next = temp;
        continue;
      };
      delete temp;
      break;
    };
  };

  // op's generating...
  next = re;
  SRegInfo *realFirst;
  while(next){
    if (next->op > ReBlockOps && next->op < ReSymbolOps){
      if (!next->prev) return EOP;
      realFirst = next->prev;
      realFirst->next = 0;
      realFirst->parent = next;
      while(next->op == ReOr && realFirst->prev && realFirst->prev->op != ReOr){
        realFirst->parent = next;
        realFirst = realFirst->prev;
      };

      if (!realFirst->prev){
        re = next;
        next->un.param = realFirst;
        next->prev = 0;
      }else{
        next->un.param = realFirst;
        next->prev = realFirst->prev;
        realFirst->prev->next = next;
      };
      realFirst->prev = 0;
    };
    next = next->next;
  };
  if (retPos == -1) retPos = expr.length();
  return EOK;
};