Example #1
0
bool Exec::FindProgram(String &dest, String name)
{
    String path;
    String exts;
    StringVector ppath;
    StringVector pext;

    int lpatherror = Environment::GetVariable(path, _T("PATH"), defpath);
    int lexterror = Environment::GetVariable(exts, _T("PATHEXT"), defexts);

    Str::SplitLine(ppath, path, _T(';'));
    Str::SplitLine(pext, exts, _T(';'));

    if (Path::FileHasExtension(name) || (pext.size() == 0))
    {
        for (auto pit : ppath)
        {
            String cpath(pit);
            if ((cpath.at(cpath.size() - 1) != _T('/')) && (cpath.at(cpath.size() - 1) != _T('\\')))
                cpath.append(1, _T('/'));
            cpath.append(name);

            if (Path::FileExists(cpath))
            {
                dest.assign(cpath);
                return true;
            }
        }
    }
    else
    {
        for (auto pit : ppath)
        {
            for (auto eit : pext)
            {
                String cpath(pit);
                String cext(eit);

                if ((cpath.at(cpath.size() - 1) != _T('/')) && (cpath.at(cpath.size() - 1) != _T('\\')))
                    cpath.append(1, _T('/'));

                cpath.append(name);
                cpath.append(cext);

                if (Path::FileExists(cpath))
                {
                    dest.assign(cpath);
                    return true;
                }
            }
        }
    }

    return false;
}
Example #2
0
EW_ENTER


bool CallableWrapT<Stream>::getline(String& val)
{
	size_t i=0;

	for(;;i++)
	{
		if(i==buffer.size())
		{
			char buf[1024];
			int rc=value.recv(buf,1024);
			if(rc>0)
			{
				buffer.append(buf,rc);
			}
			else if(rc<=0)
			{
				if(buffer.empty())
				{
					return false;
				}

				val=buffer;
				buffer.clear();
				return true;
			}
		}

		if(buffer[i]=='\n') break;
	}

	if(i>0&&buffer[i-1]=='\r')
	{
		val.assign(&buffer[0],&buffer[i-1]);
	}
	else
	{
		val.assign(&buffer[0],&buffer[i]);
	}

	buffer.erase(buffer.begin(),buffer.begin()+i+1);
	return true;
}
Example #3
0
//------------------------------------------------------------------------------
// FUNCTION: getLocalHostName
//
// REMARKS: Retrieves the local host name
//
// PARAMETERS:  [OUT] hostName -> string that will contain the local host name
//
// RETURN: TRUE if local hostname is valid, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getLocalHostName(String & hostName) 
{
    char host[PEGASUS_MAXHOSTNAMELEN];
    if (gethostname(host, PEGASUS_MAXHOSTNAMELEN) != 0)
        return false;

       hostName.assign(host);
    return true;
}
Example #4
0
/**
MakeFullPath: Returns the absolute path of the given file

@internalComponent
@released

@param aFile - Input file name
*/
void Sis2Iby::MakeFullPath(String& aFile)
{
#ifdef WIN32
    char fPath[_MAX_PATH];

    if( _fullpath(fPath, (char*)aFile.data(), _MAX_PATH) != NULL )
    {
        aFile.assign(fPath);
    }
#else
    char fPath[FILENAME_MAX];
    if (realpath(aFile.c_str(),fPath))
    {
        aFile.assign(fPath);
    }

#endif
    return;
}
// Functions from x64dbg project: https://github.com/x64dbg/x64dbg
//Conversion functions taken from: http://www.nubaria.com/en/blog/?p=289
String Utf16ToUtf8(const WString & wstr)
{
    String convertedString;
    int requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0);
    if(requiredSize > 0)
    {
        std::vector<char> buffer(requiredSize);
        WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buffer[0], requiredSize, 0, 0);
        convertedString.assign(buffer.begin(), buffer.end() - 1);
    }
    return convertedString;
}
Example #6
0
//------------------------------------------------------------------------------
// FUNCTION: isHostAddress
//
// REMARKS: Verify if host is address
//
// PARAMETERS:  [IN] host -> string containing the host name or address
//
// RETURN: TRUE if host address, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::isHostAddress(String host) {
    int ps;
    String strValue;
    Boolean ok = false;
    
    ps = host.find(".");
    if(ps > 0) {
        strValue.assign(host.subString(0, ps - 1));
        ok = (atoi(strValue.getCString()) > 0);
    }
    return ok;
}
Example #7
0
bool YStunAttributeError::fromBuffer(u_int8_t* buffer, u_int16_t len)
{
// 'len' must be at least 4 and a multiple of 4
// buffer[2]: Error class (3 bits)
// buffer[3]: Error code modulo 100 (Values: 0..99)
    if (!(buffer && len >= 4 && (len % 4) == 0))
	return false;
    m_code = (buffer[2] & 0x07) * 100 + (buffer[3] < 100 ? buffer[3] : 0);
    if (len > 4)
	m_text.assign((const char*)buffer + 4,len - 4);
    return true;
}
void ZOSConsoleManager::_updateEnvironment(
    const char* envVarName,
    const char* envVarValue)
{
    PEG_METHOD_ENTER(TRC_SERVER,
                     "ZOSConsoleManager::_updateEnvironment");

    String envVarNameString(envVarName);

    int rc=setenv(envVarName,envVarValue,1);

    if (rc==0)
    {
        String envVarValueString;
        if (envVarValue!=NULL)
        {
            envVarValueString.assign(envVarValue);
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
                MessageLoaderParms(
                    "Server.ConsoleManager_zOS."
                    "CON_MODIFY_SETENV.PEGASUS_OS_ZOS",
                    "Environment variable \"$0\" set to \"$1\" successfully.",
                    envVarNameString,
                    envVarValueString));
        }
        else
        {
            Logger::put_l(
                Logger::STANDARD_LOG, System::CIMSERVER, Logger::INFORMATION,
                MessageLoaderParms(
                    "Server.ConsoleManager_zOS."
                    "CON_MODIFY_DELETEENV.PEGASUS_OS_ZOS",
                    "Environment variable \"$0\" deleted successfully.",
                    envVarNameString));
        }
    }
    else
    {
        Logger::put_l(
            Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            MessageLoaderParms(
                "Server.ConsoleManager_zOS.CON_MODIFYENV_FAILED.PEGASUS_OS_ZOS",
                "Failed to update environment variable \"$0\".",
                envVarNameString));
    }

    // To be 100% complete we would need an AuditLog here.
    // But since we don't track env vars for z/OS, this is
    // omitted intentionally.

    PEG_METHOD_EXIT();
}
Example #9
0
bool CHttpServer::parse_startline(String const &line, String &method, String &uri, String &query)
{
    const char *s, *e;
    
    // Find first space
    for(s = line.c_str(), e = s; *e != ' ' && *e != '\0'; ++e);
    if (*e == '\0') {
        RAWLOG_ERROR1("Parse startline (1): syntax error: \"%s\"", line.c_str());
        return false;
    }
    
    method.assign(s, e);
    
    // Skip spaces
    for(s = e; *s == ' '; ++s);
    
    for(e = s; *e != '?' && *e != ' ' && *e != '\0'; ++e);
    if (*e == '\0') {
        RAWLOG_ERROR1("Parse startline (2): syntax error: \"%s\"", line.c_str());
        return false;
    }
    
    uri.assign(s, e);
    uri = URI::urlDecode(uri);
    
    query.clear();
    if (*e == '?') {
        s = ++e;
        for(e = s; *e != ' ' && *e != '\0'; ++e);
        if (*e != '\0')
            query.assign(s, e);
    }

    const char* frag = strrchr(uri.c_str(), '#');
    if (frag)
        uri = uri.substr(0, frag-uri.c_str());

    return true;
}
Example #10
0
//------------------------------------------------------------------------------
// FUNCTION: getHostAddress
//
// REMARKS: Resolves address servers
//
// PARAMETERS:  [IN] serverName     -> string containing the name server
//                [OUT] serverAddress -> string that will contain the IP server
//
// RETURN: TRUE if valid host name, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostAddress(String serverName, String & serverAddress) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    serverAddress.clear();
    host = gethostbyname(serverName.getCString());
    if(host != NULL) 
    {
        ia = *(struct in_addr *)(host->h_addr);
        serverAddress.assign(inet_ntoa(ia));
        ok = true;
    }
    return ok;
}    
Example #11
0
YETI_Result File::load(const char * path, String & data, FileInterface::open_mode mode /* = YETI_FILE_OPEN_MODE_READ */)
{
    DataBuffer buffer;

    data = "";

    File file(path);
    YETI_Result result = file.open(mode);
    if (YETI_FAILED(result)) return result;

    result = file.load(buffer);

    if (YETI_SUCCEEDED(result) && buffer.get_data_size() > 0) {
        data.assign((const char *)buffer.get_data(), buffer.get_data_size());
        data.set_length(buffer.get_data_size());
    }

    file.close();

    return result;
}
Example #12
0
//------------------------------------------------------------------------------
// FUNCTION: getUtilGetHostName 
//
// REMARKS: 
//
// PARAMETERS:  [OUT] systemName -> string that will contain the host name 
//
// RETURN: TRUE if successful, FALSE otherwise
//------------------------------------------------------------------------------
static Boolean getUtilGetHostName(String& systemName)
{
     char    hostName[PEGASUS_MAXHOSTNAMELEN];
     struct  hostent *he;

     if (gethostname(hostName, PEGASUS_MAXHOSTNAMELEN) != 0)
     {
         return false;
     }

     // Now get the official hostname.  If this call fails then return
     // the value from gethostname().

     if (he=gethostbyname(hostName))
      {
        strcpy(hostName, he->h_name);
     }

     systemName.assign(hostName);

     return true;
}
Example #13
0
//------------------------------------------------------------------------------
// FUNCTION: getHostName
//
// REMARKS: Resolves name servers
//
// PARAMETERS:  [IN] serverAddress -> string containing the IP address
//                [OUT] hostName -> string that will contain the name server
//
// RETURN: TRUE if valid host IP, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostName(String serverAddress, String & hostName) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    hostName.clear();
    if((ia.s_addr = inet_addr(serverAddress.getCString())) != -1) 
    {
        host = gethostbyaddr((const char *)&ia, 
                              sizeof(struct in_addr),
                               AF_INET);
        if(host != NULL) 
        {
            hostName.assign(host->h_name);
            ok = true;
        }
   }
   return ok;
}    
Example #14
0
	int LogBuffer::Dump()
	{
		LOGOG_CHAR *pCurrent = m_pStart;
		size_t *pSize;
		int nError;

		if ( m_pOutputTarget == NULL )
			return -1;

		// We have to lock the output target here, as we do an end run around its Receive() function */
		ScopedLock sl( m_pOutputTarget->m_MutexReceive );

		while ( pCurrent < m_pCurrent )
		{
			String sOut;
			// Get the size of this entry
			pSize = ( size_t * )pCurrent;
			// Move past that entry into the data area
			pCurrent = ( LOGOG_CHAR * )( pSize + 1 );

			sOut.assign( pCurrent, pCurrent + *pSize - 1 );

			if ( m_pOutputTarget )
			{
				nError = m_pOutputTarget->Output( sOut );
				if ( nError != 0 )
					return nError;
			}

			pCurrent += *pSize;
		}

		// reset buffer
		m_pCurrent = m_pStart;

		return 0;
	}
Example #15
0
//------------------------------------------------------------------------------
// FUNCTION: getCaption
//
// REMARKS: returns the Caption property
//
// PARAMETERS: [OUT] strValue -> string that will receive the Caption property 
//                                 value
//
// RETURN: TRUE (hard-coded property value)
//------------------------------------------------------------------------------
Boolean NTPService::getCaption(String & strValue) 
{
    strValue.assign(NTP_CAPTION);
    return true;
}
Example #16
0
//------------------------------------------------------------------------------
// FUNCTION: getNTPName
//
// REMARKS: returns the Name property
//
// PARAMETERS: [OUT] strValue -> string that will receive the NTP_Name property 
//                                 value
//
// RETURN: TRUE (hard-coded property value)
//------------------------------------------------------------------------------
Boolean NTPService::getNTPName(String & strValue) 
{
    strValue.assign(NTP_NAME);
    return true;
}
/******************************************************************************
 Syntax for Modify command is:

 MODIFY <jobname>,APPL=CONFIG,<properyname>=['<value>'|<value>][,PLANNED]
                       VERSION
                       ENV[,<varname>][=<value>]

 Parameter <command> represents the string following the "APPL=" token.

******************************************************************************/
void ZOSConsoleManager::processModifyCommand( char* command )
{
    PEG_METHOD_ENTER(TRC_SERVER,
                     "ZOSConsoleManager::processModifyCommand");

    char* currentPtr = command;
    char* cmdPtr = NULL;
    char* cfgProperty = NULL;
    char* cfgValue = NULL;
    char* planned = NULL;
    Boolean currentValueIsNull = false;
    Boolean valueIsQuoted = false;
    CommandType consCmd=consoleCmdInvalid;


    currentPtr = _skipBlanks(currentPtr);

    if (!memcmp(currentPtr,STRLIT_ARGS(ZOSCONSOLEMANAGER_TOKEN_CONFIG)))
    {
        currentPtr += strlen(ZOSCONSOLEMANAGER_TOKEN_CONFIG);
        consCmd = consoleCmdConfig;
    }
    else if (!memcmp(currentPtr,STRLIT_ARGS(ZOSCONSOLEMANAGER_TOKEN_VERSION)))
    {
        consCmd = consoleCmdVersion;
        _displayServiceLevel();
        PEG_METHOD_EXIT();
        return;
    }
    else if (!memcmp(currentPtr,STRLIT_ARGS(ZOSCONSOLEMANAGER_TOKEN_ENV)))
    {
        consCmd = consoleCmdEnv;
        currentPtr += strlen(ZOSCONSOLEMANAGER_TOKEN_ENV);
        if (*currentPtr == ',')
        {
            currentPtr++;
        }
    }
    else
    {
        _issueSyntaxError(command);
        PEG_METHOD_EXIT();
        return;
    }


    // Here currentPtr points after the [CONFIG,|VERSION|ENV] token.
    // Following is either the name of a variable or nothing
    currentPtr = _skipBlanks(currentPtr);

    cfgProperty = currentPtr;
    currentPtr = strchr(currentPtr,'=');

    if (currentPtr==NULL)
    {
        if (consCmd == consoleCmdEnv)
        {
            _showEnvironment(cfgProperty);
            PEG_METHOD_EXIT();
            return;
        }
        else
        {
            _issueSyntaxError(command);
            PEG_METHOD_EXIT();
            return;
        }
    }
    else
    {
        // skip the "="
        *currentPtr = '\0';
        currentPtr++;

        currentPtr = _skipBlanks(currentPtr);

        if (*currentPtr == '\0' || *currentPtr ==',')
        {
            currentValueIsNull=true;
        }
        else if (*currentPtr == '\'')
        {
            // Check if value is enclosed in quotes
            char* temp = strchr(currentPtr+1,'\'');
            if (temp!=NULL)
            {
                // skip the starting "'"
                *currentPtr = '\0';
                currentPtr++;

                cfgValue = currentPtr;
                currentPtr = temp;

                // skip the ending "'"
                *currentPtr = '\0';
                currentPtr++;
                valueIsQuoted = true;
            }
            else
            {
                _issueSyntaxError(command);
                PEG_METHOD_EXIT();
                return;
            }
        }
        else
        {
            cfgValue = currentPtr;
        }
    }

    currentPtr = _skipBlanks(currentPtr);

    planned = strchr(currentPtr,',');
    if (planned!=NULL)
    {
        *planned = '\0';
        planned++;

        planned = _skipBlanks(planned);

        if (memcmp(planned,STRLIT_ARGS(ZOSCONSOLEMANAGER_TOKEN_PLANNED)))
        {
            _issueSyntaxError(command);
            PEG_METHOD_EXIT();
            return;
        }
    }


    _stripTrailingBlanks( cfgProperty );
    PEG_TRACE((TRC_SERVER, Tracer::LEVEL4,"Update property: %s", cfgProperty));

    if (currentValueIsNull)
    {
        PEG_TRACE_CSTRING(TRC_SERVER, Tracer::LEVEL4,
                          "Set property with null value");
    }
    else
    {
        _stripTrailingBlanks( cfgValue );
        PEG_TRACE((TRC_SERVER, Tracer::LEVEL4,
                   "Update property value to: %s", cfgValue));
    }

    if (planned != NULL)
    {
        PEG_TRACE_CSTRING(TRC_SERVER, Tracer::LEVEL4,
                          "Updating planned value");
    }

    if (consCmd == consoleCmdEnv)
    {
        _updateEnvironment(cfgProperty, cfgValue);
        PEG_METHOD_EXIT();
        return;
    }

    String propertyString(cfgProperty);
    String propertyValue;

    if (!currentValueIsNull)
    {
        propertyValue.assign(cfgValue);

        if (!valueIsQuoted)
        {
            // All values that were not enclosed in quotes are
            // converted to lowercase
            propertyValue.toLower();
        }

    }

    _updateConfiguration(propertyString,
                         propertyValue,
                         currentValueIsNull,
                         planned);
    PEG_METHOD_EXIT();
}
Example #18
0
	bool Settings::parserModulesOptions(String::List& options, bool displayError)
	{
		// Cleanup if needed
		moduleSettings.clear();
		// End of the list
		const String::List::const_iterator end = options.end();
		// Key
		String key;
		// Value
		String value;
		// Module name
		String modName;
		// Group
		String group;
		// normalized path
		String norm;

		// The default compiler is gcc
		CompilerCompliant compliant = gcc;
		// Checking for Visual Studio
		if (not compiler.empty() && compiler.at(0) == 'v' && compiler.at(1) == 's')
			compliant = visualstudio;

		// For each entry in the ini file
		for (String::List::const_iterator i = options.begin(); i != end; ++i)
		{
			i->extractKeyValue(key, value);
			if (key.empty() || key.first() == '[')
				continue;
			value.trim();
			if (!value)
				continue;

			// Reset
			modName.clear();
			group.clear();

			// Splitting
			const String::Size p = key.find(':');
			if (p == String::npos)
				continue;
			group.assign(key, p);
			modName.assign(key, key.size() - p - 1, p + 1);
			if (not group or not modName)
				continue;

			SettingsPerModule& s = moduleSettings[modName];

			if (group == "path.include")
			{
				IO::Normalize(norm, value);
				switch (compliant)
				{
					case gcc          :
						s.includes[String() << "-I" << QuotePath(norm)] = true;
						break;

					case visualstudio :
						s.includes[String() << "/I" << QuotePath(norm)] = true;
						break;
				}
				continue;
			}

			if (group == "lib,rawcommand")
			{
				s.libs[value] = true;
				continue;
			}

			if (group == "path.lib")
			{
				IO::Normalize(norm, value);
				switch (compliant)
				{
					case gcc          :
						s.libIncludes[String() << "-L" << QuotePath(norm)] = true;
						break;
					case visualstudio :
						s.libIncludes[String() << "/LIBPATH:" << QuotePath(norm)] = true;
						break;
				}
				continue;
			}

			if (group == "lib")
			{
				IO::Normalize(norm, value);
				# ifdef YUNI_OS_MAC
				// it may happen that cmake provides a framework for linking, which is wrong obvioulsy
				CString<32,false> ext;
				IO::ExtractExtension(ext, norm);
				ext.toLower();
				if (ext != ".framework")
					s.libs[String() << "-l" << QuotePath(norm)] = true;
				else
				{
					// adding the parent directory
					String frameworkpath;
					norm += "/../";
					IO::Normalize(frameworkpath, norm);
					s.libIncludes[String() << "-F" << QuotePath(frameworkpath)] = true;
				}
				# else
				switch (compliant)
				{
					case gcc          : s.libs[String() << "-l" << QuotePath(norm)] = true; break;
					case visualstudio : s.libs[String() << QuotePath(norm)] = true; break;
				}
				# endif
				continue;
			}

			if (group == "cxxflag")
			{
				s.cxxFlags[value] = true;
				continue;
			}

			if (group == "define")
			{
				switch (compliant)
				{
					case gcc          : s.defines[String() << "-D" << value] = true; break;
					case visualstudio : s.defines[String() << "/D" << value] = true; break;
				}
				continue;
			}
			if (group == "dependency")
			{
				s.dependencies.push_back(value);
				continue;
			}

			if (group == "framework")
			{
				s.frameworks[String() << "-framework " << QuotePath(value)] = true;
				continue;
			}

			if (displayError)
				std::cout << "Error: unknown key in the config file: '" << key << "'\n";
			return false;
		}
		return true;
	}
Example #19
0
/////////////////////////////////////////////////////////////////////////
//  MAIN
//////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
    String pegasusHome;
    Boolean shutdownOption = false;
    Boolean debugOutputOption = false;

//l10n
// Set Message loading to process locale
MessageLoader::_useProcessLocale = true;
//l10n

//l10n
#if defined(PEGASUS_OS_AIX) && defined(PEGASUS_HAS_MESSAGES)
setlocale(LC_ALL, "");
#endif

#ifndef PEGASUS_OS_TYPE_WINDOWS
    //
    // Get environment variables:
    //
#if defined(PEGASUS_OS_AIX) && defined(PEGASUS_USE_RELEASE_DIRS)
    pegasusHome = AIX_RELEASE_PEGASUS_HOME;
#elif defined(PEGASUS_OS_PASE) && defined(PEGASUS_USE_RELEASE_DIRS)
    pegasusHome = PASE_PROD_HOME;
#elif !defined(PEGASUS_USE_RELEASE_DIRS)
    const char* tmp = getenv("PEGASUS_HOME");

    if (tmp)
    {
        pegasusHome = tmp;
    }
#endif

    FileSystem::translateSlashes(pegasusHome);
#else

    // windows only
    char exeDir[MAX_PATH];
    HMODULE hExe = GetModuleHandle(NULL);
    GetModuleFileName(hExe, exeDir, sizeof(exeDir));
    *strrchr(exeDir, '\\') = '\0';
    pegasusHome = String(exeDir);

#endif

        // Get help, version, and shutdown options

        for (int i = 1; i < argc; )
        {
            const char* arg = argv[i];
            if(String::equal(arg,"--help"))
            {
                    PrintHelp(argv[0]);
                    exit(0);
            }
            else if(String::equal(arg,"--version"))
            {
                cout << _cimListenerProcess->getVersion() << endl;
                exit(0);
            }
            // Check for -option
            else if (*arg == '-')
            {
                // Get the option
                const char* option = arg + 1;

                //
                // Check to see if user asked for the version (-v option):
                //
                if (*option == OPTION_VERSION &&
                    strlen(option) == 1)
                {
                    cout << _cimListenerProcess->getVersion() << endl;
                    exit(0);
                }
                //
                // Check to see if user asked for help (-h option):
                //
                else if (*option == OPTION_HELP &&
                        (strlen(option) == 1))
                {
                    PrintHelp(argv[0]);
                    exit(0);
                }
#if !defined(PEGASUS_USE_RELEASE_DIRS)
                else if (*option == OPTION_HOME &&
                        (strlen(option) == 1))
                {
                    if (i + 1 < argc)
                    {
                        pegasusHome.assign(argv[i + 1]);
                    }
                    else
                    {
                        String opt(option);
                        MessageLoaderParms parms(
                                "src.Server.cimserver.MISSING_ARGUMENT",
                                         "Missing argument for option -$0",
                                         opt);
                        cout << MessageLoader::getMessage(parms) << endl;
                        exit(0);
                    }

                    memmove(&argv[i], &argv[i + 2],
                            (argc-i-1) * sizeof(char*));
                    argc -= 2;
                }
#endif
                //
                // Check to see if user asked for debug output (-X option):
                //
                else if (*option == OPTION_DEBUGOUTPUT &&
                        (strlen(option) == 1))
                {
                    MessageLoaderParms parms(
                        "src.Server.cimserver.UNSUPPORTED_DEBUG_OPTION",
                        "Unsupported debug output option is enabled.");
                    cout << MessageLoader::getMessage(parms) << endl;

                    debugOutputOption = true;

#if defined(PEGASUS_OS_HPUX)
                    System::bindVerbose = true;
#endif

                    // remove the option from the command line
                    memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*));
                    argc--;
                }
                //
                // Check to see if user asked for shutdown (-s option):
                //
                else if (*option == OPTION_SHUTDOWN &&
                        (strlen(option) == 1))
                {
                    //
                    // Check to see if shutdown has already been specified:
                    //
                    if (shutdownOption)
                    {
                        MessageLoaderParms parms(
                           "DynListener.cimlistener.DUPLICATE_SHUTDOWN_OPTION",
                           "Duplicate shutdown option specified.");

                        cout << MessageLoader::getMessage(parms) << endl;
                        exit(0);
                    }

                    shutdownOption = true;

                    // remove the option from the command line
                    memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*));
                    argc--;
                }
                else
                    i++;
            }
            else
                i++;
        }

    //
    // Set the value for pegasusHome property
    //
    DynamicListenerConfig::setListenerHome(pegasusHome);

    //
    // Do the plaform specific run
    //

    return _cimListenerProcess->platform_run(
        argc, argv, shutdownOption, debugOutputOption);
}
Example #20
0
int main(int argc, char** argv)
{
    String pegasusHome;
    Boolean shutdownOption = false;
    Boolean debugOutputOption = false;

    // Set Message loading to process locale
    MessageLoader::_useProcessLocale = true;

#ifdef PEGASUS_OS_ZOS
    // Direct standard input to /dev/null,
    close(STDIN_FILENO);
    open("/dev/null", O_RDONLY);

    if ( setEBCDICEncoding(STDOUT_FILENO)==-1 ||
         setEBCDICEncoding(STDERR_FILENO)==-1 )
    {
       PEG_TRACE_CSTRING(TRC_SERVER,Tracer::LEVEL1,
           "Coud not set stdout or stderr to EBCDIC encoding.");
    }
    // Need to initialize timezone information in the
    // initial processing thread (IPT)
    initialize_zOS_timezone();
#endif

#if defined(PEGASUS_OS_AIX) && defined(PEGASUS_HAS_MESSAGES)
    setlocale(LC_ALL, "");
#endif

#ifndef PEGASUS_OS_TYPE_WINDOWS
    //
    // Get environment variables:
    //
# if defined(PEGASUS_OS_AIX) && defined(PEGASUS_USE_RELEASE_DIRS)
    pegasusHome = AIX_RELEASE_PEGASUS_HOME;
# elif defined(PEGASUS_OS_PASE)
    const char *tmp = getenv("PEGASUS_HOME");
    pegasusHome = (tmp == 0) ? PASE_DEFAULT_PEGASUS_HOME : tmp;
# elif !defined(PEGASUS_USE_RELEASE_DIRS) || \
    defined(PEGASUS_OS_ZOS)
    const char* tmp = getenv("PEGASUS_HOME");

    if (tmp)
    {
        pegasusHome = tmp;
    }
# endif

    FileSystem::translateSlashes(pegasusHome);
#else

    // windows only
    //setHome(pegasusHome);
    pegasusHome = _cimServerProcess->getHome();
#endif

#ifdef PEGASUS_ENABLE_PRIVILEGE_SEPARATION

    // If invoked with "--executor-socket <socket>" option, then use executor.

    Executor::setSock(_extractExecutorSockOpt(argc, argv));

    // Ping executor to verify the specified socket is valid.

    if (Executor::ping() != 0)
    {
        MessageLoaderParms parms("src.Server.cimserver.EXECUTOR_PING_FAILED",
            "Failed to ping the executor on the specified socket.");
        cerr << argv[0] << ": " << MessageLoader::getMessage(parms) << endl;
        exit(1);
    }

#endif /* !defined(PEGASUS_ENABLE_PRIVILEGE_SEPARATION) */

        // Get help, version, status and shutdown options

        for (int i = 1; i < argc; )
        {
            const char* arg = argv[i];
            if (strcmp(arg, "--help") == 0)
            {
                PrintHelp(argv[0]);
                Executor::daemonizeExecutor();
                exit(0);
            }
            if (strcmp(arg, "--status") == 0)
            {
                int retValue = 0;
                if (_serverRunStatus.isServerRunning())
                {
                    MessageLoaderParms parms(
                        "src.Server.cimserver.CIMSERVER_RUNNING",
                        "The CIM Server is running.");
                    cout << MessageLoader::getMessage(parms) << endl;
                }
                else
                {
                    MessageLoaderParms parms(
                        "src.Server.cimserver.CIMSERVER_NOT_RUNNING",
                        "The CIM Server is not running.");
                    cout << MessageLoader::getMessage(parms) << endl;
                    retValue = 2;
                }
                Executor::daemonizeExecutor();
                exit(retValue);
            }
            else if (strcmp(arg, "--version") == 0)
            {
                cout << _cimServerProcess->getCompleteVersion() << endl;
                Executor::daemonizeExecutor();
                exit(0);
            }
            // Check for -option
            else if (*arg == '-')
            {
                // Get the option
                const char* option = arg + 1;

                //
                // Check to see if user asked for the version (-v option):
                //
                if (*option == OPTION_VERSION &&
                    strlen(option) == 1)
                {
                    cout << _cimServerProcess->getCompleteVersion() << endl;
                    Executor::daemonizeExecutor();
                    exit(0);
                }
                //
                // Check to see if user asked for help (-h option):
                //
                else if (*option == OPTION_HELP &&
                        (strlen(option) == 1))
                {
                    PrintHelp(argv[0]);
                    Executor::daemonizeExecutor();
                    exit(0);
                }
#if !defined(PEGASUS_USE_RELEASE_DIRS)
                else if (*option == OPTION_HOME &&
                        (strlen(option) == 1))
                {
                    if (i + 1 < argc)
                    {
                        pegasusHome.assign(argv[i + 1]);
                    }
                    else
                    {
                        String opt(option);
                        MessageLoaderParms parms(
                            "src.Server.cimserver.MISSING_ARGUMENT",
                            "Missing argument for option -$0",
                            opt);
                        cout << MessageLoader::getMessage(parms) << endl;
                        exit(1);
                    }

                    memmove(&argv[i], &argv[i + 2], (argc-i-1) * sizeof(char*));
                    argc -= 2;
                }
#endif
                //
                // Check to see if user asked for debug output (-X option):
                //
                else if (*option == OPTION_DEBUGOUTPUT &&
                        (strlen(option) == 1))
                {
                    MessageLoaderParms parms(
                        "src.Server.cimserver.UNSUPPORTED_DEBUG_OPTION",
                        "Unsupported debug output option is enabled.");
                    cout << MessageLoader::getMessage(parms) << endl;

                    debugOutputOption = true;

#if defined(PEGASUS_OS_HPUX)
                    System::bindVerbose = true;
#endif

                    // remove the option from the command line
                    memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*));
                    argc--;
                }
                //
                // Check to see if user asked for shutdown (-s option):
                //
                else if (*option == OPTION_SHUTDOWN &&
                        (strlen(option) == 1))
                {
                    //
                    // Check to see if shutdown has already been specified:
                    //
                    if (shutdownOption)
                    {
                        MessageLoaderParms parms(
                            "src.Server.cimserver.DUPLICATE_SHUTDOWN_OPTION",
                            "Duplicate shutdown option specified.");

                        cout << MessageLoader::getMessage(parms) << endl;
                        exit(1);
                    }

                    shutdownOption = true;

                    // remove the option from the command line
                    memmove(&argv[i], &argv[i + 1], (argc-i) * sizeof(char*));
                    argc--;
                }
                else
                    i++;
            }
            else
                i++;
        }

    //
    // Set the value for pegasusHome property
    //
    ConfigManager::setPegasusHome(pegasusHome);

    //
    // Do the platform specific run
    //

    return _cimServerProcess->platform_run(
        argc, argv, shutdownOption, debugOutputOption);
}
Example #21
0
bool CHttpServer::parse_request(String &method, String &uri, String &query, HeaderList &headers, String &body)
{
    method.clear();
    uri.clear();
    headers.clear();
    body.clear();

    size_t s = 0;
    ByteVector request;

    bool parsing_headers = true;
    size_t content_length = 0;

    for (;;) {
        if (!receive_request(request))
            return false;

        size_t lim = request.size();
        while (parsing_headers) {
            size_t e;
            for(e = s; e < lim && request[e] != '\r'; ++e);
            if (e >= lim - 1) {
                // Incomplete line, will read further
                break;
            }
            if (request[e + 1] != '\n') {
                RAWLOG_ERROR("Wrong request syntax, line should ends by '\\r\\n'");
                return false;
            }
            
            String line(&request[s], e - s);
            s = e + 2;
            
            if (line.empty()) {
                parsing_headers = false;
                break;
            }
            
            if (uri.empty()) {
                // Parse start line
                if (!parse_startline(line, method, uri, query) || uri.empty())
                    return false;
            }
            else {
                Header hdr;
                if (!parse_header(line, hdr) || hdr.name.empty())
                    return false;
                headers.push_back(hdr);
                
                String low;
                std::transform(hdr.name.begin(), hdr.name.end(), std::back_inserter(low), &::tolower);
                if (low == "content-length") {
                    content_length = ::atoi(hdr.value.c_str());
                }
            }
        }

        if (!parsing_headers) {
            if (content_length == 0)
                return true;

            if (lim - s < content_length)
                continue;

            body.assign(&request[s], &request[s] + content_length);
            return true;
        }
    }
}
int main( int argc, 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;
	}

	capture = cvCaptureFromCAM( 0 );
	int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ;
	if(!capture) cout << "Capture from CAM " <<  c << " didn't work" << 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, argv );

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

		waitKey(0);

_cleanup_:
		cvReleaseCapture( &capture );
	}

	cvDestroyWindow("result");

	return 0;
}
Example #23
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;
}
Example #24
0
//------------------------------------------------------------------------------
// FUNCTION: getDescription
//
// REMARKS: returns the Description property
//
// PARAMETERS: [OUT] strValue -> string that will receive the Description property 
//                                 value
//
// RETURN: TRUE (hard-coded property value)
//------------------------------------------------------------------------------
Boolean NTPService::getDescription(String & strValue) 
{
    strValue.assign(NTP_DESCRIPTION);
    return true;
}
Example #25
0
String ClangIndexer::addNamePermutations(const CXCursor &cursor, const Location &location)
{
    CXCursorKind kind = clang_getCursorKind(cursor);
    const CXCursorKind originalKind = kind;
    char buf[32768];
    int pos = sizeof(buf) - 1;
    buf[pos] = '\0';
    int cutoff = -1;

    CXCursor c = cursor;
    do {
        CXStringScope displayName(clang_getCursorDisplayName(c));
        const char *name = displayName.data();
        if (!name)
            break;
        const int len = strlen(name);
        if (!len)
            break;

        if (pos != sizeof(buf) - 1 && (pos -= 2) >= 0) {
            memset(buf + pos, ':', 2);
        }
        pos -= len;
        if (pos < 0) {
            error("SymbolName too long. Giving up");
            return String();
        }
        memcpy(buf + pos, name, len);

        c = clang_getCursorSemanticParent(c);
        kind = clang_getCursorKind(c);
        if (cutoff == -1) {
            switch (kind) {
            case CXCursor_ClassDecl:
            case CXCursor_ClassTemplate:
            case CXCursor_StructDecl:
                break;
            case CXCursor_Namespace:
                // namespaces can include all namespaces in their symbolname
                if (originalKind == CXCursor_Namespace)
                    break;
            default:
                cutoff = pos;
                break;
            }
        }
    } while (RTags::needsQualifiers(kind));

    String type;
    switch (originalKind) {
    case CXCursor_ClassDecl:
    case CXCursor_StructDecl:
    case CXCursor_ClassTemplate:
        break;
    default:
        type = RTags::typeName(cursor);
        break;
    }
    if (cutoff == -1)
        cutoff = pos;

    String ret;
    int templateStart, templateEnd, colonColonCount;
    int colonColons[512];
    ::tokenize(buf, pos,
               &templateStart, &templateEnd,
               &colonColonCount, colonColons);

    // i == 0 --> with templates,
    // i == 1 without templates or without EnumConstantDecl part
    for (int i=0; i<2; ++i) {
        for (int j=0; j<colonColonCount; ++j) {
            const char *ch = buf + colonColons[j];
            const String name(ch, sizeof(buf) - (ch - buf) - 1);
            mData->symbolNames[name].insert(location);
            if (!type.isEmpty() && (originalKind != CXCursor_ParmDecl || !strchr(ch, '('))) {
                // We only want to add the type to the final declaration for ParmDecls
                // e.g.
                // void foo(int)::bar
                // and
                // int bar
                //
                // not
                // int void foo(int)::bar
                // or
                // void foo(int)::int bar

                mData->symbolNames[type + name].insert(location);
            }
        }

        if (i == 0) {
            // create actual symbol name that will go into CursorInfo. This doesn't include namespaces etc
            if (!type.isEmpty()) {
                ret = type;
                ret.append(buf + cutoff, sizeof(buf) - cutoff - 1);
            } else {
                ret.assign(buf + cutoff, sizeof(buf) - cutoff - 1);
            }
        }

        if (i == 1 || (templateStart == -1 && originalKind != CXCursor_EnumConstantDecl)) {
            // nothing more to do
            break;
        }

        if (originalKind == CXCursor_EnumConstantDecl) { // remove CXCursor_EnumDecl
            // struct A { enum B { C } };
            // Will by default generate a A::B::C symbolname.
            // This code removes the B:: part from it
            if (colonColonCount > 2) {
                const char *last = buf + colonColons[colonColonCount - 1];
                const char *secondLast = buf + colonColons[colonColonCount - 2];
                const int len = (last - secondLast);
                memmove(buf + pos + len, buf + pos, secondLast - (buf + pos));
                pos += len;
                // ### We could/should just move the colon colon values but this
                // should be pretty quick and I don't want to write the code to
                // do it.
                ::tokenize(buf, pos,
                           &templateStart, &templateEnd,
                           &colonColonCount, colonColons);
            }
        } else { // remove templates
            assert(templateStart != -1);
            assert(templateEnd != -1);
            const int templateSize = (templateEnd - templateStart) + 1;
            memmove(buf + pos + templateSize, buf + pos, (buf + templateStart) - (buf + pos));
            pos += templateSize;
        }
    }

    return ret;
}
Example #26
0
void update_mission_brief_point(
        interfaceItemType *dataItem, long whichBriefPoint, const Scenario* scenario,
        coordPointType *corner, long scale, Rect *bounds, vector<inlinePictType>& inlinePict,
        Rect& highlight_rect, vector<pair<Point, Point> >& lines, String& text) {
    if (whichBriefPoint < kMissionBriefPointOffset) {
        // No longer handled here.
        return;
    }

    whichBriefPoint -= kMissionBriefPointOffset;

    Rect hiliteBounds;
    long            headerID, headerNumber, contentID;
    BriefPoint_Data_Get(whichBriefPoint, scenario, &headerID, &headerNumber, &contentID,
            &hiliteBounds, corner, scale, 16, 32, bounds);
    hiliteBounds.offset(bounds->left, bounds->top);

    // TODO(sfiera): catch exception.
    Resource rsrc("text", "txt", contentID);
    text.assign(macroman::decode(rsrc.data()));
    short textHeight = GetInterfaceTextHeightFromWidth(text, dataItem->style, kMissionDataWidth);
    if (hiliteBounds.left == hiliteBounds.right) {
        dataItem->bounds.left = (bounds->right - bounds->left) / 2 - (kMissionDataWidth / 2) + bounds->left;
        dataItem->bounds.right = dataItem->bounds.left + kMissionDataWidth;
        dataItem->bounds.top = (bounds->bottom - bounds->top) / 2 - (textHeight / 2) + bounds->top;
        dataItem->bounds.bottom = dataItem->bounds.top + textHeight;
    } else {
        if ((hiliteBounds.left + (hiliteBounds.right - hiliteBounds.left) / 2) >
                (bounds->left + (bounds->right - bounds->left) / 2)) {
            dataItem->bounds.right = hiliteBounds.left - kMissionDataHBuffer;
            dataItem->bounds.left = dataItem->bounds.right - kMissionDataWidth;
        } else {
            dataItem->bounds.left = hiliteBounds.right + kMissionDataHBuffer;
            dataItem->bounds.right = dataItem->bounds.left + kMissionDataWidth;
        }

        dataItem->bounds.top = hiliteBounds.top + (hiliteBounds.bottom - hiliteBounds.top) / 2 -
                                textHeight / 2;
        dataItem->bounds.bottom = dataItem->bounds.top + textHeight;
        if (dataItem->bounds.top < (bounds->top + kMissionDataTopBuffer)) {
            dataItem->bounds.top = bounds->top + kMissionDataTopBuffer;
            dataItem->bounds.bottom = dataItem->bounds.top + textHeight;
        }
        if (dataItem->bounds.bottom > (bounds->bottom - kMissionDataBottomBuffer)) {
            dataItem->bounds.bottom = bounds->bottom - kMissionDataBottomBuffer;
            dataItem->bounds.top = dataItem->bounds.bottom - textHeight;
        }

        if (dataItem->bounds.left < (bounds->left + kMissionDataVBuffer)) {
            dataItem->bounds.left = bounds->left + kMissionDataVBuffer;
            dataItem->bounds.right = dataItem->bounds.left + kMissionDataWidth;
        }
        if (dataItem->bounds.right > (bounds->right - kMissionDataVBuffer)) {
            dataItem->bounds.right = bounds->right - kMissionDataVBuffer;
            dataItem->bounds.left = dataItem->bounds.right - kMissionDataWidth;
        }

        hiliteBounds.right++;
        hiliteBounds.bottom++;
        highlight_rect = hiliteBounds;
        Rect newRect;
        GetAnyInterfaceItemGraphicBounds(*dataItem, &newRect);
        lines.clear();
        if (dataItem->bounds.right < hiliteBounds.left) {
            Point p1(hiliteBounds.left, hiliteBounds.top);
            Point p2(newRect.right + kMissionLineHJog, hiliteBounds.top);
            Point p3(newRect.right + kMissionLineHJog, newRect.top);
            Point p4(newRect.right + 2, newRect.top);
            lines.push_back(make_pair(p1, p2));
            lines.push_back(make_pair(p2, p3));
            lines.push_back(make_pair(p3, p4));

            Point p5(hiliteBounds.left, hiliteBounds.bottom - 1);
            Point p6(newRect.right + kMissionLineHJog, hiliteBounds.bottom - 1);
            Point p7(newRect.right + kMissionLineHJog, newRect.bottom - 1);
            Point p8(newRect.right + 2, newRect.bottom - 1);
            lines.push_back(make_pair(p5, p6));
            lines.push_back(make_pair(p6, p7));
            lines.push_back(make_pair(p7, p8));
        } else {
            Point p1(hiliteBounds.right, hiliteBounds.top);
            Point p2(newRect.left - kMissionLineHJog, hiliteBounds.top);
            Point p3(newRect.left - kMissionLineHJog, newRect.top);
            Point p4(newRect.left - 3, newRect.top);
            lines.push_back(make_pair(p1, p2));
            lines.push_back(make_pair(p2, p3));
            lines.push_back(make_pair(p3, p4));

            Point p5(hiliteBounds.right, hiliteBounds.bottom - 1);
            Point p6(newRect.left - kMissionLineHJog, hiliteBounds.bottom - 1);
            Point p7(newRect.left - kMissionLineHJog, newRect.bottom - 1);
            Point p8(newRect.left - 3, newRect.bottom - 1);
            lines.push_back(make_pair(p5, p6));
            lines.push_back(make_pair(p6, p7));
            lines.push_back(make_pair(p7, p8));
        }
    }
    dataItem->item.labeledRect.label.stringID = headerID;
    dataItem->item.labeledRect.label.stringNumber = headerNumber;
    Rect newRect;
    GetAnyInterfaceItemGraphicBounds(*dataItem, &newRect);
    populate_inline_picts(dataItem->bounds, text, dataItem->style, inlinePict);
}
Example #27
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;
	
    CascadeClassifier cascade, nestedCascade;
    double scale = 1;
	
    for( int i = 1; i < argc; i++ )
    {
        if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
            cascadeName.assign( argv[i] + cascadeOptLen );
        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;
        }
        else if( argv[i][0] == '-' )
        {
            cerr << "WARNING: Unknown option %s" << argv[i] << endl;
        }
        else
            inputName.assign( argv[i] );
    }
	
	
    IplImage* motion = 0;
	
	
	// init server bitch!
	
	if (init_server() == -1)
	{
		perror("init server failed");
		return (-1);
	}
	
    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" ;
		
		close_connection();
		
		
		// send close // wait for answer before close or if -1 close
		
        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' );
    else if( inputName.size() )
    {
        image = imread( inputName, 1 );
        if( image.empty() )
            capture = cvCaptureFromAVI( inputName.c_str() );
    }
    else
        image = imread( "lena.jpg", 1 );
	
    cvNamedWindow( "result", 1 );
	cvNamedWindow( "Motion", 1 );
	
    if( capture )
    {
		
		// we should send via socket here :D
        for(;;)
        {
            IplImage* iplImg = cvQueryFrame( capture );
            frame = iplImg;
			
			
            if( !motion )
            {
                motion = cvCreateImage( cvSize(iplImg->width,iplImg->height), 8, 3 );
                cvZero( motion );
                motion->origin = iplImg->origin;
            }
			
            if( frame.empty() )
                break;
            if( iplImg->origin == IPL_ORIGIN_TL )
                frame.copyTo( frameCopy );
            else
                flip( frame, frameCopy, 0 );
			
			// send
			// recv inside the detectAndDraw
            detectAndDraw( frameCopy, iplImg, cascade, nestedCascade, scale, motion);
			
            if( waitKey( 10 ) >= 0 )
                goto _cleanup_;
        }
		close_connection();
        waitKey(0);
	_cleanup_:
		// send close // wait for answer before close or if -1 close
        cvReleaseCapture( &capture );
    }/*
	  else
	  {
	  if( !image.empty() )
	  {
	  detectAndDraw( image, cascade, nestedCascade, scale, motion );
	  waitKey(0);
	  }
	  else if( !inputName.empty() )
	  {
	  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, motion );
	  c = waitKey(0);
	  if( c == 27 || c == 'q' || c == 'Q' )
	  break;
	  }
	  }
	  fclose(f);
	  }
	  }
	  }*/
    cvDestroyWindow( "Motion" );
    cvDestroyWindow("result");
	
    return 0;
}
Example #28
0
//
// Enumerates all the user names.
//
void UserAuthProvider::enumerateInstanceNames(
    const OperationContext & context,
    const CIMObjectPath & classReference,
    ObjectPathResponseHandler & handler)
{
    PEG_METHOD_ENTER(TRC_USER_MANAGER,"UserAuthProvider::enumerateInstanceNames");

    Array<CIMObjectPath> instanceRefs;
    Array<String>       userNames;
    Array<CIMKeyBinding>   keyBindings;
    CIMKeyBinding          kb;
    String            hostName;

    //
    // get userName
    //
    String user;
    try
    {
        IdentityContainer container = context.get(IdentityContainer::NAME);
        user= container.getUserName();
    }
    catch (...)
    {
        user= String::EMPTY;
    }

    //
    // verify user authorizations
    //
    if ( user != String::EMPTY || user != "" )
    {
        _verifyAuthorization(user);
    }

    const CIMName& className = classReference.getClassName();
    const CIMNamespaceName& nameSpace = classReference.getNameSpace();

    // begin processing the request
    handler.processing();

#ifndef PEGASUS_NO_PASSWORDFILE
    //
    // check if the class name requested is PG_User
    //
    if (className.equal (CLASS_NAME_PG_USER))
    {
        try
        {
            hostName.assign(System::getHostName());

            _userManager->getAllUserNames(userNames);

            Uint32 size = userNames.size();

            for (Uint32 i = 0; i < size; i++)
            {
                keyBindings.append(CIMKeyBinding(PROPERTY_NAME_USERNAME, userNames[i],
                                                 CIMKeyBinding::STRING));

                //
                // Convert instance names to References
                //
                CIMObjectPath ref(hostName, nameSpace, className, keyBindings);

                handler.deliver(ref);

                keyBindings.clear();
            }
        }
        catch( const CIMException& )
        {
            handler.complete();
            PEG_METHOD_EXIT();
            throw;
        }
        catch(const Exception& e)
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
        }
    }
    //
    // check if the class name requested is PG_Authorization
    //
    else if (className.equal (CLASS_NAME_PG_AUTHORIZATION))
#else
    if (className.equal (CLASS_NAME_PG_AUTHORIZATION))
#endif
    {
        try
        {
            //
            // call enumerateInstanceNames of the repository
            //
            instanceRefs = _repository->enumerateInstanceNames(
                               nameSpace, className);

            handler.deliver(instanceRefs);

        }
        catch ( CIMException &e )
        {
            PEG_METHOD_EXIT();
            throw PEGASUS_CIM_EXCEPTION(CIM_ERR_FAILED, e.getMessage());
        }
    }
    else
    {
        handler.complete();

        PEG_METHOD_EXIT();
        throw PEGASUS_CIM_EXCEPTION (CIM_ERR_NOT_SUPPORTED,
                                     className.getString());
    }

    // complete processing the request
    handler.complete();

    PEG_METHOD_EXIT();
    return;
}
void HttpRequestHandler::handleRequest(Transport *transport) {
  Logger::OnNewRequest();
  GetAccessLog().onNewRequest();
  transport->enableCompression();

  ServerStatsHelper ssh("all", true);
  Logger::Verbose("receiving %s", transport->getCommand().c_str());

  // will clear all extra logging when this function goes out of scope
  StackTraceNoHeap::ExtraLoggingClearer clearer;
  StackTraceNoHeap::AddExtraLogging("URL", transport->getUrl());

  // resolve virtual host
  const VirtualHost *vhost = HttpProtocol::GetVirtualHost(transport);
  ASSERT(vhost);
  if (vhost->disabled() ||
      vhost->isBlocking(transport->getCommand(), transport->getRemoteHost())) {
    transport->sendString("Not Found", 404);
    return;
  }
  ServerStats::StartRequest(transport->getCommand().c_str(),
                            transport->getRemoteHost(),
                            vhost->getName().c_str());

  // resolve source root
  string host = transport->getHeader("Host");
  SourceRootInfo sourceRootInfo(host.c_str());

  if (sourceRootInfo.error()) {
    sourceRootInfo.handleError(transport);
    return;
  }

  // request URI
  string pathTranslation = m_pathTranslation ?
    vhost->getPathTranslation().c_str() : "";
  RequestURI reqURI(vhost, transport, sourceRootInfo.path(), pathTranslation);
  if (reqURI.done()) {
    return; // already handled with redirection or 404
  }
  string path = reqURI.path().data();
  string absPath = reqURI.absolutePath().data();

  // determine whether we should compress response
  bool compressed = transport->decideCompression();

  const char *data; int len;
  size_t pos = path.rfind('.');
  const char *ext = (pos != string::npos) ? (path.c_str() + pos + 1) : NULL;
  bool cachableDynamicContent =
    (!RuntimeOption::StaticFileGenerators.empty() &&
     RuntimeOption::StaticFileGenerators.find(path) !=
     RuntimeOption::StaticFileGenerators.end());

  // If this is not a php file, check the static and dynamic content caches
  if (ext && strcasecmp(ext, "php") != 0) {
    if (RuntimeOption::EnableStaticContentCache) {
      bool original = compressed;
      // check against static content cache
      if (StaticContentCache::TheCache.find(path, data, len, compressed)) {
        struct stat st;
        st.st_mtime = 0;
        String str;
        // (qigao) not calling stat at this point because the timestamp of
        // local cache file is not valuable, maybe misleading. This way
        // the Last-Modified header will not show in response.
        // stat(RuntimeOption::FileCache.c_str(), &st);
        if (!original && compressed) {
          data = gzdecode(data, len);
          if (data == NULL) {
            throw FatalErrorException("cannot unzip compressed data");
          }
          compressed = false;
          str.assign(data, len, AttachString);
        }
        sendStaticContent(transport, data, len, st.st_mtime, compressed, path);
        ServerStats::LogPage(path, 200);
        return;
      }
    }

    if (RuntimeOption::EnableStaticContentFromDisk &&
        RuntimeOption::StaticFileExtensions.find(ext) !=
        RuntimeOption::StaticFileExtensions.end()) {
      String translated = File::TranslatePath(String(absPath));
      if (!translated.empty()) {
        StringBuffer sb(translated.data());
        if (sb.valid()) {
          struct stat st;
          st.st_mtime = 0;
          stat(translated.data(), &st);
          sendStaticContent(transport, sb.data(), sb.size(), st.st_mtime,
                            false, path);
          ServerStats::LogPage(path, 200);
          return;
        }
      }
    }

    // check static contents that were generated by dynamic pages
    if (cachableDynamicContent) {
      // check against dynamic content cache
      ASSERT(transport->getUrl());
      string key = path + transport->getUrl();
      if (DynamicContentCache::TheCache.find(key, data, len, compressed)) {
        sendStaticContent(transport, data, len, 0, compressed, path);
        ServerStats::LogPage(path, 200);
        return;
      }
    }
  }

  // proxy any URLs that not specified in ServeURLs
  if (!RuntimeOption::ProxyOrigin.empty() &&
      ((RuntimeOption::UseServeURLs &&
        RuntimeOption::ServeURLs.find(path) ==
        RuntimeOption::ServeURLs.end()) ||
       (RuntimeOption::UseProxyURLs &&
        (RuntimeOption::ProxyURLs.find(path) !=
         RuntimeOption::ProxyURLs.end() ||
         MatchAnyPattern(path, RuntimeOption::ProxyPatterns) ||
         (abs(rand()) % 100) < RuntimeOption::ProxyPercentage)))) {
    for (int i = 0; i < RuntimeOption::ProxyRetry; i++) {
      bool force = (i == RuntimeOption::ProxyRetry - 1); // last one
      if (handleProxyRequest(transport, force)) break;
    }
    return;
  }

  // record request for debugging purpose
  std::string tmpfile = HttpProtocol::RecordRequest(transport);

  // main body
  hphp_session_init();

  bool ret = false;
  try {
    ret = executePHPRequest(transport, reqURI, sourceRootInfo,
                            cachableDynamicContent);
  } catch (...) {
    Logger::Error("Unhandled exception in HPHP server engine.");
  }
  GetAccessLog().log(transport);
  hphp_session_exit();

  HttpProtocol::ClearRecord(ret, tmpfile);
}