Exemple #1
0
/*
 * translates file of numerical strings to 2-D float array by calling:
 * readLongLine, strToFArray
 */
float * getMatrix(FILE *fp, int *dims) {
   char *line = readLongLine(fp);
   int values = 0, initvals = INIT_ROW_SIZE, cols = 0, //oldcol = 0,
       valpointer = 0, rows = 0, z;
   float * matrix = (float *)malloc(sizeof(float) * initvals);
   float * tempmatrix;

   trimWhitespace(line);
   while(strlen(line)) {
      tempmatrix = strToFArray(line, &cols);
      values += cols;

      for(z = 0; z < cols; z++) {
         if(values > initvals) {
            initvals = initvals * 2;
            CALL_ERR((matrix = (float*)realloc(matrix, sizeof(float) * initvals)), NULL);
         }

         matrix[valpointer++] = tempmatrix[z];
      }

      ++rows;

      free(tempmatrix);
      free(line);
      line = readLongLine(fp);
      trimWhitespace(line);
   }

   dims[0] = rows;
   dims[1] = cols;

   return matrix;
}
vector <string> InitFileHandler::split(string s,string delim) {
    vector <string> v;
    size_t p = s.find(delim);
    if(p != string::npos) {
        string a = trimWhitespace(s.substr(0,p));
        string b = trimWhitespace(s.substr(p+delim.length()));
        v.push_back(a);
        v.push_back(b);
    }
    return v;
}
Exemple #3
0
/*
 * unbuffered input: dynamically allocates enough space for single line of input
 */
char * readLongLine(int fd) {
   char bf[DFLT_BF_SIZE], *str = (char*)malloc(sizeof(char) * DFLT_BF_SIZE);
   int ndx1, ndx2, size = DFLT_STR_SIZE, length;

   // read and store in str until str is full or file is empty
   for (ndx1 = 0, str[0] = '\0';
    DFLT_BF_SIZE == (length = read(fd, bf, DFLT_BF_SIZE)); ndx1 += length) {
      if (size - ndx1 < length)
         str = (char*)realloc(str, (size *= 2));
      strcpy((char*)(str + ndx1), bf);

      for (ndx2 = 0; ndx2 < length; ++ndx2) {
         if (bf[ndx2] == '\n') {
            lseek(fd, ndx2 - length + 1, SEEK_CUR);

            str[ndx1 + ndx2] = '\0';
            str = (char*)realloc(str, ndx1 + ndx2 + 1);

            str = trimWhitespace(str);

            return str;
         }
      }
   }

   // store last part of file read into str
   if (size - ndx1 < length)
      str = (char*)realloc(str, (size *= 2));
   strcpy((char*)(str + ndx1), bf);

   for (ndx2 = 0; ndx2 < length; ++ndx2) {
      if (bf[ndx2] == '\n') {
         lseek(fd, ndx2 - length + 1, SEEK_CUR);

         str[ndx1 + ndx2] = '\0';
         str = (char*)realloc(str, ndx1 + ndx2 + 1);

         str = trimWhitespace(str);

         return str;
      }
   }

   ndx1 += length;

   // cleanup
   if (size != ndx1)
      str = (char*)realloc(str, ndx1+1);
   str[ndx1] = '\0';

   str = trimWhitespace(str);

   return str;
}
Exemple #4
0
	void Any::deserializeComment(TextInput& ti, Token& token, std::string& comment) {
		// Parse comments
		while (token.type() == Token::COMMENT) {
			comment += trimWhitespace(token.string()) + "\n";

			// Allow comments to contain newlines.
			do {
				token = ti.read();
				comment += "\n";
			} while (token.type() == Token::NEWLINE);
		}

		comment = trimWhitespace(comment);
	}
bool RobotConfig::LoadConfig() {
	std::string fileName;

	GetConfigFileName(fileName);
	std::ifstream configFile(fileName.c_str());
	if (configFile.good() == false)
	{
		std::printf("2135: ERROR: RobotConfig -- No such file %s\n", fileName.c_str());
		return false;
	}

    m_configMap.clear();

    std::printf("2135: RobotConfig -- Loading File %s\n", fileName.c_str());
	while (configFile.eof() == false) {
		std::string name;
		std::string valueStr;
		std::string delimiter = "=";
		std::string line;

		while(getline(configFile, line)) {
			name = "";			// Reset
			trimWhitespace(line);
			if (line[0] == '#') {	// Skipping comment line
				continue;
			}
			size_t pos = 0;
			if ((pos = line.find(delimiter)) != std::string::npos) {
				name = line.substr(0, pos);
				trimWhitespace(name);
				line.erase(0, pos + delimiter.length());
				trimWhitespace(line);
				valueStr = line;
			}

			if (!name.empty())
			{
				m_configMap[name] = valueStr;
			}

			if (configFile.bad() == true)
			{
				std::printf("2135: ERROR: RobotConfig -- configFile %s bad\n", fileName.c_str());
				return false;
			}
		}
	}

	return true;
}
Exemple #6
0
int GFont::wordWrapCut
   (float               maxWidth,
    String&             s,
    String&             firstPart,
    float               size,
    Spacing             spacing) const {

    debugAssert(maxWidth > 0);
    int n = (int)s.length();

    const float h = size * 1.5f;
    const float w = h * charWidth / charHeight;
    const float propW = w / charWidth;
    float x = 0;

    // Current character number
    int i = 0;

    // Walk forward until we hit the end of the string or the maximum width
    while ((x <= maxWidth) && (i < n)) {
        const unsigned char c = s[i] & (charsetSize - 1);

        if (spacing == PROPORTIONAL_SPACING) {
            x += propW * subWidth[(int)c];
        } else {
            x += propW * subWidth[(int)'M'] * 0.85f;
        }

        if (c == '\n') {
            // Hit a new line; force us past the line end
            break;
        }
        ++i;
    }

    if (i == n) {
        // We made it to the end
        firstPart = s;
        s = "";
        return n;
    }

    --i;

    // Search backwards for a space.  Only look up to 25% of maxWidth
    while ((i > 1) && ! isWhiteSpace(s[i]) && (x > maxWidth * 0.25f)) {
        const unsigned char c = s[i] & (charsetSize - 1);
        if (spacing == PROPORTIONAL_SPACING) {
            x -= propW * subWidth[(int)c];
        } else {
            x -= propW * subWidth[(int)'M'] * 0.85f;
        }
        --i;
    }

    firstPart = s.substr(0, i);
    s = trimWhitespace(s.substr(i));

    return i;
}
  void readVLANs(HSP *sp)
  {
    // mark interfaces that are specific to a VLAN
    FILE *procFile = fopen("/proc/net/vlan/config", "r");
    if(procFile) {
      char line[MAX_PROC_LINE_CHARS];
      int lineNo = 0;
      while(fgets(line, MAX_PROC_LINE_CHARS, procFile)) {
	// expect lines of the form "<device> VID: <vlan> ..."
	// (with a header line on the first row)
	char devName[MAX_PROC_LINE_CHARS];
	int vlan;
	++lineNo;
	if(lineNo > 1 && sscanf(line, "%s | %d", devName, &vlan) == 2) {
	  SFLAdaptor *adaptor = adaptorListGet(sp->adaptorList, trimWhitespace(devName));
	  if(adaptor && adaptor->userData &&
	     vlan >= 0 && vlan < 4096) {
	    HSPAdaptorNIO *niostate = (HSPAdaptorNIO *)adaptor->userData;
	    niostate->vlan = vlan;
	    if(debug) myLog(LOG_INFO, "adaptor %s has 802.1Q vlan %d", devName, vlan);
	  }
	}
      }
      fclose(procFile);
    }
  }
Exemple #8
0
int splitStringOnKey(std::vector<std::string>& returnSplitSubstrings,const std::string& baseStr,const std::string& delims) {

	std::string base = trimWhitespace(baseStr);
	std::string::size_type start = 0;
	std::string::size_type mark = 0;
	std::string extracted;

	int i=0;
	while (start < baseStr.size()) {
		//find the start of a non-delims
		start = baseStr.find_first_not_of(delims,mark);
		if (start == std::string::npos)
			break;
		//find the end of the current substring (where the next instance of delim lives, or end of the string)
		mark = baseStr.find_first_of(delims,start);
		if (mark == std::string::npos)
			mark = baseStr.size();

		extracted = baseStr.substr(start,mark-start);
		if (extracted.size() > 0) {
			//valid string...add it
			returnSplitSubstrings.push_back(extracted);
			++i;
		}
		start=mark;
	}

	return i;
}
  // http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
  // Nothing fancy here. We parse name/value pairs based on the '=' delimiter
  // The Java parser is much more versatile.
  void PropertiesConfiguration::parseLine(std::istream &input, size_t lineno) {
    ASSERT(!input.fail());
    if(input.fail())
      throw std::runtime_error("Should I shit or go blind???");

    std::string line;
    if (getline(input, line))
      {
	// This trim is needed to properly catch comments
	trimWhitespace(line);
	if(line.empty() || line[0] == '#')
	  return;

	static const char delim = '=';
	const size_t pos = line.find(delim, 0);

        ASSERT(pos != String::npos);
        if(pos == String::npos) {
          std::ostringstream ss;
          ss << "parseLine: delimiter not found (line: " << lineno << ")";
          // std::clog << ss.str() << std::endl;
          throw IllegalArgumentException(ss.str());
        }

	std::string key = line.substr(0, pos);
	std::string value = line.substr(pos + 1, line.size());

        // Keys must be present
	trimWhitespace(key);
        ASSERT(!key.empty());
        if(key.empty()) {                    
          std::ostringstream ss;
          ss << "parseLine: property key is not valid (line: " << lineno << ")";
          // std::clog << ss.str() << std::endl;
          throw IllegalArgumentException(ss.str());
        }

        // Value is optional, but will likely result in an exception during retrieval.
        // String *will not* throw on getString(...); but Bool and Int *will*
        // throw when using getBool(...) or getInt(...).
	trimWhitespace(value);	
	ASSERT(!value.empty());

        setString(key, value);
      }
  }
Exemple #10
0
static char* strcpyAndTrim(const char* str, int len)
{
	char* newStr = malloc(len + 256);
	memset(newStr, 0, len + 256);
	memcpy(newStr, str, len + 1);
	newStr[len] = 0;

	return trimWhitespace(newStr);
}
Exemple #11
0
GKey GKey::fromString(const std::string& _s) {
    std::string s = trimWhitespace(toLower(_s));    

    for (int i = 0; i < LAST; ++i) {
        std::string t = GKey(i).toString();
        if ((t.size() == s.size()) &&
            (toLower(t) == s)) {
            return GKey(i);
        }
    }

    return UNKNOWN;
}
Exemple #12
0
void ServerUI::command_quit()
{
	trimWhitespace();
	
	if (strlen(ptCommand) == 0)
	{
		char buff = 'q';
		write(netSock, &buff, 1);
	}
	else
	{
		printf("quit: invalid parameters\n");
	}
}
  void readIPv6Addresses(HSP *sp)
  {
    FILE *procFile = fopen("/proc/net/if_inet6", "r");
    if(procFile) {
      char line[MAX_PROC_LINE_CHARS];
      int lineNo = 0;
      while(fgets(line, MAX_PROC_LINE_CHARS, procFile)) {
	// expect lines of the form "<address> <netlink_no> <prefix_len(HEX)> <scope(HEX)> <flags(HEX)> <deviceName>
	// (with a header line on the first row)
	char devName[MAX_PROC_LINE_CHARS];
	u_char addr[MAX_PROC_LINE_CHARS];
	u_int devNo, maskBits, scope, flags;
	++lineNo;
	if(sscanf(line, "%s %x %x %x %x %s",
		  addr,
		  &devNo,
		  &maskBits,
		  &scope,
		  &flags,
		  devName) == 6) {
	  if(debug) {
	    myLog(LOG_INFO, "adaptor %s has v6 address %s with scope 0x%x",
		  devName,
		  addr,
		  scope);
	  }
	  SFLAdaptor *adaptor = adaptorListGet(sp->adaptorList, trimWhitespace(devName));
	  if(adaptor && adaptor->userData) {
	    HSPAdaptorNIO *niostate = (HSPAdaptorNIO *)adaptor->userData;
	    SFLAddress v6addr;
	    v6addr.type = SFLADDRESSTYPE_IP_V6;
	    if(hexToBinary(addr, v6addr.address.ip_v6.addr, 16) == 16) {
	      // we interpret the scope from the address now
	      // scope = remap_proc_net_if_inet6_scope(scope);
	      EnumIPSelectionPriority ipPriority = agentAddressPriority(sp,
									&v6addr,
									niostate->vlan,
									niostate->loopback);
	      if(ipPriority > niostate->ipPriority) {
		// write this in as the preferred sflow-agent-address for this adaptor
		niostate->ipAddr = v6addr;
		niostate->ipPriority = ipPriority;
	      }
	    }
	  }
	}
      }
      fclose(procFile);
    }
  }
  bool Configuration::parseBool(const String &str) const
  {
    ASSERT(!str.empty());
    if(str.empty())
      throw ParseException("Boolean property key is not valid");

    String lower(str);
    trimWhitespace(lower);
    std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);

    if (lower == String(1, (char)0x00) || lower == "0" || lower == "false" || lower == "off" || lower == "no")
      return false;
    else if (lower == String(1, (char)0x01)  || lower == "1" || lower == "true" || lower == "on" || lower == "yes")
      return true;
    else
      throw ParseException("Cannot parse as boolean: " + str);
  }
    SaveDialog(std::string& saveName, GuiSkinRef skin) : 
        GuiWindow("Save Path As", skin, Rect2D::xywh(100, 100, 10, 10), DIALOG_FRAME_STYLE, HIDE_ON_CLOSE), 
        ok(false), saveName(saveName) {
        GuiPane* rootPane = pane();

        textBox = rootPane->addTextBox("Filename", &saveName, GuiTextBox::IMMEDIATE_UPDATE);
        textBox->setSize(textBox->rect().wh() + Vector2(20, 0));
        textBox->setFocused(true);

        cancelButton = rootPane->addButton("Cancel");
        okButton = rootPane->addButton("Ok");
        okButton->moveRightOf(cancelButton);

        okButton->setEnabled(trimWhitespace(saveName) != "");

        pack();
    }
Exemple #16
0
bool TRFactory::readAndTrimNextLine(istream& inStream, string& outString)
{
    char theLine[maxLineLength];
    bool theSuccess = false;

    inStream.getline(theLine, maxLineLength);
    outString = string(theLine);

    trimWhitespace(outString);

    // Return false if the line is empty when we're done
    if(outString.length() > 1)
    {
        theSuccess = true;
    }

    return theSuccess;
}
// reads full request up to [END_REQUEST]
// returns result WITHOUT [END_REQUEST] marker at end
// returns NULL on failure
static char *readFullRequest( Socket *inSock ) {
    
    char *readSoFar = stringDuplicate( "" );

    char error = false;
    
    while( !checkForEndMarker( readSoFar ) && ! error ) {
        
        int numRead = inSock->receive( (unsigned char *)readBuffer, 
                                       READ_SIZE, 0 );
    
        if( numRead >= 0 ) {
            readBuffer[ numRead ] = '\0';
            
            char *newReadSoFar = concatonate( readSoFar, readBuffer );
            
            delete [] readSoFar;
            
            readSoFar = newReadSoFar;
            }
        else if( numRead != -2 ) {
            // not timeout, real error
            error = true;
            }
        }
    
    if( error ) {
        return NULL;
        }
    

    char found;
    char *message = replaceOnce( readSoFar, END_REQUEST,
                                 "", &found);

    delete [] readSoFar;

    char *trimmedMessage = trimWhitespace( message );
    
    delete [] message;

    return trimmedMessage;
    }
Exemple #18
0
void ServerUI::processCommand()
{
	ptCommand = szCommand;
	
	//trim whitespace
	trimWhitespace();
	
	int nLen = strlen(ptCommand);
	
	if (nLen > 4 && strncmp(ptCommand, "quit", 4))
	{
		ptCommand+=4;
		command_quit();
	}
	else
	{
		printf("unknown command\n");
	}
}
Exemple #19
0
bool testTrimWhitespace1(void) {
  char const *line = "var";
  char const *expected = "var";
  char *actual = trimWhitespace(line);
  bool retval;

  if(NULL == actual) {
    return false;
  }

  if(0 == strcmp(expected, actual)) {
    retval = true;
  } else {
    printf("Bad trimmed value: '%s'\n", actual);
    retval = false;
  }
  
  free(actual);
  return retval;
}
Exemple #20
0
bool testAllWhitespace(void) {
  char const *line = "   \t \v \f \r  \n";
  char const *expected = "";
  char *actual = NULL;
  bool retval;

  actual = trimWhitespace(line);
  if(NULL == actual) {
    return false;
  }

  if(0 == strcmp(expected, actual)) {
    retval = true;
  } else {
    retval = false;
  }
  
  free(actual);
  return retval;
}
    virtual bool onEvent(const GEvent& e) {
        if (GuiWindow::onEvent(e)) {
            return true;
        }

        okButton->setEnabled(trimWhitespace(saveName) != "");

        if (e.type == GEventType::GUI_ACTION) {
            // Text box, cancel button and ok button are the 
            // only choices.  Anything but cancel means ok,
            // and all mean close the dialog.
            ok = (e.gui.control != cancelButton);
            setVisible(false);
        } else if ((e.type == GEventType::KEY_DOWN) && (e.key.keysym.sym == GKey::ESCAPE)) {
            // Cancel the dialog
            ok = false;
            setVisible(false);
        }

        return false;
    }
void VideoRecordDialog::screenshot(RenderDevice* rd) {
    const shared_ptr<Texture>& texture = Texture::createEmpty("Screenshot", rd->width(), rd->height(), ImageFormat::RGB8());

    texture->copyFromScreen(rd->viewport());
    texture->visualization = Texture::Visualization::sRGB();

    String filename = ScreenshotDialog::nextFilenameBase(m_filenamePrefix) + "." + toLower(m_ssFormatList[m_ssFormatIndex]);
    const shared_ptr<Image>& image = texture->toImage();
    if (rd->invertY()) {
        image->flipVertical();
    }

    if (ScreenshotDialog::create(window(), theme(), FilePath::parent(filename))->getFilename(filename, "Save Screenshot", texture)) {
        filename = trimWhitespace(filename);

        if (! filename.empty()) {
            image->save(filename);
            saveMessage(filename);
        }
    }
}
void VideoRecordDialog::stopRecording() {
    debugAssert(m_video);

    // Save the movie
    m_video->commit();
    String oldFilename = m_video->filename();
    String newFilename = oldFilename;
    m_video.reset();

    if (ScreenshotDialog::create(window(), theme(), FilePath::parent(newFilename))->getFilename(newFilename, "Save Movie")) {
        newFilename = trimWhitespace(newFilename);

        if (newFilename.empty()) {
            // Cancelled--delete the file
            FileSystem::removeFile(oldFilename);
        } else {
            if (oldFilename != newFilename) {
                FileSystem::rename(oldFilename, newFilename);
            }
            saveMessage(newFilename);
        }
    }

    if (m_app) {
        // Restore the app state
        m_app->setFrameDuration(m_oldRealTimeTargetDuration, m_oldSimTimeStep);
    }

    // Reset the GUI
    m_recordButton->setCaption("Record Now (" + m_hotKeyString + ")");

    // Restore the window caption as well
    OSWindow* window = const_cast<OSWindow*>(OSWindow::current());
    const String& c = window->caption();
    const String& appendix = " - Recording " + m_hotKeyString + " to stop";
    if (endsWith(c, appendix)) {
        window->setCaption(c.substr(0, c.size() - appendix.size()));
    }
}
  int Configuration::parseInt(const String &str) const
  {
    ASSERT(!str.empty());
    if(str.empty())
      throw ParseException("Integer value is empty");

    String temp(str);
    trimWhitespace(temp);

    StringStream ss(temp);
    int n = 0;

    const String& prefix = temp.substr(0,2);
    if(prefix == "0x" || prefix == "0X")
      ss >> std::setbase(16);

    ss >> n;
    ASSERT(!(ss.fail()));
    if (ss.fail())
        throw ParseException("Cannot parse as int: " + str);

    return n;
  }
Exemple #25
0
void initTools() {
    File elementsDir( NULL, "gameElements" );

    if( !elementsDir.exists() || !elementsDir.isDirectory() ) {
        return;
        }
    
    File *toolsDir = elementsDir.getChildFile( "tools" );
    
    if( toolsDir == NULL ) {
        return;
        }
    else if( !toolsDir->exists() || !toolsDir->isDirectory() ) {
        delete toolsDir;
        return;
        }
    
    int numTools;
    File **toolNameDirs = toolsDir->getChildFiles( &numTools );

    delete toolsDir;
    
    if( toolNameDirs == NULL ) {
        return;
        }
    
    
    for( int i=0; i<numTools; i++ ) {
        
        File *f = toolNameDirs[i];
        

        if( f->exists() && f->isDirectory() ) {
            
            char completeRecord = true;

            toolRecord r;
            
            r.name = f->getFileName();
            r.description = NULL;
            r.descriptionPlural = NULL;
            r.sprite = NULL;
            
            File *infoFile = f->getChildFile( "info.txt" );
            
            completeRecord = readInfoFile( infoFile, 
                                           &( r.id ), &( r.description ) );
            delete infoFile;

            if( completeRecord ) {
                
                File *pluralFile = f->getChildFile( "plural.txt" );
            
                completeRecord = readPluralFile( pluralFile, 
                                                 &( r.descriptionPlural ) );
                delete pluralFile;
                }


            if( completeRecord ) {

                // read reach, if present (if not, default to 1)
                r.reach = 1;

                File *reachFile = f->getChildFile( "reach.txt" );
            
                if( reachFile->exists() ) {
                    
                    char *reach = reachFile->readFileContents();
                
                    sscanf( reach, "%d", &( r.reach ) );

                    delete [] reach;
                    }
                
                delete reachFile;
                

                
                File *reachSigFile = f->getChildFile( "reachSignature.txt" );
                char *reachSigContents = NULL;
                
                if( reachSigFile->exists() ) {
                    reachSigContents = reachSigFile->readFileContents();    
                    }
                delete reachSigFile;
                

                char reachSigOK = true;
    
                if( regenerateReachSignatures ) {
                    // ignore reachSignature.txt and generate a new one
                    char *newSig = computeReachSignature( &r );
                    
                    File *childFile = 
                        f->getChildFile( "reachSignature.txt" );
                    if( childFile != NULL ) {
                        childFile->writeToFile( newSig );
                        delete childFile;
                        }
                    delete [] newSig;
                    }
                else if( reachSigContents == NULL ) {
                    reachSigOK = false;
                    }
                else {
                    // else check it
                    char *sig = trimWhitespace( reachSigContents );
        
                    char *trueSig = computeReachSignature( &r );
        
                    if( strcmp( trueSig, sig ) != 0 ) {
                        reachSigOK = false;
                        }
                    delete [] sig;
                    delete [] trueSig;
                    }
                
                if( reachSigContents != NULL ) {
                    delete [] reachSigContents;
                    }
    
                
                
                if( !reachSigOK ) {
                    char *dirName = f->getFullFileName();
                    char *message = autoSprintf( 
                        "%s\n%s",
                        translate( "badReachSignature" ),
                        dirName );
                    delete [] dirName;
                    
                    loadingFailed( message );
                    delete [] message;
                    }




                
                // look for sprite TGA
                int numChildFiles;
                File **childFiles = f->getChildFiles( &numChildFiles );
    
                char *tgaPath = NULL;
                char *shadeMapTgaPath = NULL;
                
                for( int j=0; j<numChildFiles; j++ ) {
        
                    File *f = childFiles[j];
        
                    char *name = f->getFileName();
                    if( strstr( name, "_shadeMap.tga" ) != NULL ) {
                        if( shadeMapTgaPath != NULL ) {
                            delete [] shadeMapTgaPath;
                            }
                        shadeMapTgaPath = f->getFullFileName();
                        }
                    else if( strstr( name, ".tga" ) != NULL ) {
                        if( tgaPath != NULL ) {
                            delete [] tgaPath;
                            }
                        tgaPath = f->getFullFileName();
                        }
                    
                    delete [] name;

                    delete childFiles[j];
                    }
                delete [] childFiles;


                if( tgaPath != NULL ) {
                    // assume only one orientation here
                    // discard extras
                    SpriteHandle readSprites[ MAX_ORIENTATIONS ];
                    
                    int numOrientations = 
                        readShadeMappedSprites( tgaPath, shadeMapTgaPath,
                                                readSprites );
                    
                    if( numOrientations == 0 ) {
                        completeRecord = false;
                        }
                    else {
                        r.sprite = readSprites[0];
                    
                        for( int o=1; o<numOrientations; o++ ) {
                            freeSprite( readSprites[o] );
                            }
                        }
                    }
                else {
                    if( shadeMapTgaPath != NULL ) {
                        delete [] shadeMapTgaPath;
                        }
                    completeRecord = false;
                    }
                }
            
            if( completeRecord ) {
                if( r.id >= idSpaceSize ) {
                    idSpaceSize = r.id + 1;
                    }
                tools.push_back( r );
                }
            else {
                delete [] r.name;
                if( r.description != NULL ) {
                    delete [] r.description;
                    }
                if( r.descriptionPlural != NULL ) {
                    delete [] r.descriptionPlural;
                    }
                if( r.sprite != NULL ) {
                    freeSprite( r.sprite );
                    }
                }
            }
        delete f;
        }

    delete [] toolNameDirs;


    // build map
    idToIndexMap = new int[idSpaceSize];
    for( int i=0; i<idSpaceSize; i++ ) {
        idToIndexMap[i] = -1;
        }

    for( int i=0; i<tools.size(); i++ ) {
        toolRecord r = *( tools.getElement( i ) );
        
        idToIndexMap[r.id] = i;
        }
    }
int readInterfaces(HSP *sp)
{
  if(sp->adaptorList == NULL) sp->adaptorList = adaptorListNew();
  else adaptorListMarkAll(sp->adaptorList);

  // Walk the interfaces and collect the non-loopback interfaces so that we
  // have a list of MAC addresses for each interface (usually only 1).
  //
  // May need to come back and run a variation of this where we supply
  // a domain and collect the virtual interfaces for that domain in a
  // similar way.  It looks like we do that by just parsing the numbers
  // out of the interface name.
  
  int fd = socket (PF_INET, SOCK_DGRAM, 0);
  if (fd < 0) {
    fprintf (stderr, "error opening socket: %d (%s)\n", errno, strerror(errno));
    return 0;
  }

  FILE *procFile = fopen("/proc/net/dev", "r");
  if(procFile) {
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(ifr));
    char line[MAX_PROC_LINE_CHARS];
    while(fgets(line, MAX_PROC_LINE_CHARS, procFile)) {
      if(debug) myLog(LOG_INFO, "/proc/net/dev line: %s", line);
      // the device name is always the token before the ":"
      char *devName = strtok(line, ":");
      if(devName) {
	devName = trimWhitespace(devName);
	if(devName && strlen(devName) < IFNAMSIZ) {
	  // we set the ifr_name field to make our queries
	  strcpy(ifr.ifr_name, devName);

	  if(debug > 1) {
	    myLog(LOG_INFO, "reading interface %s", devName);
	  }

	  // Get the flags for this interface
	  if(ioctl(fd,SIOCGIFFLAGS, &ifr) != 0) {
	    myLog(LOG_ERR, "device %s Get SIOCGIFFLAGS failed : %s",
		  devName,
		  strerror(errno));
	  }
	  else {
	    int up = (ifr.ifr_flags & IFF_UP) ? YES : NO;
	    int loopback = (ifr.ifr_flags & IFF_LOOPBACK) ? YES : NO;
	    int promisc =  (ifr.ifr_flags & IFF_PROMISC) ? YES : NO;
	    int bond_master = (ifr.ifr_flags & IFF_MASTER) ? YES : NO;
	    //int hasBroadcast = (ifr.ifr_flags & IFF_BROADCAST);
	    //int pointToPoint = (ifr.ifr_flags & IFF_POINTOPOINT);

	    // used to igore loopback interfaces here, but now those
	    // are filtered at the point where we roll together the
	    // counters.
	    if(up) {
	      
	       // Get the MAC Address for this interface
	      if(ioctl(fd,SIOCGIFHWADDR, &ifr) != 0) {
		myLog(LOG_ERR, "device %s Get SIOCGIFHWADDR failed : %s",
		      devName,
		      strerror(errno));
	      }

	      // for now just assume that each interface has only one MAC.  It's not clear how we can
	      // learn multiple MACs this way anyhow.  It seems like there is just one per ifr record.
	      // find or create a new "adaptor" entry
	      SFLAdaptor *adaptor = adaptorListAdd(sp->adaptorList, devName, (u_char *)&ifr.ifr_hwaddr.sa_data, sizeof(HSPAdaptorNIO));

	      // clear the mark so we don't free it below
	      adaptor->marked = NO;

	      // this flag might belong in the adaptorNIO struct
	      adaptor->promiscuous = promisc;

	      // remember some useful flags in the userData structure
	      HSPAdaptorNIO *adaptorNIO = (HSPAdaptorNIO *)adaptor->userData;
	      adaptorNIO->loopback = loopback;
	      adaptorNIO->bond_master = bond_master;
	      adaptorNIO->vlan = HSP_VLAN_ALL; // may be modified below

	      // Try and get the ifIndex for this interface
	      if(ioctl(fd,SIOCGIFINDEX, &ifr) != 0) {
		// only complain about this if we are debugging
		if(debug) {
		  myLog(LOG_ERR, "device %s Get SIOCGIFINDEX failed : %s",
			devName,
			strerror(errno));
		}
	      }
	      else {
		adaptor->ifIndex = ifr.ifr_ifindex;
	      }
	      
	      // Try to get the IP address for this interface
	      if(ioctl(fd,SIOCGIFADDR, &ifr) != 0) {
		// only complain about this if we are debugging
		if(debug) {
		  myLog(LOG_ERR, "device %s Get SIOCGIFADDR failed : %s",
			devName,
			strerror(errno));
		}
	      }
	      else {
		if (ifr.ifr_addr.sa_family == AF_INET) {
		  struct sockaddr_in *s = (struct sockaddr_in *)&ifr.ifr_addr;
		  // IP addr is now s->sin_addr
		  adaptorNIO->ipAddr.type = SFLADDRESSTYPE_IP_V4;
		  adaptorNIO->ipAddr.address.ip_v4.addr = s->sin_addr.s_addr;
		}
		//else if (ifr.ifr_addr.sa_family == AF_INET6) {
		// not sure this ever happens - on a linux system IPv6 addresses
		// are picked up from /proc/net/if_inet6
		// struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ifr.ifr_addr;
		// IP6 addr is now s->sin6_addr;
		//}
	      }
	      
	      // Try to get the ethtool info for this interface so we can infer the
	      // ifDirection and ifSpeed. Learned from openvswitch (http://www.openvswitch.org).
	      struct ethtool_cmd ecmd = { 0 };
	      ecmd.cmd = ETHTOOL_GSET;
	      ifr.ifr_data = (char *)&ecmd;
	      if(ioctl(fd, SIOCETHTOOL, &ifr) == 0) {
		adaptor->ifDirection = ecmd.duplex ? 1 : 2;
		uint64_t ifSpeed_mb = ecmd.speed;
		// ethtool_cmd_speed(&ecmd) is available in newer systems and uses the
		// speed_hi field too,  but we would need to run autoconf-style
		// tests to see if it was there and we are trying to avoid that.
		if(ifSpeed_mb == (uint16_t)-1 ||
		   ifSpeed_mb == (uint32_t)-1) {
		  // unknown
		  adaptor->ifSpeed = 0;
		}
		else {
		  adaptor->ifSpeed = ifSpeed_mb * 1000000;
		}
	      }
	    }
	  }
	}
      }
    }
    fclose(procFile);
  }
  
  close (fd);

  // now remove and free any that are still marked
  adaptorListFreeMarked(sp->adaptorList);

  // check in case any of the survivors are specific
  // to a particular VLAN
  readVLANs(sp);

  // now that we have the evidence gathered together, we can
  // set the L3 address priorities (used for auto-selecting
  // the sFlow-agent-address if requrired to by the config.
  setAddressPriorities(sp);

  // now we can read IPv6 addresses too - they come from a
  // different place. Depending on the address priorities this
  // may cause the adaptor's best-choice ipAddress to be
  // overwritten.
  readIPv6Addresses(sp);

  return sp->adaptorList->num_adaptors;
}
Exemple #27
0
bool ConfigMap::readFile(const std::string &filename) 
{
	std::string instr;

	if (MinVR::FileSystem::getInstance().exists(filename))
	{
		std::string output = "ConfigMap parsing file \"" + filename + "\".";
		std::cout << output << std::endl;

		ifstream fIn;
		fIn.open(filename.c_str(),std::ios::in);

		if (!fIn) {
			MinVR::Logger::getInstance().assertMessage(false, "ConfigMap Error: Unable to load config file");
		}
		std::stringstream ss;
		ss << fIn.rdbuf();
    
		instr =  ss.str();
	}
	else
	{  
		std::stringstream ss;
		ss << "Cannot locate config file " << filename;
		MinVR::Logger::getInstance().assertMessage(false, ss.str().c_str());
	}


	// convert all endline characters to \n's
	for (int i=0;i<instr.size();i++)
	{ 
		if (instr[i] == '\r') {
			instr[i] = '\n';
		}
	}

	// remove any cases of two \n's next to each other
	for (int i=0;i<instr.size()-1;i++)
	{ 
		if ((instr[i] == '\n') && (instr[i+1] == '\n'))	{
			instr = instr.substr(0,i) + instr.substr(i+1);
		}
	}

	// add a \n so that every file ends in at least one \n
	instr = instr + std::string("\n");

	// start pulling out name, value pairs
	// the config file must end with a newline
	//
	while (instr.size()) {
		int endline = instr.find("\n");
		std::string nameval = instr.substr(0,endline);

		// a backslash not followed by a second backslash means continue on
		// the next line, wipe out everything from the backslash to the newline
		/**  Note, this will miss the following scenario, which will probably
		never occur in practice:
		myname myvalue with a single slash here \\ and \
		continued on the next line like this
		So, this doesn't handle a \\ on the same line as a \
		**/
		int slash = nameval.find("\\");

		bool nextCharIsSlash = false;
		if (slash < nameval.size() - 1) {
			nextCharIsSlash = (nameval[slash+1] == '\\');
		} 
		else {
			nextCharIsSlash = false;
		}

		while ((slash != nameval.npos) && !nextCharIsSlash && (endline != nameval.npos)) {
			std::string fromPrevLine = nameval.substr(0,slash);
			instr = instr.substr(endline+1);
			endline = instr.find("\n");
			nameval = fromPrevLine + instr.substr(0,endline);
			slash = nameval.find("\\");
			if (slash < nameval.size() - 1) {
				nextCharIsSlash = (nameval[slash+1] == '\\');
			}
			else {
				nextCharIsSlash = false;
			}
		}

		// a line starting with # is a comment, ignore it
		//
		if (nameval.size() > 0 && nameval[0] != '#')
		{ 
			// if we have two backslashes \\ treat this as an escape sequence for
			// a single backslash, so replace the two with one
			int doubleslash = nameval.find("\\\\");

			if (doubleslash >= 0)
			{  nameval = nameval.substr(0,doubleslash)
			+ nameval.substr(doubleslash + 1);
			}

			// replace all $(NAME) sequences with the value of the environment
			// variable NAME.  under cygwin, cygwin-style paths are replaced with
			// windows style paths.
			nameval = replaceEnvVars(nameval);

			int firstspace = nameval.find(" ");
			int firsttab = nameval.find('\t');
			if (((firsttab >=0) && (firsttab < firstspace)) || ((firsttab >=0) && (firstspace < 0)))
			{
				firstspace = firsttab;
			}

			std::string name = nameval.substr(0,firstspace);
			std::string val;

			if (firstspace >= 0)
			{  
				val = trimWhitespace(nameval.substr(firstspace + 1));
			}

			if (name != "")	{
				if ((name.size() > 2) && (name[name.size()-2] == '+') && (name[name.size()-1] == '='))
				{
					name = name.substr(0,name.size()-2);

					if (ConfigMap::containsKey(name)) {
						std::string newVal = ConfigMap::getValue(name) + " " + val;
						ConfigMap::set(name, newVal);
					}
					else {
						ConfigMap::set(name, val);
					}
				}
				else {
					ConfigMap::set(name, val);
				}
			}
		} // end not a comment

		instr = instr.substr(endline+1);
	}

	return true;
}
Exemple #28
0
/**
* Test application to test creating a document from scratch
*/
int main()
{
   // Create the basic context and document to work on
   // - All nodes need to have an associated context
   //   we will just define one here at the beginning and use it
   //   the entire way through
   cppdom::ContextPtr ctx( new cppdom::Context );
   cppdom::Document doc("Document", ctx );

   // What it should look like
   // - Root
   //   - Element1: attrib1:1, attrib2:two
   //        cdata: This is element1
   //   - Element2:
   //      - Element3: attrib1:attrib1
   //        cdata: We are element 3
   //        cdata: We are still element 3
   cppdom::NodePtr root(new cppdom::Node("root", ctx));
   cppdom::NodePtr element1(new cppdom::Node("Element1", ctx));
   cppdom::NodePtr element2(new cppdom::Node("Element2", ctx));
   cppdom::NodePtr element3(new cppdom::Node("Element3", ctx));
   cppdom::NodePtr element1_cdata(new cppdom::Node("Element1-cdata", ctx));
   cppdom::NodePtr element3_cdata2(new cppdom::Node("Element3-cdata2", ctx));

   // Document can only have one element as child (to be valid xml)
   // Set this to the root element
   doc.addChild(root);

   // Now add element 1
   // - Also set it's attributes
   root->addChild(element1);
   element1->setAttribute("attrib1", 1);
   element1->setAttribute("attrib2", "two");
   std::string escaped_attrib_text = "<this>&<that>\"\'<done>";
   element1->setAttribute("attrib3", escaped_attrib_text);
   element1->addChild(element1_cdata);

   // Cdata must have it's type set
   // then set the actual contents of the cdata
   element1_cdata->setType(Node::xml_nt_cdata);
   std::string escaped_elt1_cdata("\n<test>\n<more>This is 'element1'<here>&\"there\"");
   element1_cdata->setCdata(escaped_elt1_cdata);

   // Add a couple of nested nodes and set the attributes
   root->addChild(element2);
   element2->addChild(element3);
   element3->setAttribute("attrib1", "attrib1");

   // Set Cdata a couple of different ways (this is a test isn't it :)
   element3->setCdata("We are element 3 <<clear me>>");
   element3_cdata2->setType(Node::xml_nt_cdata);
   element3_cdata2->setCdata("We are still element 3");
   element3->addChild(element3_cdata2);
   element3->setCdata("We are element 3");

   // Get the cdata contents and make sure they match up
   std::string cdata_text;
   cdata_text = element1->getCdata();
   std::cout << escaped_elt1_cdata << cdata_text << std::endl;
   cdata_text = element1->getFullCdata();
   std::cout << escaped_elt1_cdata << cdata_text << std::endl;
   cdata_text = element1_cdata->getCdata();
   std::cout << escaped_elt1_cdata << cdata_text << std::endl;

   cdata_text = element3->getCdata();
   std::cout << "We are element 3: " << cdata_text << std::endl;
   cdata_text = element3->getFullCdata();
   std::cout << "We are element 3,We are still element 3: " << cdata_text << std::endl;

   // Dump the tree to the screen
   testHelpers::dump_node(doc);

   // Write the document out to a file
   std::cout << "------- Indented document ------\n";
   doc.save(std::cout);
   std::cout << "------- No indent, no newline document ------\n";
   doc.save(std::cout, false, false);
   std::cout << std::endl;

   std::string filename("maketree.xml");
   doc.saveFile(filename);

   // Now load it to test some things
   cppdom::Document loaded_doc(ctx);
   loaded_doc.loadFile(filename);

   cppdom::NodePtr r_element1 = loaded_doc.getChild("root")->getChild("Element1");

   std::string r_elt1_cdata = r_element1->getCdata();
   std::string tr_elt1_cdata = trimWhitespace(r_elt1_cdata);
   std::string t_escaped_elt1_cdata = trimWhitespace(escaped_elt1_cdata);

//   assert(tr_elt1_cdata == t_escaped_elt1_cdata);

   std::string r_attrib = r_element1->getAttribute("attrib3");
   assert(r_attrib == escaped_attrib_text);

   std::cout << "---------------------------------------\n"
             << "Tests passed." << std::endl;

   return 0;
}
Exemple #29
0
int readInterfaces(HSP *sp)
{
  newAdaptorList(sp);

  // Walk the interfaces and collect the non-loopback interfaces so that we
  // have a list of MAC addresses for each interface (usually only 1).
  //
  // May need to come back and run a variation of this where we supply
  // a domain and collect the virtual interfaces for that domain in a
  // similar way.  It looks like we do that by just parsing the numbers
  // out of the interface name.

  struct ifaddrs *ifap;
  getifaddrs(&ifap);
  for(struct ifaddrs *ifp = ifap; ifp; ifp = ifp->ifa_next) {
    char *devName = ifp->ifa_name;

    if(devName) {
      devName = trimWhitespace(devName);
      // Get the flags for this interface
      int up = (ifp->ifa_flags & IFF_UP) ? YES : NO;
      int loopback = (ifp->ifa_flags & IFF_LOOPBACK) ? YES : NO;
      int address_family = ifp->ifa_addr->sa_family;
      if(debug > 1) {
	myLog(LOG_INFO, "reading interface %s (up=%d, loopback=%d, family=%d)",
	      devName,
	      up,
	      loopback,
	      address_family);
      }
      //int hasBroadcast = (ifp->ifa_flags & IFF_BROADCAST);
      //int pointToPoint = (ifp->ifa_flags & IFF_POINTOPOINT);
      if(up && !loopback && address_family == AF_LINK) {
	// for now just assume that each interface has only one MAC.  It's not clear how we can
	// learn multiple MACs this way anyhow.  It seems like there is just one per ifr record.
	// create a new "adaptor" entry
	SFLAdaptor *adaptor = (SFLAdaptor *)my_calloc(sizeof(SFLAdaptor) + (1 * sizeof(SFLMacAddress)));
	memcpy(adaptor->macs[0].mac, &ifp->ifa_addr->sa_data, 6);
	adaptor->num_macs = 1;
	adaptor->deviceName = strdup(devName);
	
	// Try and get the ifIndex for this interface
	// if(ioctl(fd,SIOCGIFINDEX, &ifr) != 0) {
	// only complain about this if we are debugging
	//if(debug) {
	//myLog(LOG_ERR, "device %s Get SIOCGIFINDEX failed : %s",
	//devName,
	//strerror(errno));
	//}
	//}
	//else {
	//adaptor->ifIndex = ifr.ifr_ifindex;
	//}
	       
	// Try to get the IP address for this interface
/* 	if(ioctl(fd,SIOCGIFADDR, &ifr) != 0) { */
/* 	  // only complain about this if we are debugging */
/* 	  if(debug) { */
/* 	    myLog(LOG_ERR, "device %s Get SIOCGIFADDR failed : %s", */
/* 		  devName, */
/* 		  strerror(errno)); */
/* 	  } */
/* 	} */
/* 	else { */
/* 	  if (ifr.ifr_addr.sa_family == AF_INET) { */
/* 	    struct sockaddr_in *s = (struct sockaddr_in *)&ifr.ifr_addr; */
/* 	    // IP addr is now s->sin_addr */
/* 	    adaptor->ipAddr.addr = s->sin_addr.s_addr; */
/* 	  } */
/* 	  //else if (ifr.ifr_addr.sa_family == AF_INET6) { */
/* 	  // not sure this ever happens - on a linux system IPv6 addresses */
/* 	  // are picked up from /proc/net/if_inet6 */
/* 	  // struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ifr.ifr_addr; */
/* 	  // IP6 addr is now s->sin6_addr; */
/* 	  //} */
/* 	} */
	
	// add it to the list
	sp->adaptorList->adaptors[sp->adaptorList->num_adaptors] = adaptor;
	if(++sp->adaptorList->num_adaptors == sp->adaptorList->capacity)  {
	  // grow
	  sp->adaptorList->capacity *= 2;
	  sp->adaptorList->adaptors = (SFLAdaptor **)my_realloc(sp->adaptorList->adaptors,
								sp->adaptorList->capacity * sizeof(SFLAdaptor *));
	}
      }
    }
  }
  freeifaddrs(ifap);
  return sp->adaptorList->num_adaptors;
}
Exemple #30
0
	void Any::deserializeBody(TextInput& ti, Token& token) {
		char closeSymbol = '}';
		m_type = TABLE;

		const char c = token.string()[0];

		if (c != '{') {
			m_type = ARRAY;
			// Chose the appropriate close symbol
			closeSymbol = (c == '(') ? ')' : ']';
		}

		// Allocate the underlying data structure
		ensureData();
		m_data->source.set(ti, token);

		// Consume the open token
		token = ti.read();

		while (!((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol))) {
			// Read any leading comment.  This must be done here (and not in the recursive deserialize
			// call) in case the body contains only a comment.
			std::string comment;
			deserializeComment(ti, token, comment);

			if ((token.type() == Token::SYMBOL) && (token.string()[0] == closeSymbol)) {
				// We're done; this catches the case where the array is empty
				break;
			}

			// Pointer the value being read
			Any a;
			std::string key;

			if (m_type == TABLE) {
				// Read the key
				if (token.type() != Token::SYMBOL && token.type() != Token::STRING) {
					throw ParseError(ti.filename(), token.line(), token.character(), "Expected a name");
				}

				key = token.string();
				// Consume everything up to the = sign
				token = ti.readSignificant();

				if ((token.type() != Token::SYMBOL) || (token.string() != "=")) {
					throw ParseError(ti.filename(), token.line(), token.character(), "Expected =");
				}
				else {
					// Consume (don't consume comments--we want the value pointed to by a to get those).
					token = ti.read();
				}
			}
			a.deserialize(ti, token);

			if (!comment.empty()) {
				// Prepend the comment we read earlier
				a.ensureData();
				a.m_data->comment = trimWhitespace(comment + "\n" + a.m_data->comment);
			}

			if (m_type == TABLE) {
				set(key, a);
			}
			else {
				append(a);
			}

			// Read until the comma or close paren, discarding trailing comments and newlines
			readUntilCommaOrClose(ti, token);

			// Consume the comma
			if (isSeparator(token.string()[0])) {
				token = ti.read();
			}
		}

		// Consume the close paren (to match other deserialize methods)
		token = ti.read();
	}