Example #1
0
bool SendEmail::send(const String& from, const String& to, const String& subject, const String& msg)
{
  if (!host.length())
  {
    return false;
  }
  client->stop();
  client->setTimeout(timeout);
  // smtp connect
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.print("Connecting: ");
  DEBUG_EMAIL_PORT.print(host);
  DEBUG_EMAIL_PORT.print(":");
  DEBUG_EMAIL_PORT.println(port);
#endif
  if (!client->connect(host.c_str(), port))
  {
    return false;
  }
  String buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  if (!buffer.startsWith(F("220")))
  {
    return false;
  }
  buffer = F("EHLO ");
  buffer += client->localIP();
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  if (!buffer.startsWith(F("250")))
  {
    return false;
  }
  if (user.length()>0  && passwd.length()>0 )
  {
    buffer = F("AUTH LOGIN");
    client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    if (!buffer.startsWith(F("334")))
    {
      return false;
    }
    base64 b;
    buffer = user;
    buffer = b.encode(buffer);
    client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    if (!buffer.startsWith(F("334")))
    {
      return false;
    }
    buffer = this->passwd;
    buffer = b.encode(buffer);
    client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
    if (!buffer.startsWith(F("235")))
    {
      return false;
    }
  }
  // smtp send mail
  buffer = F("MAIL FROM: ");
  buffer += from;
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  if (!buffer.startsWith(F("250")))
  {
    return false;
  }
  buffer = F("RCPT TO: ");
  buffer += to;
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  if (!buffer.startsWith(F("250")))
  {
    return false;
  }
  buffer = F("DATA");
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = readClient();
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  if (!buffer.startsWith(F("354")))
  {
    return false;
  }
  buffer = F("From: ");
  buffer += from;
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = F("To: ");
  buffer += to;
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = F("Subject: ");
  buffer += subject;
  buffer += F("\r\n");
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = msg;
  client->println(buffer);
  client->println('.');
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  buffer = F("QUIT");
  client->println(buffer);
#ifdef DEBUG_EMAIL_PORT
  DEBUG_EMAIL_PORT.println(buffer);
#endif
  return true;
}
// Runs the "INQUIRY" command, with user defined timeout. Returns the number of
//  devices found, up to 5. The response expected looks like this:
//    INQUIRY 20FABB010272 240404 -37db
//    INQUIRY A4D1D203A4F4 6A041C -91db
//    OK
// "ERROR" is, as always, a possible result. What we want to do is extract that
//  12-digit hex value and save it. We may get duplicates; we only want to keep
//  new addresses. The parameter "timeout" is not in seconds; it can be between
//  1 and 48 inclusive, and the timeout period will be 1.28*timeout. We'll set
//  an internal timeout period that is slightly longer than that, for safety.
BC127::opResult BC127::inquiry(int timeout)
{

  int result = 0;
  String buffer = "";
  String addressTemp;
  String EOL = String("\n\r");
  
  for (byte i = 0; i <5; i++) _addresses[i] = "";
  _numAddresses = -1;
    
  knownStart(); // Purge serial buffers on Arduino and module.
  
  // Now issue the inquiry command.
  _serialPort->print("INQUIRY "); 
  _serialPort->print(timeout);
  _serialPort->print("\r");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the inquiry. Bog-standard Arduino stuff.
  unsigned long loopStart = millis();
  
  // Calculate a reset timeout value that's a tish longer than the module will
  //  use. This is our catch-all, so we don't sit in this loop forever waiting
  //  for input that will never come from the module.
  unsigned long loopTimeout = timeout*1300;
  
  // Oooookaaaayyy...now the fun part. A state machine that parses the input
  //  from the Bluetooth module!
  while (loopStart + loopTimeout > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));
    
    // If we've received the EOL string, we should parse the current buffer
    //  contents. There are three potential results to expect, here:
    // "OK" - The module has finished scanning (timed out) and the results we
    //   have are the only ones we'll ever get.
    // "ERROR" - Something went wrong and we're not scanning.
    // "INQUIRY <addr> <class> <rss>" - A remote device has responded. <addr>
    //   will be 12 upper case hex digits, and is the remote device's address,
    //   to be used to refer to that device later on. <class> is the remote
    //   device class; for example, by default, the BC127 will return 240404,
    //   which corresponds to a Bluetooth headset. <rss> is the received signal
    //   strength; generally, -70dBm is a good link strength.
    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("OK")) return (opResult)result;
      if (buffer.startsWith("ER")) return MODULE_ERROR;
      if (buffer.startsWith("IN")) // An address has been found!
      {
        // Nab the address from the received string and store it in addressTemp.
        addressTemp = buffer.substring(8,20);
        buffer = "";   // Clear the buffer for next round of data collection.
        // If this is the first address, we need to do some things to ensure
        //  that we get the right result value. If it's not first...
        if (_numAddresses == -1) 
        {
          _addresses[0] = addressTemp;
          _numAddresses = 1;
          result = 1;
        }
        else // ...search the list for this address, and append if it's not in
             //  the list and the list isn't too long.
        {
          // If we find it, change the addressTemp value to 'x'.
          for (char i = 0; i <= _numAddresses; i++)
          {
            if (addressTemp == _addresses[i])
            {
              addressTemp = "x";
              break;
            }
          }
          // If we get here and the value isn't x, it was a new value, and can
          //  be stored.
          if (addressTemp != "x")
          {
            _addresses[_numAddresses++] = addressTemp;
            result++;
          }
          // If we get HERE, our address list is full and we should return.
          if (_numAddresses == 5) return (opResult)result;
        }
      }
    }
  }
  return TIMEOUT_ERROR;
}
// Scan is very similar to inquiry, but for BLE devices rather than for classic.
//  Result format is slightly different, however- different enough to warrant
//  another whole function, IMO.
BC127::opResult BC127::BLEScan(int timeout)
{
  // We're going to assume that what's going to happen is a timeout with no
  //  valid input from the module.
  int result = 0;
  String buffer = "";
  String addressTemp;
  String EOL = String("\n\r");
  
  for (byte i = 0; i <5; i++) _addresses[i] = "";
  _numAddresses = 0;
    
  knownStart();
  
  // Now issue the inquiry command.
  _serialPort->print("SCAN "); _serialPort->print(timeout); _serialPort->print("\r");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the command. Bog-standard Arduino stuff.
  unsigned long loopStart = millis();
  
  // Calculate a timeout value that's a tish longer than the module will
  //  use. This is our catch-all, so we don't sit in this loop forever waiting
  //  for input that will never come from the module.
  unsigned long loopTimeout = timeout*1300;
  
  // Oooookaaaayyy...now the fun part. A state machine that parses the input
  //  from the Bluetooth module!
  while (loopStart + loopTimeout > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));
    
    // If we've received the EOL string, we should parse the current buffer
    //  contents. There are three potential results to expect, here:
    // "OK" - The module has finished scanning (timed out) and the results we
    //   have are the only ones we'll ever get.
    // "ERROR" - Something went wrong and we're not scanning.
    //  SCAN <addr> <short_name> <role> <RSS>
    //  <addr> is a 12-digit hex value
    //  <short_name> is a string, surrounded by carets ( <like this> )
    //  <role> is advertising flags. BC127 devices will show up as 0A; single mode
    //    devices as 02.
    //  <RSS> is the signal strength. Anything better than -70dBm is likely to be
    //    quite okay for connecting.
    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("OK")) return (opResult)result;
      if (buffer.startsWith("ER")) return MODULE_ERROR;
      if (buffer.startsWith("SC")) // An address has been found!
      {
        addressTemp = buffer.substring(5,17);
        buffer = "";
        if (_numAddresses == 0) 
        {
          _addresses[0] = addressTemp;
          _numAddresses++;
          result = (opResult)1;
        }
        else // search the list for this address, and append if it's not in
             //  the list and the list isn't too long.
        {
          for (char i = 0; i < _numAddresses; i++)
          {
            if (addressTemp == _addresses[i])
            {
              addressTemp = "x";
              break;
            }
          }
          if (addressTemp != "x")
          {
            _addresses[_numAddresses++] = addressTemp;
            result++;
          }
          if (_numAddresses == 5) return (opResult)result;
        }
      }
    }
  }
  return TIMEOUT_ERROR;
}
Example #4
0
bool rn2483::txData(String command, String data)
{
  bool send_success = false;
  uint8_t busy_count = 0;
  uint8_t retry_count = 0;

  while(!send_success)
  {
    //retransmit a maximum of 10 times
    retry_count++;
    if(retry_count>10)
    {
      return false;
    }

    _serial.print(command);
    sendEncoded(data);
    _serial.println();
    String receivedData = _serial.readStringUntil('\n');

    if(receivedData.startsWith("ok"))
    {
      _serial.setTimeout(30000);
      receivedData = _serial.readStringUntil('\n');
      _serial.setTimeout(2000);
      
      if(receivedData.startsWith("mac_tx_ok"))
      {
        //SUCCESS!!
        send_success = true;
        return true;
      }

      else if(receivedData.startsWith("mac_rx"))
      {
        //we received data downstream
        //TODO: handle received data
        send_success = true;
        return true;
      }

      else if(receivedData.startsWith("mac_err"))
      {
        init();
      }

      else if(receivedData.startsWith("invalid_data_len"))
      {
        //this should never happen if the prototype worked
        send_success = true;
        return false;
      }

      else if(receivedData.startsWith("radio_tx_ok"))
      {
        //SUCCESS!!
        send_success = true;
        return true;
      }

      else if(receivedData.startsWith("radio_err"))
      {
        //This should never happen. If it does, something major is wrong.
        init();
      }

      else
      {
        //unknown response
        //init();
      }
    }

    else if(receivedData.startsWith("invalid_param"))
    {
      //should not happen if we typed the commands correctly
      send_success = true;
      return false;
    }

    else if(receivedData.startsWith("not_joined"))
    {
      init();
    }

    else if(receivedData.startsWith("no_free_ch"))
    {
      //retry
      delay(1000);
    }

    else if(receivedData.startsWith("silent"))
    {
      init();
    }

    else if(receivedData.startsWith("frame_counter_err_rejoin_needed"))
    {
      init();
    }

    else if(receivedData.startsWith("busy"))
    {
      busy_count++;

      if(busy_count>=10)
      {
        init();
      }
      else
      {
        delay(1000);
      }
    }

    else if(receivedData.startsWith("mac_paused"))
    {
      init();
    }

    else if(receivedData.startsWith("invalid_data_len"))
    {
      //should not happen if the prototype worked
      send_success = true;
      return false;
    }

    else
    {
      //unknown response after mac tx command
      init();
    }
  }

  return false; //should never reach this
}
Example #5
0
void HTMLAnchorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == hrefAttr) {
        bool wasLink = isLink();
        setIsLink(!value.isNull());
        if (wasLink != isLink())
            didAffectSelector(AffectedSelectorLink | AffectedSelectorVisited | AffectedSelectorEnabled);
        if (isLink()) {
            String parsedURL = stripLeadingAndTrailingHTMLSpaces(value);
            if (document()->isDNSPrefetchEnabled()) {
                if (protocolIs(parsedURL, "http") || protocolIs(parsedURL, "https") || parsedURL.startsWith("//"))
                    prefetchDNS(document()->completeURL(parsedURL).host());
            }
        }
        invalidateCachedVisitedLinkHash();
    } else if (name == nameAttr || name == titleAttr) {
        // Do nothing.
    } else if (name == relAttr)
        setRel(value);
    else
        HTMLElement::parseAttribute(name, value);
}
Example #6
0
bool parseManifest(const KURL& manifestURL, const char* data, int length, Manifest& manifest)
{
    ASSERT(manifest.explicitURLs.isEmpty());
    ASSERT(manifest.onlineWhitelistedURLs.isEmpty());
    ASSERT(manifest.fallbackURLs.isEmpty());
    manifest.allowAllNetworkRequests = false;

    Mode mode = Explicit;

    RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/cache-manifest", "UTF-8");
    String s = decoder->decode(data, length);
    s.append(decoder->flush());
    
    // Look for the magic signature: "^\xFEFF?CACHE MANIFEST[ \t]?" (the BOM is removed by TextResourceDecoder).
    // Example: "CACHE MANIFEST #comment" is a valid signature.
    // Example: "CACHE MANIFEST;V2" is not.
    if (!s.startsWith("CACHE MANIFEST"))
        return false;
    
    const UChar* end = s.characters() + s.length();    
    const UChar* p = s.characters() + 14; // "CACHE MANIFEST" is 14 characters.

    if (p < end && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
        return false;

    // Skip to the end of the line.
    while (p < end && *p != '\r' && *p != '\n')
        p++;

    while (1) {
        // Skip whitespace
        while (p < end && (*p == '\n' || *p == '\r' || *p == ' ' || *p == '\t'))
            p++;
        
        if (p == end)
            break;
        
        const UChar* lineStart = p;
        
        // Find the end of the line
        while (p < end && *p != '\r' && *p != '\n')
            p++;
        
        // Check if we have a comment
        if (*lineStart == '#')
            continue;
        
        // Get rid of trailing whitespace
        const UChar* tmp = p - 1;
        while (tmp > lineStart && (*tmp == ' ' || *tmp == '\t'))
            tmp--;
        
        String line(lineStart, tmp - lineStart + 1);

        if (line == "CACHE:") 
            mode = Explicit;
        else if (line == "FALLBACK:")
            mode = Fallback;
        else if (line == "NETWORK:")
            mode = OnlineWhitelist;
        else if (line.endsWith(':'))
            mode = Unknown;
        else if (mode == Unknown)
            continue;
        else if (mode == Explicit || mode == OnlineWhitelist) {
            const UChar* p = line.characters();
            const UChar* lineEnd = p + line.length();
            
            // Look for whitespace separating the URL from subsequent ignored tokens.
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            if (mode == OnlineWhitelist && p - line.characters() == 1 && *line.characters() == '*') {
                // Wildcard was found.
                manifest.allowAllNetworkRequests = true;
                continue;
            }

            KURL url(manifestURL, String(line.characters(), p - line.characters()));
            
            if (!url.isValid())
                continue;

            if (url.hasFragmentIdentifier())
                url.removeFragmentIdentifier();
            
            if (!equalIgnoringCase(url.protocol(), manifestURL.protocol()))
                continue;
            
            if (mode == Explicit && manifestURL.protocolIs("https") && !protocolHostAndPortAreEqual(manifestURL, url))
                continue;
            
            if (mode == Explicit)
                manifest.explicitURLs.add(url.string());
            else
                manifest.onlineWhitelistedURLs.append(url);
            
        } else if (mode == Fallback) {
            const UChar* p = line.characters();
            const UChar* lineEnd = p + line.length();
            
            // Look for whitespace separating the two URLs
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            if (p == lineEnd) {
                // There was no whitespace separating the URLs.
                continue;
            }
            
            KURL namespaceURL(manifestURL, String(line.characters(), p - line.characters()));
            if (!namespaceURL.isValid())
                continue;
            if (namespaceURL.hasFragmentIdentifier())
                namespaceURL.removeFragmentIdentifier();

            if (!protocolHostAndPortAreEqual(manifestURL, namespaceURL))
                continue;
                                   
            // Skip whitespace separating fallback namespace from URL.
            while (p < lineEnd && (*p == '\t' || *p == ' '))
                p++;

            // Look for whitespace separating the URL from subsequent ignored tokens.
            const UChar* fallbackStart = p;
            while (p < lineEnd && *p != '\t' && *p != ' ') 
                p++;

            KURL fallbackURL(manifestURL, String(fallbackStart, p - fallbackStart));
            if (!fallbackURL.isValid())
                continue;
            if (fallbackURL.hasFragmentIdentifier())
                fallbackURL.removeFragmentIdentifier();

            if (!protocolHostAndPortAreEqual(manifestURL, fallbackURL))
                continue;

            manifest.fallbackURLs.append(make_pair(namespaceURL, fallbackURL));            
        } else 
            ASSERT_NOT_REACHED();
    }

    return true;
}
Example #7
0
static bool isTextMimeType(const String& type)
{
    return type == "text/plain" || type.startsWith("text/plain;");
}
Example #8
0
//===> dissect incomming subscribe <-------------------------------------------
TdissectResult ApplicationMQTTClient::dissectPayload(String subTopic, String subValue){
  TdissectResult dissectResult;
  String Topics[4];
  for (int i = 0; i < 4; i++) {
    Topics[i] = NULL;
  }

  String str = subTopic;
  if (str.startsWith("/")) str.remove(0, 1);
  if (str.endsWith("/")) str.remove(str.length()-1,str.length());
  dissectResult.topic = str;
  dissectResult.value = subTopic;

  //Serial.print("dissectPayload subTopic = "); Serial.println(str);

  int index = -1;
  int i = 0;
  do{
   index = str.indexOf("/");
   if (index != -1){
      Topics[i] = str.substring(0, index);
      //Serial.println("Topic[" + String(i) + "] = " + Topics[i]);
	  str.remove(0, index +1);
	  i++;
	  if (str.indexOf("/") == -1 and str.length() > 0){    //best of the rest
	    index = -1;
		Topics[i] = str;
		//Serial.println("Topic[" + String(i) + "] = " + Topics[i]);
		i++;
	  }
	}else{
	}
  } while (index != -1);
  int depth = i;
  int countDepth = 0;
  //Serial.println("TreeDepth = " + String(i));

  //find item index
  String itemPath = "";
  bool found_e1 = false;
  if (depth > 1 and Topics[1] != NULL){
    for (int i = 0; i < topic.sub.E1.count; i++) {
	  if (topic.sub.E1.item[i] != NULL){
	    	//Serial.println(topic.sub.E1.item[i] + " / " + Topics[1]);
	    if (topic.sub.E1.item[i] == Topics[1]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E1 = i;
		  itemPath = String(i);
		  dissectResult.found = true;
		  found_e1 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }

  bool found_e2 = false;
  if (depth > 2 and Topics[2] != NULL and found_e1){
    for (int i = 0; i < topic.sub.E2.count; i++) {
	  if (topic.sub.E2.item[dissectResult.E1][i] != NULL){
	    	//Serial.println(topic.sub.E2.item[dissectResult.E1][i] + " / " + Topics[2]);
	    if (topic.sub.E2.item[dissectResult.E1][i] == Topics[2]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E2 = i;
		  itemPath += "/";
		  itemPath += String(i);
		  dissectResult.found = true;
		  found_e2 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }

  bool found_e3 = false;
  if (depth > 3 and Topics[3] != NULL and found_e1 and found_e2){
    for (int i = 0; i < topic.sub.E3.count; i++) {
	  if (topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] != NULL){
	    	//Serial.println(topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] + " / " + Topics[3]);
	    if (topic.sub.E3.item[dissectResult.E1][dissectResult.E2][i] == Topics[3]){
	    	//Serial.println("----> gefunden!");
	    	//Serial.println("");
          dissectResult.E3 = i;
		  itemPath += "/";
		  itemPath += String(i);
		  dissectResult.found = true;
		  found_e3 = true;
		  countDepth++;
		  break;
        }else dissectResult.found = false;
	  }
    }
  }
  if (depth == countDepth+1){
	  Serial.println("dissectResult found!");
	  dissectResult.itemPath = itemPath;

  }else{
	  dissectResult.found = false;
	  Serial.println("no dissectResult found!");
  }
  return dissectResult;
}
void HTMLAnchorElement::parseAttribute(Attribute* attr)
{
    if (attr->name() == hrefAttr) {
        bool wasLink = isLink();
        setIsLink(!attr->isNull());
        if (wasLink != isLink())
            setNeedsStyleRecalc();
        if (isLink()) {
            String parsedURL = stripLeadingAndTrailingHTMLSpaces(attr->value());
            if (document()->isDNSPrefetchEnabled()) {
                if (protocolIs(parsedURL, "http") || protocolIs(parsedURL, "https") || parsedURL.startsWith("//"))
                    prefetchDNS(document()->completeURL(parsedURL).host());
            }
            if (document()->page() && !document()->page()->javaScriptURLsAreAllowed() && protocolIsJavaScript(parsedURL)) {
                clearIsLink();
                attr->setValue(nullAtom);
            }
        }
        invalidateCachedVisitedLinkHash();
    } else if (attr->name() == nameAttr || attr->name() == titleAttr) {
        // Do nothing.
    } else if (attr->name() == relAttr)
        setRel(attr->value());
    else
        HTMLElement::parseAttribute(attr);
}
Example #10
0
void CtFindTask::run()
{
	// Build command string
	String command = makeQuery();

	// Execult the query in another process
	Process findProcess;
	findProcess.execCommand(command, true);

	InputStream* stdOutStream = findProcess.getStdOut();
	TextReader findReader(stdOutStream);
	bool readSuccess;

	// Extract the first returned version name
	String versionName = findReader.readLine(readSuccess);

	// If the returned string is empty just return as we found nothing
	if (!readSuccess)
	{
		return;
	}

	// Skip warning on systems that have configuration issues
	// Can start with a string like:
	// noname: Warning: Can not find a group named "xxx\yyy"
	if (versionName.startsWith("noname: Warning:"))
	{
		versionName = findReader.readLine(readSuccess);

		if (!readSuccess)
		{
			return;
		}
	}

	// Print errors returned from cleartool
	if (versionName.startsWith("cleartool: Error:"))
	{
		cerr << "Failed to execute cleartool find command. Aborting." << endl
			<< versionName << endl;
		exit(1);
	}

	AnalyzeTask* analyzeTask = new AnalyzeTask(m_threadPool,
			m_dataStore,
			m_settings,
			versionName);
	m_threadPool->execute(analyzeTask);

	// Loop to analyze remaining versions
	while (true)
	{
		versionName = findReader.readLine(readSuccess);

		if (!readSuccess)
			break;

		analyzeTask = new AnalyzeTask(m_threadPool,
			m_dataStore,
			m_settings,
			versionName);
		m_threadPool->execute(analyzeTask);
	}

	// Wait for the find process to exit
	findProcess.waitFor();
}
Example #11
0
int main()
{
    // 路由表, 使一个程序能逻辑上实现多个页面
    std::map<String, void(*)(Page*)> handle;
    handle["index"] = index;
    handle["product_list"] = productList;
    handle["article_list"] = articleList;
    handle["node"] = node;
    handle["admin_login"] = adminLogin;
    handle["admin_index"] = adminIndex;
    handle["admin_user"] = adminUser;
    handle["admin_type"] = adminType;
    handle["admin_node"] = adminNode;
    handle["admin_node_modify"] = adminNodeModify;
    handle["admin_comment"] = adminComment;
    handle["admin_attachment"] = adminAttachment;
    handle["admin_attachment_dialog"] = adminAttachmentDialog;
    handle["admin_setting"] = adminSetting;
    handle["admin_password"] = adminPassword;
    handle["admin_edit_tmpl"] = adminEditTmpl;
    handle["admin_run_sql"] = adminRunSql;
    handle["admin_file"] = adminFile;

    // 获取数据库连接参数
    String db_host(getenv("DATABASE_HOST"));
    String db_name(getenv("DATABASE_NAME"));
    String db_user(getenv("DATABASE_USER"));
    String db_password(getenv("DATABASE_PASSWORD"));
    int db_port = atoi(getenv("DATABASE_PORT"));

    // 打开数据库
    db = new Mysql;
    db->open(db_host, db_user, db_password, db_name, db_port);
    // MySQL需要执行下面语句避免数据库中文乱码
    db->exec("set names 'utf8'");

    // 设置模版加载目录
    Page::setTmplDir("./tmpl/");
    // 临时文件存放目录
    Page::setTempDir("./cache/");
    // 文件上传目录
    Page::setUploadDir("/uploads/");

    // 初始化页面对象
    Page page;
    // 页面中可以使用变量html_head在HTML头中插入额外的CSS和JS
    page.response("html_head", "");

    String path = page.pathInfo(0);
    if(!path.startsWith("admin_"))
    {
        db->query("select name,value from settings where name in ('web_title','web_logo','web_keywords','web_description')");
        while(db->next())
        {
            if(db->getString(0) == "web_title")
                page.response("web_title", db->getString(1));
            if(db->getString(0) == "web_logo")
                page.response("web_logo", db->getString(1));
            if(db->getString(0) == "web_keywords")
                page.response("web_keywords", db->getString(1));
            if(db->getString(0) == "web_description")
                page.response("web_description", db->getString(1));
        }
    }

    if(path.empty())
        index(&page);
    else if(handle.find(path) != handle.end())
        handle[path](&page);
    else
        page.notFound();

    // 关闭数据库
    db->close();
    delete db;

    return 0;
}
Example #12
0
void SyscallPolicy::addDirectoryPermission(const String& path, Permission permission)
{
    ASSERT(path.startsWith('/') && !path.contains("//") && (path.length() == 1 || !path.endsWith('/')));

    m_directoryPermission.set(canonicalizeFileName(path), permission);
}
Example #13
0
void SyscallPolicy::addFilePermission(const String& path, Permission permission)
{
    ASSERT(!path.isEmpty() && path.startsWith('/')  && !path.endsWith('/') && !path.contains("//"));

    m_filePermission.set(canonicalizeFileName(path), permission);
}
void HTMLConstructionSite::setCompatibilityModeFromDoctype(const String& name, const String& publicId, const String& systemId)
{
    // There are three possible compatibility modes:
    // Quirks - quirks mode emulates WinIE and NS4. CSS parsing is also relaxed in this mode, e.g., unit types can
    // be omitted from numbers.
    // Limited Quirks - This mode is identical to no-quirks mode except for its treatment of line-height in the inline box model.
    // No Quirks - no quirks apply. Web pages will obey the specifications to the letter.

    // Check for Quirks Mode.
    if (name != "html"
        || publicId.startsWith("+//Silmaril//dtd html Pro v0r11 19970101//", false)
        || publicId.startsWith("-//AdvaSoft Ltd//DTD HTML 3.0 asWedit + extensions//", false)
        || publicId.startsWith("-//AS//DTD HTML 3.0 asWedit + extensions//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0 Level 1//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0 Level 2//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0 Strict Level 1//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0 Strict Level 2//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0 Strict//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.0//", false)
        || publicId.startsWith("-//IETF//DTD HTML 2.1E//", false)
        || publicId.startsWith("-//IETF//DTD HTML 3.0//", false)
        || publicId.startsWith("-//IETF//DTD HTML 3.2 Final//", false)
        || publicId.startsWith("-//IETF//DTD HTML 3.2//", false)
        || publicId.startsWith("-//IETF//DTD HTML 3//", false)
        || publicId.startsWith("-//IETF//DTD HTML Level 0//", false)
        || publicId.startsWith("-//IETF//DTD HTML Level 1//", false)
        || publicId.startsWith("-//IETF//DTD HTML Level 2//", false)
        || publicId.startsWith("-//IETF//DTD HTML Level 3//", false)
        || publicId.startsWith("-//IETF//DTD HTML Strict Level 0//", false)
        || publicId.startsWith("-//IETF//DTD HTML Strict Level 1//", false)
        || publicId.startsWith("-//IETF//DTD HTML Strict Level 2//", false)
        || publicId.startsWith("-//IETF//DTD HTML Strict Level 3//", false)
        || publicId.startsWith("-//IETF//DTD HTML Strict//", false)
        || publicId.startsWith("-//IETF//DTD HTML//", false)
        || publicId.startsWith("-//Metrius//DTD Metrius Presentational//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 2.0 HTML Strict//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 2.0 HTML//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 2.0 Tables//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 3.0 HTML Strict//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 3.0 HTML//", false)
        || publicId.startsWith("-//Microsoft//DTD Internet Explorer 3.0 Tables//", false)
        || publicId.startsWith("-//Netscape Comm. Corp.//DTD HTML//", false)
        || publicId.startsWith("-//Netscape Comm. Corp.//DTD Strict HTML//", false)
        || publicId.startsWith("-//O'Reilly and Associates//DTD HTML 2.0//", false)
        || publicId.startsWith("-//O'Reilly and Associates//DTD HTML Extended 1.0//", false)
        || publicId.startsWith("-//O'Reilly and Associates//DTD HTML Extended Relaxed 1.0//", false)
        || publicId.startsWith("-//SoftQuad Software//DTD HoTMetaL PRO 6.0::19990601::extensions to HTML 4.0//", false)
        || publicId.startsWith("-//SoftQuad//DTD HoTMetaL PRO 4.0::19971010::extensions to HTML 4.0//", false)
        || publicId.startsWith("-//Spyglass//DTD HTML 2.0 Extended//", false)
        || publicId.startsWith("-//SQ//DTD HTML 2.0 HoTMetaL + extensions//", false)
        || publicId.startsWith("-//Sun Microsystems Corp.//DTD HotJava HTML//", false)
        || publicId.startsWith("-//Sun Microsystems Corp.//DTD HotJava Strict HTML//", false)
        || publicId.startsWith("-//W3C//DTD HTML 3 1995-03-24//", false)
        || publicId.startsWith("-//W3C//DTD HTML 3.2 Draft//", false)
        || publicId.startsWith("-//W3C//DTD HTML 3.2 Final//", false)
        || publicId.startsWith("-//W3C//DTD HTML 3.2//", false)
        || publicId.startsWith("-//W3C//DTD HTML 3.2S Draft//", false)
        || publicId.startsWith("-//W3C//DTD HTML 4.0 Frameset//", false)
        || publicId.startsWith("-//W3C//DTD HTML 4.0 Transitional//", false)
        || publicId.startsWith("-//W3C//DTD HTML Experimental 19960712//", false)
        || publicId.startsWith("-//W3C//DTD HTML Experimental 970421//", false)
        || publicId.startsWith("-//W3C//DTD W3 HTML//", false)
        || publicId.startsWith("-//W3O//DTD W3 HTML 3.0//", false)
        || equalIgnoringCase(publicId, "-//W3O//DTD W3 HTML Strict 3.0//EN//")
        || publicId.startsWith("-//WebTechs//DTD Mozilla HTML 2.0//", false)
        || publicId.startsWith("-//WebTechs//DTD Mozilla HTML//", false)
        || equalIgnoringCase(publicId, "-/W3C/DTD HTML 4.0 Transitional/EN")
        || equalIgnoringCase(publicId, "HTML")
        || equalIgnoringCase(systemId, "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd")
        || (systemId.isEmpty() && publicId.startsWith("-//W3C//DTD HTML 4.01 Frameset//", false))
        || (systemId.isEmpty() && publicId.startsWith("-//W3C//DTD HTML 4.01 Transitional//", false))) {
        setCompatibilityMode(Document::QuirksMode);
        return;
    }

    // Check for Limited Quirks Mode.
    if (publicId.startsWith("-//W3C//DTD XHTML 1.0 Frameset//", false)
        || publicId.startsWith("-//W3C//DTD XHTML 1.0 Transitional//", false)
        || (!systemId.isEmpty() && publicId.startsWith("-//W3C//DTD HTML 4.01 Frameset//", false))
        || (!systemId.isEmpty() && publicId.startsWith("-//W3C//DTD HTML 4.01 Transitional//", false))) {
        setCompatibilityMode(Document::LimitedQuirksMode);
        return;
    }

    // Otherwise we are No Quirks Mode.
    setCompatibilityMode(Document::NoQuirksMode);
}
Example #15
0
//==============================================================================
String File::parseAbsolutePath (const String& p)
{
    if (p.isEmpty())
        return String();

#if JUCE_WINDOWS
    // Windows..
    String path (p.replaceCharacter ('/', '\\'));

    if (path.startsWithChar (separator))
    {
        if (path[1] != separator)
        {
            /*  When you supply a raw string to the File object constructor, it must be an absolute path.
                If you're trying to parse a string that may be either a relative path or an absolute path,
                you MUST provide a context against which the partial path can be evaluated - you can do
                this by simply using File::getChildFile() instead of the File constructor. E.g. saying
                "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
                path if that's what was supplied, or would evaluate a partial path relative to the CWD.
            */
            jassertfalse;

            path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
        }
    }
    else if (! path.containsChar (':'))
    {
        /*  When you supply a raw string to the File object constructor, it must be an absolute path.
            If you're trying to parse a string that may be either a relative path or an absolute path,
            you MUST provide a context against which the partial path can be evaluated - you can do
            this by simply using File::getChildFile() instead of the File constructor. E.g. saying
            "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
            path if that's what was supplied, or would evaluate a partial path relative to the CWD.
        */
        jassertfalse;

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#else
    // Mac or Linux..

    // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
    // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
    // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
    jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));

    String path (p);

    if (path.startsWithChar ('~'))
    {
        if (path[1] == separator || path[1] == 0)
        {
            // expand a name of the form "~/abc"
            path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
                    + path.substring (1);
        }
        else
        {
            // expand a name of type "~dave/abc"
            const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));

            if (struct passwd* const pw = getpwnam (userName.toUTF8()))
                path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
        }
    }
    else if (! path.startsWithChar (separator))
    {
       #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
        if (! (path.startsWith ("./") || path.startsWith ("../")))
        {
            /*  When you supply a raw string to the File object constructor, it must be an absolute path.
                If you're trying to parse a string that may be either a relative path or an absolute path,
                you MUST provide a context against which the partial path can be evaluated - you can do
                this by simply using File::getChildFile() instead of the File constructor. E.g. saying
                "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
                path if that's what was supplied, or would evaluate a partial path relative to the CWD.
            */
            jassertfalse;

           #if JUCE_LOG_ASSERTIONS
            Logger::writeToLog ("Illegal absolute path: " + path);
           #endif
        }
       #endif

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#endif

    while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
        path = path.dropLastCharacters (1);

    return path;
}
Example #16
0
void ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){
  
#ifdef DEBUG
  DEBUG_OUTPUT.print("Parse Form: Boundary: ");
  DEBUG_OUTPUT.print(boundary);
  DEBUG_OUTPUT.print(" Length: ");
  DEBUG_OUTPUT.println(len);
#endif
  String line;
  line = client.readStringUntil('\r');
  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.startsWith("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
            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
          DEBUG_OUTPUT.print("PostArg Name: ");
          DEBUG_OUTPUT.println(argName);
#endif
          argType = "text/plain";
          line = client.readStringUntil('\r');
          client.readStringUntil('\n');
          if (line.startsWith("Content-Type")){
            argType = line.substring(line.indexOf(':')+2);
            //skip next line
            client.readStringUntil('\r');
            client.readStringUntil('\n');
          }
#ifdef DEBUG
          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
            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
              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
            DEBUG_OUTPUT.print("Start File: ");
            DEBUG_OUTPUT.print(_currentUpload.filename);
            DEBUG_OUTPUT.print(" Type: ");
            DEBUG_OUTPUT.println(_currentUpload.type);
#endif
            if (_fileUploadHandler) _fileUploadHandler();
            _currentUpload.status = UPLOAD_FILE_WRITE;
            uint8_t argByte = _uploadReadByte(client);
readfile:
            while(argByte != 0x0D){
              _uploadWriteByte(argByte);
              argByte = _uploadReadByte(client);
            }
            
            argByte = _uploadReadByte(client);
            if (argByte == 0x0A){
              argByte = _uploadReadByte(client);
              if ((char)argByte != '-'){
                //continue reading the file
                _uploadWriteByte(0x0D);
                _uploadWriteByte(0x0A);
                goto readfile;
              } else {
                argByte = _uploadReadByte(client);
                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 (_fileUploadHandler) _fileUploadHandler();
                _currentUpload.totalSize += _currentUpload.currentSize;
                _currentUpload.status = UPLOAD_FILE_END;
                if (_fileUploadHandler) _fileUploadHandler();
#ifdef DEBUG
                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
                  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;
  }
}
void ESP8266WebServer::handleClient()
{
  WiFiClient client = _server.available();
  if (!client) {
    return;
  }

#ifdef DEBUG
  Serial.println("New client");
#endif
  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
  }

  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');

  HTTPMethod method = HTTP_GET;
  if (req.startsWith("POST")) {
    method = HTTP_POST;
  }

  // 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
    Serial.print("Invalid request: ");
    Serial.println(req);
#endif
    return;
  }

  req = req.substring(addr_start + 1, addr_end);

  String formData;
  if (method == HTTP_POST) {
    int contentLength = -1;
    int headerCount = 0;
    while(headerCount < 1024) { // there shouldn't be that much really
      String line = client.readStringUntil('\r');
      client.readStringUntil('\n');

      if (line.length() > 0) {  // this is a header
        ++headerCount;
        if (contentLength < 0 && line.startsWith("Content-Length")) {
          // get content length from the header
          int valuePos = line.indexOf(' ', 14);
          if (valuePos > 0) {
            String valueStr = line.substring(valuePos+1);
            contentLength = valueStr.toInt();
#ifdef DEBUG
            Serial.print("Content-Length: ");
            Serial.println(contentLength);
#endif
          }
        }
      }
      else {
        break;
      }
    }
#ifdef DEBUG
    Serial.print("headerCount=");
    Serial.println(headerCount);
#endif
    if (contentLength >= 0) {
      formData = "";
      int n = 0;   // timeout counter
      while (formData.length() < contentLength && ++n < 3)
        formData += client.readString();
    }
    else {
      formData = client.readStringUntil('\r'); // will return after timing out once
    }
  }
  else if (method == HTTP_GET) {
    int args_start = req.indexOf('?');
    if (args_start != -1) {
      formData = req.substring(args_start + 1);
      req = req.substring(0, args_start);
    }
  }

  client.flush();

#ifdef DEBUG
  Serial.print("Request: ");
  Serial.println(req);
  Serial.print("Args: ");
  Serial.println(formData);
#endif

  _parseArguments(formData);
  _handleRequest(client, req, method);

}
Example #18
0
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');

  // 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
    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 searchStr = "";
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = url.substring(hasSearch + 1);
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  
  HTTPMethod method = HTTP_GET;
  if (methodStr == "POST") {
    method = HTTP_POST;
  } else if (methodStr == "DELETE") {
    method = HTTP_DELETE;
  } else if (methodStr == "PUT") {
    method = HTTP_PUT;
  } else if (methodStr == "PATCH") {
    method = HTTP_PATCH;
  }
  _currentMethod = method;
  
#ifdef DEBUG
  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

  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;
    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 + 2);
      if (headerName == "Content-Type"){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("multipart/form-data")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName == "Content-Length"){
        contentLength = headerValue.toInt();
      }
    }
  
    if (!isForm){
      if (searchStr != "") searchStr += '&';
      //some clients send headers first and data after (like we do)
      //give them a chance
      int tries = 100;//100ms max wait
      while(!client.available() && tries--)delay(1);
      size_t plainLen = client.available();
      char *plainBuf = (char*)malloc(plainLen+1);
      client.readBytes(plainBuf, plainLen);
      plainBuf[plainLen] = '\0';
#ifdef DEBUG
      DEBUG_OUTPUT.print("Plain: ");
      DEBUG_OUTPUT.println(plainBuf);
#endif
      if(plainBuf[0] == '{' || plainBuf[0] == '[' || strstr(plainBuf, "=") == NULL){
        //plain post json or other data
        searchStr += "plain=";
        searchStr += plainBuf;
      } else {
        searchStr += plainBuf;
      }
      free(plainBuf);
    }
    _parseArguments(searchStr);
    if (isForm){
      _parseForm(client, boundaryStr, contentLength);
    }
  } else {
    _parseArguments(searchStr);
  }
  client.flush();

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

  return true;
}
Example #19
0
static bool isSupportedSVG11Feature(const String& feature, const String& version)
{
    if (!version.isEmpty() && version != "1.1")
        return false;

    static bool initialized = false;
    DEFINE_STATIC_LOCAL(FeatureSet, svgFeatures, ());
    if (!initialized) {
        // Sadly, we cannot claim to implement any of the SVG 1.1 generic feature sets
        // lack of Font and Filter support.
        // http://bugs.webkit.org/show_bug.cgi?id=15480
#if ENABLE(SVG_FONTS)
        addString(svgFeatures, "SVG");
        addString(svgFeatures, "SVGDOM");
        addString(svgFeatures, "SVG-static");
        addString(svgFeatures, "SVGDOM-static");
#endif
        addString(svgFeatures, "SVG-animation");
        addString(svgFeatures, "SVGDOM-animation");
//      addString(svgFeatures, "SVG-dynamic);
//      addString(svgFeatures, "SVGDOM-dynamic);
        addString(svgFeatures, "CoreAttribute");
        addString(svgFeatures, "Structure");
        addString(svgFeatures, "BasicStructure");
        addString(svgFeatures, "ContainerAttribute");
        addString(svgFeatures, "ConditionalProcessing");
        addString(svgFeatures, "Image");
        addString(svgFeatures, "Style");
        addString(svgFeatures, "ViewportAttribute");
        addString(svgFeatures, "Shape");
        addString(svgFeatures, "Text");
        addString(svgFeatures, "BasicText");
        addString(svgFeatures, "PaintAttribute");
        addString(svgFeatures, "BasicPaintAttribute");
        addString(svgFeatures, "OpacityAttribute");
        addString(svgFeatures, "GraphicsAttribute");
        addString(svgFeatures, "BaseGraphicsAttribute");
        addString(svgFeatures, "Marker");
//      addString(svgFeatures, "ColorProfile");
        addString(svgFeatures, "Gradient");
        addString(svgFeatures, "Pattern");
        addString(svgFeatures, "Clip");
        addString(svgFeatures, "BasicClip");
        addString(svgFeatures, "Mask");
        addString(svgFeatures, "Filter");
        addString(svgFeatures, "BasicFilter");
        addString(svgFeatures, "DocumentEventsAttribute");
        addString(svgFeatures, "GraphicalEventsAttribute");
//      addString(svgFeatures, "AnimationEventsAttribute");
        addString(svgFeatures, "Cursor");
        addString(svgFeatures, "Hyperlinking");
        addString(svgFeatures, "XlinkAttribute");
        addString(svgFeatures, "View");
        addString(svgFeatures, "Script");
        addString(svgFeatures, "Animation");
#if ENABLE(SVG_FONTS)
        addString(svgFeatures, "Font");
        addString(svgFeatures, "BasicFont");
#endif
        addString(svgFeatures, "Extensibility");
        initialized = true;
    }
    return feature.startsWith("http://www.w3.org/tr/svg11/feature#", false)
        && svgFeatures.contains(feature.right(feature.length() - 35));
}
bool PlyLoader::readHeader(TextStream* line_reader)
{
  mVerts   = NULL;
  mNormals = NULL;
  mColors  = NULL;
  mIndices.reserve(100);
  bool ok = true;
  elements().clear();
  String str;
  // ply loader
  line_reader->readLineLF(str);
  if (str.trim() != "ply")
    return false;
  // format
  line_reader->readLineLF(str);
  if (str.trim() == "format ascii 1.0")
  {
    mBinary = false;
  }
  else
  if (str.trim() == "format binary_little_endian 1.0")
  {
    mBinary = true;
    mLittleEndian = true;
  }
  else
  if (str.trim() == "format binary_big_endian 1.0")
  {
    mBinary = true;
    mLittleEndian = false;
  }
  else
    return false;
  // read elements
  while ( (line_reader->readLineLF(str)) && str.trim() != "end_header")
  {
    if (str.startsWith("comment"))
      continue;
    else
    if (str.startsWith("element"))
    {
      elements().push_back(new PlyElement);
      elements().back()->setName( str.field(' ',1) );
      elements().back()->setElemCount( str.field(' ',2).toInt() );
    }
    else
    if (str.startsWith("property"))
    {
      String prop_type = str.field(' ',1);
      ref<PlyScalar> prop;
      ref<PlyScalarList> scalar_list;
      if (prop_type == "list")
      {
        String num_type = str.field(' ',2);
        String idx_type = str.field(' ',3);
        String name     = str.field(' ',4);
        if (name.empty())
        {
          Log::error("PLY parse error #5.\n");
          return false;
        }

        scalar_list = new PlyScalarList;
        elements().back()->properties().push_back(scalar_list);

        scalar_list->setCountType(translateType(num_type));
        scalar_list->setScalarType(translateType(idx_type));
        scalar_list->setName(name);
      }
      else
      {
        prop = new PlyScalar;
        elements().back()->properties().push_back(prop);
        prop->setName( str.field(' ',2) );
        prop->setScalarType(translateType(prop_type));
      }
    }
    else
    {
      Log::error("PLY parse error #2.\n");
      return false;
    }
  }
  analyzeHeader();
  mVertexIndex = 0;
  return ok;
}
Example #21
0
static bool isHtmlMimeType(const String& type)
{
    return type == "text/html" || type.startsWith("text/html;");
}
Example #22
0
void HTMLAnchorElement::parseAttribute(const Attribute& attribute)
{
    if (attribute.name() == hrefAttr) {
        bool wasLink = isLink();
        setIsLink(!attribute.isNull());
        if (wasLink != isLink())
            setNeedsStyleRecalc();
        if (isLink()) {
            String parsedURL = stripLeadingAndTrailingHTMLSpaces(attribute.value());
            if (document()->isDNSPrefetchEnabled()) {
                if (protocolIs(parsedURL, "http") || protocolIs(parsedURL, "https") || parsedURL.startsWith("//"))
                    prefetchDNS(document()->completeURL(parsedURL).host());
            }
        }
        invalidateCachedVisitedLinkHash();
    } else if (attribute.name() == nameAttr || attribute.name() == titleAttr) {
        // Do nothing.
    } else if (attribute.name() == relAttr)
        setRel(attribute.value());
    else
        HTMLElement::parseAttribute(attribute);
}
Example #23
0
void rn2483::init(String AppEUI, String AppKey)
{
  _otaa = true;
  _appeui = AppEUI;
  _nwkskey = "0";
  _appskey = AppKey; //reuse the variable

  //clear serial buffer
  while(_serial.read() != -1);

  _serial.println("sys get hweui");
  String addr = _serial.readStringUntil('\n');
  addr.trim();
  
  _serial.println("mac reset 868");
  String receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  _serial.println("mac set appeui "+_appeui);
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  _serial.println("mac set appkey "+_appskey);
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  if(addr!="" && addr.length() == 16)
  {
    _serial.println("mac set deveui "+addr);
  }
  else 
  {
    _serial.println("mac set deveui "+_default_deveui);
  }
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  _serial.println("mac set pwridx 1");
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  _serial.println("mac set adr off");
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  _serial.println("mac set rx2 3 869525000");
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  // _serial.println("mac set retx 10");
  // _serial.readStringUntil('\n');
  // _serial.println("mac set linkchk 60");
  // _serial.readStringUntil('\n');
  // _serial.println("mac set ar on");
  // _serial.readStringUntil('\n');
  _serial.setTimeout(30000);
  _serial.println("mac save");
  receivedData = _serial.readStringUntil('\n');
  Serial.print(receivedData);

  bool joined = false;

  for(int i=0; i<10 && !joined; i++)
  {
    _serial.println("mac join otaa");
    receivedData = _serial.readStringUntil('\n');
    Serial.print(receivedData);
    receivedData = _serial.readStringUntil('\n');
    Serial.print(receivedData);

    if(receivedData.startsWith("accepted"))
    {
      joined=true;
      delay(1000);
    }
    else
    {
      delay(1000);
    }
  }
  _serial.setTimeout(2000);
}
Example #24
0
bool copyRuntime( const Path& binpath, const Path& tgtpath )
{
   message( "Searching VSx CRT in " + binpath.getFullLocation() );

   // open the binary path in search of "Microsoft.*.CRT"
   VFSProvider* provider = Engine::getVFS( "file" );
   fassert( provider != 0 );
   
   DirEntry* dir = provider->openDir( binpath.getFullLocation() );
   if( dir == 0 )
   {
      warning( "Can't search CRT in " + binpath.getFullLocation() );
      return false;
   }
   
   String fname;
   while( dir->read(fname) )
   {
      if( fname.wildcardMatch("Microsoft.*.CRT") )
      {
         // we're done with dir.
         delete dir;

         Path source( binpath.getFullLocation() + "/" + fname + "/");
         Path target( tgtpath.getFullLocation() + "/" + fname + "/");
         
         // first, create the target path
         int32 fsStatus;
         if( ! Sys::fal_mkdir( target.getFullLocation(), fsStatus, true ) )
         {
            warning( "Can't create CRT directory in " + target.getFullLocation() );
            return false;
         }

         // then copy everything inside it.
         DirEntry* crtdir = provider->openDir( source.getFullLocation() );
         if( crtdir == 0 )
         {
            warning( "Can't read source CRT directory " + source.getFullLocation() );
            return false;
         }

         //loop copying everything that's not a dir.
         String sFile;
         while( crtdir->read( sFile ) )
         {
            if( sFile.startsWith(".") )
               continue;

            source.setFilename( sFile );
            target.setFilename( sFile );
            if ( ! copyFile( source.get(), target.get() ) )
            {
               delete crtdir;
               warning( "Can't copy CRT file " + source.get() +  " into " 
                  + target.get() );
               return false;
            }
         }

         return true;
      }
   }

   delete dir;
   return false;
}
// connect by address
//  Attempts to connect to one of the Bluetooth devices which has an address
//  stored in the _addresses array.
BC127::opResult BC127::connect(String address, connType connection)
{
  // Before we go any further, we'll do a simple error check on the incoming
  //  address. We know that it should be 12 hex digits, all uppercase; to
  //  minimize execution time and code size, we'll only check that it's 12
  //  characters in length.
  if (address.length() != 12) return INVALID_PARAM;

  // We need a buffer to store incoming data.
  String buffer;
  String EOL = String("\n\r"); // This is just handy.
  
  // Convert our connType enum into the actual string we need to send to the
  //  BC127 module.
  switch(connection)
  {
    case SPP:
      buffer = " SPP";
      break;
    case BLE:
      buffer = " BLE";
      break;
    case A2DP:
      buffer = " A2DP";
      break;
    case AVRCP:
      buffer = " AVRCP";
      break;
    case HFP:
      buffer = " HFP";
      break;
    case PBAP:
      buffer = " PBAP";
      break;
    default:
      buffer = " SPP";
      break;
  }
  
  knownStart(); // Purge serial buffers on both the module and the Arduino.
  
  // Now issue the inquiry command.
  _serialPort->print("OPEN "); 
  _serialPort->print(address);
  _serialPort->print(buffer);
  _serialPort->print("\r");
  // We need to wait until the command finishes before we start looking for a
  //  response; that's what flush() does.
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the connect command. Bog-standard Arduino stuff.
  unsigned long connectStart = millis();
  
  buffer = "";

  // The timeout on this is 5 seconds; that may be a bit long.
  while (connectStart + 5000 > millis())
  {
    // Grow the current buffered data, until we receive the EOL string.    
    if (_serialPort->available() >0) buffer.concat(char(_serialPort->read()));
    
    // At some point, the BC127 response string will contain the EOL string.
    //  Once that happens, we can figure out what the response looks like:
    //  "ERROR" - there's a syntax error in your message to the module; this is
    //    kind of unlikely, although it could happen if you call this function
    //    with an invalid address (something not entirely uppercase hex digits)
    //  "OPEN_ERROR" - most likely, the module can't find any devices with that
    //    address.
    //  "PAIR_ERROR" - the connection was refused by the remote module.
    //  "PAIR_OK" - the connection has been made, but the SPP channel is not
    //    yet open. We should probably just ignore this.
    //  "OPEN_OK" - ready to rock! This is when we should return success.
    if (buffer.endsWith(EOL))
    {
      if (buffer.startsWith("ERROR")) return MODULE_ERROR;
      if (buffer.startsWith("OPEN_ERROR")) return CONNECT_ERROR;
      if (buffer.startsWith("PAIR_ERROR")) return REMOTE_ERROR;
      if (buffer.startsWith("OPEN_OK")) return SUCCESS;
      buffer = "";    
    }
  }
  return TIMEOUT_ERROR;
}
Example #26
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
bool ProgramOptions::parse(const std::vector<String>& commandLineArguments)
{
    const String prefixStr = prefixString();
    const size_t prefixLen = prefixStr.size();

    m_parsedOptions.clear();
    m_positionalParams.clear();
    m_unknownOptions.clear();
    m_optionsWithMissingValues.clear();

    ref<ParsedOption> currParseOption;

    const size_t numCmdLineArgs = commandLineArguments.size();
    size_t ia = 1;
    while (ia < numCmdLineArgs)
    {
        String arg = commandLineArguments[ia];
        arg = arg.trimmed();
        if (arg.isEmpty())
        {
            ia++;
            continue;
        }

        if (arg.startsWith(prefixStr))
        {
            // Finish the option currently being parsed if any
            if (currParseOption.notNull())
            {
                if (currParseOption->hasEnoughValues())
                {
                    addNewParsedOption(currParseOption.p());
                }
                else
                {
                    m_optionsWithMissingValues.push_back(currParseOption->m_spec->m_name);
                }

                currParseOption = NULL;
            }
            
            if (arg.size() > prefixLen)
            {
                const String optName = arg.subString(prefixLen);
                const OptionSpec* optSpec = findOptionSpec(optName);
                if (optSpec)
                {
                    currParseOption = new ParsedOption(optSpec);
                }
                else
                {
                    m_unknownOptions.push_back(optName);
                }
            }
        }
        else
        {
            // Determine if this arg belongs as a value to the option currently being parsed or if it is a positional parameter
            if (currParseOption.notNull())
            {
                // Simple flags should never get here
                CVF_ASSERT(currParseOption->m_spec->m_valueReq != NO_VALUE);

                CVF_ASSERT(currParseOption->canAcceptMoreValues());
                currParseOption->m_values.push_back(arg);
            }
            else
            {
                m_positionalParams.push_back(arg);
            }
        }

        if (currParseOption.notNull())
        {
            if (!currParseOption->canAcceptMoreValues())
            {
                addNewParsedOption(currParseOption.p());
                currParseOption = NULL;
            }
        }
        
        ia++;
    }

    // Finish the option currently being parsed if any
    if (currParseOption.notNull())
    {
        if (currParseOption->hasEnoughValues())
        {
            addNewParsedOption(currParseOption.p());
        }
        else
        {
            m_optionsWithMissingValues.push_back(currParseOption->m_spec->m_name);
        }

        currParseOption = NULL;
    }


    if (m_unknownOptions.empty() && m_optionsWithMissingValues.empty())
    {
        return true;
    }
    else
    {
        return false;
    }
}
// There are times when it is useful to be able to know whether or not the
//  module is connected; this function will tell you whether or not the module
//  is connected with a certain protocol, or if it is connected at all. This is
//  particularly challenging; the strings coming from the module are so fast,
//  even at 9600 baud, that you don't really have time to parse them. The only
//  solution I've been able to come up with is to just let the buffer overflow
//  and give up on identifying connections by type.
BC127::opResult BC127::connectionState()
{
  String buffer;
  String EOL = String("\n\r");
  
  opResult retVal = TIMEOUT_ERROR;
  
  knownStart();
  
  _serialPort->print("STATUS");
  _serialPort->print("\r");
  _serialPort->flush();
  
  // We're going to use the internal timer to track the elapsed time since we
  //  issued the command. Bog-standard Arduino stuff.
  unsigned long startTime = millis();
  
  // This is our timeout loop. We'll give the module 500 milliseconds.
  //  Note: if you have more than one active connection this WILL overflow a
  //  software serial buffer. Working under this assumption, we're going to
  //  try and deal with both the overflow and no overflow case gracefully. I'm
  //  also removing the ability to check on a specific connection type, since
  //  that's what causes the overflow.
  while ((startTime + 500) > millis())
  {  
    // Grow the current buffered data, until we receive the EOL string.  
    while (_serialPort->available() > 0) 
    {
      char temp = _serialPort->read();
      buffer.concat(temp);
      if (temp = '\r') break;
    }  

    // Parse the current line of text from the module and see what we find out.
    if (buffer.endsWith(EOL))
    {
      // If the current line starts with "STATE", we need more parsing. This is
      //  also the only guaranteed result.
      if (buffer.startsWith("ST"))
      {
        // If "CONNECTED" is in the received string, we know we're connected,
        //  but not if we're connected with the particular profile we're
        //  interested in. So, we need to consider a bit further.
        if (buffer.substring(13, 15) == "ED") retVal = SUCCESS;
        // If "CONNECTED" *isn't* there, we want to return an appropriate error.
        else retVal = CONNECT_ERROR;
      }
      // If we ARE connected, we'll get a list of different link types. We'll
      //  want to parse over those and see if the profile we want is in it. If
      //  it is, we can call it a success; if not, do nothing.
      
      // NB This is commented out, because we'll always overflow the soft serial
      //  buffer if we have more than one type of connection open. I'm leaving
      //  it in just in case somebody wants to use it in a "hardware-only" mode.
      /*
      if (buffer.startsWith("LI"))
      {
        switch(connection)
        {
          case SPP:
            if (buffer.substring(17,19) == "SP") retVal = SUCCESS;
            break;
          case BLE:
            if (buffer.substring(17,19) == "BL") retVal = SUCCESS;
            break;
          case A2DP:
            if (buffer.substring(17,19) == "A2") retVal = SUCCESS;
            break;
          case HFP:
            if (buffer.substring(17,19) == "HF") retVal = SUCCESS;
            break;
          case AVRCP:
            if (buffer.substring(17,19) == "AV") retVal = SUCCESS;
            break;
          case PBAP:
            if (buffer.substring(17,19) == "PB") retVal = SUCCESS;
            break;
          case ANY:
          default:
            break;
        }
      }
      */
      // If by some miracle we *do* get to this point without a buffer overflow,
      //  we're safe to return without a buffer purge.
      if (buffer.startsWith("OK")) return retVal;
      buffer = "";
    }
  }
  // Okay, now we need to clean up our input buffer on the serial port. After
  //  all, we can be pretty sure that an overflow happened, and there's crap in
  //  the buffer.
  while (_serialPort->available() > 0) _serialPort->read();
  return retVal;
}
void SVGSVGElement::setupInitialView(const String& fragmentIdentifier, Element* anchorNode)
{
    LayoutObject* layoutObject = this->layoutObject();
    SVGViewSpec* view = m_viewSpec.get();
    if (view)
        view->reset();

    bool hadUseCurrentView = m_useCurrentView;
    m_useCurrentView = false;

    if (fragmentIdentifier.startsWith("xpointer(")) {
        // FIXME: XPointer references are ignored (https://bugs.webkit.org/show_bug.cgi?id=17491)
        if (layoutObject && hadUseCurrentView)
            markForLayoutAndParentResourceInvalidation(layoutObject);
        return;
    }

    if (fragmentIdentifier.startsWith("svgView(")) {
        if (!view)
            view = currentView(); // Create the SVGViewSpec.

        view->inheritViewAttributesFromElement(this);

        if (view->parseViewSpec(fragmentIdentifier))
            m_useCurrentView = true;
        else
            view->reset();

        if (layoutObject && (hadUseCurrentView || m_useCurrentView))
            markForLayoutAndParentResourceInvalidation(layoutObject);
        return;
    }

    // Spec: If the SVG fragment identifier addresses a 'view' element within an SVG document (e.g., MyDrawing.svg#MyView
    // or MyDrawing.svg#xpointer(id('MyView'))) then the closest ancestor 'svg' element is displayed in the viewport.
    // Any view specification attributes included on the given 'view' element override the corresponding view specification
    // attributes on the closest ancestor 'svg' element.
    // TODO(ed): The spec text above is a bit unclear.
    // Should the transform from outermost svg to nested svg be applied to "display"
    // the inner svg in the viewport, then let the view element override the inner
    // svg's view specification attributes. Should it fill/override the outer viewport?
    if (isSVGViewElement(anchorNode)) {
        SVGViewElement& viewElement = toSVGViewElement(*anchorNode);

        if (SVGSVGElement* svg = viewElement.ownerSVGElement()) {
            svg->inheritViewAttributes(&viewElement);

            if (LayoutObject* layoutObject = svg->layoutObject())
                markForLayoutAndParentResourceInvalidation(layoutObject);

            return;
        }
    }

    // If we previously had a view and didn't get a new one, we need to
    // layout again.
    if (layoutObject && hadUseCurrentView)
        markForLayoutAndParentResourceInvalidation(layoutObject);

    // FIXME: We need to decide which <svg> to focus on, and zoom to it.
    // FIXME: We need to actually "highlight" the viewTarget(s).
}
Example #29
0
bool SVGSMILElement::parseCondition(const String& value, BeginOrEnd beginOrEnd)
{
    String parseString = value.stripWhiteSpace();
    
    double sign = 1.;
    bool ok;
    size_t pos = parseString.find('+');
    if (pos == notFound) {
        pos = parseString.find('-');
        if (pos != notFound)
            sign = -1.;
    }
    String conditionString;
    SMILTime offset = 0;
    if (pos == notFound)
        conditionString = parseString;
    else {
        conditionString = parseString.left(pos).stripWhiteSpace();
        String offsetString = parseString.substring(pos + 1).stripWhiteSpace();
        offset = parseOffsetValue(offsetString);
        if (offset.isUnresolved())
            return false;
        offset = offset * sign;
    }
    if (conditionString.isEmpty())
        return false;
    pos = conditionString.find('.');
    
    String baseID;
    String nameString;
    if (pos == notFound)
        nameString = conditionString;
    else {
        baseID = conditionString.left(pos);
        nameString = conditionString.substring(pos + 1);
    }
    if (nameString.isEmpty())
        return false;

    Condition::Type type;
    int repeats = -1;
    if (nameString.startsWith("repeat(") && nameString.endsWith(')')) {
        // FIXME: For repeat events we just need to add the data carrying TimeEvent class and 
        // fire the events at appropiate times.
        repeats = nameString.substring(7, nameString.length() - 8).toUIntStrict(&ok);
        if (!ok)
            return false;
        nameString = "repeat";
        type = Condition::EventBase;
    } else if (nameString == "begin" || nameString == "end") {
        if (baseID.isEmpty())
            return false;
        type = Condition::Syncbase;
    } else if (nameString.startsWith("accesskey(")) {
        // FIXME: accesskey() support.
        type = Condition::AccessKey;
    } else
        type = Condition::EventBase;
    
    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset, repeats));

    if (type == Condition::EventBase && beginOrEnd == End)
        m_hasEndEventConditions = true;

    return true;
}
Example #30
0
// parseDataUrl() is taken from the CURL http backend.
static gboolean parseDataUrl(gpointer callbackData)
{
    ResourceHandle* handle = static_cast<ResourceHandle*>(callbackData);
    ResourceHandleClient* client = handle->client();
    ResourceHandleInternal* d = handle->getInternal();
    if (d->m_cancelled)
        return false;

    d->m_idleHandler = 0;

    ASSERT(client);
    if (!client)
        return false;

    String url = handle->request().url().string();
    ASSERT(url.startsWith("data:", false));

    int index = url.find(',');
    if (index == -1) {
        client->cannotShowURL(handle);
        return false;
    }

    String mediaType = url.substring(5, index - 5);
    String data = url.substring(index + 1);

    bool isBase64 = mediaType.endsWith(";base64", false);
    if (isBase64)
        mediaType = mediaType.left(mediaType.length() - 7);

    if (mediaType.isEmpty())
        mediaType = "text/plain;charset=US-ASCII";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    ResourceResponse response;
    response.setURL(handle->request().url());
    response.setMimeType(mimeType);

    if (isBase64) {
        data = decodeURLEscapeSequences(data);
        response.setTextEncodingName(charset);
        client->didReceiveResponse(handle, response);

        // The load may be cancelled, and the client may be destroyed
        // by any of the client reporting calls, so we check, and bail
        // out in either of those cases.
        if (d->m_cancelled || !handle->client())
            return false;

        // Use the GLib Base64, since WebCore's decoder isn't
        // general-purpose and fails on Acid3 test 97 (whitespace).
        size_t outLength = 0;
        char* outData = 0;
        outData = reinterpret_cast<char*>(g_base64_decode(data.utf8().data(), &outLength));
        if (outData && outLength > 0)
            client->didReceiveData(handle, outData, outLength, 0);
        g_free(outData);
    } else {
        // We have to convert to UTF-16 early due to limitations in KURL
        data = decodeURLEscapeSequences(data, TextEncoding(charset));
        response.setTextEncodingName("UTF-16");
        client->didReceiveResponse(handle, response);

        if (d->m_cancelled || !handle->client())
            return false;

        if (data.length() > 0)
            client->didReceiveData(handle, reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);
    }

    if (d->m_cancelled || !handle->client())
        return false;

    client->didFinishLoading(handle);

    return false;
}