Esempio n. 1
0
int main(int argc, char *argv[])
{
    GenericAgentConfig *config = CheckOpts(argc, argv);
    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    GenericAgentDiscoverContext(ctx, config);

    Policy *policy = NULL;
    if (GenericAgentCheckPolicy(config, false, false))
    {
        policy = LoadPolicy(ctx, config);
    }
    else if (config->tty_interactive)
    {
        exit(EXIT_FAILURE);
    }
    else
    {
        Log(LOG_LEVEL_ERR, "CFEngine was not able to get confirmation of promises from cf-promises, so going to failsafe");
        EvalContextClassPutHard(ctx, "failsafe_fallback", "attribute_name=Errors,source=agent");
        GenericAgentConfigSetInputFile(config, GetInputDir(), "failsafe.cf");
        policy = LoadPolicy(ctx, config);
    }

    ThisAgentInit();

    ExecConfig *exec_config = ExecConfigNew(!ONCE, ctx, policy);
    ExecdConfig *execd_config = ExecdConfigNew(ctx, policy);
    SetFacility(execd_config->log_facility);

#ifdef __MINGW32__
    if (WINSERVICE)
    {
        NovaWin_StartExecService();
    }
    else
#endif /* __MINGW32__ */
    {
        StartServer(ctx, policy, config, &execd_config, &exec_config);
    }

    ExecConfigDestroy(exec_config);
    ExecdConfigDestroy(execd_config);
    GenericAgentConfigDestroy(config);

    return 0;
}
Esempio n. 2
0
static Seq *LoadAndCheck(const char *filename)
{
    Policy *p = LoadPolicy(filename);

    Seq *errs = SeqNew(10, PolicyErrorDestroy);
    PolicyCheckPartial(p, errs);

    DumpErrors(errs);

    return errs;
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
    GenericAgentConfig *config = CheckOpts(argc, argv);
    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    GenericAgentDiscoverContext(ctx, config);
    Policy *policy = LoadPolicy(ctx, config);

    ThisAgentInit(ctx);
    KeepPromises(ctx, policy);

    MonitorStartServer(ctx, policy);

    PolicyDestroy(policy);
    GenericAgentFinalize(ctx, config);
    return 0;
}
Esempio n. 4
0
static void CheckFileChanges(EvalContext *ctx, Policy **policy, GenericAgentConfig *config)
{
    Log(LOG_LEVEL_DEBUG, "Checking file updates for input file '%s'",
        config->input_file);

    time_t validated_at = ReadTimestampFromPolicyValidatedFile(config, NULL);

    bool reload_config = false;

    if (config->agent_specific.daemon.last_validated_at < validated_at)
    {
        Log(LOG_LEVEL_VERBOSE, "New promises detected...");
        reload_config = true;
    }
    if (ReloadConfigRequested())
    {
        Log(LOG_LEVEL_VERBOSE, "Force reload of inputs files...");
        reload_config = true;
    }

    if (reload_config)
    {
        ClearRequestReloadConfig();

        /* Rereading policies now, so update timestamp. */
        config->agent_specific.daemon.last_validated_at = validated_at;

        if (GenericAgentArePromisesValid(config))
        {
            Log(LOG_LEVEL_NOTICE, "Rereading policy file '%s'",
                config->input_file);

            /* STEP 1: Free everything */

            EvalContextClear(ctx);

            strcpy(VDOMAIN, "undefined.domain");

            ClearAuthAndACLs();
            PolicyDestroy(*policy);               *policy = NULL;

            /* STEP 2: Set Environment, Parse and Evaluate policy */

            /*
             * TODO why is this done separately here? What's the difference to
             * calling the same steps as in cf-serverd.c:main()? Those are:
             *   GenericAgentConfigApply();     // not here!
             *   GenericAgentDiscoverContext(); // not here!
             *   EvalContextClassPutHard("server");             // only here!
             *   if (GenericAgentCheckPolicy()) // not here!
             *     policy = LoadPolicy();
             *   ThisAgentInit();               // not here, only calls umask()
             *   ReloadHAConfig();                              // only here!
             *   KeepPromises();
             *   Summarize();
             * Plus the following from within StartServer() which is only
             * called during startup:
             *   InitSignals();                  // not here
             *   ServerTLSInitialize();          // not here
             *   SetServerListenState();         // not here
             *   InitServer()                    // not here
             *   PolicyNew()+AcquireServerLock() // not here
             *   PrepareServer(sd);              // not here
             *   CollectCallStart();  // both
             */

            EvalContextSetPolicyServerFromFile(ctx, GetWorkDir());

            UpdateLastPolicyUpdateTime(ctx);

            DetectEnvironment(ctx);
            KeepHardClasses(ctx);
            LoadAugments(ctx, config);

            /* During startup this is done in GenericAgentDiscoverContext(). */
            EvalContextClassPutHard(ctx, CF_AGENTTYPES[AGENT_TYPE_SERVER], "cfe_internal,source=agent");

            time_t t = SetReferenceTime();
            UpdateTimeClasses(ctx, t);

            /* TODO BUG: this modifies config, but previous config has not
             * been reset/free'd. Ideally we would want LoadPolicy to not
             * modify config at all, but only modify ctx. */
            *policy = LoadPolicy(ctx, config);

            /* Reload HA related configuration */
            ReloadHAConfig();

            KeepPromises(ctx, *policy, config);
            Summarize();
        }
        else
        {
            Log(LOG_LEVEL_INFO, "File changes contain errors -- ignoring");
        }
    }
    else
    {
        Log(LOG_LEVEL_DEBUG, "No new promises found");
    }
}
Esempio n. 5
0
static bool ScheduleRun(EvalContext *ctx, Policy **policy, GenericAgentConfig *config,
                        ExecdConfig **execd_config, ExecConfig **exec_config)
{
    Log(LOG_LEVEL_VERBOSE, "Sleeping for pulse time %d seconds...", CFPULSETIME);
    sleep(CFPULSETIME);         /* 1 Minute resolution is enough */

    /*
     * FIXME: this logic duplicates the one from cf-serverd.c. Unify ASAP.
     */

    if (CheckNewPromises(config) == RELOAD_FULL)
    {
        /* Full reload */

        Log(LOG_LEVEL_INFO, "Re-reading promise file '%s'", config->input_file);

        EvalContextClear(ctx);

        strcpy(VDOMAIN, "undefined.domain");

        PolicyDestroy(*policy);
        *policy = NULL;

        {
            char *existing_policy_server = ReadPolicyServerFile(GetWorkDir());
            SetPolicyServer(ctx, existing_policy_server);
            free(existing_policy_server);
        }
        UpdateLastPolicyUpdateTime(ctx);

        DetectEnvironment(ctx);

        EvalContextClassPutHard(ctx, CF_AGENTTYPES[AGENT_TYPE_EXECUTOR], "cfe_internal,source=agent");

        time_t t = SetReferenceTime();
        UpdateTimeClasses(ctx, t);

        GenericAgentConfigSetBundleSequence(config, NULL);

        *policy = LoadPolicy(ctx, config);
        ExecConfigDestroy(*exec_config);
        ExecdConfigDestroy(*execd_config);

        *exec_config = ExecConfigNew(!ONCE, ctx, *policy);
        *execd_config = ExecdConfigNew(ctx, *policy);

        SetFacility((*execd_config)->log_facility);
    }
    else
    {
        /* Environment reload */

        EvalContextClear(ctx);

        DetectEnvironment(ctx);

        time_t t = SetReferenceTime();
        UpdateTimeClasses(ctx, t);
    }

    {
        StringSetIterator it = StringSetIteratorInit((*execd_config)->schedule);
        const char *time_context = NULL;
        while ((time_context = StringSetIteratorNext(&it)))
        {
            if (IsDefinedClass(ctx, time_context))
            {
                Log(LOG_LEVEL_VERBOSE, "Waking up the agent at %s ~ %s", ctime(&CFSTARTTIME), time_context);
                return true;
            }
        }
    }

    Log(LOG_LEVEL_VERBOSE, "Nothing to do at %s", ctime(&CFSTARTTIME));
    return false;
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
#if !defined(__MINGW32__)
    int count = 0;
    int status;
    int pid;
#endif

    GenericAgentConfig *config = CheckOpts(argc, argv);
    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    GenericAgentDiscoverContext(ctx, config);
    Policy *policy = LoadPolicy(ctx, config);

    ThisAgentInit();
    KeepControlPromises(ctx, policy);      // Set RUNATTR using copy

    if (BACKGROUND && INTERACTIVE)
    {
        Log(LOG_LEVEL_ERR, "You cannot specify background mode and interactive mode together");
        exit(EXIT_FAILURE);
    }

/* HvB */
    if (HOSTLIST)
    {
        const Rlist *rp = HOSTLIST;

        while (rp != NULL)
        {

#ifdef __MINGW32__
            if (BACKGROUND)
            {
                Log(LOG_LEVEL_VERBOSE,
                    "Windows does not support starting processes in the background - starting in foreground");
                BACKGROUND = false;
            }
#else
            if (BACKGROUND)     /* parallel */
            {
                if (count <= MAXCHILD)
                {
                    if (fork() == 0)    /* child process */
                    {
                        HailServer(ctx, config, RlistScalarValue(rp));
                        exit(EXIT_SUCCESS);
                    }
                    else        /* parent process */
                    {
                        rp = rp->next;
                        count++;
                    }
                }
                else
                {
                    pid = wait(&status);
                    Log(LOG_LEVEL_DEBUG, "child = %d, child number = %d", pid, count);
                    count--;
                }
            }
            else                /* serial */
#endif /* __MINGW32__ */
            {
                HailServer(ctx, config, RlistScalarValue(rp));
                rp = rp->next;
            }
        }                       /* end while */
    }                           /* end if HOSTLIST */

#ifndef __MINGW32__
    if (BACKGROUND)
    {
        Log(LOG_LEVEL_NOTICE, "Waiting for child processes to finish");
        while (count > 1)
        {
            pid = wait(&status);
            Log(LOG_LEVEL_VERBOSE, "Child %d ended, number %d", pid, count);
            count--;
        }
    }
#endif

    PolicyDestroy(policy);
    GenericAgentFinalize(ctx, config);

    return 0;
}
Esempio n. 7
0
int main(int argc,char *argv[])
{
	int i,j,num;
	
	int retval;
	int recordsize,certsize;
	
	int templen;
	void *p;
	unsigned char *temp;
	struct stat statbuf;
	BYTE * buffer, *databuffer;
	int fd;

	retval=0;

	// test the policy function
	InitPolicyLib();

	LoadTxtPolicyFile("../txtpolicy/sublist.txt","SUBL",&buffer);
	LoadPolicyData(buffer);
	free(buffer);

	char * newPolicyString="/etc/rc2.d/s02syslog	syslog	0	16	AAAAAAAAAAA	20 	AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
	void * policy;
	policy=BuildPolicy(newPolicyString,"SUBL");
	if(policy==NULL)
	{
		printf("Build Policy Struct Error!");
		return 0;
	}
	OutPutPolicy(policy,"SUBL");
	printf("\n");
	AddPolicy(policy,"SUBL");
	char * newPolicyString1="/etc/rc2.d/s02syslog	device	0	12	AAAAAAAAAAA	0";
	policy=BuildPolicy(newPolicyString1,"SUBL");
	if(policy==NULL)
	{
		printf("Build Policy Struct Error!");
		return 0;
	}
	AddPolicy(policy,"SUBL");

	policy=FindPolicy("$auditd","SUBL");

	UpdatePolicyFile("SUBL");

	LoadPolicy("SUBL");

	policy=GetFirstPolicy("SUBL");
	i=0;
	while(policy!=NULL)
	{
		OutPutPolicy(policy,"SUBL");
		printf("\n");
		policy=GetNextPolicy("SUBL");
		i++;
	}	

	//  update OBJL policy
	LoadTxtPolicyFile("../txtpolicy/objlist.txt","OBJL",&buffer);
	LoadPolicyData(buffer);
	free(buffer);
	policy=GetFirstPolicy("OBJL");
	i=0;
	while(policy!=NULL)
	{
		OutPutPolicy(policy,"OBJL");
		printf("\n");
		policy=GetNextPolicy("OBJL");
		i++;
	}	
	UpdatePolicyFile("OBJL");

	//  update AUUL policy
	LoadTxtPolicyFile("../txtpolicy/uidfile.txt","AUUL",&buffer);
	LoadPolicyData(buffer);
	free(buffer);
	policy=GetFirstPolicy("AUUL");
	i=0;
	while(policy!=NULL)
	{
		OutPutPolicy(policy,"AUUL");
		printf("\n");
		policy=GetNextPolicy("AUUL");
		i++;
	}	
	UpdatePolicyFile("AUUL");

	// update AUDI policy
	LoadTxtPolicyFile("../txtpolicy/auditlist.txt","AUDI",&buffer);
	LoadPolicyData(buffer);
	free(buffer);
	policy=GetFirstPolicy("AUDI");
	i=0;
	while(policy!=NULL)
	{
		OutPutPolicy(policy,"AUDI");
		printf("\n");
		policy=GetNextPolicy("AUDI");
		i++;
	}	
	UpdatePolicyFile("AUDI");

	// test the policy function
/*	
	void * filter1, *filter2;
	void * auditlist;

	filter1=CreateAuditFilter();
	filter2=CreateAuditFilter();
	
	time_t time;
	time=ConvertTimeString("20111117120000");

	SetAuditFilterAttr(filter1,"tm1",&time);
	unsigned short Bret=0xff;
	SetAuditFilterAttr(filter1,"Bret",&Bret);

	auditlist=CreateAuditList();

	SetAuditFilterOp(filter1,AUDIT_PROBE_EXEC_FILE,1);
	SetAuditListFilter(auditlist,filter1);
	SetAuditListType(auditlist,KEY_AUDIT_RECORD);
	retval=ReadAuditList(auditlist);
	printf("read %d audit record!\n",retval);
		
	AUDIT_RECORD audit_record;	
	retval=GetLastAuditRecord(&audit_record,auditlist);
	while(retval>0)
	{
		if(IfAuditRecordHasExpand(&audit_record))
		{
			void * currsite;
			currsite=GetCurrRecordSite(auditlist);
			OutputAuditRecordWithExpand(&audit_record,
				currsite,auditlist);
		}
		else
		{
			OutputAuditRecord(&audit_record);

		}	
		retval=GetPrevAuditRecord(&audit_record,auditlist);
	}
	

	DelAuditList(auditlist);
	DelAuditFilter(filter1);
	DelAuditFilter(filter2);
	*/
	return 0;
}
Esempio n. 8
0
static void test_policy_json_offsets(void)
{
    JsonElement *json = NULL;
    {
        Policy *original = LoadPolicy("benchmark.cf");
        json = PolicyToJson(original);
        PolicyDestroy(original);
    }
    assert_true(json);

    JsonElement *json_bundles = JsonObjectGetAsArray(json, "bundles");
    {
        JsonElement *main_bundle = JsonArrayGetAsObject(json_bundles, 0);
        int line = JsonPrimitiveGetAsInteger(JsonObjectGet(main_bundle, "line"));
        assert_int_equal(9, line);

        JsonElement *json_promise_types = JsonObjectGetAsArray(main_bundle, "promiseTypes");
        {
            JsonElement *json_reports_type = JsonArrayGetAsObject(json_promise_types, 0);
            line = JsonPrimitiveGetAsInteger(JsonObjectGet(json_reports_type, "line"));
            assert_int_equal(11, line);

            JsonElement *json_contexts = JsonObjectGetAsArray(json_reports_type, "contexts");
            JsonElement *cf_context = JsonArrayGetAsObject(json_contexts, 0);
            JsonElement *cf_context_promises = JsonObjectGetAsArray(cf_context, "promises");
            JsonElement *hello_cf_promise = JsonArrayGetAsObject(cf_context_promises, 0);

            line = JsonPrimitiveGetAsInteger(JsonObjectGet(hello_cf_promise, "line"));
            assert_int_equal(13, line);
            JsonElement *hello_cf_attribs = JsonObjectGetAsArray(hello_cf_promise, "attributes");
            {
                JsonElement *friend_pattern_attrib = JsonArrayGetAsObject(hello_cf_attribs, 0);

                line = JsonPrimitiveGetAsInteger(JsonObjectGet(friend_pattern_attrib, "line"));
                assert_int_equal(14, line);
            }
        }
    }

    JsonElement *json_bodies = JsonObjectGetAsArray(json, "bodies");
    {
        JsonElement *control_body = JsonArrayGetAsObject(json_bodies, 0);
        int line = JsonPrimitiveGetAsInteger(JsonObjectGet(control_body, "line"));
        assert_int_equal(4, line);

        JsonElement *myperms_body = JsonArrayGetAsObject(json_bodies, 1);
        line = JsonPrimitiveGetAsInteger(JsonObjectGet(myperms_body, "line"));
        assert_int_equal(28, line);

        JsonElement *myperms_contexts = JsonObjectGetAsArray(myperms_body, "contexts");
        JsonElement *any_context = JsonArrayGetAsObject(myperms_contexts, 0);
        JsonElement *any_attribs = JsonObjectGetAsArray(any_context, "attributes");
        {
            JsonElement *mode_attrib = JsonArrayGetAsObject(any_attribs, 0);
            line = JsonPrimitiveGetAsInteger(JsonObjectGet(mode_attrib, "line"));
            assert_int_equal(30, line);
        }
    }

    JsonDestroy(json);
}
Esempio n. 9
0
static void test_policy_json_to_from(void)
{
    EvalContext *ctx = EvalContextNew();
    Policy *policy = NULL;
    {
        Policy *original = LoadPolicy("benchmark.cf");
        JsonElement *json = PolicyToJson(original);
        PolicyDestroy(original);
        policy = PolicyFromJson(json);
        JsonDestroy(json);
    }
    assert_true(policy);

    assert_int_equal(1, SeqLength(policy->bundles));
    assert_int_equal(2, SeqLength(policy->bodies));

    {
        Bundle *main_bundle = PolicyGetBundle(policy, NULL, "agent", "main");
        assert_true(main_bundle);
        {
            {
                PromiseType *files = BundleGetPromiseType(main_bundle, "files");
                assert_true(files);
                assert_int_equal(1, SeqLength(files->promises));

                for (size_t i = 0; i < SeqLength(files->promises); i++)
                {
                    Promise *promise = SeqAt(files->promises, i);

                    if (strcmp("/tmp/stuff", promise->promiser) == 0)
                    {
                        assert_string_equal("any", promise->classes);

                        assert_int_equal(2, SeqLength(promise->conlist));

                        {
                            Constraint *create = PromiseGetConstraint(ctx, promise, "create");
                            assert_true(create);
                            assert_string_equal("create", create->lval);
                            assert_string_equal("true", RvalScalarValue(create->rval));
                        }

                        {
                            Constraint *create = PromiseGetConstraint(ctx, promise, "perms");
                            assert_true(create);
                            assert_string_equal("perms", create->lval);
                            assert_string_equal("myperms", RvalScalarValue(create->rval));
                        }
                    }
                    else
                    {
                        fprintf(stderr, "Found unknown promise");
                        fail();
                    }
                }
            }

            {
                const char* reportOutput[2] = { "Hello, CFEngine", "Hello, world" };
                const char* reportClass[2] = { "cfengine", "any" };
                PromiseType *reports = BundleGetPromiseType(main_bundle, "reports");
                assert_true(reports);
                assert_int_equal(2, SeqLength(reports->promises));

                for (size_t i = 0; i < SeqLength(reports->promises); i++)
                {
                    Promise *promise = SeqAt(reports->promises, i);

                    if (strcmp(reportOutput[i], promise->promiser) == 0)
                    {
                        assert_string_equal(reportClass[i], promise->classes);

                        assert_int_equal(1, SeqLength(promise->conlist));

                        {
                            Constraint *friend_pattern = SeqAt(promise->conlist, 0);
                            assert_true(friend_pattern);
                            assert_string_equal("friend_pattern", friend_pattern->lval);
                            assert_int_equal(RVAL_TYPE_FNCALL, friend_pattern->rval.type);
                            FnCall *fn = RvalFnCallValue(friend_pattern->rval);
                            assert_string_equal("hash", fn->name);
                            assert_int_equal(2, RlistLen(fn->args));
                        }
                    }
                    else
                    {
                        fprintf(stderr, "Found unknown promise");
                        fail();
                    }
                }
            }
        }
    }

    {
        Body *myperms = PolicyGetBody(policy, NULL, "perms", "myperms");
        assert_true(myperms);

        {
            Seq *mode_cps = BodyGetConstraint(myperms, "mode");
            assert_int_equal(1, SeqLength(mode_cps));

            Constraint *mode = SeqAt(mode_cps, 0);
            assert_string_equal("mode", mode->lval);
            assert_string_equal("555", RvalScalarValue(mode->rval));
        }
    }

    PolicyDestroy(policy);
    EvalContextDestroy(ctx);
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    GenericAgentConfig *config = CheckOpts(argc, argv);
    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    GenericAgentDiscoverContext(ctx, config);
    Policy *policy = LoadPolicy(ctx, config);
    if (!policy)
    {
        Log(LOG_LEVEL_ERR, "Input files contain errors.");
        exit(EXIT_FAILURE);
    }

    if (NULL != config->tag_release_dir)
    {
        // write the validated file and the release ID
        bool tagged = GenericAgentTagReleaseDirectory(config, config->tag_release_dir, true, true);
        if (tagged)
        {
            Log(LOG_LEVEL_VERBOSE, "Release tagging done!");
        }
        else
        {
            Log(LOG_LEVEL_ERR, "The given directory could not be tagged, sorry.");
            exit(EXIT_FAILURE);
        }
    }

    if (SHOWREPORTS)
    {
        ShowPromises(policy->bundles, policy->bodies);
    }

    switch (config->agent_specific.common.policy_output_format)
    {
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF:
        {
            Policy *output_policy = ParserParseFile(AGENT_TYPE_COMMON, config->input_file,
                                                    config->agent_specific.common.parser_warnings,
                                                    config->agent_specific.common.parser_warnings_error);
            Writer *writer = FileWriter(stdout);
            PolicyToString(policy, writer);
            WriterClose(writer);
            PolicyDestroy(output_policy);
        }
        break;

    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON:
        {
            Policy *output_policy = ParserParseFile(AGENT_TYPE_COMMON, config->input_file,
                                                    config->agent_specific.common.parser_warnings,
                                                    config->agent_specific.common.parser_warnings_error);
            JsonElement *json_policy = PolicyToJson(output_policy);
            Writer *writer = FileWriter(stdout);
            JsonWrite(writer, json_policy, 2);
            WriterClose(writer);
            JsonDestroy(json_policy);
            PolicyDestroy(output_policy);
        }
        break;

    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_NONE:
        break;
    }

    if(config->agent_specific.common.show_classes)
    {
        ShowContextsFormatted(ctx);
    }

    if(config->agent_specific.common.show_variables)
    {
        ShowVariablesFormatted(ctx);
    }

    PolicyDestroy(policy);
    GenericAgentFinalize(ctx, config);
}
Esempio n. 11
0
static void test_load(void)
{
    GenericAgentConfig *agent_config = GenericAgentConfigNewDefault(AGENT_TYPE_EXECUTOR);
    ExecConfig *c = ExecConfigNewDefault(true, "host", "ip");

    assert_true(c->scheduled_run);
    assert_string_equal("host", c->fq_name);
    assert_string_equal("ip", c->ip_address);

    TestCheckConfigIsDefault(c);

    EvalContext *ctx = EvalContextNew();
    {
        VarRef *lval = VarRefParse("g.host");
        EvalContextVariablePut(ctx, lval, "snookie", DATA_TYPE_STRING, NULL);
        VarRefDestroy(lval);
    }

    // provide a full body executor control and check that all options are collected
    {
        Policy *p = LoadPolicy("body_executor_control_full.cf");
        PolicyResolve(ctx, p, agent_config);

        ExecConfigUpdate(ctx, p, c);

        assert_true(c->scheduled_run);
        assert_string_equal("host", c->fq_name);
        assert_string_equal("ip", c->ip_address);

        assert_int_equal(120, c->agent_expireafter);
        assert_string_equal("/bin/echo", c->exec_command);
        assert_string_equal("LOG_LOCAL6",c->log_facility);
        assert_string_equal("*****@*****.**",c->mail_from_address);
        assert_int_equal(50, c->mail_max_lines);
        assert_string_equal("localhost", c->mail_server);
        assert_string_equal("*****@*****.**",c->mail_to_address);
        assert_string_equal("Test [localhost/127.0.0.1]",c->mail_subject);

        // splay time hard to test (pseudo random)

        assert_int_equal(2, StringSetSize(c->schedule));
        assert_true(StringSetContains(c->schedule, "Min00_05"));
        assert_true(StringSetContains(c->schedule, "Min05_10"));

        PolicyDestroy(p);
    }

    // provide a small policy and check that missing settings are being reverted to default
    {
        {
            Policy *p = LoadPolicy("body_executor_control_agent_expireafter_only.cf");
            PolicyResolve(ctx, p, agent_config);

            ExecConfigUpdate(ctx, p, c);

            assert_true(c->scheduled_run);
            assert_string_equal("host", c->fq_name);
            assert_string_equal("ip", c->ip_address);

            assert_int_equal(121, c->agent_expireafter);

            // rest should be default
            assert_string_equal("", c->exec_command);
            assert_string_equal("LOG_USER",c->log_facility);
            assert_string_equal("",c->mail_from_address);
            assert_int_equal(30, c->mail_max_lines);
            assert_string_equal("", c->mail_server);
            assert_string_equal("",c->mail_to_address);
            assert_string_equal("",c->mail_subject);
            assert_int_equal(0, c->splay_time);

            assert_int_equal(12, StringSetSize(c->schedule));

            PolicyDestroy(p);
        }
    }

    EvalContextDestroy(ctx);
    GenericAgentConfigDestroy(agent_config);

}
Esempio n. 12
0
int main()
{

    struct tcloud_connector_hub * hub;
    struct tcloud_connector * temp_conn;
    int ret;
    int retval;
    void * message_box;
    int i,j;

    void * main_proc; // point to the main proc's subject struct
    void * conn_proc; // point to the conn proc's subject struct
    void * router_proc; // point to the conn proc's subject struct
    char local_uuid[DIGEST_SIZE*2];

    const char * audit_filename= "./message.log";
    FILE * fp;
    char audit_text[4096];
    int fd =open(audit_filename,O_CREAT|O_RDWR|O_TRUNC,0666);
    close(fd);

    system("mkdir lib");
    openstack_trust_lib_init();
    sec_respool_list_init();
    // init the main proc struct
    ret=sec_subject_create(main_proc_name,PROC_TYPE_MAIN,NULL,&main_proc);
    if(ret<0)
    	return ret;

    // init the proc's main share data
    ret=proc_share_data_init(share_data_desc);
    ret=get_local_uuid(local_uuid);
    printf("this machine's local uuid is %s\n",local_uuid);
    proc_share_data_setvalue("uuid",local_uuid);
    proc_share_data_setvalue("proc_name",main_proc_name);

    // do the main proc's init function
    sec_subject_setinitfunc(main_proc,main_proc_initfunc);
    sec_subject_setstartfunc(main_proc,NULL);
    sec_subject_init(main_proc,main_proc_name);
	
    // init all the proc database

    usleep(time_val.tv_usec);

    for(i=0;procdb_init_list[i].name!=NULL;i++)
    {
	    PROCDB_INIT * db_init=&procdb_init_list[i];
	    if(db_init->record_desc!=NULL)
	    {
		    retval=register_record_type(db_init->name,db_init->record_desc);
		    if(retval<0)
			    return -EINVAL;
	    }
		
	    if(db_init->recordlib_ops!=NULL)
	    {
	   	 retval=register_policy_lib(db_init->name,db_init->recordlib_ops);
	  	 if(retval<0)
	         {
		    printf("register lib %s error!\n",db_init->name);
		    return retval;
	    	 }
	         retval=db_init->init(db_init->name,NULL);
		 if(retval<0)
			return -EINVAL;
	    	 retval=LoadPolicy(db_init->name);
	    }
    }
		

    // init the connect proc	
    ret=sec_subject_create("connector_proc",PROC_TYPE_CONN,NULL,&conn_proc);
    if(ret<0)
	    return ret;

    sec_subject_setinitfunc(conn_proc,conn_proc_initdata.init);
    sec_subject_setstartfunc(conn_proc,conn_proc_initdata.start);

    sec_subject_init(conn_proc,NULL);

    add_sec_subject(conn_proc);

    // init the router proc	
    ret=sec_subject_create("router_proc",PROC_TYPE_MONITOR,NULL,&router_proc);
    if(ret<0)
	    return ret;

    sec_subject_setinitfunc(router_proc,router_proc_initdata.init);
    sec_subject_setstartfunc(router_proc,router_proc_initdata.start);

    sec_subject_init(router_proc,NULL);
	
    printf("prepare the router proc\n");
    ret=sec_subject_start(router_proc,NULL);
    if(ret<0)
	    return ret;
   // first loop: init all the subject
    for(i=0;proc_init_list[i].name!=NULL;i++)
    {
	  void * sub_proc;
       	  ret=sec_subject_create(proc_init_list[i].name,proc_init_list[i].type,NULL,&sub_proc);
   	  if(ret<0)
		    return ret;

    	  ret=add_sec_subject(sub_proc);
	  void * sub_proc1;
	  ret=find_sec_subject(proc_init_list[i].name,&sub_proc1);
	  if(ret<0)
		  return ret;
	  if(sub_proc1==NULL)
	  {
		  printf("create sub_proc %s failed!\n",proc_init_list[i].name);
		  return -EINVAL;
	  }
    	  sec_subject_setinitfunc(sub_proc,proc_init_list[i].init);
   	  sec_subject_setstartfunc(sub_proc,proc_init_list[i].start);
  	  sec_subject_init(sub_proc,NULL);

	  if(ret<0)
  		return ret;
    }	    

    usleep(time_val.tv_usec);
    printf("prepare the conn proc\n");
    ret=sec_subject_start(conn_proc,NULL);
    if(ret<0)
	    return ret;

    // second loop:  start all the monitor process
    for(i=0;proc_init_list[i].name!=NULL;i++)
    {
	  void * sub_proc;
	  ret=find_sec_subject(proc_init_list[i].name,&sub_proc);
	  if(ret<0)
		  return ret;
	  if(sub_proc==NULL)
	  {
		  printf("create sub_proc %s failed!\n",proc_init_list[i].name);
		  return -EINVAL;
	  }
	  if(sec_subject_gettype(sub_proc) == PROC_TYPE_MONITOR)
	  {
  		ret=sec_subject_start(sub_proc,NULL);
	  	if(ret<0)
  			return ret;
		printf("monitor sub_proc %s started successfully!\n",sec_subject_getname(sub_proc));
	 }
    }	    

 

    int thread_retval;
    ret=sec_subject_join(conn_proc,&thread_retval);
    printf("thread return value %d!\n",thread_retval);

    if(ret<0)
	return ret;
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    SetupSignalsForAgent();

    GenericAgentConfig *config = CheckOpts(argc, argv);
    enum generic_agent_config_common_policy_output_format format = config->agent_specific.common.policy_output_format;

    if (format == GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF ||
        format == GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON)
    {
        // Just parse and write content to output
        Policy *output_policy = ParserParseFile(AGENT_TYPE_COMMON, config->input_file,
                                                config->agent_specific.common.parser_warnings,
                                                config->agent_specific.common.parser_warnings_error);
        Writer *writer = FileWriter(stdout);
        if (format == GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF)
        {
            PolicyToString(output_policy, writer);
        }
        else
        {
            JsonElement *json_policy = PolicyToJson(output_policy);
            JsonWrite(writer, json_policy, 2);
            JsonDestroy(json_policy);
        }
        WriterClose(writer);
        PolicyDestroy(output_policy);
        return EXIT_SUCCESS;
    }

    EvalContext *ctx = EvalContextNew();
    GenericAgentConfigApply(ctx, config);

    GenericAgentDiscoverContext(ctx, config);
    Policy *policy = LoadPolicy(ctx, config);
    if (!policy)
    {
        Log(LOG_LEVEL_ERR, "Input files contain errors.");
        exit(EXIT_FAILURE);
    }

    GenericAgentPostLoadInit(ctx);

    if (NULL != config->tag_release_dir)
    {
        // write the validated file and the release ID
        bool tagged = GenericAgentTagReleaseDirectory(config, config->tag_release_dir, true, true);
        if (tagged)
        {
            Log(LOG_LEVEL_VERBOSE, "Release tagging done!");
        }
        else
        {
            Log(LOG_LEVEL_ERR, "The given directory could not be tagged, sorry.");
            exit(EXIT_FAILURE);
        }
    }

    switch (config->agent_specific.common.policy_output_format)
    {
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF_FULL:
    {
        Writer *writer = FileWriter(stdout);
        PolicyToString(policy, writer);
        WriterClose(writer);
    }
    break;

    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON_FULL:
    {
        Writer *writer = FileWriter(stdout);
        JsonElement *json_policy = PolicyToJson(policy);
        JsonWrite(writer, json_policy, 2);
        JsonDestroy(json_policy);
        WriterClose(writer);
    }
    break;

    // already handled, but avoids compiler warnings
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_CF:
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_JSON:
    case GENERIC_AGENT_CONFIG_COMMON_POLICY_OUTPUT_FORMAT_NONE:
        break;
    }

    if(config->agent_specific.common.show_classes)
    {
        ShowContextsFormatted(ctx);
    }

    if(config->agent_specific.common.show_variables)
    {
        ShowVariablesFormatted(ctx);
    }

    PolicyDestroy(policy);
    GenericAgentFinalize(ctx, config);
}