void Nuclide::setIsomerEnergy() { if ( st == 0 ) return; extractValue(full_data,39,46,is_nrg); // Some isomers(3 in total) are measured via beta difference so come out -ve is_nrg = fabs(is_nrg); extractValue(full_data,48,56,dis_nrg); }
void Settings::update() { std::string name; std::string value; m_values.clear(); std::ifstream settings(m_fileName.c_str()); if (!settings.is_open()) { std::cout << "Failed to open " << m_fileName << "\n"; return; } do { std::getline(settings, m_rawStr); m_index = 0; name = extractKey(); value = extractValue(); // Add name-value pair to map m_values[name] = value; } while (!settings.eof()); settings.close(); std::cout << "Settings loaded from " << m_fileName << "\n"; }
bool JsonParser::extractElement(JsonNode &node, char terminator) { if (!extractValue(node)) return false; if (!extractWhitespace()) return false; bool comma = (input[pos] == ','); if (comma ) { pos++; if (!extractWhitespace()) return false; } if (input[pos] == terminator) { //FIXME: MOD COMPATIBILITY: Too many of these right now, re-enable later //if (comma) //error("Extra comma found!", true); return true; } if (!comma) error("Comma expected!", true); return true; }
JsonNode JsonParser::parse(std::string fileName) { JsonNode root; if (input.size() == 0) { error("File is empty", false); } else { if (!Unicode::isValidString(&input[0], input.size())) error("Not a valid UTF-8 file", false); extractValue(root); extractWhitespace(false); //Warn if there are any non-whitespace symbols left if (pos < input.size()) error("Not all file was parsed!", true); } if (!errors.empty()) { logGlobal->warnStream()<<"File " << fileName << " is not a valid JSON file!"; logGlobal->warnStream()<<errors; } return root; }
static Variant HHVM_METHOD(ResourceBundle, next) { FETCH_RSRC(data, this_); if (!data->iterNext()) { return init_null(); } UErrorCode error = U_ZERO_ERROR; return extractValue(data, data->iterCurrent(error)); }
void Nuclide::setHalfLife() { std::string lifetime; lifetime = (full_data.size() < 59) ? "no_units" : full_data.substr(60,9); if ( lifetime.find("p-unst") != std::string::npos || lifetime.find_first_not_of(" ") == std::string::npos || lifetime.find("R") != std::string::npos ) { lifetime = "no_units"; } size_t found = lifetime.find_first_of("<>~"); if ( found != std::string::npos ) { lifetime.at(found) = ' '; } extractValue(lifetime,0,9,hl); if ( hl < 0.0001 ) { hl = (lifetime == "no_units") ? 1.0e-24 : 1.0e24; } else { std::string halfLifeUnit = full_data.substr(69,2); if( halfLifeUnit.find_first_not_of(' ') == std::string::npos ) { halfLifeUnit = "ys"; } if (halfLifeUnit == "ys") hl*=1.0e-24; else if (halfLifeUnit == "zs") hl*=1.0e-21; else if (halfLifeUnit == "as") hl*=1.0e-18; else if (halfLifeUnit == "ps") hl*=1.0e-12; else if (halfLifeUnit == "ns") hl*=1.0e-09; else if (halfLifeUnit == "us") hl*=1.0e-06; else if (halfLifeUnit == "ms") hl*=1.0e-03; else if (halfLifeUnit == " s") hl*=1.0; else if (halfLifeUnit == " m") hl*=60.0; else if (halfLifeUnit == " h") hl*=3600.0; else if (halfLifeUnit == " d") hl*=86400.0; else if (halfLifeUnit == " y") hl*=31557600.0; else if (halfLifeUnit == "ky") hl*=31557600*1.0e03; else if (halfLifeUnit == "My") hl*=31557600*1.0e06; else if (halfLifeUnit == "Gy") hl*=31557600*1.0e09; else if (halfLifeUnit == "Ty") hl*=31557600*1.0e12; else if (halfLifeUnit == "Py") hl*=31557600*1.0e15; else if (halfLifeUnit == "Ey") hl*=31557600*1.0e18; else if (halfLifeUnit == "Zy") hl*=31557600*1.0e21; else if (halfLifeUnit == "Yy") hl*=31557600*1.0e24; } }
virtual void output(Entity* entity, QIODevice& file) const{ auto v = extractValue(DOCUMENT_IMAGE); for(auto e : v.keys()) { qDebug() << e << "," << v.value(e) << '\n'; } }
double DurationSpinBox::valueFromText( const QString & text ) const { QString s = extractValue( text ).remove( KGlobal::locale()->thousandsSeparator() ); bool ok = false; double v = KGlobal::locale()->readNumber( s, &ok ); if ( ! ok ) { v = QDoubleSpinBox::valueFromText( s ); } return v; }
void handleServerMessage(char * message) { char * str; if (strstr(message, "ERROR") != NULL) { state = 0; printf("Error while Registering"); } else if (strstr(message, "Registered") != NULL) { state = 1; printf("Registered Successfully"); } else if (strstr(message, "Switch") != NULL) { str = extractValue(message); if (strcmp(str,"ON") == 0) { state = 1; } else { state = 0; } } else if (strstr(message, "setInterval") != NULL) { str = extractValue(message); interval = atoi(str); } }
/* * Extract 8bit Value to operand1 * * Operation: * if nothing is throw * * Return: * operand1 value * */ int operand1ExtractValue(String *arguments) { ErrorCode error; int operand1; Try{ operand1 = extractValue(arguments); } Catch(error) { Throw(error); } return operand1; }
//--------------------------------------------------- bool skInterpreter::extractFieldArrayValue(skStackFrame& frame,skRValue& robject,const skString& field_name,skExprNode * array_index,const skString& attrib,skRValue& ret) //--------------------------------------------------- { skRValue array_field; SAVE_VARIABLE(array_field); skString blank; bool found=extractValue(frame,robject,field_name,blank,array_field); if (found) { extractArrayValue(frame,array_field,array_index,attrib,ret); } RELEASE_VARIABLE(array_field); return found; }
/** * * operand1ExtractValue * * Try to get the operand1 and return operand1. Catch e and throw error. * * Input : * arguements * * Return : * operand1 * **/ int operand1ExtractValue(String *arguments){ int operand1; ErrorCode e; Try{ operand1 = extractValue(arguments); }Catch(e){ printf("Error operand1 Throw"); Throw(e); } return operand1; }
bool VehicleParam::readLine(std::ifstream& ifs, std::string identifyName, float& outValue) { std::string str; do { std::getline(ifs, str); if (ifs.eof()) return false; } while (str.empty());//jump over the null line return extractValue(str, identifyName, outValue); }
void NCDParser::publishLaserMessage(const std::vector<std::string>& tokens, const std::string& laserFrame, const ros::Publisher& publisher) { ROS_DEBUG("Laser message"); sensor_msgs::LaserScan scan; double time = extractValue(tokens[3], "time="); scan.header.stamp = ros::Time(time); scan.header.frame_id = laserFrame; scan.angle_min = extractValue(tokens[3], "minAngle=") * DEG_TO_RAD; scan.angle_max = extractValue(tokens[3], "maxAngle=") * DEG_TO_RAD; scan.angle_increment = extractValue(tokens[3], "angRes=") * DEG_TO_RAD; scan.range_min = RANGE_MIN; scan.range_max = RANGE_MAX; scan.ranges = extractArray(tokens[3], "Range=[181]"); scan.intensities = extractArray(tokens[3], "Reflectance=[181]"); publisher.publish(scan); }
void NCDParser::publishTfMessages(const std::vector<std::string>& tokens) { ROS_DEBUG("Tf message"); // extract time double time = extractValue(tokens[3], "time="); // extract x, y, theta std::vector<float> xytheta = extractArray(tokens[3], "Pose=[3x1]"); double x = xytheta[0]; double y = xytheta[1]; double z = 0.0; double theta = xytheta[2]; // extract Pitch double pitch = extractValue(tokens[3], "Pitch="); // extract Roll double roll = extractValue(tokens[3], "Roll="); btQuaternion rotation; rotation.setRPY (roll, pitch, theta); worldToOdom_.setRotation (rotation); btVector3 origin; origin.setValue (x, y, z); worldToOdom_.setOrigin (origin); tf::StampedTransform worldToOdomStamped(worldToOdom_, ros::Time(time), worldFrame_, odomFrame_); tfBroadcaster_.sendTransform(worldToOdomStamped); tf::StampedTransform odomToLeftLaserStamped(odomToLeftLaser_, ros::Time(time), odomFrame_, leftLaserFrame_); tfBroadcaster_.sendTransform(odomToLeftLaserStamped); tf::StampedTransform odomToRightLaserStamped(odomToRightLaser_, ros::Time(time), odomFrame_, rightLaserFrame_); tfBroadcaster_.sendTransform(odomToRightLaserStamped); }
static Variant HHVM_METHOD(ResourceBundle, get, const Variant& index, bool fallback) { FETCH_RSRC(data, this_); UErrorCode error = U_ZERO_ERROR; icu::ResourceBundle child(error); if (U_FAILURE(error)) { data->setError(error, "Unable to generate default resource bundle"); return false; } if (index.isInteger()) { child = data->resource()->get((int32_t)index.toInt64(), error); if (U_FAILURE(error)) { data->setError(error, "Cannot load resource element %d", (int)index.toInt64()); return init_null(); } } else if (index.isString()) { child = data->resource()->get(index.toString().c_str(), error); if (U_FAILURE(error)) { data->setError(error, "Cannot load resource element '%s'", index.toString().c_str()); return init_null(); } } else { data->setError(U_ILLEGAL_ARGUMENT_ERROR, "resourcebundle_get: index should be integer or string"); return init_null(); } if (!fallback && ((error == U_USING_FALLBACK_WARNING) || (error == U_USING_DEFAULT_WARNING))) { UErrorCode dummy = U_ZERO_ERROR; auto locale = data->resource()->getLocale(ULOC_ACTUAL_LOCALE, dummy); if (index.isInteger()) { data->setError(error, "Cannot load element %d without fallback from to %s", (int)index.toInt64(), locale.getName()); } else { data->setError(error, "Cannot load element %s without fallback from to %s", index.toString().c_str(), locale.getName()); } return init_null(); } return extractValue(data, child); }
virtual void output(Entity* entity, QIODevice& iodevice) const{ auto v = extractValue(EYOU_TAG); QString url = v["URL"]; if (url.isEmpty()){ return; } // <iframe width="560" height="315" src="https://www.youtube.com/embed/vlDYoATH_jI" frameborder="0" allowfullscreen></iframe> //<iframe width="560" height="315" src="https://www.youtube.com/embed/vlDYoATH_jI" frameborder="0" allowfullscreen> // <iframe width="560" height="315" src="https://youtu.be/vlDYoATH_jI" frameborder="0" allowfullscreen></iframe> iodevice.write(QString("<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/").append(url).append("\" frameborder=\"0\" allowfullscreen></iframe>").toUtf8()); }
void ConfigFile::extractContents(const std::string &line) { std::string temp = line; temp.erase(0, temp.find_first_not_of("\t ")); size_t sepPos = temp.find('='); std::string key, value; extractKey(key, sepPos, temp); extractValue(value, sepPos, temp); if (!keyExists(key)) contents.insert(std::pair<std::string, std::string > (key, value)); else std::cout << "CFG: Can only have unique key names!\n" << std::endl; }
//--------------------------------------------------- void skInterpreter::makeMethodCall(skStackFrame& frame,skRValue& robject,const skString& method_name,skExprNode * array_index,const skString& attribute, skExprListNode * exprs,skRValue& ret) //--------------------------------------------------- { skString checked_method_name=checkIndirectId(frame,method_name); if (robject.type()==skRValue::T_Object) { skRValueArray args; SAVE_VARIABLE(robject); skExprListIterator iter(exprs->getExprs()); skExprNode * expr=0; while ((expr=iter())!=0) { #ifndef EXCEPTIONS_DEFINED if (frame.getContext().getError().getErrorCode()!=skScriptError::NONE) break; #endif args.append(evaluate(frame,expr)); } #ifndef EXCEPTIONS_DEFINED if (frame.getContext().getError().getErrorCode()==skScriptError::NONE) { #endif if (m_Tracing) trace(skString::addStrings(frame.getLocation().ptr(),s_colon,skString::from(frame.getLineNum()+1).ptr(),s_colon,checked_method_name.ptr(),s_FunctionEnd)); // call to this object bool bRet=robject.obj()->method(checked_method_name,args,ret,frame.getContext()); if (bRet==false) runtimeError(frame,skString::addStrings(s_MethodStart,checked_method_name.ptr(),s_NotFound)); // case foo()[i] if (array_index) { skRValue array_value; bRet=extractArrayValue(frame,ret,array_index,attribute,array_value); ret=array_value; } else { // case foo():attr if (attribute.length()) { skRValue attr_value; skString blank; bRet=extractValue(frame,ret,blank,attribute,attr_value); ret=attr_value; } } #ifndef EXCEPTIONS_DEFINED } #endif RELEASE_VARIABLE(robject); } else { runtimeError(frame,skString::addStrings(s_CannotCallMethod,checked_method_name.ptr(),s_OnANonObject)); } }
/* * Extract 3 bit value to operand2 * * Operation: * To Catch No Argument and Empty Argument Value,extract value * * Throw: * NO argument * Not empty argument but illegal argument * * Return: * operand2 value * */ int extract3BitsValue(String *arguments){ ErrorCode error; int operand2; Try{ operand2 = extractValue(arguments); }Catch(error){ if(error == ERR_NO_ARGUMENT){ Throw(error); }else if(error != ERR_EMPTY_ARGUMENT){ if(error == ERR_ILLEGAL_ARGUMENT){ Throw(error); } } } return operand2; }
QValidator::State DurationSpinBox::validate ( QString & input, int & pos ) const { //kDebug(planDbg())<<input; KDoubleValidator validator( minimum(), maximum(), decimals(), 0 ); if ( input.isEmpty() ) { return validator.validate ( input, pos ); } QString s = extractUnit( input ); if ( s.isEmpty() ) { return validator.validate ( input, pos ); } int idx = Duration::unitList( true ).indexOf( s ); if ( idx < m_maxunit || idx > m_minunit ) { return QValidator::Invalid; } s = extractValue( input ); int p = 0; return validator.validate ( s, p ); // pos doesn't matter }
void Config::extractLine(const std::string& section, const std::string& line, std::ifstream& file, int& lineNb) { std::string temp = line; temp.erase(0, temp.find_first_not_of(" \t\r\n\v\f")); size_t sepPos = temp.find('='); std::string key; std::string value; extractKey(key, sepPos, temp); key = section.substr(1, section.length()-2) + "." + key; extractValue(value, sepPos, temp); if (!isKeyExists(key)) { _map.insert(std::pair<std::string, std::string>(key, value)); } else { Log(LOG_TYPE::ERROR) << "Config: Can only have unique key names!"; } }
int operandExtract1BitsValue(String *arguments){ ErrorCode e; int operand1; Try{ operand1 = extractValue(arguments); }Catch(e){ if(e == ERR_NO_ARGUMENT || e == ERR_EMPTY_ARGUMENT){ operand1 = 0; return operand1; }else if(e == ERR_ILLEGAL_ARGUMENT){ Throw(e); } } operand1 = operand1 & 0x01; return operand1; }
void ConfigFile::extractContents(const std::string &line) { // called from parse_line(), validated there std::string tmp = line; // remove leading whitespace tmp.erase(0, tmp.find_first_not_of("\t ")); size_t sep_pos = tmp.find('='); std::string key, value; extractKey(key, sep_pos, tmp); extractValue(value, sep_pos, tmp); if (!containsKey(key)) { contents.insert(std::pair<std::string, std::string>(key, value)); } else { ConfigUtil::warn(key + " was declared at least twice in configuration file."); } }
//--------------------------------------------------- void skInterpreter::followIdList(skStackFrame& frame,skIdListNode * idList,skRValue& object) //--------------------------------------------------- { skString blank; // skip down the id.id.id list, resolving each as we go along, we exclude the final id in the list skIdNode * idNode=idList->getId(0); skString name=idNode->getId(); // trace("followIdList: %s - %d ids\n",(const char *)name,idList->m_Ids.entries()); if (idNode->getExprs()==0) object=findValue(frame,name,idNode->getArrayIndex(),blank); else { skRValue caller; SAVE_VARIABLE(caller); caller.assignObject(frame.getObject(),false); makeMethodCall(frame,caller,name,idNode->getArrayIndex(),blank,idNode->getExprs(),object); RELEASE_VARIABLE(caller); } for (unsigned int i=1; i<idList->numIds()-1; i++) { #ifndef EXCEPTIONS_DEFINED if (frame.getContext().getError().getErrorCode()!=skScriptError::NONE) break; #endif idNode=idList->getId(i); name=idNode->getId(); name=checkIndirectId(frame,name); // trace("followIdList: %d: %s\n",i,(const char *)name); skRValue result; SAVE_VARIABLE(result); if (idNode->getExprs()==0) { if (idNode->getArrayIndex()) extractFieldArrayValue(frame,object,name,idNode->getArrayIndex(),blank,result); else if (extractValue(frame,object,name,blank,result)==false) runtimeError(frame,skString::addStrings(s_FieldError,name.ptr(),s_cr)); } else makeMethodCall(frame,object,name,idNode->getArrayIndex(),blank,idNode->getExprs(),result); object=result; RELEASE_VARIABLE(result); } }
/** * Read attributes of a node. * @param initialArgs Tokens on the line of the opening "(" of the node * but with leading whitespace and the opening "(" removed. * @param stream The QTextStream from which to read following lines. * @return Pointer to the created PetalNode or NULL on error. */ PetalNode *readAttributes(QStringList initialArgs, QTextStream& stream) { methodName(QLatin1String("readAttributes")); if (initialArgs.count() == 0) { uError() << loc() << "initialArgs is empty"; return NULL; } PetalNode::NodeType nt; QString type = shift(initialArgs); if (type == QLatin1String("object")) nt = PetalNode::nt_object; else if (type == QLatin1String("list")) nt = PetalNode::nt_list; else { uError() << loc() << "unknown node type " << type; return NULL; } PetalNode *node = new PetalNode(nt); bool seenClosing = checkClosing(initialArgs); node->setInitialArgs(initialArgs); if (seenClosing) return node; PetalNode::NameValueList attrs; QString line; while (!(line = stream.readLine()).isNull()) { linum++; line = line.trimmed(); if (line.isEmpty()) continue; QStringList tokens = scan(line); QString stringOrNodeOpener = shift(tokens); QString name; if (nt == PetalNode::nt_object && !stringOrNodeOpener.contains(QRegExp(QLatin1String("^[A-Za-z]")))) { uError() << loc() << "unexpected line " << line; delete node; return NULL; } PetalNode::StringOrNode value; if (nt == PetalNode::nt_object) { name = stringOrNodeOpener; if (tokens.count() == 0) { // expect verbatim text to follow on subsequent lines value.string = collectVerbatimText(stream); PetalNode::NameValue attr(name, value); attrs.append(attr); if (nClosures) { // Decrement nClosures exactly once, namely for the own scope. // Each recursion of readAttributes() is only responsible for // its own scope. I.e. each further scope closing is handled by // an outer recursion in case of multiple closing parentheses. nClosures--; break; } continue; } stringOrNodeOpener = shift(tokens); } else if (stringOrNodeOpener != QLatin1String("(")) { value.string = stringOrNodeOpener; PetalNode::NameValue attr; attr.second = value; attrs.append(attr); if (tokens.count() && tokens.first() != QLatin1String(")")) { uDebug() << loc() << "NYI - immediate list entry with more than one item"; } if (checkClosing(tokens)) break; continue; } if (stringOrNodeOpener == QLatin1String("(")) { QString nxt = tokens.first(); if (isImmediateValue(nxt)) { value.string = extractImmediateValues(tokens); } else if (nxt == QLatin1String("value") || nxt.startsWith(QLatin1Char('"'))) { value.string = extractValue(tokens, stream); } else { value.node = readAttributes(tokens, stream); if (value.node == NULL) { delete node; return NULL; } } PetalNode::NameValue attr(name, value); attrs.append(attr); if (nClosures) { // Decrement nClosures exactly once, namely for the own scope. // Each recursion of readAttributes() is only responsible for // its own scope. I.e. each further scope closing is handled by // an outer recursion in case of multiple closing parentheses. nClosures--; break; } } else { value.string = stringOrNodeOpener; bool seenClosing = checkClosing(tokens); PetalNode::NameValue attr(name, value); attrs.append(attr); if (seenClosing) { break; } } } node->setAttributes(attrs); return node; }
void NCDParser::launch() { std::ifstream aLogFile; aLogFile.open(filename_); if(!aLogFile.is_open()) ROS_FATAL("Could not open %s\n", filename_); int lineCounter = 0; std::string line; // **** skip first lines for (int i = 0; i < 210; i++) { getline(aLogFile, line); lineCounter++; } // **** iterate over rest of file while (getline(aLogFile, line)) { lineCounter++; std::vector<std::string> tokens; tokenize(line, tokens, " "); // skip incomplete line if (tokens.size() < 4) continue; // skip log entries before start time if (strtod(tokens[0].c_str(), NULL) <= start_) continue; // stop if time is bigger than end point time if (strtod(tokens[0].c_str(), NULL) > end_ && end_ != -1) { std::cout << strtod(tokens[0].c_str(), NULL) << ", " << end_ << std::endl; ROS_INFO("Reached specified end time."); break; } // publish messages if (tokens[1].compare("LMS_LASER_2D_LEFT") == 0) publishLaserMessage(tokens, leftLaserFrame_, leftLaserPublisher_); else if (tokens[1].compare("LMS_LASER_2D_RIGHT") == 0) publishLaserMessage(tokens, rightLaserFrame_, rightLaserPublisher_); else if (tokens[1].compare("ODOMETRY_POSE") == 0) publishTfMessages(tokens); else continue; // wait before publishing next message double time = extractValue(tokens[3], "time="); if(lastTime_ == -1) lastTime_ = time; else { ros::Duration d = (ros::Time(time) - ros::Time(lastTime_)) * ( 1.0 / rate_); lastTime_ = time; if (d.toNSec() > 0) d.sleep(); } } }
//--------------------------------------------------- skRValue skInterpreter::evaluate(skStackFrame& frame,skExprNode * n) //--------------------------------------------------- { skRValue r; skString blank; SAVE_VARIABLE(r); skRValue item1; SAVE_VARIABLE(item1); skRValue item2; SAVE_VARIABLE(item2); switch(n->getType()) { case s_IdList: { skIdListNode * ids=(skIdListNode *)n; skIdNode * idNode=ids->getLastId(); skString method_name; SAVE_VARIABLE(method_name); method_name=idNode->getId(); if (ids->numIds()==1) { if (idNode->getExprs()==0) r=findValue(frame,method_name,idNode->getArrayIndex(),ids->getAttribute()); else { skRValue caller; caller.assignObject(frame.getObject()); makeMethodCall(frame,caller,method_name,idNode->getArrayIndex(),ids->getAttribute(),idNode->getExprs(),r); } } else { method_name=checkIndirectId(frame,method_name); skRValue robject; SAVE_VARIABLE(robject); followIdList(frame,ids,robject); if (idNode->getExprs()==0) { if (idNode->getArrayIndex()) { skRValue array_field; if (extractValue(frame,robject,method_name,blank,array_field)) extractArrayValue(frame,array_field,idNode->getArrayIndex(),ids->getAttribute(),r); else runtimeError(frame,skString::addStrings(s_FieldError,method_name.ptr(),s_cr)); } else if (extractValue(frame,robject,method_name,ids->getAttribute(),r)==false) runtimeError(frame,skString::addStrings(s_FieldError,method_name.ptr(),s_cr)); } else makeMethodCall(frame,robject,method_name,idNode->getArrayIndex(),ids->getAttribute(),idNode->getExprs(),r); RELEASE_VARIABLE(robject); } RELEASE_VARIABLE(method_name); break; } case s_String: r=skRValue(((skLiteralNode *)n)->getString()); break; case s_Integer: r=skRValue(((skLiteralNode *)n)->getInt()); break; case s_Character: r=skRValue(((skLiteralNode *)n)->getChar()); break; #ifdef USE_FLOATING_POINT case s_Float: r=skRValue(((skLiteralNode *)n)->getFloat()); break; #endif default: { skOpNode * opNode=(skOpNode *)n; item1=evaluate(frame,opNode->getExpr1()); int item1Type=item1.type(); switch(n->getType()) { case s_Not: r=bool(!item1.boolValue()); break; case s_And: r=bool(item1.boolValue() && evaluate(frame,opNode->getExpr2()).boolValue()); break; case s_Or: r=bool(item1.boolValue() || evaluate(frame,opNode->getExpr2()).boolValue()); break; case s_Equals: r=bool(item1 == evaluate(frame,opNode->getExpr2())); break; case s_NotEquals: { bool equals=item1 == evaluate(frame,opNode->getExpr2()); if (equals) r=false; else r=true; break; } case s_Minus: if (item1Type==skRValue::T_Float) r=skRValue(-item1.floatValue()); else r=skRValue((-item1.intValue())); break; case s_Concat: r=skRValue(skString::addStrings(item1.str(),evaluate(frame,opNode->getExpr2()).str())); break; default: { item2=evaluate(frame,opNode->getExpr2()); int item2Type=item2.type(); if (item1Type==skRValue::T_Int && item2Type==skRValue::T_Int) { // we can use integer arithmetic if both objects are integer int val1=item1.intValue(); int val2=item2.intValue(); switch(opNode->getType()) { case s_Plus: r=skRValue(val1+val2); break; case s_More: r=bool(val1>val2); break; case s_MoreEqual: r=bool(val1>=val2); break; case s_Less: r=bool(val1<val2); break; case s_LessEqual: r=bool(val1<=val2); break; case s_Subtract: r=skRValue(val1-val2); break; case s_Divide: { long top=val1; long bottom=val2; if (bottom) r=skRValue((int)(top/bottom)); else { r=skRValue((int)1); runtimeError(frame,skSTR("Divide by zero error")); } break; } case s_Mult: r=skRValue(val1*val2); break; case s_Mod: r=skRValue(val1 % val2); break; } } else { // in all other cases we using floating point float val1=item1.floatValue(); float val2=item2.floatValue(); switch(opNode->getType()) { case s_Plus: r=skRValue(val1+val2); break; case s_More: r=bool(val1>val2); break; case s_MoreEqual: r=bool(val1>=val2); break; case s_Less: r=bool(val1<val2); break; case s_LessEqual: r=bool(val1<=val2); break; case s_Subtract: r=skRValue(val1-val2); break; case s_Divide: { double top=val1; double bottom=val2; if (bottom) r=skRValue((float)(top/bottom)); else { r=skRValue(1.0f); runtimeError(frame,skSTR("Divide by zero error")); } break; } case s_Mult: r=skRValue(val1*val2); break; case s_Mod: r=skRValue((int)((long)val1 % (long)val2)); break; } } } } } } RELEASE_VARIABLE(item2); RELEASE_VARIABLE(item1); RELEASE_VARIABLE(r); return r; }
/* * ruleMatch * * p: packet data structure, same as the one found in snort. * options: NULL terminated list of rule options * * Returns: * > 0 : match found * = 0 : no match found * * Predefined constants: * (see sf_snort_plugin_api.h for more values) * RULE_MATCH - if asn1 specifier is found within buffer * RULE_NOMATCH - if asn1 specifier is not found within buffer * */ int ruleMatchInternal(SFSnortPacket *p, Rule* rule, u_int32_t optIndex, u_int8_t **cursor) { u_int8_t *thisCursor = NULL, *startCursor = NULL; u_int8_t *tmpCursor = NULL; int retVal = RULE_NOMATCH; u_int32_t notFlag = 0; int thisType; ContentInfo *thisContentInfo = NULL; int startAdjust = 0; u_int32_t origFlags = 0; int32_t origOffset = 0; u_int32_t origDepth = 0; int continueLoop = 1; PCREInfo *thisPCREInfo = NULL; if (cursor) startCursor = thisCursor = *cursor; if (optIndex >= rule->numOptions || !rule->options[optIndex] ) return RULE_NOMATCH; thisType = rule->options[optIndex]->optionType; /* Do some saving off of some info for recursion purposes */ switch (thisType) { case OPTION_TYPE_CONTENT: thisContentInfo = rule->options[optIndex]->option_u.content; origFlags = thisContentInfo->flags; origDepth = thisContentInfo->depth; origOffset = thisContentInfo->offset; break; case OPTION_TYPE_PCRE: thisPCREInfo = rule->options[optIndex]->option_u.pcre; origFlags = thisPCREInfo->flags; break; default: /* Other checks should not need to check again like * PCRE & Content do. */ break; } do { switch (thisType) { case OPTION_TYPE_CONTENT: retVal = contentMatch(p, rule->options[optIndex]->option_u.content, &thisCursor); notFlag = rule->options[optIndex]->option_u.content->flags & NOT_FLAG; break; case OPTION_TYPE_PCRE: retVal = pcreMatch(p, rule->options[optIndex]->option_u.pcre, &thisCursor); notFlag = rule->options[optIndex]->option_u.pcre->flags & NOT_FLAG; break; case OPTION_TYPE_FLOWBIT: retVal = processFlowbits(p, rule->options[optIndex]->option_u.flowBit); notFlag = rule->options[optIndex]->option_u.flowBit->flags & NOT_FLAG; break; case OPTION_TYPE_BYTE_TEST: retVal = byteTest(p, rule->options[optIndex]->option_u.byte, thisCursor); notFlag = rule->options[optIndex]->option_u.byte->flags & NOT_FLAG; break; case OPTION_TYPE_BYTE_JUMP: retVal = byteJump(p, rule->options[optIndex]->option_u.byte, &thisCursor); notFlag = rule->options[optIndex]->option_u.byte->flags & NOT_FLAG; break; case OPTION_TYPE_FLOWFLAGS: retVal = checkFlow(p, rule->options[optIndex]->option_u.flowFlags); notFlag = rule->options[optIndex]->option_u.flowFlags->flags & NOT_FLAG; break; case OPTION_TYPE_ASN1: retVal = detectAsn1(p, rule->options[optIndex]->option_u.asn1, thisCursor); notFlag = rule->options[optIndex]->option_u.asn1->flags & NOT_FLAG; break; case OPTION_TYPE_CURSOR: retVal = checkCursor(p, rule->options[optIndex]->option_u.cursor, thisCursor); notFlag = rule->options[optIndex]->option_u.cursor->flags & NOT_FLAG; break; case OPTION_TYPE_SET_CURSOR: retVal = setCursor(p, rule->options[optIndex]->option_u.cursor, &thisCursor); notFlag = rule->options[optIndex]->option_u.cursor->flags & NOT_FLAG; break; case OPTION_TYPE_HDR_CHECK: retVal = checkHdrOpt(p, rule->options[optIndex]->option_u.hdrData); notFlag = rule->options[optIndex]->option_u.hdrData->flags & NOT_FLAG; break; case OPTION_TYPE_BYTE_EXTRACT: retVal = extractValue(p, rule->options[optIndex]->option_u.byteExtract, thisCursor); notFlag = rule->options[optIndex]->option_u.byteExtract->flags & NOT_FLAG; break; case OPTION_TYPE_LOOP: retVal = loopEval(p, rule->options[optIndex]->option_u.loop, &thisCursor); notFlag = rule->options[optIndex]->option_u.loop->flags & NOT_FLAG; break; case OPTION_TYPE_PREPROCESSOR: retVal = preprocOptionEval(p, rule->options[optIndex]->option_u.preprocOpt, &thisCursor); notFlag = rule->options[optIndex]->option_u.preprocOpt->flags & NOT_FLAG; break; } if ( notFlag ) { if ((retVal <= RULE_NOMATCH)) { /* Set this as a positive match -- a ! was specified. */ retVal = RULE_MATCH; } else /* Match */ { retVal = RULE_NOMATCH; } } if (retVal > RULE_NOMATCH) { /* This one matched. Depending on type, check the next one * either in a loop, or not, saving cursor temporarily. */ if (optIndex < rule->numOptions -1) /* hehe, optIndex is 0 based */ { int nestedRetVal; /* Here's where it gets tricky... */ if (thisType == OPTION_TYPE_CONTENT) { /* If this is a content option, we've found a match. * Save off the end-point of the current match. * Less the length of current match plus 1. * * This gives us the starting point to check for this * content again if subsequent options fail. That starting * point is the byte AFTER the beginning of the current * match. */ if ((origFlags & CONTENT_RELATIVE) && startCursor) { /* relative content. * need to adjust offset/depth as well */ tmpCursor = thisCursor - thisContentInfo->patternByteFormLength + thisContentInfo->incrementLength; /* Start Adjust is the difference between the old * starting point and the 'next' starting point. */ startAdjust = tmpCursor - startCursor; } else { /* non-relative content */ tmpCursor = thisCursor - thisContentInfo->patternByteFormLength + thisContentInfo->incrementLength; } } else if (thisType == OPTION_TYPE_PCRE) { /* Start next search at end of current pattern */ /* XXX: Could miss something here if part of pattern * repeats but not easy to tell with PCRE. */ tmpCursor = thisCursor; } nestedRetVal = ruleMatchInternal(p, rule, optIndex+1, &thisCursor); if (nestedRetVal == RULE_MATCH) { /* Cool, everyone after us matched, we're done with a match */ if (cursor) *cursor = thisCursor; break; } /* If Content or PCRE, look farther into the packet * for another match. */ if (((thisType == OPTION_TYPE_CONTENT) || (thisType == OPTION_TYPE_PCRE)) && !notFlag) { /* Only try to find this content again if it is a * positive match. */ /* And only if the next option is relative */ if (!isRelativeOption(rule->options[optIndex+1])) { /* Match failed, next option is not relative. * We're done. */ retVal = nestedRetVal; break; } switch (thisType) { case OPTION_TYPE_CONTENT: if (origFlags & CONTENT_RELATIVE) { if ((int32_t)(origDepth - startAdjust) < (int32_t)thisContentInfo->patternByteFormLength) { /* Adjusted depth would be less than the content we're searching for? * we're done. */ retVal = nestedRetVal; continueLoop = 0; } else { /* For contents that were already relative, adjust the offset & depth fields * from their original values. Makes it easy to determine when we'll be out * of the original bounds, relative to the original cursor. */ thisContentInfo->offset = origOffset + startAdjust; thisContentInfo->depth = origDepth - startAdjust; /* And use the original cursor that was passed in */ thisCursor = startCursor; } } else { thisContentInfo->flags |= CONTENT_RELATIVE; /* For contents that were not already relative, we simply use the adjusted * cursor. Set thisCursor to tmpCursor as calculated above */ thisCursor = tmpCursor; } break; case OPTION_TYPE_PCRE: /* Doesn't matter if it was already relative, * just make it relative anyway. */ thisPCREInfo->flags |= CONTENT_RELATIVE; /* For PCREs that were not already relative, we use the cursor * that was returned at the end of the pattern to start searching * again. */ thisCursor = tmpCursor; break; } continue; } /* Only need to search again when this is a * content option. If its not, we're done. */ if (nestedRetVal <= RULE_NOMATCH) { /* Handle the case when an error is propigated * via nestedRetVal. */ retVal = RULE_NOMATCH; } break; } else { /* Cool, nobody after us, we're done with a match */ if (cursor) *cursor = thisCursor; break; } } else { /* No match, get outta dodge */ break; } } while (continueLoop); /* Keep looping until we break or serialized content checks returns no match. */ /* Reset the flags for this content in case we added the * relative flag above. */ if (thisContentInfo) { thisContentInfo->flags = origFlags; thisContentInfo->offset = origOffset; thisContentInfo->depth = origDepth; } if (thisPCREInfo) { thisPCREInfo->flags = origFlags; } return retVal; }
void Expression::tokenize() { struct Token tempToken; char c; while((c=expression[expressionIndex])!='\0') { //isFunction(*expression); if(isDigit(c)) { // if first char is digit char temp[20]; unsigned int count = 0, dotcount = 0; while(isDigit(c) or c=='.') { if(c=='.')dotcount++; if(dotcount>1) throw(parse); // error, more than 1 dots temp[count++] = c; c = expression[++expressionIndex]; } temp[count] = '\0'; tempToken.numVal = extractValue(temp); tempToken.type = VALUE; tokens.push_back(tempToken); // store the token } else if(isOperator(c)) { // symbol is an operator if(isOperator(expression[expressionIndex+1]))throw(parse); // error, two operators at same place if((expressionIndex==0 or expression[expressionIndex-1]=='(') and c=='-') c='#'; char temp[2]; temp[0]= c; temp[1] = '\0'; strcpy(tempToken.str, temp); tempToken.type = OPERATOR; tokens.push_back(tempToken); // store the token c = expression[++expressionIndex]; } else if(isVariable(c) or isConstant(c)) { // symbol is a variable or the constant char d = expression[expressionIndex+1]; if(isVariable(d) or isConstant(d)) throw parse; if(c=='z')throw parse; char temp[2]; temp[0]= c; temp[1] = '\0'; strcpy(tempToken.str, temp); if(isVariable(c)) tempToken.type = VARIABLE; if(isConstant(c)) tempToken.type = CONSTANT; tokens.push_back(tempToken); // store the token c = expression[++expressionIndex]; } else if (isFunction(expression+expressionIndex)) { char t2[3], t3[4], t4[5]; int i = expressionIndex; char *tempc = expression; t2[0]=tempc[i]; t2[1]=tempc[i+1];t2[2]='\0'; t3[0]=tempc[i];t3[1]=tempc[i+1];t3[2]=tempc[i+2];t3[3]='\0'; t4[0]=tempc[i];t4[1]=tempc[i+1];t4[2]=tempc[i+2];t4[3]=tempc[i+3];t4[4]='\0'; for(int x = 0;x<numFunctions; x++) { if(strcmp(t4, functions[x])==0) { strcpy(tempToken.str, functions[x]); expressionIndex+=4; break;} if(strcmp(t2, functions[x])==0) { strcpy(tempToken.str, functions[x]); expressionIndex+=2; break;} if(strcmp(t3, functions[x])==0) { strcpy(tempToken.str, functions[x]); expressionIndex+=3; break;} } tempToken.type = FUNCTION; tokens.push_back(tempToken); // store the token c = expression[expressionIndex]; } else if (c=='(') { tempToken.type = LEFT_PARENTHESIS; char temp[2]; temp[0] = c; temp[1]= '\0'; strcpy(tempToken.str, temp); tokens.push_back(tempToken); // store the token expressionIndex++; c = expression[expressionIndex]; } else if (c==')') { tempToken.type = RIGHT_PARENTHESIS; char temp[2]; temp[0] = c; temp[1]= '\0'; strcpy(tempToken.str, temp); tokens.push_back(tempToken); // store the token expressionIndex++; c = expression[expressionIndex]; } else if (c==' ') { // ignore the spaces ++expressionIndex; c = expression[expressionIndex]; } else { throw (token); ++expressionIndex; c= expression[expressionIndex]; } // unrecognized token; } }