Example #1
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::modifyClass
//
// ///////////////////////////////////////////////////////////////////////////
void WMIClassProvider::modifyClass(const String& nameSpace,
                                   const String& userName,
                                   const String& password,
                                   const CIMClass& modifiedClass)
{

    PEG_METHOD_ENTER(TRC_WMIPROVIDER, "WMIClassProvider::modifyClass()");

    setup(nameSpace, userName, password);

    if (!m_bInitialized)
    {
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
            "WMIClassProvider::modifyClass - m_bInitilized= %x, "
            "throw CIM_ERR_FAILED exception",
            m_bInitialized));

        throw CIMException(CIM_ERR_FAILED);
    }

    // check if class does exist
    if (!classAlreadyExists(modifiedClass.getClassName().getString()))
    {
        throw CIMException(CIM_ERR_NOT_FOUND);
    }

    // check if superclass does exist
    if (!classAlreadyExists(modifiedClass.getSuperClassName().getString()))
    {
        // superclass doesn't exist
        throw CIMException(CIM_ERR_INVALID_SUPERCLASS);
    }

    //
    // By Jair
    //
    // If the class already has a superclass and it isn't explicitly
    // defined in the <modifiedClass> definition, we must set it
    // before changing the control to the createClass method. This way
    // we don't change the Class definition, as specified in DSP0200.
    //
    CIMClass updatedClass = modifiedClass;

    if ((updatedClass.getSuperClassName().getString()).size() == 0)
    {
        // set the superclass

        CComPtr<IWbemClassObject> pClass;

        if (!(_collector->getObject(&pClass,
            updatedClass.getClassName().getString())))
        {
            if (pClass)
                pClass.Release();

            throw CIMException(CIM_ERR_NOT_FOUND);
        }

        String superClass = _collector->getSuperClass(pClass);

        if (0 != superClass.size())
        {
            CIMName superclassName = superClass;
            updatedClass.setSuperClassName(superclassName);
        }

        if (pClass)
            pClass.Release();
    }

    //update the class using createClass
    createClass(nameSpace,
                userName,
                password,
                updatedClass,
                true);

    PEG_METHOD_EXIT();

    return;
}
/////////////////////////////////////////////////////////////////////////////
// WMIInstanceProvider::setProperty
//
// ///////////////////////////////////////////////////////////////////////////
void WMIInstanceProvider::setProperty(
        const String& nameSpace,
        const String& userName,
        const String& password,
        const CIMObjectPath& instanceName,
        const String& propertyName,
        const CIMValue& newValue)
{

    CComPtr<IWbemServices>            pServices;
    CComPtr<IWbemClassObject>        pInstance;
    CComVariant                        vValue;
    CComBSTR                        bsPropName;
    HRESULT                            hr;
    String                            sInstanceName;

    PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIInstanceProvider::setProperty()");

    sInstanceName = getObjectName(instanceName);

    setup(nameSpace, userName, password);

    PEG_TRACE((TRC_WMIPROVIDER,
                  Tracer::LEVEL3,
                  "setProperty() - setting property %s in %s",
                  propertyName,
                  sInstanceName));

    if (!m_bInitialized)
    {
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
            "WMIInstanceProvider::setProperty - m_bInitilized= %x, "
            "throw CIM_ERR_FAILED exception",
            m_bInitialized));

        throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED,
            "Collector initialization failed.");
    }

    // retrieve instance object
    if (!(_collector->getObject(&pInstance, sInstanceName)))
    {
        if (pInstance)
            pInstance.Release();

        throw CIMException(CIM_ERR_NOT_FOUND);
    }
    //else if ((!(_collector->isInstance(pInstance))) || (prop == ""))
    else if ((!(_collector->isInstance(pInstance))) ||
        (propertyName.size() == 0))
    {
        if (pInstance)
            pInstance.Release();

        throw CIMException(CIM_ERR_INVALID_PARAMETER);
    }

    //check if property exists
    CIMInstance cimInstance;
    Array<CIMName> propertyNames;
    CIMName propName = propertyName;

    propertyNames.append(propName);
    CIMPropertyList propertyList = CIMPropertyList(propertyNames);

    cimInstance = getCIMInstance(nameSpace,
                                 userName,
                                 password,
                                 instanceName,
                                 propertyList);

    Uint32 pos = cimInstance.findProperty(propName);

    if (PEG_NOT_FOUND == pos)
    {
        throw CIMException(CIM_ERR_NO_SUCH_PROPERTY);
    }

    // check the existing value and type
    //bsPropName = prop.Bstr();
    bsPropName = propertyName.getCString();

    //convert property value from CIMValue to VARIANT
    WMIValue(newValue).getAsVariant(&vValue, nameSpace, userName, password);

    //update property value
    hr = pInstance->Put(bsPropName, 0, &vValue, 0);
    vValue.Clear();

    if (FAILED(hr))
    {
        if (pInstance)
            pInstance.Release();

        switch(hr)
        {
            case WBEM_E_TYPE_MISMATCH:
                throw CIMException(CIM_ERR_TYPE_MISMATCH);
            default:
                PEG_TRACE((TRC_WMIPROVIDER,
                              Tracer::LEVEL1,
                              "setProperty() - Put failed, hr = %x",
                              hr));

                throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED,
                    "WMI Put property failed.");
        }

    }

    //update instance
    _collector->Connect(&pServices);

    hr = pServices->PutInstance(pInstance,
                                WBEM_FLAG_UPDATE_ONLY,
                                NULL,
                                NULL);

    if (pInstance)
        pInstance.Release();

    if (pServices)
        pServices.Release();

    if (FAILED(hr))
    {
        PEG_TRACE((TRC_WMIPROVIDER,
                      Tracer::LEVEL1,
                      "setProperty() - PutInstance failed, hr = %x",
                      hr));

        throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED,
            "WMI Put instance failed.");
    }

    PEG_METHOD_EXIT();

    return;
}
void LuaChunk::store(String& s, size_t size){
  int pos = (int)s.size();
  s.resize(pos + sizeof(size_t));
  memcpy(&s[pos], &size, sizeof(size_t));
}
Example #4
0
void f_header(CStrRef str, bool replace /* = true */,
              int http_response_code /* = 0 */) {
  if (f_headers_sent()) {
    raise_warning("Cannot modify header information - headers already sent");
  }

  String header = f_rtrim(str);

  // new line safety check
  // NOTE: PHP actually allows "\n " and "\n\t" to fall through. Is that bad
  // for security?
  if (header.find('\n') >= 0 || header.find('\r') >= 0) {
    raise_warning("Header may not contain more than a single header, "
                  "new line detected");
    return;
  }

  Transport *transport = g_context->getTransport();
  if (transport && header->size()) {
    const char *header_line = header->data();

    // handle single line of status code
    if (header->size() >= 5 && strncasecmp(header_line, "HTTP/", 5) == 0) {
      int code = 200;
      for (const char *ptr = header_line; *ptr; ptr++) {
        if (*ptr == ' ' && *(ptr + 1) != ' ') {
          code = atoi(ptr + 1);
          break;
        }
      }
      if (code) {
        transport->setResponse(code, "explicit_header");
      }
      return;
    }

    const char *colon_offset = strchr(header_line, ':');
    String newHeader;
    if (colon_offset) {
      if (!strncasecmp(header_line, "Content-Type",
                       colon_offset - header_line)) {
        const char *ptr = colon_offset+1, *mimetype = NULL;
        while (*ptr == ' ') ptr++;
        mimetype = ptr;
        if (strncmp(mimetype, "text/", 5) == 0 &&
            strstr(mimetype, "charset=") == NULL) {
          newHeader = header + ";charset=utf-8";
        }
      }
    }
    if (replace) {
      transport->replaceHeader(newHeader.empty() ? header : newHeader);
    } else {
      transport->addHeader(newHeader.empty() ? header : newHeader);
    }
    if (http_response_code) {
      transport->setResponse(http_response_code,
                             "explicit_header_response_code");
    }
  }
}
Example #5
0
void CommandlineParser::printHelp(const set<String>& parameter_names, bool show_manual)
{
	if (parameter_names.size() == 0 && registered_parameters_.size() > 0)
	{
		Log << "Available parameters are ('*' indicates mandatory parameters): " << endl;
	}

	for (list<MapIterator>::iterator it = original_parameter_order_.begin(); it != original_parameter_order_.end(); it++)
	{
		ParameterDescription& p = (*it)->second;
		if (((parameter_names.size() > 0) && parameter_names.find(p.name) == parameter_names.end()) || p.advanced)
		{
			continue;
		}
		Log << "   ";
		if ((parameter_names.size() == 0) && p.mandatory) 
		{
			Log<<"*  ";
		}
		else 
		{
		  Log << "   ";
		}
		Log << "-" << p.name;
		String n = "";
		if (p.type == INFILE)
		{
			n = " <in.file>";
		}
		else if (p.type == OUTFILE)
		{
			n = " <out.file>";
		}
		else if (p.type == BALL::INT)
		{
			n = " <int>";
		}
		else if (p.type == DOUBLE)
		{
			n = " <double>";
		}
		else if (p.type == STRING)
		{
			n = " <string>";
		}
		Log<<n;
		Size space_size = max_parname_length_+4-p.name.size()-n.size();
		for (Size j = 0; j < space_size; j++)
		{
			Log << " ";
		}
		Log << p.description << endl;
	}
	if (parameter_names.size() == 0 && registered_flags_.size() > 0)
	{
		Log << endl << "Available flags are: " << endl;
	}
	for (list<MapIterator>::iterator it = original_flag_order_.begin(); it != original_flag_order_.end(); it++)
	{
		ParameterDescription& p = (*it)->second;
		if (parameter_names.size() > 0 && parameter_names.find(p.name) == parameter_names.end())
		{
			continue;
		}
		Log << "      " << "-" << p.name << String(' ', max_flagname_length_ + 4 - p.name.size())
        << p.description << endl;
	}
	Log << endl;
	if (show_manual && tool_manual_ != "")
	{
		Log << endl << tool_manual_ << endl << endl << endl;
	}
}
Example #6
0
int main( int argc, const char** argv )
{
    CvCapture* capture = 0;
    Mat frame, frameCopy, image;
    const String scaleOpt = "--scale=";
    size_t scaleOptLen = scaleOpt.length();
    const String cascadeOpt = "--cascade=";
    size_t cascadeOptLen = cascadeOpt.length();
    const String nestedCascadeOpt = "--nested-cascade";
    size_t nestedCascadeOptLen = nestedCascadeOpt.length();
    String inputName;

    help();

    CascadeClassifier cascade, nestedCascade;
    double scale = 1;

    for( int i = 1; i < argc; i++ )
    {
        cout << "Processing " << i << " " <<  argv[i] << endl;
        if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
        {
            cascadeName.assign( argv[i] + cascadeOptLen );
            cout << "  from which we have cascadeName= " << cascadeName << endl;
        }
        else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 )
        {
            if( argv[i][nestedCascadeOpt.length()] == '=' )
                nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 );
            if( !nestedCascade.load( nestedCascadeName ) )
                cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
        }
        else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )
        {
            if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 )
                scale = 1;
            cout << " from which we read scale = " << scale << endl;
        }
        else if( argv[i][0] == '-' )
        {
            cerr << "WARNING: Unknown option %s" << argv[i] << endl;
        }
        else
            inputName.assign( argv[i] );
    }

    if( !cascade.load( cascadeName ) )
    {
        cerr << "ERROR: Could not load classifier cascade" << endl;
        cerr << "Usage: facedetect [--cascade=<cascade_path>]\n"
            "   [--nested-cascade[=nested_cascade_path]]\n"
            "   [--scale[=<image scale>\n"
            "   [filename|camera_index]\n" << endl ;
        return -1;
    }

    if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
    {
        capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' );
        int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ;
        if(!capture) cout << "Capture from CAM " <<  c << " didn't work" << endl;
    }
    else if( inputName.size() )
    {
        image = imread( inputName, 1 );
        if( image.empty() )
        {
            capture = cvCaptureFromAVI( inputName.c_str() );
            if(!capture) cout << "Capture from AVI didn't work" << endl;
        }
    }
    else
    {
        image = imread( "lena.jpg", 1 );
        if(image.empty()) cout << "Couldn't read lena.jpg" << endl;
    }

    cvNamedWindow( "result", 1 );

    if( capture )
    {
        cout << "In capture ..." << endl;
        for(;;)
        {
            IplImage* iplImg = cvQueryFrame( capture );
            frame = iplImg;
            if( frame.empty() )
                break;
            if( iplImg->origin == IPL_ORIGIN_TL )
                frame.copyTo( frameCopy );
            else
                flip( frame, frameCopy, 0 );

            detectAndDraw( frameCopy, cascade, nestedCascade, scale );

            if( waitKey( 10 ) >= 0 )
                goto _cleanup_;
        }

        waitKey(0);

_cleanup_:
        cvReleaseCapture( &capture );
    }
    else
    {
        cout << "In image read" << endl;
        if( !image.empty() )
        {
            detectAndDraw( image, cascade, nestedCascade, scale );
            waitKey(0);
        }
        else if( !inputName.empty() )
        {
            /* assume it is a text file containing the
            list of the image filenames to be processed - one per line */
            FILE* f = fopen( inputName.c_str(), "rt" );
            if( f )
            {
                char buf[1000+1];
                while( fgets( buf, 1000, f ) )
                {
                    int len = (int)strlen(buf), c;
                    while( len > 0 && isspace(buf[len-1]) )
                        len--;
                    buf[len] = '\0';
                    cout << "file " << buf << endl;
                    image = imread( buf, 1 );
                    if( !image.empty() )
                    {
                        detectAndDraw( image, cascade, nestedCascade, scale );
                        c = waitKey(0);
                        if( c == 27 || c == 'q' || c == 'Q' )
                            break;
                    }
                    else
                    {
                    	cerr << "Aw snap, couldn't read image " << buf << endl;
                    }
                }
                fclose(f);
            }
        }
    }

    cvDestroyWindow("result");

    return 0;
}
bool ModificationDefinitionsSet::isCompatible(const AASequence & peptide) const
{
    set<String> var_names(getVariableModificationNames()), fixed_names(getFixedModificationNames());
    // no modifications present and needed
    if (fixed_names.empty() && !peptide.isModified())
    {
        return true;
    }

    // check whether the fixed modifications are fulfilled
    if (!fixed_names.empty())
    {
        for (set<String>::const_iterator it1 = fixed_names.begin(); it1 != fixed_names.end(); ++it1)
        {
            String origin = ModificationsDB::getInstance()->getModification(*it1).getOrigin();
            // only single 1lc amino acids are allowed
            if (origin.size() != 1)
            {
                continue;
            }
            for (AASequence::ConstIterator it2 = peptide.begin(); it2 != peptide.end(); ++it2)
            {
                if (origin == it2->getOneLetterCode())
                {
                    // check whether the residue is modified (has to be)
                    if (!it2->isModified())
                    {
                        return false;
                    }
                    // check whether the modification is the same
                    if (ModificationsDB::getInstance()->getModification(*it1).getId() != it2->getModification())
                    {
                        return false;
                    }
                }
            }
        }
    }

    // check wether other modifications than the variable are present
    for (AASequence::ConstIterator it = peptide.begin(); it != peptide.end(); ++it)
    {
        if (it->isModified())
        {
            String mod = ModificationsDB::getInstance()->getModification(it->getOneLetterCode(), it->getModification(), ResidueModification::ANYWHERE).getFullId();
            if (var_names.find(mod) == var_names.end() &&
                    fixed_names.find(mod) == fixed_names.end())
            {
                return false;
            }
        }
    }

    if (peptide.hasNTerminalModification())
    {
        String mod = ModificationsDB::getInstance()->getTerminalModification(peptide.getNTerminalModification(), ResidueModification::N_TERM).getFullId();
        if (var_names.find(mod) == var_names.end() &&
                fixed_names.find(mod) == fixed_names.end())
        {
            return false;
        }
    }

    if (peptide.hasCTerminalModification())
    {
        String mod = ModificationsDB::getInstance()->getTerminalModification(peptide.getCTerminalModification(), ResidueModification::C_TERM).getFullId();
        if (var_names.find(mod) == var_names.end() &&
                fixed_names.find(mod) == fixed_names.end())
        {
            return false;
        }
    }

    return true;
}
Example #8
0
 String getDatabaseMetadataPath(const String & base_path)
 {
     return (endsWith(base_path, "/") ? base_path.substr(0, base_path.size() - 1) : base_path) + ".sql";
 }
bool mm::parse(ID3_TagImpl& tag, ID3_Reader& rdr)
{
  io::ExitTrigger et(rdr);
  ID3_Reader::pos_type end = rdr.getCur();
  if (end < rdr.getBeg() + 48)
  {
    ID3D_NOTICE( "mm::parse: bailing, not enough bytes to parse, pos = " << end );
    return false;
  }
  
  rdr.setCur(end - 48);
  String version;
  
  {
    if (io::readText(rdr, 32) != "Brava Software Inc.             ")
    {
      ID3D_NOTICE( "mm::parse: bailing, couldn't find footer" );
      return false;
    }
    
    version = io::readText(rdr, 4);
    if (version.size() != 4 || 
        !isdigit(version[0]) || version[1] != '.' ||
        !isdigit(version[2]) || 
        !isdigit(version[3]))
    {
      ID3D_WARNING( "mm::parse: bailing, nonstandard version = " << version );
      return false;
    }
  }
    
  ID3_Reader::pos_type beg = rdr.setCur(end - 48);
  et.setExitPos(beg);
  if (end < 68)
  {
    ID3D_NOTICE( "mm::parse: bailing, not enough bytes to parse offsets, pos = " << end );
    return false;
  }
  rdr.setCur(end - 68);
    
  io::WindowedReader dataWindow(rdr);
  dataWindow.setEnd(rdr.getCur());

  size_t offsets[5];
    
  io::WindowedReader offsetWindow(rdr, 20);
  for (size_t i = 0; i < 5; ++i)
  {
    offsets[i] = io::readLENumber(rdr, sizeof(uint32));
  }

  size_t metadataSize = 0;
  if (version <= "3.00")
  {
    // All MusicMatch tags up to and including version 3.0 had metadata 
    // sections exactly 7868 bytes in length.
    metadataSize = 7868;
  }
  else
  {
    // MusicMatch tags after version 3.0 had three possible lengths for their
    // metadata sections.  We can determine which it was by searching for
    // the version section signature that should precede the metadata section
    // by exactly 256 bytes.
    size_t possibleSizes[] = { 8132, 8004, 7936 };
      
    for (size_t i = 0; i < sizeof(possibleSizes)/sizeof(size_t); ++i)
    {
      dataWindow.setCur(dataWindow.getEnd());
        
      // Our offset will be exactly 256 bytes prior to our potential metadata
      // section
      size_t offset = possibleSizes[i] + 256;
      if (dataWindow.getCur() < offset)
      {
        // if our filesize is less than the offset, then it can't possibly
        // be the correct offset, so try again.
        continue;
      }
      dataWindow.setCur(dataWindow.getCur() - offset);
        
      // now read in the signature to see if it's a match
      if (io::readText(dataWindow, 8) == "18273645")
      {
        metadataSize = possibleSizes[i];
        break;
      }
    }
  }
  if (0 == metadataSize)
  {
    // if we didn't establish a size for the metadata, then something is
    // wrong.  probably should log this.
    ID3D_WARNING( "mm::parse: bailing, couldn't find meta data signature, end = " << end );
    return false;
  }
    
  // parse the offset pointers to determine the actual sizes of all the 
  // sections
  size_t sectionSizes[5];
  size_t tagSize = metadataSize;
    
  // we already know the size of the last section
  sectionSizes[4] = metadataSize;
    
  size_t lastOffset = 0;
  for (int i = 0; i < 5; i++)
  {
    size_t thisOffset = offsets[i];
    //ASSERT(thisOffset > lastOffset);
    if (i > 0)
    {
      size_t sectionSize = thisOffset - lastOffset;
      sectionSizes[i-1] = sectionSize;
      tagSize += sectionSize;
    }
    lastOffset = thisOffset;
  }
    
  // now check to see that our tag size is reasonable
  if (dataWindow.getEnd() < tagSize)
  {
    // Ack!  The tag size doesn't jive with the tag's ending position in
    // the file.  Bail!
    ID3D_WARNING( "mm::parse: bailing, tag size is too big, tag size = " << tagSize << ", end = " << end );
    return false;
  }

  dataWindow.setBeg(dataWindow.getEnd() - tagSize);
  dataWindow.setCur(dataWindow.getBeg());
    
  // Now calculate the adjusted offsets
  offsets[0] = dataWindow.getBeg();
  for (size_t i = 0; i < 4; ++i)
  {
    offsets[i+1] = offsets[i] + sectionSizes[i];
  }
    
  // now check for a tag header and adjust the tag_beg pointer appropriately
  if (dataWindow.getBeg() >= 256)
  {
    rdr.setCur(dataWindow.getBeg() - 256);
    if (io::readText(rdr, 8) == "18273645")
    {
      et.setExitPos(rdr.getCur() - 8);
    }
    else
    {
      et.setExitPos(dataWindow.getBeg());
    }
    dataWindow.setCur(dataWindow.getBeg());
  }
    
  // Now parse the various sections...
    
  // Parse the image extension at offset 0
  dataWindow.setCur(offsets[0]);
  String imgExt = io::readTrailingSpaces(dataWindow, 4);
    
  // Parse the image binary at offset 1
  dataWindow.setCur(offsets[1]);
  uint32 imgSize = io::readLENumber(dataWindow, 4);
  if (imgSize == 0)
  {
    // no image binary.  don't do anything.
  }
  else
  {
    io::WindowedReader imgWindow(dataWindow, imgSize);
    if (imgWindow.getEnd() < imgWindow.getBeg() + imgSize)
    {
      // Ack!  The image size given extends beyond the next offset!  This is 
      // not good...  log?
    }
    else
    {
      BString imgData = io::readAllBinary(imgWindow);
      ID3_Frame* frame = new ID3_Frame(ID3FID_PICTURE);
      if (frame)
      {
        String mimetype("image/");
        mimetype += imgExt;
        frame->GetField(ID3FN_MIMETYPE)->Set(mimetype.c_str());
        frame->GetField(ID3FN_IMAGEFORMAT)->Set("");
        frame->GetField(ID3FN_PICTURETYPE)->Set(static_cast<unsigned int>(0));
        frame->GetField(ID3FN_DESCRIPTION)->Set("");
        frame->GetField(ID3FN_DATA)->Set(reinterpret_cast<const uchar*>(imgData.data()), imgData.size());
        tag.AttachFrame(frame);
      }
    }
  }
    
  //file.seekg(offsets[2]);
  //file.seekg(offsets[3]);
  dataWindow.setCur(offsets[4]);
    
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_TITLE));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_ALBUM));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_LEADARTIST));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_CONTENTTYPE));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Tempo"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Mood"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Situation"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Preference"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_SONGLEN));
    
  // The next 12 bytes can be ignored.  The first 8 represent the 
  // creation date as a 64 bit floating point number.  The last 4 are
  // for a play counter.
  dataWindow.skipChars(12);
    
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Path"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Serial"));
    
  // 2 bytes for track
  uint32 trkNum = io::readLENumber(dataWindow, 2);
  if (trkNum > 0)
  {
    String trkStr = toString(trkNum);
    ID3_Frame* frame = new ID3_Frame(ID3FID_TRACKNUM);
    if (frame)
    {
      frame->GetField(ID3FN_TEXT)->Set(trkStr.c_str());
      tag.AttachFrame(frame);
    }
  }
    
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Notes"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_Bio"));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_UNSYNCEDLYRICS));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_WWWARTIST));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_WWWCOMMERCIALINFO));
  tag.AttachFrame(readTextFrame(dataWindow, ID3FID_COMMENT, "MusicMatch_ArtistEmail"));
    
  // email?

  return true;
}
Example #10
0
void WriteStream::writeString(const String &str) {
	write(str.c_str(), str.size());
}
Example #11
0
void DatabaseOrdinary::createTable(
    const Context & context,
    const String & table_name,
    const StoragePtr & table,
    const ASTPtr & query)
{
    const auto & settings = context.getSettingsRef();

    /// Create a file with metadata if necessary - if the query is not ATTACH.
    /// Write the query of `ATTACH table` to it.

    /** The code is based on the assumption that all threads share the same order of operations
      * - creating the .sql.tmp file;
      * - adding a table to `tables`;
      * - rename .sql.tmp to .sql.
      */

    /// A race condition would be possible if a table with the same name is simultaneously created using CREATE and using ATTACH.
    /// But there is protection from it - see using DDLGuard in InterpreterCreateQuery.

    {
        std::lock_guard<std::mutex> lock(mutex);
        if (tables.find(table_name) != tables.end())
            throw Exception("Table " + name + "." + table_name + " already exists.", ErrorCodes::TABLE_ALREADY_EXISTS);
    }

    String table_metadata_path = getTableMetadataPath(table_name);
    String table_metadata_tmp_path = table_metadata_path + ".tmp";
    String statement;

    {
        statement = getTableDefinitionFromCreateQuery(query);

        /// Exclusive flags guarantees, that table is not created right now in another thread. Otherwise, exception will be thrown.
        WriteBufferFromFile out(table_metadata_tmp_path, statement.size(), O_WRONLY | O_CREAT | O_EXCL);
        writeString(statement, out);
        out.next();
        if (settings.fsync_metadata)
            out.sync();
        out.close();
    }

    try
    {
        /// Add a table to the map of known tables.
        {
            std::lock_guard<std::mutex> lock(mutex);
            if (!tables.emplace(table_name, table).second)
                throw Exception("Table " + name + "." + table_name + " already exists.", ErrorCodes::TABLE_ALREADY_EXISTS);
        }

        /// If it was ATTACH query and file with table metadata already exist
        /// (so, ATTACH is done after DETACH), then rename atomically replaces old file with new one.
        Poco::File(table_metadata_tmp_path).renameTo(table_metadata_path);
    }
    catch (...)
    {
        Poco::File(table_metadata_tmp_path).remove();
        throw;
    }
}
Example #12
0
int main(int argc, char *argv[])
{
  CSimpleOpt s(argc, argv, argumentSpecifications);
  
  logger.setDefaultLogLevel(LOG_DEBUG);
  
  String xmlFile;
  
  char *endptr;
  
  while (s.Next())
  {
    if (s.LastError() != SO_SUCCESS)
    {
      std::cout << s.GetLastErrorText(s.LastError()) << ": '" << s.OptionText() << "' (use -h to get command line help)" << std::endl;
      help();
      return -1;
    }
    
    //std::cout << s.OptionId() << ": " << s.OptionArg() << std::endl;
    
    Vector<String> splits;
    switch (s.OptionId())
    {
      case XML_FILE:
        xmlFile = s.OptionArg();
        break;
        
      default:
        help();
        break;
    };
  }
  
  if(xmlFile.size() == 0)
  {
    logger(LOG_ERROR) << "Required argument missing." << std::endl;
    help();
    return -1;
  }
  
  std::ifstream f(xmlFile, std::ios::binary);
  
  if(!f.good())
  {
    logger(LOG_ERROR) << "Failed to open '" << xmlFile << "'" << std::endl;
    return -1;
  }
  
  f.close();
  
  //XMLDocument doc;
  
  //doc.LoadFile(xmlFile.c_str());
  
  //XMLElement *node = doc.FirstChildElement("RegMap");
  
  DummyRegisterProgrammer r;
  
  ParameterDMLParser p(r, xmlFile);
  
  Vector<ParameterPtr> params;
  
  p.getParameters(params);
  
  return 0;
  
}
Example #13
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::createProperties creates all properties including keys
//                                      add the qualifiers too
// ///////////////////////////////////////////////////////////////////////////
void WMIClassProvider::createProperties(const CIMClass& newClass,
                                        IWbemServices *pServices,
                                        IWbemClassObject *pNewClass)
{
    HRESULT hr;

    PEG_METHOD_ENTER(TRC_WMIPROVIDER, "WmiClassProvider::createProperties()");

    // create the properties but don't create the keys again
    CIMProperty prop;

    for (Uint32 i = 0; i < newClass.getPropertyCount(); i++)
    {
        prop = newClass.getProperty(i).clone();

        // create the properties
        try
        {
            createProperty(prop, pNewClass);
        }
        catch (CIMException&)
        {
            throw;
        }

        // get a pointer to work with qualifiers
        CComPtr<IWbemQualifierSet> pQual;
        CComBSTR bs = prop.getName().getString().getCString();

        hr = pNewClass->GetPropertyQualifierSet(bs, &pQual);
        bs.Empty();

        if (FAILED(hr))
        {
            CMyString msg;
            msg.Format("Failed get Qualifier set of [%s]. Error: 0x%X", 255,
                prop.getName().getString().getCString(), hr);

            PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
                "WMIClassProvider::createProperties() - %s", (LPCTSTR)msg));

            if (pQual)
                pQual.Release();

            throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
        }

        // set the qualifiers to the property
        for (Uint32 j = 0; j < prop.getQualifierCount(); j++)
        {
            WMIQualifier qualifier(prop.getQualifier(j));
            try
            {
                createQualifier(qualifier, pQual);
            }
            catch (CIMException&)
            {
                if (pQual)
                    pQual.Release();

                throw;
            }
        }

        // set the CLASSORIGIN qualifier if it wasn't set yet
        String strClassorigin = prop.getClassOrigin().getString();

        if (strClassorigin.size() == 0)
        {
            strClassorigin = newClass.getClassName().getString();
        }

        WMIFlavor flavor(CIMFlavor::DEFAULTS);

        /*
        v.vt = VT_BSTR;
        v.bstrVal = strClassorigin.getCString();
        */
        CComVariant v;
        v = strClassorigin.getCString();

        hr = pQual->Put(L"CLASSORIGIN", &v, flavor.getAsWMIValue());
        v.Clear();

        if (pQual)
            pQual.Release();

        if (FAILED(hr))
        {
            CMyString msg;
            msg.Format("Failed to add CLASSORIGIN qualifier in [%s]. Error: "
                "0x%X", 255, prop.getName().getString().getCString(), hr);

            PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
                          "WMIClassProvider::createProperties () - %s",
                          (LPCTSTR)msg));

            throw CIMException(CIM_ERR_FAILED, (LPCTSTR)msg);
        }
    }

    PEG_METHOD_EXIT();

    return;
}
Example #14
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::getClass
//
/// virtual class CIMClass. From the operations class
// ///////////////////////////////////////////////////////////////////////////
CIMClass WMIClassProvider::getClass(
        const String& nameSpace,
        const String& userName,
        const String& password,
        const String& className,
        Boolean localOnly,
        Boolean includeQualifiers,
        Boolean includeClassOrigin,
        const CIMPropertyList& propertyList)
{
    PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIClassProvider::getClass()");

    CComPtr<IWbemClassObject> pClass;

    setup(nameSpace,userName,password);

    PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL3,
        "getClass - localOnly %x, includeQualifiers %x, includeClassOrigin %x",
        localOnly, includeQualifiers, includeClassOrigin));

    if (!m_bInitialized)
    {
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
            "WMIClassProvider::getClass - m_bInitilized= %x, "
                "throw CIM_ERR_FAILED exception",
            m_bInitialized));

        throw CIMException(CIM_ERR_FAILED);
    }

    try
    {
        if (!(_collector->getObject(&pClass, className)))
        {
            if (pClass)
                pClass.Release();

            throw CIMException(CIM_ERR_NOT_FOUND);
        }
        else if (_collector->isInstance(pClass))
        {
            if (pClass)
                pClass.Release();

            throw CIMException(CIM_ERR_INVALID_PARAMETER);
        }
    }
    catch (CIMException &e)
    {
        if (pClass)
            pClass.Release();

        switch(e.getCode())
        {
            case CIM_ERR_INVALID_CLASS:
                throw CIMException(CIM_ERR_NOT_FOUND);
                break;
            default: throw;
        }
    }

    String superClass = _collector->getSuperClass(pClass);
    CIMName objName = className;
    CIMClass cimClass = CIMClass(objName);

    if (0 != superClass.size())
    {
        CIMName superclassName = superClass;
        cimClass.setSuperClassName(superclassName);
    }

    if (!(_collector->getCIMClass(pClass,
                cimClass,
                localOnly,
                includeQualifiers,
                includeClassOrigin,
                propertyList)))
    {
        throw CIMException(CIM_ERR_NOT_FOUND);
    }

    if (pClass)
        pClass.Release();

    PEG_METHOD_EXIT();

    return cimClass;
}
Example #15
0
/**
 * New sprintf implementation for PHP.
 *
 * Modifiers:
 *
 *  " "   pad integers with spaces
 *  "-"   left adjusted field
 *   n    field size
 *  "."n  precision (floats only)
 *  "+"   Always place a sign (+ or -) in front of a number
 *
 * Type specifiers:
 *
 *  "%"   literal "%", modifiers are ignored.
 *  "b"   integer argument is printed as binary
 *  "c"   integer argument is printed as a single character
 *  "d"   argument is an integer
 *  "f"   the argument is a float
 *  "o"   integer argument is printed as octal
 *  "s"   argument is a string
 *  "x"   integer argument is printed as lowercase hexadecimal
 *  "X"   integer argument is printed as uppercase hexadecimal
 */
char *string_printf(const char *format, int len, CArrRef args, int *outlen) {
  Array vargs = args;
  if (!vargs.isNull() && !vargs->isVectorData()) {
    vargs = Array::Create();
    for (ArrayIter iter(args); iter; ++iter) {
      vargs.append(iter.second());
    }
  }

  if (len == 0) {
    return strdup("");
  }

  int size = 240;
  char *result = (char *)malloc(size);
  int outpos = 0;

  int argnum = 0, currarg = 1;
  for (int inpos = 0; inpos < len; ++inpos) {
    char ch = format[inpos];

    int expprec = 0;
    if (ch != '%') {
      appendchar(&result, &outpos, &size, ch);
      continue;
    }

    if (format[inpos + 1] == '%') {
      appendchar(&result, &outpos, &size, '%');
      inpos++;
      continue;
    }

    /* starting a new format specifier, reset variables */
    int alignment = ALIGN_RIGHT;
    int adjusting = 0;
    char padding = ' ';
    int always_sign = 0;
    int width, precision;
    inpos++;      /* skip the '%' */
    ch = format[inpos];

    if (isascii(ch) && !isalpha(ch)) {
      /* first look for argnum */
      int temppos = inpos;
      while (isdigit((int)format[temppos])) temppos++;
      if (format[temppos] == '$') {
        argnum = getnumber(format, &inpos);
        if (argnum <= 0) {
          free(result);
          throw_invalid_argument("argnum: must be greater than zero");
          return NULL;
        }
        inpos++;  /* skip the '$' */
      } else {
        argnum = currarg++;
      }

      /* after argnum comes modifiers */
      for (;; inpos++) {
        ch = format[inpos];

        if (ch == ' ' || ch == '0') {
          padding = ch;
        } else if (ch == '-') {
          alignment = ALIGN_LEFT;
          /* space padding, the default */
        } else if (ch == '+') {
          always_sign = 1;
        } else if (ch == '\'') {
          padding = format[++inpos];
        } else {
          break;
        }
      }
      ch = format[inpos];

      /* after modifiers comes width */
      if (isdigit(ch)) {
        if ((width = getnumber(format, &inpos)) < 0) {
          free(result);
          throw_invalid_argument("width: must be greater than zero "
                                 "and less than %d", INT_MAX);
          return NULL;
        }
        adjusting |= ADJ_WIDTH;
      } else {
        width = 0;
      }
      ch = format[inpos];

      /* after width and argnum comes precision */
      if (ch == '.') {
        ch = format[++inpos];
        if (isdigit((int)ch)) {
          if ((precision = getnumber(format, &inpos)) < 0) {
            free(result);
            throw_invalid_argument("precision: must be greater than zero "
                                   "and less than %d", INT_MAX);
            return NULL;
          }
          ch = format[inpos];
          adjusting |= ADJ_PRECISION;
          expprec = 1;
        } else {
          precision = 0;
        }
      } else {
        precision = 0;
      }
    } else {
      width = precision = 0;
      argnum = currarg++;
    }

    if (argnum > vargs.size()) {
      free(result);
      throw_invalid_argument("arguments: (too few)");
      return NULL;
    }

    if (ch == 'l') {
      ch = format[++inpos];
    }
    /* now we expect to find a type specifier */
    Variant tmp = vargs[argnum-1];

    switch (ch) {
    case 's': {
      String s = tmp.toString();
      appendstring(&result, &outpos, &size, s,
                   width, precision, padding, alignment, s.size(),
                   0, expprec, 0);
      break;
    }
    case 'd':
      appendint(&result, &outpos, &size, tmp.toInt64(),
                width, padding, alignment, always_sign);
      break;
    case 'u':
      appenduint(&result, &outpos, &size, tmp.toInt64(),
                 width, padding, alignment);
      break;

    case 'g':
    case 'G':
    case 'e':
    case 'E':
    case 'f':
    case 'F':
      appenddouble(&result, &outpos, &size, tmp.toDouble(),
                   width, padding, alignment, precision, adjusting,
                   ch, always_sign);
      break;

    case 'c':
      appendchar(&result, &outpos, &size, tmp.toByte());
      break;

    case 'o':
      append2n(&result, &outpos, &size, tmp.toInt64(),
               width, padding, alignment, 3, hexchars, expprec);
      break;

    case 'x':
      append2n(&result, &outpos, &size, tmp.toInt64(),
               width, padding, alignment, 4, hexchars, expprec);
      break;

    case 'X':
      append2n(&result, &outpos, &size, tmp.toInt64(),
               width, padding, alignment, 4, HEXCHARS, expprec);
      break;

    case 'b':
      append2n(&result, &outpos, &size, tmp.toInt64(),
               width, padding, alignment, 1, hexchars, expprec);
      break;

    case '%':
      appendchar(&result, &outpos, &size, '%');

      break;
    default:
      break;
    }
  }

  /* possibly, we have to make sure we have room for the terminating null? */
  result[outpos]=0;
  if (outlen) *outlen = outpos;
  return result;
}
Example #16
0
void Item::toString( String &target ) const
{
   target.size(0);

   switch( this->type() )
   {
      case FLC_ITEM_NIL:
         target = "Nil";
      break;

      case FLC_ITEM_UNB:
         target = "_";
      break;

      case FLC_ITEM_BOOL:
         target = asBoolean() ? "true" : "false";
      break;


      case FLC_ITEM_INT:
         target.writeNumber( this->asInteger() );
      break;

      case FLC_ITEM_RANGE:
         target = "[";
         target.writeNumber( (int64) this->asRangeStart() );
         target += ":";
         if ( ! this->asRangeIsOpen() )
         {
            target.writeNumber( (int64) this->asRangeEnd() );
            if ( this->asRangeStep() != 0 )
            {
               target += ":";
               target.writeNumber( (int64) this->asRangeStep() );
            }
         }
         target += "]";
      break;

      case FLC_ITEM_NUM:
      {
         target.writeNumber( this->asNumeric(), "%.16g" );
      }
      break;

      case FLC_ITEM_MEMBUF:
         target = "MemBuf( ";
         target.writeNumber( (int64) this->asMemBuf()->length() );
         target += ", ";
            target.writeNumber( (int64) this->asMemBuf()->wordSize() );
         target += " )";
      break;

      case FLC_ITEM_STRING:
         target = *asString();
      break;

      case FLC_ITEM_LBIND:
         if ( isFutureBind() )
         {
            String temp;
            asFutureBind().toString(temp);
            target = *asLBind() + "|" + temp;
         }
         else
            target = "&" + *asLBind();
      break;

      case FLC_ITEM_REFERENCE:
         dereference()->toString( target );
      break;

      case FLC_ITEM_OBJECT:
         target = "Object from " + asObjectSafe()->generator()->symbol()->name();
      break;

      case FLC_ITEM_ARRAY:
         target = "Array";
      break;

      case FLC_ITEM_DICT:
         target = "Dictionary";
      break;

      case FLC_ITEM_FUNC:
         target = "Function " + this->asFunction()->symbol()->name();
      break;

      case FLC_ITEM_CLASS:
         target = "Class " + this->asClass()->symbol()->name();
      break;

      case FLC_ITEM_METHOD:
         {
            Item orig;
            this->getMethodItem( orig );
            String temp;
            orig.dereference()->toString( temp );
            target = "Method (" + temp + ")." + this->asMethodFunc()->name();
         }
      break;

      case FLC_ITEM_CLSMETHOD:
         target = "ClsMethod " + this->asMethodClass()->symbol()->name();
      break;

      default:
         target = "<?>";
   }
}
Example #17
0
Error BitmapFont::create_from_fnt(const String &p_file) {
	//fnt format used by angelcode bmfont
	//http://www.angelcode.com/products/bmfont/

	FileAccess *f = FileAccess::open(p_file, FileAccess::READ);

	if (!f) {
		ERR_EXPLAIN("Can't open font: " + p_file);
		ERR_FAIL_V(ERR_FILE_NOT_FOUND);
	}

	clear();

	while (true) {

		String line = f->get_line();

		int delimiter = line.find(" ");
		String type = line.substr(0, delimiter);
		int pos = delimiter + 1;
		Map<String, String> keys;

		while (pos < line.size() && line[pos] == ' ')
			pos++;

		while (pos < line.size()) {

			int eq = line.find("=", pos);
			if (eq == -1)
				break;
			String key = line.substr(pos, eq - pos);
			int end = -1;
			String value;
			if (line[eq + 1] == '"') {
				end = line.find("\"", eq + 2);
				if (end == -1)
					break;
				value = line.substr(eq + 2, end - 1 - eq - 1);
				pos = end + 1;
			} else {
				end = line.find(" ", eq + 1);
				if (end == -1)
					end = line.size();

				value = line.substr(eq + 1, end - eq);

				pos = end;
			}

			while (pos < line.size() && line[pos] == ' ')
				pos++;

			keys[key] = value;
		}

		if (type == "info") {

			if (keys.has("face"))
				set_name(keys["face"]);
			/*
			if (keys.has("size"))
				font->set_height(keys["size"].to_int());
			*/

		} else if (type == "common") {

			if (keys.has("lineHeight"))
				set_height(keys["lineHeight"].to_int());
			if (keys.has("base"))
				set_ascent(keys["base"].to_int());

		} else if (type == "page") {

			if (keys.has("file")) {

				String base_dir = p_file.get_base_dir();
				String file = base_dir.plus_file(keys["file"]);
				Ref<Texture> tex = ResourceLoader::load(file);
				if (tex.is_null()) {
					ERR_PRINT("Can't load font texture!");
				} else {
					add_texture(tex);
				}
			}
		} else if (type == "char") {

			CharType idx = 0;
			if (keys.has("id"))
				idx = keys["id"].to_int();

			Rect2 rect;

			if (keys.has("x"))
				rect.position.x = keys["x"].to_int();
			if (keys.has("y"))
				rect.position.y = keys["y"].to_int();
			if (keys.has("width"))
				rect.size.width = keys["width"].to_int();
			if (keys.has("height"))
				rect.size.height = keys["height"].to_int();

			Point2 ofs;

			if (keys.has("xoffset"))
				ofs.x = keys["xoffset"].to_int();
			if (keys.has("yoffset"))
				ofs.y = keys["yoffset"].to_int();

			int texture = 0;
			if (keys.has("page"))
				texture = keys["page"].to_int();
			int advance = -1;
			if (keys.has("xadvance"))
				advance = keys["xadvance"].to_int();

			add_char(idx, texture, rect, ofs, advance);

		} else if (type == "kerning") {

			CharType first = 0, second = 0;
			int k = 0;

			if (keys.has("first"))
				first = keys["first"].to_int();
			if (keys.has("second"))
				second = keys["second"].to_int();
			if (keys.has("amount"))
				k = keys["amount"].to_int();

			add_kerning_pair(first, second, -k);
		}

		if (f->eof_reached())
			break;
	}

	memdelete(f);

	return OK;
}
Example #18
0
static Array HHVM_FUNCTION(getopt, const String& options,
                                   const Variant& longopts /*=null */) {
  opt_struct *opts, *orig_opts;
  int len = parse_opts(options.data(), options.size(), &opts);

  if (!longopts.isNull()) {
    Array arropts = longopts.toArray();
    int count = arropts.size();

    /* the first <len> slots are filled by the one short ops
     * we now extend our array and jump to the new added structs */
    opts = (opt_struct *)realloc(opts, sizeof(opt_struct) * (len + count + 1));
    orig_opts = opts;
    opts += len;

    memset(opts, 0, count * sizeof(opt_struct));

    for (ArrayIter iter(arropts); iter; ++iter) {
      String entry = iter.second().toString();

      opts->need_param = 0;
      opts->opt_name = strdup(entry.data());
      len = strlen(opts->opt_name);
      if ((len > 0) && (opts->opt_name[len - 1] == ':')) {
        opts->need_param++;
        opts->opt_name[len - 1] = '\0';
        if ((len > 1) && (opts->opt_name[len - 2] == ':')) {
          opts->need_param++;
          opts->opt_name[len - 2] = '\0';
        }
      }
      opts->opt_char = 0;
      opts++;
    }
  } else {
    opts = (opt_struct*) realloc(opts, sizeof(opt_struct) * (len + 1));
    orig_opts = opts;
    opts += len;
  }

  /* php_getopt want to identify the last param */
  opts->opt_char   = '-';
  opts->need_param = 0;
  opts->opt_name   = NULL;

  static const StaticString s_argv("argv");
  Array vargv = php_global(s_argv).toArray();
  int argc = vargv.size();
  char **argv = (char **)malloc((argc+1) * sizeof(char*));
  std::vector<String> holders;
  int index = 0;
  for (ArrayIter iter(vargv); iter; ++iter) {
    String arg = iter.second().toString();
    holders.push_back(arg);
    argv[index++] = (char*)arg.data();
  }
  argv[index] = NULL;

  /* after our pointer arithmetic jump back to the first element */
  opts = orig_opts;

  int o;
  char *php_optarg = NULL;
  int php_optind = 1;

  SCOPE_EXIT {
    free_longopts(orig_opts);
    free(orig_opts);
    free(argv);
  };

  Array ret = Array::Create();

  Variant val;
  int optchr = 0;
  int dash = 0; /* have already seen the - */
  char opt[2] = { '\0' };
  char *optname;
  int optname_len = 0;
  int php_optidx;
  while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1,
                         optchr, dash, php_optidx))
         != -1) {
    /* Skip unknown arguments. */
    if (o == '?') {
      continue;
    }

    /* Prepare the option character and the argument string. */
    if (o == 0) {
      optname = opts[php_optidx].opt_name;
    } else {
      if (o == 1) {
        o = '-';
      }
      opt[0] = o;
      optname = opt;
    }

    if (php_optarg != NULL) {
      /* keep the arg as binary, since the encoding is not known */
      val = String(php_optarg, CopyString);
    } else {
      val = false;
    }

    /* Add this option / argument pair to the result hash. */
    optname_len = strlen(optname);
    if (!(optname_len > 1 && optname[0] == '0') &&
        is_numeric_string(optname, optname_len, NULL, NULL, 0) ==
        KindOfInt64) {
      /* numeric string */
      int optname_int = atoi(optname);
      if (ret.exists(optname_int)) {
        Variant &e = ret.lvalAt(optname_int);
        if (!e.isArray()) {
          ret.set(optname_int, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(optname_int, val);
      }
    } else {
      /* other strings */
      String key(optname, strlen(optname), CopyString);
      if (ret.exists(key)) {
        Variant &e = ret.lvalAt(key);
        if (!e.isArray()) {
          ret.set(key, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(key, val);
      }
    }

    php_optarg = NULL;
  }

  return ret;
}
bool HttpRequestHandler::executePHPRequest(Transport *transport,
                                           RequestURI &reqURI,
                                           SourceRootInfo &sourceRootInfo,
                                           bool cachableDynamicContent) {
  ExecutionContext *context = hphp_context_init();
  if (RuntimeOption::ImplicitFlush) {
    context->obSetImplicitFlush(true);
  }
  if (RuntimeOption::EnableOutputBuffering) {
    if (RuntimeOption::OutputHandler.empty()) {
      context->obStart();
    } else {
      context->obStart(String(RuntimeOption::OutputHandler));
    }
  }
  context->setTransport(transport);

  string file = reqURI.absolutePath().c_str();
  {
    ServerStatsHelper ssh("input");
    HttpProtocol::PrepareSystemVariables(transport, reqURI, sourceRootInfo);
    Extension::RequestInitModules();

    if (RuntimeOption::EnableDebugger) {
      Eval::DSandboxInfo sInfo = sourceRootInfo.getSandboxInfo();
      Eval::Debugger::RegisterSandbox(sInfo);
      context->setSandboxId(sInfo.id());
    }
    reqURI.clear();
    sourceRootInfo.clear();
  }

  int code;
  bool ret = true;

  // Let the debugger initialize.
  // FIXME: hphpd can be initialized this way as well
  DEBUGGER_ATTACHED_ONLY(phpDebuggerRequestInitHook());
  if (RuntimeOption::EnableDebugger) {
    Eval::Debugger::InterruptRequestStarted(transport->getUrl());
  }

  bool error = false;
  std::string errorMsg = "Internal Server Error";
  ret = hphp_invoke(context, file, false, Array(), uninit_null(),
                    RuntimeOption::RequestInitFunction,
                    RuntimeOption::RequestInitDocument,
                    error, errorMsg,
                    true /* once */,
                    false /* warmupOnly */,
                    false /* richErrorMessage */);

  if (ret) {
    String content = context->obDetachContents();
    if (cachableDynamicContent && !content.empty()) {
      assert(transport->getUrl());
      string key = file + transport->getUrl();
      DynamicContentCache::TheCache.store(key, content.data(),
                                          content.size());
    }
    transport->sendRaw((void*)content.data(), content.size());
    code = transport->getResponseCode();
  } else if (error) {
    code = 500;

    string errorPage = context->getErrorPage().data();
    if (errorPage.empty()) {
      errorPage = RuntimeOption::ErrorDocument500;
    }
    if (!errorPage.empty()) {
      context->obProtect(false);
      context->obEndAll();
      context->obStart();
      context->obProtect(true);
      ret = hphp_invoke(context, errorPage, false, Array(), uninit_null(),
                        RuntimeOption::RequestInitFunction,
                        RuntimeOption::RequestInitDocument,
                        error, errorMsg,
                        true /* once */,
                        false /* warmupOnly */,
                        false /* richErrorMessage */);
      if (ret) {
        String content = context->obDetachContents();
        transport->sendRaw((void*)content.data(), content.size());
        code = transport->getResponseCode();
      } else {
        Logger::Error("Unable to invoke error page %s", errorPage.c_str());
        errorPage.clear(); // so we fall back to 500 return
      }
    }
    if (errorPage.empty()) {
      if (RuntimeOption::ServerErrorMessage) {
        transport->sendString(errorMsg, 500, false, false, "hphp_invoke");
      } else {
        transport->sendString(RuntimeOption::FatalErrorMessage,
                              500, false, false, "hphp_invoke");
      }
    }
  } else {
    code = 404;
    transport->sendString("Not Found", 404);
  }

  if (RuntimeOption::EnableDebugger) {
    Eval::Debugger::InterruptRequestEnded(transport->getUrl());
  }

  // If we have registered post-send shutdown functions, end the request before
  // executing them. If we don't, be compatible with Zend by allowing usercode
  // in hphp_context_shutdown to run before we end the request.
  bool hasPostSend =
    context->hasShutdownFunctions(ExecutionContext::ShutdownType::PostSend);
  if (hasPostSend) {
    transport->onSendEnd();
  }
  context->onShutdownPostSend();
  Eval::Debugger::InterruptPSPEnded(transport->getUrl());
  hphp_context_shutdown();
  if (!hasPostSend) {
    transport->onSendEnd();
  }
  hphp_context_exit(false);
  ServerStats::LogPage(file, code);
  return ret;
}
Example #20
0
Variant ZendPack::pack(CStrRef fmt, CArrRef argv) {
  /* Preprocess format into formatcodes and formatargs */
  vector<char> formatcodes;
  vector<int> formatargs;
  int argc = argv.size();

  const char *format = fmt.c_str();
  int formatlen = fmt.size();
  int currentarg = 0;
  for (int i = 0; i < formatlen; ) {
    char code = format[i++];
    int arg = 1;

    /* Handle format arguments if any */
    if (i < formatlen) {
      char c = format[i];

      if (c == '*') {
        arg = -1;
        i++;
      }
      else if (c >= '0' && c <= '9') {
        arg = atoi(&format[i]);

        while (format[i] >= '0' && format[i] <= '9' && i < formatlen) {
          i++;
        }
      }
    }

    /* Handle special arg '*' for all codes and check argv overflows */
    switch ((int) code) {
      /* Never uses any args */
    case 'x':
    case 'X':
    case '@':
      if (arg < 0) {
        throw_invalid_argument("Type %c: '*' ignored", code);
        arg = 1;
      }
      break;

      /* Always uses one arg */
    case 'a':
    case 'A':
    case 'h':
    case 'H':
      if (currentarg >= argc) {
        throw_invalid_argument("Type %c: not enough arguments", code);
        return false;
      }

      if (arg < 0) {
        arg = argv[currentarg].toString().size();
      }

      currentarg++;
      break;

      /* Use as many args as specified */
    case 'c':
    case 'C':
    case 's':
    case 'S':
    case 'i':
    case 'I':
    case 'l':
    case 'L':
    case 'n':
    case 'N':
    case 'v':
    case 'V':
    case 'f':
    case 'd':
      if (arg < 0) {
        arg = argc - currentarg;
      }

      currentarg += arg;

      if (currentarg > argc) {
        throw_invalid_argument("Type %c: too few arguments", code);
        return false;
      }
      break;

    default:
      throw_invalid_argument("Type %c: unknown format code", code);
      return false;
    }

    formatcodes.push_back(code);
    formatargs.push_back(arg);
  }

  if (currentarg < argc) {
    throw_invalid_argument("%d arguments unused", (argc - currentarg));
  }

  int outputpos = 0, outputsize = 0;
  /* Calculate output length and upper bound while processing*/
  for (int i = 0; i < (int)formatcodes.size(); i++) {
    int code = (int) formatcodes[i];
    int arg = formatargs[i];

    switch ((int) code) {
    case 'h':
    case 'H':
      INC_OUTPUTPOS((arg + (arg % 2)) / 2,1);  /* 4 bit per arg */
      break;

    case 'a':
    case 'A':
    case 'c':
    case 'C':
    case 'x':
      INC_OUTPUTPOS(arg,1);    /* 8 bit per arg */
      break;

    case 's':
    case 'S':
    case 'n':
    case 'v':
      INC_OUTPUTPOS(arg,2);    /* 16 bit per arg */
      break;

    case 'i':
    case 'I':
      INC_OUTPUTPOS(arg,sizeof(int));
      break;

    case 'l':
    case 'L':
    case 'N':
    case 'V':
      INC_OUTPUTPOS(arg,4);    /* 32 bit per arg */
      break;

    case 'f':
      INC_OUTPUTPOS(arg,sizeof(float));
      break;

    case 'd':
      INC_OUTPUTPOS(arg,sizeof(double));
      break;

    case 'X':
      outputpos -= arg;

      if (outputpos < 0) {
        throw_invalid_argument("Type %c: outside of string", code);
        outputpos = 0;
      }
      break;

    case '@':
      outputpos = arg;
      break;
    }

    if (outputsize < outputpos) {
      outputsize = outputpos;
    }
  }

  String s = String(outputsize, ReserveString);
  char *output = s.mutableSlice().ptr;
  outputpos = 0;
  currentarg = 0;

  /* Do actual packing */
  for (int i = 0; i < (int)formatcodes.size(); i++) {
    int code = (int) formatcodes[i];
    int arg = formatargs[i];
    String val;
    const char *s;
    int slen;

    switch ((int) code) {
    case 'a':
    case 'A':
      memset(&output[outputpos], (code == 'a') ? '\0' : ' ', arg);
      val = argv[currentarg++].toString();
      s = val.c_str();
      slen = val.size();
      memcpy(&output[outputpos], s, (slen < arg) ? slen : arg);
      outputpos += arg;
      break;

    case 'h':
    case 'H': {
      int nibbleshift = (code == 'h') ? 0 : 4;
      int first = 1;
      const char *v;

      val = argv[currentarg++].toString();
      v = val.data();
      slen = val.size();
      outputpos--;
      if(arg > slen) {
        throw_invalid_argument
          ("Type %c: not enough characters in string", code);
        arg = slen;
      }

      while (arg-- > 0) {
        char n = *v++;

        if (n >= '0' && n <= '9') {
          n -= '0';
        } else if (n >= 'A' && n <= 'F') {
          n -= ('A' - 10);
        } else if (n >= 'a' && n <= 'f') {
          n -= ('a' - 10);
        } else {
          throw_invalid_argument("Type %c: illegal hex digit %c", code, n);
          n = 0;
        }

        if (first--) {
          output[++outputpos] = 0;
        } else {
          first = 1;
        }

        output[outputpos] |= (n << nibbleshift);
        nibbleshift = (nibbleshift + 4) & 7;
      }

      outputpos++;
      break;
    }

    case 'c':
    case 'C':
      while (arg-- > 0) {
        pack(argv[currentarg++], 1, byte_map, &output[outputpos]);
        outputpos++;
      }
      break;

    case 's':
    case 'S':
    case 'n':
    case 'v': {
      int *map = machine_endian_short_map;

      if (code == 'n') {
        map = big_endian_short_map;
      } else if (code == 'v') {
        map = little_endian_short_map;
      }

      while (arg-- > 0) {
        pack(argv[currentarg++], 2, map, &output[outputpos]);
        outputpos += 2;
      }
      break;
    }

    case 'i':
    case 'I':
      while (arg-- > 0) {
        pack(argv[currentarg++], sizeof(int), int_map, &output[outputpos]);
        outputpos += sizeof(int);
      }
      break;

    case 'l':
    case 'L':
    case 'N':
    case 'V': {
      int *map = machine_endian_int32_map;

      if (code == 'N') {
        map = big_endian_int32_map;
      } else if (code == 'V') {
        map = little_endian_int32_map;
      }

      while (arg-- > 0) {
        pack(argv[currentarg++], 4, map, &output[outputpos]);
        outputpos += 4;
      }
      break;
    }

    case 'f': {
      float v;

      while (arg-- > 0) {
        v = argv[currentarg++].toDouble();
        memcpy(&output[outputpos], &v, sizeof(v));
        outputpos += sizeof(v);
      }
      break;
    }

    case 'd': {
      double v;

      while (arg-- > 0) {
        v = argv[currentarg++].toDouble();
        memcpy(&output[outputpos], &v, sizeof(v));
        outputpos += sizeof(v);
      }
      break;
    }

    case 'x':
      memset(&output[outputpos], '\0', arg);
      outputpos += arg;
      break;

    case 'X':
      outputpos -= arg;

      if (outputpos < 0) {
        outputpos = 0;
      }
      break;

    case '@':
      if (arg > outputpos) {
        memset(&output[outputpos], '\0', arg - outputpos);
      }
      outputpos = arg;
      break;
    }
  }

  return s.setSize(outputpos);
}
Example #21
0
bool World::Initialize(unsigned int windowWidth, unsigned int windowHeight, String windowName, bool antiAliasing, bool fullScreen, bool resizable)
{
	if (_initialized)
	{
		return false;
	}
	
	_running = true;

	// Windows DLL locations
	#if defined(WIN32) && defined(NDEBUG)
		String bitsPath = "bits";
		char currentDir[MAX_PATH];
		_getcwd(currentDir, MAX_PATH);
		String currDir(currentDir);

		StringList libs;
		#if !ANGEL_DISABLE_DEVIL
			libs.push_back("DevIL.dll");
			libs.push_back("ILU.dll");
			libs.push_back("ILUT.dll");
		#endif
		#if ANGEL_DISABLE_FMOD
			libs.push_back("OpenAL32.dll");
		#else
			libs.push_back("fmodex.dll");
		#endif

		for	(int i=0; i < libs.size(); i++)
		{
			String libstring = currDir + "\\" + bitsPath + "\\" + libs[i];
			HMODULE work = LoadLibrary(libstring.c_str());
			if (work == 0)
			{
				DWORD err = GetLastError();
				_com_error error(err);
				LPCSTR errorText = error.ErrorMessage();
				sysLog.Printf("ERROR: Couldn't load DLL (%s); %s", libs[i].c_str(), errorText);
			}
		}

		// does bits directory exist?
		DWORD dwAttrib = GetFileAttributes(bitsPath.c_str());
		if (dwAttrib != INVALID_FILE_ATTRIBUTES && dwAttrib & FILE_ATTRIBUTE_DIRECTORY)
		{
			_chdir(bitsPath.c_str());
		}
	#endif
	
	// General windowing initialization
	#if !ANGEL_MOBILE
		glfwInit();
	#endif
	
	#if defined(__APPLE__)
		// Set up paths correctly in the .app bundle
		#if !ANGEL_MOBILE
			CFBundleRef mainBundle = CFBundleGetMainBundle();
			CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
			char path[PATH_MAX];
			if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
			{
				sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!");
			}
			CFRelease(resourcesURL);
			chdir(path);
			chdir("..");
			#if DEBUG
				// set paths to the local resources rather than the copied ones
				String fileName = __FILE__;
				String dirPath = fileName.substr(0, fileName.size() - String("Angel/Infrastructure/World.cpp").size());
				CFURLRef exeURL = CFBundleCopyExecutableURL(mainBundle);
				char exePath[PATH_MAX];
				if (!CFURLGetFileSystemRepresentation(exeURL, TRUE, (UInt8 *)exePath, PATH_MAX))
				{
					sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!");
				}
				CFRelease(exeURL);
				chdir(dirPath.c_str());
				StringList pathElements = SplitString(exePath, "/");
				String exeName = pathElements[pathElements.size()-1];
				chdir(exeName.c_str());
			#endif
		#else
			CFBundleRef mainBundle = CFBundleGetMainBundle();
			CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
			char path[PATH_MAX];
			if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
			{
				std::cout << "Problem setting up working directory! Probably nothing will work!" << std::endl;
			}
			CFRelease(resourcesURL);
			chdir(path);
			chdir("Angel"); // the iPhone doesn't like having a "Resources" directory in the root of the .app bundle
		#endif
	#endif
	
	//Start scripting
	LuaScriptingModule::Prep();

	//Reset values based on preferences
	antiAliasing = thePrefs.OverrideInt("WindowSettings", "antiAliasing", antiAliasing);
	fullScreen = thePrefs.OverrideInt("WindowSettings", "fullScreen", fullScreen);
	resizable = thePrefs.OverrideInt("WindowSettings", "resizable", resizable);
	windowHeight = thePrefs.OverrideInt("WindowSettings", "height", windowHeight);
	windowWidth = thePrefs.OverrideInt("WindowSettings", "width", windowWidth);
	windowName = thePrefs.OverrideString("WindowSettings", "name", windowName);
	
	//Windowing system setup
	#if !ANGEL_MOBILE
		if (antiAliasing)
		{
			glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); //4x looks pretty good
			_antiAliased = true;
		}
		else
		{
			_antiAliased = false;
		}
		int windowMode = GLFW_WINDOW;
		if (fullScreen)
		{
			windowMode = GLFW_FULLSCREEN;
		}
		if (resizable)
		{
			glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_FALSE);
		}
		else
		{
			glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
		}
	
		glfwOpenWindow(windowWidth, windowHeight, 8, 8, 8, 8, 8, 1, windowMode);		
		glfwSetWindowTitle(windowName.c_str());
		glfwSetWindowPos(50, 50);

		#if defined(WIN32)
			glfwSwapInterval(0); // because double-buffering and Windows don't get along apparently
		#else
			glfwSwapInterval(1);
		#endif
		glfwSetWindowSizeCallback(Camera::ResizeCallback);
		glfwSetKeyCallback(keyboardInput);
		glfwSetCharCallback(charInput);
		glfwDisable(GLFW_KEY_REPEAT);
		glfwSetMousePosCallback(MouseMotion);
		glfwSetMouseButtonCallback(MouseButton);
		glfwSetMouseWheelCallback(MouseWheel);
		glfwSetWindowCloseCallback(windowClosed);
		_prevTime = glfwGetTime();
	#else
		struct timeval tv;
		gettimeofday(&tv, NULL);
		_currTime = _startTime = tv.tv_sec + (double) tv.tv_usec / 1000000.0;
	#endif
	
	//OpenGL state setup
	#if !ANGEL_MOBILE
		glClearDepth(1.0f);
		glPolygonMode(GL_FRONT, GL_FILL);
	#else
		glEnable(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(1.0f, -1.0f);
	#endif
	glShadeModel(GL_FLAT);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearStencil(0);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);


	theCamera.ResizeCallback(windowWidth, windowHeight);
	
	//Get textures going
	InitializeTextureLoading();
	
	//Subscribe to camera changes
	theSwitchboard.SubscribeTo(this, "CameraChange");
	
	//initialize singletons
	#if !ANGEL_MOBILE
		theInput;
		theControllerManager.Setup();
	#endif
	theSound;
	theSpatialGraph;

	#if !ANGEL_MOBILE
		RegisterConsole(new TestConsole());
	#else
		// register fonts, since we don't have the console doing it for us on the phone
		RegisterFont("Resources/Fonts/Inconsolata.otf", 24, "Console");
		RegisterFont("Resources/Fonts/Inconsolata.otf", 18, "ConsoleSmall");
	#endif
	
	LuaScriptingModule::Initialize();

	return _initialized = true;
}
Example #22
0
void PDOConnection::persistentSave() {
  String serialized = f_serialize(def_stmt_ctor_args);
  serialized_def_stmt_ctor_args = string(serialized.data(), serialized.size());
  def_stmt_ctor_args.reset();
}
Example #23
0
void CommandlineParser::printToolInfo()
{
	String tool = "| " + tool_name_ + " -- " + tool_description_;
	String version = "| Version: " + tool_version_;
	String build = "| build date: " + build_date_;
	String host = "| execution host: " + hostname_;
	String time = "| execution time: " + start_time_;

	Size max_len = tool.size();

	if (max_len < version.size())
	{
		max_len = version.size();
	}
	if (max_len < build.size())
	{
		max_len = build.size();
	}
	if (max_len < host.size())
	{
		max_len = host.size();
	}
	if (max_len < time.size())
	{
		max_len = time.size();
	}

	Log << endl;
	Log << " " << String('=', max_len) << endl; 
	Log << tool << String(' ', max_len - tool.size()) << " |" << endl;
	Log << "|" << String('=', max_len) << "|" << endl; 
	Log << "|" << String(' ', max_len) << "|" << endl;
	Log << version << String(' ', max_len - version.size()) << " |" << endl;
	Log << build   << String(' ', max_len - build.size()) <<" |" << endl;
	Log << host    << String(' ', max_len - host.size()) << " |" << endl;
	Log << time    << String(' ', max_len - time.size()) << " |" << endl;
	Log << " "     << String('-', max_len) << endl << endl; 
}
Example #24
0
void reserialize(VariableUnserializer *uns, StringBuffer &buf) {

  char type = uns->readChar();
  char sep = uns->readChar();

  if (type == 'N') {
    buf.append(type);
    buf.append(sep);
    return;
  }

  switch (type) {
  case 'r':
  case 'R':
  case 'b':
  case 'i':
  case 'd':
    {
      buf.append(type);
      buf.append(sep);
      while (uns->peek() != ';') {
        char ch;
        ch = uns->readChar();
        buf.append(ch);
      }
    }
    break;
  case 'S':
  case 'A':
    {
      // shouldn't happen, but keep the code here anyway.
      buf.append(type);
      buf.append(sep);
      char pointer[8];
      uns->read(pointer, 8);
      buf.append(pointer, 8);
    }
    break;
  case 's':
    {
      String v;
      v.unserialize(uns);
      assert(!v.isNull());
      if (v->isStatic()) {
        union {
          char pointer[8];
          StringData *sd;
        } u;
        u.sd = v.get();
        buf.append("S:");
        buf.append(u.pointer, 8);
        buf.append(';');
      } else {
        buf.append("s:");
        buf.append(v.size());
        buf.append(":\"");
        buf.append(v.data(), v.size());
        buf.append("\";");
      }
      sep = uns->readChar();
      return;
    }
    break;
  case 'a':
    {
      buf.append("a:");
      int64_t size = uns->readInt();
      char sep2 = uns->readChar();
      buf.append(size);
      buf.append(sep2);
      sep2 = uns->readChar();
      buf.append(sep2);
      for (int64_t i = 0; i < size; i++) {
        reserialize(uns, buf); // key
        reserialize(uns, buf); // value
      }
      sep2 = uns->readChar(); // '}'
      buf.append(sep2);
      return;
    }
    break;
  case 'o':
  case 'O':
    {
      buf.append(type);
      buf.append(sep);

      String clsName;
      clsName.unserialize(uns);
      buf.append(clsName.size());
      buf.append(":\"");
      buf.append(clsName.data(), clsName.size());
      buf.append("\":");

      uns->readChar();
      int64_t size = uns->readInt();
      char sep2 = uns->readChar();

      buf.append(size);
      buf.append(sep2);
      sep2 = uns->readChar(); // '{'
      buf.append(sep2);
      for (int64_t i = 0; i < size; i++) {
        reserialize(uns, buf); // property name
        reserialize(uns, buf); // property value
      }
      sep2 = uns->readChar(); // '}'
      buf.append(sep2);
      return;
    }
    break;
  case 'C':
    {
      buf.append(type);
      buf.append(sep);

      String clsName;
      clsName.unserialize(uns);
      buf.append(clsName.size());
      buf.append(":\"");
      buf.append(clsName.data(), clsName.size());
      buf.append("\":");

      sep = uns->readChar(); // ':'
      String serialized;
      serialized.unserialize(uns, '{', '}');
      buf.append(serialized.size());
      buf.append(":{");
      buf.append(serialized.data(), serialized.size());
      buf.append('}');
      return;
    }
    break;
  default:
    throw Exception("Unknown type '%c'", type);
  }

  sep = uns->readChar(); // the last ';'
  buf.append(sep);
}
Example #25
0
    String Dialog::input(const String& heading, const String& defaultt, int type, int option, int autoclose)
    {
      DelayedCallGuard dcguard(languageHook);
      std::string value(defaultt);
      SYSTEMTIME timedate;
      GetLocalTime(&timedate);

      switch (type)
      {
        case INPUT_ALPHANUM:
          {
            bool bHiddenInput = (option & ALPHANUM_HIDE_INPUT) == ALPHANUM_HIDE_INPUT;
            if (!CGUIKeyboardFactory::ShowAndGetInput(value, CVariant{heading}, true, bHiddenInput, autoclose))
              value = emptyString;
          }
          break;
        case INPUT_NUMERIC:
          {
            if (!CGUIDialogNumeric::ShowAndGetNumber(value, heading, autoclose))
              value = emptyString;
          }
          break;
        case INPUT_DATE:
          {
            if (!defaultt.empty() && defaultt.size() == 10)
            {
              std::string sDefault = defaultt;
              timedate.wDay = atoi(sDefault.substr(0, 2).c_str());
              timedate.wMonth = atoi(sDefault.substr(3, 4).c_str());
              timedate.wYear = atoi(sDefault.substr(sDefault.size() - 4).c_str());
            }
            if (CGUIDialogNumeric::ShowAndGetDate(timedate, heading))
              value = StringUtils::Format("%2d/%2d/%4d", timedate.wDay, timedate.wMonth, timedate.wYear);
            else
              value = emptyString;
          }
          break;
        case INPUT_TIME:
          {
            if (!defaultt.empty() && defaultt.size() == 5)
            {
              std::string sDefault = defaultt;
              timedate.wHour = atoi(sDefault.substr(0, 2).c_str());
              timedate.wMinute = atoi(sDefault.substr(3, 2).c_str());
            }
            if (CGUIDialogNumeric::ShowAndGetTime(timedate, heading))
              value = StringUtils::Format("%2d:%02d", timedate.wHour, timedate.wMinute);
            else
              value = emptyString;
          }
          break;
        case INPUT_IPADDRESS:
          {
            if (!CGUIDialogNumeric::ShowAndGetIPAddress(value, heading))
              value = emptyString;
          }
          break;
        case INPUT_PASSWORD:
          {
            bool bResult = false;

            if (option & PASSWORD_VERIFY)
              bResult = CGUIKeyboardFactory::ShowAndVerifyPassword(value, heading, 0, autoclose) == 0 ? true : false;
            else
              bResult = CGUIKeyboardFactory::ShowAndVerifyNewPassword(value, heading, true, autoclose);

            if (!bResult)
              value = emptyString;
          }
          break;
        default:
          value = emptyString;
          break;
      }

      return value;
    }
Example #26
0
boost::tuple<const camp::Property*, String, camp::UserObject> 
    CampStringInterpreter::getPropertyFromString( const camp::UserObject& rUserObject, 
    const String& rQuery, bool wantArrayProperty /*= false */ )
{
    camp::UserObject userObject = rUserObject;
    const camp::Class* metaClass = &userObject.getClass();
    std::size_t pos = 0;
    const std::size_t size = rQuery.size();
    camp::Value value = camp::Value::nothing;

    const camp::Property* property = 0;
    String arrayIdentifier;

    while( pos < size )
    {
        String dotString;
        std::size_t dotPos = rQuery.find_first_of( ".", pos );
        if( dotPos != String::npos )
        {
            // Get a string token, separated by a dot.
            dotString = rQuery.substr( pos, dotPos - pos );
        }
        else
        {
            // No dot was found, take the substring from position to the end of the string.
            dotString = rQuery.substr( pos );
            // End the loop.
            dotPos = size;
        }

        // Get array identifier if there is one.
        const std::size_t arrayBeginPos = dotString.find_first_of( "[" );
        if( arrayBeginPos != String::npos )
        {
            // Separate property name and array identifier.
            String propertyString = dotString.substr( 0, arrayBeginPos );
            const std::size_t arrayEndPos = dotString.find_first_of( "]" );

            arrayIdentifier = dotString.substr( arrayBeginPos + 1, 
                dotString.size() - arrayEndPos );
            property = &metaClass->property( propertyString );

            if( property->type() == camp::arrayType )
            {
                const camp::ArrayProperty* arrayProperty = 
                    static_cast<const camp::ArrayProperty*>( property );

                // Convert array identifier to a number.
                value = arrayProperty->get( userObject, boost::lexical_cast<size_t>( 
                    arrayIdentifier ) );
            }
            else
            {
                // Array identifier found, but property is not an array.
                DIVERSIA_EXCEPT( Exception::ERR_SYNTAX_ERROR, 
                    "Array identifier found in query string, but property is not an array", 
                    "CampStringInterpreter::getPropertyFromString" );
            }
        }
        else
        {
            property = &metaClass->property( dotString );

            if( property->type() != camp::arrayType )
            {
                value = property->get( userObject );
                arrayIdentifier = "";
            }
            else if( !wantArrayProperty )
            {
                // Property is an array but no array identifier was found in the query.
                DIVERSIA_EXCEPT( Exception::ERR_SYNTAX_ERROR, 
                    "Property is an array, but no array identifier was found in the query string", 
                    "CampStringInterpreter::getPropertyFromString" );
            }
        }

        if( value.type() == camp::userType && dotPos != size )
        {
            // Value is of user type, set the new metaclass and userobject and nest further.
            // Only nest further if the loop has not been completed yet.
            userObject = value.to<camp::UserObject>();
            metaClass = &userObject.getClass();
        }
        else
        {
            // No more nesting possible, end the loop.
            dotPos = size;
        }

        pos = dotPos + 1;
    }

    // Return the property and optional array identifier
    return boost::make_tuple( property, arrayIdentifier, userObject );
}
Example #27
0
/*
 * PegasusSLP supports return of attributes piggybacked on the srvReply,
 * other implementations may not
 */
static BOOL
_lookup_attrs(const String &save_url, Array<Attribute>& attribs,const SLPClientOptions* options)
{
    struct slp_client *client = NULL;
    lslpMsg responses, *attrReplyEntry;
    
    const char *scopes;
    const char *spi;
    char *iface;
    char *addr;
    const char *type;
    const char *predicate;
    int16 port;
    BOOL dir_agent;
    
    char* tags = (char*)NULL;
    int16 converge=(int16)0;
    if(0==save_url.size()){
        /* Pilot error */
        return FALSE;
    }

    char* url=strdup((const char*)save_url.getCString());
    if (url == NULL)
    {
        return FALSE;
    }

    if((SLPClientOptions*)NULL == options){
        addr = NULL;
        iface = NULL;
        port = 427;
        scopes = "DEFAULT";
        spi="DSA";
        type = "service:wbem";
        predicate = NULL;
        dir_agent = FALSE;
    }else{
        scopes = (char*)options->scopes;
        spi = (char*)options->spi;
        iface = options->local_interface;
        addr = options->target_address;
        type = options->service_type;
        predicate = options->predicate;
        port = options->target_port;
        dir_agent = options->use_directory_agent==true?1:0;
    }
    /* largely cut-and-paste from slp_attrreq.cpp
     * with gratuitous reformatting
     */
    if(NULL != (client = create_slp_client(
                    addr,
                    iface,
                    port,
                    spi,
                    scopes,
                    FALSE, 
                    dir_agent))) {
        if(addr != NULL && inet_addr(addr) == inet_addr("127.0.0.1")) {
            client->local_attr_req(client, url, scopes, tags);
        } else if(converge) {
            client->_convergence = converge ;
            client->converge_attr_req(client, url, scopes, tags);
        } else {
            SOCKADDR_IN address;
            address.sin_port = htons(port);
            address.sin_family = AF_INET;
            if(addr != NULL) {
                address.sin_addr.s_addr = inet_addr(addr);
                client->unicast_attr_req(client, url, scopes, tags, &address);
            }else {
                address.sin_addr.s_addr = _LSLP_MCAST;
                client->converge_attr_req(client, url, scopes, tags);
            }
        } /* end of request  */

        responses.isHead = TRUE;
        responses.next = responses.prev = &responses;

        client->get_response(client, &responses);
        while( ! _LSLP_IS_EMPTY(&responses) ) {
            attrReplyEntry = responses.next;
            if(attrReplyEntry->type == attrRep) {
                if( attrReplyEntry->msg.attrRep.attrListLen > 0) {
                    String attrString = attrReplyEntry->msg.attrRep.attrList;
                    _extractAttributes(attrString,attribs);
                }
                
            }/* if we got an attr rply */ 
            _LSLP_UNLINK(attrReplyEntry);
            lslpDestroySLPMsg(attrReplyEntry, LSLP_DESTRUCTOR_DYNAMIC);
        } /* while traversing response list */ 

        destroy_slp_client(client);

     } /* client successfully created */ 

    free(url);
    return TRUE;
}/*static BOOL _lookup_attrs()*/
Example #28
0
SharedVariant::SharedVariant(CVarRef source, bool serialized,
                             bool inner /* = false */,
                             bool unserializeObj /* = false */)
  : m_shouldCache(false), m_flags(0) {
  assert(!serialized || source.isString());
  m_count = 1;
  m_type = source.getType();
  switch (m_type) {
  case KindOfBoolean:
    {
      m_data.num = source.toBoolean();
      break;
    }
  case KindOfInt64:
    {
      m_type = KindOfInt64;
      m_data.num = source.toInt64();
      break;
    }
  case KindOfDouble:
    {
      m_data.dbl = source.toDouble();
      break;
    }
  case KindOfStaticString:
    {
      if (serialized) goto StringCase;
      m_data.str = source.getStringData();
      break;
    }
StringCase:
  case KindOfString:
    {
      String s = source.toString();
      if (serialized) {
        m_type = KindOfObject;
        // It is priming, and there might not be the right class definitions
        // for unserialization.
        s = apc_reserialize(s);
      }
      StringData* st = StringData::LookupStaticString(s.get());
      if (st) {
        m_data.str = st;
        m_type = KindOfStaticString;
        break;
      }
      m_data.str = s->copy(true);
      break;
    }
  case KindOfArray:
    {
      ArrayData *arr = source.getArrayData();

      if (!inner) {
        // only need to call hasInternalReference() on the toplevel array
        PointerSet seen;
        if (arr->hasInternalReference(seen)) {
          setSerializedArray();
          m_shouldCache = true;
          String s = apc_serialize(source);
          m_data.str = StringData::MakeMalloced(s.data(), s.size());
          break;
        }
      }

      if (arr->isVectorData()) {
        setIsVector();
        m_data.vec = new (arr->size()) VectorData();
        for (ArrayIter it(arr); !it.end(); it.next()) {
          SharedVariant* val = Create(it.secondRef(), false, true,
                                      unserializeObj);
          if (val->m_shouldCache) m_shouldCache = true;
          m_data.vec->vals()[m_data.vec->m_size++] = val;
        }
      } else {
        m_data.map = ImmutableMap::Create(arr, unserializeObj, m_shouldCache);
      }
      break;
    }
  case KindOfUninit:
  case KindOfNull:
    {
      break;
    }
  case KindOfResource:
    {
      // TODO Task #2661075: Here and elsewhere in the runtime, we convert
      // Resources to the empty array during various serialization operations,
      // which does not match Zend behavior. We should fix this.
      m_type = KindOfArray;
      setIsVector();
      m_data.vec = new (0) VectorData();
      break;
    }
  default:
    {
      assert(source.isObject());
      m_shouldCache = true;
      if (unserializeObj) {
        // This assumes hasInternalReference(seen, true) is false
        ImmutableObj* obj = new ImmutableObj(source.getObjectData());
        m_data.obj = obj;
        setIsObj();
      } else {
        String s = apc_serialize(source);
        m_data.str = StringData::MakeMalloced(s.data(), s.size());
      }
      break;
    }
  }
  assert(m_type != KindOfResource);
}
void LuaChunk::store(String& s, int val){
  int pos = (int)s.size();
  s.resize(pos + sizeof(int));
  memcpy(&s[pos], &val, sizeof(int));
}
Example #30
0
/////////////////////////////////////////////////////////////////////////////
// WMIClassProvider::enumerateClasses
//
// ///////////////////////////////////////////////////////////////////////////
Array<CIMClass> WMIClassProvider::enumerateClasses(
        const String& nameSpace,
        const String& userName,
        const String& password,
        const String& className,
        Boolean deepInheritance ,
        Boolean localOnly,
        Boolean includeQualifiers,
        Boolean includeClassOrigin)
{
    PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIClassProvider::enumerateClasses()");

    HRESULT hr;
    long lCount = 0;
    DWORD dwReturned;
    CComPtr<IEnumWbemClassObject>    pClassEnum;
    CComPtr<IWbemClassObject>        pClass;
    Array<CIMClass>                    cimClasses;

    setup(nameSpace,userName,password);

    PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL3,
        "enumerateClasses - deepInheritance %x, localOnly %x, "
        "includeQualifiers %x, includeClassOrigin %x",
        deepInheritance, localOnly, includeQualifiers, includeClassOrigin));

    if (!m_bInitialized)
    {
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL1,
            "WMIClassProvider::enumerateClasses - m_bInitilized= %x, "
                "throw CIM_ERR_FAILED exception",
            m_bInitialized));

        throw CIMException(CIM_ERR_FAILED);
    }

    if (!(_collector->getClassEnum(&pClassEnum, className, deepInheritance)))
    {
        if (pClassEnum)
            pClassEnum.Release();

        throw CIMException(CIM_ERR_FAILED);
    }

    // set proxy security on pClassEnum
    bool bSecurity = _collector->setProxySecurity(pClassEnum);

    //
    //TODO:  What happens if bSecurity is false
    //

    // get the classes and append them to the array
    hr = pClassEnum->Next(WBEM_INFINITE, 1, &pClass, &dwReturned);

    while (SUCCEEDED(hr) && (1 == dwReturned))
    {
        String className = _collector->getClassName(pClass);
        String superClass = _collector->getSuperClass(pClass);

        CIMName objName = className;

        CIMClass tempClass = CIMClass(objName);

        if (0 != superClass.size())
        {
            CIMName superclassName = superClass;
            tempClass.setSuperClassName(superclassName);
        }

        if (_collector->getCIMClass(pClass,
                    tempClass,
                    localOnly,
                    includeQualifiers,
                    includeClassOrigin))
        {
            lCount++;
            cimClasses.append(tempClass);
        }

        if (pClass)
            pClass.Release();

        hr = pClassEnum->Next(WBEM_INFINITE, 1, &pClass, &dwReturned);
    }

    if (pClassEnum)
        pClassEnum.Release();

    PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL4,
        "WMIClassProvider::enumerateClasses() - Class count is %d", lCount));

    if (lCount == 0)
    {
        PEG_TRACE((TRC_WMIPROVIDER, Tracer::LEVEL2,
            "WMIClassProvider::enumerateClasses() - no classes found, "
            "hResult value is %x", hr));
    }

    PEG_METHOD_EXIT();

    return cimClasses;
}