modules_k/dialog: Fix timer reset and improve timeout value logging
[sip-router] / modules_k / dialog / dlg_handlers.c
1 /*
2  * $Id$
3  *
4  * Copyright (C) 2006 Voice System SRL
5  *
6  * This file is part of Kamailio, a free SIP server.
7  *
8  * Kamailio is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  *
13  * Kamailio is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  * History:
23  * --------
24  * 2006-04-14  initial version (bogdan)
25  * 2006-11-28  Added support for tracking the number of early dialogs, and the
26  *             number of failed dialogs. This involved updates to dlg_onreply()
27  *             (Jeffrey Magder - SOMA Networks)
28  * 2007-03-06  syncronized state machine added for dialog state. New tranzition
29  *             design based on events; removed num_1xx and num_2xx (bogdan)
30  * 2007-04-30  added dialog matching without DID (dialog ID), but based only
31  *             on RFC3261 elements - based on an original patch submitted
32  *             by Michel Bensoussan <michel@extricom.com> (bogdan)
33  * 2007-05-17  new feature: saving dialog info into a database if
34  *             realtime update is set(ancuta)
35  * 2007-07-06  support for saving additional dialog info : cseq, contact,
36  *             route_set and socket_info for both caller and callee (ancuta)
37  * 2007-07-10  Optimized dlg_match_mode 2 (DID_NONE), it now employs a proper
38  *             hash table lookup and isn't dependant on the is_direction
39  *             function (which requires an RR param like dlg_match_mode 0
40  *             anyways.. ;) ; based on a patch from
41  *             Tavis Paquette <tavis@galaxytelecom.net>
42  *             and Peter Baer <pbaer@galaxytelecom.net>  (bogdan)
43  * 2008-04-04  added direction reporting in dlg callbacks (bogdan)
44  */
45
46
47 /*!
48  * \file
49  * \brief Functions related to dialog handling
50  * \ingroup dialog
51  * Module: \ref dialog
52  */
53
54 #include <string.h>
55 #include <time.h>
56
57 #include "../../trim.h"
58 #include "../../pvar.h"
59 #include "../../timer.h"
60 #include "../../lib/kcore/statistics.h"
61 #include "../../action.h"
62 #include "../../script_cb.h"
63 #include "../../lib/kcore/faked_msg.h"
64 #include "../../lib/kcore/parser_helpers.h"
65 #include "../../parser/parse_from.h"
66 #include "../../parser/parse_cseq.h"
67 #include "../../parser/contact/parse_contact.h"
68 #include "../../parser/parse_from.h"
69 #include "../../parser/parse_rr.h"
70 #include "../../modules/tm/tm_load.h"
71 #include "../rr/api.h"
72 #include "dlg_hash.h"
73 #include "dlg_timer.h"
74 #include "dlg_cb.h"
75 #include "dlg_handlers.h"
76 #include "dlg_req_within.h"
77 #include "dlg_db_handler.h"
78 #include "dlg_profile.h"
79 #include "dlg_var.h"
80
81 static str       rr_param;              /*!< record-route parameter for matching */
82 static int       dlg_flag;              /*!< flag for dialog tracking */
83 static pv_spec_t *timeout_avp;          /*!< AVP for timeout setting */
84 static int       default_timeout;       /*!< default dialog timeout */
85 static int       seq_match_mode;        /*!< dlg_match mode */ 
86 static int       shutdown_done = 0;     /*!< 1 when destroy_dlg_handlers was called */
87
88 extern struct rr_binds d_rrb;           /*!< binding to record-routing module */
89
90 /* statistic variables */
91 extern stat_var *early_dlgs;            /*!< number of early dialogs */
92 extern stat_var *processed_dlgs;        /*!< number of processed dialogs */
93 extern stat_var *expired_dlgs;          /*!< number of expired dialogs */
94 extern stat_var *failed_dlgs;           /*!< number of failed dialogs */
95
96 extern pv_elem_t *ruri_param_model;     /*!< pv-string to get r-uri */
97
98 static unsigned int CURR_DLG_LIFETIME = 0;      /*!< current dialog lifetime */
99 static unsigned int CURR_DLG_STATUS = 0;        /*!< current dialog state */
100 static unsigned int CURR_DLG_ID  = 0xffffffff;  /*!< current dialog id */
101
102
103 /*! size of the dialog record-route parameter */
104 #define RR_DLG_PARAM_SIZE  (2*2*sizeof(int)+3+MAX_DLG_RR_PARAM_NAME)
105 /*! separator inside the record-route paramter */
106 #define DLG_SEPARATOR      '.'
107
108
109 /*!
110  * \brief Initialize the dialog handlers
111  * \param rr_param_p added record-route parameter
112  * \param dlg_flag_p dialog flag
113  * \param timeout_avp_p AVP for timeout setting
114  * \param default_timeout_p default timeout
115  * \param seq_match_mode_p matching mode
116  */
117 void init_dlg_handlers(char *rr_param_p, int dlg_flag_p,
118                 pv_spec_t *timeout_avp_p ,int default_timeout_p,
119                 int seq_match_mode_p)
120 {
121         rr_param.s = rr_param_p;
122         rr_param.len = strlen(rr_param.s);
123
124         dlg_flag = 1<<dlg_flag_p;
125
126         timeout_avp = timeout_avp_p;
127         default_timeout = default_timeout_p;
128         seq_match_mode = seq_match_mode_p;
129 }
130
131
132 /*!
133  * \brief Shutdown operation of the module
134  */
135 void destroy_dlg_handlers(void)
136 {
137         shutdown_done = 1;
138 }
139
140
141 /*!
142  * \brief Add record-route parameter for dialog tracking
143  * \param req SIP request
144  * \param entry dialog hash entry
145  * \param id dialog hash id
146  * \return 0 on success, -1 on failure
147  */
148 static inline int add_dlg_rr_param(struct sip_msg *req, unsigned int entry,
149                 unsigned int id)
150 {
151         static char buf[RR_DLG_PARAM_SIZE];
152         str s;
153         int n;
154         char *p;
155
156         s.s = p = buf;
157
158         *(p++) = ';';
159         memcpy(p, rr_param.s, rr_param.len);
160         p += rr_param.len;
161         *(p++) = '=';
162
163         n = RR_DLG_PARAM_SIZE - (p-buf);
164         if (int2reverse_hex( &p, &n, entry)==-1)
165                 return -1;
166
167         *(p++) = DLG_SEPARATOR;
168
169         n = RR_DLG_PARAM_SIZE - (p-buf);
170         if (int2reverse_hex( &p, &n, id)==-1)
171                 return -1;
172
173         s.len = p-buf;
174
175         if (d_rrb.add_rr_param( req, &s)<0) {
176                 LM_ERR("failed to add rr param\n");
177                 return -1;
178         }
179
180         return 0;
181 }
182
183
184 /*!
185  * \brief Parse SIP message and populate leg informations
186  *
187  * Parse SIP message and populate leg informations. 
188  * \param dlg the dialog to add cseq, contact & record_route
189  * \param msg sip message
190  * \param flag  0-for a request(INVITE), 1- for a reply(200 ok)
191  * \return 0 on success, -1 on failure
192  * \note for a request: get record route in normal order, for a reply get
193  * in reverse order, skipping the ones from the request and the proxies' own
194  */
195 int populate_leg_info( struct dlg_cell *dlg, struct sip_msg *msg,
196         struct cell* t, unsigned int leg, str *tag)
197 {
198         unsigned int skip_recs;
199         str cseq;
200         str contact;
201         str rr_set;
202
203         dlg->bind_addr[leg] = msg->rcv.bind_address;
204
205         /* extract the cseq number as string */
206         if (leg==DLG_CALLER_LEG) {
207                 if((!msg->cseq && (parse_headers(msg,HDR_CSEQ_F,0)<0 || !msg->cseq))
208                         || !msg->cseq->parsed){
209                         LM_ERR("bad sip message or missing CSeq hdr :-/\n");
210                         goto error0;
211                 }
212                 cseq = (get_cseq(msg))->number;
213         } else {
214                 /* use the same as in request */
215                 cseq = dlg->cseq[DLG_CALLER_LEG];
216         }
217
218         /* extract the contact address */
219         if (!msg->contact&&(parse_headers(msg,HDR_CONTACT_F,0)<0||!msg->contact)){
220                 LM_ERR("bad sip message or missing Contact hdr\n");
221                 goto error0;
222         }
223         if ( parse_contact(msg->contact)<0 ||
224         ((contact_body_t *)msg->contact->parsed)->contacts==NULL ||
225         ((contact_body_t *)msg->contact->parsed)->contacts->next!=NULL ) {
226                 LM_ERR("bad Contact HDR\n");
227                 goto error0;
228         }
229         contact = ((contact_body_t *)msg->contact->parsed)->contacts->uri;
230
231         /* extract the RR parts */
232         if(!msg->record_route && (parse_headers(msg,HDR_EOH_F,0)<0)  ){
233                 LM_ERR("failed to parse record route header\n");
234                 goto error0;
235         }
236
237         if (leg==DLG_CALLER_LEG) {
238                 skip_recs = 0;
239         } else {
240                 /* was the 200 OK received or local generated */
241                 skip_recs = dlg->from_rr_nb +
242                         ((t->relayed_reply_branch>=0)?
243                                 ((t->uac[t->relayed_reply_branch].flags&TM_UAC_FLAG_R2)?2:
244                                  ((t->uac[t->relayed_reply_branch].flags&TM_UAC_FLAG_RR)?1:0))
245                                 :0);
246         }
247
248         if(msg->record_route){
249                 if( print_rr_body(msg->record_route, &rr_set, leg,
250                                                         &skip_recs) != 0 ){
251                         LM_ERR("failed to print route records \n");
252                         goto error0;
253                 }
254         } else {
255                 rr_set.s = 0;
256                 rr_set.len = 0;
257         }
258
259         if(leg==DLG_CALLER_LEG)
260                 dlg->from_rr_nb = skip_recs;
261
262         LM_DBG("route_set %.*s, contact %.*s, cseq %.*s and bind_addr %.*s\n",
263                 rr_set.len, rr_set.s, contact.len, contact.s,
264                 cseq.len, cseq.s,
265                 msg->rcv.bind_address->sock_str.len,
266                 msg->rcv.bind_address->sock_str.s);
267
268         if (dlg_set_leg_info( dlg, tag, &rr_set, &contact, &cseq, leg)!=0) {
269                 LM_ERR("dlg_set_leg_info failed\n");
270                 if (rr_set.s) pkg_free(rr_set.s);
271                 goto error0;
272         }
273
274         if (rr_set.s) pkg_free(rr_set.s);
275
276         return 0;
277 error0:
278         return -1;
279 }
280
281
282 /*!
283  * \brief Function that is registered as TM callback and called on replies
284  *
285  * Function that is registered as TM callback and called on replies. It
286  * parses the reply and set the appropriate event. This is then used to
287  * update the dialog state, run eventual dialog callbacks and save or
288  * update the necessary informations about the dialog.
289  * \see next_state_dlg
290  * \param t transaction, unused
291  * \param type type of the entered callback
292  * \param param saved dialog structure in the callback
293  */
294 static void dlg_onreply(struct cell* t, int type, struct tmcb_params *param)
295 {
296         struct sip_msg *rpl;
297         struct dlg_cell *dlg;
298         int new_state, old_state, unref, event;
299         str tag;
300
301         dlg = (struct dlg_cell *)(*param->param);
302         if (shutdown_done || dlg==0)
303                 return;
304
305         rpl = param->rpl;
306
307         if (type==TMCB_RESPONSE_FWDED) {
308                 /* The state does not change, but the msg is mutable in this callback*/
309                 run_dlg_callbacks(DLGCB_RESPONSE_FWDED, dlg, rpl, DLG_DIR_UPSTREAM, 0);
310                 return;
311         }
312
313         if (type==TMCB_DESTROY)
314                 event = DLG_EVENT_TDEL;
315         else if (param->code<200)
316                 event = DLG_EVENT_RPL1xx;
317         else if (param->code<300)
318                 event = DLG_EVENT_RPL2xx;
319         else
320                 event = DLG_EVENT_RPL3xx;
321
322         next_state_dlg( dlg, event, &old_state, &new_state, &unref);
323
324         if (new_state==DLG_STATE_EARLY) {
325                 run_dlg_callbacks(DLGCB_EARLY, dlg, rpl, DLG_DIR_UPSTREAM, 0);
326                 if (old_state!=DLG_STATE_EARLY)
327                         if_update_stat(dlg_enable_stats, early_dlgs, 1);
328                 return;
329         }
330
331         if (new_state==DLG_STATE_CONFIRMED_NA &&
332         old_state!=DLG_STATE_CONFIRMED_NA && old_state!=DLG_STATE_CONFIRMED ) {
333                 LM_DBG("dialog %p confirmed\n",dlg);
334
335                  if (rpl != FAKED_REPLY) {
336                         /* get to tag*/
337                         if ( !rpl->to && ((parse_headers(rpl, HDR_TO_F,0)<0)
338                                                 || !rpl->to) ) {
339                                 LM_ERR("bad reply or missing TO hdr :-/\n");
340                                 tag.s = 0;
341                                 tag.len = 0;
342                         } else {
343                                 tag = get_to(rpl)->tag_value;
344                                 if (tag.s==0 || tag.len==0) {
345                                         LM_ERR("missing TAG param in TO hdr :-/\n");
346                                         tag.s = 0;
347                                         tag.len = 0;
348                                 }
349                         }
350
351                         /* save callee's tag, cseq, contact and record route*/
352                         if (populate_leg_info( dlg, rpl, t, DLG_CALLEE_LEG, &tag) !=0) {
353                                 LM_ERR("could not add further info to the dialog\n");
354                         }
355                  } else {
356                          LM_ERR("Faked reply!\n");
357                  }
358
359                 /* set start time */
360                 dlg->start_ts = (unsigned int)(time(0));
361
362                 /* save the settings to the database,
363                  * if realtime saving mode configured- save dialog now
364                  * else: the next time the timer will fire the update*/
365                 dlg->dflags |= DLG_FLAG_NEW;
366                 if ( dlg_db_mode==DB_MODE_REALTIME )
367                         update_dialog_dbinfo(dlg);
368
369                 if (0 != insert_dlg_timer( &dlg->tl, dlg->lifetime )) {
370                         LM_CRIT("Unable to insert dlg %p [%u:%u] on event %d [%d->%d] "
371                                 "with clid '%.*s' and tags '%.*s' '%.*s'\n",
372                                 dlg, dlg->h_entry, dlg->h_id, event, old_state, new_state,
373                                 dlg->callid.len, dlg->callid.s,
374                                 dlg->tag[DLG_CALLER_LEG].len, dlg->tag[DLG_CALLER_LEG].s,
375                                 dlg->tag[DLG_CALLEE_LEG].len, dlg->tag[DLG_CALLEE_LEG].s);
376                 } else {
377                         ref_dlg(dlg,1);
378                 }
379
380                 /* dialog confirmed */
381                 run_dlg_callbacks( DLGCB_CONFIRMED, dlg, rpl, DLG_DIR_UPSTREAM, 0);
382
383                 if (old_state==DLG_STATE_EARLY)
384                         if_update_stat(dlg_enable_stats, early_dlgs, -1);
385
386                 if (unref) unref_dlg(dlg,unref);
387                 if_update_stat(dlg_enable_stats, active_dlgs, 1);
388                 return;
389         }
390
391         if ( old_state!=DLG_STATE_DELETED && new_state==DLG_STATE_DELETED ) {
392                 LM_DBG("dialog %p failed (negative reply)\n", dlg);
393                 /* dialog setup not completed (3456XX) */
394                 run_dlg_callbacks( DLGCB_FAILED, dlg, rpl, DLG_DIR_UPSTREAM, 0);
395                 /* do unref */
396                 if (unref)
397                         unref_dlg(dlg,unref);
398                 if (old_state==DLG_STATE_EARLY)
399                         if_update_stat(dlg_enable_stats, early_dlgs, -1);
400                 return;
401         }
402
403         if (unref) unref_dlg(dlg,unref);
404
405         return;
406 }
407
408
409 /*!
410  * \brief Helper function that run dialog callbacks on forwarded requests
411  * \see dlg_seq_up_onreply
412  * \see dlg_seq_down_onreply
413  * \param t transaction, unused
414  * \param type type of the callback, should be TMCB_RESPONSE_FWDED
415  * \param param saved dialog structure inside the callback
416  * \param direction direction of the request
417  */
418 static void dlg_seq_onreply_helper(struct cell* t, int type,
419                 struct tmcb_params *param, const int direction)
420 {
421         struct dlg_cell *dlg;
422
423         dlg = (struct dlg_cell *)(*param->param);
424         if (shutdown_done || dlg==0)
425                 return;
426
427         if (type==TMCB_RESPONSE_FWDED) {
428                 run_dlg_callbacks(DLGCB_RESPONSE_WITHIN, dlg, param->rpl,
429                         direction, 0);
430                 return;
431         }
432
433         return;
434 }
435
436
437 /*!
438  * \brief Run dialog callbacks on forwarded requests in upstream direction
439  * \see dlg_seq_onreply_helper
440  * \param t transaction, unused
441  * \param type type of the callback, should be TMCB_RESPONSE_FWDED
442  * \param param saved dialog structure inside the callback
443  */
444 static void dlg_seq_up_onreply(struct cell* t, int type, struct tmcb_params *param)
445 {
446         return dlg_seq_onreply_helper(t, type, param, DLG_DIR_UPSTREAM);
447 }
448
449
450 /*!
451  * \brief Run dialog callbacks on forwarded requests in downstream direction
452  * \see dlg_seq_onreply_helper
453  * \param t transaction, unused
454  * \param type type of the callback, should be TMCB_RESPONSE_FWDED
455  * \param param saved dialog structure inside the callback
456  */
457 static void dlg_seq_down_onreply(struct cell* t, int type, struct tmcb_params *param)
458 {
459         return dlg_seq_onreply_helper(t, type, param, DLG_DIR_DOWNSTREAM);
460 }
461
462
463 /*!
464  * \brief Return the timeout for a dialog
465  * \param req SIP message
466  * \return value from timeout AVP if present or default timeout
467  */
468 inline static int get_dlg_timeout(struct sip_msg *req)
469 {
470         pv_value_t pv_val;
471
472         if( timeout_avp ) {
473                 if ( pv_get_spec_value( req, timeout_avp, &pv_val)==0 &&
474                                 pv_val.flags&PV_VAL_INT && pv_val.ri>0 ) {
475                         return pv_val.ri;
476                 }
477                 LM_DBG("invalid AVP value, using default timeout\n");
478         }
479         return default_timeout;
480 }
481
482
483 /*!
484  * \brief Function that is registered as TM callback and called on requests
485  * \see dlg_new_dialog
486  * \param t transaction, used to created the dialog
487  * \param type type of the entered callback
488  * \param param saved dialog structure in the callback
489  */
490 void dlg_onreq(struct cell* t, int type, struct tmcb_params *param)
491 {
492         struct sip_msg *msg;
493         msg = param->req;
494         if((msg->flags&dlg_flag)!=dlg_flag)
495                 return;
496         if (current_dlg_pointer!=NULL)
497                 return;
498         dlg_new_dialog(msg, t);
499 }
500
501
502 /*!
503  * \brief Unreference a new dialog, helper function for dlg_onreq
504  * \see dlg_onreq
505  * \param dialog unreferenced dialog
506  */
507 static void unref_new_dialog(void *dialog)
508 {
509         struct tmcb_params p;
510
511         memset(&p, 0, sizeof(struct tmcb_params));
512         p.param = (void*)&dialog;
513         dlg_onreply(0, TMCB_DESTROY, &p);
514 }
515
516
517 /*!
518  * \brief Dummy callback just to keep the compiler happy
519  * \param t unused
520  * \param type unused
521  * \param param unused
522  */
523 void dlg_tmcb_dummy(struct cell* t, int type, struct tmcb_params *param)
524 {
525         return;
526 }
527
528
529 /*!
530  * \brief Create a new dialog from a sip message
531  *
532  * Create a new dialog from a SIP message, register a callback
533  * to keep track of the dialog with help of the tm module.
534  * This function is either called from the request callback, or
535  * from the dlg_manage function in the configuration script.
536  * \see dlg_onreq
537  * \see w_dlg_manage
538  * \param msg SIP message
539  * \param t transaction
540  * \return 0 on success, -1 on failure
541  */ 
542 int dlg_new_dialog(struct sip_msg *msg, struct cell *t)
543 {
544         struct dlg_cell *dlg;
545         str s;
546         str req_uri;
547
548         if((msg->to==NULL && parse_headers(msg, HDR_TO_F,0)<0) || msg->to==NULL)
549         {
550                 LM_ERR("bad request or missing TO hdr\n");
551                 return -1;
552         }
553         s = get_to(msg)->tag_value;
554         if(s.s!=0 && s.len!=0)
555                 return -1;
556
557         if(msg->first_line.u.request.method_value==METHOD_CANCEL)
558                 return -1;
559
560         if(parse_from_header(msg))
561         {
562                 LM_ERR("bad request or missing FROM hdr\n");
563                 return -1;
564         }
565         if((msg->callid==NULL && parse_headers(msg,HDR_CALLID_F,0)<0)
566                         || msg->callid==NULL){
567                 LM_ERR("bad request or missing CALLID hdr\n");
568                 return -1;
569         }
570         s = msg->callid->body;
571         trim(&s);
572
573         if (pv_printf_s(msg, ruri_param_model, &req_uri)<0) {
574                 LM_ERR("error - cannot print the r-uri format\n");
575                 return -1;
576         }
577         trim(&req_uri);
578
579         /* some sanity checks */
580         if (s.len==0 || get_from(msg)->tag_value.len==0) {
581                 LM_ERR("invalid request -> callid (%d) or from TAG (%d) empty\n",
582                         s.len, get_from(msg)->tag_value.len);
583                 return -1;
584         }
585
586         dlg = build_new_dlg(&s /*callid*/, &(get_from(msg)->uri) /*from uri*/,
587                 &(get_to(msg)->uri) /*to uri*/,
588                 &(get_from(msg)->tag_value)/*from_tag*/, &req_uri /*r-uri*/ );
589         if (dlg==0) {
590                 LM_ERR("failed to create new dialog\n");
591                 return -1;
592         }
593
594         /* save caller's tag, cseq, contact and record route*/
595         if (populate_leg_info(dlg, msg, t, DLG_CALLER_LEG,
596                         &(get_from(msg)->tag_value)) !=0)
597         {
598                 LM_ERR("could not add further info to the dialog\n");
599                 shm_free(dlg);
600                 return -1;
601         }
602
603         set_current_dialog(msg, dlg);
604         _dlg_ctx.dlg = dlg;
605
606         link_dlg(dlg, 2/* extra ref for the callback and current dlg hook */);
607
608         /* first INVITE seen (dialog created, unconfirmed) */
609         if ( seq_match_mode!=SEQ_MATCH_NO_ID &&
610                         add_dlg_rr_param( msg, dlg->h_entry, dlg->h_id)<0 ) {
611                 LM_ERR("failed to add RR param\n");
612                 goto error;
613         }
614
615         if ( d_tmb.register_tmcb( msg, t,
616                                 TMCB_RESPONSE_READY|TMCB_RESPONSE_FWDED,
617                                 dlg_onreply, (void*)dlg, unref_new_dialog)<0 ) {
618                 LM_ERR("failed to register TMCB\n");
619                 goto error;
620         }
621
622         dlg->lifetime = get_dlg_timeout(msg);
623         dlg->toroute = _dlg_ctx.to_route;
624         dlg->sflags |= _dlg_ctx.flags;
625
626         if (_dlg_ctx.to_bye!=0)
627                 dlg->dflags |= DLG_FLAG_TOBYE;
628
629         if (t) {
630                 if ( d_tmb.register_tmcb( msg, t, TMCB_MAX,
631                                         dlg_tmcb_dummy, (void*)dlg, 0)<0 ) {
632                         LM_ERR("failed cache in T the shortcut to dlg\n");
633                         goto error;
634                 }
635         }
636 #if 0
637                 t->dialog_ctx = (void*) dlg;
638 #endif
639
640         run_create_callbacks( dlg, msg);
641
642         if_update_stat( dlg_enable_stats, processed_dlgs, 1);
643
644         return 0;
645 error:
646         unref_dlg(dlg,1);
647         profile_cleanup(msg, 0, NULL);
648         update_stat(failed_dlgs, 1);
649         return -1;
650 }
651
652
653 /*!
654  * \brief Parse the record-route parameter, to get dialog information back
655  * \param p start of parameter string
656  * \param end end of parameter string
657  * \param h_entry found dialog hash entry
658  * \param h_id found dialog hash id
659  * \return 0 on success, -1 on failure
660  */
661 static inline int parse_dlg_rr_param(char *p, char *end, int *h_entry, int *h_id)
662 {
663         char *s;
664
665         for ( s=p ; p<end && *p!=DLG_SEPARATOR ; p++ );
666         if (*p!=DLG_SEPARATOR) {
667                 LM_ERR("malformed rr param '%.*s'\n", (int)(long)(end-s), s);
668                 return -1;
669         }
670
671         if ( reverse_hex2int( s, p-s, (unsigned int*)h_entry)<0 ) {
672                 LM_ERR("invalid hash entry '%.*s'\n", (int)(long)(p-s), s);
673                 return -1;
674         }
675
676         if ( reverse_hex2int( p+1, end-(p+1), (unsigned int*)h_id)<0 ) {
677                 LM_ERR("invalid hash id '%.*s'\n", (int)(long)(end-(p+1)), p+1 );
678                 return -1;
679         }
680
681         return 0;
682 }
683
684
685 /*!
686  * \brief Helper function to get the necessary content from SIP message
687  * \param req SIP request
688  * \param callid found callid
689  * \param ftag found from tag
690  * \param ttag found to tag
691  * \return 0 on succes, -1 on failure
692  */
693 static inline int pre_match_parse( struct sip_msg *req, str *callid,
694                 str *ftag, str *ttag)
695 {
696         if (parse_headers(req,HDR_CALLID_F|HDR_TO_F,0)<0 || !req->callid ||
697         !req->to ) {
698                 LM_ERR("bad request or missing CALLID/TO hdr :-/\n");
699                 return -1;
700         }
701
702         if (get_to(req)->tag_value.len==0) {
703                 /* out of dialog request with preloaded Route headers; ignore. */
704                 return -1;
705         }
706
707         if (parse_from_header(req)<0 || get_from(req)->tag_value.len==0) {
708                 LM_ERR("failed to get From header\n");
709                 return -1;
710         }
711
712         /* callid */
713         *callid = req->callid->body;
714         trim(callid);
715         /* to tag */
716         *ttag = get_to(req)->tag_value;
717         /* from tag */
718         *ftag = get_from(req)->tag_value;
719         return 0;
720 }
721
722
723 /*!
724  * \brief Update the saved CSEQ information in dialog from SIP message
725  * \param dlg updated dialog
726  * \param req SIP request
727  * \param dir direction of request, must DLG_DIR_UPSTREAM or DLG_DIR_DOWNSTREAM
728  * \return 0 on success, -1 on failure
729  */
730 static inline int update_cseqs(struct dlg_cell *dlg, struct sip_msg *req,
731                 unsigned int dir)
732 {
733         if ( (!req->cseq && parse_headers(req,HDR_CSEQ_F,0)<0) || !req->cseq ||
734         !req->cseq->parsed) {
735                 LM_ERR("bad sip message or missing CSeq hdr :-/\n");
736                 return -1;
737         }
738
739         if ( dir==DLG_DIR_UPSTREAM) {
740                 return dlg_update_cseq(dlg, DLG_CALLEE_LEG,&((get_cseq(req))->number));
741         } else if ( dir==DLG_DIR_DOWNSTREAM) {
742                 return dlg_update_cseq(dlg, DLG_CALLER_LEG,&((get_cseq(req))->number));
743         } else {
744                 LM_CRIT("dir is not set!\n");
745                 return -1;
746         }
747 }
748
749
750 /*!
751  * \brief Unreference a dialog, small wrapper to care for shutdown
752  * \see unref_dlg 
753  * \param dialog unreferenced dialog
754  */
755 static void unreference_dialog(void *dialog)
756 {
757         // if the dialog table is gone, it means the system is shutting down.
758         if (!d_table)
759                 return;
760         unref_dlg((struct dlg_cell*)dialog, 1);
761 }
762
763
764 /*!
765  * \brief Function that is registered as RR callback for dialog tracking
766  * 
767  * Function that is registered as RR callback for dialog tracking. It
768  * sets the appropriate events after the SIP method and run the state
769  * machine to update the dialog state. It updates then the saved
770  * dialogs and also the statistics.
771  * \param req SIP request
772  * \param route_params record-route parameter
773  * \param param unused
774  */
775 void dlg_onroute(struct sip_msg* req, str *route_params, void *param)
776 {
777         struct dlg_cell *dlg;
778         str val, callid, ftag, ttag;
779         int h_entry, h_id, new_state, old_state, unref, event, timeout;
780         unsigned int dir;
781         int ret = 0;
782
783         if (current_dlg_pointer!=NULL)
784                 return;
785
786         /* skip initial requests - they may end up here because of the
787          * preloaded route */
788         if ( (!req->to && parse_headers(req, HDR_TO_F,0)<0) || !req->to ) {
789                 LM_ERR("bad request or missing TO hdr :-/\n");
790                 return;
791         }
792         if ( get_to(req)->tag_value.len==0 )
793                 return;
794
795         dlg = 0;
796         dir = DLG_DIR_NONE;
797
798         if ( seq_match_mode!=SEQ_MATCH_NO_ID ) {
799                 if( d_rrb.get_route_param( req, &rr_param, &val)!=0) {
800                         LM_DBG("Route param '%.*s' not found\n", rr_param.len,rr_param.s);
801                         if (seq_match_mode==SEQ_MATCH_STRICT_ID )
802                                 return;
803                 } else {
804                         LM_DBG("route param is '%.*s' (len=%d)\n",val.len,val.s,val.len);
805
806                         if ( parse_dlg_rr_param( val.s, val.s+val.len, &h_entry, &h_id)<0 )
807                                 return;
808
809                         dlg = lookup_dlg( h_entry, h_id);
810                         if (dlg==0) {
811                                 LM_WARN("unable to find dialog for %.*s "
812                                         "with route param '%.*s' [%u:%u]\n",
813                                         req->first_line.u.request.method.len,
814                                         req->first_line.u.request.method.s,
815                                         val.len,val.s, h_entry, h_id);
816                                 if (seq_match_mode==SEQ_MATCH_STRICT_ID )
817                                         return;
818                         } else {
819                                 // lookup_dlg has incremented the ref count by 1
820                                 if (pre_match_parse( req, &callid, &ftag, &ttag)<0) {
821                                         unref_dlg(dlg, 1);
822                                         return;
823                                 }
824                                 if (match_dialog( dlg, &callid, &ftag, &ttag, &dir )==0) {
825                                         LM_WARN("tight matching failed for %.*s with callid='%.*s'/%d, "
826                                                         "ftag='%.*s'/%d, ttag='%.*s'/%d and direction=%d\n",
827                                                         req->first_line.u.request.method.len,
828                                                         req->first_line.u.request.method.s,
829                                                         callid.len, callid.s, callid.len,
830                                                         ftag.len, ftag.s, ftag.len,
831                                                         ttag.len, ttag.s, ttag.len, dir);
832                                         LM_WARN("dialog identification elements are callid='%.*s'/%d, "
833                                                         "caller tag='%.*s'/%d, callee tag='%.*s'/%d\n",
834                                                         dlg->callid.len, dlg->callid.s, dlg->callid.len,
835                                                         dlg->tag[DLG_CALLER_LEG].len, dlg->tag[DLG_CALLER_LEG].s,
836                                                         dlg->tag[DLG_CALLER_LEG].len,
837                                                         dlg->tag[DLG_CALLEE_LEG].len, dlg->tag[DLG_CALLEE_LEG].s,
838                                                         dlg->tag[DLG_CALLEE_LEG].len);
839                                         unref_dlg(dlg, 1);
840
841                                         // Reset variables in order to do a lookup based on SIP-Elements.
842                                         dlg = 0;
843                                         dir = DLG_DIR_NONE;
844
845                                         if (seq_match_mode==SEQ_MATCH_STRICT_ID )
846                                                 return;
847                                 }
848                         }
849                 }
850         }
851
852         if (dlg==0) {
853                 if (pre_match_parse( req, &callid, &ftag, &ttag)<0)
854                         return;
855                 /* TODO - try to use the RR dir detection to speed up here the
856                  * search -bogdan */
857                 dlg = get_dlg(&callid, &ftag, &ttag, &dir);
858                 if (!dlg){
859                         LM_DBG("Callid '%.*s' not found\n",
860                                 req->callid->body.len, req->callid->body.s);
861                         return;
862                 }
863         }
864
865         /* run state machine */
866         switch ( req->first_line.u.request.method_value ) {
867                 case METHOD_PRACK:
868                         event = DLG_EVENT_REQPRACK; break;
869                 case METHOD_ACK:
870                         event = DLG_EVENT_REQACK; break;
871                 case METHOD_BYE:
872                         event = DLG_EVENT_REQBYE; break;
873                 default:
874                         event = DLG_EVENT_REQ;
875         }
876
877         next_state_dlg( dlg, event, &old_state, &new_state, &unref);
878
879         CURR_DLG_ID = req->id;
880         CURR_DLG_LIFETIME = (unsigned int)(time(0))-dlg->start_ts;
881         CURR_DLG_STATUS = new_state;
882
883         /* set current dialog - it will keep a ref! */
884         set_current_dialog( req, dlg);
885         _dlg_ctx.dlg = dlg;
886
887         /* run actions for the transition */
888         if (event==DLG_EVENT_REQBYE && new_state==DLG_STATE_DELETED &&
889         old_state!=DLG_STATE_DELETED) {
890                 LM_DBG("BYE successfully processed\n");
891                 /* remove from timer */
892                 ret = remove_dialog_timer(&dlg->tl);
893                 if (ret < 0) {
894                         LM_CRIT("unable to unlink the timer on dlg %p [%u:%u] "
895                                 "with clid '%.*s' and tags '%.*s' '%.*s'\n",
896                                 dlg, dlg->h_entry, dlg->h_id,
897                                 dlg->callid.len, dlg->callid.s,
898                                 dlg->tag[DLG_CALLER_LEG].len, dlg->tag[DLG_CALLER_LEG].s,
899                                 dlg->tag[DLG_CALLEE_LEG].len, dlg->tag[DLG_CALLEE_LEG].s);
900                 } else if (ret > 0) {
901                         LM_WARN("inconsitent dlg timer data on dlg %p [%u:%u] "
902                                 "with clid '%.*s' and tags '%.*s' '%.*s'\n",
903                                 dlg, dlg->h_entry, dlg->h_id,
904                                 dlg->callid.len, dlg->callid.s,
905                                 dlg->tag[DLG_CALLER_LEG].len, dlg->tag[DLG_CALLER_LEG].s,
906                                 dlg->tag[DLG_CALLEE_LEG].len, dlg->tag[DLG_CALLEE_LEG].s);
907                 } else {
908                         unref++;
909                 }
910                 /* dialog terminated (BYE) */
911                 run_dlg_callbacks( DLGCB_TERMINATED, dlg, req, dir, 0);
912
913                 /* delete the dialog from DB */
914                 if (dlg_db_mode)
915                         remove_dialog_from_db(dlg);
916
917                 /* destroy dialog */
918                 unref_dlg(dlg, unref);
919
920                 if_update_stat( dlg_enable_stats, active_dlgs, -1);
921                 return;
922         }
923
924         if ( (event==DLG_EVENT_REQ || event==DLG_EVENT_REQACK)
925         && new_state==DLG_STATE_CONFIRMED) {
926                 LM_DBG("sequential request successfully processed\n");
927                 timeout = get_dlg_timeout(req);
928                 if (timeout!=default_timeout) {
929                         dlg->lifetime = timeout;
930                 }
931                 if (update_dlg_timer( &dlg->tl, dlg->lifetime )==-1) {
932                         LM_ERR("failed to update dialog lifetime\n");
933                 }
934                 if (update_cseqs(dlg, req, dir)!=0) {
935                         LM_ERR("cseqs update failed\n");
936                 } else {
937                         dlg->dflags |= DLG_FLAG_CHANGED;
938                         if ( dlg_db_mode==DB_MODE_REALTIME )
939                                 update_dialog_dbinfo(dlg);
940                 }
941
942                 /* within dialog request */
943                 run_dlg_callbacks( DLGCB_REQ_WITHIN, dlg, req, dir, 0);
944
945                 if ( (event!=DLG_EVENT_REQACK) &&
946                 (dlg->cbs.types)&DLGCB_RESPONSE_WITHIN ) {
947                         /* ref the dialog as registered into the transaction callback.
948                          * unref will be done when the callback will be destroyed */
949                         ref_dlg( dlg , 1);
950                         /* register callback for the replies of this request */
951                         if ( d_tmb.register_tmcb( req, 0, TMCB_RESPONSE_FWDED,
952                         (dir==DLG_DIR_UPSTREAM)?dlg_seq_down_onreply:dlg_seq_up_onreply,
953                         (void*)dlg, unreference_dialog)<0 ) {
954                                 LM_ERR("failed to register TMCB (2)\n");
955                                         unref_dlg( dlg , 1);
956                         }
957                 }
958         }
959
960         if(new_state==DLG_STATE_CONFIRMED && old_state==DLG_STATE_CONFIRMED_NA){
961                 dlg->dflags |= DLG_FLAG_CHANGED;
962                 if(dlg_db_mode == DB_MODE_REALTIME)
963                         update_dialog_dbinfo(dlg);
964         }
965
966         return;
967 }
968
969
970 /*!
971  * \brief Timer function that removes expired dialogs, run timeout route
972  * \param tl dialog timer list
973  */
974 void dlg_ontimeout( struct dlg_tl *tl)
975 {
976         struct dlg_cell *dlg;
977         int new_state, old_state, unref;
978         struct sip_msg *fmsg;
979
980         /* get the dialog tl payload */
981         dlg = ((struct dlg_cell*)((char *)(tl) -
982                 (unsigned long)(&((struct dlg_cell*)0)->tl)));
983
984         if(dlg->toroute>0 && dlg->toroute<main_rt.entries
985                         && main_rt.rlist[dlg->toroute]!=NULL)
986         {
987                 fmsg = faked_msg_next();
988                 if (exec_pre_script_cb(fmsg, REQUEST_CB_TYPE)>0)
989                 {
990                         dlg_set_ctx_dialog(dlg);
991                         LM_DBG("executing route %d on timeout\n", dlg->toroute);
992                         set_route_type(REQUEST_ROUTE);
993                         run_top_route(main_rt.rlist[dlg->toroute], fmsg, 0);
994                         dlg_set_ctx_dialog(0);
995                         exec_post_script_cb(fmsg, REQUEST_CB_TYPE);
996                 }
997         }
998
999         if ((dlg->dflags&DLG_FLAG_TOBYE)
1000                         && (dlg->state==DLG_STATE_CONFIRMED_NA
1001                                 || dlg->state==DLG_STATE_CONFIRMED))
1002         {
1003                 dlg_bye_all(dlg, NULL);
1004                 unref_dlg(dlg, 1);
1005                 if_update_stat(dlg_enable_stats, expired_dlgs, 1);
1006                 return;
1007         }
1008
1009         next_state_dlg( dlg, DLG_EVENT_REQBYE, &old_state, &new_state, &unref);
1010
1011         if (new_state==DLG_STATE_DELETED && old_state!=DLG_STATE_DELETED) {
1012                 LM_WARN("timeout for dlg with CallID '%.*s' and tags '%.*s' '%.*s'\n",
1013                         dlg->callid.len, dlg->callid.s,
1014                         dlg->tag[DLG_CALLER_LEG].len, dlg->tag[DLG_CALLER_LEG].s,
1015                         dlg->tag[DLG_CALLEE_LEG].len, dlg->tag[DLG_CALLEE_LEG].s);
1016
1017                 /* dialog timeout */
1018                 run_dlg_callbacks( DLGCB_EXPIRED, dlg, 0, DLG_DIR_NONE, 0);
1019
1020                 /* delete the dialog from DB */
1021                 if (dlg_db_mode)
1022                         remove_dialog_from_db(dlg);
1023
1024                 unref_dlg(dlg, unref+1);
1025
1026                 if_update_stat( dlg_enable_stats, expired_dlgs, 1);
1027                 if_update_stat( dlg_enable_stats, active_dlgs, -1);
1028         } else {
1029                 unref_dlg(dlg, 1);
1030         }
1031
1032         return;
1033 }
1034
1035
1036 /*!
1037  * \brief Function that returns the dialog lifetime as pseudo-variable
1038  * \param msg SIP message
1039  * \param param pseudo-variable parameter
1040  * \param res pseudo-variable result
1041  * \return 0 on success, -1 on failure
1042  */
1043 int pv_get_dlg_lifetime(struct sip_msg *msg, pv_param_t *param, pv_value_t *res)
1044 {
1045         int l = 0;
1046         char *ch = NULL;
1047
1048         if(msg==NULL || res==NULL)
1049                 return -1;
1050
1051         if (CURR_DLG_ID!=msg->id)
1052                 return pv_get_null( msg, param, res);
1053
1054         res->ri = CURR_DLG_LIFETIME;
1055         ch = int2str( (unsigned long)res->ri, &l);
1056
1057         res->rs.s = ch;
1058         res->rs.len = l;
1059
1060         res->flags = PV_VAL_STR|PV_VAL_INT|PV_TYPE_INT;
1061
1062         return 0;
1063 }
1064
1065
1066 /*!
1067  * \brief Function that returns the dialog state as pseudo-variable
1068  * \param msg SIP message
1069  * \param param pseudo-variable parameter
1070  * \param res pseudo-variable result
1071  * \return 0 on success, -1 on failure
1072  */
1073 int pv_get_dlg_status(struct sip_msg *msg, pv_param_t *param, pv_value_t *res)
1074 {
1075         int l = 0;
1076         char *ch = NULL;
1077
1078         if(msg==NULL || res==NULL)
1079                 return -1;
1080
1081         if (CURR_DLG_ID!=msg->id)
1082                 return pv_get_null( msg, param, res);
1083
1084         res->ri = CURR_DLG_STATUS;
1085         ch = int2str( (unsigned long)res->ri, &l);
1086
1087         res->rs.s = ch;
1088         res->rs.len = l;
1089
1090         res->flags = PV_VAL_STR|PV_VAL_INT|PV_TYPE_INT;
1091
1092         return 0;
1093 }