Mercurial > hg > waaad
view waaad/message.c @ 381:3591d0486a2c
Allow NULL model in msg_new
author | Sebastien Decugis <sdecugis@nict.go.jp> |
---|---|
date | Tue, 26 May 2009 17:17:05 +0900 |
parents | e86dba02630a |
children | 316bb3f38d04 |
line wrap: on
line source
/********************************************************************************************************* * Software License Agreement (BSD License) * * Author: Sebastien Decugis <sdecugis@nict.go.jp> * * * * Copyright (c) 2009, WIDE Project and NICT * * All rights reserved. * * * * Redistribution and use of this software in source and binary forms, with or without modification, are * * permitted provided that the following conditions are met: * * * * * Redistributions of source code must retain the above * * copyright notice, this list of conditions and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above * * copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other * * materials provided with the distribution. * * * * * Neither the name of the WIDE Project or NICT nor the * * names of its contributors may be used to endorse or * * promote products derived from this software without * * specific prior written permission of WIDE Project and * * NICT. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************************************/ /* Messages module. * * This module allows to manipulate the msg_t and msg_avp_t structures that represents a Diameter message in memory. * See message.h and message-api.h for more information on the functions and types involved. */ #include "waaad-internal.h" #include <sys/param.h> /* These types are internal to this module. It represents the "real" content of msg_t and msg_avp_t objects. */ typedef enum { _MSG_MSG = 1, _MSG_AVP } _msg_objtype_t; /* The following structure is used to represent the chaining of AVPs in a message or a grouped AVP. */ typedef struct _msg_avp_chain { uti_list_t chaining; /* Chaining information at this level. */ uti_list_t children; /* sentinel for the children of this object */ _msg_objtype_t type; /* Type of this object, _MSG_MSG or _MSG_AVP */ rule_position_t pos; /* The position rule of this object, if any, otherwise 0. */ } _msg_avp_chain_t; /* Return the chain information from an AVP or MSG. Since it's the first field, we just cast */ #define _C(_x) ((_msg_avp_chain_t *)(_x)) /* Some details about chaining: * * A message is made of a header ( _msg_t ) and 0 or more AVPs (_msg_avp_t ). * The structure is a kind of tree, where some AVPs (grouped AVPs) can contain other AVPs. * Exemple: * msg * |-avp * |-gavp * | |-avp * | |-avp * | \-avp * |-avp * \-avp * * Each item (msg or avp) structure begins with a _msg_avp_chain_t structure. * The element at the top of the hierarchy (msg in our example) has all the fields of its "chaining" equal to the same value. * * All elements at the same level are linked by their "chaining" list. * The "children" list is the sentinel for the lists of children of this element. */ /* The following definitions are used to avoid programming errors. */ #define _MSG_MSG_EYEC (0x11355463) #define _MSG_AVP_EYEC (0x11355467) /* The following structure represents an AVP instance. */ typedef struct { _msg_avp_chain_t avp_chain; /* Chaining information of this AVP */ int avp_eyec; /* Must be equal to _MSG_AVP_EYEC */ dict_object_t *avp_model; /* If not NULL, pointer to the dictionary object of this avp */ msg_avp_data_t avp_public; /* AVP data that can be managed by extensions */ unsigned char *avp_source; /* If the message was parsed from a buffer, pointer to the AVP data start in the buffer. */ unsigned char *avp_rawdata; /* when the data can not be interpreted, the raw data is copied here. The header is not part of it. */ size_t avp_rawlen; /* The length of the raw buffer. */ avp_value_t avp_storage; /* To avoid many alloc/free, store the integer values here and set avp_public.avp_data to &storage */ int avp_mustfreeos; /* 1 if an octetstring is malloc'd in avp_storage and must be freed. */ } _msg_avp_t; /* Macro to compute the AVP header size */ #define AVPHDRSZ_NOVEND 8 #define AVPHDRSZ_VENDOR 12 #define GETAVPHDRSZ( _flag ) ((_flag & AVP_FLAG_VENDOR) ? AVPHDRSZ_VENDOR : AVPHDRSZ_NOVEND) /* Macro to cast a msg_avp_t */ #define _A(_x) ((_msg_avp_t *)(_x)) /* Check the type and eyecatcher */ #define CHECK_AVP(_x) ((_C(_x)->type == _MSG_AVP) && (_A(_x)->avp_eyec == _MSG_AVP_EYEC)) /* The following structure represents an instance of a message (command and children AVPs). */ typedef struct { _msg_avp_chain_t msg_chain; /* List of the AVPs in the message */ int msg_eyec; /* Must be equal to _MSG_MSG_EYEC */ dict_object_t *msg_model; /* If not NULL, pointer to the dictionary object of this message */ msg_data_t msg_public; /* Message data that can be managed by extensions. */ unsigned char * msg_rawbuffer; /* data buffer that was received, saved during msg_parse_buffer and freed in msg_parse_dict */ int msg_routable; /* Is this a routable message? (0: undef, 1: routable, 2: non routable) */ msg_t *msg_query; /* the associated query if the message is a received answer */ rt_dpl_t *msg_rtlist; /* Routing list for the query */ struct { void (*fct)(void *, msg_t **); void * data; } msg_cb; /* Callback to be called when an answer is received, if not NULL */ char * msg_src_id; /* Diameter Id of the peer this message was received from. This string is malloc'd and must be freed */ uint32_t msg_src_hash; /* Hash of the msg_src_id value */ } _msg_t; /* Macro to compute the message header size */ #define GETMSGHDRSZ() 20 /* Macro to cast a msg_avp_t */ #define _M(_x) ((_msg_t *)(_x)) /* Check the type and eyecatcher */ #define CHECK_MSG(_x) ((_C(_x)->type == _MSG_MSG) && (_M(_x)->msg_eyec == _MSG_MSG_EYEC)) #define VALIDATE_OBJ(_x) ( (CHECK_MSG(_x)) || (CHECK_AVP(_x)) ) /* Macro to validate a MSGFL_ value */ #define CHECK_MSGFL(_fl) ( ((_fl) & (- (MSGFL_MAX << 1) )) == 0 ) /* initial sizes of AVP from their types, in bytes. -1 for unknown sizes */ static int avp_value_sizes[] = { 0, /* AVP_TYPE_GROUPED: size is dynamic */ 0, /* AVP_TYPE_OCTETSTRING: size is dynamic */ 4, /* AVP_TYPE_INTEGER32: size is 32 bits */ 8, /* AVP_TYPE_INTEGER64: size is 64 bits */ 4, /* AVP_TYPE_UNSIGNED32: size is 32 bits */ 8, /* AVP_TYPE_UNSIGNED64: size is 64 bits */ 4, /* AVP_TYPE_FLOAT32: size is 32 bits */ 8 /* AVP_TYPE_FLOAT64: size is 64 bits */ }; #define CHECK_BASETYPE( _type ) ( (_type <= AVP_TYPE_MAX) && (_type >= 0) ) #define GETINITIALSIZE( _type, _vend ) (avp_value_sizes[ CHECK_BASETYPE(_type) ? _type : 0] + GETAVPHDRSZ(_vend)) static dict_object_t * dict_avp_OH = NULL; /* Origin-Host */ static dict_object_t * dict_avp_OR = NULL; /* Origin-Realm */ static dict_object_t * dict_avp_OSI = NULL; /* Origin-State-Id */ static dict_object_t * dict_avp_RC = NULL; /* Result-Code */ static dict_object_t * dict_avp_EM = NULL; /* Error-Message */ static dict_object_t * dict_avp_ERH = NULL; /* Error-Reporting-Host */ static dict_object_t * dict_avp_FAVP= NULL; /* Failed-AVP */ static dict_object_t * dict_avp_RR = NULL; /* Route-Record */ static uint32_t eteid; /* The next available end-to-end id */ static pthread_mutex_t eteid_lock = PTHREAD_MUTEX_INITIALIZER; /***************************************************************************************************************/ /* Initialize a _msg_avp_chain_t structure */ static void init_chain(_msg_avp_chain_t * chain, int type) { uti_list_init( &chain->chaining, (void *)chain); uti_list_init( &chain->children, (void *)chain); chain->type = type; } /* Initialize a new AVP object */ static void init_avp ( _msg_avp_t * avp ) { TRACE_ENTRY("%p", avp); memset(avp, 0, sizeof(_msg_avp_t)); init_chain( &avp->avp_chain, _MSG_AVP); avp->avp_eyec = _MSG_AVP_EYEC; } /* Initialize a new MSG object */ static void init_msg ( _msg_t * msg ) { TRACE_ENTRY("%p", msg); memset(msg, 0, sizeof(_msg_t)); init_chain( &msg->msg_chain, _MSG_MSG); msg->msg_eyec = _MSG_MSG_EYEC; } /* Destroy and free an AVP or message */ static int destroy_obj (_msg_avp_chain_t * obj ) { TRACE_ENTRY("%p", obj); /* Check the parameter is a valid object */ CHECK_PARAMS( VALIDATE_OBJ(obj) && IS_LIST_EMPTY( &obj->children ) ); /* Unlink this object if needed */ uti_list_unlink( &obj->chaining ); /* Free the octetstring if needed */ if ((obj->type == _MSG_AVP) && (_A(obj)->avp_mustfreeos == 1)) { free(_A(obj)->avp_storage.os.data); } /* Free the rawdata if needed */ if ((obj->type == _MSG_AVP) && (_A(obj)->avp_rawdata != NULL)) { free(_A(obj)->avp_rawdata); } if ((obj->type == _MSG_MSG) && (_M(obj)->msg_rawbuffer != NULL)) { free(_M(obj)->msg_rawbuffer); } if ((obj->type == _MSG_MSG) && (_M(obj)->msg_src_id != NULL)) { free(_M(obj)->msg_src_id); } /* free the object */ free(obj); return 0; } /***************************************************************************************************************/ /* Get and set some meta data for the messages */ /* Associate answers and queries */ int msg_answ_associate( msg_t * answer, msg_t * query ) { TRACE_ENTRY( "%p %p", answer, query ); CHECK_PARAMS( CHECK_MSG(answer) && CHECK_MSG(query) && (_M(answer)->msg_query == NULL ) ); _M(answer)->msg_query = query; return 0; } int msg_answ_getq( msg_t * answer, msg_t ** query ) { TRACE_ENTRY( "%p %p", answer, query ); CHECK_PARAMS( CHECK_MSG(answer) && query ); *query = _M(answer)->msg_query; return 0; } int msg_answ_detach( msg_t * answer ) { TRACE_ENTRY( "%p", answer ); CHECK_PARAMS( CHECK_MSG(answer) ); _M(answer)->msg_query = NULL; return 0; } /* Associate routing lists */ int msg_rt_associate( msg_t * msg, rt_dpl_t ** list ) { TRACE_ENTRY( "%p %p", msg, list ); CHECK_PARAMS( CHECK_MSG(msg) && list ); _M(msg)->msg_rtlist = *list; *list = NULL; return 0; } int msg_rt_get( msg_t * msg, rt_dpl_t ** list ) { TRACE_ENTRY( "%p %p", msg, list ); CHECK_PARAMS( CHECK_MSG(msg) && list ); *list = _M(msg)->msg_rtlist; _M(msg)->msg_rtlist = NULL; return 0; } /* Associate name of peer it was received from */ int msg_source_set( msg_t * msg, char * diamid, uint32_t hash, int add_rr ) { TRACE_ENTRY( "%p %p %x", msg, diamid, hash); /* Check we received a valid message */ CHECK_PARAMS( CHECK_MSG(msg) ); /* Cleanup any previous source */ free(_M(msg)->msg_src_id); _M(msg)->msg_src_id = NULL; /* If the request is to cleanup the source, we are done */ if (diamid == NULL) { _M(msg)->msg_src_hash = 0; return 0; } /* Otherwise save the new informations */ CHECK_MALLOC( _M(msg)->msg_src_id = strdup(diamid) ); _M(msg)->msg_src_hash = hash; if (add_rr) { avp_value_t val; msg_avp_t * avp = NULL; /* Add the Route-Record AVP */ CHECK_FCT( msg_avp_new( dict_avp_RR, 0, &avp ) ); memset(&val, 0, sizeof(val)); val.os.data = (unsigned char *)diamid; val.os.len = strlen(diamid); CHECK_FCT( msg_avp_setvalue( avp, &val ) ); CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) ); } /* done */ return 0; } int msg_source_get( msg_t * msg, char ** diamid, uint32_t *hash ) { TRACE_ENTRY( "%p %p %p", msg, diamid, hash); /* Check we received valid parameters */ CHECK_PARAMS( CHECK_MSG(msg) ); CHECK_PARAMS( diamid ); /* Copy the informations */ *diamid = _M(msg)->msg_src_id; if (hash) *hash = _M(msg)->msg_src_hash; /* done */ return 0; } /***************************************************************************************************************/ /* Insert an item in a list, ordered by positions. */ static void insert_in_list_pos(uti_list_t * sentinel, uti_list_t * item) { uti_list_t *li; TRACE_ENTRY("%p %p", sentinel, item); /* Do some sanity checkings */ ASSERT(_C(item->o)->pos); /* the item has a position set */ ASSERT(sentinel->head == sentinel); /* the sentinel is really a sentinel */ ASSERT(IS_LIST_EMPTY(item)); /* the item is not linked already */ /* Find the place where the item should be inserted. */ for (li = sentinel; (li->next != sentinel) && (_C(li->next->o)->pos <= _C(item->o)->pos); li = li->next); /* Now insert it here */ uti_list_insert_after(li, item); } /* Destroy an object and all its children */ static void destroy_tree(_msg_avp_chain_t * obj) { uti_list_t *rem; TRACE_ENTRY("%p", obj); /* Destroy any subtree */ while ( (rem = obj->children.next) != &obj->children) destroy_tree(_C(rem->o)); /* Then unlink and destroy the object */ CHECK_FCT_DO( destroy_obj(obj), /* nothing */ ); } /***************************************************************************************************************/ /* We use this structure to pass arguments to create_child_avp when called in dict_iterate_rules */ typedef struct { _msg_avp_chain_t * parent; int flags; } cb_data_t; /* For each rule of a parent object, this function is called. This is part of the process of creations from templates */ static int create_child_avp(void *data, dict_rule_data_t *rule) { int i; cb_data_t *_data = (cb_data_t *)data; TRACE_ENTRY("%p %p", data, rule); /* Create as many children as the template says */ for (i=0; i<rule->rule_template; i++) { msg_avp_t * child = NULL; /* Create the child AVP -- eventually a tree of AVPs */ CHECK_FCT( msg_avp_new(rule->rule_avp, _data->flags, &child) ); /* If no error occurred, link this child into the parent's hierarchy */ _C(child)->pos = rule->rule_position; insert_in_list_pos(&(_data->parent->children), &(_C(child)->chaining)); } /* We're done with this rule entry */ return 0; } /***************************************************************************************************************/ /* Debug functions: dumping */ /* indentation inside an object */ #define INOBJHDR "%*s " #define INOBJHDRVAL indent<0 ? 1 : indent, indent<0 ? "-" : "|" /* Dump a msg_t object */ static void obj_dump_msg (_msg_t * msg, int indent ) { int ret = 0; log_debug("%*sMSG: %p\n", INOBJHDRVAL, msg); if (!CHECK_MSG(msg)) { log_debug(INOBJHDR "INVALID!\n", INOBJHDRVAL); return; } if (!msg->msg_model) { log_debug(INOBJHDR "(no model)\n", INOBJHDRVAL); } else { dict_object_type_t dicttype; dict_cmd_data_t dictdata; ret = dict_gettype(msg->msg_model, &dicttype); if (ret || (dicttype != DICT_COMMAND)) { log_debug(INOBJHDR "(invalid model: %d %d)\n", INOBJHDRVAL, ret, dicttype); goto public; } ret = dict_getval(msg->msg_model, &dictdata); if (ret != 0) { log_debug(INOBJHDR "(error getting model data: %s)\n", INOBJHDRVAL, strerror(ret)); goto public; } log_debug(INOBJHDR "model : v/m:" DUMP_CMDFL_str "/" DUMP_CMDFL_str ", %u \"%s\"\n", INOBJHDRVAL, DUMP_CMDFL_val(dictdata.cmd_flag_val), DUMP_CMDFL_val(dictdata.cmd_flag_mask), dictdata.cmd_code, dictdata.cmd_name); } public: log_debug(INOBJHDR "public: V:%d L:%d fl:" DUMP_CMDFL_str " CC:%u A:%d hi:%x ei:%x\n", INOBJHDRVAL, msg->msg_public.msg_version, msg->msg_public.msg_length, DUMP_CMDFL_val(msg->msg_public.msg_flags), msg->msg_public.msg_code, msg->msg_public.msg_appl, msg->msg_public.msg_hbhid, msg->msg_public.msg_eteid ); log_debug(INOBJHDR "intern: rwb:%p rt:%d cb:%p(%p) qry:%p h:%x src:%s\n", INOBJHDRVAL, msg->msg_rawbuffer, msg->msg_routable, msg->msg_cb.fct, msg->msg_cb.data, msg->msg_query, msg->msg_src_hash, msg->msg_src_id?:"(nil)"); } #define DUMP_VALUE(_format, _parms...) log_debug(INOBJHDR "value : t:'%s' v:'" _format "'\n", INOBJHDRVAL, typename, ## _parms); /* Dump an AVP value that is not a constant */ static void dump_basic_type(avp_value_t * value, dict_base_type_t type, char * typename, int indent) { switch (type) { case AVP_TYPE_GROUPED: DUMP_VALUE("%s", "error: grouped AVP with a value!"); break; case AVP_TYPE_OCTETSTRING: { /* Dump only up to 16 bytes of the buffer */ unsigned char buf[16]; memset(buf, 0, sizeof(buf)); memcpy(buf, value->os.data, value->os.len < sizeof(buf)-1 ? value->os.len : sizeof(buf)-1 ); DUMP_VALUE("l:%d, v:%02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X " "%02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X %02.2X ... (%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c...)", value->os.len, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15], ASCII(buf[0]), ASCII(buf[1]), ASCII(buf[2]), ASCII(buf[3]), ASCII(buf[4]), ASCII(buf[5]), ASCII(buf[6]), ASCII(buf[7]), ASCII(buf[8]), ASCII(buf[9]), ASCII(buf[10]), ASCII(buf[11]), ASCII(buf[12]), ASCII(buf[13]), ASCII(buf[14]), ASCII(buf[15]) ); } break; case AVP_TYPE_INTEGER32: DUMP_VALUE("%i",value->i32); break; case AVP_TYPE_INTEGER64: DUMP_VALUE("%lli (0x%llx)",value->i64,value->i64); break; case AVP_TYPE_UNSIGNED32: DUMP_VALUE("%u",value->u32); break; case AVP_TYPE_UNSIGNED64: DUMP_VALUE("%llu",value->u64); break; case AVP_TYPE_FLOAT32: DUMP_VALUE("%f",value->f32); break; case AVP_TYPE_FLOAT64: DUMP_VALUE("%g",value->f64); break; default: DUMP_VALUE("%s %d", "error: invalid type :", type); } } /* Dump an AVP value that is a constant */ #define DUMP_CONST(_format, _parms...) log_debug(INOBJHDR "value : t:'%s' v:'%s' ( " _format " )\n", INOBJHDRVAL, typename, value->enum_name, ## _parms); static void dump_constant_type(dict_type_enum_data_t * value, dict_base_type_t type, char * typename, int indent) { switch (type) { case AVP_TYPE_GROUPED: DUMP_CONST("%s", "error: grouped AVP with a constant value!"); break; case AVP_TYPE_OCTETSTRING: DUMP_CONST("%s", "value skipped"); break; case AVP_TYPE_INTEGER32: DUMP_CONST("%i",value->enum_value.i32); break; case AVP_TYPE_INTEGER64: DUMP_CONST("%li",value->enum_value.i64); break; case AVP_TYPE_UNSIGNED32: DUMP_CONST("%u",value->enum_value.u32); break; case AVP_TYPE_UNSIGNED64: DUMP_CONST("%lu",value->enum_value.u64); break; case AVP_TYPE_FLOAT32: DUMP_CONST("%f",value->enum_value.f32); break; case AVP_TYPE_FLOAT64: DUMP_CONST("%g",value->enum_value.f64); break; default: DUMP_CONST("%s %d", "error: invalid type :", type); } } /* Dump a msg_avp_t object */ static void obj_dump_avp ( _msg_avp_t * avp, int indent ) { int ret = 0; dict_base_type_t type = -1; if (!CHECK_AVP(avp)) { log_debug(INOBJHDR "INVALID!\n", INOBJHDRVAL); return; } if (!avp->avp_model) { log_debug(INOBJHDR "(no model)\n", INOBJHDRVAL); } else { dict_object_type_t dicttype; dict_avp_data_t dictdata; ret = dict_gettype(avp->avp_model, &dicttype); if (ret || (dicttype != DICT_AVP)) { log_debug(INOBJHDR "(invalid model: %d %d)\n", INOBJHDRVAL, ret, dicttype); goto public; } ret = dict_getval(avp->avp_model, &dictdata); if (ret != 0) { log_debug(INOBJHDR "(error getting model data: %s)\n", INOBJHDRVAL, strerror(ret)); goto public; } log_debug(INOBJHDR "model : v/m:" DUMP_AVPFL_str "/" DUMP_AVPFL_str ", %12s, %u \"%s\"\n", INOBJHDRVAL, DUMP_AVPFL_val(dictdata.avp_flag_val), DUMP_AVPFL_val(dictdata.avp_flag_mask), type_base_name[dictdata.avp_basetype], dictdata.avp_code, dictdata.avp_name ); type = dictdata.avp_basetype; } public: log_debug(INOBJHDR "public: C:%u fl:" DUMP_AVPFL_str " L:%d V:%u data:@%p\n", INOBJHDRVAL, avp->avp_public.avp_code, DUMP_AVPFL_val(avp->avp_public.avp_flags), avp->avp_public.avp_len, avp->avp_public.avp_vendor, avp->avp_public.avp_data ); /* Dump the value if set */ if (avp->avp_public.avp_data) { if (!avp->avp_model) { log_debug(INOBJHDR "(data set but no model: ERROR)\n", INOBJHDRVAL); } else { /* Try and find a constant name for this value */ dict_object_t * avp_type = NULL; dict_object_t * avp_constant = NULL; dict_type_data_t type_data; dict_type_enum_request_t request; ret = dict_search(DICT_TYPE, TYPE_OF_AVP, avp->avp_model, &avp_type); if ((ret != 0) || (avp_type == NULL)) { dump_basic_type(avp->avp_public.avp_data, type, type_base_name[type], indent); goto end; } ret = dict_getval(avp_type, &type_data); if (ret != 0) { dump_basic_type(avp->avp_public.avp_data, type, "(error getting type data)", indent); goto end; } if (type_data.type_base != type) { dump_basic_type(avp->avp_public.avp_data, type, "(mismatching type information!)", indent); goto end; } /* Create a query for a constant */ memset(&request, 0, sizeof(request)); request.type_obj = avp_type; memcpy(&request.search.enum_value, avp->avp_public.avp_data, sizeof(avp_value_t)); ret = dict_search(DICT_TYPE_ENUM, ENUM_BY_STRUCT, &request, &avp_constant); if ((ret != 0) || (avp_constant == NULL)) { dump_basic_type(avp->avp_public.avp_data, type, type_data.type_name, indent); goto end; } /* get the constant's information; we re-use request.search field */ ret = dict_getval(avp_constant, &request.search); if (ret != 0) { dump_basic_type(avp->avp_public.avp_data, type, "(error getting constant data)", indent); goto end; } dump_constant_type(&request.search, type, type_data.type_name, indent); } } end: log_debug(INOBJHDR "intern: src:%p mf:%d raw:%p(%d)\n", INOBJHDRVAL, avp->avp_source, avp->avp_mustfreeos, avp->avp_rawdata, avp->avp_rawlen); } /* Dump a single object content */ static void msg_dump_intern ( int level, void * obj, int indent ) { /* Log only if we are at least at level */ if ( ! TRACE_BOOL(level) ) return; /* Check the object */ if (!VALIDATE_OBJ(obj)) { log_debug( ">>> invalid object (%p)!.\n", obj); return; } /* Dump the object */ switch (_C(obj)->type) { case _MSG_AVP: obj_dump_avp ( _A(obj), indent ); break; case _MSG_MSG: obj_dump_msg ( _M(obj), indent ); break; default: assert(0); } } /***************************************************************************************************************/ /* Creating a buffer from memory objects */ /* Following macros are used to store 32 and 64 bit fields into a buffer in network byte order */ #define PUT_in_buf_32( _u32data, _bufptr ) { \ *(uint32_t *)(_bufptr) = htonl((uint32_t)(_u32data)); \ } #define PUT_in_buf_64( _u64data, _bufptr ) { \ *(uint64_t *)(_bufptr) = htonll((uint64_t)(_u64data)); \ } /* Write a message header in the buffer */ static int _msg_buf_msg(unsigned char * buffer, size_t buflen, size_t * offset, _msg_t * msg) { TRACE_ENTRY("%p %d %p %p", buffer, buflen, offset, msg); if ((buflen - *offset) < GETMSGHDRSZ()) return ENOSPC; if (*offset & 0x3) return EFAULT; /* We are supposed to start on 32 bit boundaries */ PUT_in_buf_32(msg->msg_public.msg_length, buffer + *offset); buffer[*offset] = msg->msg_public.msg_version; *offset += 4; PUT_in_buf_32(msg->msg_public.msg_code, buffer + *offset); buffer[*offset] = msg->msg_public.msg_flags; *offset += 4; PUT_in_buf_32(msg->msg_public.msg_appl, buffer + *offset); *offset += 4; PUT_in_buf_32(msg->msg_public.msg_hbhid, buffer + *offset); *offset += 4; PUT_in_buf_32(msg->msg_public.msg_eteid, buffer + *offset); *offset += 4; return 0; } static int _msg_buf_chain(unsigned char * buffer, size_t buflen, size_t * offset, uti_list_t * list); /* Write an AVP in the buffer */ static int _msg_buf_avp(unsigned char * buffer, size_t buflen, size_t * offset, _msg_avp_t * avp) { dict_avp_data_t dictdata; TRACE_ENTRY("%p %d %p %p", buffer, buflen, offset, avp); if ((buflen - *offset) < avp->avp_public.avp_len) return ENOSPC; /* Write the header */ PUT_in_buf_32(avp->avp_public.avp_code, buffer + *offset); *offset += 4; PUT_in_buf_32(avp->avp_public.avp_len, buffer + *offset); buffer[*offset] = avp->avp_public.avp_flags; *offset += 4; if (avp->avp_public.avp_flags & AVP_FLAG_VENDOR) { PUT_in_buf_32(avp->avp_public.avp_vendor, buffer + *offset); *offset += 4; } /* Then we must write the AVP value */ if (avp->avp_model == NULL) { /* In the case where we don't know the type of AVP, just copy the raw data or source */ CHECK_PARAMS( avp->avp_source || avp->avp_rawdata ); if ( avp->avp_source != NULL ) { /* the message was not parsed completely */ size_t datalen = avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags); memcpy(&buffer[*offset], avp->avp_source, datalen); *offset += PAD4(datalen); } else { /* the content is stored in rawdata */ memcpy(&buffer[*offset], avp->avp_rawdata, avp->avp_rawlen); *offset += PAD4(avp->avp_rawlen); } } else { /* The AVP is defined in the dictionary */ CHECK_FCT( dict_getval(avp->avp_model, &dictdata) ); switch (dictdata.avp_basetype) { case AVP_TYPE_GROUPED: return _msg_buf_chain(buffer, buflen, offset, &_C(avp)->children); case AVP_TYPE_OCTETSTRING: memcpy(&buffer[*offset], avp->avp_public.avp_data->os.data, avp->avp_public.avp_data->os.len); *offset += PAD4(avp->avp_public.avp_data->os.len); break; case AVP_TYPE_INTEGER32: PUT_in_buf_32(avp->avp_public.avp_data->i32, buffer + *offset); *offset += 4; break; case AVP_TYPE_INTEGER64: PUT_in_buf_64(avp->avp_public.avp_data->i64, buffer + *offset); *offset += 8; break; case AVP_TYPE_UNSIGNED32: PUT_in_buf_32(avp->avp_public.avp_data->u32, buffer + *offset); *offset += 4; break; case AVP_TYPE_UNSIGNED64: PUT_in_buf_64(avp->avp_public.avp_data->u64, buffer + *offset); *offset += 8; break; case AVP_TYPE_FLOAT32: /* We read the f32 as "u32" here to avoid casting to uint make decimals go away. The alternative would be something like "*(uint32_t *)(& f32)" but then the compiler complains about strict-aliasing rules. */ PUT_in_buf_32(avp->avp_public.avp_data->u32, buffer + *offset); *offset += 4; break; case AVP_TYPE_FLOAT64: /* Same remark as previously */ PUT_in_buf_64(avp->avp_public.avp_data->u64, buffer + *offset); *offset += 8; break; default: ASSERT(0); } } return 0; } /* Write a chain of AVPs in the buffer */ static int _msg_buf_chain(unsigned char * buffer, size_t buflen, size_t * offset, uti_list_t * list) { uti_list_t * avpch; TRACE_ENTRY("%p %d %p %p", buffer, buflen, offset, list); for (avpch = list->next; avpch != list; avpch = avpch->next) { /* Bufferize the AVP */ CHECK_FCT( _msg_buf_avp(buffer, buflen, offset, _A(avpch->o)) ); } return 0; } /***************************************************************************************************************/ /* Parsing buffers and building AVP objects lists */ /* note: the _mpb prefix stands for "msg_parse_buffer" */ /* Parse a buffer containing a supposed list of AVPs */ static int _mpb_list(unsigned char * buf, size_t buflen, uti_list_t * head) { size_t offset = 0; TRACE_ENTRY("%p %d %p", buf, buflen, head); while (offset < buflen) { _msg_avp_t * avp; if (buflen - offset <= AVPHDRSZ_NOVEND) { TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes", buflen - offset); return EBADMSG; } /* Create a new AVP object */ CHECK_MALLOC( avp = (_msg_avp_t *) malloc (sizeof(_msg_avp_t)) ); init_avp(avp); /* Initialize the header */ avp->avp_public.avp_code = ntohl(*(uint32_t *)(buf + offset)); avp->avp_public.avp_flags = buf[offset + 4]; avp->avp_public.avp_len = ((uint32_t)buf[offset+5]) << 16 | ((uint32_t)buf[offset+6]) << 8 | ((uint32_t)buf[offset+7]) ; offset += 8; if (avp->avp_public.avp_flags & AVP_FLAG_VENDOR) { if (buflen - offset <= 4) { TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes for vendor and data", buflen - offset); free(avp); return EBADMSG; } avp->avp_public.avp_vendor = ntohl(*(uint32_t *)(buf + offset)); offset += 4; } /* Check there is enough remaining data in the buffer */ if (buflen - offset < avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags)) { TRACE_DEBUG(INFO, "truncated buffer: remaining only %d bytes for data, and avp data size is %d", buflen - offset, avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags)); free(avp); return EBADMSG; } /* buf[offset] is now the beginning of the data */ avp->avp_source = &buf[offset]; /* Now eat the data and eventual padding */ offset += PAD4(avp->avp_public.avp_len - GETAVPHDRSZ(avp->avp_public.avp_flags)); /* And insert this avp in the list, at the end */ uti_list_insert_before( head, &_C(avp)->chaining ); } return 0; } /***************************************************************************************************************/ /* Parsing messages and AVP for dictionary compliance */ /* Resolve dictionary objects of the cmd and avp instances, from their headers. * When the model is found, the data is interpreted from the avp_source buffer and copied to avp_storage. * When the model is not found, the raw data is copied and saved. * Therefore, after this function has been called, the source buffer can be freed. * For command, if the dictionary model is not found, an error is returned. */ /* note: the _mpd prefix stands for "msg_parse_dict" */ static int _mpd_do_chain(uti_list_t * head, int recheck, int mandatory); /* Process an AVP. If we are not in recheck, the avp_source must be set. */ static int _mpd_do_avp(_msg_avp_t * avp, int recheck, int mandatory) { dict_avp_data_t dictdata; TRACE_ENTRY("%p %d %d", avp, recheck, mandatory); /* First check we received an AVP as input */ CHECK_PARAMS( CHECK_AVP(avp) && ( recheck || (avp->avp_model == NULL)) ); if (avp->avp_model != NULL) { /* the model has already been resolved. we do check it is still valid */ CHECK_FCT( dict_getval(avp->avp_model, &dictdata) ); CHECK_PARAMS( avp->avp_public.avp_code == dictdata.avp_code ); /* Ok then just process the children if any */ return _mpd_do_chain(&_C(avp)->children, recheck, mandatory && (avp->avp_public.avp_flags & AVP_FLAG_MANDATORY)); } /* Now try and resolve the model from the avp code and vendor */ if (avp->avp_public.avp_flags & AVP_FLAG_VENDOR) { dict_avp_request_t avpreq; avpreq.avp_vendor = avp->avp_public.avp_vendor; avpreq.avp_code = avp->avp_public.avp_code; CHECK_FCT( dict_search ( DICT_AVP, AVP_BY_CODE_AND_VENDOR, &avpreq, &avp->avp_model)); } else { /* no vendor */ CHECK_FCT( dict_search ( DICT_AVP, AVP_BY_CODE_REF, &avp->avp_public.avp_code, &avp->avp_model)); } /* First handle the case where we have not found this AVP in the dictionary */ if (!avp->avp_model) { if (mandatory && (avp->avp_public.avp_flags & AVP_FLAG_MANDATORY)) { TRACE_DEBUG(INFO, "Unsupported mandatory AVP found:"); msg_dump_intern(INFO, avp, 2); return ENOTSUP; } if (avp->avp_source) { /* we must copy the data from the source to the internal buffer area */ CHECK_PARAMS( !avp->avp_rawdata ); avp->avp_rawlen = avp->avp_public.avp_len - GETAVPHDRSZ( avp->avp_public.avp_flags ); CHECK_MALLOC( avp->avp_rawdata = malloc(avp->avp_rawlen) ); memcpy(avp->avp_rawdata, avp->avp_source, avp->avp_rawlen); avp->avp_source = NULL; TRACE_DEBUG(FULL, "Unsupported optional AVP found, raw source data saved in avp_rawdata."); } CHECK_PARAMS( avp->avp_rawdata ); return 0; } /* Ok we have resolved the object. Now we need to interpret its content. */ CHECK_FCT( dict_getval(avp->avp_model, &dictdata) ); if (recheck && avp->avp_rawdata) { /* This happens if the dictionary object was defined after the first check */ avp->avp_source = avp->avp_rawdata; } /* A bit of sanity here... */ ASSERT(CHECK_BASETYPE(dictdata.avp_basetype)); /* Check the size is valid */ if ((avp_value_sizes[dictdata.avp_basetype] != 0) && (avp->avp_public.avp_len - GETAVPHDRSZ( avp->avp_public.avp_flags ) != avp_value_sizes[dictdata.avp_basetype])) { TRACE_DEBUG(INFO, "The AVP size is not conform to the type. EBADMSG."); return EBADMSG; } /* Now get the value inside */ switch (dictdata.avp_basetype) { case AVP_TYPE_GROUPED: /* This is a grouped AVP, so let's parse the list of AVPs inside */ CHECK_FCT( _mpb_list(avp->avp_source, avp->avp_public.avp_len - GETAVPHDRSZ( avp->avp_public.avp_flags ), &_C(avp)->children) ); return _mpd_do_chain(&_C(avp)->children, 0, mandatory && (avp->avp_public.avp_flags & AVP_FLAG_MANDATORY)); case AVP_TYPE_OCTETSTRING: /* We just have to copy the string into the storage area */ CHECK_PARAMS( avp->avp_public.avp_len > GETAVPHDRSZ( avp->avp_public.avp_flags ) ); avp->avp_storage.os.len = avp->avp_public.avp_len - GETAVPHDRSZ( avp->avp_public.avp_flags ); CHECK_MALLOC( avp->avp_storage.os.data = malloc(avp->avp_storage.os.len) ); avp->avp_mustfreeos = 1; memcpy(avp->avp_storage.os.data, avp->avp_source, avp->avp_storage.os.len); break; case AVP_TYPE_INTEGER32: avp->avp_storage.i32 = (int32_t)ntohl(*(uint32_t *)avp->avp_source); break; case AVP_TYPE_INTEGER64: avp->avp_storage.i64 = (int64_t)ntohll(*(uint64_t *)avp->avp_source); break; case AVP_TYPE_UNSIGNED32: case AVP_TYPE_FLOAT32: /* For float, we must not cast, or the value is changed. Instead we use implicit cast by changing the member of the union */ avp->avp_storage.u32 = (uint32_t)ntohl(*(uint32_t *)avp->avp_source); break; case AVP_TYPE_UNSIGNED64: case AVP_TYPE_FLOAT64: /* same as 32 bits */ avp->avp_storage.u64 = (uint64_t)ntohll(*(uint64_t *)avp->avp_source); break; } /* The value is now set, so set the data pointer and return 0 */ avp->avp_public.avp_data = &avp->avp_storage; return 0; } /* Process a list of AVPs */ static int _mpd_do_chain(uti_list_t * head, int recheck, int mandatory) { uti_list_t * avpch; TRACE_ENTRY("%p %d %d", head, recheck, mandatory); /* Sanity check */ ASSERT ( head == head->head ); /* Now process the list */ for (avpch=head->next; avpch != head; avpch = avpch->next) { CHECK_FCT( _mpd_do_avp(_A(avpch->o), recheck, mandatory) ); } /* Done */ return 0; } /* Process a msg header. */ static int _mpd_do_msg(_msg_t * msg, int recheck, int only_msg) { int ret = 0; TRACE_ENTRY("%p %d %d", msg, recheck, only_msg); CHECK_PARAMS( CHECK_MSG(msg) ); if (recheck) msg->msg_model = NULL; if ( msg->msg_model == NULL ) { /* Now look for the model from the header */ CHECK_FCT( dict_search ( DICT_COMMAND, (msg->msg_public.msg_flags & CMD_FLAG_REQUEST) ? CMD_BY_CODE_R_REF : CMD_BY_CODE_A_REF, &msg->msg_public.msg_code, &msg->msg_model) ); if (!msg->msg_model) { CHECK_FCT(ENOTSUP); /* log and return this code */ } } if (!only_msg) { /* Then process the children */ ret = _mpd_do_chain(&_C(msg)->children, recheck, 1); /* Free the raw buffer if any */ if ((ret == 0) && (msg->msg_rawbuffer != NULL)) { free(msg->msg_rawbuffer); msg->msg_rawbuffer=NULL; } } return ret; } static int _mpd_do(_msg_avp_chain_t * obj, int recheck) { TRACE_ENTRY("%p %d", obj, recheck); CHECK_PARAMS( VALIDATE_OBJ(obj) ); switch (_C(obj)->type) { case _MSG_MSG: return _mpd_do_msg(_M(obj), recheck, 0); case _MSG_AVP: return _mpd_do_avp(_A(obj), recheck, 0); default: ASSERT(0); } return EINVAL; } /***************************************************************************************************************/ /* Parsing messages and AVP for rule compliance */ /* note: the _mpr prefix stands for "msg_parse_rule" */ /* This function is used to get stats (first occurence position, last occurence position, number of occurences) on AVP instances of a given model in a chain of AVP */ static void _mpr_stat_avps( dict_object_t * model_avp, uti_list_t *list, int * count, int * firstpos, int * lastpos) { uti_list_t * li; int curpos = 0; /* The current position in the list */ TRACE_ENTRY("%p %p %p %p %p", model_avp, list, count, firstpos, lastpos); *count = 0; /* number of instances found */ *firstpos = 0; /* position of the first instance */ *lastpos = 0; /* position of the last instance, starting from the end */ for (li = list->next; li != list; li = li->next) { /* Increment the current position counter */ curpos++; /* If we previously saved a "lastpos" information, increment it */ if (*lastpos != 0) (*lastpos)++; /* Check the type of the next AVP. We can compare the references directly, it is safe. */ if (_A(li->o)->avp_model == model_avp) { /* This AVP is of the type we are searching */ (*count)++; /* If we don't have yet a "firstpos", save it */ if (*firstpos == 0) *firstpos = curpos; /* Reset the lastpos */ (*lastpos) = 1; } } } /* Type of the "void *" pointer passed to the _msg_check_rule function by dict_iterate_rules */ typedef struct { uti_list_t * sentinel; /* Sentinel of the list of children AVP */ dict_object_t * ruleavp; /* If the rule conflicts, save it's rule_avp here (we don't have direct access to the rule) */ } _mpr_t; /* Check that a list of AVPs is compliant with a given rule */ static int _mpr_check_rule(void * data, dict_rule_data_t *rule) { int ret = 0, count, first, last, min; _mpr_t * _data = (_mpr_t *) data; TRACE_ENTRY("%p %p", data, rule); /* Get statistics of the AVP concerned by this rule in the message instance */ _mpr_stat_avps( rule->rule_avp, _data->sentinel, &count, &first, &last); { dict_avp_data_t avpdata; ret = dict_getval(rule->rule_avp, &avpdata); TRACE_DEBUG(ANNOYING, "Checking rule: p:%d(%d) m/M/t:%2d/%2d/%d. Counted %d (first: %d, last:%d) of AVP '%s'", rule->rule_position, rule->rule_order, rule->rule_min, rule->rule_max, rule->rule_template, count, first, last, (ret == 0) ? avpdata.avp_name : "???" ); } /* Now check the rule is not conflicting */ ret = 0; /* Check the "min" value */ if ((min = rule->rule_min) == -1) { if (rule->rule_position == RULE_OPTIONAL) min = 0; else min = 1; } if (count < min) { TRACE_DEBUG(INFO, "Conflicting rule: the number of occurences (%d) is < the rule min (%d).", count, min); ret = EBADMSG; goto end; } /* Check the "max" value */ if ((rule->rule_max != -1) && (count > rule->rule_max)) { TRACE_DEBUG(INFO, "Conflicting rule: the number of occurences (%d) is > the rule max (%d).", count, rule->rule_max); ret = EBADMSG; goto end; } /* Check the position and order (if relevant) */ switch (rule->rule_position) { case RULE_OPTIONAL: case RULE_REQUIRED: /* No special position constraints */ break; case RULE_FIXED_HEAD: /* Since "0*1<fixed>" is a valid rule specifier, we only reject cases where the AVP appears *after* its fixed position */ if (first > rule->rule_order) { TRACE_DEBUG(INFO, "Conflicting rule: the FIXED_HEAD AVP appears first in (%d) position, the rule requires (%d).", first, rule->rule_order); ret = EBADMSG; goto end; } break; case RULE_FIXED_TAIL: /* Since "0*1<fixed>" is a valid rule specifier, we only reject cases where the AVP appears *before* its fixed position */ if (last > rule->rule_order) { /* We have a ">" here because we count in reverse order (i.e. from the end) */ TRACE_DEBUG(INFO, "Conflicting rule: the FIXED_TAIL AVP appears last in (%d) position, the rule requires (%d).", last, rule->rule_order); ret = EBADMSG; goto end; } break; default: /* What is this position ??? */ ASSERT(0); ret = ENOTSUP; } /* We've checked all the parameters */ end: if (ret == EBADMSG) { _data->ruleavp = rule->rule_avp; } return ret; } /* The recursive version of msg_parse_rules */ static int _mpr_do ( void * object, dict_object_t ** rule, int mandatory) { int ret = 0; _mpr_t data; dict_object_t * model = NULL; TRACE_ENTRY("%p %p %d", object, rule, mandatory); /* object has already been checked and dict-parsed when we are called. */ /* First, handle the cases where there is no model */ { if (CHECK_MSG(object)) { if ( _M(object)->msg_public.msg_flags & CMD_FLAG_ERROR ) { /* The case of error messages: the ABNF is different */ model = dict_cmd_error; } else { model = _M(object)->msg_model; } /* Commands MUST be supported in the dictionary */ if (model == NULL) { TRACE_DEBUG(INFO, "Message with no dictionary model. EBADMSG"); return EBADMSG; } } /* AVP with the 'M' flag must also be recognized in the dictionary -- except inside an optional grouped AVP */ if (CHECK_AVP(object) && ((model = _A(object)->avp_model) == NULL)) { if ( mandatory && (_A(object)->avp_public.avp_flags & AVP_FLAG_MANDATORY)) { /* Return an error in this case */ TRACE_DEBUG(INFO, "Mandatory AVP with no dictionary model. EBADMSG"); return EBADMSG; } else { /* We don't know any rule for this object, so assume OK */ TRACE_DEBUG(FULL, "Unknown informational AVP, ignoring..."); return 0; } } } /* Now "model" is set and points to the object's model */ /* If we are an AVP with no children, just return OK */ if (CHECK_AVP(object)) { dict_avp_data_t dictdata; CHECK_FCT( dict_getval(model, &dictdata) ); if (dictdata.avp_basetype != AVP_TYPE_GROUPED) { /* This object has no children and no rules */ return 0; } } /* If this object has children, first check the rules for all its children */ { int is_child_mand = 0; uti_list_t * ch = NULL; if ( CHECK_MSG(object) || (mandatory && (_A(object)->avp_public.avp_flags & AVP_FLAG_MANDATORY)) ) is_child_mand = 1; for (ch = _C(object)->children.next; ch != &_C(object)->children; ch = ch->next) { CHECK_FCT( _mpr_do ( _C(ch->o), rule, is_child_mand ) ); } } /* Now check all rules of this object */ data.sentinel = &_C(object)->children; data.ruleavp = NULL; ret = dict_iterate_rules ( model, &data, _mpr_check_rule ); /* Save the reference to the eventual conflicting rule; otherwise set to NULL */ if (rule && data.ruleavp) { /* data.ruleavp contains the AVP, and model is the parent */ dict_object_t * conflictrule = NULL; dict_rule_request_t req = { model, data.ruleavp }; CHECK_FCT_DO( dict_search ( DICT_RULE, RULE_BY_AVP_AND_PARENT, &req, &conflictrule), conflictrule = NULL ); *rule = conflictrule; } return ret; } /***************************************************************************************************************/ /* Functions exported to other files in the daemon. More information in message.h */ /* Dump a message content -- for debug mostly */ void msg_dump_walk ( int level, void * obj ) { void * ref = obj; int indent = 1; TRACE_DEBUG(level, "------ Dumping object %p (w)-------\n", obj); do { msg_dump_intern ( level, ref, indent ); /* Now find the next object */ CHECK_FCT_DO( msg_browse ( ref, MSG_BRW_WALK, &ref, &indent ), break ); /* dump next object */ } while (ref); TRACE_DEBUG(level, "------ /end of object %p -------\n", obj); } /* Dump a single object content -- for debug mostly */ void msg_dump_one ( int level, void * obj ) { TRACE_DEBUG(level, "------ Dumping object %p (s)-------\n", obj); msg_dump_intern ( level, obj, 1 ); TRACE_DEBUG(level, "------ /end of object %p -------\n", obj); } /* Initialize the module */ int msg_init ( void ) { TRACE_ENTRY(""); /* Initialize the dictionary objects that we may use frequently */ CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Origin-Host", &dict_avp_OH ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Origin-Realm", &dict_avp_OR ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Origin-State-Id", &dict_avp_OSI ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Result-Code", &dict_avp_RC ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Error-Message", &dict_avp_EM ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Error-Reporting-Host", &dict_avp_ERH ) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Failed-AVP", &dict_avp_FAVP) ); CHECK_FCT( dict_search( DICT_AVP, AVP_BY_NAME, "Route-Record", &dict_avp_RR ) ); /* The End-to-end id */ eteid = ((uint32_t)time(NULL) << 20) | ((uint32_t)lrand48() & ( (1 << 20) - 1 )); return 0; } /* End of the module */ int msg_fini ( void ) { TRACE_ENTRY(""); /* Nothing to do here */ return 0; } /* Resolve dictionary objects of message instances. See _mpd_* functions in this file. */ int msg_parse_dict ( msg_t * msg ) { TRACE_ENTRY("%p", msg); return _mpd_do(_C(msg), 0); } /* Idem, for one AVP. */ int msg_parse_dict_avp ( msg_avp_t * avp ) { TRACE_ENTRY("%p", avp); return _mpd_do(_C(avp), 1); } /***************************************************************************************************************/ /* The API functions. See more information on these functions in message-api.h file. */ /* Create a new message instance */ int msg_new ( dict_object_t * model, int flags, msg_t ** msg ) { int ret=0; _msg_t *new = NULL; dict_object_type_t dicttype; dict_cmd_data_t dictdata; dict_object_t *dictappl; TRACE_ENTRY("%p %x %p", model, flags, msg); /* Check the parameters */ CHECK_PARAMS( msg && CHECK_MSGFL(flags) ); if (model) { ret = dict_gettype(model, &dicttype); if (ret || (dicttype != DICT_COMMAND)) { TRACE_DEBUG (INFO, "(%d, %d) -> EINVAL.", ret, dicttype ); return EINVAL; } CHECK_FCT( dict_getval(model, &dictdata) ); } /* Create a new object */ CHECK_MALLOC( new = (_msg_t *) malloc (sizeof(_msg_t)) ); /* Initialize the fields */ init_msg(new); new->msg_public.msg_version = MSG_VERSION; new->msg_public.msg_length = GETMSGHDRSZ(); /* This will be updated later */ if (model) { new->msg_model = model; new->msg_public.msg_flags = dictdata.cmd_flag_val; new->msg_public.msg_code = dictdata.cmd_code; /* Initialize application from the parent, if any */ CHECK_FCT( dict_search( DICT_APPLICATION, APPLICATION_OF_COMMAND, model, &dictappl) ); if (dictappl != NULL) { dict_application_data_t appdata; CHECK_FCT( dict_getval(dictappl, &appdata) ); new->msg_public.msg_appl = appdata.application_id; } } if (flags & MSGFL_ALLOW_ETEID) { new->msg_public.msg_eteid = msg_get_eteid(); } /* Create the children from template if needed */ if (model && (flags & MSGFL_FROM_TEMPLATE)) { cb_data_t data = { _C(new), flags}; CHECK_FCT_DO( ret = dict_iterate_rules ( model, &data, create_child_avp ), { destroy_tree(_C(new)); return ret; } ); } /* The new object is ready, return */ *msg = (msg_t *)new; return 0; } /* Create answer from a request */ int msg_new_answ ( msg_t ** msg, int flags ) { dict_object_t * model = NULL; _msg_t * qry; TRACE_ENTRY("%p %x", msg, flags); /* Check the parameters */ CHECK_PARAMS( msg && CHECK_MSG(*msg) && (_M(*msg)->msg_public.msg_flags & CMD_FLAG_REQUEST) ); qry = _M(*msg); /* Find the model for the answer */ CHECK_FCT( _mpd_do_msg(qry, 0, 1) ); CHECK_FCT( dict_search ( DICT_COMMAND, CMD_ANSWER, qry->msg_model, &model ) ); /* Create the answer */ CHECK_FCT( msg_new( model, flags, msg ) ); /* associate with query */ /* may do that but this is faster... CHECK_FCT( msg_answ_associate( *msg, (msg_t *)qry ) ); */ _M(*msg)->msg_query = (msg_t *)qry; return 0; } /* Create a new AVP instance */ int msg_avp_new ( dict_object_t * model, int flags, msg_avp_t ** avp ) { int ret=0; _msg_avp_t *new = NULL; dict_object_type_t dicttype; dict_avp_data_t dictavpdata; TRACE_ENTRY("%p %x %p", model, flags, avp); /* Check the parameters */ CHECK_PARAMS( model && avp && CHECK_MSGFL(flags) ); ret = dict_gettype(model, &dicttype); if (ret || (dicttype != DICT_AVP)) { TRACE_DEBUG (INFO, "(%d, %d) -> EINVAL.", ret, dicttype ); return EINVAL; } CHECK_FCT( dict_getval(model, &dictavpdata) ); /* Create a new object */ CHECK_MALLOC( new = (_msg_avp_t *) malloc (sizeof(_msg_avp_t)) ); /* Initialize the fields */ init_avp(new); new->avp_model = model; new->avp_public.avp_code = dictavpdata.avp_code; new->avp_public.avp_flags = dictavpdata.avp_flag_val; new->avp_public.avp_len = GETINITIALSIZE(dictavpdata.avp_basetype, dictavpdata.avp_flag_val ); new->avp_public.avp_vendor = dictavpdata.avp_vendor; /* Create the children from template if needed */ if ((flags & MSGFL_FROM_TEMPLATE) && (dictavpdata.avp_basetype == AVP_TYPE_GROUPED)) { cb_data_t data = { _C(new), flags}; CHECK_FCT_DO( ret = dict_iterate_rules ( model, &data, create_child_avp ), { destroy_tree(_C(new)); return ret; } ); } /* The new object is ready, return */ *avp = (msg_avp_t*)new; return 0; } /* Add an AVP into a tree */ int msg_avp_add ( void * reference, msg_dir_t dir, msg_avp_t *avp) { TRACE_ENTRY("%p %d %p", reference, dir, avp); /* Check the parameters */ CHECK_PARAMS( VALIDATE_OBJ(reference) && CHECK_AVP(avp) && IS_LIST_EMPTY(&_C(avp)->chaining) ); /* Now insert */ switch (dir) { case MSG_BRW_NEXT: /* Check the reference is an AVP -- we do not chain AVPs at same level as msgs. */ CHECK_PARAMS( _C(reference)->type == _MSG_AVP ); /* Insert the new avp after the reference */ uti_list_insert_after( &_C(reference)->chaining, &_C(avp)->chaining ); break; case MSG_BRW_PREV: /* Check the reference is an AVP */ CHECK_PARAMS( _C(reference)->type == _MSG_AVP ); /* Insert the new avp before the reference */ uti_list_insert_before( &_C(reference)->chaining, &_C(avp)->chaining ); break; case MSG_BRW_FIRST_CHILD: /* Insert the new avp after the children sentinel */ uti_list_insert_after( &_C(reference)->children, &_C(avp)->chaining ); break; case MSG_BRW_LAST_CHILD: /* Insert the new avp before the children sentinel */ uti_list_insert_before( &_C(reference)->children, &_C(avp)->chaining ); break; default: /* Other directions are invalid */ CHECK_PARAMS( dir = 0 ); } return 0; } /* Free an object and its tree */ int msg_free ( void * object, int subtree ) { TRACE_ENTRY("%p %d", object, subtree); if (CHECK_MSG(object)) { if (!subtree) { CHECK_PARAMS( _M(object)->msg_query == NULL ); CHECK_PARAMS( _M(object)->msg_rtlist == NULL ); } if (_M(object)->msg_query) { CHECK_FCT_DO( msg_free( _M(object)->msg_query, 1 ), /* continue */ ); _M(object)->msg_query = NULL; } while (_M(object)->msg_rtlist != NULL) { rt_dpl_t * head = _M(object)->msg_rtlist; _M(object)->msg_rtlist = head->next; free(head); } } if (!subtree) return destroy_obj ( _C(object) ); destroy_tree(_C(object)); return 0; } /* Allow exploring a message */ int msg_browse ( void * reference, msg_dir_t dir, void ** found, int * depth ) { int ret = 0; _msg_avp_chain_t *_found = NULL; int diff = 0; uti_list_t *li = NULL; TRACE_ENTRY("%p %d %p %p", reference, dir, found, depth); /* Initialize the "found" result if any */ if (found) *found = NULL; /* Check the parameters */ CHECK_PARAMS( VALIDATE_OBJ(reference) ); TRACE_DEBUG(FCTS, "chaining(%p): nxt:%p prv:%p hea:%p top:%p", &_C(reference)->chaining, _C(reference)->chaining.next, _C(reference)->chaining.prev, _C(reference)->chaining.head, _C(reference)->chaining.o); TRACE_DEBUG(FCTS, "children(%p): nxt:%p prv:%p hea:%p top:%p", &_C(reference)->children, _C(reference)->children.next, _C(reference)->children.prev, _C(reference)->children.head, _C(reference)->children.o); /* Now search */ switch (dir) { case MSG_BRW_NEXT: /* Check the reference is an AVP */ CHECK_PARAMS( _C(reference)->type == _MSG_AVP ); li = &_C(reference)->chaining; /* Check if the next element is not the sentinel ( ==> the parent) */ if (li->next != li->head) _found = _C(li->next->o); break; case MSG_BRW_PREV: /* Check the reference is an AVP */ CHECK_PARAMS( _C(reference)->type == _MSG_AVP ); li = &_C(reference)->chaining; /* Check if the prev element is not the sentinel ( ==> the parent) */ if (li->prev != li->head) _found = _C(li->prev->o); break; case MSG_BRW_FIRST_CHILD: li = &_C(reference)->children; if (! IS_LIST_EMPTY(li)) { _found = _C(li->next->o); diff = 1; } break; case MSG_BRW_LAST_CHILD: li = &_C(reference)->children; if (! IS_LIST_EMPTY(li)) { _found = _C(li->prev->o); diff = 1; } break; case MSG_BRW_PARENT: /* If the object is not chained, it has no parent */ li = &_C(reference)->chaining; if (li != li->head) { /* The sentinel is the parent's children list */ _found = _C(li->head->o); diff = -1; } break; case MSG_BRW_WALK: /* First, try to find a child */ li = &_C(reference)->children; if ( ! IS_LIST_EMPTY(li) ) { _found = _C(li->next->o); diff = 1; break; } /* Then try to find a "next" at this level or one of the parent's */ li = &_C(reference)->chaining; do { /* If this element has a "next" element, return it */ if (li->next != li->head) { _found = _C(li->next->o); break; } /* otherwise, check if we have a parent */ if (li == li->head) { /* no parent */ break; } /* Go to the parent's chaining information and loop */ diff -= 1; li = &_C(li->head->o)->chaining; } while (1); break; default: /* Other directions are invalid */ CHECK_PARAMS( dir = 0 ); } /* Save the found object, if any */ if (found && _found) *found = (void *)_found; /* Return ENOENT if found was NULL */ if ((!found) && (!_found)) ret = ENOENT; /* Modify the depth according to the walk direction */ if (depth && diff) (*depth) += diff; /* Return the error code */ return ret; } /* Retrieve the model of an object */ int msg_model ( void * reference, dict_object_t ** model ) { TRACE_ENTRY("%p %p", reference, model); /* Check the parameters */ CHECK_PARAMS( model && VALIDATE_OBJ(reference) ); /* copy the model reference */ switch (_C(reference)->type) { case _MSG_AVP: *model = _A(reference)->avp_model; break; case _MSG_MSG: *model = _M(reference)->msg_model; break; default: ASSERT(0); } return 0; } /* Set the value of an AVP */ int msg_avp_setvalue ( msg_avp_t *avp, avp_value_t *value ) { dict_base_type_t type = -1; TRACE_ENTRY("%p %p", avp, value); /* Check parameter */ CHECK_PARAMS( CHECK_AVP(avp) && _A(avp)->avp_model ); /* Retrieve information from the AVP model */ { dict_object_type_t dicttype = -1; dict_avp_data_t dictdata; int ret = 0; ret = dict_gettype(_A(avp)->avp_model, &dicttype); if (ret || (dicttype != DICT_AVP)) { TRACE_DEBUG(INFO, "Received an invalid reference object. EINVAL"); return EINVAL; } CHECK_FCT( dict_getval(_A(avp)->avp_model, &dictdata) ); type = dictdata.avp_basetype; CHECK_PARAMS( type != AVP_TYPE_GROUPED ); } /* First, clean any previous value */ if (_A(avp)->avp_mustfreeos != 0) { free(_A(avp)->avp_storage.os.data); _A(avp)->avp_mustfreeos = 0; } memset(&_A(avp)->avp_storage, 0, sizeof(avp_value_t)); /* If the request is to delete a value: */ if (!value) { _A(avp)->avp_public.avp_data = NULL; return 0; } /* Now we have to set the value */ memcpy(&_A(avp)->avp_storage, value, sizeof(avp_value_t)); /* Copy an octetstring if needed. */ if (type == AVP_TYPE_OCTETSTRING) { CHECK_MALLOC( _A(avp)->avp_storage.os.data = malloc(value->os.len) ); _A(avp)->avp_mustfreeos = 1; memcpy(_A(avp)->avp_storage.os.data, value->os.data, value->os.len); } /* Set the data pointer of the public part */ _A(avp)->avp_public.avp_data = &_A(avp)->avp_storage; return 0; } /* Set the value of an AVP, using formatted data */ int msg_avp_value_encode ( void *data, msg_avp_t *avp ) { dict_base_type_t type = -1; dict_type_data_t type_data; int ret = 0; TRACE_ENTRY("%p %p", data, avp); /* Check parameter */ CHECK_PARAMS( CHECK_AVP(avp) && _A(avp)->avp_model ); /* Retrieve information from the AVP model and it's parent type */ { dict_object_type_t dicttype = -1; dict_avp_data_t dictdata; dict_object_t * parenttype = NULL; /* First check the base type of the AVP */ ret = dict_gettype(_A(avp)->avp_model, &dicttype); if (ret || (dicttype != DICT_AVP)) { TRACE_DEBUG(INFO, "Received an invalid reference object. EINVAL"); return EINVAL; } CHECK_FCT( dict_getval(_A(avp)->avp_model, &dictdata) ); type = dictdata.avp_basetype; CHECK_PARAMS( type != AVP_TYPE_GROUPED ); /* Then retrieve information about the parent's type (= derived type) */ CHECK_FCT( dict_search(DICT_TYPE, TYPE_OF_AVP, _A(avp)->avp_model, &parenttype) ); CHECK_PARAMS( parenttype ); CHECK_FCT( dict_getval(parenttype, &type_data) ); if (type_data.type_encode == NULL) { TRACE_DEBUG(INFO, "This AVP type does not provide a callback to encode formatted data. ENOTSUP."); return ENOTSUP; } } /* Ok, now we can encode the value */ /* First, clean any previous value */ if (_A(avp)->avp_mustfreeos != 0) { free(_A(avp)->avp_storage.os.data); _A(avp)->avp_mustfreeos = 0; } _A(avp)->avp_public.avp_data = NULL; memset(&_A(avp)->avp_storage, 0, sizeof(avp_value_t)); /* Now call the type's callback to encode the data */ CHECK_FCT( (*type_data.type_encode)(data, &_A(avp)->avp_storage) ); /* If an octetstring has been allocated, let's mark it to be freed */ if (type == AVP_TYPE_OCTETSTRING) _A(avp)->avp_mustfreeos = 1; /* Set the data pointer of the public part */ _A(avp)->avp_public.avp_data = &_A(avp)->avp_storage; return 0; } /* Interpret the value of an AVP into formatted data */ int msg_avp_value_interpret ( msg_avp_t *avp, void *data ) { dict_type_data_t type_data; TRACE_ENTRY("%p %p", avp, data); /* Check parameter */ CHECK_PARAMS( CHECK_AVP(avp) && _A(avp)->avp_model && _A(avp)->avp_public.avp_data ); /* Retrieve information about the AVP parent type */ { dict_object_t * parenttype = NULL; CHECK_FCT( dict_search(DICT_TYPE, TYPE_OF_AVP, _A(avp)->avp_model, &parenttype) ); CHECK_PARAMS( parenttype ); CHECK_FCT( dict_getval(parenttype, &type_data) ); if (type_data.type_interpret == NULL) { TRACE_DEBUG(INFO, "This AVP type does not provide a callback to interpret value in formatted data. ENOTSUP."); return ENOTSUP; } } /* Ok, now we can interpret the value */ CHECK_FCT( (*type_data.type_interpret)(_A(avp)->avp_public.avp_data, data) ); return 0; } /* Retrieve the address of the msg_public field of a message */ int msg_data ( msg_t *msg, msg_data_t **pdata ) { TRACE_ENTRY("%p %p", msg, pdata); CHECK_PARAMS( CHECK_MSG(msg) && pdata ); *pdata = & _M(msg)->msg_public; return 0; } /* Retrieve the address of the avp_public field of an avp */ int msg_avp_data ( msg_avp_t *avp, msg_avp_data_t **pdata ) { TRACE_ENTRY("%p %p", avp, pdata); CHECK_PARAMS( CHECK_AVP(avp) && pdata ); *pdata = & _A(avp)->avp_public; return 0; } /* Retrieve the raw data of an AVP for which the model was not resolved. */ int msg_avp_getrawdata ( msg_avp_t *avp, unsigned char **data ) { TRACE_ENTRY("%p %p", avp, data); CHECK_PARAMS( CHECK_AVP(avp) && data ); *data = _A(avp)->avp_rawdata; return 0; } /* Compute the lengh of an object and its subtree. */ int msg_update_length ( void * object ) { size_t sz = 0; dict_object_t * model; union { dict_cmd_data_t cmddata; dict_avp_data_t avpdata; } dictdata; TRACE_ENTRY("%p", object); /* Get the model of the object. This also validates the object */ CHECK_FCT( msg_model ( object, &model ) ); /* Get the information of the model */ if (model) { CHECK_FCT( dict_getval(model, &dictdata) ); } else { /* For unknown AVP, just don't change the size */ if (_C(object)->type == _MSG_AVP) return 0; } /* Deal with easy cases: AVPs without children */ if ((_C(object)->type == _MSG_AVP) && (dictdata.avpdata.avp_basetype != AVP_TYPE_GROUPED)) { /* Sanity check */ ASSERT(IS_LIST_EMPTY(&_C(object)->children)); /* Now check that the data is set in the AVP */ CHECK_PARAMS( _A(object)->avp_public.avp_data ); sz = GETAVPHDRSZ( _A(object)->avp_public.avp_flags ); switch (dictdata.avpdata.avp_basetype) { case AVP_TYPE_OCTETSTRING: sz += _A(object)->avp_public.avp_data->os.len; break; case AVP_TYPE_INTEGER32: case AVP_TYPE_INTEGER64: case AVP_TYPE_UNSIGNED32: case AVP_TYPE_UNSIGNED64: case AVP_TYPE_FLOAT32: case AVP_TYPE_FLOAT64: sz += avp_value_sizes[dictdata.avpdata.avp_basetype]; break; default: /* Something went wrong... */ ASSERT(0); } } else /* message or grouped AVP */ { uti_list_t * ch = NULL; /* First, compute the header size */ if (_C(object)->type == _MSG_AVP) sz = GETAVPHDRSZ( _A(object)->avp_public.avp_flags ); else sz = GETMSGHDRSZ( ); /* Recurse in all children and update the sz information */ for (ch = _C(object)->children.next; ch != &_C(object)->children; ch = ch->next) { CHECK_FCT( msg_update_length ( ch->o ) ); /* Add the padded size to the parent */ sz += PAD4( _A(ch->o)->avp_public.avp_len ); } } /* When we arrive here, the "sz" variable contains the size to write in the object */ if (_C(object)->type == _MSG_AVP) _A(object)->avp_public.avp_len = sz; else _M(object)->msg_public.msg_length = sz; return 0; } /* Check that an object instance does not break a rule */ int msg_parse_rules ( void * object, dict_object_t ** rule) { TRACE_ENTRY("%p %p", object, rule); /* Resolve the dictionary objects when missing. This also validates the object. */ CHECK_FCT( _mpd_do( _C(object), 1 ) ); /* Call the recursive function */ return _mpr_do (object, rule, 1); } /* Assign a new End-to-end id */ uint32_t msg_get_eteid ( void ) { uint32_t ret; CHECK_POSIX_DO( pthread_mutex_lock(&eteid_lock), /* continue */ ); ret = eteid ++; CHECK_POSIX_DO( pthread_mutex_unlock(&eteid_lock), /* continue */ ); return ret; } /* Send a message and optionaly register a callback for an answer */ int msg_send ( msg_t ** msg, void (*anscb)(void *, msg_t **), void * data ) { TRACE_ENTRY("%p %p %p", msg, anscb, data); /* Check the parameters */ CHECK_PARAMS( msg && CHECK_MSG(*msg) ); CHECK_PARAMS( (anscb == NULL) || (_M(*msg)->msg_public.msg_flags & CMD_FLAG_REQUEST) ); CHECK_PARAMS( (anscb == NULL) || (_M(*msg)->msg_cb.fct == NULL) ); /* No cb is already registered */ /* Associate callback and data with the message, if any */ if (anscb) { _M(*msg)->msg_cb.fct = anscb; _M(*msg)->msg_cb.data = data; } /* Now push the message in the global outgoing queue */ CHECK_FCT( meq_post( g_meq_outgoing, *msg ) ); /* Done */ *msg = NULL; return 0; } int msg_get_anscb(msg_t * msg, void (**anscb)(void *, msg_t **), void ** data ) { TRACE_ENTRY("%p %p %p", msg, anscb, data); /* Check the parameters */ CHECK_PARAMS( CHECK_MSG(msg) && anscb && data ); /* Copy the result */ *anscb = _M(msg)->msg_cb.fct; *data = _M(msg)->msg_cb.data; return 0; } /**********************************************************************************************************/ /* The following functions are used to parse messages from and to buffers. It is responsible for converting * to and from network byte-order. */ /* Create the message buffer, in network-byte order. We browse the tree twice, this could be probably improved if needed */ int msg_bufferize ( msg_t * msg, unsigned char ** buffer, size_t * len ) { int ret = 0; unsigned char * buf = NULL; size_t offset = 0; TRACE_ENTRY("%p %p %p", msg, buffer, len); /* Check the parameters */ CHECK_PARAMS( buffer && CHECK_MSG(msg) ); /* Update the length. This also checks that all AVP have their values set */ CHECK_FCT( msg_update_length(msg) ); /* Now allocate a buffer to store the message */ CHECK_MALLOC( buf = malloc(_M(msg)->msg_public.msg_length) ); /* Clear the memory, so that the padding is always 0 */ memset(buf, 0, _M(msg)->msg_public.msg_length); /* Write the message header in the buffer */ CHECK_FCT_DO( ret = _msg_buf_msg(buf, _M(msg)->msg_public.msg_length, &offset, _M(msg)), { free(buf); return ret; } ); /* Write the list of AVPs */ CHECK_FCT_DO( ret = _msg_buf_chain(buf, _M(msg)->msg_public.msg_length, &offset, &_C(msg)->children), { free(buf); return ret; } ); ASSERT(offset == _M(msg)->msg_public.msg_length); /* or the msg_update_length is buggy */ if (len) { *len = offset; } *buffer = buf; return 0; } /* Create a message object from a buffer. Dictionary objects are not resolved, AVP contents are not interpreted, buffer is saved in msg */ int msg_parse_buffer ( unsigned char ** buffer, size_t buflen, msg_t ** msg ) { _msg_t * new = NULL; int ret = 0; unsigned char * buf; TRACE_ENTRY("%p %d %p", buffer, buflen, msg); CHECK_PARAMS( buffer && *buffer && msg && (buflen >= GETMSGHDRSZ()) ); buf = *buffer; *buffer = NULL; if ( buf[0] != MSG_VERSION) { log_error("Buffer contains an invalid protocol number: %d (supported: %d)\n", (int)buf[0], MSG_VERSION); TRACE_DEBUG(INFO, "Invalid version in message: %d (supported: %d)", buf[0], MSG_VERSION); free(buf); return EBADMSG; } CHECK_PARAMS_DO( buflen == ((ntohl(*(uint32_t *)buf)) & 0x00ffffff), { free(buf); return EBADMSG; } ); /* Create a new object */ CHECK_MALLOC_DO( new = (_msg_t *) malloc (sizeof(_msg_t)), { free(buf); return ENOMEM; } ); /* Initialize the fields */ init_msg(new); /* Now read from the buffer */ new->msg_public.msg_version = buf[0]; new->msg_public.msg_length = ntohl(*(uint32_t *)buf) & 0x00ffffff; new->msg_public.msg_flags = buf[4]; new->msg_public.msg_code = ntohl(*(uint32_t *)(buf+4)) & 0x00ffffff; new->msg_public.msg_appl = ntohl(*(uint32_t *)(buf+8)); new->msg_public.msg_hbhid = ntohl(*(uint32_t *)(buf+12)); new->msg_public.msg_eteid = ntohl(*(uint32_t *)(buf+16)); new->msg_rawbuffer = buf; /* Parse the AVP list */ CHECK_FCT_DO( ret = _mpb_list(buf + GETMSGHDRSZ(), buflen - GETMSGHDRSZ(), &_C(new)->children), { destroy_tree(_C(new)); return ret; } ); *msg = new; return 0; } /**********************************************************************************************************/ /* Find if a message is routable */ int msg_is_routable ( msg_t * msg ) { TRACE_ENTRY("%p", msg); CHECK_PARAMS_DO( CHECK_MSG(msg), return 0 /* pretend the message is not routable */ ); if ( ! _M(msg)->msg_routable ) { /* To define if a message is routable, we rely on the "PXY" command flag yet. */ _M(msg)->msg_routable = (_M(msg)->msg_public.msg_flags & CMD_FLAG_PROXIABLE) ? 1 : 2; /* Note : the 'real' criteria according to the Diameter I-D is that the message is routable if and only if the "Destination-Realm" AVP is required by the command ABNF. We could make a test for this here, but it's more computational work and our test seems accurate (until proven otherwise...) */ } return (_M(msg)->msg_routable == 1) ? 1 : 0; } /**********************************************************************************************************/ /* Search a given AVP model in a message */ int msg_search_avp ( msg_t * msg, dict_object_t * what, msg_avp_t ** avp ) { msg_avp_t * navp; TRACE_ENTRY("%p %p %p", msg, what, avp); CHECK_PARAMS( CHECK_MSG(msg) ); CHECK_FCT( msg_browse(msg, MSG_BRW_FIRST_CHILD, &navp, NULL) ); while (navp) { _msg_avp_t * iavp = (_msg_avp_t *) navp; /* Resolve the model. Ignore errors here. */ (void)_mpd_do_avp(iavp, 1, 0); /* Check if we found a model matching the object we are searching */ if (iavp->avp_model == what) break; /* Otherwise move to next AVP in the message */ CHECK_FCT( msg_browse(navp, MSG_BRW_NEXT, &navp, NULL) ); } if (avp) *avp = navp; if (avp || navp) return 0; else return ENOENT; } /**********************************************************************************************************/ /* Following functions are useful tools to use in other parts of the daemon */ /* Add Origin-Host, Origin-Realm, Origin-State-Id AVPS at the end of the message */ int msg_add_origin ( msg_t * msg, int osi ) { avp_value_t val; msg_avp_t * avp_OH = NULL; msg_avp_t * avp_OR = NULL; msg_avp_t * avp_OSI = NULL; TRACE_ENTRY("%p", msg); CHECK_PARAMS( CHECK_MSG(msg) ); /* Create the Origin-Host AVP */ CHECK_FCT( msg_avp_new( dict_avp_OH, 0, &avp_OH ) ); /* Set its value */ memset(&val, 0, sizeof(val)); val.os.data = (unsigned char *)g_pconf->diameter_identity; val.os.len = g_conf->diamid_len; CHECK_FCT( msg_avp_setvalue( avp_OH, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_OH ) ); /* Create the Origin-Realm AVP */ CHECK_FCT( msg_avp_new( dict_avp_OR, 0, &avp_OR ) ); /* Set its value */ memset(&val, 0, sizeof(val)); val.os.data = (unsigned char *)g_pconf->diameter_realm; val.os.len = g_conf->realm_len; CHECK_FCT( msg_avp_setvalue( avp_OR, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_OR ) ); /* Create the Origin-State-Id AVP */ CHECK_FCT( msg_avp_new( dict_avp_OSI, 0, &avp_OSI ) ); /* Set its value */ memset(&val, 0, sizeof(val)); val.u32 = g_pconf->origin_state_id; CHECK_FCT( msg_avp_setvalue( avp_OSI, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_OSI ) ); return 0; } /* Create an anwer to a query */ int msg_new_answer_from_req ( msg_t ** msg ) { _msg_t *qry; TRACE_ENTRY("%p", msg); CHECK_PARAMS( msg && CHECK_MSG(*msg) ); qry = (_msg_t *)(*msg); CHECK_PARAMS( qry->msg_public.msg_flags & CMD_FLAG_REQUEST ); /* Create the new message */ CHECK_FCT( msg_new_answ(msg, 0) ); /* If the first AVP of the query is a Session-Id, copy it to the answer */ { msg_avp_t * avp = NULL; msg_avp_t * navp = NULL; msg_avp_data_t * avpdata = NULL; CHECK_FCT( msg_browse(qry, MSG_BRW_FIRST_CHILD, &avp, NULL) ); CHECK_FCT( msg_avp_data( avp, &avpdata ) ); /* No need to search, Session-Id is always the first AVP if present */ if (((avpdata->avp_flags & AVP_FLAG_VENDOR) == 0) && (avpdata->avp_code == AC_SESSION_ID)) { CHECK_FCT( msg_parse_dict_avp(avp) ); /* to interpret its data */ ASSERT(avpdata->avp_data); CHECK_FCT( msg_avp_new( ((_msg_avp_t *)avp)->avp_model, 0, &navp ) ); /* Set its value */ CHECK_FCT( msg_avp_setvalue( navp, avpdata->avp_data ) ); /* Add it to the answer message */ CHECK_FCT( msg_avp_add( *msg, MSG_BRW_FIRST_CHILD, navp ) ); } } return 0; } /* Add Result-Code and eventually Failed-AVP, Error-Message and Error-Reporting-Host AVPs */ int msg_rescode_set( msg_t * msg, char * rescode, char * errormsg, msg_avp_t * optavp, int type_id ) { avp_value_t val; msg_avp_t * avp_RC = NULL; msg_avp_t * avp_EM = NULL; msg_avp_t * avp_ERH = NULL; msg_avp_t * avp_FAVP= NULL; uint32_t rc_val = 0; int set_e_bit=0; int std_err_msg=0; TRACE_ENTRY("%p %s %p %p %d", msg, rescode, errormsg, optavp, type_id); CHECK_PARAMS( CHECK_MSG(msg) && rescode ); CHECK_PARAMS( (optavp == NULL) || CHECK_AVP(optavp) ); /* Find the enum value corresponding to the rescode string, this will give the class of error */ { dict_object_t * enum_obj = NULL; dict_type_enum_request_t req; memset(&req, 0, sizeof(dict_type_enum_request_t)); /* First, get the enumerated type of the Result-Code AVP */ CHECK_FCT( dict_search( DICT_TYPE, TYPE_OF_AVP, dict_avp_RC, &(req.type_obj) ) ); /* Now search for the value given as parameter */ req.search.enum_name = rescode; CHECK_FCT( dict_search( DICT_TYPE_ENUM, ENUM_BY_STRUCT, &req, &enum_obj) ); /* finally retrieve its data */ CHECK_FCT_DO( dict_getval( enum_obj, &(req.search) ), return EINVAL ); /* copy the found value, we're done */ rc_val = req.search.enum_value.u32; } if (type_id == 1) { /* Add the Origin-Host and Origin-Realm AVP */ CHECK_FCT( msg_add_origin ( msg, 0 ) ); } /* Create the Result-Code AVP */ CHECK_FCT( msg_avp_new( dict_avp_RC, 0, &avp_RC ) ); /* Set its value */ memset(&val, 0, sizeof(val)); val.u32 = rc_val; CHECK_FCT( msg_avp_setvalue( avp_RC, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_RC ) ); if (type_id == 2) { /* Add the Error-Reporting-Host AVP */ CHECK_FCT( msg_avp_new( dict_avp_ERH, 0, &avp_ERH ) ); /* Set its value */ memset(&val, 0, sizeof(val)); val.os.data = (unsigned char *)g_pconf->diameter_identity; val.os.len = g_conf->diamid_len; CHECK_FCT( msg_avp_setvalue( avp_ERH, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_ERH ) ); } /* Now add the optavp in a FailedAVP if provided */ if (optavp) { /* Create the Failed-AVP AVP */ CHECK_FCT( msg_avp_new( dict_avp_FAVP, 0, &avp_FAVP ) ); /* Add the passed AVP inside it */ CHECK_FCT( msg_avp_add( avp_FAVP, MSG_BRW_LAST_CHILD, optavp ) ); /* And add to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_FAVP ) ); } /* Deal with the 'E' bit and the error message */ switch (rc_val / 1000) { case 1: /* Informational */ case 2: /* Success */ /* Nothing special here: no E bit, no error message unless one is specified */ break; case 3: /* Protocol Errors */ set_e_bit = 1; std_err_msg = 1; break; case 4: /* Transcient Failure */ case 5: /* Permanent Failure */ default: std_err_msg = 1; break; } if (set_e_bit) { msg_data_t * hdr = NULL; CHECK_FCT( msg_data( msg, &hdr ) ); hdr->msg_flags |= CMD_FLAG_ERROR; } if (std_err_msg || errormsg) { /* Add the Error-Message AVP */ CHECK_FCT( msg_avp_new( dict_avp_EM, 0, &avp_EM ) ); /* Set its value */ memset(&val, 0, sizeof(val)); if (errormsg) { val.os.data = (unsigned char *)errormsg; val.os.len = strlen(errormsg); } else { val.os.data = (unsigned char *)rescode; val.os.len = strlen(rescode); } CHECK_FCT( msg_avp_setvalue( avp_EM, &val ) ); /* Add it to the message */ CHECK_FCT( msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp_EM ) ); } return 0; }