Esempio n. 1
0
int t_unref( struct sip_msg* p_msg  )
{
	enum kill_reason kr;

	if (T==T_UNDEFINED || T==T_NULL_CELL)
		return -1;
	if (p_msg->first_line.type==SIP_REQUEST){
		kr=get_kr();
		if (kr==0 
				||(p_msg->REQ_METHOD==METHOD_ACK && !(kr & REQ_RLSD))) {
			LOG(L_WARN, "WARNING: script writer didn't release transaction\n");
			t_release_transaction(T);
		}
	}
	UNREF( T );
	set_t(T_UNDEFINED);
	return 1;
}
/// Test routine called when an otherwise-unclaimed NetIO packet is received.
gboolean
gotnetpkt(Listener* l,		///<[in/out] Input GSource
	  FrameSet* fs,		///<[in/out] @ref FrameSet "FrameSet"s received
	  NetAddr* srcaddr	///<[in] Source address of this packet
	  )
{
	(void)l; (void)srcaddr;
	++wirepktcount;
	switch(fs->fstype) {
	case FRAMESETTYPE_HBDEAD:
		g_message("CMA Received dead host notification (type %d) over the 'wire'."
		,	  fs->fstype);
		break;
	case FRAMESETTYPE_SWDISCOVER:
		g_message("CMA Received switch discovery data (type %d) over the 'wire'."
		,	  fs->fstype);
		break;
	case FRAMESETTYPE_JSDISCOVERY:
		g_message("CMA Received JSON discovery data (type %d) over the 'wire'."
		,	  fs->fstype);
		check_JSON(fs);
		break;
	case FRAMESETTYPE_RSCOPREPLY:
		g_message("CMA Received resource operation data (type %d) over the 'wire'."
		,	  fs->fstype);
		check_JSON(fs);
		break;
	default:{
			char *	fsstr = fs->baseclass.toString(&fs->baseclass);
			g_message("CMA Received a FrameSet of type %d [%s] over the 'wire'."
			,	  fs->fstype, fsstr);
			FREE(fsstr); fsstr = NULL;
		}
	}
	
	l->transport->_netio->ackmessage(l->transport->_netio, srcaddr, fs);
	UNREF(fs);
	if (wirepktcount >= maxpkts) {
		g_message("QUITTING NOW - wirepktcount!");
		nano_initiate_shutdown();
		return FALSE;
	}
	return TRUE;
}
Esempio n. 3
0
inline static int w_t_lookup_cancel(struct sip_msg* msg, char* str, char* str2)
{
	struct cell *ret;
	if (msg->REQ_METHOD==METHOD_CANCEL) {
		ret = t_lookupOriginalT( msg );
		DBG("lookup_original: t_lookupOriginalT returned: %p\n", ret);
		if (ret != T_NULL_CELL) {
			/* The cell is reffed by t_lookupOriginalT, but T is not set.
			So we must unref it before returning. */
			UNREF(ret);
			set_t(T_UNDEFINED);
			return 1;
		}
		set_t(T_UNDEFINED);
	} else {
		LOG(L_WARN, "WARNING: script error t_lookup_cancel() called for non-CANCEL request\n");
	}
	return -1;
}
Esempio n. 4
0
/**
 * FILE_RmDir callback. Recursively destroys the directory contents
 */
STATIC Bool RmDirCB(Str dir, Str fname, void * ctx) 
{
    Bool ok = False;
    StrBuf64 path;
    UNREF(ctx);
    STRBUF_InitBufXXX(&path);
    if (STRBUF_Copy(&path.sb, dir) && 
        STRBUF_AppendChar(&path.sb, FILE_SEPARATOR_CHAR) &&
        STRBUF_Append(&path.sb, fname)) {
        ok = True;
        if (FILE_IsDir(path.sb.s)) {
            FILE_RmDir(path.sb.s, True);
        } else {
            FILE_Delete(path.sb.s);
        }
    }
    STRBUF_Destroy(&path.sb);
    return ok;
}
const StringId ServerIntangibleObjectTemplate::_SchematicAttribute::getName(bool versionOk, bool testData) const
{
#ifdef _DEBUG
StringId testDataValue = DefaultStringId;
#else
UNREF(testData);
#endif

	const ServerIntangibleObjectTemplate::_SchematicAttribute * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerIntangibleObjectTemplate::_SchematicAttribute *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getName(true);
#endif
	}

	if (!m_name.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter name in template %s", DataResource::getName()));
			return DefaultStringId;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter name has not been defined in template %s!", DataResource::getName()));
			return base->getName(versionOk);
		}
	}

	const StringId value = m_name.getValue();
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerIntangibleObjectTemplate::_SchematicAttribute::getName
ServerIntangibleObjectTemplate::IngredientType ServerIntangibleObjectTemplate::_Ingredient::getIngredientType(bool versionOk, bool testData) const
{
#ifdef _DEBUG
ServerIntangibleObjectTemplate::IngredientType testDataValue = static_cast<ServerIntangibleObjectTemplate::IngredientType>(0);
#else
UNREF(testData);
#endif

	const ServerIntangibleObjectTemplate::_Ingredient * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerIntangibleObjectTemplate::_Ingredient *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getIngredientType(true);
#endif
	}

	if (!m_ingredientType.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter ingredientType in template %s", DataResource::getName()));
			return static_cast<IngredientType>(0);
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter ingredientType has not been defined in template %s!", DataResource::getName()));
			return base->getIngredientType(versionOk);
		}
	}

	IngredientType value = static_cast<IngredientType>(m_ingredientType.getValue());
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerIntangibleObjectTemplate::_Ingredient::getIngredientType
const std::string & SharedShipObjectTemplate::getInteriorLayoutFileName(bool testData) const
{
#ifdef _DEBUG
std::string testDataValue = DefaultString;
#else
UNREF(testData);
#endif

	const SharedShipObjectTemplate * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const SharedShipObjectTemplate *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getInteriorLayoutFileName(true);
#endif
	}

	if (!m_interiorLayoutFileName.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter interiorLayoutFileName in template %s", DataResource::getName()));
			return DefaultString;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter interiorLayoutFileName has not been defined in template %s!", DataResource::getName()));
			return base->getInteriorLayoutFileName();
		}
	}

	const std::string & value = m_interiorLayoutFileName.getValue();
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// SharedShipObjectTemplate::getInteriorLayoutFileName
Esempio n. 8
0
File: tm.c Progetto: Deni90/opensips
inline static int t_check_trans(struct sip_msg* msg)
{
	struct cell *trans;

	if (msg->REQ_METHOD==METHOD_CANCEL) {
		/* parse needed hdrs*/
		if (check_transaction_quadruple(msg)==0) {
			LM_ERR("too few headers\n");
			return 0; /*drop request!*/
		}
		if (!msg->hash_index)
			msg->hash_index = tm_hash(msg->callid->body,get_cseq(msg)->number);
		/* performe lookup */
		trans = t_lookupOriginalT(  msg );
		return trans?1:-1;
	} else {
		trans = get_t();
		if (trans==NULL)
			return -1;
		if (trans!=T_UNDEFINED)
			return 1;
		switch ( t_lookup_request( msg , 0) ) {
			case 1:
				/* transaction found -> is it local ACK? */
				if (msg->REQ_METHOD==METHOD_ACK)
					return 1;
				/* .... else -> retransmission */
				trans = get_t();
				t_retransmit_reply(trans);
				UNREF(trans);
				set_t(0);
				return 0;
			case -2:
				/* e2e ACK found */
				return 1;
			default:
				/* notfound */
				return -1;
		}
	}
}
//@BEGIN TFD
const std::string & ServerManufactureSchematicObjectTemplate::getDraftSchematic(bool testData) const
{
#ifdef _DEBUG
std::string testDataValue = DefaultString;
#else
UNREF(testData);
#endif

	const ServerManufactureSchematicObjectTemplate * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerManufactureSchematicObjectTemplate *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getDraftSchematic(true);
#endif
	}

	if (!m_draftSchematic.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter draftSchematic in template %s", DataResource::getName()));
			return DefaultString;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter draftSchematic has not been defined in template %s!", DataResource::getName()));
			return base->getDraftSchematic();
		}
	}

	const std::string & value = m_draftSchematic.getValue();
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerManufactureSchematicObjectTemplate::getDraftSchematic
bool SharedShipObjectTemplate::getPlayerControlled(bool testData) const
{
#ifdef _DEBUG
bool testDataValue = false;
#else
UNREF(testData);
#endif

	const SharedShipObjectTemplate * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const SharedShipObjectTemplate *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getPlayerControlled(true);
#endif
	}

	if (!m_playerControlled.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter playerControlled in template %s", DataResource::getName()));
			return false;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter playerControlled has not been defined in template %s!", DataResource::getName()));
			return base->getPlayerControlled();
		}
	}

	bool value = m_playerControlled.getValue();
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// SharedShipObjectTemplate::getPlayerControlled
const std::string & ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand(bool versionOk, bool testData) const
{
#ifdef _DEBUG
std::string testDataValue = DefaultString;
#else
UNREF(testData);
#endif

	const ServerIntangibleObjectTemplate::_Ingredient * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerIntangibleObjectTemplate::_Ingredient *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getSkillCommand(true);
#endif
	}

	if (!m_skillCommand.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter skillCommand in template %s", DataResource::getName()));
			return DefaultString;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter skillCommand has not been defined in template %s!", DataResource::getName()));
			return base->getSkillCommand(versionOk);
		}
	}

	const std::string & value = m_skillCommand.getValue();
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerIntangibleObjectTemplate::_Ingredient::getSkillCommand
/**
 * Writes the ending of a class header file.
 *
 * @param fp				the file to write to
 * @param sourceTemplate	the template we are writing code for
 */
void TemplateDefinitionFile::writeClassHeaderEnd(File &fp, const TemplateData & sourceTemplate) const
{
	UNREF(sourceTemplate);

	const char *name = getTemplateName().c_str();

	fp.print("\n");
	fp.print("private:\n");
	fp.print("\tTag  m_templateVersion;\t// the template version\n");
	fp.print("\tbool m_versionOk;\t// flag that the template version loaded is "
		"the one we expect\n");
	if (!m_writeForCompilerFlag)
		fp.print("\tstatic bool ms_allowDefaultTemplateParams;\t// flag to allow defaut params instead of fataling\n");
	fp.print("\n");
	fp.print("\tstatic void registerMe(void);\n");
	fp.print("\tstatic ObjectTemplate * create(const std::string & filename);\n");
	fp.print("\n");
	fp.print("\t// no copying\n");
	fp.print("\t%s(const %s &);\n", name, name);
	fp.print("\t%s & operator =(const %s &);\n", name, name);
	fp.print("};\n");
	fp.print("\n");
	fp.print("\n");
	if (m_writeForCompilerFlag)
	{
		fp.print("inline void %s::install(void)\n", name);
		fp.print("{\n");
	}
	else
	{
		fp.print("inline void %s::install(bool allowDefaultTemplateParams)\n", name);
		fp.print("{\n");
		fp.print("\tms_allowDefaultTemplateParams = allowDefaultTemplateParams;\n");
	}
	sourceTemplate.writeRegisterTemplate(fp, "\t");
	fp.print("}\n");
	fp.print("\n");
	fp.print("\n");
	fp.print("#endif\t// _INCLUDED_%s_H\n", name);
}	// TemplateDefinitionFile::writeClassHeaderEnd
	void loadDataTables()
	{
		FILE* fp = fopen("datatables.plf","r");
		char buf [256];
		if (fp)
		{
			DEBUG_REPORT_LOG(true, ("Scanning tables"));
			char* line = fgets(buf, 256, fp);
			while (line)
			{
				
				//strip newline
				int len = strlen(line);
				for (int i = len - 1; i > 0; --i)
				{
					if (buf[i] == '\n')
					{
						buf[i] = 0;
						break;
					}
				}
				
				char* tmp = strstr(buf, "datatables/");
				if (tmp)
					line = tmp;

				DataTable* dt =  DataTableManager::getTable(line, true);
#if 0
				if (dt)
					ms_dataTableList.push_back(dt);
#else
				UNREF(dt);
#endif
				DEBUG_REPORT_LOG(true, ("."));
				line = fgets(buf, 256, fp);
			}
			fclose(fp);
			DEBUG_REPORT_LOG(true, ("\n"));
		}
	}
Esempio n. 14
0
gboolean
workspace_load_compat( Workspace *ws, int major, int minor )
{
	char pathname[FILENAME_MAX];
	GSList *path;
	int best_major;
	int best_minor;

	if( workspace_have_compat( major, minor, &best_major, &best_minor ) ) {
		/* Make a private toolkitgroup local to this workspace to 
		 * hold the compatibility defs we are planning to load.
		 */
		UNREF( ws->kitg );
		ws->kitg = toolkitgroup_new( ws->sym );
		g_object_ref( G_OBJECT( ws->kitg ) );
		iobject_sink( IOBJECT( ws->kitg ) );

		im_snprintf( pathname, FILENAME_MAX, 
			"$VIPSHOME/share/" PACKAGE "/compat/%d.%d", 
			best_major, best_minor );
		path = path_parse( pathname );
		if( path_map( path, "*.def", 
			(path_map_fn) workspace_load_toolkit, ws->kitg ) ) {
			path_free2( path );
			return( FALSE );
		}
		path_free2( path );

		ws->compat_major = best_major;
		ws->compat_minor = best_minor;
	}
	else {
		/* No compat defs necessary for this ws. 
		 */
		ws->compat_major = 0;
		ws->compat_minor = 0;
	}

	return( TRUE );
}
Esempio n. 15
0
/* fifo command to cancel a pending call (Uli)
 * Syntax:
 *
 * ":uac_cancel:[response file]\n
 * callid\n
 * cseq\n
 */
void rpc_cancel(rpc_t* rpc, void* c)
{
	struct cell *trans;
	static char cseq[128], callid[128];
	struct cancel_info cancel_data;
	int i,j;

	str cseq_s;   /* cseq */
	str callid_s; /* callid */

	cseq_s.s=cseq;
	callid_s.s=callid;
	init_cancel_info(&cancel_data);

	if (rpc->scan(c, "SS", &callid_s, &cseq_s) < 2) {
		rpc->fault(c, 400, "Callid and CSeq expected as parameters");
		return;
	}

	if( t_lookup_callid(&trans, callid_s, cseq_s) < 0 ) {
		DBG("Lookup failed\n");
		rpc->fault(c, 400, "Transaction not found");
		return;
	}
	/*  find the branches that need cancel-ing */
	prepare_to_cancel(trans, &cancel_data.cancel_bitmap, 0);
	 /* tell tm to cancel the call */
	DBG("Now calling cancel_uacs\n");
	i=cancel_uacs(trans, &cancel_data, 0); /* don't fake 487s, 
										 just wait for timeout */
	
	/* t_lookup_callid REF`d the transaction for us, we must UNREF here! */
	UNREF(trans);
	j=0;
	while(i){
		j++;
		i&=i-1;
	}
	rpc->add(c, "ds", j, "branches remaining (waiting for timeout)");
}
void JNICALL ScriptMethodsChatNamespace::chatSendSystemMessage(JNIEnv * env, jobject self, jstring _to, jstring _message, jstring _oob)
{
	UNREF(self);

	if (!_to)
		return;

	Unicode::String to;
	{
		const JavaStringParam jt(_to);
		if(!JavaLibrary::convert(jt, to))
			return;
	}

	Unicode::String message;

	if (_message)
	{
		const JavaStringParam jt(_message);
		if (!JavaLibrary::convert(jt, message))
			return;
	}

	Unicode::String oob;

	if (_oob)
	{
		const JavaStringParam jt(_oob);
		if (!JavaLibrary::convert(jt, oob))
			return;
	}

	if (message.empty () && oob.empty ())
	{
		DEBUG_WARNING (true, ("chatSendSystemMessage with empty message _and_ oob"));
	}

	Chat::sendSystemMessage(Unicode::wideToNarrow (to), message, oob);
}
Esempio n. 17
0
/**
 * "End element" callback for XML_Handle. If this tag has been "skipped" by
 * XML_StartElemCB, simply decrements skipDepth. Otherwise, calls the client
 * callback to deallocate the tag context.
 */
STATIC void XML_HandleEndElem(void * ctx, Str tag)
{
    XMLContext * context = (XMLContext*)ctx;
    UNREF(tag);
    if (context->error && context->skipDepth > 0) {
        context->skipDepth--;
    } else {    
        int depth = VECTOR_Size(&context->stack);
        ASSERT(depth > 0);
        if (depth == 1 && !context->error) {
            XMLTagCtx * root;
            root = (XMLTagCtx*)VECTOR_Get(&context->stack,0);
            ASSERT(root && root->context == context);
            ASSERT(!context->rootTag);

            /* prevent XML_VectorFreeTagContext from deallocating the tag */
            context->rootTag = root->tag;
            root->tag = NULL;
        }
        if (depth > 0) {
            VECTOR_Remove(&context->stack, depth-1);
        }
    }
}
/**
 * Saves the template data to an iff file.
 *
 * @param file			file to save to
 * @param location		file type (client or server)
 */
void ServerStaticObjectTemplate::save(Iff &file)
{
int count;

	file.insertForm(ServerStaticObjectTemplate_tag);
	if (m_baseTemplateName.size() != 0)
	{
		file.insertForm(TAG(D,E,R,V));
		file.insertChunk(TAG(X, X, X, X));
		file.insertChunkData(m_baseTemplateName.c_str(), m_baseTemplateName.size() + 1);
		file.exitChunk();
		file.exitForm();
	}
	file.insertForm(TAG(0,0,0,1));
	file.allowNonlinearFunctions();

	int paramCount = 0;

	// save clientOnlyBuildout
	file.insertChunk(TAG(X, X, X, X));
	file.insertChunkString("clientOnlyBuildout");
	m_clientOnlyBuildout.saveToIff(file);
	file.exitChunk();
	++paramCount;

	// write number of parameters
	file.goToTopOfForm();
	file.insertChunk(TAG(P, C, N, T));
	file.insertChunkData(&paramCount, sizeof(paramCount));
	file.exitChunk();

	file.exitForm(true);
	ServerObjectTemplate::save(file);
	file.exitForm();
	UNREF(count);
}	// ServerStaticObjectTemplate::save
Esempio n. 19
0
/// Finalizing function for Discovery objects
FSTATIC void
_discovery_finalize(AssimObj* gself)	///<[in/out] Object to finalize (free)
{
	Discovery*	self = CASTTOCLASS(Discovery, gself);
	char *		instancename = self->_instancename;
	
	if (self->_timerid > 0) {
		g_source_remove(self->_timerid);
		self->_timerid = 0;
	}
	if (self->_config) {
		UNREF(self->_config);
	}
	if (_discovery_timers && instancename) {
		self->_instancename = NULL;	// Avoid infinite recursion...
		g_hash_table_remove(_discovery_timers, instancename);
	}
	if (instancename) {
		g_free(instancename);
		self->_instancename = instancename = NULL;
	}
	
	FREECLASSOBJ(self); self=NULL;
}
/**
 * Loads the template data from an iff file. We should already be in the form
 * for this template.
 *
 * @param file		file to load from
 */
void ServerManufactureSchematicObjectTemplate::_IngredientSlot::load(Iff &file)
{
static const int MAX_NAME_SIZE = 256;
char paramName[MAX_NAME_SIZE];

	file.enterForm();

	file.enterChunk();
	int paramCount = file.read_int32();
	file.exitChunk();
	for (int i = 0; i < paramCount; ++i)
	{
		file.enterChunk();
		file.read_string(paramName, MAX_NAME_SIZE);
		if (strcmp(paramName, "name") == 0)
			m_name.loadFromIff(file);
		else if (strcmp(paramName, "ingredient") == 0)
			m_ingredient.loadFromIff(file);
		file.exitChunk(true);
	}

	file.exitForm();
	UNREF(file);
}	// ServerManufactureSchematicObjectTemplate::_IngredientSlot::load
Esempio n. 21
0
/// Append a ResourceQuee
FSTATIC gboolean
_resource_queue_Qcmd(ResourceQueue* self
,	ConfigContext* request
,	ResourceCmdCallback callback
,	gpointer user_data)
{
	ResourceCmd*	cmd;
	gboolean	ret;

	// Will replace NULL with our qelem object
	cmd = resourcecmd_new(request, NULL, _resource_queue_endnotify);

	if (cmd == NULL) {
		if (callback) {
			callback(request, user_data, EXITED_INVAL
			,	0, 0, FALSE, "Invalid Arguments");
		}
		return FALSE;
	}

	ret = _resource_queue_cmd_append(self, cmd, callback, user_data);
	UNREF(cmd);
	return ret;
}
/**
 * Loads the template data from an iff file. We should already be in the form
 * for this template.
 *
 * @param file		file to load from
 */
void ServerIntangibleObjectTemplate::_SchematicAttribute::load(Iff &file)
{
static const int MAX_NAME_SIZE = 256;
char paramName[MAX_NAME_SIZE];

	file.enterForm();

	file.enterChunk();
	int paramCount = file.read_int32();
	file.exitChunk();
	for (int i = 0; i < paramCount; ++i)
	{
		file.enterChunk();
		file.read_string(paramName, MAX_NAME_SIZE);
		if (strcmp(paramName, "name") == 0)
			m_name.loadFromIff(file);
		else if (strcmp(paramName, "value") == 0)
			m_value.loadFromIff(file);
		file.exitChunk(true);
	}

	file.exitForm();
	UNREF(file);
}	// ServerIntangibleObjectTemplate::_SchematicAttribute::load
float ServerIntangibleObjectTemplate::_Ingredient::getComplexityMax(bool versionOk, bool testData) const
{
#ifdef _DEBUG
float testDataValue = 0.0f;
#else
UNREF(testData);
#endif

	const ServerIntangibleObjectTemplate::_Ingredient * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerIntangibleObjectTemplate::_Ingredient *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getComplexityMax(true);
#endif
	}

	if (!m_complexity.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter complexity in template %s", DataResource::getName()));
			return 0.0f;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter complexity has not been defined in template %s!", DataResource::getName()));
			return base->getComplexityMax(versionOk);
		}
	}

	float value = m_complexity.getMaxValue();
	char delta = m_complexity.getDeltaType();
	if (delta == '+' || delta == '-' || delta == '_' || delta == '=')
	{
		float baseValue = 0;
		if (m_baseData != NULL)
		{
			if (base != NULL)
				baseValue = base->getComplexityMax(versionOk);
			else if (ms_allowDefaultTemplateParams)
				DEBUG_WARNING(true, ("No base template for delta, using 0"));
			else
				NOT_NULL(base);
		}
		if (delta == '+')
			value = baseValue + value;
		else if (delta == '-')
			value = baseValue - value;
		else if (delta == '=')
			value = baseValue + static_cast<float>(baseValue * (value / 100.0f));
		else if (delta == '_')
			value = baseValue - static_cast<float>(baseValue * (value / 100.0f));
	}
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerIntangibleObjectTemplate::_Ingredient::getComplexityMax
Esempio n. 24
0
/**
 * @ref ChildProcess constructor.
 * Here's what we're going to do:
 * 1) Create child process using g_spawn_async_with_pipes()
 * 2) ...In child process become our own process group
 * 3) Create LogSourceFd object for stderr
 * 4) Create LogSourceFd or GMainFd object for stdout
 * 5) Set timer (if any)
 * 6) Initialize the child state to running
 * 7) Return.
 */
WINEXPORT ChildProcess*
childprocess_new(gsize cpsize		///< Size of created ChildProcess object
,		char** argv		///< NULL-terminated argv for the ChildProcess
,		const char** envp	///< Environment for the ChildProcess
,		ConfigContext* envmod	///< Modifications to the ChildProcess environment
,		const char* curdir	///< Current directory to start the child in
,		void (*notify)(ChildProcess*, enum HowDied, int rc, int signal, gboolean core_dumped)
					///< Function to call if/when the child terminates
,		gboolean save_stdout	///< TRUE to save stdout, FALSE to log it
,		const char*logdomain	///< Glib log domain
,		const char*logprefix	///< Prefix to prepend to log entries
,		GLogLevelFlags loglevel	///< Glib Log level
,		guint32 timeout_seconds	///< How long to wait before killing it - zero for no timeout
,		gpointer user_data	///< Data our user wants us to keep
,		enum ChildErrLogMode logmode ///< How to log child exits
,		const char* logname)	///< Name to use when logging child exits as requested
{
	AssimObj*	aself;
	ChildProcess*	self;
	gint		stdoutfd;
	gint		stderrfd;
	GError*		failcode = NULL;
	gchar**		childenv = NULL;

	BINDDEBUG(ChildProcess);
	g_return_val_if_fail(logprefix != NULL, NULL);
	if (cpsize < sizeof(ChildProcess)) {
		cpsize = sizeof(ChildProcess);
	}
	aself = assimobj_new(cpsize);
	g_return_val_if_fail(aself != NULL, NULL);
	self = NEWSUBCLASS(ChildProcess, aself);
	childenv = assim_merge_environ(envp, envmod);
	if (!g_spawn_async_with_pipes(
		curdir,				// Current directory
		argv,				// Arguments
		childenv,			// environment
		G_SPAWN_DO_NOT_REAP_CHILD,	// GSpawnFlags flags,
		_childprocess_setup_child,	// GSpawnChildSetupFunc child_setup,
		self,				// gpointer user_data,
		&self->child_pid,		// GPid *child_pid,
		NULL,				// gint *standard_input,
		&stdoutfd,			// gint *standard_output,
		&stderrfd,			// gint *standard_error,
		&failcode)) {			// GError **error

		// OOPS!  Failed!
		const char *	msg = "unknown exec error";
		if (failcode && failcode->message) {
			msg = failcode->message;
		}
		g_critical("%s.%d: %s", __FUNCTION__, __LINE__, msg);
		if (failcode) {
			g_clear_error(&failcode);	// sets failcode back to NULL
		}
		assim_free_environ(childenv); childenv = NULL;
		UNREF(self);
		aself = NULL;
		return NULL;
	}
	DEBUGMSG2("%s.%d: Spawned process with user_data = %p", __FUNCTION__, __LINE__, self);

	aself->_finalize = _childprocess_finalize;
	aself->toString = _childprocess_toString;
	self->stderr_src = logsourcefd_new(0, stderrfd, G_PRIORITY_HIGH, g_main_context_default()
	,		                   logdomain, loglevel, logprefix);
	self->user_data = user_data;
	self->logmode = logmode;
	if (NULL == logname) {
		logname = argv[0];
	}
	self->loggingname = g_strdup(logname);
	assim_free_environ(childenv);
	childenv = NULL;

	if (!save_stdout) {
		LogSourceFd*	logsrc;
		logsrc = logsourcefd_new(0, stdoutfd, G_PRIORITY_HIGH
		,		g_main_context_default(), logdomain, loglevel, logprefix);
		self->stdout_src = &logsrc->baseclass;
	}else{
		self->stdout_src = gmainfd_new(0, stdoutfd, G_PRIORITY_HIGH, g_main_context_default());
	}
	self->childsrc_id = g_child_watch_add(self->child_pid, _childprocess_childexit, self);

	self->notify = notify;

	if (0 == timeout_seconds) {
		DEBUGMSG2("No timeout for process with user_data = %p", self);
		self->timeoutsrc_id = 0;
	}else{
		self->timeoutsrc_id = g_timeout_add_seconds(timeout_seconds
		,			                   _childprocess_timeout, self);
		DEBUGMSG3("%s.%d: Set %d second timeout %d for process with user_data = %p"
		,	__FUNCTION__, __LINE__, timeout_seconds, self->timeoutsrc_id, self);
	}
	self->child_state = CHILDSTATE_RUNNING;
	DEBUGMSG5("%s.%d: REF child: %p", __FUNCTION__,__LINE__, self);
	REF(self);	// We do this because we need to still be here when the process exits
	return self;
}
int ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMin(bool versionOk, bool testData) const
{
#ifdef _DEBUG
int testDataValue = 0;
#else
UNREF(testData);
#endif

	const ServerIntangibleObjectTemplate::_SchematicAttribute * base = NULL;
	if (m_baseData != NULL)
	{
		base = dynamic_cast<const ServerIntangibleObjectTemplate::_SchematicAttribute *>(m_baseData);
#ifdef _DEBUG
		if (testData && base != NULL)
			testDataValue = base->getValueMin(true);
#endif
	}

	if (!m_value.isLoaded())
	{
		if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL)
		{
			DEBUG_WARNING(true, ("Returning default value for missing parameter value in template %s", DataResource::getName()));
			return 0;
		}
		else
		{
			DEBUG_FATAL(base == NULL, ("Template parameter value has not been defined in template %s!", DataResource::getName()));
			return base->getValueMin(versionOk);
		}
	}

	int value = m_value.getMinValue();
	char delta = m_value.getDeltaType();
	if (delta == '+' || delta == '-' || delta == '_' || delta == '=')
	{
		int baseValue = 0;
		if (m_baseData != NULL)
		{
			if (base != NULL)
				baseValue = base->getValueMin(versionOk);
			else if (ms_allowDefaultTemplateParams)
				DEBUG_WARNING(true, ("No base template for delta, using 0"));
			else
				NOT_NULL(base);
		}
		if (delta == '+')
			value = baseValue + value;
		else if (delta == '-')
			value = baseValue - value;
		else if (delta == '=')
			value = baseValue + static_cast<int>(baseValue * (value / 100.0f));
		else if (delta == '_')
			value = baseValue - static_cast<int>(baseValue * (value / 100.0f));
	}
#ifdef _DEBUG
	if (testData && base != NULL)
	{
	}
#endif

	return value;
}	// ServerIntangibleObjectTemplate::_SchematicAttribute::getValueMin
Esempio n. 26
0
void unref_cell(struct cell *t)
{
	UNREF(t);
}
Esempio n. 27
0
/// Function called when the child (finally) exits...
FSTATIC void
_childprocess_childexit(GPid pid, gint status, gpointer childprocess_object)
{
	ChildProcess*	self = CASTTOCLASS(ChildProcess, childprocess_object);
	gboolean	signalled = WIFSIGNALED(status);
	int		exitrc = 0;
	int		signal = 0;
	gboolean	logexit = FALSE;
	enum HowDied	howwedied = NOT_EXITED;
	(void)pid;

	if (self->timeoutsrc_id > 0)  {
		g_source_remove(self->timeoutsrc_id);
		DEBUGMSG3("%s.%d: Removed timeout %d for process with user_data = %p"
		,	__FUNCTION__, __LINE__, self->timeoutsrc_id, self);
		self->timeoutsrc_id = 0;
	}
	// If it refused to die, then the status is invalid
	if ((guint)(self->child_state) >= DIMOF(signalmap)) {
		howwedied = EXITED_HUNG;
	}else if ((guint)self->child_state != CHILDSTATE_RUNNING) {
 		// Then we tried to kill it...
		howwedied = EXITED_TIMEOUT;
		signal = signalled ? WTERMSIG(status) : 0;
	}else{
		if (signalled) {
			signal = WTERMSIG(status);
			howwedied = EXITED_SIGNAL;
		}else{
			exitrc = WEXITSTATUS(status);
			howwedied = (exitrc == 0 ? EXITED_ZERO : EXITED_NONZERO);
		}
	}
	switch (howwedied) {
		case EXITED_SIGNAL:	/*FALLTHROUGH*/
		case EXITED_TIMEOUT:	/*FALLTHROUGH*/
		case EXITED_HUNG:
			logexit = self->logmode  > CHILD_NOLOG;
			break;
		case EXITED_NONZERO:
			logexit = self->logmode  >= CHILD_LOGERRS;
			break;
		case EXITED_ZERO:
			logexit = self->logmode  >= CHILD_LOGALL;
			break;
		default:
			// We'll never produce any other values above
			/*NOTREACHED*/
			logexit = TRUE;
			break;
	}
	if (logexit) {
		switch (howwedied) {
		case EXITED_SIGNAL:
			g_warning("Child process [%s] died from signal %d%s."
			,	self->loggingname, signal, WCOREDUMP(status) ? " (core dumped)" : "");
			break;
		case EXITED_TIMEOUT:
			if (signalled) {
				g_warning("Child process [%s] timed out after %d seconds [signal %d%s]."
				,	self->loggingname, self->timeout, signal
				,	WCOREDUMP(status) ? " (core dumped)" : "");
			}else{
				g_warning("Child process [%s] timed out after %d seconds."
				,	self->loggingname, self->timeout);
			}
			break;
		case EXITED_HUNG:
			g_warning("Child process [%s] timed out after %d seconds and could not be killed."
			,	self->loggingname, self->timeout);
			break;
		case EXITED_NONZERO:
			g_message("Child process [%s] exited with return code %d."
			,	self->loggingname, exitrc);
			break;
		case EXITED_ZERO:
			g_message("Child process [%s] exited normally.", self->loggingname);
			break;
		default:/*NOTREACHED*/
			break;
		}
	}

	DEBUGMSG2("%s.%d: Exit happened howwedied:%d", __FUNCTION__, __LINE__
	,	howwedied);
	if (!self->stdout_src->atEOF) {
		//DEBUGMSG3("Child %d [%s] EXITED but output is not at EOF [fd%d]", pid
		//,	self->loggingname, self->stdout_src->gfd.fd);
		self->stdout_src->readmore(self->stdout_src);
	}
	if (!self->stderr_src->baseclass.atEOF) {
		self->stderr_src->baseclass.readmore(&self->stderr_src->baseclass);
	}
	self->notify(self, howwedied, exitrc, signal, WCOREDUMP(status));
	self->child_state = -1;
	DEBUGMSG5("%s.%d: UNREF child: %p", __FUNCTION__,__LINE__, self);
	UNREF(self);	// Undo the REF(self) in our constructor
}
Esempio n. 28
0
File: t_fwd.c Progetto: OPSF/uClinux
/* function returns:
 *       1 - forward successful
 *      -1 - error during forward
 */
int t_forward_nonack( struct cell *t, struct sip_msg* p_msg ,
                      struct proxy_l * proxy, int proto)
{
    str          backup_uri;
    int branch_ret, lowest_ret;
    str current_uri;
    branch_bm_t	added_branches;
    int first_branch;
    int i, q;
    struct cell *t_invite;
    int success_branch;
    int try_new;
    str dst_uri;

    /* make -Wall happy */
    current_uri.s=0;

    set_kr(REQ_FWDED);

    if (p_msg->REQ_METHOD==METHOD_CANCEL) {
        t_invite=t_lookupOriginalT(  p_msg );
        if (t_invite!=T_NULL_CELL) {
            e2e_cancel( p_msg, t, t_invite );
            UNREF(t_invite);
            return 1;
        }
    }

    /* backup current uri ... add_uac changes it */
    backup_uri = p_msg->new_uri;
    /* if no more specific error code is known, use this */
    lowest_ret=E_BUG;
    /* branches added */
    added_branches=0;
    /* branch to begin with */
    first_branch=t->nr_of_outgoings;

    /* on first-time forwarding, use current uri, later only what
       is in additional branches (which may be continuously refilled
    */
    if (first_branch==0) {
        try_new=1;
        branch_ret=add_uac( t, p_msg, GET_RURI(p_msg), GET_NEXT_HOP(p_msg), proxy, proto );
        if (branch_ret>=0)
            added_branches |= 1<<branch_ret;
        else
            lowest_ret=branch_ret;
    } else try_new=0;

    init_branch_iterator();
    while((current_uri.s=next_branch( &current_uri.len, &q, &dst_uri.s, &dst_uri.len))) {
        try_new++;
        branch_ret=add_uac( t, p_msg, &current_uri,
                            (dst_uri.len) ? (&dst_uri) : &current_uri,
                            proxy, proto);
        /* pick some of the errors in case things go wrong;
           note that picking lowest error is just as good as
           any other algorithm which picks any other negative
           branch result */
        if (branch_ret>=0)
            added_branches |= 1<<branch_ret;
        else
            lowest_ret=branch_ret;
    }
    /* consume processed branches */
    clear_branches();

    /* restore original URI */
    p_msg->new_uri=backup_uri;

    /* don't forget to clear all branches processed so far */

    /* things went wrong ... no new branch has been fwd-ed at all */
    if (added_branches==0) {
        if (try_new==0) {
            LOG(L_ERR, "ERROR: t_forward_nonack: no branched for forwarding\n");
            return -1;
        }
        LOG(L_ERR, "ERROR: t_forward_nonack: failure to add branches\n");
        return lowest_ret;
    }

    /* send them out now */
    success_branch=0;
    for (i=first_branch; i<t->nr_of_outgoings; i++) {
        if (added_branches & (1<<i)) {
            if (SEND_BUFFER( &t->uac[i].request)==-1) {
                LOG(L_ERR, "ERROR: t_forward_nonack: sending request failed\n");
                if (proxy) {
                    proxy->errors++;
                    proxy->ok=0;
                }
            } else {
                success_branch++;
            }
            start_retr( &t->uac[i].request );
        }
    }
    if (success_branch<=0) {
        ser_error=E_SEND;
        return -1;
    }
    return 1;
}
/// Constructs a GSList list of @ref FrameSet objects from a datagram/packet.
/// That is, it decodes the datagram/packet.
/// @return GSList of @ref FrameSet object pointers.
GSList*
_pktdata_to_framesetlist(PacketDecoder*self,		///<[in] PacketDecoder object
			 gpointer pktstart,		///<[in] start of packet
			 gconstpointer pktend)		///<[in] first byte past end of packet
{
	guint8*		curframeset = pktstart;
	GSList*		ret = NULL;

	// Loop over all the FrameSets in the packet we were given.
	while (curframeset < (guint8*)pktend) {
		gpointer	nextframeset = NULL;
		gpointer	framestart = ((guint8*)curframeset + FRAMESET_INITSIZE);
		gpointer	curframe;
		FrameSet*	fs;
		gconstpointer	fsend = pktend;
		gpointer	newframestart = NULL;
		gboolean	firstframe = TRUE;
		guint32		framesetlen;

		// Check the overall frame size
		framesetlen = get_generic_tlv_len(curframeset, pktend);
		if (framesetlen > (guint32)((guint8*)pktend-(curframeset+FRAMESET_INITSIZE))) {
			g_warning("%s.%d: Received frameset length [%d] is invalid - cannot exceed %d"
			,	__FUNCTION__, __LINE__, framesetlen
			,	(int)((guint8*)pktend-(curframeset+FRAMESET_INITSIZE)));
			goto errout;
		}
		fsend = curframeset+framesetlen+FRAMESET_INITSIZE;
		fs = _decode_packet_get_frameset_data(curframeset, curframeset+framesetlen, &nextframeset);
		g_return_val_if_fail(fs != NULL,  ret);
		if (!is_valid_generic_tlv_packet(framestart, pktend)) {
			g_warning("%s.%d:  Frameset type %d not a valid TLV frameset"
			,	__FUNCTION__, __LINE__, fs->fstype);
			UNREF(fs);
			goto errout;
		}

		// Construct this FrameSet from the series of frames encoded in the packet.
		// Note that two special kinds of frames can alter the packet we're examining.
		// This is explained in more detail inside the loop.
		curframe = framestart;
		while (curframe != NULL && curframe < fsend) {
			Frame*		newframe;
			gpointer	newpacket = NULL;
			// The first special case frame is the compression frame, in which case the
			// remaining packet is replaced by a new, larger (decompressed) packet.
			//
			// The second type is the encryption packet, in which case the remaining
			// packet is replaced by a new chunk of data which will have different
			// (decrypted) content, and would normally be expected to be the same size
			// as the original.
			//
			// This means that "decode_packet_framedata_to_frameobject" might replace the
			// packet data we've been looking at.
			// (FWIW: It's perfectly OK to have an encryption frame followed by a
			// (embedded) compression frame -- both kinds can occur in the same FrameSet).
			newframe = _decode_packet_framedata_to_frameobject(self, &curframe, &fsend, &newpacket);
			if (newpacket) {
				if (newframestart != NULL) {
					// We did packet replacement more than once...
					g_free(newframestart);
				}
				newframestart = newpacket;
			}
			if (NULL == newframe) {
				UNREF(fs);
				goto errout;
			}
			if (TRUE == firstframe) {
				if (!OBJ_IS_A(newframe, "SignFrame")) {
					UNREF(newframe);
					UNREF(fs);
					g_warning("%s.%d: First frame NOT a signature frame - [%d] instead"
					,	__FUNCTION__, __LINE__, newframe->type);
					goto errout;
				}
				firstframe = FALSE;
			}
			frameset_append_frame(fs, newframe);
			UNREF(newframe);
		}
		if (curframe != fsend) {
			g_warning("%s.%d:  Received %d frameset - length is off by"
			": %d instead"
			,	__FUNCTION__, __LINE__, fs->fstype
			,	(int)((guint8*)fsend-((guint8*)curframe)));
			goto errout;
		}
		if (newframestart) {
			g_free(newframestart); newframestart = NULL;
		}
		if (fs) {
			ret = g_slist_append(ret, fs); fs = NULL;
		}
		curframeset = nextframeset;
	}
	return ret;
errout:
	g_slist_free_full(ret, assim_g_notify_unref); ret = NULL;
	return ret;
}
LogObserver *DatabaseLogObserver::create(std::string const &spec)
{
	UNREF(spec);
	return new DatabaseLogObserver();
}