src/modules/dialog/dialog.c
5b3d7218
 /*
  * dialog module - basic support for dialog tracking
  *
  * Copyright (C) 2006 Voice Sistem SRL
60d9c557
  * Copyright (C) 2011 Carsten Bock, carsten@ng-voice.com
5b3d7218
  *
27642a08
  * This file is part of Kamailio, a free SIP server.
5b3d7218
  *
27642a08
  * Kamailio is free software; you can redistribute it and/or modify
5b3d7218
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version
  *
27642a08
  * Kamailio is distributed in the hope that it will be useful,
5b3d7218
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
0e86b73a
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
9e1ff448
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
5b3d7218
  *
c3291cfe
  */
 
 /*!
  * \file
  * \brief Module interface
  * \ingroup dialog
  * Module: \ref dialog
5b3d7218
  */
 
f992d9b4
 /**
  * @defgroup dialog dialog :: Kamailio dialog module
  * @brief Kamailio dialog module
  *
  * The dialog module provides dialog awareness to the Kamailio proxy. Its
  * functionality is to keep track of the current dialogs, to offer
  * information about them (like how many dialogs are active) or to manage
  * them. The module exports several functions that could be used directly
  * from scripts.
  * The module, via an internal API, also provide the foundation to build
  * on top of it more complex dialog-based functionalities via other
0e86b73a
  * Kamailio modules.
f992d9b4
  */
5b3d7218
 
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
a70300b1
 #include <sys/time.h>
51716422
 
cf83221d
 #include "../../core/sr_module.h"
afda814b
 #include "../../lib/srdb1/db.h"
cf83221d
 #include "../../core/dprint.h"
 #include "../../core/error.h"
 #include "../../core/ut.h"
 #include "../../core/pvar.h"
 #include "../../core/mod_fix.h"
 #include "../../core/script_cb.h"
196537b0
 #include "../../core/kemi.h"
cf83221d
 #include "../../core/fmsg.h"
 #include "../../core/hashes.h"
 #include "../../core/counters.h"
 #include "../../core/mem/mem.h"
 #include "../../core/timer_proc.h"
 #include "../../core/lvalue.h"
8f9b6ea5
 #include "../../core/globals.h"
cf83221d
 #include "../../core/parser/parse_to.h"
eb38b3df
 #include "../../modules/tm/tm_load.h"
cf83221d
 #include "../../core/rpc_lookup.h"
 #include "../../core/srapi.h"
5b3d7218
 #include "../rr/api.h"
 #include "dlg_hash.h"
 #include "dlg_timer.h"
 #include "dlg_handlers.h"
 #include "dlg_load.h"
 #include "dlg_cb.h"
a70300b1
 #include "dlg_db_handler.h"
d58ad600
 #include "dlg_req_within.h"
4d41d724
 #include "dlg_profile.h"
29d70f7d
 #include "dlg_var.h"
 #include "dlg_transfer.h"
94f18a95
 #include "dlg_cseq.h"
9fe51ed4
 #include "dlg_dmq.h"
5b3d7218
 
 MODULE_VERSION
 
 
33e7e899
 #define RPC_DATE_BUF_LEN 21
 
5b3d7218
 static int mod_init(void);
011f0642
 static int child_init(int rank);
351fc577
 static void mod_destroy(void);
5b3d7218
 
 /* module parameter */
 static int dlg_hash_size = 4096;
 static char* rr_param = "did";
 static int dlg_flag = -1;
e2cf6343
 static str timeout_spec = {NULL, 0};
5b3d7218
 static int default_timeout = 60 * 60 * 12;  /* 12 hours */
60d9c557
 static int seq_match_mode = SEQ_MATCH_STRICT_ID;
4d41d724
 static char* profiles_wv_s = NULL;
 static char* profiles_nv_s = NULL;
2f7700d3
 str dlg_extra_hdrs = {NULL,0};
68c8b77d
 static int db_fetch_rows = 200;
9eb6ab94
 static int db_skip_load = 0;
0b3562ac
 static int dlg_keep_proxy_rr = 0;
14348216
 int dlg_filter_mode = 0;
48b8190c
 int initial_cbs_inscript = 1;
53ec53db
 int dlg_wait_ack = 1;
1157db7c
 static int dlg_timer_procs = 0;
94f18a95
 static int _dlg_track_cseq_updates = 0;
e8cd0ebb
 int dlg_ka_failed_limit = 1;
3c6b3ecb
 int dlg_early_timeout = 300;
 int dlg_noack_timeout = 60;
313265ac
 int dlg_end_timeout = 300;
68c8b77d
 
9fe51ed4
 int dlg_enable_dmq = 0;
 
a46f2ee6
 int dlg_event_rt[DLG_EVENTRT_MAX];
5b7838c9
 str dlg_event_callback = STR_NULL;
a46f2ee6
 
68875ad3
 str dlg_bridge_controller = str_init("sip:controller@kamailio.org");
5b3d7218
 
68875ad3
 str dlg_bridge_contact = str_init("sip:controller@kamailio.org:5060");
64490219
 
68875ad3
 str ruri_pvar_param = str_init("$ru");
8c1b49d5
 pv_elem_t * ruri_param_model = NULL;
684afd9c
 str empty_str = STR_NULL;
8c1b49d5
 
8f9b6ea5
 int dlg_h_id_start = 0;
 int dlg_h_id_step = 1;
 
5b3d7218
 /* statistic variables */
 int dlg_enable_stats = 1;
0b665153
 int detect_spirals = 1;
84d38ce7
 int dlg_send_bye = 0;
b5993240
 int dlg_timeout_noreset = 0;
5b3d7218
 stat_var *active_dlgs = 0;
 stat_var *processed_dlgs = 0;
 stat_var *expired_dlgs = 0;
f56ae82e
 stat_var *failed_dlgs = 0;
 stat_var *early_dlgs  = 0;
5b3d7218
 
 struct tm_binds d_tmb;
 struct rr_binds d_rrb;
b0a7f212
 pv_spec_t timeout_avp;
5b3d7218
 
0b8226f9
 int dlg_db_mode_param = DB_MODE_NONE;
 
7d013ceb
 str dlg_xavp_cfg = {0};
 int dlg_ka_timer = 0;
 int dlg_ka_interval = 0;
97781390
 int dlg_clean_timer = 90;
7d013ceb
 
d8c92fd3
 str dlg_lreq_callee_headers = {0};
 
a70300b1
 /* db stuff */
e2cf6343
 static str db_url = str_init(DEFAULT_DB_URL);
a70300b1
 static unsigned int db_update_period = DB_DEFAULT_UPDATE_PERIOD;
5b3d7218
 
b0a7f212
 static int pv_get_dlg_count( struct sip_msg *msg, pv_param_t *param,
 		pv_value_t *res);
5b3d7218
 
7d013ceb
 void dlg_ka_timer_exec(unsigned int ticks, void* param);
97781390
 void dlg_clean_timer_exec(unsigned int ticks, void* param);
7d013ceb
 
4d41d724
 /* commands wrappers and fixups */
 static int fixup_profile(void** param, int param_no);
 static int fixup_get_profile2(void** param, int param_no);
 static int fixup_get_profile3(void** param, int param_no);
 static int w_set_dlg_profile(struct sip_msg*, char*, char*);
04ca7955
 static int w_unset_dlg_profile(struct sip_msg*, char*, char*);
4d41d724
 static int w_is_in_profile(struct sip_msg*, char*, char*);
028e3cc1
 static int w_get_profile_size2(struct sip_msg*, char*, char*);
 static int w_get_profile_size3(struct sip_msg*, char*, char*, char*);
29d70f7d
 static int w_dlg_isflagset(struct sip_msg *msg, char *flag, str *s2);
 static int w_dlg_resetflag(struct sip_msg *msg, char *flag, str *s2);
 static int w_dlg_setflag(struct sip_msg *msg, char *flag, char *s2);
7d013ceb
 static int w_dlg_set_property(struct sip_msg *msg, char *prop, char *s2);
4883b692
 static int w_dlg_reset_property(struct sip_msg *msg, char *prop, char *s2);
29d70f7d
 static int w_dlg_manage(struct sip_msg*, char*, char*);
 static int w_dlg_bye(struct sip_msg*, char*, char*);
 static int w_dlg_refer(struct sip_msg*, char*, char*);
 static int w_dlg_bridge(struct sip_msg*, char*, char*, char*);
3beef50c
 static int w_dlg_set_timeout(struct sip_msg*, char*, char*, char*);
17d1934c
 static int w_dlg_set_timeout_by_profile2(struct sip_msg *, char *, char *);
87ca7a1b
 static int w_dlg_set_timeout_by_profile3(struct sip_msg *, char *, char *,
17d1934c
 					char *);
29d70f7d
 static int fixup_dlg_bye(void** param, int param_no);
 static int fixup_dlg_refer(void** param, int param_no);
 static int fixup_dlg_bridge(void** param, int param_no);
 static int w_dlg_get(struct sip_msg*, char*, char*, char*);
49bd77d1
 static int w_is_known_dlg(struct sip_msg *);
87ca7a1b
 static int w_dlg_set_ruri(sip_msg_t *, char *, char *);
3d3f5ca1
 static int w_dlg_db_load_callid(sip_msg_t *msg, char *ci, char *p2);
0f2f7611
 static int w_dlg_db_load_extra(sip_msg_t *msg, char *p1, char *p2);
a70300b1
 
9c8020d2
 static int w_dlg_remote_profile(sip_msg_t *msg, char *cmd, char *pname,
 		char *pval, char *puid, char *expires);
 static int fixup_dlg_remote_profile(void** param, int param_no);
 
5b3d7218
 static cmd_export_t cmds[]={
29d70f7d
 	{"dlg_manage", (cmd_function)w_dlg_manage,            0,0,
 			0, REQUEST_ROUTE },
4d41d724
 	{"set_dlg_profile", (cmd_function)w_set_dlg_profile,  1,fixup_profile,
1b11548c
 			0, ANY_ROUTE },
4d41d724
 	{"set_dlg_profile", (cmd_function)w_set_dlg_profile,  2,fixup_profile,
1b11548c
 			0, ANY_ROUTE },
04ca7955
 	{"unset_dlg_profile", (cmd_function)w_unset_dlg_profile,  1,fixup_profile,
74c1a622
 			0, REQUEST_ROUTE| FAILURE_ROUTE | ONREPLY_ROUTE | BRANCH_ROUTE },
04ca7955
 	{"unset_dlg_profile", (cmd_function)w_unset_dlg_profile,  2,fixup_profile,
74c1a622
 			0, REQUEST_ROUTE| FAILURE_ROUTE | ONREPLY_ROUTE | BRANCH_ROUTE },
4d41d724
 	{"is_in_profile", (cmd_function)w_is_in_profile,      1,fixup_profile,
1b11548c
 			0, ANY_ROUTE },
4d41d724
 	{"is_in_profile", (cmd_function)w_is_in_profile,      2,fixup_profile,
1b11548c
 			0, ANY_ROUTE },
028e3cc1
 	{"get_profile_size",(cmd_function)w_get_profile_size2, 2,fixup_get_profile2,
1b11548c
 			0, ANY_ROUTE },
028e3cc1
 	{"get_profile_size",(cmd_function)w_get_profile_size3, 3,fixup_get_profile3,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_setflag", (cmd_function)w_dlg_setflag,          1,fixup_igp_null,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_resetflag", (cmd_function)w_dlg_resetflag,      1,fixup_igp_null,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_isflagset", (cmd_function)w_dlg_isflagset,      1,fixup_igp_null,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_bye",(cmd_function)w_dlg_bye,                   1,fixup_dlg_bye,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_refer",(cmd_function)w_dlg_refer,               2,fixup_dlg_refer,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_bridge",(cmd_function)w_dlg_bridge,             3,fixup_dlg_bridge,
1b11548c
 			0, ANY_ROUTE },
29d70f7d
 	{"dlg_get",(cmd_function)w_dlg_get,                   3,fixup_dlg_bridge,
1b11548c
 			0, ANY_ROUTE },
49bd77d1
 	{"is_known_dlg", (cmd_function)w_is_known_dlg,        0, NULL,
1b11548c
 			0, ANY_ROUTE },
3beef50c
 	{"dlg_set_timeout", (cmd_function)w_dlg_set_timeout,  1,fixup_igp_null,
 			0, ANY_ROUTE },
 	{"dlg_set_timeout", (cmd_function)w_dlg_set_timeout,  3,fixup_igp_all,
 			0, ANY_ROUTE },
e8cd0ebb
 	{"dlg_set_timeout_by_profile",
17d1934c
 		(cmd_function) w_dlg_set_timeout_by_profile2, 2, fixup_profile,
 			0, ANY_ROUTE },
e8cd0ebb
 	{"dlg_set_timeout_by_profile",
17d1934c
 		(cmd_function) w_dlg_set_timeout_by_profile3, 3, fixup_profile,
 			0, ANY_ROUTE },
7d013ceb
 	{"dlg_set_property", (cmd_function)w_dlg_set_property,1,fixup_spve_null,
 			0, ANY_ROUTE },
3af08bbd
 	{"dlg_reset_property", (cmd_function)w_dlg_reset_property,1,fixup_spve_null,
a1acd621
             0, ANY_ROUTE },
9c8020d2
 	{"dlg_remote_profile", (cmd_function)w_dlg_remote_profile, 5, fixup_dlg_remote_profile,
 			0, ANY_ROUTE },
87ca7a1b
 	{"dlg_set_ruri",       (cmd_function)w_dlg_set_ruri,  0, NULL,
 			0, ANY_ROUTE },
3d3f5ca1
 	{"dlg_db_load_callid", (cmd_function)w_dlg_db_load_callid, 1, fixup_spve_null,
 			0, ANY_ROUTE },
0f2f7611
 	{"dlg_db_load_extra", (cmd_function)w_dlg_db_load_extra, 0, 0,
 			0, ANY_ROUTE },
3d3f5ca1
 
80998a7f
 	{"load_dlg",  (cmd_function)load_dlg,   0, 0, 0, 0},
 	{0,0,0,0,0,0}
5b3d7218
 };
 
 static param_export_t mod_params[]={
a70300b1
 	{ "enable_stats",          INT_PARAM, &dlg_enable_stats         },
 	{ "hash_size",             INT_PARAM, &dlg_hash_size            },
31c1415e
 	{ "rr_param",              PARAM_STRING, &rr_param                 },
a70300b1
 	{ "dlg_flag",              INT_PARAM, &dlg_flag                 },
31c1415e
 	{ "timeout_avp",           PARAM_STR, &timeout_spec           },
a70300b1
 	{ "default_timeout",       INT_PARAM, &default_timeout          },
31c1415e
 	{ "dlg_extra_hdrs",        PARAM_STR, &dlg_extra_hdrs         },
a70300b1
 	{ "dlg_match_mode",        INT_PARAM, &seq_match_mode           },
0b665153
 	{ "detect_spirals",        INT_PARAM, &detect_spirals,          },
31c1415e
 	{ "db_url",                PARAM_STR, &db_url                 },
0b8226f9
 	{ "db_mode",               INT_PARAM, &dlg_db_mode_param        },
31c1415e
 	{ "table_name",            PARAM_STR, &dialog_table_name        },
 	{ "call_id_column",        PARAM_STR, &call_id_column         },
 	{ "from_uri_column",       PARAM_STR, &from_uri_column        },
 	{ "from_tag_column",       PARAM_STR, &from_tag_column        },
 	{ "to_uri_column",         PARAM_STR, &to_uri_column          },
 	{ "to_tag_column",         PARAM_STR, &to_tag_column          },
 	{ "h_id_column",           PARAM_STR, &h_id_column            },
 	{ "h_entry_column",        PARAM_STR, &h_entry_column         },
 	{ "state_column",          PARAM_STR, &state_column           },
 	{ "start_time_column",     PARAM_STR, &start_time_column      },
 	{ "timeout_column",        PARAM_STR, &timeout_column         },
 	{ "to_cseq_column",        PARAM_STR, &to_cseq_column         },
 	{ "from_cseq_column",      PARAM_STR, &from_cseq_column       },
 	{ "to_route_column",       PARAM_STR, &to_route_column        },
 	{ "from_route_column",     PARAM_STR, &from_route_column      },
 	{ "to_contact_column",     PARAM_STR, &to_contact_column      },
 	{ "from_contact_column",   PARAM_STR, &from_contact_column    },
 	{ "to_sock_column",        PARAM_STR, &to_sock_column         },
 	{ "from_sock_column",      PARAM_STR, &from_sock_column       },
 	{ "sflags_column",         PARAM_STR, &sflags_column          },
 	{ "toroute_name_column",   PARAM_STR, &toroute_name_column    },
 
 	{ "vars_table_name",       PARAM_STR, &dialog_vars_table_name   },
 	{ "vars_h_id_column",      PARAM_STR, &vars_h_id_column       },
 	{ "vars_h_entry_column",   PARAM_STR, &vars_h_entry_column    },
 	{ "vars_key_column",       PARAM_STR, &vars_key_column        },
 	{ "vars_value_column",     PARAM_STR, &vars_value_column      },
60d9c557
 
a70300b1
 	{ "db_update_period",      INT_PARAM, &db_update_period         },
68c8b77d
 	{ "db_fetch_rows",         INT_PARAM, &db_fetch_rows            },
31c1415e
 	{ "profiles_with_value",   PARAM_STRING, &profiles_wv_s            },
 	{ "profiles_no_value",     PARAM_STRING, &profiles_nv_s            },
 	{ "bridge_controller",     PARAM_STR, &dlg_bridge_controller  },
64490219
 	{ "bridge_contact",        PARAM_STR, &dlg_bridge_contact       },
31c1415e
 	{ "ruri_pvar",             PARAM_STR, &ruri_pvar_param        },
48b8190c
 	{ "initial_cbs_inscript",  INT_PARAM, &initial_cbs_inscript     },
84d38ce7
 	{ "send_bye",              INT_PARAM, &dlg_send_bye             },
53ec53db
 	{ "wait_ack",              INT_PARAM, &dlg_wait_ack             },
31c1415e
 	{ "xavp_cfg",              PARAM_STR, &dlg_xavp_cfg           },
7d013ceb
 	{ "ka_timer",              INT_PARAM, &dlg_ka_timer             },
 	{ "ka_interval",           INT_PARAM, &dlg_ka_interval          },
b5993240
 	{ "timeout_noreset",       INT_PARAM, &dlg_timeout_noreset      },
1157db7c
 	{ "timer_procs",           PARAM_INT, &dlg_timer_procs          },
94f18a95
 	{ "track_cseq_updates",    PARAM_INT, &_dlg_track_cseq_updates  },
d8c92fd3
 	{ "lreq_callee_headers",   PARAM_STR, &dlg_lreq_callee_headers  },
9eb6ab94
 	{ "db_skip_load",          INT_PARAM, &db_skip_load             },
e8cd0ebb
 	{ "ka_failed_limit",       INT_PARAM, &dlg_ka_failed_limit      },
9fe51ed4
 	{ "enable_dmq",            INT_PARAM, &dlg_enable_dmq           },
3c6b3ecb
 	{ "event_callback",        PARAM_STR, &dlg_event_callback       },
 	{ "early_timeout",         PARAM_INT, &dlg_early_timeout        },
 	{ "noack_timeout",         PARAM_INT, &dlg_noack_timeout        },
313265ac
 	{ "end_timeout",           PARAM_INT, &dlg_end_timeout          },
8f9b6ea5
 	{ "h_id_start",            PARAM_INT, &dlg_h_id_start           },
 	{ "h_id_step",             PARAM_INT, &dlg_h_id_step            },
0b3562ac
 	{ "keep_proxy_rr",         INT_PARAM, &dlg_keep_proxy_rr        },
14348216
 	{ "dlg_filter_mode",       INT_PARAM, &dlg_filter_mode          },
5b3d7218
 	{ 0,0,0 }
 };
 
 
 static stat_export_t mod_stats[] = {
 	{"active_dialogs" ,     STAT_NO_RESET,  &active_dlgs       },
f56ae82e
 	{"early_dialogs",       STAT_NO_RESET,  &early_dlgs        },
5b3d7218
 	{"processed_dialogs" ,  0,              &processed_dlgs    },
 	{"expired_dialogs" ,    0,              &expired_dlgs      },
f56ae82e
 	{"failed_dialogs",      0,              &failed_dlgs       },
5b3d7218
 	{0,0,0}
 };
 
9591ceb0
 static rpc_export_t rpc_methods[];
5b3d7218
 
b0a7f212
 static pv_export_t mod_items[] = {
b162288d
 	{ {"DLG_count",  sizeof("DLG_count")-1}, PVT_OTHER,  pv_get_dlg_count,    0,
b0a7f212
 		0, 0, 0, 0 },
b162288d
 	{ {"DLG_lifetime",sizeof("DLG_lifetime")-1}, PVT_OTHER, pv_get_dlg_lifetime, 0,
b0a7f212
 		0, 0, 0, 0 },
b162288d
 	{ {"DLG_status",  sizeof("DLG_status")-1}, PVT_OTHER, pv_get_dlg_status, 0,
b0a7f212
 		0, 0, 0, 0 },
29d70f7d
 	{ {"dlg_ctx",  sizeof("dlg_ctx")-1}, PVT_OTHER, pv_get_dlg_ctx,
 		pv_set_dlg_ctx, pv_parse_dlg_ctx_name, 0, 0, 0 },
 	{ {"dlg",  sizeof("dlg")-1}, PVT_OTHER, pv_get_dlg,
 		0, pv_parse_dlg_name, 0, 0, 0 },
60d9c557
 	{ {"dlg_var", sizeof("dlg_var")-1}, PVT_OTHER, pv_get_dlg_variable,
 		pv_set_dlg_variable,    pv_parse_dialog_var_name, 0, 0, 0},
b0a7f212
 	{ {0, 0}, 0, 0, 0, 0, 0, 0, 0 }
ee90e8e2
 };
 
5b3d7218
 struct module_exports exports= {
 	"dialog",        /* module's name */
51716422
 	DEFAULT_DLFLAGS, /* dlopen flags */
5b3d7218
 	cmds,            /* exported functions */
 	mod_params,      /* param exports */
8fdc4da6
 	0,               /* exported RPC methods */
ee90e8e2
 	mod_items,       /* exported pseudo-variables */
5b3d7218
 	0,               /* reply processing function */
8fdc4da6
 	mod_init,        /* module initialization function */
 	child_init,      /* per-child init function */
 	mod_destroy
5b3d7218
 };
 
 
4d41d724
 static int fixup_profile(void** param, int param_no)
 {
 	struct dlg_profile_table *profile;
2a7ada93
 	pv_elem_t *model=NULL;
4d41d724
 	str s;
 
 	s.s = (char*)(*param);
 	s.len = strlen(s.s);
2a7ada93
 	if(s.len==0) {
 		LM_ERR("param %d is empty string!\n", param_no);
 		return E_CFG;
 	}
4d41d724
 
 	if (param_no==1) {
 		profile = search_dlg_profile( &s );
 		if (profile==NULL) {
c3291cfe
 			LM_CRIT("profile <%s> not defined\n",s.s);
4d41d724
 			return E_CFG;
 		}
 		pkg_free(*param);
 		*param = (void*)profile;
 		return 0;
 	} else if (param_no==2) {
2a7ada93
 		if(pv_parse_format(&s ,&model) || model==NULL) {
 			LM_ERR("wrong format [%s] for value param!\n", s.s);
 			return E_CFG;
 		}
 		*param = (void*)model;
4d41d724
 	}
 	return 0;
 }
 
 
 static int fixup_get_profile2(void** param, int param_no)
 {
 	pv_spec_t *sp;
 	int ret;
 
 	if (param_no==1) {
 		return fixup_profile(param, 1);
 	} else if (param_no==2) {
efa24adc
 		ret = fixup_pvar_null(param, 1);
4d41d724
 		if (ret<0) return ret;
 		sp = (pv_spec_t*)(*param);
 		if (sp->type!=PVT_AVP && sp->type!=PVT_SCRIPTVAR) {
 			LM_ERR("return must be an AVP or SCRIPT VAR!\n");
 			return E_SCRIPT;
 		}
 	}
 	return 0;
 }
 
 
 static int fixup_get_profile3(void** param, int param_no)
 {
 	if (param_no==1) {
 		return fixup_profile(param, 1);
 	} else if (param_no==2) {
 		return fixup_profile(param, 2);
 	} else if (param_no==3) {
 		return fixup_get_profile2( param, 2);
 	}
 	return 0;
 }
 
 
 
5b3d7218
 int load_dlg( struct dlg_binds *dlgb )
 {
 	dlgb->register_dlgcb = register_dlgcb;
f43f2f1e
 	dlgb->terminate_dlg = dlg_bye_all;
c021559e
 	dlgb->set_dlg_var = set_dlg_variable;
 	dlgb->get_dlg_var = get_dlg_variable;
0f702f6e
 	dlgb->get_dlg = dlg_get_msg_dialog;
 	dlgb->release_dlg = dlg_release;
5b3d7218
 	return 1;
 }
 
 
b0a7f212
 static int pv_get_dlg_count(struct sip_msg *msg, pv_param_t *param,
 		pv_value_t *res)
5b3d7218
 {
 	int n;
 	int l;
 	char *ch;
 
 	if(msg==NULL || res==NULL)
 		return -1;
 
60d9c557
 	n = active_dlgs ? get_stat_val(active_dlgs) : 0;
5b3d7218
 	l = 0;
 	ch = int2str( n, &l);
 
 	res->rs.s = ch;
 	res->rs.len = l;
 
 	res->ri = n;
b0a7f212
 	res->flags = PV_VAL_STR|PV_VAL_INT|PV_TYPE_INT;
5b3d7218
 
 	return 0;
 }
 
 
 static int mod_init(void)
 {
fcb8aeaf
 	unsigned int n;
cddcf1da
 	sr_cfgenv_t *cenv = NULL;
aa7edc2b
 
8f9b6ea5
 	if(dlg_h_id_start==-1) {
 		dlg_h_id_start = server_id;
 	} else if(dlg_h_id_start<0) {
 		dlg_h_id_start = 0;
 	}
 
 	if(dlg_h_id_step<1) {
 		dlg_h_id_step = 1;
 	}
 
5c5b587d
 	if(dlg_ka_interval!=0 && dlg_ka_interval<30) {
 		LM_ERR("ka interval too low (%d), has to be at least 30\n",
 				dlg_ka_interval);
 		return -1;
 	}
 
a46f2ee6
 	dlg_event_rt[DLG_EVENTRT_START] = route_lookup(&event_rt, "dialog:start");
 	dlg_event_rt[DLG_EVENTRT_END] = route_lookup(&event_rt, "dialog:end");
65889069
 	dlg_event_rt[DLG_EVENTRT_FAILED] = route_lookup(&event_rt, "dialog:failed");
3fc1c922
 
 #ifdef STATISTICS
 	/* register statistics */
8fdc4da6
 	if (dlg_enable_stats && (register_module_stats( exports.name, mod_stats)!=0 )) {
e0e0a753
 		LM_ERR("failed to register %s statistics\n", exports.name);
3fc1c922
 		return -1;
 	}
 #endif
 
9591ceb0
 	if (rpc_register_array(rpc_methods)!=0) {
 		LM_ERR("failed to register RPC commands\n");
 		return -1;
 	}
 
29d70f7d
 	if(faked_msg_init()<0)
 		return -1;
 
64490219
 	if(dlg_bridge_init_hdrs()<0)
 		return -1;
 
5b3d7218
 	/* param checkings */
404f4037
 	if (dlg_flag!=-1 && dlg_flag>MAX_FLAG) {
 		LM_ERR("invalid dlg flag %d!!\n", dlg_flag);
5b3d7218
 		return -1;
 	}
 
 	if (rr_param==0 || rr_param[0]==0) {
b9bb99d2
 		LM_ERR("empty rr_param!!\n");
5b3d7218
 		return -1;
 	} else if (strlen(rr_param)>MAX_DLG_RR_PARAM_NAME) {
b9bb99d2
 		LM_ERR("rr_param too long (max=%d)!!\n", MAX_DLG_RR_PARAM_NAME);
5b3d7218
 		return -1;
 	}
 
0b3562ac
 	if (dlg_keep_proxy_rr < 0 || dlg_keep_proxy_rr > 3) {
 		LM_ERR("invalid value for keep_proxy_rr\n");
 		return -1;
 	}
 
e2cf6343
 	if (timeout_spec.s) {
cddcf1da
 		if ( pv_parse_spec(&timeout_spec, &timeout_avp)==0
b0a7f212
 				&& (timeout_avp.type!=PVT_AVP)){
b9bb99d2
 			LM_ERR("malformed or non AVP timeout "
abac67b5
 				"AVP definition in '%.*s'\n", timeout_spec.len,timeout_spec.s);
5b3d7218
 			return -1;
 		}
 	}
 
 	if (default_timeout<=0) {
b9bb99d2
 		LM_ERR("0 default_timeout not accepted!!\n");
5b3d7218
 		return -1;
 	}
 
31c1415e
 	if (ruri_pvar_param.s==NULL || ruri_pvar_param.len<=0) {
8c1b49d5
 		LM_ERR("invalid r-uri PV string\n");
 		return -1;
 	}
31c1415e
 
8c1b49d5
 	if(pv_parse_format(&ruri_pvar_param, &ruri_param_model) < 0
 				|| ruri_param_model==NULL) {
 		LM_ERR("malformed r-uri PV string: %s\n", ruri_pvar_param.s);
 		return -1;
 	}
 
48b8190c
 	if (initial_cbs_inscript != 0 && initial_cbs_inscript != 1) {
ad4cfe8a
 		LM_ERR("invalid parameter for running initial callbacks in-script"
 				" (must be either 0 or 1)\n");
48b8190c
 		return -1;
 	}
 
2fc86906
 	if (seq_match_mode!=SEQ_MATCH_NO_ID &&
 	seq_match_mode!=SEQ_MATCH_FALLBACK &&
 	seq_match_mode!=SEQ_MATCH_STRICT_ID ) {
b9bb99d2
 		LM_ERR("invalid value %d for seq_match_mode param!!\n",seq_match_mode);
2fc86906
 		return -1;
 	}
 
0b665153
 	if (detect_spirals != 0 && detect_spirals != 1) {
 		LM_ERR("invalid value %d for detect_spirals param!!\n",detect_spirals);
 		return -1;
 	}
 
b5993240
 	if (dlg_timeout_noreset != 0 && dlg_timeout_noreset != 1) {
 		LM_ERR("invalid value %d for timeout_noreset param!!\n",
 				dlg_timeout_noreset);
c70823c0
 		return -1;
 	}
 
4d41d724
 	/* create profile hashes */
 	if (add_profile_definitions( profiles_nv_s, 0)!=0 ) {
 		LM_ERR("failed to add profiles without value\n");
 		return -1;
 	}
 	if (add_profile_definitions( profiles_wv_s, 1)!=0 ) {
 		LM_ERR("failed to add profiles with value\n");
 		return -1;
 	}
 
5b3d7218
 	/* load the TM API */
 	if (load_tm_api(&d_tmb)!=0) {
b9bb99d2
 		LM_ERR("can't load TM API\n");
5b3d7218
 		return -1;
 	}
 
 	/* load RR API also */
 	if (load_rr_api(&d_rrb)!=0) {
b9bb99d2
 		LM_ERR("can't load RR API\n");
5b3d7218
 		return -1;
 	}
 
 	/* register callbacks*/
 	/* listen for all incoming requests  */
aedf352d
 	if ( d_tmb.register_tmcb( 0, 0, TMCB_REQUEST_IN, dlg_onreq, 0, 0 ) <=0 ) {
b9bb99d2
 		LM_ERR("cannot register TMCB_REQUEST_IN callback\n");
5b3d7218
 		return -1;
 	}
 
 	/* listen for all routed requests  */
 	if ( d_rrb.register_rrcb( dlg_onroute, 0 ) <0 ) {
b9bb99d2
 		LM_ERR("cannot register RR callback\n");
5b3d7218
 		return -1;
 	}
 
8216129f
 	if (register_script_cb( profile_cleanup, POST_SCRIPT_CB|REQUEST_CB,0)<0) {
e3298264
 		LM_ERR("cannot register script callback");
4d41d724
 		return -1;
 	}
29d70f7d
 	if (register_script_cb(dlg_cfg_cb,
8216129f
 				PRE_SCRIPT_CB|REQUEST_CB,0)<0)
29d70f7d
 	{
e3298264
 		LM_ERR("cannot register pre-script ctx callback\n");
29d70f7d
 		return -1;
 	}
 	if (register_script_cb(dlg_cfg_cb,
8216129f
 				POST_SCRIPT_CB|REQUEST_CB,0)<0)
29d70f7d
 	{
e3298264
 		LM_ERR("cannot register post-script ctx callback\n");
29d70f7d
 		return -1;
 	}
4d41d724
 
b0679c91
 	if (register_script_cb(spiral_detect_reset,POST_SCRIPT_CB|REQUEST_CB,0)<0) {
48b8190c
 		LM_ERR("cannot register req pre-script spiral detection reset callback\n");
 		return -1;
 	}
 
b0679c91
 	if (register_script_cb(cb_dlg_locals_reset,POST_SCRIPT_CB|ONREPLY_CB,0)<0) {
dcdb73d7
 		LM_ERR("cannot register reply post-script dlg locals reset callback\n");
 		return -1;
 	}
 
b0679c91
 	if (register_script_cb(cb_dlg_locals_reset,POST_SCRIPT_CB|FAILURE_CB,0)<0) {
dcdb73d7
 		LM_ERR("cannot register failure post-script dlg locals reset callback\n");
 		return -1;
 	}
 
1157db7c
 	if(dlg_timer_procs<=0) {
 		if ( register_timer( dlg_timer_routine, 0, 1)<0 ) {
 			LM_ERR("failed to register timer \n");
 			return -1;
 		}
 	} else {
 		register_sync_timers(1);
5b3d7218
 	}
 
 	/* init handlers */
 	init_dlg_handlers( rr_param, dlg_flag,
0b3562ac
 		timeout_spec.s?&timeout_avp:0, default_timeout, seq_match_mode, dlg_keep_proxy_rr);
5b3d7218
 
 	/* init timer */
 	if (init_dlg_timer(dlg_ontimeout)!=0) {
b9bb99d2
 		LM_ERR("cannot init timer list\n");
5b3d7218
 		return -1;
 	}
 
11033b05
 	/* sanitize dlg_hash_zie */
 	if (dlg_hash_size < 1){
 		LM_WARN("hash_size is smaller "
 				"then 1  -> rounding from %d to 1\n",
 				dlg_hash_size);
 		dlg_hash_size = 1;
 	}
5b3d7218
 	/* initialized the hash table */
 	for( n=0 ; n<(8*sizeof(n)) ; n++) {
 		if (dlg_hash_size==(1<<n))
 			break;
11033b05
 		if (n && dlg_hash_size<(1<<n)) {
b9bb99d2
 			LM_WARN("hash_size is not a power "
5b3d7218
 				"of 2 as it should be -> rounding from %d to %d\n",
 				dlg_hash_size, 1<<(n-1));
 			dlg_hash_size = 1<<(n-1);
 		}
 	}
a70300b1
 
5b3d7218
 	if ( init_dlg_table(dlg_hash_size)<0 ) {
b9bb99d2
 		LM_ERR("failed to create hash table\n");
5b3d7218
 		return -1;
 	}
 
aa7edc2b
 	/* if a database should be used to store the dialogs' information */
0b8226f9
 	dlg_db_mode = dlg_db_mode_param;
8a717ade
 	if (dlg_db_mode==DB_MODE_NONE) {
e2cf6343
 		db_url.s = 0; db_url.len = 0;
8a717ade
 	} else {
8129c9a9
 		if (dlg_db_mode!=DB_MODE_REALTIME &&
 		dlg_db_mode!=DB_MODE_DELAYED && dlg_db_mode!=DB_MODE_SHUTDOWN ) {
b9bb99d2
 			LM_ERR("unsupported db_mode %d\n", dlg_db_mode);
a70300b1
 			return -1;
 		}
e2cf6343
 		if ( !db_url.s || db_url.len==0 ) {
8a717ade
 			LM_ERR("db_url not configured for db_mode %d\n", dlg_db_mode);
 			return -1;
 		}
9eb6ab94
 		if (init_dlg_db(&db_url, dlg_hash_size, db_update_period, db_fetch_rows, db_skip_load)!=0) {
aa7edc2b
 			LM_ERR("failed to initialize the DB support\n");
 			return -1;
 		}
a70300b1
 	}
 
97781390
 
 	/* timer process to send keep alive requests */
7d013ceb
 	if(dlg_ka_timer>0 && dlg_ka_interval>0)
 		register_sync_timers(1);
aa7edc2b
 
97781390
 	/* timer process to clean old unconfirmed dialogs */
 	register_sync_timers(1);
 
cddcf1da
 	if(_dlg_track_cseq_updates!=0) {
 		cenv = sr_cfgenv_get();
cc5e86d7
 		cenv->cb_cseq_update = dlg_cseq_update;
94f18a95
 		dlg_register_cseq_callbacks();
cddcf1da
 	}
94f18a95
 
9fe51ed4
 	if (dlg_enable_dmq>0 && dlg_dmq_initialize()!=0) {
 		LM_ERR("failed to initialize dmq integration\n");
 		return -1;
 	}
 
1ff86ffc
 	if(dlg_db_mode==DB_MODE_SHUTDOWN) {
 		ksr_module_set_flag(KSRMOD_FLAG_POSTCHILDINIT);
 	}
 
5b3d7218
 	return 0;
 }
 
 
011f0642
 static int child_init(int rank)
 {
0b8226f9
 	dlg_db_mode = dlg_db_mode_param;
 
3d0e1f79
 
 	if(rank==PROC_INIT) {
 		if (dlg_db_mode!=DB_MODE_NONE) {
 			run_load_callbacks();
 		}
 	}
 
97781390
 	if(rank==PROC_MAIN) {
1157db7c
 		if(dlg_timer_procs>0) {
 			if(fork_sync_timer(PROC_TIMER, "Dialog Main Timer", 1 /*socks flag*/,
 					dlg_timer_routine, NULL, 1 /*every sec*/)<0) {
 				LM_ERR("failed to start main timer routine as process\n");
 				return -1; /* error */
 			}
 		}
 
97781390
 		if(dlg_ka_timer>0 && dlg_ka_interval>0) {
 			if(fork_sync_timer(PROC_TIMER, "Dialog KA Timer", 1 /*socks flag*/,
 					dlg_ka_timer_exec, NULL, dlg_ka_timer /*sec*/)<0) {
 				LM_ERR("failed to start ka timer routine as process\n");
 				return -1; /* error */
 			}
 		}
 
 		if(fork_sync_timer(PROC_TIMER, "Dialog Clean Timer", 1 /*socks flag*/,
 					dlg_clean_timer_exec, NULL, dlg_clean_timer /*sec*/)<0) {
 			LM_ERR("failed to start clean timer routine as process\n");
7d013ceb
 			return -1; /* error */
 		}
 	}
 
1ff86ffc
 	if ( ((dlg_db_mode==DB_MODE_REALTIME || dlg_db_mode==DB_MODE_DELAYED)
 				&& (rank>0 || rank==PROC_TIMER || rank==PROC_RPC))
 			|| (dlg_db_mode==DB_MODE_SHUTDOWN && (rank==PROC_POSTCHILDINIT)) ) {
e2cf6343
 		if ( dlg_connect_db(&db_url) ) {
011f0642
 			LM_ERR("failed to connect to database (rank=%d)\n",rank);
 			return -1;
 		}
 	}
 
8129c9a9
 	/* in DB_MODE_SHUTDOWN only PROC_MAIN will do a DB dump at the end, so
 	 * for the rest of the processes will be the same as DB_MODE_NONE */
 	if (dlg_db_mode==DB_MODE_SHUTDOWN && rank!=PROC_MAIN)
 		dlg_db_mode = DB_MODE_NONE;
7c79fc7a
 	/* in DB_MODE_REALTIME and DB_MODE_DELAYED the PROC_MAIN have no DB handle */
ffcf29e6
 	if ( (dlg_db_mode==DB_MODE_REALTIME || dlg_db_mode==DB_MODE_DELAYED) &&
7c79fc7a
 			rank==PROC_MAIN)
ffcf29e6
 		dlg_db_mode = DB_MODE_NONE;
8129c9a9
 
011f0642
 	return 0;
 }
 
 
351fc577
 static void mod_destroy(void)
5b3d7218
 {
8129c9a9
 	if(dlg_db_mode == DB_MODE_DELAYED || dlg_db_mode == DB_MODE_SHUTDOWN) {
b9bb99d2
 		dialog_update_db(0, 0);
 		destroy_dlg_db();
 	}
64490219
 	dlg_bridge_destroy_hdrs();
b9bb99d2
 	/* no DB interaction from now on */
 	dlg_db_mode = DB_MODE_NONE;
5b3d7218
 	destroy_dlg_table();
2fd1d5fb
 	destroy_dlg_timer();
aa7edc2b
 	destroy_dlg_callbacks( DLGCB_CREATED|DLGCB_LOADED );
d6cc5af6
 	destroy_dlg_handlers();
4d41d724
 	destroy_dlg_profiles();
5b3d7218
 }
 
4d41d724
 
1a38dd7b
 static int w_set_dlg_profile_helper(sip_msg_t *msg,
 		struct dlg_profile_table *profile, str *value)
 {
 	if (profile->has_value) {
 		if (value==NULL || value->len<=0) {
 			LM_ERR("invalid value parameter\n");
 			return -1;
 		}
 		if ( set_dlg_profile( msg, value, profile) < 0 ) {
 			LM_ERR("failed to set profile with key\n");
 			return -1;
 		}
 	} else {
 		if ( set_dlg_profile( msg, NULL, profile) < 0 ) {
 			LM_ERR("failed to set profile\n");
 			return -1;
 		}
 	}
 	return 1;
 }
4d41d724
 
 static int w_set_dlg_profile(struct sip_msg *msg, char *profile, char *value)
 {
1a38dd7b
 	pv_elem_t *pve = NULL;
 	str val_s = STR_NULL;
4d41d724
 
2a7ada93
 	pve = (pv_elem_t *)value;
1a38dd7b
 	if(pve!=NULL) {
 		if(pv_printf_s(msg, pve, &val_s)!=0 || val_s.len <= 0
 				|| val_s.s == NULL) {
4d41d724
 			LM_WARN("cannot get string for value\n");
 			return -1;
 		}
1a38dd7b
 	}
 
 	return w_set_dlg_profile_helper(msg, (struct dlg_profile_table*)profile,
 				&val_s);
 }
 
 static int w_unset_dlg_profile_helper(sip_msg_t *msg,
 		struct dlg_profile_table *profile, str *value)
 {
 	if (profile->has_value) {
 		if (value==NULL || value->len<=0) {
 			LM_ERR("invalid value parameter\n");
 			return -1;
 		}
 		if ( unset_dlg_profile( msg, value, profile) < 0 ) {
 			LM_ERR("failed to unset profile with key\n");
4d41d724
 			return -1;
 		}
 	} else {
1a38dd7b
 		if ( unset_dlg_profile( msg, NULL, profile) < 0 ) {
 			LM_ERR("failed to unset profile\n");
4d41d724
 			return -1;
 		}
 	}
 	return 1;
 }
 
04ca7955
 static int w_unset_dlg_profile(struct sip_msg *msg, char *profile, char *value)
 {
1a38dd7b
 	pv_elem_t *pve = NULL;
 	str val_s = STR_NULL;
04ca7955
 
 	pve = (pv_elem_t *)value;
1a38dd7b
 	if(pve!=NULL) {
 		if(pv_printf_s(msg, pve, &val_s)!=0 || val_s.len <= 0
 				|| val_s.s == NULL) {
04ca7955
 			LM_WARN("cannot get string for value\n");
 			return -1;
 		}
1a38dd7b
 	}
 
 	return w_unset_dlg_profile_helper(msg, (struct dlg_profile_table*)profile,
 				&val_s);
 }
 
 static int w_is_in_profile_helper(sip_msg_t *msg,
 		struct dlg_profile_table *profile, str *value)
 {
 	if (profile->has_value) {
 		if (value==NULL || value->len<=0) {
 			LM_ERR("invalid value parameter\n");
04ca7955
 			return -1;
 		}
1a38dd7b
 		return is_dlg_in_profile( msg, profile, value);
04ca7955
 	} else {
1a38dd7b
 		return is_dlg_in_profile( msg, profile, NULL);
04ca7955
 	}
 }
 
4d41d724
 static int w_is_in_profile(struct sip_msg *msg, char *profile, char *value)
 {
1a38dd7b
 	pv_elem_t *pve = NULL;
 	str val_s = STR_NULL;
4d41d724
 
2a7ada93
 	pve = (pv_elem_t *)value;
1a38dd7b
 	if(pve!=NULL) {
 		if(pv_printf_s(msg, pve, &val_s)!=0 || val_s.len <= 0
 				|| val_s.s == NULL) {
4d41d724
 			LM_WARN("cannot get string for value\n");
 			return -1;
 		}
 	}
 
1a38dd7b
 	return w_is_in_profile_helper(msg, (struct dlg_profile_table*)profile,
 				&val_s);
 }
4d41d724
 
028e3cc1
 /**
  * get dynamic name profile size
  */
1a38dd7b
 static int w_get_profile_size_helper(sip_msg_t *msg,
 		struct dlg_profile_table *profile, str *value, pv_spec_t *spd)
4d41d724
 {
 	unsigned int size;
86fe9674
 	pv_value_t val;
4d41d724
 
1a38dd7b
 	if (profile->has_value) {
 		if(value==NULL || value->s==NULL || value->len<=0) {
 			LM_ERR("invalid value parameter\n");
4d41d724
 			return -1;
 		}
1a38dd7b
 		size = get_profile_size( profile, value );
4d41d724
 	} else {
1a38dd7b
 		size = get_profile_size( profile, NULL );
4d41d724
 	}
 
86fe9674
 	memset(&val, 0, sizeof(pv_value_t));
 	val.flags = PV_VAL_INT|PV_TYPE_INT;
 	val.ri = (int)size;
4d41d724
 
1a38dd7b
 	if(spd->setf(msg, &spd->pvp, (int)EQ_T, &val)<0)
86fe9674
 	{
 		LM_ERR("setting profile PV failed\n");
 		return -1;
4d41d724
 	}
 
 	return 1;
 }
 
1a38dd7b
 static int w_get_profile_size3(struct sip_msg *msg, char *profile,
 		char *value, char *result)
 {
 	pv_elem_t *pve = NULL;
 	str val_s = STR_NULL;
 	pv_spec_t *spd = NULL;
 
 	if(result!=NULL)
 	{
 		pve = (pv_elem_t *)value;
 		spd = (pv_spec_t *)result;
 	} else {
 		pve = NULL;
 		spd = (pv_spec_t *)value;
 	}
 	if (pve!=NULL) {
 		if ( pv_printf_s(msg, pve, &val_s)!=0
 				|| val_s.len == 0 || val_s.s == NULL) {
 			LM_WARN("cannot get string for value\n");
 			return -1;
 		}
 	}
 
 	return w_get_profile_size_helper(msg, (struct dlg_profile_table*)profile,
 			(pve)?&val_s:NULL, spd);
 }
028e3cc1
 
 /**
  * get static name profile size
  */
 static int w_get_profile_size2(struct sip_msg *msg, char *profile, char *result)
 {
 	return w_get_profile_size3(msg, profile, result, NULL);
 }
 
 
0b9899a5
 static int ki_dlg_setflag(struct sip_msg *msg, int val)
29d70f7d
 {
5d131fe7
 	dlg_ctx_t *dctx;
5bdee1ff
 	dlg_cell_t *d;
4d41d724
 
29d70f7d
 	if(val<0 || val>31)
 		return -1;
5d131fe7
 	if ( (dctx=dlg_get_dlg_ctx())==NULL )
29d70f7d
 		return -1;
 
5d131fe7
 	dctx->flags |= 1<<val;
5bdee1ff
 	d = dlg_get_by_iuid(&dctx->iuid);
 	if(d!=NULL) {
 		d->sflags |= 1<<val;
 		dlg_release(d);
 	}
29d70f7d
 	return 1;
 }
 
0b9899a5
 static int w_dlg_setflag(struct sip_msg *msg, char *flag, char *s2)
29d70f7d
 {
 	int val;
 
 	if(fixup_get_ivalue(msg, (gparam_p)flag, &val)!=0)
 	{
 		LM_ERR("no flag value\n");
 		return -1;
 	}
0b9899a5
 
 	return ki_dlg_setflag(msg, val);
 }
 
 static int ki_dlg_resetflag(struct sip_msg *msg, int val)
 {
 	dlg_ctx_t *dctx;
 	dlg_cell_t *d;
 
29d70f7d
 	if(val<0 || val>31)
 		return -1;
 
5d131fe7
 	if ( (dctx=dlg_get_dlg_ctx())==NULL )
29d70f7d
 		return -1;
 
5d131fe7
 	dctx->flags &= ~(1<<val);
5bdee1ff
 	d = dlg_get_by_iuid(&dctx->iuid);
 	if(d!=NULL) {
 		d->sflags &= ~(1<<val);
 		dlg_release(d);
 	}
29d70f7d
 	return 1;
 }
 
0b9899a5
 static int w_dlg_resetflag(struct sip_msg *msg, char *flag, str *s2)
29d70f7d
 {
 	int val;
 
 	if(fixup_get_ivalue(msg, (gparam_p)flag, &val)!=0)
 	{
 		LM_ERR("no flag value\n");
 		return -1;
 	}
0b9899a5
 	return ki_dlg_resetflag(msg, val);
 }
 
 static int ki_dlg_isflagset(struct sip_msg *msg, int val)
 {
 	dlg_ctx_t *dctx;
 	dlg_cell_t *d;
 	int ret;
 
29d70f7d
 	if(val<0 || val>31)
 		return -1;
 
5d131fe7
 	if ( (dctx=dlg_get_dlg_ctx())==NULL )
29d70f7d
 		return -1;
 
5bdee1ff
 	d = dlg_get_by_iuid(&dctx->iuid);
 	if(d!=NULL) {
 		ret = (d->sflags&(1<<val))?1:-1;
 		dlg_release(d);
 		return ret;
 	}
5d131fe7
 	return (dctx->flags&(1<<val))?1:-1;
29d70f7d
 }
 
0b9899a5
 static int w_dlg_isflagset(struct sip_msg *msg, char *flag, str *s2)
 {
 	int val;
 
 	if(fixup_get_ivalue(msg, (gparam_p)flag, &val)!=0)
 	{
 		LM_ERR("no flag value\n");
 		return -1;
 	}
 	return ki_dlg_isflagset(msg, val);
 }
 
7a8ad674
 /**
  *
  */
29d70f7d
 static int w_dlg_manage(struct sip_msg *msg, char *s1, char *s2)
 {
7a8ad674
 	return dlg_manage(msg);
29d70f7d
 }
 
 static int w_dlg_bye(struct sip_msg *msg, char *side, char *s2)
 {
5bdee1ff
 	dlg_cell_t *dlg = NULL;
29d70f7d
 	int n;
 
 	dlg = dlg_get_ctx_dialog();
 	if(dlg==NULL)
 		return -1;
 	
 	n = (int)(long)side;
 	if(n==1)
 	{
 		if(dlg_bye(dlg, NULL, DLG_CALLER_LEG)!=0)
5bdee1ff
 			goto error;
 		goto done;
29d70f7d
 	} else if(n==2) {
 		if(dlg_bye(dlg, NULL, DLG_CALLEE_LEG)!=0)
5bdee1ff
 			goto error;
 		goto done;
29d70f7d
 	} else {
 		if(dlg_bye_all(dlg, NULL)!=0)
5bdee1ff
 			goto error;
 		goto done;
29d70f7d
 	}
5bdee1ff
 
 done:
 	dlg_release(dlg);
 	return 1;
 
 error:
 	dlg_release(dlg);
 	return -1;
29d70f7d
 }
 
 static int w_dlg_refer(struct sip_msg *msg, char *side, char *to)
 {
5bdee1ff
 	dlg_cell_t *dlg;
29d70f7d
 	int n;
 	str st = {0,0};
 
 	dlg = dlg_get_ctx_dialog();
 	if(dlg==NULL)
 		return -1;
 	
 	n = (int)(long)side;
 
 	if(fixup_get_svalue(msg, (gparam_p)to, &st)!=0)
 	{
 		LM_ERR("unable to get To\n");
5bdee1ff
 		goto error;
29d70f7d
 	}
 	if(st.s==NULL || st.len == 0)
 	{
 		LM_ERR("invalid To parameter\n");
5bdee1ff
 		goto error;
29d70f7d
 	}
 	if(n==1)
 	{
 		if(dlg_transfer(dlg, &st, DLG_CALLER_LEG)!=0)
5bdee1ff
 			goto error;
29d70f7d
 	} else {
 		if(dlg_transfer(dlg, &st, DLG_CALLEE_LEG)!=0)
5bdee1ff
 			goto error;
29d70f7d
 	}
5bdee1ff
 
 	dlg_release(dlg);
29d70f7d
 	return 1;
5bdee1ff
 
 error:
 	dlg_release(dlg);
 	return -1;
29d70f7d
 }
 
 static int w_dlg_bridge(struct sip_msg *msg, char *from, char *to, char *op)
 {
 	str sf = {0,0};
 	str st = {0,0};
 	str so = {0,0};
 
 	if(from==0 || to==0 || op==0)
 	{
 		LM_ERR("invalid parameters\n");
 		return -1;
 	}
 
 	if(fixup_get_svalue(msg, (gparam_p)from, &sf)!=0)
 	{
 		LM_ERR("unable to get From\n");
 		return -1;
 	}
 	if(sf.s==NULL || sf.len == 0)
 	{
 		LM_ERR("invalid From parameter\n");
 		return -1;
 	}
 	if(fixup_get_svalue(msg, (gparam_p)to, &st)!=0)
 	{
 		LM_ERR("unable to get To\n");
 		return -1;
 	}
 	if(st.s==NULL || st.len == 0)
 	{
 		LM_ERR("invalid To parameter\n");
 		return -1;
 	}
 	if(fixup_get_svalue(msg, (gparam_p)op, &so)!=0)
 	{
 		LM_ERR("unable to get OP\n");
 		return -1;
 	}
 
2df6f560
 	if(dlg_bridge(&sf, &st, &so, NULL)!=0)
29d70f7d
 		return -1;
 	return 1;
 }
 
10f116e7
 static int ki_dlg_bridge(sip_msg_t *msg, str *sfrom, str *sto, str *soproxy)
 {
 	if(dlg_bridge(sfrom, sto, soproxy, NULL)!=0)
 		return -1;
 	return 1;
 
 }
 
3beef50c
 /**
  *
  */
 static int w_dlg_set_timeout(struct sip_msg *msg, char *pto, char *phe, char *phi)
 {
 	int to = 0;
 	unsigned int he = 0;
 	unsigned int hi = 0;
 	dlg_cell_t *dlg = NULL;
 
 	if(fixup_get_ivalue(msg, (gparam_p)pto, &to)!=0)
 	{
 		LM_ERR("no timeout value\n");
 		return -1;
 	}
618888cc
 	if(to<=0) {
 		LM_ERR("invalid timeout value: %d\n", to);
 		return -1;
 	}
3beef50c
 	if(phe!=NULL)
 	{
618888cc
 		if(phi==NULL) {
 			LM_ERR("invalid number of parameters\n");
 			return -1;
 		}
3beef50c
 		if(fixup_get_ivalue(msg, (gparam_p)phe, (int*)&he)!=0)
 		{
 			LM_ERR("no hash entry value value\n");
 			return -1;
 		}
 		if(fixup_get_ivalue(msg, (gparam_p)phi, (int*)&hi)!=0)
 		{
 			LM_ERR("no hash id value value\n");
 			return -1;
 		}
 		dlg = dlg_lookup(he, hi);
 	} else {
 		dlg = dlg_get_msg_dialog(msg);
 	}
 
 	if(dlg==NULL)
 	{
 		LM_DBG("no dialog found\n");
 		return -1;
 	}
 
618888cc
 	if(update_dlg_timeout(dlg, to) != 0)
3beef50c
 		return -1;
17d1934c
 
3beef50c
 	return 1;
 }
29d70f7d
 
bd6e0a29
 /**
  *
  */
 static int ki_dlg_set_property(sip_msg_t *msg, str *pval)
7d013ceb
 {
 	dlg_ctx_t *dctx;
 	dlg_cell_t *d;
 
bd6e0a29
 	if(pval->len<=0) {
7d013ceb
 		LM_ERR("empty property value\n");
 		return -1;
 	}
 	if ( (dctx=dlg_get_dlg_ctx())==NULL )
 		return -1;
 
bd6e0a29
 	if(pval->len==6 && strncmp(pval->s, "ka-src", 6)==0) {
7d013ceb
 		dctx->iflags |= DLG_IFLAG_KA_SRC;
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags |= DLG_IFLAG_KA_SRC;
 			dlg_release(d);
 		}
bd6e0a29
 	} else if(pval->len==6 && strncmp(pval->s, "ka-dst", 6)==0) {
7d013ceb
 		dctx->iflags |= DLG_IFLAG_KA_DST;
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags |= DLG_IFLAG_KA_DST;
 			dlg_release(d);
 		}
bd6e0a29
 	} else if(pval->len==15 && strncmp(pval->s, "timeout-noreset", 15)==0) {
c70823c0
 		dctx->iflags |= DLG_IFLAG_TIMER_NORESET;
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags |= DLG_IFLAG_TIMER_NORESET;
 			dlg_release(d);
 		}
7d013ceb
 	} else {
bd6e0a29
 		LM_ERR("unknown property value [%.*s]\n", pval->len, pval->s);
7d013ceb
 		return -1;
 	}
 
 	return 1;
 }
 
bd6e0a29
 /**
  *
  */
 static int w_dlg_set_property(struct sip_msg *msg, char *prop, char *s2)
 {
 	str val;
 
 	if(fixup_get_svalue(msg, (gparam_t*)prop, &val)!=0)
 	{
 		LM_ERR("no property value\n");
 		return -1;
 	}
 
 	return ki_dlg_set_property(msg, &val);
 }
 
4883b692
 /**
  *
  */
 static int ki_dlg_reset_property(sip_msg_t *msg, str *pval)
 {
 	dlg_ctx_t *dctx;
 	dlg_cell_t *d;
 
 	if(pval->len<=0) {
3af08bbd
 		LM_ERR("empty property value\n");
 		return -1;
4883b692
 	}
 	if ( (dctx=dlg_get_dlg_ctx())==NULL )
3af08bbd
 		return -1;
4883b692
 
 	if(pval->len==6 && strncmp(pval->s, "ka-src", 6)==0) {
3af08bbd
 		dctx->iflags &= ~(DLG_IFLAG_KA_SRC);
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags &= ~(DLG_IFLAG_KA_SRC);
 			dlg_release(d);
 		}
4883b692
 	} else if(pval->len==6 && strncmp(pval->s, "ka-dst", 6)==0) {
3af08bbd
 		dctx->iflags &= ~(DLG_IFLAG_KA_DST);
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags &= ~(DLG_IFLAG_KA_DST);
 			dlg_release(d);
 		}
4883b692
 	} else if(pval->len==15 && strncmp(pval->s, "timeout-noreset", 15)==0) {
3af08bbd
 		dctx->iflags &= ~(DLG_IFLAG_TIMER_NORESET);
 		d = dlg_get_by_iuid(&dctx->iuid);
 		if(d!=NULL) {
 			d->iflags &= ~(DLG_IFLAG_TIMER_NORESET);
 			dlg_release(d);
 		}
4883b692
 	} else {
3af08bbd
 		LM_ERR("unknown property value [%.*s]\n", pval->len, pval->s);
 		return -1;
4883b692
 	}
 
 	return 1;
 }
 
 /**
  *
  */
 static int w_dlg_reset_property(struct sip_msg *msg, char *prop, char *s2)
 {
 	str val;
 
 	if(fixup_get_svalue(msg, (gparam_t*)prop, &val)!=0)
 	{
3af08bbd
 		LM_ERR("no property value\n");
 		return -1;
4883b692
 	}
 
 	return ki_dlg_reset_property(msg, &val);
 }
 
17d1934c
 static int w_dlg_set_timeout_by_profile3(struct sip_msg *msg, char *profile,
 					char *value, char *timeout_str) 
 {
 	pv_elem_t *pve = NULL;
 	str val_s;
 
 	pve = (pv_elem_t *) value;
 
 	if(pve != NULL && ((struct dlg_profile_table *) profile)->has_value) {
 		if(pv_printf_s(msg,pve, &val_s) != 0 || 
 		   !val_s.s || val_s.len == 0) {
 			LM_WARN("cannot get string for value\n");
 			return -1;
 		}
 	}
 
 	if(dlg_set_timeout_by_profile((struct dlg_profile_table *) profile,
 				   &val_s, atoi(timeout_str)) != 0)
 		return -1;
 
 	return 1;
 }
 
 static int w_dlg_set_timeout_by_profile2(struct sip_msg *msg, 
 					 char *profile, char *timeout_str)
 {
 	return w_dlg_set_timeout_by_profile3(msg, profile, NULL, timeout_str);
 }
7d013ceb
 
 void dlg_ka_timer_exec(unsigned int ticks, void* param)
 {
 	dlg_ka_run(ticks);
 }
 
97781390
 void dlg_clean_timer_exec(unsigned int ticks, void* param)
 {
 	dlg_clean_run(ticks);
157a50f7
 	remove_expired_remote_profiles(time(NULL));
97781390
 }
 
29d70f7d
 static int fixup_dlg_bye(void** param, int param_no)
 {
 	char *val;
 	int n = 0;
 
 	if (param_no==1) {
 		val = (char*)*param;
 		if (strcasecmp(val,"all")==0) {
 			n = 0;
 		} else if (strcasecmp(val,"caller")==0) {
 			n = 1;
 		} else if (strcasecmp(val,"callee")==0) {
 			n = 2;
 		} else {
 			LM_ERR("invalid param \"%s\"\n", val);
 			return E_CFG;
 		}
 		pkg_free(*param);
 		*param=(void*)(long)n;
 	} else {
 		LM_ERR("called with parameter != 1\n");
 		return E_BUG;
 	}
 	return 0;
 }
 
 static int fixup_dlg_refer(void** param, int param_no)
 {
 	char *val;
 	int n = 0;
 
 	if (param_no==1) {
 		val = (char*)*param;
 		if (strcasecmp(val,"caller")==0) {
 			n = 1;
 		} else if (strcasecmp(val,"callee")==0) {
 			n = 2;
 		} else {
 			LM_ERR("invalid param \"%s\"\n", val);
 			return E_CFG;
 		}
 		pkg_free(*param);
 		*param=(void*)(long)n;
 	} else if (param_no==2) {
 		return fixup_spve_null(param, 1);
 	} else {
 		LM_ERR("called with parameter idx %d\n", param_no);
 		return E_BUG;
 	}
 	return 0;
 }
 
 static int fixup_dlg_bridge(void** param, int param_no)
 {
 	if (param_no>=1 && param_no<=3) {
 		return fixup_spve_null(param, 1);
 	} else {
 		LM_ERR("called with parameter idx %d\n", param_no);
 		return E_BUG;
 	}
 	return 0;
 }
 
b36d012e
 static int ki_dlg_get(sip_msg_t *msg, str *sc, str *sf, str *st)
29d70f7d
 {
5bdee1ff
 	dlg_cell_t *dlg = NULL;
b36d012e
 	unsigned int dir = 0;
 
 	if(sc==NULL || sc->s==NULL || sc->len == 0) {
 		LM_ERR("invalid Call-ID parameter\n");
 		return -1;
 	}
 	if(sf==NULL || sf->s==NULL || sf->len == 0) {
 		LM_ERR("invalid From tag parameter\n");
 		return -1;
 	}
 	if(st==NULL || st->s==NULL || st->len == 0) {
 		LM_ERR("invalid To tag parameter\n");
 		return -1;
 	}
 
 	dlg = get_dlg(sc, sf, st, &dir);
 	if(dlg==NULL)
 		return -1;
 	/* set shorcut to dialog internal unique id */
 	_dlg_ctx.iuid.h_entry = dlg->h_entry;
 	_dlg_ctx.iuid.h_id = dlg->h_id;
 	_dlg_ctx.dir = dir;
 	dlg_release(dlg);
 	return 1;
 }
 
 static int w_dlg_get(struct sip_msg *msg, char *ci, char *ft, char *tt)
 {
29d70f7d
 	str sc = {0,0};
 	str sf = {0,0};
 	str st = {0,0};
 
 	if(ci==0 || ft==0 || tt==0)
 	{
 		LM_ERR("invalid parameters\n");
 		return -1;
 	}
 
 	if(fixup_get_svalue(msg, (gparam_p)ci, &sc)!=0)
 	{
 		LM_ERR("unable to get Call-ID\n");
 		return -1;
 	}
b36d012e
 
29d70f7d
 	if(fixup_get_svalue(msg, (gparam_p)ft, &sf)!=0)
 	{
 		LM_ERR("unable to get From tag\n");
 		return -1;
 	}
b36d012e
 
29d70f7d
 	if(fixup_get_svalue(msg, (gparam_p)tt, &st)!=0)
 	{
 		LM_ERR("unable to get To Tag\n");
 		return -1;
 	}
 	if(st.s==NULL || st.len == 0)
 	{
 		LM_ERR("invalid To tag parameter\n");
 		return -1;
 	}
 
b36d012e
 	return ki_dlg_get(msg, &sc, &sf, &st);
29d70f7d
 }
9224dafc
 
9c8020d2
 /**
  *
  */
 static int w_dlg_remote_profile(sip_msg_t *msg, char *cmd, char *pname,
 		char *pval, char *puid, char *expires)
 {
 	str scmd;
 	str sname;
 	str sval;
 	str suid;
 	int ival;
 	int ret;
 
 	if(fixup_get_svalue(msg, (gparam_t*)cmd, &scmd)!=0) {
 		LM_ERR("unable to get command\n");
 		return -1;
 	}
 	if(fixup_get_svalue(msg, (gparam_t*)pname, &sname)!=0) {
 		LM_ERR("unable to get profile name\n");
 		return -1;
 	}
 	if(fixup_get_svalue(msg, (gparam_t*)pval, &sval)!=0) {
 		LM_ERR("unable to get profile value\n");
 		return -1;
 	}
 	if(fixup_get_svalue(msg, (gparam_t*)puid, &suid)!=0) {
 		LM_ERR("unable to get profile uid\n");
 		return -1;
 	}
 	if(fixup_get_ivalue(msg, (gparam_t*)expires, &ival)!=0) {
 		LM_ERR("no hash entry value value\n");
 		return -1;
 	}
 
 	ret = dlg_cmd_remote_profile(&scmd, &sname, &sval, &suid, (time_t)ival, 0);
 	if(ret==0)
 		return 1;
 	return ret;
 }
 
 static int fixup_dlg_remote_profile(void** param, int param_no)
 {
 	if(param_no>=1 && param_no<=4)
 		return fixup_spve_null(param, 1);
 	if(param_no==5)
 		return fixup_igp_null(param, 1);
 	return 0;
 }
 
bd6e0a29
 /**
  *
  */
 static int ki_dlg_bye(sip_msg_t *msg, str *side)
 {
 	dlg_cell_t *dlg = NULL;
 
 	dlg = dlg_get_ctx_dialog();
 	if(dlg==NULL)
 		return -1;
 
 	if(side->len==6 && strncasecmp(side->s, "caller", 6)==0)
 	{
 		if(dlg_bye(dlg, NULL, DLG_CALLER_LEG)!=0)
 			goto error;
 		goto done;
 	} else if(side->len==6 && strncasecmp(side->s, "callee", 6)==0) {
 		if(dlg_bye(dlg, NULL, DLG_CALLEE_LEG)!=0)
 			goto error;
 		goto done;
 	} else {
 		if(dlg_bye_all(dlg, NULL)!=0)
 			goto error;
 		goto done;
 	}
 
 done:
 	dlg_release(dlg);
 	return 1;
 
 error:
 	dlg_release(dlg);
 	return -1;
 }
 
 /**
  *
  */
 static int ki_dlg_set_timeout_id(sip_msg_t *msg, int to, int he, int hi)
 {
 	dlg_cell_t *dlg = NULL;
 
 	dlg = dlg_lookup(he, hi);
 	if(dlg==NULL) {
 		LM_DBG("no dialog found\n");
 		return -1;
 	}
 
 	/* update_dlg_timeout() does dlg_release() */
 	if(update_dlg_timeout(dlg, to) != 0)
 		return -1;
 
 	return 1;
 }
 
 /**
  *
  */
 static int ki_dlg_set_timeout(sip_msg_t *msg, int to)
 {
 	dlg_cell_t *dlg = NULL;
 
 	dlg = dlg_get_msg_dialog(msg);
 	if(dlg==NULL) {
 		LM_DBG("no dialog found\n");
 		return -1;
 	}
 
 	/* update_dlg_timeout() does dlg_release() */
 	if(update_dlg_timeout(dlg, to) != 0)
 		return -1;
 
 	return 1;
 
 }
 
1a38dd7b
 /**
  *
  */
 static int ki_set_dlg_profile_static(sip_msg_t *msg, str *sprofile)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_set_dlg_profile_helper(msg, profile, NULL);
 }
 
 /**
  *
  */
 static int ki_set_dlg_profile(sip_msg_t *msg, str *sprofile, str *svalue)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_set_dlg_profile_helper(msg, profile, svalue);
 }
 
 /**
  *
  */
 static int ki_unset_dlg_profile_static(sip_msg_t *msg, str *sprofile)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_unset_dlg_profile_helper(msg, profile, NULL);
 }
 
 /**
  *
  */
 static int ki_unset_dlg_profile(sip_msg_t *msg, str *sprofile, str *svalue)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_unset_dlg_profile_helper(msg, profile, svalue);
 }
 
 /**
  *
  */
 static int ki_is_in_profile_static(sip_msg_t *msg, str *sprofile)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_is_in_profile_helper(msg, profile, NULL);
 }
 
 /**
  *
  */
 static int ki_is_in_profile(sip_msg_t *msg, str *sprofile, str *svalue)
 {
 	struct dlg_profile_table *profile = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 
 	return w_is_in_profile_helper(msg, profile, svalue);
 }
 
 /**
  *
  */
 static int ki_get_profile_size_static(sip_msg_t *msg, str *sprofile, str *spv)
 {
 	struct dlg_profile_table *profile = NULL;
 	pv_spec_t *pvs = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	if(spv==NULL || spv->s==NULL || spv->len<=0) {
 		LM_ERR("invalid destination var name\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 	pvs = pv_cache_get(spv);
 	if(pvs==NULL) {
 		LM_ERR("cannot get pv spec for [%.*s]\n", spv->len, spv->s);
 		return -1;
 	}
 	if (pvs->type!=PVT_AVP && pvs->type!=PVT_SCRIPTVAR) {
 		LM_ERR("return must be an AVP or SCRIPT VAR!\n");
 		return -1;
 	}
 
 	return w_get_profile_size_helper(msg, profile, NULL, pvs);
 }
 
 /**
  *
  */
 static int ki_get_profile_size(sip_msg_t *msg, str *sprofile, str *svalue,
 		str *spv)
 {
 	struct dlg_profile_table *profile = NULL;
 	pv_spec_t *pvs = NULL;
 
 	if(sprofile==NULL || sprofile->s==NULL || sprofile->len<=0) {
 		LM_ERR("invalid profile identifier\n");
 		return -1;
 	}
 	if(spv==NULL || spv->s==NULL || spv->len<=0) {
 		LM_ERR("invalid destination var name\n");
 		return -1;
 	}
 	profile = search_dlg_profile( sprofile );
 	if (profile==NULL) {
 		LM_CRIT("profile <%.*s> not defined\n", sprofile->len, sprofile->s);
 		return -1;
 	}
 	pvs = pv_cache_get(spv);
 	if(pvs==NULL) {
 		LM_ERR("cannot get pv spec for [%.*s]\n", spv->len, spv->s);
 		return -1;
 	}
 	if (pvs->type!=PVT_AVP && pvs->type!=PVT_SCRIPTVAR) {
 		LM_ERR("return must be an AVP or SCRIPT VAR!\n");
 		return -1;
 	}
 
 	return w_get_profile_size_helper(msg, profile, svalue, pvs);
 }
 
3d3f5ca1
 /**
  *
  */
 static int ki_dlg_db_load_callid(sip_msg_t *msg, str *callid)
 {
 	int ret;
 
 	ret = load_dialog_info_from_db(dlg_hash_size, db_fetch_rows, 1, callid);
 
 	if(ret==0) return 1;
 	return ret;
 }
 
 /**
  *
  */
 static int w_dlg_db_load_callid(sip_msg_t *msg, char *ci, char *p2)
 {
 	str sc = {0,0};
 
 	if(ci==0) {
 		LM_ERR("invalid parameters\n");
 		return -1;
 	}
 
 	if(fixup_get_svalue(msg, (gparam_t*)ci, &sc)!=0) {
 		LM_ERR("unable to get Call-ID\n");
 		return -1;
 	}
 
 	return ki_dlg_db_load_callid(msg, &sc);
 }
 
0f2f7611
 /**
  *
  */
 static int ki_dlg_db_load_extra(sip_msg_t *msg)
 {
 	int ret;
 
 	ret = load_dialog_info_from_db(dlg_hash_size, db_fetch_rows, 2, NULL);
 
 	if(ret==0) return 1;
 	return ret;
 }
 
 /**
  *
  */
 static int w_dlg_db_load_extra(sip_msg_t *msg, char *p1, char *p2)
 {
 	return ki_dlg_db_load_extra(msg);
 }
 
7d8ee6fc
 /**
  *
  */
 static int ki_dlg_var_sets(sip_msg_t *msg, str *name, str *val)
 {
 	dlg_cell_t *dlg;
 	int ret;
 
 	dlg = dlg_get_msg_dialog(msg);
 	ret = set_dlg_variable_unsafe(dlg, name, val);
 	if(dlg) {
 		dlg_release(dlg);
 	}
 
 	return (ret==0)?1:ret;
 }
 
 /**
  *
  */
 static sr_kemi_xval_t _sr_kemi_dialog_xval = {0};
 
 /**
  *
  */
 static sr_kemi_xval_t* ki_dlg_var_get_mode(sip_msg_t *msg, str *name, int rmode)
 {
 	dlg_cell_t *dlg;
 	str *pval;
 
 	memset(&_sr_kemi_dialog_xval, 0, sizeof(sr_kemi_xval_t));
 
 	dlg = dlg_get_msg_dialog(msg);
 	if(dlg==NULL) {
 		sr_kemi_xval_null(&_sr_kemi_dialog_xval, rmode);
 		return &_sr_kemi_dialog_xval;
 	}
 	pval = get_dlg_variable(dlg, name);
 	if(pval==NULL || pval->s==NULL) {
 		sr_kemi_xval_null(&_sr_kemi_dialog_xval, rmode);
 		goto done;
 	}
 
 	_sr_kemi_dialog_xval.vtype = SR_KEMIP_STR;
 	_sr_kemi_dialog_xval.v.s = *pval;
 
 done:
 	dlg_release(dlg);
 	return &_sr_kemi_dialog_xval;
 }
 
 /**
  *
  */
 static sr_kemi_xval_t* ki_dlg_var_get(sip_msg_t *msg, str *name)
 {
 	return ki_dlg_var_get_mode(msg, name, SR_KEMI_XVAL_NULL_NONE);
 }
 
71522702
 /**
  *
  */
 static sr_kemi_xval_t* ki_dlg_var_gete(sip_msg_t *msg, str *name)
 {
 	return ki_dlg_var_get_mode(msg, name, SR_KEMI_XVAL_NULL_EMPTY);
 }
 /**
  *
  */
 static sr_kemi_xval_t* ki_dlg_var_getw(sip_msg_t *msg, str *name)
 {
 	return ki_dlg_var_get_mode(msg, name, SR_KEMI_XVAL_NULL_PRINT);
 }
 
0dfd5bd1
 /**
  *
  */
 static int ki_dlg_var_rm(sip_msg_t *msg, str *name)
 {
 	dlg_cell_t *dlg;
 
 	dlg = dlg_get_msg_dialog(msg);
 	set_dlg_variable_unsafe(dlg, name, NULL);
 	return 1;
 }
 
 /**
  *
  */
 static int ki_dlg_var_is_null(sip_msg_t *msg, str *name)
 {
 	dlg_cell_t *dlg;
 	str *pval;
 
 	dlg = dlg_get_msg_dialog(msg);
 	if(dlg==NULL) {
 		return 1;
 	}
 	pval = get_dlg_variable(dlg, name);
 	if(pval==NULL || pval->s==NULL) {
 		return 1;
 	}
 	return -1;
 }
 
196537b0
 /**
  *
  */
 /* clang-format off */
 static sr_kemi_t sr_kemi_dialog_exports[] = {
 	{ str_init("dialog"), str_init("dlg_manage"),
 		SR_KEMIP_INT, dlg_manage,
 		{ SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
bd6e0a29
 	{ str_init("dialog"), str_init("dlg_bye"),
 		SR_KEMIP_INT, ki_dlg_bye,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("is_known_dlg"),
 		SR_KEMIP_INT, is_known_dlg,
 		{ SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("dlg_set_timeout"),
 		SR_KEMIP_INT, ki_dlg_set_timeout,
 		{ SR_KEMIP_INT, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("dlg_set_timeout_id"),
 		SR_KEMIP_INT, ki_dlg_set_timeout_id,
 		{ SR_KEMIP_INT, SR_KEMIP_INT, SR_KEMIP_INT,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("dlg_set_property"),
 		SR_KEMIP_INT, ki_dlg_set_property,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
a1acd621
 	{ str_init("dialog"), str_init("dlg_reset_property"),
 		SR_KEMIP_INT, ki_dlg_reset_property,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
b36d012e
 	{ str_init("dialog"), str_init("dlg_get"),
 		SR_KEMIP_INT, ki_dlg_get,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_STR,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
1a38dd7b
 	{ str_init("dialog"), str_init("set_dlg_profile_static"),
 		SR_KEMIP_INT, ki_set_dlg_profile_static,
ed2c9153
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
1a38dd7b
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("set_dlg_profile"),
 		SR_KEMIP_INT, ki_set_dlg_profile,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("unset_dlg_profile_static"),
 		SR_KEMIP_INT, ki_unset_dlg_profile_static,
ed2c9153
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
1a38dd7b
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("unset_dlg_profile"),
 		SR_KEMIP_INT, ki_unset_dlg_profile,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("is_in_profile_static"),
 		SR_KEMIP_INT, ki_is_in_profile_static,
ed2c9153
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
1a38dd7b
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("is_in_profile"),
 		SR_KEMIP_INT, ki_is_in_profile,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("get_profile_size_static"),
 		SR_KEMIP_INT, ki_get_profile_size_static,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("get_profile_size"),
 		SR_KEMIP_INT, ki_get_profile_size,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_STR,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
0b9899a5
 	{ str_init("dialog"), str_init("dlg_setflag"),
 		SR_KEMIP_INT, ki_dlg_setflag,
 		{ SR_KEMIP_INT, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("dlg_resetflag"),
 		SR_KEMIP_INT, ki_dlg_resetflag,
 		{ SR_KEMIP_INT, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("dlg_isflagset"),
 		SR_KEMIP_INT, ki_dlg_isflagset,
 		{ SR_KEMIP_INT, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
3d3f5ca1
 	{ str_init("dialog"), str_init("dlg_db_load_callid"),
 		SR_KEMIP_INT, ki_dlg_db_load_callid,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
0f2f7611
 	{ str_init("dialog"), str_init("dlg_db_load_extra"),
 		SR_KEMIP_INT, ki_dlg_db_load_extra,
 		{ SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
7d8ee6fc
 	{ str_init("dialog"), str_init("var_sets"),
 		SR_KEMIP_INT, ki_dlg_var_sets,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("var_get"),
 		SR_KEMIP_XVAL, ki_dlg_var_get,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
71522702
 	{ str_init("dialog"), str_init("var_gete"),
 		SR_KEMIP_XVAL, ki_dlg_var_gete,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("var_getw"),
 		SR_KEMIP_XVAL, ki_dlg_var_getw,
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
0dfd5bd1
 	{ str_init("dialog"), str_init("var_rm"),
6a633ef3
 		SR_KEMIP_INT, ki_dlg_var_rm,
0dfd5bd1
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
 	{ str_init("dialog"), str_init("var_is_null"),
6a633ef3
 		SR_KEMIP_INT, ki_dlg_var_is_null,
0dfd5bd1
 		{ SR_KEMIP_STR, SR_KEMIP_NONE, SR_KEMIP_NONE,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
10f116e7
 	{ str_init("dialog"), str_init("dlg_bridge"),
 		SR_KEMIP_INT, ki_dlg_bridge,
 		{ SR_KEMIP_STR, SR_KEMIP_STR, SR_KEMIP_STR,
 			SR_KEMIP_NONE, SR_KEMIP_NONE, SR_KEMIP_NONE }
 	},
196537b0
 
 	{ {0, 0}, {0, 0}, 0, NULL, { 0, 0, 0, 0, 0, 0 } }
 };
 /* clang-format on */
 
 /**
  *
  */
 int mod_register(char *path, int *dlflags, void *p1, void *p2)
 {
 	sr_kemi_modules_add(sr_kemi_dialog_exports);
 	return 0;
 }
 
9591ceb0
 /**************************** RPC functions ******************************/
2d00e26d
 /*!
  * \brief Helper method that outputs a dialog in a file
  * \see rpc_dump_file_dlg
  * \param dlg printed dialog
  * \param output file descriptor
  * \return 0 on success, -1 on failure
  */
 static inline void internal_rpc_dump_file_dlg(dlg_cell_t *dlg, FILE* dialogf)
 {
 	dlg_profile_link_t *pl;
 	dlg_var_t *var;
 	srjson_doc_t jdoc;
 	srjson_t * jdoc_caller = NULL;
 	srjson_t * jdoc_callee = NULL;
 	srjson_t * jdoc_profiles = NULL;
 	srjson_t * jdoc_variables = NULL;
 
 	srjson_InitDoc(&jdoc, NULL);
 	jdoc.root = srjson_CreateObject(&jdoc);
 	if (!jdoc.root) {
 		LM_ERR("cannot create json\n");
 		goto clear;
 	}
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "h_entry", dlg->h_entry);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "h_id", dlg->h_id);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "ref", dlg->ref);
 	srjson_AddStrToObject(&jdoc, jdoc.root, "call_id", dlg->callid.s, dlg->callid.len);
 	srjson_AddStrToObject(&jdoc, jdoc.root, "from_uri", dlg->from_uri.s, dlg->from_uri.len);
 	srjson_AddStrToObject(&jdoc, jdoc.root, "to_uri", dlg->to_uri.s, dlg->to_uri.len);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "state", dlg->state);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "start_ts", dlg->start_ts);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "init_ts", dlg->init_ts);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "end_ts", dlg->end_ts);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "timeout", dlg->tl.timeout ? time(0) + dlg->tl.timeout - get_ticks() : 0);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "lifetime", dlg->lifetime);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "dflags", dlg->dflags);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "sflags", dlg->sflags);
 	srjson_AddNumberToObject(&jdoc, jdoc.root, "iflags", dlg->iflags);
 
 	jdoc_caller = srjson_CreateObject(&jdoc);
 	if (!jdoc_caller) {
 		LM_ERR("cannot create json caller\n");
 		goto clear;
 	}
 	srjson_AddStrToObject(&jdoc, jdoc_caller, "tag", dlg->tag[DLG_CALLER_LEG].s, dlg->tag[DLG_CALLER_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_caller, "contact", dlg->contact[DLG_CALLER_LEG].s, dlg->contact[DLG_CALLER_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_caller, "cseq", dlg->cseq[DLG_CALLER_LEG].s, dlg->cseq[DLG_CALLER_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_caller, "route_set", dlg->route_set[DLG_CALLER_LEG].s, dlg->route_set[DLG_CALLER_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_caller, "socket",
 			dlg->bind_addr[DLG_CALLER_LEG] ? dlg->bind_addr[DLG_CALLER_LEG]->sock_str.s : empty_str.s,
 			dlg->bind_addr[DLG_CALLER_LEG] ? dlg->bind_addr[DLG_CALLER_LEG]->sock_str.len : empty_str.len);
 	srjson_AddItemToObject(&jdoc, jdoc.root, "caller", jdoc_caller);
 
 	jdoc_callee = srjson_CreateObject(&jdoc);
 	if (!jdoc_callee) {
 		LM_ERR("cannot create json callee\n");
 		goto clear;
 	}
 	srjson_AddStrToObject(&jdoc, jdoc_callee, "tag", dlg->tag[DLG_CALLEE_LEG].s, dlg->tag[DLG_CALLEE_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_callee, "contact", dlg->contact[DLG_CALLEE_LEG].s, dlg->contact[DLG_CALLEE_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_callee, "cseq", dlg->cseq[DLG_CALLEE_LEG].s, dlg->cseq[DLG_CALLEE_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_callee, "route_set", dlg->route_set[DLG_CALLEE_LEG].s, dlg->route_set[DLG_CALLEE_LEG].len);
 	srjson_AddStrToObject(&jdoc, jdoc_callee, "socket",
 			dlg->bind_addr[DLG_CALLEE_LEG] ? dlg->bind_addr[DLG_CALLEE_LEG]->sock_str.s : empty_str.s,
 			dlg->bind_addr[DLG_CALLEE_LEG] ? dlg->bind_addr[DLG_CALLEE_LEG]->sock_str.len : empty_str.len);
 	srjson_AddItemToObject(&jdoc, jdoc.root, "callee", jdoc_callee);
 
 	// profiles section
 	jdoc_profiles = srjson_CreateObject(&jdoc);
 	if (!jdoc_profiles) {
 		LM_ERR("cannot create json profiles\n");
 		goto clear;
 	}
 	for (pl = dlg->profile_links ; pl && (dlg->state<DLG_STATE_DELETED) ; pl=pl->next) {
 		if (pl->profile->has_value) {
 			srjson_AddStrToObject(&jdoc, jdoc_profiles, pl->profile->name.s, pl->hash_linker.value.s, pl->hash_linker.value.len);
 		} else {
 			srjson_AddStrToObject(&jdoc, jdoc_profiles, pl->profile->name.s, empty_str.s, empty_str.len);
 		}
 	}
 	srjson_AddItemToObject(&jdoc, jdoc.root, "profiles", jdoc_profiles);
 
 	// variables section
 	jdoc_variables = srjson_CreateObject(&jdoc);
 	if (!jdoc_variables) {
 		LM_ERR("cannot create json variables\n");
 		goto clear;
 	}
 	for (var=dlg->vars ; var && (dlg->state<DLG_STATE_DELETED) ; var=var->next) {
 		srjson_AddStrToObject(&jdoc, jdoc_variables, var->key.s, var->value.s, var->value.len);
 	}
 	srjson_AddItemToObject(&jdoc, jdoc.root, "variables", jdoc_variables);
 
 	// serialize and print to file
 	jdoc.buf.s = srjson_PrintUnformatted(&jdoc, jdoc.root);
 	if (!jdoc.buf.s) {
 		LM_ERR("unable to serialize data\n");
 		goto clear;
 	}
 	jdoc.buf.len = strlen(jdoc.buf.s);
 	LM_DBG("sending serialized data %.*s\n", jdoc.buf.len, jdoc.buf.s);
 	fprintf(dialogf,"%s\n", jdoc.buf.s);
 
 clear:
 	if (jdoc.buf.s) {
 		jdoc.free_fn(jdoc.buf.s);
 		jdoc.buf.s = NULL;
 	}
 	srjson_DestroyDoc(&jdoc);
 	return;
 }
 
9591ceb0
 /*!
  * \brief Helper method that outputs a dialog via the RPC interface
  * \see rpc_print_dlg
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param dlg printed dialog
  * \param with_context if 1 then the dialog context will be also printed
  * \return 0 on success, -1 on failure
  */
5bdee1ff
 static inline void internal_rpc_print_dlg(rpc_t *rpc, void *c, dlg_cell_t *dlg,
 		int with_context)
9591ceb0
 {
a2f7b089
 	rpc_cb_ctx_t rpc_cb;
684afd9c
 	void *h, *sh, *ssh;
 	dlg_profile_link_t *pl;
 	dlg_var_t *var;
ba773d2a
 	time_t tnow;
 	int tdur;
684afd9c
 
 	if (rpc->add(c, "{", &h) < 0) goto error;
 
ba773d2a
 	tnow = time(NULL);
1d0b7f22
 	if (dlg->end_ts) {
ba773d2a
 		tdur = (int)(dlg->end_ts - dlg->start_ts);
1d0b7f22
 	} else if (dlg->start_ts) {
ba773d2a
 		tdur = (int)(tnow - dlg->start_ts);
 	} else {
 		tdur = 0;
 	}
 	rpc->struct_add(h, "dddSSSdddddddddd",
684afd9c
 		"h_entry", dlg->h_entry,
 		"h_id", dlg->h_id,
25c4b9eb
 		"ref", dlg->ref,
684afd9c
 		"call-id", &dlg->callid,
 		"from_uri", &dlg->from_uri,
 		"to_uri", &dlg->to_uri,
 		"state", dlg->state,
 		"start_ts", dlg->start_ts,
 		"init_ts", dlg->init_ts,
25c4b9eb
 		"end_ts", dlg->end_ts,
ba773d2a
 		"duration", tdur,
 		"timeout", dlg->tl.timeout ? tnow + dlg->tl.timeout - get_ticks() : 0,
684afd9c
 		"lifetime", dlg->lifetime,
 		"dflags", dlg->dflags,
 		"sflags", dlg->sflags,
 		"iflags", dlg->iflags);
 
 	if (rpc->struct_add(h, "{", "caller", &sh) < 0) goto error;
 	rpc->struct_add(sh, "SSSSS",
 		"tag", &dlg->tag[DLG_CALLER_LEG],
 		"contact", &dlg->contact[DLG_CALLER_LEG],
 		"cseq", &dlg->cseq[DLG_CALLER_LEG],
 		"route_set", &dlg->route_set[DLG_CALLER_LEG],
 		"socket", dlg->bind_addr[DLG_CALLER_LEG] ? &dlg->bind_addr[DLG_CALLER_LEG]->sock_str : &empty_str);
 
 	if (rpc->struct_add(h, "{", "callee", &sh) < 0) goto error;
 	rpc->struct_add(sh, "SSSSS",
 		"tag", &dlg->tag[DLG_CALLEE_LEG],
 		"contact", &dlg->contact[DLG_CALLEE_LEG],
 		"cseq", &dlg->cseq[DLG_CALLEE_LEG],
 		"route_set", &dlg->route_set[DLG_CALLEE_LEG],
 		"socket", dlg->bind_addr[DLG_CALLEE_LEG] ? &dlg->bind_addr[DLG_CALLEE_LEG]->sock_str : &empty_str);
 
 	if (rpc->struct_add(h, "[", "profiles", &sh) < 0) goto error;
8bc037bc
 	for (pl = dlg->profile_links ; pl && (dlg->state<DLG_STATE_DELETED) ; pl=pl->next) {
684afd9c
 		if (pl->profile->has_value) {
 			rpc->array_add(sh, "{", &ssh);
 			rpc->struct_add(ssh, "S", pl->profile->name.s, &pl->hash_linker.value);
 		} else {
 			rpc->array_add(sh, "S", &pl->profile->name);
33e7e899
 		}
 	}
a2f7b089
 
684afd9c
 	if (rpc->struct_add(h, "[", "variables", &sh) < 0) goto error;
8bc037bc
 	for(var=dlg->vars ; var && (dlg->state<DLG_STATE_DELETED) ; var=var->next) {
684afd9c
 		rpc->array_add(sh, "{", &ssh);
 		rpc->struct_add(ssh, "S", var->key.s, &var->value);
9591ceb0
 	}
684afd9c
 
ea6356bc
 	if (with_context) {
a2f7b089
 		rpc_cb.rpc = rpc;
684afd9c
 		rpc_cb.c = h;
c021559e
 		run_dlg_callbacks( DLGCB_RPC_CONTEXT, dlg, NULL, NULL, DLG_DIR_NONE, (void *)&rpc_cb);
ea6356bc
 	}
684afd9c
 
 	return;
 error:
 	LM_ERR("Failed to add item to RPC response\n");
 	return;
9591ceb0
 }
 
2d00e26d
 /*!
  * \brief Helper function that outputs all dialogs via the RPC interface
  * \see rpc_dump_file_dlgs
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param with_context if 1 then the dialog context will be also printed
  */
 static void internal_rpc_dump_file_dlgs(rpc_t *rpc, void *c, int with_context)
 {
 	dlg_cell_t *dlg;
 	str output_file_name;
 	FILE* dialogf;
 	unsigned int i;
 	if (rpc->scan(c, ".S", &output_file_name) < 1) return;
 
 	dialogf = fopen(output_file_name.s, "a+");
 	if (!dialogf) {
 		LM_ERR("failed to open output file: %s\n", output_file_name.s);
 		return;
 	}
 
 	for( i=0 ; i<d_table->size ; i++ ) {
 		dlg_lock( d_table, &(d_table->entries[i]) );
 
 		for( dlg=d_table->entries[i].first ; dlg ; dlg=dlg->next ) {
 			internal_rpc_dump_file_dlg(dlg, dialogf);
 		}
 		dlg_unlock( d_table, &(d_table->entries[i]) );
 	}
 	fclose(dialogf);
 }
 
9591ceb0
 /*!
  * \brief Helper function that outputs all dialogs via the RPC interface
  * \see rpc_print_dlgs
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param with_context if 1 then the dialog context will be also printed
  */
 static void internal_rpc_print_dlgs(rpc_t *rpc, void *c, int with_context)
 {
5bdee1ff
 	dlg_cell_t *dlg;
9591ceb0
 	unsigned int i;
 
 	for( i=0 ; i<d_table->size ; i++ ) {
 		dlg_lock( d_table, &(d_table->entries[i]) );
 
 		for( dlg=d_table->entries[i].first ; dlg ; dlg=dlg->next ) {
 			internal_rpc_print_dlg(rpc, c, dlg, with_context);
 		}
 		dlg_unlock( d_table, &(d_table->entries[i]) );
 	}
 }
 
 /*!
  * \brief Helper function that outputs a dialog via the RPC interface
  * \see rpc_print_dlgs
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param with_context if 1 then the dialog context will be also printed
  */
 static void internal_rpc_print_single_dlg(rpc_t *rpc, void *c, int with_context) {
0a2f5e76
 	str callid, ft;
 	str *from_tag = NULL;
5bdee1ff
 	dlg_entry_t *d_entry;
 	dlg_cell_t *dlg;
9591ceb0
 	unsigned int h_entry;
 
0a2f5e76
 	if (rpc->scan(c, ".S", &callid) < 1) return;
9591ceb0
 
606f613a
 	h_entry = core_hash( &callid, 0, d_table->size);
9591ceb0
 	d_entry = &(d_table->entries[h_entry]);
0a2f5e76
 
 	if (rpc->scan(c, "*.S", &ft) == 1) {
 		from_tag = &ft;
 	}
 
9591ceb0
 	dlg_lock( d_table, d_entry);
 	for( dlg = d_entry->first ; dlg ; dlg = dlg->next ) {
0a2f5e76
 		if (match_downstream_dialog( dlg, &callid, from_tag)==1) {
9591ceb0
 			internal_rpc_print_dlg(rpc, c, dlg, with_context);
 		}
 	}
 	dlg_unlock( d_table, d_entry);
 }
 
 /*!
  * \brief Helper function that outputs the size of a given profile via the RPC interface
  * \see rpc_profile_get_size
  * \see rpc_profile_w_value_get_size
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param profile_name the given profile
  * \param value the given profile value
  */
5bdee1ff
 static void internal_rpc_profile_get_size(rpc_t *rpc, void *c, str *profile_name,
 		str *value) {
9591ceb0
 	unsigned int size;
5bdee1ff
 	dlg_profile_table_t *profile;
9224dafc
 
9591ceb0
 	profile = search_dlg_profile( profile_name );
 	if (!profile) {
684afd9c
 		rpc->fault(c, 404, "Profile not found: %.*s",
9591ceb0
 			profile_name->len, profile_name->s);
 		return;
 	}
 	size = get_profile_size(profile, value);
684afd9c
 	rpc->add(c, "d", size);
9591ceb0
 	return;
 }
 
 /*!
  * \brief Helper function that outputs the dialogs belonging to a given profile via the RPC interface
  * \see rpc_profile_print_dlgs
  * \see rpc_profile_w_value_print_dlgs
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param profile_name the given profile
  * \param value the given profile value
  * \param with_context if 1 then the dialog context will be also printed
  */
5bdee1ff
 static void internal_rpc_profile_print_dlgs(rpc_t *rpc, void *c, str *profile_name,
 		str *value) {
 	dlg_profile_table_t *profile;
 	dlg_profile_hash_t *ph;
9591ceb0
 	unsigned int i;
 
 	profile = search_dlg_profile( profile_name );
 	if (!profile) {
684afd9c
 		rpc->fault(c, 404, "Profile not found: %.*s",
9591ceb0
 			profile_name->len, profile_name->s);
 		return;
 	}
 
 	/* go through the hash and print the dialogs */
684afd9c
 	if (profile->has_value==0)
 		value=NULL;
 
 	lock_get( &profile->lock );
 	for ( i=0 ; i< profile->size ; i++ ) {
 		ph = profile->entries[i].first;
 		if(ph) {
 			do {
79695ed2
 				if ((!value || (STR_EQ(*value, ph->value))) && ph->dlg) {
9591ceb0
 					/* print dialog */
 					internal_rpc_print_dlg(rpc, c, ph->dlg, 0);
684afd9c
 				}
 				/* next */
 				ph=ph->next;
 			}while(ph!=profile->entries[i].first);
9591ceb0
 		}
 	}
c986a820
 	lock_release(&profile->lock);
9591ceb0
 }
 
49bd77d1
 /*
  * Wrapper around is_known_dlg().
  */
 
5bdee1ff
 static int w_is_known_dlg(sip_msg_t *msg) {
49bd77d1
 	return	is_known_dlg(msg);
 }
9591ceb0
 
87ca7a1b
 static int w_dlg_set_ruri(sip_msg_t *msg, char *p1, char *p2)
 {
 	return	dlg_set_ruri(msg);
 }
 
9591ceb0
 static const char *rpc_print_dlgs_doc[2] = {
 	"Print all dialogs", 0
 };
2d00e26d
 static const char *rpc_dump_file_dlgs_doc[2] = {
 	"Print all dialogs to json file", 0
 };
ea6356bc
 static const char *rpc_print_dlgs_ctx_doc[2] = {
 	"Print all dialogs with associated context", 0
 };
862758b4
 static const char *rpc_dlg_list_match_doc[2] = {
 	"Print matching dialogs", 0
 };
 static const char *rpc_dlg_list_match_ctx_doc[2] = {
 	"Print matching dialogs with associated context", 0
 };
9591ceb0
 static const char *rpc_print_dlg_doc[2] = {
0a2f5e76
 	"Print dialog based on callid and optionally fromtag", 0
9591ceb0
 };
ea6356bc
 static const char *rpc_print_dlg_ctx_doc[2] = {
0a2f5e76
 	"Print dialog with associated context based on callid and optionally fromtag", 0
ea6356bc
 };
9591ceb0
 static const char *rpc_end_dlg_entry_id_doc[2] = {
 	"End a given dialog based on [h_entry] [h_id]", 0
 };
72b15ef9
 static const char *rpc_dlg_terminate_dlg_doc[2] = {
         "End a given dialog based on callid", 0
 };
f25bef92
 static const char *rpc_dlg_set_state_doc[3] = {
         "Set state for a dialog based on callid and tags",
         "It is targeting the need to update from state 4 (confirmed) to 5 (terminated)",
         0
e0c7e7dd
 };
9591ceb0
 static const char *rpc_profile_get_size_doc[2] = {
 	"Returns the number of dialogs belonging to a profile", 0
 };
 static const char *rpc_profile_print_dlgs_doc[2] = {
 	"Lists all the dialogs belonging to a profile", 0
 };
 static const char *rpc_dlg_bridge_doc[2] = {
d091de55
 	"Bridge two SIP addresses in a call using INVITE(hold)-REFER-BYE mechanism:"
 		" to, from, [outbound SIP proxy]", 0
 };
 static const char *rpc_dlg_is_alive_doc[2] = {
 	"Check whether dialog is alive or not", 0
9591ceb0
 };
 
 
 static void rpc_print_dlgs(rpc_t *rpc, void *c) {
 	internal_rpc_print_dlgs(rpc, c, 0);
 }
2d00e26d
 static void rpc_dump_file_dlgs(rpc_t *rpc, void *c) {
 	internal_rpc_dump_file_dlgs(rpc, c, 0);
 }
ea6356bc
 static void rpc_print_dlgs_ctx(rpc_t *rpc, void *c) {
 	internal_rpc_print_dlgs(rpc, c, 1);
 }
9591ceb0
 static void rpc_print_dlg(rpc_t *rpc, void *c) {
 	internal_rpc_print_single_dlg(rpc, c, 0);
 }
ea6356bc
 static void rpc_print_dlg_ctx(rpc_t *rpc, void *c) {
 	internal_rpc_print_single_dlg(rpc, c, 1);
 }
72b15ef9
 
 static void rpc_dlg_terminate_dlg(rpc_t *rpc,void *c){
 	str callid = {NULL,0};
 	str ftag = {NULL,0};
 	str ttag = {NULL,0};
 
 	dlg_cell_t * dlg = NULL;
 	unsigned int dir;
 	int ret=0;
 	dir = 0;
 
 
 	if(rpc->scan(c, ".S.S.S", &callid,&ftag,&ttag)<3) {
 		LM_ERR("Unable to read the parameters dlg_terminate_dlg \n" );
 		rpc->fault(c, 400, "Need a Callid ,from tag ,to tag");
 		return;
 	}
 
 	dlg=get_dlg(&callid, &ftag, &ttag, &dir);
 
 	if(dlg==NULL) {
 		LM_ERR("Couldnt find callid in dialog '%.*s' \n",callid.len, callid.s);
 		rpc->fault(c, 500, "Couldnt find callid in dialog");
 		return;
 	}
 
 	LM_DBG("Dialog is found with callid  for terminate rpc '%.*s' \n",
 			callid.len, callid.s);
 
 	ret=dlg_bye_all(dlg, NULL);
 
 	LM_DBG("Dialog bye return code %d \n",ret);
 
 	if(ret>=0) {
         LM_WARN("Dialog is terminated callid: '%.*s' \n",
         		callid.len, callid.s);
         dlg_release(dlg);
     }
 }
 
f25bef92
 static void rpc_dlg_set_state(rpc_t *rpc,void *c){
e0c7e7dd
 	str callid = {NULL,0};
 	str ftag = {NULL,0};
 	str ttag = {NULL,0};
f25bef92
 	int sval = DLG_STATE_DELETED;
 	int ostate = 0;
e0c7e7dd
 
 	dlg_cell_t * dlg = NULL;
 	unsigned int dir;
 	int unref=1;
 	dir = 0;
 
f25bef92
 	if(rpc->scan(c, ".S.S.Sd", &callid, &ftag, &ttag, &sval)<3) {
 		LM_ERR("unable to read the parameters\n" );
 		rpc->fault(c, 400, "Need the callid, from tag,to tag and state");
 		return;
 	}
 	if(sval < DLG_STATE_UNCONFIRMED || sval > DLG_STATE_DELETED) {
 		LM_ERR("invalid new state value: %d\n", sval);
 		rpc->fault(c, 500, "Invalid state value");
e0c7e7dd
 		return;
 	}
 
 	dlg=get_dlg(&callid, &ftag, &ttag, &dir);
 
 	if(dlg==NULL) {
f25bef92
 		LM_ERR("dialog not found - callid '%.*s' \n", callid.len, callid.s);
 		rpc->fault(c, 500, "Dialog not found");
e0c7e7dd
 		return;
 	}
 
f25bef92
 	LM_DBG("dialog found - callid '%.*s'\n", callid.len, callid.s);
e0c7e7dd
 
f25bef92
 	if(dlg->state != DLG_STATE_CONFIRMED || sval!=DLG_STATE_DELETED) {
 		LM_WARN("updating states for not confirmed dialogs not properly supported yet,"
 				" use at own risk: '%.*s'\n", callid.len, callid.s);
e0c7e7dd
 	}
 
f25bef92
 	/* setting new state for this dialog */
 	ostate = dlg->state;
 	dlg->state = sval;
 
 	/* updates for terminated dialogs */
 	if(ostate==DLG_STATE_CONFIRMED && sval==DLG_STATE_DELETED) {
 		/* updating timestamps, flags, dialog stats */
 		dlg->init_ts = (unsigned int)(time(0));
 		dlg->end_ts = (unsigned int)(time(0));
 	}
b86d2490
 	dlg->dflags |= DLG_FLAG_CHANGED;
e0c7e7dd
 
 	dlg_unref(dlg, unref);
f25bef92
 
 	if(ostate==DLG_STATE_CONFIRMED && sval==DLG_STATE_DELETED) {
 		if_update_stat(dlg_enable_stats, active_dlgs, -1);
 	}
e0c7e7dd
 
 	/* dlg_clean_run called by timer execution will handle timers deletion and all that stuff */
f25bef92
 	LM_NOTICE("dialog callid '%.*s' - state change forced - old: %d - new: %d\n",
 			callid.len, callid.s, ostate, sval);
e0c7e7dd
 
 	rpc->add(c, "s", "Done");
 
 }
 
d091de55
 static void rpc_dlg_is_alive(rpc_t *rpc, void *c)
 {
 	str callid = {NULL, 0};
 	str ftag = {NULL, 0};
 	str ttag = {NULL, 0};
 
 	dlg_cell_t *dlg = NULL;
 	unsigned int dir = 0;
 	unsigned int state = 0;
 
 	if (rpc->scan(c, ".S.S.S", &callid, &ftag, &ttag) < 3) {
 		LM_DBG("Unable to read expected parameters\n");
 		rpc->fault(c, 400, "Too few parameters (required callid, from-tag, to-tag)");
 		return;
 	}
 
 	dlg = get_dlg(&callid, &ftag, &ttag, &dir);
 
 	if (dlg == NULL) {
 		LM_DBG("Couldnt find dialog with callid: '%.*s'\n", callid.len, callid.s);
 		rpc->fault(c, 404, "Dialog not found");
 		return;
 	}
 	state = dlg->state;
     dlg_release(dlg);
 	if (state != DLG_STATE_CONFIRMED) {
 		LM_DBG("Dialog with Call-ID '%.*s' is in state: %d (confirmed: %d)\n",
 				callid.len, callid.s, state, DLG_STATE_CONFIRMED);
 		rpc->fault(c, 500, "Dialog not in confirmed state");
 		return;
 	} else {
 		rpc->add(c, "s", "Alive");
 	}
 }
72b15ef9
 
9591ceb0
 static void rpc_end_dlg_entry_id(rpc_t *rpc, void *c) {
 	unsigned int h_entry, h_id;
5bdee1ff
 	dlg_cell_t * dlg = NULL;
9591ceb0
 	str rpc_extra_hdrs = {NULL,0};
840d2319
 	int n;
9591ceb0
 
840d2319
 	n = rpc->scan(c, "dd", &h_entry, &h_id);
 	if (n < 2) {
 		LM_ERR("unable to read the parameters (%d)\n", n);
 		rpc->fault(c, 500, "Invalid parameters");
 		return;
 	}
7fc74e46
 	if(rpc->scan(c, "*S", &rpc_extra_hdrs)<1)
 	{
 		rpc_extra_hdrs.s = NULL;
 		rpc_extra_hdrs.len = 0;
 	}
9591ceb0
 
5bdee1ff
 	dlg = dlg_lookup(h_entry, h_id);
840d2319
 	if(dlg==NULL) {
 		rpc->fault(c, 404, "Dialog not found");
 		return;
9591ceb0
 	}
840d2319
 
 	dlg_bye_all(dlg, (rpc_extra_hdrs.len>0)?&rpc_extra_hdrs:NULL);
 	dlg_release(dlg);
9591ceb0
 }
 static void rpc_profile_get_size(rpc_t *rpc, void *c) {
 	str profile_name = {NULL,0};
 	str value = {NULL,0};
 
6e00d854
 	if (rpc->scan(c, ".S", &profile_name) < 1) return;
 	if (rpc->scan(c, "*.S", &value) > 0) {
 		internal_rpc_profile_get_size(rpc, c, &profile_name, &value);
 	} else {
 		internal_rpc_profile_get_size(rpc, c, &profile_name, NULL);
 	}
9591ceb0
 	return;
 }
 static void rpc_profile_print_dlgs(rpc_t *rpc, void *c) {
 	str profile_name = {NULL,0};
 	str value = {NULL,0};
 
6e00d854
 	if (rpc->scan(c, ".S", &profile_name) < 1) return;
 	if (rpc->scan(c, "*.S", &value) > 0) {
 		internal_rpc_profile_print_dlgs(rpc, c, &profile_name, &value);
 	} else {
 		internal_rpc_profile_print_dlgs(rpc, c, &profile_name, NULL);
 	}
9591ceb0
 	return;
 }
ebb14906
 
9591ceb0
 static void rpc_dlg_bridge(rpc_t *rpc, void *c) {
 	str from = {NULL,0};
 	str to = {NULL,0};
 	str op = {NULL,0};
2df6f560
 	str bd = {NULL,0};
7fc74e46
 	int n;
9591ceb0
 
7fc74e46
 	n = rpc->scan(c, "SS", &from, &to);
 	if (n< 2) {
 		LM_ERR("unable to read the parameters (%d)\n", n);
 		rpc->fault(c, 500, "Invalid parameters");
 		return;
 	}
 	if(rpc->scan(c, "*S", &op)<1) {
 		op.s = NULL;
 		op.len = 0;
2df6f560
 	} else {
 		if(op.len==1 && *op.s=='.') {
 			op.s = NULL;
 			op.len = 0;
 		}
 		if(rpc->scan(c, "*S", &bd)<1) {
 			bd.s = NULL;
 			bd.len = 0;
832fcfd8
 		} else {
 			if(bd.len==1 && *bd.s=='.') {
 				bd.s = NULL;
 				bd.len = 0;
 			} else if(bd.len==1 && *bd.s=='_') {
 				bd.s = "";
 				bd.len = 0;
 			}
2df6f560
 		}
7fc74e46
 	}
9591ceb0
 
2df6f560
 	dlg_bridge(&from, &to, &op, &bd);
9591ceb0
 }
 
ebb14906
 static const char *rpc_dlg_stats_active_doc[2] = {
 	"Get stats about active dialogs", 0
 };
 
 /*!
  * \brief Print stats of active dialogs
  */
 static void rpc_dlg_stats_active(rpc_t *rpc, void *c)
 {
 	dlg_cell_t *dlg;
 	unsigned int i;
506672e5
 	int dlg_own = 0;
ebb14906
 	int dlg_starting = 0;
 	int dlg_connecting = 0;
 	int dlg_answering = 0;
 	int dlg_ongoing = 0;
 	void *h;
 
506672e5
 	if(rpc->scan(c, "*d", &dlg_own) < 1)
 		dlg_own = 0;
ebb14906
 	for( i=0 ; i<d_table->size ; i++ ) {
 		dlg_lock( d_table, &(d_table->entries[i]) );
 
 		for( dlg=d_table->entries[i].first ; dlg ; dlg=dlg->next ) {
506672e5
 			if(dlg_own != 0 && dlg->bind_addr[0] == NULL)
 				continue;
ebb14906
 			switch(dlg->state) {
 				case DLG_STATE_UNCONFIRMED:
 					dlg_starting++;
 				break;
 				case DLG_STATE_EARLY:
 					dlg_connecting++;
 				break;
 				case DLG_STATE_CONFIRMED_NA:
 					dlg_answering++;
 				break;
 				case DLG_STATE_CONFIRMED:
 					dlg_ongoing++;
 				break;
 				default:
 					LM_DBG("not active - state: %d\n", dlg->state);
 			}
 		}
 		dlg_unlock( d_table, &(d_table->entries[i]) );
 	}
 
 	if (rpc->add(c, "{", &h) < 0) {
 		rpc->fault(c, 500, "Server failure");
 		return;
 	}
 
 	rpc->struct_add(h, "ddddd",
 		"starting", dlg_starting,
 		"connecting", dlg_connecting,
 		"answering", dlg_answering,
 		"ongoing", dlg_ongoing,
 		"all", dlg_starting + dlg_connecting + dlg_answering + dlg_ongoing);
 }
 
862758b4
 /*!
  * \brief Helper function that outputs matching dialogs via the RPC interface
  *
  * \param rpc RPC node that should be filled
  * \param c RPC void pointer
  * \param with_context if 1 then the dialog context will be also printed
  */
 static void rpc_dlg_list_match_ex(rpc_t *rpc, void *c, int with_context)
 {
 	dlg_cell_t *dlg = NULL;
 	int i = 0;
 	str mkey = {NULL, 0};
 	str mop = {NULL, 0};
 	str mval = {NULL, 0};
 	str sval = {NULL, 0};
b177f05e
 	unsigned int ival = 0;
 	unsigned int mival = 0;
862758b4
 	int n = 0;
 	int m = 0;
 	int vkey = 0;
 	int vop = 0;
 	int matched = 0;
 	regex_t mre;
 	regmatch_t pmatch;
 
 	i = rpc->scan(c, "SSS", &mkey, &mop, &mval);
 	if (i < 3) {
 		LM_ERR("unable to read required parameters (%d)\n", i);
 		rpc->fault(c, 500, "Invalid parameters");
 		return;
 	}
 	if(mkey.s==NULL || mkey.len<=0 || mop.s==NULL || mop.len<=0
 			|| mval.s==NULL || mval.len<=0) {
 		LM_ERR("invalid parameters (%d)\n", i);
 		rpc->fault(c, 500, "Invalid parameters");
 		return;
 	}
 	if(mkey.len==4 && strncmp(mkey.s, "ruri", mkey.len)==0) {
 		vkey = 0;
 	} else if(mkey.len==4 && strncmp(mkey.s, "furi", mkey.len)==0) {
 		vkey = 1;
 	} else if(mkey.len==4 && strncmp(mkey.s, "turi", mkey.len)==0) {
 		vkey = 2;
360e012d
 	} else if(mkey.len==6 && strncmp(mkey.s, "callid", mkey.len)==0) {
862758b4
 		vkey = 3;
b177f05e
 	} else if(mkey.len==8 && strncmp(mkey.s, "start_ts", mkey.len)==0) {
 		vkey = 4;
862758b4
 	} else {
 		LM_ERR("invalid key %.*s\n", mkey.len, mkey.s);
 		rpc->fault(c, 500, "Invalid matching key parameter");
 		return;
 	}
 	if(mop.len!=2) {
 		LM_ERR("invalid matching operator %.*s\n", mop.len, mop.s);
 		rpc->fault(c, 500, "Invalid matching operator parameter");
 		return;
 
 	}
 	if(strncmp(mop.s, "eq", 2)==0) {
 		vop = 0;
 	} else if(strncmp(mop.s, "re", 2)==0) {
 		vop = 1;
 		memset(&mre, 0, sizeof(regex_t));
 		if (regcomp(&mre, mval.s, REG_EXTENDED|REG_ICASE|REG_NEWLINE)!=0) {
 			LM_ERR("failed to compile regex: %.*s\n", mval.len, mval.s);
 			rpc->fault(c, 500, "Invalid matching value parameter");
 			return;
 		}
 	} else if(strncmp(mop.s, "sw", 2)==0) {
 		vop = 2;
b177f05e
 	} else if(strncmp(mop.s, "gt", 2)==0) {
 		vop = 3;
 	} else if(strncmp(mop.s, "lt", 2)==0) {
 		vop = 4;
862758b4
 	} else {
 		LM_ERR("invalid matching operator %.*s\n", mop.len, mop.s);
 		rpc->fault(c, 500, "Invalid matching operator parameter");
 		return;
 	}
 	if(rpc->scan(c, "*d", &n)<1) {
 		n = 0;
 	}
 
b177f05e
 	if (vkey == 4  && vop <= 2) {
 		LM_ERR("Matching operator %.*s not supported with start_ts key\n", mop.len, mop.s);
 		rpc->fault(c, 500, "Matching operator not supported with start_ts key");
 		return;
 	}
 
 	if (vkey != 4  && vop >= 3) {
 		LM_ERR("Matching operator %.*s not supported with key %.*s\n", mop.len, mop.s, mkey.len, mkey.s);
 		rpc->fault(c, 500, "Matching operator not supported");
 		return;
 	}
 
862758b4
 	for(i=0; i<d_table->size; i++) {
 		dlg_lock(d_table, &(d_table->entries[i]));
 		for(dlg=d_table->entries[i].first; dlg!=NULL; dlg=dlg->next) {
 			matched = 0;
 			switch(vkey) {
 				case 0:
 					sval = dlg->req_uri;
 				break;
 				case 1:
 					sval = dlg->from_uri;
 				break;
 				case 2:
 					sval = dlg->to_uri;
 				break;
 				case 3:
 					sval = dlg->callid;
 				break;
b177f05e
 				case 4:
 					ival = dlg->start_ts;
 				break;
862758b4
 			}
 			switch(vop) {
 				case 0:
 					/* string comparison */
 					if(mval.len==sval.len
 							&& strncmp(mval.s, sval.s, mval.len)==0) {
 						matched = 1;
 					}
 				break;
 				case 1:
 					/* regexp matching */
 					if(regexec(&mre, sval.s, 1, &pmatch, 0)==0) {
 						matched = 1;
 					}
 				break;
 				case 2:
 					/* starts with */
 					if(mval.len<=sval.len
 							&& strncmp(mval.s, sval.s, mval.len)==0) {
 						matched = 1;
 					}
 				break;
b177f05e
 				case 3:		
 					/* greater than */
 					if (str2int(&mval, &mival) == 0 && ival > mival) {
 						matched = 1;
 					}
 				break;
 				case 4:
 					if (str2int(&mval, &mival) == 0 && ival < mival) {
 						matched = 1;
 					}
 				break;
862758b4
 			}
 			if (matched==1) {
 				m++;
 				internal_rpc_print_dlg(rpc, c, dlg, with_context);
 				if(n>0 && m==n) {
 					break;
 				}
 			}
 		}
 		dlg_unlock(d_table, &(d_table->entries[i]));
 		if(n>0 && m==n) {
 			break;
 		}
 	}
8153309c
 	if(vop == 1) {
 		regfree(&mre);
 	}
 
862758b4
 	if(m==0) {
 		rpc->fault(c, 404, "Not found");
 		return;
 	}
 }
 
 /*!
  * \brief Print matching dialogs
  */
 static void rpc_dlg_list_match(rpc_t *rpc, void *c)
 {
 	rpc_dlg_list_match_ex(rpc, c, 0);
 }
 
 /*!
  * \brief Print matching dialogs wih context
  */
 static void rpc_dlg_list_match_ctx(rpc_t *rpc, void *c)
 {
 	rpc_dlg_list_match_ex(rpc, c, 1);
 }
 
3585f802
 static const char *rpc_dlg_briefing_doc[2] = {
 	"List the summary of dialog records in memory", 0
 };
 
 /*!
  * \brief List summary of active calls
  */
 static void rpc_dlg_briefing(rpc_t *rpc, void *c)
 {
4507ed57
 	dlg_cell_t *dlg = NULL;
 	unsigned int i = 0;
 	int n = 0;
 	str fmt = STR_NULL;
 	void *h = NULL;
 
 	n = rpc->scan(c, "S", &fmt);
 	if (n < 1) {
 		fmt.s = "ftcFT";
 		fmt.len = 5;
 	}
3585f802
 
 	for( i=0 ; i<d_table->size ; i++ ) {
 		dlg_lock( d_table, &(d_table->entries[i]) );
 		for( dlg=d_table->entries[i].first ; dlg ; dlg=dlg->next ) {
 			if (rpc->add(c, "{", &h) < 0) {
 				rpc->fault(c, 500, "Failed to create the structure");
 				return;
 			}
4507ed57
 			if(rpc->struct_add(h, "dd",
3585f802
 					"h_entry", dlg->h_entry,
4507ed57
 					"h_id", dlg->h_id) < 0) {
3585f802
 				rpc->fault(c, 500, "Failed to add fields");
 				return;
 
 			}
4507ed57
 			for(n=0; n<fmt.len; n++) {
 				switch(fmt.s[n]) {
 					case 'f':
 						if(rpc->struct_add(h, "S",
 									"from_uri", &dlg->from_uri) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 't':
 						if(rpc->struct_add(h, "S",
 									"to_uri", &dlg->to_uri) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'c':
 						if(rpc->struct_add(h, "S",
 									"call-id", &dlg->callid) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'F':
 						if(rpc->struct_add(h, "S",
 									"from_tag", &dlg->tag[DLG_CALLER_LEG]) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'T':
 						if(rpc->struct_add(h, "S",
 									"to_tag", &dlg->tag[DLG_CALLER_LEG]) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'I':
 						if(rpc->struct_add(h, "d",
 									"init_ts", dlg->init_ts) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'S':
 						if(rpc->struct_add(h, "d",
 									"start_ts", dlg->start_ts) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 'E':
 						if(rpc->struct_add(h, "d",
 									"end_ts", dlg->end_ts) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 					case 's':
 						if(rpc->struct_add(h, "d",
 									"state", dlg->state) < 0) {
 							rpc->fault(c, 500, "Failed to add fields");
 							return;
 						}
 					break;
 				}
 			}
 
3585f802
 		}
 		dlg_unlock( d_table, &(d_table->entries[i]) );
 	}
 }
 
9591ceb0
 static rpc_export_t rpc_methods[] = {
3585f802
 	{"dlg.briefing", rpc_dlg_briefing, rpc_dlg_briefing_doc, RET_ARRAY},
684afd9c
 	{"dlg.list", rpc_print_dlgs, rpc_print_dlgs_doc, RET_ARRAY},
2d00e26d
 	{"dlg.dump_file", rpc_dump_file_dlgs, rpc_dump_file_dlgs_doc, 0},
684afd9c
 	{"dlg.list_ctx", rpc_print_dlgs_ctx, rpc_print_dlgs_ctx_doc, RET_ARRAY},
862758b4
 	{"dlg.list_match", rpc_dlg_list_match, rpc_dlg_list_match_doc, RET_ARRAY},
 	{"dlg.list_match_ctx", rpc_dlg_list_match_ctx, rpc_dlg_list_match_ctx_doc, RET_ARRAY},
9591ceb0
 	{"dlg.dlg_list", rpc_print_dlg, rpc_print_dlg_doc, 0},
ea6356bc
 	{"dlg.dlg_list_ctx", rpc_print_dlg_ctx, rpc_print_dlg_ctx_doc, 0},
9591ceb0
 	{"dlg.end_dlg", rpc_end_dlg_entry_id, rpc_end_dlg_entry_id_doc, 0},
 	{"dlg.profile_get_size", rpc_profile_get_size, rpc_profile_get_size_doc, 0},
684afd9c
 	{"dlg.profile_list", rpc_profile_print_dlgs, rpc_profile_print_dlgs_doc, RET_ARRAY},
9591ceb0
 	{"dlg.bridge_dlg", rpc_dlg_bridge, rpc_dlg_bridge_doc, 0},
72b15ef9
 	{"dlg.terminate_dlg", rpc_dlg_terminate_dlg, rpc_dlg_terminate_dlg_doc, 0},
f25bef92
 	{"dlg.set_state", rpc_dlg_set_state, rpc_dlg_set_state_doc, 0},
ebb14906
 	{"dlg.stats_active", rpc_dlg_stats_active, rpc_dlg_stats_active_doc, 0},
d091de55
 	{"dlg.is_alive",  rpc_dlg_is_alive, rpc_dlg_is_alive_doc, 0},
9591ceb0
 	{0, 0, 0, 0}
 };