Beispiel #1
0
static void
check(uint8_t *buf, int size, long check_long, int check_ret) {
	char scratch[128];
	char verify[32];
	INTEGER_t val;
	uint8_t *buf_end = buf + size;
	int ret;
	long rlong = 123;

	assert(buf);
	assert(size >= 0);

	val.buf = buf;
	val.size = size;

	printf("Testing: [");
	for(; buf < buf_end; buf++) {
		if(buf != val.buf) printf(":");
		printf("%02x", *buf);
	}
	printf("]: ");

	ret = asn_INTEGER2long(&val, &rlong);
	printf(" (%ld, %d) vs (%ld, %d)\n",
		rlong, ret, check_long, check_ret);
	assert(ret == check_ret);
	printf("%ld %ld\n", rlong, check_long);
	assert(rlong == check_long);

	if(check_ret == 0) {
		INTEGER_t val2;
		long rlong2;
		val2.buf = 0;
		val2.size = 0;
		ret = asn_long2INTEGER(&val2, rlong);
		assert(ret == 0);
		assert(val2.buf);
		assert(val2.size <= val.size);	/* At least as compact */
		ret = asn_INTEGER2long(&val, &rlong2);
		assert(ret == 0);
		assert(rlong == rlong2);
	}

	shared_scratch_start = scratch;
	ret = INTEGER_print(&asn_DEF_INTEGER, &val, 0, _print2buf, scratch);
	assert(shared_scratch_start < scratch + sizeof(scratch));
	assert(ret == 0);
	ret = snprintf(verify, sizeof(verify), "%ld", check_long);
	assert(ret < sizeof(verify));
	ret = strcmp(scratch, verify);
	printf("         [%s] vs [%s]: %d%s\n",
		scratch, verify, ret,
		(check_ret == -1)?" (expected to fail)":""
		);
	if(check_ret == -1) {
		assert(strcmp(scratch, verify));
	} else {
		assert(strcmp(scratch, verify) == 0);
	}
}
Beispiel #2
0
long _PR2_BMDDatagram2bmdDatagram(	BMDDatagram_t *asn1_dtg,
						bmdDatagram_t **dtg)
{
	/************************/
	/* walidacja parametrow */
	/************************/
	if (asn1_dtg==NULL)		{	BMD_FOK(BMD_ERR_PARAM1);	}
	if (dtg==NULL)			{	BMD_FOK(BMD_ERR_PARAM2);	}
	if ((*dtg)!=NULL)			{	BMD_FOK(BMD_ERR_PARAM2);	}

	(*dtg)=(bmdDatagram_t *)malloc(sizeof(bmdDatagram_t));
	if(*dtg == NULL)	 {	BMD_FOK(NO_MEMORY);	}
	memset(*dtg,0,sizeof(bmdDatagram_t));

	/* wartosci INTEGER */
	BMD_FOK(asn_INTEGER2long(&(asn1_dtg->protocolVersion), &((*dtg)->protocolVersion)));
	BMD_FOK(asn_INTEGER2long(&(asn1_dtg->datagramType), &((*dtg)->datagramType)));
	BMD_FOK(asn_INTEGER2long(&(asn1_dtg->randId), &((*dtg)->randId)));
	BMD_FOK(asn_INTEGER2long(&(asn1_dtg->filesRemaining), &((*dtg)->filesRemaining)));
	BMD_FOK(asn_INTEGER2long(&(asn1_dtg->datagramStatus), &((*dtg)->datagramStatus)));

	/* wartosci OCTET_STRING */
	if(asn1_dtg->protocolData)
	{
		BMD_FOK(set_gen_buf2((char *)(asn1_dtg->protocolData->buf), asn1_dtg->protocolData->size, &((*dtg)->protocolData)));
	}
	if(asn1_dtg->protocolDataFilename)
	{
		BMD_FOK(set_gen_buf2((char *)(asn1_dtg->protocolDataFilename->buf), asn1_dtg->protocolDataFilename->size, &((*dtg)->protocolDataFilename)));
	}
	if(asn1_dtg->protocolDataFileLocationId)
	{
		BMD_FOK(set_gen_buf2((char *)(asn1_dtg->protocolDataFileLocationId->buf), asn1_dtg->protocolDataFileLocationId->size, &((*dtg)->protocolDataFileLocationId)));
	}
	if(asn1_dtg->protocolDataFileId)
	{
		BMD_FOK(set_gen_buf2((char*)(asn1_dtg->protocolDataFileId->buf), asn1_dtg->protocolDataFileId->size, &((*dtg)->protocolDataFileId)));
	}
	if(asn1_dtg->protocolDataOwner)
	{
		BMD_FOK(set_gen_buf2((char*)(asn1_dtg->protocolDataOwner->buf), asn1_dtg->protocolDataOwner->size, &((*dtg)->protocolDataOwner)));
	}


	BMD_FOK(_PR_MetaData2MetaDataBuf(	(struct MetaDatas *)asn1_dtg->sysMetaDatas,
							&((*dtg)->sysMetaData),
							&((*dtg)->no_of_sysMetaData), NULL));
	BMD_FOK(_PR_MetaData2MetaDataBuf(	(struct MetaDatas *)asn1_dtg->actionMetaDatas,
							&((*dtg)->actionMetaData),
							&((*dtg)->no_of_actionMetaData), NULL));
	BMD_FOK(_PR_MetaData2MetaDataBuf(	(struct MetaDatas *)asn1_dtg->pkiMetaDatas,
							&((*dtg)->pkiMetaData),
							&((*dtg)->no_of_pkiMetaData), NULL));
	BMD_FOK(_PR_MetaData2MetaDataBuf(	(struct MetaDatas *)asn1_dtg->additionalMetaDatas,
							&((*dtg)->additionalMetaData),
							&((*dtg)->no_of_additionalMetaData), NULL));

	return BMD_OK;
}
Beispiel #3
0
static void
check_xer(int tofail, char *xmldata, long orig_value) {
	INTEGER_t *st = 0;
	asn_dec_rval_t rc;
	long value;
	int ret;

	printf("[%s] vs %ld: ", xmldata, orig_value);

	rc = xer_decode(0, &asn_DEF_INTEGER, (void *)&st,
		xmldata, strlen(xmldata));
	if(rc.code != RC_OK) {
		assert(tofail);
		printf("\tfailed, as expected\n");
		return;
	}
	assert(!tofail);

	ret = asn_INTEGER2long(st, &value);
	assert(ret == 0);

	printf("\t%ld\n", value);

	assert(value == orig_value);

	asn_DEF_INTEGER.free_struct(&asn_DEF_INTEGER, st, 0);
}
Beispiel #4
0
void *inap_decode(Invoke_t *invoke, asn_TYPE_descriptor_t **type) {
	long opcode;
	int rv;
	void *arg = 0;

	if (!invoke || !invoke->parameter || !type)
		goto nothing;

	if (invoke->opCode.present != OPERATION_PR_localValue)
		goto nothing;

	if (asn_INTEGER2long(&invoke->opCode.choice.localValue, &opcode))
		goto nothing;

	if (opcode >= ARRAY_SIZE(opcode_type_map))
		goto nothing;

	*type = opcode_type_map[opcode];
	if (!*type)
		goto nothing;

	rv = ANY_to_type(invoke->parameter, *type, &arg);

	if (!rv)
		return arg;

	if (arg)
		(*type)->free_struct(*type, arg, 0);

nothing:
	*type = NULL;
	return NULL;
}
Beispiel #5
0
asn_dec_rval_t
NativeInteger_decode_aper(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td,
	asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {

	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
	asn_dec_rval_t rval;
	long *native = (long *)*sptr;
	INTEGER_t tmpint;
	void *tmpintptr = &tmpint;

	(void)opt_codec_ctx;
	ASN_DEBUG("Decoding NativeInteger %s (APER)", td->name);

	if(!native) {
		native = (long *)(*sptr = CALLOC(1, sizeof(*native)));
		if(!native) _ASN_DECODE_FAILED;
	}

	memset(&tmpint, 0, sizeof tmpint);
	rval = INTEGER_decode_aper(opt_codec_ctx, td, constraints,
				   &tmpintptr, pd);
	if(rval.code == RC_OK) {
		if((specs&&specs->field_unsigned)
			? asn_INTEGER2ulong(&tmpint, (unsigned long *)native)
			: asn_INTEGER2long(&tmpint, native))
			rval.code = RC_FAIL;
		else
			ASN_DEBUG("NativeInteger %s got value %ld",
				td->name, *native);
	}
	ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &tmpint);

	return rval;
}
Beispiel #6
0
Datei: Gauge.c Projekt: madf/stg
int
Gauge_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
			asn_app_constraint_failed_f *ctfailcb, void *app_key) {
	const INTEGER_t *st = (const INTEGER_t *)sptr;
	long value;
	
	if(!sptr) {
		_ASN_CTFAIL(app_key, td, sptr,
			"%s: value not given (%s:%d)",
			td->name, __FILE__, __LINE__);
		return -1;
	}
	
	if(asn_INTEGER2long(st, &value)) {
		_ASN_CTFAIL(app_key, td, sptr,
			"%s: value too large (%s:%d)",
			td->name, __FILE__, __LINE__);
		return -1;
	}
	
	if((value >= 0 && value <= 4294967295)) {
		/* Constraint check succeeded */
		return 0;
	} else {
		_ASN_CTFAIL(app_key, td, sptr,
			"%s: constraint failed (%s:%d)",
			td->name, __FILE__, __LINE__);
		return -1;
	}
}
uint32_t
mmsClient_getInvokeId(ConfirmedResponsePdu_t* confirmedResponse)
{
	long invokeId;

	asn_INTEGER2long(&confirmedResponse->invokeID, &invokeId);

	return (uint32_t) invokeId;
}
Beispiel #8
0
// Sprawdzenie, czy dany SignerInfo jest okreslonej wersji
// 0 - nie jest
// 1 - jest
long SignerInfo_is_Version(
	SignerInfo_t* sigInfo,
	CMSVersion_e version)
{
	long v = -1;
	if ( sigInfo == NULL )
		return 0;
	asn_INTEGER2long( &(sigInfo->version), &v );
	return v == version;
}
Beispiel #9
0
asn_enc_rval_t
ENUMERATED_encode_uper(asn_TYPE_descriptor_t *td,
	asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
	ENUMERATED_t *st = (ENUMERATED_t *)sptr;
	long value;

	if(asn_INTEGER2long(st, &value))
		ASN__ENCODE_FAILED;

	return NativeEnumerated_encode_uper(td, constraints, &value, po);
}
static int
handleConfirmedRequestPdu(
		MmsServerConnection* self,
		ConfirmedRequestPdu_t* request,
		ByteBuffer* response)
{
	long invokeIdLong;
	int32_t invokeId;

	asn_INTEGER2long((INTEGER_t*) &(request->invokeID), &invokeIdLong);

	invokeId = (int32_t) invokeIdLong;

	if (DEBUG) printf("invokeId: %i\n", invokeId);

	switch(request->confirmedServiceRequest.present) {
	case ConfirmedServiceRequest_PR_getNameList:
		mmsServer_handleGetNameListRequest(self, &(request->confirmedServiceRequest.choice.getNameList),
				invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_read:
		mmsServer_handleReadRequest(self, &(request->confirmedServiceRequest.choice.read),
				invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_write:
		mmsServer_handleWriteRequest(self, &(request->confirmedServiceRequest.choice.write),
						invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_getVariableAccessAttributes:
		mmsServer_handleGetVariableAccessAttributesRequest(self,
				&(request->confirmedServiceRequest.choice.getVariableAccessAttributes),
				invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_defineNamedVariableList:
		mmsServer_handleDefineNamedVariableListRequest(self,
				&(request->confirmedServiceRequest.choice.defineNamedVariableList),
				invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_getNamedVariableListAttributes:
		mmsServer_handleGetNamedVariableListAttributesRequest(self,
				&(request->confirmedServiceRequest.choice.getNamedVariableListAttributes),
				invokeId, response);
		break;
	case ConfirmedServiceRequest_PR_deleteNamedVariableList:
		mmsServer_handleDeleteNamedVariableListRequest(self,
				&(request->confirmedServiceRequest.choice.deleteNamedVariableList),
				invokeId, response);
		break;
	default:
		writeMmsRejectPdu(&invokeId, REJECT_UNRECOGNIZED_SERVICE, response);
		break;
	}
}
static int asn_DFL_2_set_0(int set_value, void **sptr) {
	INTEGER_t *st = *sptr;
	
	if(!st) {
		if(!set_value) return -1;	/* Not a default value */
		st = (*sptr = CALLOC(1, sizeof(*st)));
		if(!st) return -1;
	}
	
	if(set_value) {
		/* Install default value 0 */
		return asn_long2INTEGER(st, 0);
	} else {
		/* Test default value 0 */
		long value;
		if(asn_INTEGER2long(st, &value))
			return -1;
		return (value == 0);
	}
}
Beispiel #12
0
/*
 * Decode the chunk of XML text encoding INTEGER.
 */
asn_dec_rval_t NativeInteger_decode_xer(asn_codec_ctx_t *opt_codec_ctx,
                                        asn_TYPE_descriptor_t *td, void **sptr,
                                        const char *opt_mname,
                                        const void *buf_ptr, size_t size)
{
    asn_INTEGER_specifics_t *specs = (asn_INTEGER_specifics_t *)td->specifics;
    asn_dec_rval_t rval;
    INTEGER_t st;
    void *st_ptr = (void *)&st;
    long *native = (long *)*sptr;

    if (!native) {
        native = (long *)(*sptr = CALLOC(1, sizeof(*native)));
        if (!native)
            _ASN_DECODE_FAILED;
    }

    memset(&st, 0, sizeof(st));
    rval = INTEGER_decode_xer(opt_codec_ctx, td, &st_ptr, opt_mname, buf_ptr,
                              size);
    if (rval.code == RC_OK) {
        long l;
        if ((specs && specs->field_unsigned)
                ? asn_INTEGER2ulong(&st, (unsigned long *)&l) /* sic */
                : asn_INTEGER2long(&st, &l)) {
            rval.code = RC_FAIL;
            rval.consumed = 0;
        } else {
            *native = l;
        }
    } else {
        /*
         * Cannot restart from the middle;
         * there is no place to save state in the native type.
         * Request a continuation from the very beginning.
         */
        rval.consumed = 0;
    }
    ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_INTEGER, &st);
    return rval;
}
Beispiel #13
0
long _get_respStatus(DVCSResponse_t *response, long *status)
{
long resp_status=0;
long ret_val=0;

	if(response == NULL)
	{
		PRINT_ERROR("LIBBMDPRERR Invalid first parameter value. Error=%i\n",-1);
		return -1;
	}

	/********************** poprawka **********************************/
	if(response->present != DVCSResponse_PR_dvCertInfo)
	{
		PRINT_ERROR("Error\n");
		return -2;
	}
	/******************************************************************/
	if(response->choice.dvCertInfo.dvStatus == NULL) //jesli brak to sukces
	{
		*status=0;
		return 0;
	}

	ret_val=asn_INTEGER2long(&(response->choice.dvCertInfo.dvStatus->status), &resp_status);
	if(ret_val != 0)
	{
		PRINT_ERROR("Error\n");
		return -3;
	}

	/*!!! tak mozna dobrac sie o info, co nie tak z certyfikatem
	printf("<%s>\n", response->choice.dvCertInfo.certs2->list.array[0]->chain->list.array[0]->choice.pkistatus.statusString->list.array[0]->buf);
	*/

	*status=resp_status;
	return 0;
}
Beispiel #14
0
static void
check_xer(e_Enum2 eval, char *xer_string) {
	asn_dec_rval_t rv;
	char buf2[128];
	Enum2_t *e = 0;
	long val;

	rv = xer_decode(0, &asn_DEF_Enum2, (void **)&e,
		xer_string, strlen(xer_string));
	assert(rv.code == RC_OK);
	assert(rv.consumed == strlen(xer_string));

	asn_INTEGER2long(e, &val);
	printf("%s -> %ld == %d\n", xer_string, val, eval);
	assert(val == eval);

	buf_offset = 0;
	xer_encode(&asn_DEF_Enum2, e, XER_F_CANONICAL, buf_writer, 0);
	buf[buf_offset] = 0;
	sprintf(buf2, "<Enum2>%s</Enum2>", xer_string);
	printf("%d -> %s == %s\n", eval, buf, buf2);
	assert(0 == strcmp(buf, buf2));
}
Beispiel #15
0
static long i2l(const INTEGER_t *i) {
    long l;
    int ret = asn_INTEGER2long(i, &l);
    assert(ret == 0);
    return l;
}
Beispiel #16
0
/*
 * Decode INTEGER type.
 */
asn_dec_rval_t
NativeInteger_decode_ber(asn_codec_ctx_t *opt_codec_ctx,
	asn_TYPE_descriptor_t *td,
	void **nint_ptr, const void *buf_ptr, size_t size, int tag_mode) {
	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
	long *native = (long *)*nint_ptr;
	asn_dec_rval_t rval;
	ber_tlv_len_t length;

	/*
	 * If the structure is not there, allocate it.
	 */
	if(native == NULL) {
		native = (long *)(*nint_ptr = CALLOC(1, sizeof(*native)));
		if(native == NULL) {
			rval.code = RC_FAIL;
			rval.consumed = 0;
			return rval;
		}
	}

	ASN_DEBUG("Decoding %s as INTEGER (tm=%d)",
		td->name, tag_mode);

	/*
	 * Check tags.
	 */
	rval = ber_check_tags(opt_codec_ctx, td, 0, buf_ptr, size,
			tag_mode, 0, &length, 0);
	if(rval.code != RC_OK)
		return rval;

	ASN_DEBUG("%s length is %d bytes", td->name, (int)length);

	/*
	 * Make sure we have this length.
	 */
	buf_ptr = ((const char *)buf_ptr) + rval.consumed;
	size -= rval.consumed;
	if(length > (ber_tlv_len_t)size) {
		rval.code = RC_WMORE;
		rval.consumed = 0;
		return rval;
	}

	/*
	 * ASN.1 encoded INTEGER: buf_ptr, length
	 * Fill the native, at the same time checking for overflow.
	 * If overflow occured, return with RC_FAIL.
	 */
	{
		INTEGER_t tmp;
		union {
			const void *constbuf;
			void *nonconstbuf;
		} unconst_buf;
		long l;

		unconst_buf.constbuf = buf_ptr;
		tmp.buf = (uint8_t *)unconst_buf.nonconstbuf;
		tmp.size = length;

		if((specs&&specs->field_unsigned)
			? asn_INTEGER2ulong(&tmp, (unsigned long *)&l) /* sic */
			: asn_INTEGER2long(&tmp, &l)) {
			rval.code = RC_FAIL;
			rval.consumed = 0;
			return rval;
		}

		*native = l;
	}

	rval.code = RC_OK;
	rval.consumed += length;

	ASN_DEBUG("Took %ld/%ld bytes to encode %s (%ld)",
		(long)rval.consumed, (long)length, td->name, (long)*native);

	return rval;
}
static MmsNamedVariableList
createNamedVariableList(MmsDomain* domain, MmsDevice* device,
		DefineNamedVariableListRequest_t* request,
		char* variableListName, MmsError* mmsError)
{
    MmsNamedVariableList namedVariableList = NULL;

	int variableCount = request->listOfVariable.list.count;

	if (variableCount > CONFIG_MMS_MAX_NUMBER_OF_DATA_SET_MEMBERS) {
	    *mmsError = MMS_ERROR_DEFINITION_OTHER;
	    goto exit_function;
	}

	namedVariableList = MmsNamedVariableList_create(domain, variableListName, true);

	int i;
	for (i = 0; i < variableCount; i++) {
		VariableSpecification_t* varSpec =
				&request->listOfVariable.list.array[i]->variableSpecification;

		long arrayIndex = -1;

		char componentNameBuf[65];
		char* componentName = NULL;

		/* Handle alternate access specification - for array element definition */
		if (request->listOfVariable.list.array[i]->alternateAccess != NULL) {

			if (request->listOfVariable.list.array[i]->alternateAccess->list.count != 1) {
				MmsNamedVariableList_destroy(namedVariableList);
				namedVariableList = NULL;
				break;
			}
			else {

				struct AlternateAccess__Member* alternateAccess =
						request->listOfVariable.list.array[i]->alternateAccess->list.array[0];

				if ((alternateAccess->present == AlternateAccess__Member_PR_unnamed)
				    &&(alternateAccess->choice.unnamed->present == AlternateAccessSelection_PR_selectAlternateAccess)
				    && (alternateAccess->choice.unnamed->choice.selectAlternateAccess.accessSelection.present ==
				               AlternateAccessSelection__selectAlternateAccess__accessSelection_PR_index))
				{
					asn_INTEGER2long(&(alternateAccess->choice.unnamed->choice.selectAlternateAccess.accessSelection.choice.index),
							&arrayIndex);

					Identifier_t componentIdentifier = alternateAccess->choice.unnamed->
                            choice.selectAlternateAccess.alternateAccess->list.array[0]->
                            choice.unnamed->choice.selectAccess.choice.component;

					componentName =
					        StringUtils_createStringFromBufferInBuffer(componentNameBuf,
					                componentIdentifier.buf, componentIdentifier.size);

				}
				else {
					MmsNamedVariableList_destroy(namedVariableList);
					namedVariableList = NULL;
					*mmsError = MMS_ERROR_DEFINITION_INVALID_ADDRESS;
					break;
				}

			}

		}

		if (varSpec->present == VariableSpecification_PR_name) {

		    char variableName[65];
		    char domainId[65];

		    StringUtils_createStringFromBufferInBuffer(variableName,
		            varSpec->choice.name.choice.domainspecific.itemId.buf,
                    varSpec->choice.name.choice.domainspecific.itemId.size);

		    StringUtils_createStringFromBufferInBuffer(domainId,
		            varSpec->choice.name.choice.domainspecific.domainId.buf,
                    varSpec->choice.name.choice.domainspecific.domainId.size);

			MmsDomain* elementDomain = MmsDevice_getDomain(device, domainId);

			MmsAccessSpecifier accessSpecifier;

			accessSpecifier.domain = elementDomain;
			accessSpecifier.variableName = variableName;
			accessSpecifier.arrayIndex = arrayIndex;
			accessSpecifier.componentName = componentName;

			// check if element exists
			if (checkIfVariableExists(device, &accessSpecifier) == true) {

                MmsNamedVariableListEntry variable =
                        MmsNamedVariableListEntry_create(accessSpecifier);

                MmsNamedVariableList_addVariable(namedVariableList, variable);
			}
			else {
			    MmsNamedVariableList_destroy(namedVariableList);
                namedVariableList = NULL;
                i = variableCount; // exit loop after freeing loop variables
                *mmsError = MMS_ERROR_DEFINITION_OBJECT_UNDEFINED;
			}
		}
		else {
			MmsNamedVariableList_destroy(namedVariableList);
			namedVariableList = NULL;
			*mmsError = MMS_ERROR_DEFINITION_INVALID_ADDRESS;
			break;
		}
	}

exit_function:

	return namedVariableList;
}
void
mmsServer_handleDeleteNamedVariableListRequest(MmsServerConnection* connection,
        DeleteNamedVariableListRequest_t* request,
        int invokeId,
        ByteBuffer* response)
{
    //TODO implement for association specific named variable lists

    MmsDevice* device;
    long scopeOfDelete;
    request->scopeOfDelete;

    asn_INTEGER2long(request->scopeOfDelete, &scopeOfDelete);

    device = MmsServer_getDevice(connection->server);

    if (scopeOfDelete == DeleteNamedVariableListRequest__scopeOfDelete_specific) {
        int numberMatched = 0;
        int numberDeleted = 0;

        int numberItems = request->listOfVariableListName->list.count;

        int i;

        for (i = 0; i < numberItems; i++) {
            if (request->listOfVariableListName->list.array[i]->present == ObjectName_PR_domainspecific) {
                char* domainId = mmsMsg_createStringFromAsnIdentifier(
                                     request->listOfVariableListName->list.array[i]->choice.domainspecific.domainId);

                MmsDomain* domain = MmsDevice_getDomain(device, domainId);

                char* itemId = mmsMsg_createStringFromAsnIdentifier(
                                   request->listOfVariableListName->list.array[i]->choice.domainspecific.itemId);

                MmsNamedVariableList variableList = MmsDomain_getNamedVariableList(domain, itemId);

                if (variableList != NULL) {
                    numberMatched++;

                    if (MmsNamedVariableList_isDeletable(variableList)) {
                        MmsDomain_deleteNamedVariableList(domain, itemId);
                        numberDeleted++;
                    }
                }

                free(domainId);
                free(itemId);
            }
            else if (request->listOfVariableListName->list.array[i]->present == ObjectName_PR_aaspecific) {
                char* itemId = mmsMsg_createStringFromAsnIdentifier(
                                   request->listOfVariableListName->list.array[i]->choice.aaspecific);

                MmsNamedVariableList variableList = MmsServerConnection_getNamedVariableList(connection, itemId);

                if (variableList != NULL) {
                    numberMatched++;
                    numberDeleted++;

                    MmsServerConnection_deleteNamedVariableList(connection, itemId);
                }

                free(itemId);
            }
            //TODO else send error???
        }

        createDeleteNamedVariableListResponse(invokeId, response, numberMatched, numberDeleted);
    }
    else {
        mmsServer_createConfirmedErrorPdu(invokeId, response, MMS_ERROR_TYPE_OBJECT_ACCESS_UNSUPPORTED);
    }
}
void
mmsServer_handleDeleteNamedVariableListRequest(MmsServerConnection connection,
		uint8_t* buffer, int bufPos, int maxBufPos,
		uint32_t invokeId,
		ByteBuffer* response)
{
	DeleteNamedVariableListRequest_t* request = 0;

    MmsPdu_t* mmsPdu = 0;

    asn_dec_rval_t rval = ber_decode(NULL, &asn_DEF_MmsPdu, (void**) &mmsPdu, buffer, maxBufPos);

    if (rval.code != RC_OK) {
        mmsServer_writeMmsRejectPdu(&invokeId, MMS_ERROR_REJECT_INVALID_PDU, response);
        goto exit_function;
    }

    request = &(mmsPdu->choice.confirmedRequestPdu.confirmedServiceRequest.choice.deleteNamedVariableList);

	long scopeOfDelete;

	asn_INTEGER2long(request->scopeOfDelete, &scopeOfDelete);

	MmsDevice* device = MmsServer_getDevice(connection->server);

	if (scopeOfDelete == DeleteNamedVariableListRequest__scopeOfDelete_specific) {
		int numberMatched = 0;
		int numberDeleted = 0;

		int numberItems = request->listOfVariableListName->list.count;

		int i;

		for (i = 0; i < numberItems; i++) {
			if (request->listOfVariableListName->list.array[i]->present == ObjectName_PR_domainspecific) {
		        char domainName[65];
		        char listName[65];

		        mmsMsg_copyAsn1IdentifierToStringBuffer(request->listOfVariableListName->list.array[i]->choice.domainspecific.domainId,
		                domainName, 65);

		        mmsMsg_copyAsn1IdentifierToStringBuffer(request->listOfVariableListName->list.array[i]->choice.domainspecific.itemId,
		                listName, 65);

		        MmsDomain* domain = MmsDevice_getDomain(device, domainName);

		        if (domain != NULL) {

                    MmsNamedVariableList variableList = MmsDomain_getNamedVariableList(domain, listName);

                    if (variableList != NULL) {
                        numberMatched++;

                        if (MmsNamedVariableList_isDeletable(variableList)) {

                            if (mmsServer_callVariableListChangedHandler(false, MMS_DOMAIN_SPECIFIC, domain, listName, connection) == MMS_ERROR_NONE) {
                                MmsDomain_deleteNamedVariableList(domain, listName);
                                numberDeleted++;
                            }
                        }
                    }
		        }
			}
			else if (request->listOfVariableListName->list.array[i]->present == ObjectName_PR_aaspecific) {
			    char listName[65];

			    mmsMsg_copyAsn1IdentifierToStringBuffer(request->listOfVariableListName->list.array[i]->choice.aaspecific,
			            listName, 65);

				MmsNamedVariableList variableList = MmsServerConnection_getNamedVariableList(connection, listName);

				if (variableList != NULL) {
					numberMatched++;

					if (mmsServer_callVariableListChangedHandler(false, MMS_ASSOCIATION_SPECIFIC, NULL, listName, connection) == MMS_ERROR_NONE) {
					    numberDeleted++;
					    MmsServerConnection_deleteNamedVariableList(connection, listName);
					}
				}
			}
		}

		createDeleteNamedVariableListResponse(invokeId, response, numberMatched, numberDeleted);
	}
	else {
		mmsServer_createConfirmedErrorPdu(invokeId, response, MMS_ERROR_ACCESS_OBJECT_ACCESS_UNSUPPORTED);
	}

    asn_DEF_MmsPdu.free_struct(&asn_DEF_MmsPdu, mmsPdu, 0);

exit_function:
    return;
}
Beispiel #20
0
/*
WSZ porzdki - BMD_ERR_LOAD_SIG_POLICY (-77)
@return BMD_ERR_LOAD_SIG_POLICY (-77) jesli nie mona zaladowac badz zdekodowac wskazanej polityki podpisu
@return BMDPKI_ERR_FIND_CERT_STORE (-78) jesli nie mozna odnalezc magazynu certyfikatow zaufanych
z funkcji bmd_verify_cert_with_crl():
@return BMD_ERR_PARAM1				- niewlasciwe wywolanie
@return BMD_ERR_OP_FAILED			- wiele bledow nie okreslonych blizej
@return BMD_ERR_PKI_NO_CRL (-56)	- nie moze wczytac listy CRL
@return BMD_ERR_PKI_VERIFY			- blad weryfikacji certyfikatu
*/
long bmd_set_signature_params_policy(bmd_signature_params_t *sig_params,char *sig_policy,long auto_params_create,GenBuf_t *cert, CertExtConfig_t *certCheckParams)
{
long status;
GenBuf_t *buf=NULL;
SignaturePolicy_t *policy=NULL;
asn_dec_rval_t rval;
CMSAttrs_t *policy_signed_attrs=NULL;
SignerAndVerifierRules_t *SigVerRules=NULL;
long i=0;
long j=0;
long type;
char *policy_oid=NULL;
bmd_crypt_ctx_t *hash_ctx=NULL;
GenBuf_t *policy_hash_buf=NULL;
GenBuf_t *cert_hash_buf=NULL;
Attribute_t *sig_pol_attr=NULL;
Attribute_t *cert_attr=NULL;
Attribute_t *time_attr=NULL;
Certificate_t *asn1_cert=NULL;
CertificateTrustPoint_t *trust_point=NULL;
CertificateTrustTrees_t *trust_trees=NULL;
SigningCertTrustCondition_t *sig_cert_trust=NULL;
GeneralNames_t *g_names=NULL;
GeneralName_t *g_name=NULL;
char *policy_url=NULL;
long trust_condition=0;

GenBuf_t **trusted_certs=NULL;
GenBuf_t **constructed_cert_path=NULL;
long cert_path_length=0;

long flag_trust_found=0;

	if(sig_params==NULL)
	{
		PRINT_DEBUG("LIBBMDPKIERR Invalid first parameter value. Error=%i\n",BMD_ERR_PARAM1);
		return BMD_ERR_PARAM1;
	}
	if(sig_policy==NULL)
	{
		PRINT_DEBUG("LIBBMDPKIERR Invalid second parameter value. Error=%i\n",BMD_ERR_PARAM2);
		return BMD_ERR_PARAM2;
	}

	status=_bmd_load_signature_policy(sig_policy,&buf);
	if(status!=BMD_OK)
	{
		PRINT_DEBUG("LIBBMDPKIERR Error loading signature policy. Error=%i\n",BMDPKI_ERR_LOAD_SIG_POLICY);
		return BMDPKI_ERR_LOAD_SIG_POLICY;
	}
	rval=ber_decode(NULL,&asn_DEF_SignaturePolicy,&(sig_params->signature_policy),buf->buf,buf->size);
	if(rval.code!=RC_OK)
	{
		PRINT_DEBUG("LIBBMDPKIERR Error loading signature policy. Error=%i\n",BMDPKI_ERR_LOAD_SIG_POLICY);
		return BMDPKI_ERR_LOAD_SIG_POLICY;
	}

	policy=(SignaturePolicy_t *)sig_params->signature_policy;
	/* pobranie zaufanych certyfikatow dla podpisujacego z polityki podpisu */
	trust_trees=&(policy->signPolicyInfo.signatureValidationPolicy.commonRules.signingCertTrustCondition->signerTrustTrees);
	trusted_certs=(GenBuf_t **)calloc((trust_trees->list.count+2), sizeof(GenBuf_t *));
	for(i=0;i<trust_trees->list.count;i++)
	{
		trust_point=trust_trees->list.array[i];
		asn1_encode(&asn_DEF_Certificate,&(trust_point->trustpoint), NULL, &(trusted_certs[i]));
	}

	if(sig_params->tcc) /* jesli ustawiono Trusted Cert Store */
	{
		status=bmd_verify_cert_path(cert,sig_params->tcc,&constructed_cert_path,NULL);
		if(status==BMD_OK)
		{
			i=0;
			while(constructed_cert_path[i])
			{
				i++;
			}
			cert_path_length=i;

			i=0;
			while(trusted_certs[i])
			{
				if(trusted_certs[i]->size==constructed_cert_path[cert_path_length-1]->size)
				{
					if(memcmp(trusted_certs[i]->buf,constructed_cert_path[cert_path_length-1]->buf,trusted_certs[i]->size)==0)
					{
						flag_trust_found=1;
						break;
					}
				}
				i++;
			}
			if(flag_trust_found==0)
			{
				PRINT_DEBUG("LIBBMDPKIERR Error. Error=%i\n",BMD_ERR_OP_FAILED);
				return BMD_ERR_OP_FAILED;
			}
		}
		else
		{
			PRINT_DEBUG("LIBBMDPKIERR Error in finding cert store. Error=%i\n",BMDPKI_ERR_FIND_CERT_STORE);
			return BMDPKI_ERR_FIND_CERT_STORE;
		}
	}
	else
	{
		PRINT_DEBUG("LIBBMDPKIERR Error. Error=%i\n",BMD_ERR_OP_FAILED);
		return BMD_ERR_OP_FAILED;
	}

	/* sprawdzenie czy certyfikat ktorym ma sie wykonac podpis jest na CRL - jesli tylko to jest w polityce */
	sig_cert_trust=policy->signPolicyInfo.signatureValidationPolicy.commonRules.signingCertTrustCondition;
	asn_INTEGER2long(&(sig_cert_trust->signerRevReq.endCertRevReq.enuRevReq),&trust_condition);
	if(trust_condition==EnuRevReq_clrCheck)
	{
		if(certCheckParams==NULL) /*na podstawie CRL distribution point w certyfikacie*/
		{
			status=bmd_verify_cert_with_crl(cert, NULL, NULL);
		}
		else if(certCheckParams->check_with_crl > 0)
		{
			if(certCheckParams->download_crl > 0)
			{
				status=bmd_verify_cert_with_crl(cert, certCheckParams->url_of_crl, NULL);
			}
			else if(certCheckParams->use_crl_file > 0)
			{
				status=bmd_verify_cert_with_crl(cert, NULL, certCheckParams->crl_file_path);
			}
			else /*na podstawie CRL distribution point w certyfikacie*/
			{
				status=bmd_verify_cert_with_crl(cert, NULL, NULL);
			}
		}
		else /*jesli wylaczona weryfikacja crl*/
		{
			status=BMD_OK;
		}

		if(status!=BMD_OK)
		{
			PRINT_DEBUG("LIBBMDPKIERR Error. Error=%li\n",status);
			return status;
		}
	}

	/* w tym momencie wiemy ze certyfikat moze wykonac podpis ??? */

	if(auto_params_create==1) /* stworzenie parametrow stalych do podpisu  */
	{
		policy=(SignaturePolicy_t *)sig_params->signature_policy;
		/* ustaw wskaznik na liste obowiazkowych atrybutow podpisanych */
		SigVerRules=policy->signPolicyInfo.signatureValidationPolicy.commonRules.signerAndVeriferRules;
		policy_signed_attrs=&(SigVerRules->signerRules.mandatedSignedAttr);
		sig_params->signed_attributes=(SignedAttributes_t *)malloc(sizeof(SignedAttributes_t));
		memset(sig_params->signed_attributes,0,sizeof(SignedAttributes_t));

		for(i=0;i<policy_signed_attrs->list.count;i++)
		{
			__bmd_determine_signed_attr_type(policy_signed_attrs->list.array[i],&type);
			switch(type)
			{
				case BMD_CMS_ATTR_CONTENT_TYPE: /* rozszerzenie standardowe - nic nie trzeba robic */
					break;
				case BMD_CMS_ATTR_MESSAGE_DIGEST: /* rozszerzenie standardowe - nic nie trzeba robic */
					break;
				case BMD_CMS_ATTR_SIGNING_TIME: /* zostanie stworzony pozniej */
					SigAttr_Create_SigningTime(&time_attr);
					asn_set_add(sig_params->signed_attributes,time_attr);
					break;
				case BMD_CMS_ATTR_SIGNING_CERT:
					if(cert)
					{
						bmd_ctx_destroy(&hash_ctx);
						bmd_set_ctx_hash(&hash_ctx,BMD_HASH_ALGO_SHA1);
						status=bmd_hash_data(cert,&hash_ctx,&cert_hash_buf,NULL);
						ber_decode(NULL,&asn_DEF_Certificate,(void **)&asn1_cert,cert->buf,cert->size);
						SigAttr_Create_SigningCertificate(cert_hash_buf,asn1_cert,&cert_attr);

						asn_set_add(sig_params->signed_attributes,cert_attr);
						bmd_ctx_destroy(&hash_ctx);
						asn_DEF_Certificate.free_struct(&asn_DEF_Certificate,asn1_cert,0);asn1_cert=NULL;
						free_gen_buf(&cert_hash_buf);
					}
					else
					{
						PRINT_DEBUG("LIBBMDPKIERR Error. Error=%i\n",BMD_ERR_OP_FAILED);
						return BMD_ERR_OP_FAILED;
					}
					break;
				case BMD_CMS_ATTR_SIG_POLICY_ID:
					status=OBJECT_IDENTIFIER2string(&(policy->signPolicyInfo.signPolicyIdentifier),&policy_oid);
					if(status!=BMD_OK)
					{
						PRINT_DEBUG("LIBBMDPKIERR Error. Error=%i\n",BMD_ERR_OP_FAILED);
						return BMD_ERR_OP_FAILED;
					}

					/* (by WSZ)  zmiana sposobu wyliczania skrotu polityki podipsu (ProCertum API compatible)
					bmd_ctx_destroy(&hash_ctx);
					status=bmd_set_ctx_hash(&hash_ctx,BMD_HASH_ALGO_SHA1);
					status=bmd_hash_data(buf,&hash_ctx,&policy_hash_buf,NULL);
					*/
					status=bmd_hash_SignaturePolicy(buf, &policy_hash_buf);
					g_names=&(policy->signPolicyInfo.policyIssuerName);
					for(j=0;j<g_names->list.count;j++)
					{
						g_name=g_names->list.array[j];
						if(g_name->present==GeneralName_PR_dNSName)
						{
							GeneralName2string(g_name,&policy_url);
							break;
						}
					}

					SigAttr_Create_SignaturePolicyId(policy_oid,policy_url,policy_hash_buf,&sig_pol_attr);
					asn_set_add(sig_params->signed_attributes,(void *)sig_pol_attr);
					free(policy_oid);
					free(policy_url);
					bmd_ctx_destroy(&hash_ctx);
					free_gen_buf(&policy_hash_buf);

					break;
			}
		}
	}

	i=0;
	if(trusted_certs)
	{
		while(trusted_certs[i])
		{
			free_gen_buf(&(trusted_certs[i]));
			i++;
		}
		free(trusted_certs);trusted_certs=NULL;
	}

	i=0;
	if(constructed_cert_path)
	{
		while(constructed_cert_path[i])
		{
			free_gen_buf(&(constructed_cert_path[i]));
			i++;
		}
		free(constructed_cert_path);constructed_cert_path=NULL;
	}

	return BMD_OK;
}
Beispiel #21
0
/*
 * INTEGER specific human-readable output.
 */
static ssize_t
INTEGER__dump(const asn_TYPE_descriptor_t *td, const INTEGER_t *st, asn_app_consume_bytes_f *cb, void *app_key, int plainOrXER) {
	asn_INTEGER_specifics_t *specs=(asn_INTEGER_specifics_t *)td->specifics;
	char scratch[32];	/* Enough for 64-bit integer */
	uint8_t *buf = st->buf;
	uint8_t *buf_end = st->buf + st->size;
	signed long value;
	ssize_t wrote = 0;
	char *p;
	int ret;

	if(specs && specs->field_unsigned)
		ret = asn_INTEGER2ulong(st, (unsigned long *)&value);
	else
		ret = asn_INTEGER2long(st, &value);

	/* Simple case: the integer size is small */
	if(ret == 0) {
		const asn_INTEGER_enum_map_t *el;
		size_t scrsize;
		char *scr;

		el = (value >= 0 || !specs || !specs->field_unsigned)
			? INTEGER_map_value2enum(specs, value) : 0;
		if(el) {
			scrsize = el->enum_len + 32;
			scr = (char *)alloca(scrsize);
			if(plainOrXER == 0)
				ret = snprintf(scr, scrsize,
					"%ld (%s)", value, el->enum_name);
			else
				ret = snprintf(scr, scrsize,
					"<%s/>", el->enum_name);
		} else if(plainOrXER && specs && specs->strict_enumeration) {
			ASN_DEBUG("ASN.1 forbids dealing with "
				"unknown value of ENUMERATED type");
			errno = EPERM;
			return -1;
		} else {
			scrsize = sizeof(scratch);
			scr = scratch;
			ret = snprintf(scr, scrsize,
				(specs && specs->field_unsigned)
				?"%lu":"%ld", value);
		}
		assert(ret > 0 && (size_t)ret < scrsize);
		return (cb(scr, ret, app_key) < 0) ? -1 : ret;
	} else if(plainOrXER && specs && specs->strict_enumeration) {
		/*
		 * Here and earlier, we cannot encode the ENUMERATED values
		 * if there is no corresponding identifier.
		 */
		ASN_DEBUG("ASN.1 forbids dealing with "
			"unknown value of ENUMERATED type");
		errno = EPERM;
		return -1;
	}

	/* Output in the long xx:yy:zz... format */
	/* TODO: replace with generic algorithm (Knuth TAOCP Vol 2, 4.3.1) */
	for(p = scratch; buf < buf_end; buf++) {
		const char * const h2c = "0123456789ABCDEF";
		if((p - scratch) >= (ssize_t)(sizeof(scratch) - 4)) {
			/* Flush buffer */
			if(cb(scratch, p - scratch, app_key) < 0)
				return -1;
			wrote += p - scratch;
			p = scratch;
		}
		*p++ = h2c[*buf >> 4];
		*p++ = h2c[*buf & 0x0F];
		*p++ = 0x3a;	/* ":" */
	}
	if(p != scratch)
		p--;	/* Remove the last ":" */

	wrote += p - scratch;
	return (cb(scratch, p - scratch, app_key) < 0) ? -1 : wrote;
}
static MmsVariableSpecification*
createTypeSpecification(TypeSpecification_t* asnTypeSpec) {
	MmsVariableSpecification* typeSpec = (MmsVariableSpecification*) 
        GLOBAL_CALLOC(1, sizeof(MmsVariableSpecification));

	switch (asnTypeSpec->present) {
	case TypeSpecification_PR_structure:
		{
			typeSpec->type = MMS_STRUCTURE;

			int elementCount = asnTypeSpec->choice.structure.components.list.count;
			typeSpec->typeSpec.structure.elementCount = elementCount;

			typeSpec->typeSpec.structure.elements = (MmsVariableSpecification**)
                GLOBAL_CALLOC(elementCount, sizeof(MmsVariableSpecification*));

			int i;

			for (i = 0; i < elementCount; i++) {

				char* name = createStringFromBuffer(
						asnTypeSpec->choice.structure.components.list.array[i]->componentName->buf,
						asnTypeSpec->choice.structure.components.list.array[i]->componentName->size);

				typeSpec->typeSpec.structure.elements[i] =
						createTypeSpecification(asnTypeSpec->choice.structure.components.
								list.array[i]->componentType);

				typeSpec->typeSpec.structure.elements[i]->name = name;
			}
		}
		break;
	case TypeSpecification_PR_array:
		{
			typeSpec->type = MMS_ARRAY;

			long elementCount;
			asn_INTEGER2long(&asnTypeSpec->choice.array.numberOfElements, &elementCount);

			typeSpec->typeSpec.array.elementCount = elementCount;

			typeSpec->typeSpec.array.elementTypeSpec =
					createTypeSpecification(asnTypeSpec->choice.array.elementType);
		}
		break;
	case TypeSpecification_PR_boolean:
		typeSpec->type = MMS_BOOLEAN;
		break;
	case TypeSpecification_PR_bitstring:
		typeSpec->type = MMS_BIT_STRING;
		typeSpec->typeSpec.bitString = asnTypeSpec->choice.bitstring;
		break;
	case TypeSpecification_PR_integer:
		typeSpec->type = MMS_INTEGER;
		typeSpec->typeSpec.integer = asnTypeSpec->choice.integer;
		break;
	case TypeSpecification_PR_unsigned:
		typeSpec->type = MMS_UNSIGNED;
		typeSpec->typeSpec.unsignedInteger = asnTypeSpec->choice.Unsigned;
		break;
	case TypeSpecification_PR_floatingpoint:
		typeSpec->type = MMS_FLOAT;
		typeSpec->typeSpec.floatingpoint.exponentWidth =
				asnTypeSpec->choice.floatingpoint.exponentwidth;
		typeSpec->typeSpec.floatingpoint.formatWidth =
						asnTypeSpec->choice.floatingpoint.formatwidth;
		break;
	case TypeSpecification_PR_octetstring:
		typeSpec->type = MMS_OCTET_STRING;
		typeSpec->typeSpec.octetString = asnTypeSpec->choice.octetstring;
		break;
	case TypeSpecification_PR_visiblestring:
		typeSpec->type = MMS_VISIBLE_STRING;
		typeSpec->typeSpec.visibleString = asnTypeSpec->choice.visiblestring;
		break;
	case TypeSpecification_PR_mMSString:
		typeSpec->type = MMS_STRING;
		typeSpec->typeSpec.mmsString = asnTypeSpec->choice.mMSString;
		break;
	case TypeSpecification_PR_utctime:
		typeSpec->type = MMS_UTC_TIME;
		break;
	case TypeSpecification_PR_binarytime:
	    typeSpec->type = MMS_BINARY_TIME;
	    if (asnTypeSpec->choice.binarytime == 0)
	        typeSpec->typeSpec.binaryTime = 4;
	    else
	        typeSpec->typeSpec.binaryTime = 6;
	    break;
	default:
		printf("ERROR: unknown type in type specification\n");
		break;
	}

	return typeSpec;
}
Beispiel #23
0
long _PR_MetaData2MetaDataBuf(struct MetaDatas *input,
				     	MetaDataBuf_t ***mtds,
					long *no_of_mtds,
					bmdDatagram_t *twf_bmdDatagram)
{
long i				= 0;
long pos				= 0;
char *OIDs_str                = NULL;
char *myIds_str               = NULL;
char *ownerIds_str            = NULL;
char *ownerTypes_str          = NULL;
char *datas_str               = NULL;
char *str_pos			= NULL;

	/************************/
	/* walidacja parametrow */
	/************************/
	if(mtds == NULL)				{	BMD_FOK(BMD_ERR_PARAM2);	}
	if((*mtds)!= NULL)			{	BMD_FOK(BMD_ERR_PARAM2);	}
	if(no_of_mtds == NULL)			{	BMD_FOK(BMD_ERR_PARAM3);	}

	if(input==NULL)
	{
		*no_of_mtds=0;
		*mtds=NULL;
		return BMD_OK;
	}

	/**************************************************************/
	/* określenie liczby metadanych i zaalokowanie pamięci na nie */
	/**************************************************************/
	(*no_of_mtds)=input->lenOfDatas.list.count;
	PRINT_VDEBUG("LIBBMDPRVDEBUG Metadatas count: %li\n", *no_of_mtds);

	(*mtds)=(MetaDataBuf_t **)malloc(sizeof(MetaDataBuf_t *)*( (*no_of_mtds)));
	if( (*mtds) == NULL )	{	BMD_FOK(NO_MEMORY);	}
	memset((*mtds),0,sizeof(MetaDataBuf_t *)*( (*no_of_mtds)));

	for (i=0; i<(*no_of_mtds); i++)
	{
		(*mtds)[i]=(MetaDataBuf_t *)malloc(sizeof(MetaDataBuf_t ));
		memset((*mtds)[i], 0, sizeof(MetaDataBuf_t ));
	}

	/***********************************/
	/* deserializacja oidów metadanych */
	/***********************************/
	BMD_FOK(OCTET_STRING2string(&(input->oids), &OIDs_str));
	pos = 0;
	str_pos = OIDs_str;
	for(i=0; i < (*no_of_mtds); i++)
	{
		str_pos = str_pos + pos;
		BMD_FOK(asn_INTEGER2long(input->lenOfOids.list.array[i], &pos));
		((*mtds)[i])->OIDTableBuf=malloc((pos+1)*sizeof(char));
		if (((*mtds)[i])->OIDTableBuf==NULL)	{	BMD_FOK(NO_MEMORY);	}
		memset(((*mtds)[i])->OIDTableBuf, 0, (pos+1)*sizeof(char));
 		memcpy(((*mtds)[i])->OIDTableBuf, str_pos, pos*sizeof(char));
		pos++; /*Na NULL*/
	}
	free(OIDs_str); OIDs_str = NULL;

	/**********************************/
	/* deserializacja myId metadanych */
	/**********************************/
	BMD_FOK(OCTET_STRING2string(&(input->myIds), &myIds_str));
	pos = 0;
	str_pos = myIds_str;
	for(i=0; i < *no_of_mtds; i++)
	{
		str_pos = str_pos + pos;
		((*mtds)[i])->myId = atol(str_pos);
		BMD_FOK(asn_INTEGER2long(input->lenOfMyIds.list.array[i], &pos));
		pos++; /*Na NULL*/
	}
	free(myIds_str); myIds_str = NULL;

	/*************************************/
	/* deserializacja ownerId metadanych */
	/*************************************/
	BMD_FOK(OCTET_STRING2string(&(input->ownerIds), &ownerIds_str));
	pos = 0;
	str_pos = ownerIds_str;
	for(i=0; i < *no_of_mtds; i++)
	{
		str_pos = str_pos + pos;
		((*mtds)[i])->ownerId = atol(str_pos);
		BMD_FOK(asn_INTEGER2long(input->lenOfOwnerIds.list.array[i], &pos));
		pos++; /*Na NULL*/
	}
	free(ownerIds_str); ownerIds_str = NULL;

	/***************************************/
	/* deserializacja ownerType metadanych */
	/***************************************/
	BMD_FOK(OCTET_STRING2string(&(input->ownerTypes), &ownerTypes_str));
	pos = 0;
	str_pos = ownerTypes_str;
	for(i=0; i < *no_of_mtds; i++)
	{
		str_pos = str_pos + pos;
		((*mtds)[i])->ownerType = atol(str_pos);
		BMD_FOK(asn_INTEGER2long(input->lenOfOwnerTypes.list.array[i], &pos));
		pos++; /*Na NULL*/
	}
	free(ownerTypes_str); ownerTypes_str = NULL;

	/**************************************/
	/* deserializacja wartości metadanych */
	/**************************************/
	BMD_FOK(OCTET_STRING2string(&(input->datas), &datas_str));
	pos = 0;
	str_pos = datas_str;

	if(twf_bmdDatagram != NULL)
	{
		str_pos = str_pos + pos;
		BMD_FOK(asn_INTEGER2long(input->lenOfDatas.list.array[i], &pos));
		((*mtds)[i])->AnyBuf = malloc((pos + 1) * sizeof(char));
		if(((*mtds)[i])->AnyBuf == NULL) 	{	BMD_FOK(NO_MEMORY);	}
		memset( ((*mtds)[i])->AnyBuf, 0, (pos + 1) * sizeof(char));
		memcpy( ((*mtds)[i])->AnyBuf, str_pos, pos * sizeof(char));
		((*mtds)[i])->AnySize = pos;
		pos++; /*Na NULL*/
	}
	else
	{
		for(i=0; i < *no_of_mtds; i++)
		{
			str_pos = str_pos + pos;
			BMD_FOK(asn_INTEGER2long(input->lenOfDatas.list.array[i], &pos));
			PRINT_VDEBUG("LIBBMDPRVDEBUG Decoding loop i: %li, data string len: %li\n", i, pos);
			((*mtds)[i])->AnyBuf = malloc((pos + 1) * sizeof(char));
			if(((*mtds)[i])->AnyBuf == NULL) 	{	BMD_FOK(NO_MEMORY);	}
			memset( ((*mtds)[i])->AnyBuf, 0, (pos + 1) * sizeof(char));
			memcpy( ((*mtds)[i])->AnyBuf, str_pos, pos * sizeof(char));
			/*BMD_FOK(asn_INTEGER2long(input->lenOfDatas.list.array[i], &pos));*/
			((*mtds)[i])->AnySize = pos;
			pos++; /*Na NULL*/
		}
		free(datas_str); datas_str = NULL;
	}

	return BMD_OK;
}
Beispiel #24
0
MmsValue*
mmsClient_parseReadResponse(ByteBuffer* message, uint32_t* invokeId)
{
	MmsPdu_t* mmsPdu = 0; /* allow asn1c to allocate structure */
	MmsIndication retVal =  MMS_OK;

	MmsValue* valueList = NULL;
	MmsValue* value = NULL;

	asn_dec_rval_t rval;

	rval = ber_decode(NULL, &asn_DEF_MmsPdu,
			(void**) &mmsPdu, ByteBuffer_getBuffer(message), ByteBuffer_getSize(message));

	if (DEBUG) xer_fprint(stdout, &asn_DEF_MmsPdu, mmsPdu);

	if (mmsPdu->present == MmsPdu_PR_confirmedResponsePdu) {

		*invokeId = mmsClient_getInvokeId(&mmsPdu->choice.confirmedResponsePdu);

		if (mmsPdu->choice.confirmedResponsePdu.confirmedServiceResponse.present == ConfirmedServiceResponse_PR_read) {
			ReadResponse_t* response = &(mmsPdu->choice.confirmedResponsePdu.confirmedServiceResponse.choice.read);

			int elementCount = response->listOfAccessResult.list.count;

			if (elementCount > 1)
				valueList = MmsValue_createEmtpyArray(elementCount);

			int i = 0;

			for (i = 0; i < elementCount; i++) {
				value = NULL;

				AccessResult_PR presentType = response->listOfAccessResult.list.array[i]->present;

				if (presentType == AccessResult_PR_failure) {
					if (DEBUG) printf("access error!\n");

					retVal = MMS_ERROR;
				}
				else if (presentType == AccessResult_PR_array) {
					value = calloc(1, sizeof(MmsValue));
					value->type = MMS_ARRAY;

					int elementCount =
							response->listOfAccessResult.list.array[i]->choice.array.list.count;

					value->value.array.size = elementCount;
					value->value.array.components = calloc(elementCount, sizeof(MmsValue*));

					int j;

					for (j = 0; j < elementCount; j++) {
						value->value.array.components[j] = mmsMsg_parseDataElement(
								response->listOfAccessResult.list.array[i]->choice.array.list.array[j]);
					}
				}
				else if (presentType == AccessResult_PR_structure) {
					value = calloc(1, sizeof(MmsValue));
					value->type = MMS_STRUCTURE;

					int componentCount =
							response->listOfAccessResult.list.array[i]->choice.structure.list.count;

					value->value.structure.componentCount = componentCount;
					value->value.structure.components = calloc(componentCount, sizeof(MmsValue*));

					int j;
					for (j = 0; j < componentCount; j++) {
						value->value.structure.components[j] = mmsMsg_parseDataElement(
								response->listOfAccessResult.list.array[i]->choice.structure.list.array[j]);
					}
				}
				else if (presentType == AccessResult_PR_bitstring) {
					value = calloc(1, sizeof(MmsValue));
					value->type = MMS_BIT_STRING;
					int size = response->listOfAccessResult.list.array[i]->choice.bitstring.size;

					value->value.bitString.size = (size * 8)
					   - response->listOfAccessResult.list.array[i]->choice.bitstring.bits_unused;

					value->value.bitString.buf = malloc(size);
					memcpy(value->value.bitString.buf,
							response->listOfAccessResult.list.array[i]->choice.bitstring.buf, size);

				}
				else if (presentType == AccessResult_PR_integer) {
					long integerValue;
					asn_INTEGER2long(&response->listOfAccessResult.list.array[i]->choice.integer, &integerValue);
					value = MmsValue_newIntegerFromInt32((int32_t) integerValue);
				}
				else if (presentType == AccessResult_PR_floatingpoint) {
					int size = response->listOfAccessResult.list.array[i]->choice.floatingpoint.size;

					value = calloc(1, sizeof(MmsValue));
					value->type = MMS_FLOAT;

					if (size == 5) { /* FLOAT32 */
						value->value.floatingPoint.formatWidth = 32;
						value->value.floatingPoint.exponentWidth = response->listOfAccessResult.list.array[i]->choice.floatingpoint.buf[0];

						uint8_t* floatBuf = (response->listOfAccessResult.list.array[i]->choice.floatingpoint.buf + 1);

						value->value.floatingPoint.buf = malloc(4);

#ifdef ORDER_LITTLE_ENDIAN
							memcpyReverseByteOrder(value->value.floatingPoint.buf, floatBuf, 4);
#else
							memcpy(value->value.floatingPoint.buf, floatBuf, 4);
#endif

					}

					if (size == 9) { /* FLOAT64 */
						value->value.floatingPoint.formatWidth = 64;
						value->value.floatingPoint.exponentWidth = response->listOfAccessResult.list.array[i]->choice.floatingpoint.buf[0];

						uint8_t* floatBuf = (response->listOfAccessResult.list.array[i]->choice.floatingpoint.buf + 1);

						value->value.floatingPoint.buf = malloc(8);

#ifdef ORDER_LITTLE_ENDIAN
							memcpyReverseByteOrder(value->value.floatingPoint.buf, floatBuf, 8);
#else
							memcpy(value->value.floatingPoint.buf, floatBuf, 8);
#endif
					}

				}
				else if (presentType == AccessResult_PR_utctime) {
						value->type = MMS_UTC_TIME;
						memcpy(value->value.utcTime,
								response->listOfAccessResult.list.array[i]->choice.utctime.buf, 8);
				}
				else {
					printf("unknown type\n");
					retVal = MMS_ERROR;
				}

				if (elementCount > 1)
					MmsValue_setArrayElement(valueList, i, value);
			}
		}
		else {
			retVal = MMS_ERROR;
		}
	}
	else {
		retVal = MMS_ERROR;
	}

	asn_DEF_MmsPdu.free_struct(&asn_DEF_MmsPdu, mmsPdu, 0);

	if (valueList == NULL)
		valueList = value;

	return valueList;
}
MmsIndication
mmsClient_parseWriteMultipleItemsResponse(ByteBuffer* message, int itemCount, LinkedList* accessResults)
{
    MmsPdu_t* mmsPdu = 0;
    MmsIndication retVal =  MMS_OK;

    asn_dec_rval_t rval;

    rval = ber_decode(NULL, &asn_DEF_MmsPdu,
            (void**) &mmsPdu, ByteBuffer_getBuffer(message), ByteBuffer_getSize(message));

    if (rval.code != RC_OK) {
        retVal = MMS_ERROR;
        goto cleanUp;
    }

    if (DEBUG) xer_fprint(stdout, &asn_DEF_MmsPdu, mmsPdu);

    if (mmsPdu->present == MmsPdu_PR_confirmedResponsePdu) {

        if (mmsPdu->choice.confirmedResponsePdu.confirmedServiceResponse.present == ConfirmedServiceResponse_PR_write)
        {
            WriteResponse_t* response =
                    &(mmsPdu->choice.confirmedResponsePdu.confirmedServiceResponse.choice.write);

            if (response->list.count == itemCount) {

                int i;

                *accessResults = LinkedList_create();

                for (i = 0; i < itemCount; i++) {

                    MmsValue* value;

                    if (response->list.array[i]->present == WriteResponse__Member_PR_success) {
                        MmsDataAccessError error;
                        value = MmsValue_newDataAccessError(DATA_ACCESS_ERROR_SUCCESS);
                    }
                    else {
                        long errorCode;

                        asn_INTEGER2long(&response->list.array[i]->choice.failure, &errorCode);

                        value = MmsValue_newDataAccessError((MmsDataAccessError) errorCode);
                    }

                    LinkedList_add(*accessResults, (void*) value);
                }
            }
            else
                retVal = MMS_ERROR;

        }
        else {
            retVal = MMS_ERROR;
        }
    }
    else {
        retVal = MMS_ERROR;
    }


 cleanUp:
    asn_DEF_MmsPdu.free_struct(&asn_DEF_MmsPdu, mmsPdu, 0);

    return retVal;
}