Example #1
0
void CommandScriptController::ExecuteScript(ScriptConfig::Script* script)
{
	PrintMessage(Message::mkInfo, "Executing script %s with command %s", script->GetName(), *m_command);

	SetArgs({script->GetLocation()});

	BString<1024> infoName("script %s with command %s", script->GetName(), *m_command);
	SetInfoName(infoName);

	SetLogPrefix(script->GetDisplayName());
	PrepareParams(script->GetName());

	int exitCode = Execute();

	infoName[0] = 'S'; // uppercase
	SetLogPrefix(nullptr);

	switch (exitCode)
	{
		case COMMANDPROCESS_SUCCESS:
			PrintMessage(Message::mkInfo, "%s successful", *infoName);
			break;

		case COMMANDPROCESS_ERROR:
		case -1: // Execute() returns -1 if the process could not be started (file not found or other problem)
			PrintMessage(Message::mkError, "%s failed", *infoName);
			break;

		default:
			PrintMessage(Message::mkError, "%s failed (terminated with unknown status)", *infoName);
			break;
	}
}
Example #2
0
void ScanScriptController::ExecuteScript(Options::Script* pScript)
{
	if (!pScript->GetScanScript() || !Util::FileExists(m_szNZBFilename))
	{
		return;
	}

	PrintMessage(Message::mkInfo, "Executing scan-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBFilename));

	SetScript(pScript->GetLocation());
	SetArgs(NULL, false);

	char szInfoName[1024];
	snprintf(szInfoName, 1024, "scan-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBFilename));
	szInfoName[1024-1] = '\0';
	SetInfoName(szInfoName);

	SetLogPrefix(pScript->GetDisplayName());
	m_iPrefixLen = strlen(pScript->GetDisplayName()) + 2; // 2 = strlen(": ");
	PrepareParams(pScript->GetName());

	Execute();

	SetLogPrefix(NULL);
}
Example #3
0
    void Save() {
        // We save the settings twice because the module arguments can
        // be more easily edited via webadmin, while the SetNV() stuff
        // survives e.g. /msg *status reloadmod ctcpflood.
        SetNV("secs", CString(m_iThresholdSecs));
        SetNV("msgs", CString(m_iThresholdMsgs));

        SetArgs(CString(m_iThresholdMsgs) + " " + CString(m_iThresholdSecs));
    }
Example #4
0
bool pybase::ReloadModule()
{
    SetArgs();
    PyObject *newmod;
    
    if(modname.length()) {

        if(module)
            newmod = PyImport_ReloadModule(module);
        else {
            // search in module path (TODO: check before if module is already present to avoid costly searching)
            char dir[1024];
            if(getmodulepath(modname.c_str(),dir,sizeof(dir)))
                AddToPath(dir);
//            else
//                PyErr_SetString(PyExc_ImportError,"Module not found in path");

#if 1
            // strip off eventual subpath from module name
            // it should already have been considered in the above AddToPath call
            size_t p = modname.rfind('/');
            const char *m;
            if(p == std::string::npos)
                m = modname.c_str();
            else {
                // reuse dir buffer...
                strcpy(dir,modname.c_str()+p+1);
                m = dir;
            }

            // module could also be loaded ok, even if it's not in the path (e.g. for internal stuff)
            newmod = PyImport_ImportModule((char *)m);
#else
            newmod = PyImport_ImportModule((char *)modname.c_str());
#endif
        }
    }
    else {
        // if no module name given, take py module
        newmod = module_obj; 
        Py_INCREF(newmod);
    }

    if(!newmod) {
        // unload faulty module
        UnimportModule();
        return false;
    }
    else {
        Py_XDECREF(module);
        module = newmod;
        dict = PyModule_GetDict(module); // borrowed
        return true;
    }
}
Example #5
0
	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		if (sArgs.empty())
			m_sPass = GetNV("Password");
		else {
			m_sPass = sArgs;
			SetNV("Password", m_sPass);
			SetArgs("");
		}

		return true;
	}
Example #6
0
    bool OnLoad(const CString& sArgs, CString& sMessage) override {
        if (!sArgs.empty() && sArgs != "<hidden>") {
            SetNV("Password", sArgs);
            SetArgs("<hidden>");
        }

        if (GetNV("IdentifyCmd").empty()) {
            SetNV("IdentifyCmd", "NICKSERV IDENTIFY {password}");
        }

        return true;
    }
Example #7
0
void ScriptController::PrepareArgs()
{
#ifdef WIN32
	if (!m_szArgs)
	{
		// Special support for script languages:
		// automatically find the app registered for this extension and run it
		const char* szExtension = strrchr(GetScript(), '.');
		if (szExtension && strcasecmp(szExtension, ".exe") && strcasecmp(szExtension, ".bat") && strcasecmp(szExtension, ".cmd"))
		{
			debug("Looking for associated program for %s", szExtension);
			char szCommand[512];
			int iBufLen = 512-1;
			if (Util::RegReadStr(HKEY_CLASSES_ROOT, szExtension, NULL, szCommand, &iBufLen))
			{
				szCommand[iBufLen] = '\0';
				debug("Extension: %s", szCommand);
				
				char szRegPath[512];
				snprintf(szRegPath, 512, "%s\\shell\\open\\command", szCommand);
				szRegPath[512-1] = '\0';
				
				iBufLen = 512-1;
				if (Util::RegReadStr(HKEY_CLASSES_ROOT, szRegPath, NULL, szCommand, &iBufLen))
				{
					szCommand[iBufLen] = '\0';
					debug("Command: %s", szCommand);
					
					DWORD_PTR pArgs[] = { (DWORD_PTR)GetScript(), (DWORD_PTR)0 };
					if (FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ARGUMENT_ARRAY, szCommand, 0, 0,
									  m_szCmdLine, sizeof(m_szCmdLine), (va_list*)pArgs))
					{
						debug("CmdLine: %s", m_szCmdLine);
						return;
					}
				}
			}
			warn("Could not found associated program for %s. Trying to execute %s directly", szExtension, Util::BaseFileName(GetScript()));
		}
	}
#endif

	if (!m_szArgs)
	{
		m_szStdArgs[0] = GetScript();
		m_szStdArgs[1] = NULL;
		SetArgs(m_szStdArgs, false);
	}
}
Example #8
0
    bool OnLoad(const CString& sArgs, CString& sMessage) override {
        if (!sArgs.empty() && sArgs != "<hidden>") {
            SetNV("Password", sArgs);
            SetArgs("<hidden>");
        }

        if (GetNV("IdentifyCmd").empty()) {
            SetNV("IdentifyCmd", "NICKSERV IDENTIFY {password}");
        }

        CString sTmp;
        m_bJoinAfterIdentified = (sTmp = GetNV("JoinAfterIdentified")).empty() ? false : sTmp.ToBool();

        return true;
    }
point_test_suite::point_test_suite(char** args_list, int args_count) :
        test_case()
{
    SetArgs(args_list);
    SetArgsCount(args_count);

    adopt_test_case(new default_constructor_test);
    adopt_test_case(new specific_constructor_test);
    adopt_test_case(new copy_constructor_test);
    adopt_test_case(new equality_operator_test);
    adopt_test_case(new inequality_operator_test);
    adopt_test_case(new self_addition_test);
    adopt_test_case(new self_subtraction_test);
    adopt_test_case(new addition_test);
    adopt_test_case(new subtraction_test);
    adopt_test_case(new copy_operator_test);
    adopt_test_case(new cmd_args_test(GetArgs(), GetArgsCount()));
}
Example #10
0
inline void ScriptObject::Invoke(const StringRef& funcName, TArgs&&... args)
{
	asIObjectType* scriptObjectType = mScriptObject->GetObjectType();
	asIScriptFunction* func = scriptObjectType->GetMethodByName(funcName.c_str());
	if (func == nullptr)
	{
		Log::AssertFailedFormat("Cannot find {}::{}", scriptObjectType->GetName(), funcName.c_str());
		return;
	}

	asIScriptContext* context = ScriptEngine::Instance().GetScriptContext();
	context->Prepare(func);
	context->SetObject(mScriptObject);
	SetArgs(context, std::forward<TArgs>(args)...);
	context->Execute();

	asThreadCleanup();
}
bool CStickyChan::OnLoad(const CString& sArgs, CString& sMessage)
{
	VCString vsChans;
	VCString::iterator it;
	sArgs.Split(",", vsChans, false);

	for (it = vsChans.begin(); it != vsChans.end(); ++it) {
		CString sChan = it->Token(0);
		CString sKey = it->Token(1, true);
		SetNV(sChan, sKey);
	}

	// Since we now have these channels added, clear the argument list
	SetArgs("");

	AddTimer(RunTimer, "StickyChanTimer", 15);
	return(true);
}
Example #12
0
void QueueScriptController::ExecuteScript(ScriptConfig::Script* script)
{
	PrintMessage(m_event == QueueScriptCoordinator::qeFileDownloaded ? Message::mkDetail : Message::mkInfo,
		"Executing queue-script %s for %s", script->GetName(), FileSystem::BaseFileName(m_nzbName));

	SetArgs({script->GetLocation()});

	BString<1024> infoName("queue-script %s for %s", script->GetName(), FileSystem::BaseFileName(m_nzbName));
	SetInfoName(infoName);

	SetLogPrefix(script->GetDisplayName());
	m_prefixLen = strlen(script->GetDisplayName()) + 2; // 2 = strlen(": ");
	PrepareParams(script->GetName());

	Execute();

	SetLogPrefix(nullptr);
}
Example #13
0
void QueueScriptController::ExecuteScript(ScriptConfig::Script* pScript)
{
	PrintMessage(m_eEvent == QueueScriptCoordinator::qeFileDownloaded ? Message::mkDetail : Message::mkInfo,
		"Executing queue-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBName));

	SetScript(pScript->GetLocation());
	SetArgs(NULL, false);

	char szInfoName[1024];
	snprintf(szInfoName, 1024, "queue-script %s for %s", pScript->GetName(), Util::BaseFileName(m_szNZBName));
	szInfoName[1024-1] = '\0';
	SetInfoName(szInfoName);

	SetLogPrefix(pScript->GetDisplayName());
	m_iPrefixLen = strlen(pScript->GetDisplayName()) + 2; // 2 = strlen(": ");
	PrepareParams(pScript->GetName());

	Execute();

	SetLogPrefix(NULL);
}
Example #14
0
void FeedScriptController::ExecuteScript(ScriptConfig::Script* pScript)
{
	if (!pScript->GetFeedScript())
	{
		return;
	}

	PrintMessage(Message::mkInfo, "Executing feed-script %s for Feed%i", pScript->GetName(), m_iFeedID);

	SetScript(pScript->GetLocation());
	SetArgs(NULL, false);

	char szInfoName[1024];
	snprintf(szInfoName, 1024, "feed-script %s for Feed%i", pScript->GetName(), m_iFeedID);
	szInfoName[1024-1] = '\0';
	SetInfoName(szInfoName);

	SetLogPrefix(pScript->GetDisplayName());
	PrepareParams(pScript->GetName());

	Execute();

	SetLogPrefix(NULL);
}
Example #15
0
File: nickserv.cpp Project: KTE/znc
	virtual bool OnLoad(const CString& sArgs, CString& sMessage) {
		if (!sArgs.empty()) {
			SetNV("Password", sArgs);
			SetArgs("");
		}

		if (GetNV("IdentifyCmd").empty()) {
			SetNV("IdentifyCmd", "PRIVMSG NickServ :IDENTIFY {password}");
		}
		if (GetNV("GhostCmd").empty()) {
			SetNV("GhostCmd", "PRIVMSG NickServ :GHOST {nickname} {password}");
		}
		if (GetNV("RecoverCmd").empty()) {
			SetNV("RecoverCmd", "PRIVMSG NickServ :RECOVER {nickname} {password}");
		}
		if (GetNV("ReleaseCmd").empty()) {
			SetNV("ReleaseCmd", "PRIVMSG NickServ :RELEASE {nickname} {password}");
		}
		if (GetNV("GroupCmd").empty()) {
			SetNV("GroupCmd", "PRIVMSG NickServ :GROUP {nickname} {password}");
		}

		return true;
	}
Example #16
0
 void SetArgs(T anArg, Args... args) {
   assert(count < MaxDeps);
   modules[count++] = anArg;
   SetArgs(args...);
 }
Example #17
0
 DepList(Args... args) : count(0) {
   SetArgs(args...);
 }
Example #18
0
FArgs::FArgs(int argc, char **argv)
{
	SetArgs(argc, argv);
}
Example #19
0
void MythSystemUnix::Fork(time_t timeout)
{
    QString LOC_ERR = QString("myth_system('%1'): Error: ").arg(GetLogCmd());

    // For use in the child
    char locerr[MAX_BUFLEN];
    strncpy(locerr, (const char *)LOC_ERR.toUtf8().constData(), MAX_BUFLEN);
    locerr[MAX_BUFLEN-1] = '\0';

    LOG(VB_SYSTEM, LOG_DEBUG, QString("Launching: %1").arg(GetLogCmd()));

    GetBuffer(0)->setBuffer(0);
    GetBuffer(1)->setBuffer(0);
    GetBuffer(2)->setBuffer(0);

    int p_stdin[]  = {-1,-1};
    int p_stdout[] = {-1,-1};
    int p_stderr[] = {-1,-1};

    /* set up pipes */
    if( GetSetting("UseStdin") )
    {
        if( pipe(p_stdin) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdin pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdin[1], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStdout") )
    {
        if( pipe(p_stdout) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stdout pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stdout[0], F_SETFL, O_NONBLOCK);
    }
    if( GetSetting("UseStderr") )
    {
        if( pipe(p_stderr) == -1 )
        {
            LOG(VB_SYSTEM, LOG_ERR, LOC_ERR + "stderr pipe() failed");
            SetStatus( GENERIC_EXIT_NOT_OK );
        }
        else
            fcntl(p_stderr[0], F_SETFL, O_NONBLOCK);
    }

    // set up command args
    if (GetSetting("UseShell"))
    {
        QStringList args = QStringList("-c");
        args << GetCommand() + " " + GetArgs().join(" ");
        SetArgs( args );
        QString cmd = "/bin/sh";
        SetCommand( cmd );
    }
    QStringList args = GetArgs();
    args.prepend(GetCommand().split('/').last());
    SetArgs( args );

    QByteArray cmdUTF8 = GetCommand().toUtf8();
    const char *command = strdup(cmdUTF8.constData());

    char **cmdargs = (char **)malloc((args.size() + 1) * sizeof(char *));
    int i;
    QStringList::const_iterator it;

    for( i = 0, it = args.constBegin(); it != args.constEnd(); it++, i++ )
    {
        cmdargs[i] = strdup( it->toUtf8().constData() );
    }
    cmdargs[i] = NULL;

    const char *directory = NULL;
    QString dir = GetDirectory();
    if (GetSetting("SetDirectory") && !dir.isEmpty())
        directory = strdup(dir.toUtf8().constData());

    // check before fork to avoid QString use in child
    bool setpgidsetting = GetSetting("SetPGID");

    /* Do this before forking in case the child miserably fails */
    m_timeout = timeout;
    if( timeout )
        m_timeout += time(NULL);

    pid_t child = fork();

    if (child < 0)
    {
        /* Fork failed, still in parent */
        LOG(VB_SYSTEM, LOG_ERR, "fork() failed: " + ENO);
        SetStatus( GENERIC_EXIT_NOT_OK );
    }
    else if( child > 0 )
    {
        /* parent */
        m_pid = child;
        SetStatus( GENERIC_EXIT_RUNNING );

        LOG(VB_SYSTEM, LOG_INFO,
                    QString("Managed child (PID: %1) has started! "
                            "%2%3 command=%4, timeout=%5")
                        .arg(m_pid) .arg(GetSetting("UseShell") ? "*" : "")
                        .arg(GetSetting("RunInBackground") ? "&" : "")
                        .arg(GetLogCmd()) .arg(timeout));

        /* close unused pipe ends */
        CLOSE(p_stdin[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[1]);

        // store the rest
        m_stdpipe[0] = p_stdin[1];
        m_stdpipe[1] = p_stdout[0];
        m_stdpipe[2] = p_stderr[0];
    }
    else if (child == 0)
    {
        /* Child - NOTE: it is not safe to use LOG or QString between the 
         * fork and execv calls in the child.  It causes occasional locking 
         * issues that cause deadlocked child processes. */

        /* handle standard input */
        if( p_stdin[0] >= 0 )
        {
            /* try to attach stdin to input pipe - failure is fatal */
            if( dup2(p_stdin[0], 0) < 0 )
            {
                cerr << locerr
                     << "Cannot redirect input pipe to standard input: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }
        else
        {
            /* try to attach stdin to /dev/null */
            int fd = open("/dev/null", O_RDONLY);
            if( fd >= 0 )
            {
                if( dup2(fd, 0) < 0)
                {
                    cerr << locerr
                         << "Cannot redirect /dev/null to standard input,"
                            "\n\t\t\tfailed to duplicate file descriptor: " 
                         << strerror(errno) << endl;
                }
            }
            else
            {
                cerr << locerr
                     << "Cannot redirect /dev/null to standard input, "
                        "failed to open: "
                     << strerror(errno) << endl;
            }
        }

        /* handle standard output */
        if( p_stdout[1] >= 0 )
        {
            /* try to attach stdout to output pipe - failure is fatal */
            if( dup2(p_stdout[1], 1) < 0)
            {
                cerr << locerr
                     << "Cannot redirect output pipe to standard output: "
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* handle standard err */
        if( p_stderr[1] >= 0 )
        {
            /* try to attach stderr to error pipe - failure is fatal */
            if( dup2(p_stderr[1], 2) < 0)
            {
                cerr << locerr
                     << "Cannot redirect error pipe to standard error: " 
                     << strerror(errno) << endl;
                _exit(GENERIC_EXIT_PIPE_FAILURE);
            }
        }

        /* Close all open file descriptors except stdin/stdout/stderr */
        for( int i = sysconf(_SC_OPEN_MAX) - 1; i > 2; i-- )
            close(i);

        /* set directory */
        if( directory && chdir(directory) < 0 )
        {
            cerr << locerr
                 << "chdir() failed: "
                 << strerror(errno) << endl;
        }

        /* Set the process group id to be the same as the pid of this child
         * process.  This ensures that any subprocesses launched by this
         * process can be killed along with the process itself. */ 
        if (setpgidsetting && setpgid(0,0) < 0 ) 
        {
            cerr << locerr
                 << "setpgid() failed: "
                 << strerror(errno) << endl;
        }

        /* run command */
        if( execv(command, cmdargs) < 0 )
        {
            // Can't use LOG due to locking fun.
            cerr << locerr
                 << "execv() failed: "
                 << strerror(errno) << endl;
        }

        /* Failed to exec */
        _exit(GENERIC_EXIT_DAEMONIZING_ERROR); // this exit is ok
    }

    /* Parent */

    // clean up the memory use
    if( command )
        free((void *)command);

    if( directory )
        free((void *)directory);

    if( cmdargs )
    {
        for (i = 0; cmdargs[i]; i++)
            free( cmdargs[i] );
        free( cmdargs );
    }

    if( GetStatus() != GENERIC_EXIT_RUNNING )
    {
        CLOSE(p_stdin[0]);
        CLOSE(p_stdin[1]);
        CLOSE(p_stdout[0]);
        CLOSE(p_stdout[1]);
        CLOSE(p_stderr[0]);
        CLOSE(p_stderr[1]);
    }
}
Example #20
0
DArgs::DArgs (const char *cmdline)
{
	SetArgs(cmdline);
}
 cmd_args_test(char** args_list, int args_count)
 {
     SetArgs(args_list);
     SetArgsCount(args_count);
 }