Merge remote branch 'origin/sr_3.0'
[sip-router] / modules / tm / tm.c
1 /*
2  * $Id$
3  *
4  * TM module
5  *
6  *
7  * ***************************************************
8  * * Jiri's Source Memorial                          *
9  * *                                                 *
10  * * Welcome, pilgrim ! This is the greatest place   *
11  * * where dramatic changes happend. There are not   *
12  * * many places with a history like this, as there  *
13  * * are not so many people like Jiri, one of the    *
14  * * ser's fathers, who brought everywhere the wind  *
15  * * of change, the flood of clean-up. We all felt   *
16  * * his fatherly eye watching over us day and night.*
17  * *                                                 *
18  * * Please, preserve this codework heritage, as     *
19  * * it's unlikely for fresh, juicy pieces of code to  *
20  * * arise to give him the again the chance to       *
21  * * demonstrate his clean-up and improvement skills.*
22  * *                                                 *
23  * * Hereby, we solicit you to adopt this historical *
24  * * piece of code. For $100, your name will be      *
25  * * be printed in this banner and we will use       *
26  * * collected funds to create and display an ASCII  *
27  * * statue of Jiri  .                               *
28  * ***************************************************
29  *
30  *
31  * Copyright (C) 2001-2003 FhG Fokus
32  *
33  * This file is part of SIP-router, a free SIP server.
34  *
35  * SIP-router is free software; you can redistribute it and/or modify
36  * it under the terms of the GNU General Public License as published by
37  * the Free Software Foundation; either version 2 of the License, or
38  * (at your option) any later version
39  *
40  * SIP-router is distributed in the hope that it will be useful,
41  * but WITHOUT ANY WARRANTY; without even the implied warranty of
42  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
43  * GNU General Public License for more details.
44  *
45  * You should have received a copy of the GNU General Public License
46  * along with this program; if not, write to the Free Software
47  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
48  */
49 /*
50  * History:
51  * --------
52  *  2003-02-18  added t_forward_nonack_{udp, tcp}, t_relay_to_{udp,tcp},
53  *               t_replicate_{udp, tcp} (andrei)
54  *  2003-02-19  added t_rely_{udp, tcp} (andrei)
55  *  2003-03-06  voicemail changes accepted (jiri)
56  *  2003-03-10  module export interface updated to the new format (andrei)
57  *  2003-03-16  flags export parameter added (janakj)
58  *  2003-03-19  replaced all mallocs/frees w/ pkg_malloc/pkg_free (andrei)
59  *  2003-03-30  set_kr for requests only (jiri)
60  *  2003-04-05  s/reply_route/failure_route, onreply_route introduced (jiri)
61  *  2003-04-14  use protocol from uri (jiri)
62  *  2003-07-07  added t_relay_to_tls, t_replicate_tls, t_forward_nonack_tls
63  *              added #ifdef USE_TCP, USE_TLS
64  *              removed t_relay_{udp,tcp,tls} (andrei)
65  *  2003-09-26  added t_forward_nonack_uri() - same as t_forward_nonack() but
66  *              takes no parameters -> forwards to uri (bogdan)
67  *  2004-02-11  FIFO/CANCEL + alignments (hash=f(callid,cseq)) (uli+jiri)
68  *  2004-02-18  t_reply exported via FIFO - imported from VM (bogdan)
69  *  2004-10-01  added a new param.: restart_fr_on_each_reply (andrei)
70  *  2005-11-14  new timer support, changed timer related module params (andrei)
71  *  2005-12-09  fixup_hostport2proxy uses route_struct to access param #1
72  *              when fixing param #2
73  *  2005-12-09  added t_set_fr() (andrei)
74  *  2006-02-07  named routes support (andrei)
75  *  2006-09-28  added t_branch_replied, t_branch_timeout, t_any_replied, 
76  *               t_any_timeout, t_is_canceled (andrei)
77  *  2006-10-16  added a new param.: aggregate challenges (andrei)
78  *  2007-05-28  two new params: reparse_invite, ac_extra_hdrs
79  *              added w_t_relay_cancel() (Miklos)
80  *  2007-06-05  added t_set_auto_inv_100() and auto_inv_100 (param);
81  *               t_set_max_lifetime(), max_{non}inv_lifetime  (andrei)
82  *  2008-02-05  module config parameters use the configuration framework (Miklos)
83  *  2008-02-29  added t_grep_status(code) (andrei)
84  *  2008-05-15  added t_relay(host, port) (similar to forward(host, port)) &
85  *               t_relay_to_{udp,tcp,tls}(<no param>) (force protocol, but 
86  *               forward to uri)  (andrei)
87  *  2008-08-11  sctp support: t_relay_to_sctp, t_replicate_sctp,
88  *               t_forward_nonack_sctp (andrei)
89  *  2009-03-18  added a new param: auto_inv_100_reason (aheise) 
90  */
91
92 /*!
93  * \file 
94  * \brief TM :: Module API (core)
95  * \ingroup tm
96  */
97
98 /*!
99  * \defgroup tm TM :: Transaction stateful proxy support
100  *
101    The TM module enables stateful processing of SIP transactions. The main use
102    of stateful logic, which is costly in terms of memory and CPU, is some
103    services that inherently need state. 
104
105    For example, transaction-based accounting (module acc) needs to process 
106    transaction state as opposed to individual messages, and any kinds of 
107    forking must be implemented statefully. Other use of stateful processing 
108    is it trading CPU caused by retransmission processing for memory. 
109    That however only makes sense if CPU consumption per request is huge. 
110    For example, if you want to avoid costly DNS resolution for every 
111    retransmission of a request to an unresolvable destination, use stateful 
112    mode. Then, only the initial message burdens server by DNS queries, 
113    subsequent retransmissions will be dropped and will not result in more 
114    processes blocked by DNS resolution. The price is more memory consumption 
115    and higher processing latency.
116
117  *
118 \code
119  * ***************************************************
120  * * Jiri's Source Memorial                          *
121  * *                                                 *
122  * * Welcome, pilgrim ! This is the greatest place   *
123  * * where dramatic changes happend. There are not   *
124  * * many places with a history like this, as there  *
125  * * are not so many people like Jiri, one of the    *
126  * * ser's fathers, who brought everywhere the wind  *
127  * * of change, the flood of clean-up. We all felt   *
128  * * his fatherly eye watching over us day and night.*
129  * *                                                 *
130  * * Please, preserve this codework heritage, as     *
131  * * it's unlikely for fresh, juicy pieces of code to  *
132  * * arise to give him the again the chance to       *
133  * * demonstrate his clean-up and improvement skills.*
134  * *                                                 *
135  * * Hereby, we solicit you to adopt this historical *
136  * * piece of code. For $100, your name will be      *
137  * * be printed in this banner and we will use       *
138  * * collected funds to create and display an ASCII  *
139  * * statue of Jiri  .                               *
140  * ***************************************************
141 \endcode
142  */
143
144
145 #include "defs.h"
146
147
148 #include <stdio.h>
149 #include <string.h>
150 #include <netdb.h>
151
152 #include "../../sr_module.h"
153 #include "../../dprint.h"
154 #include "../../error.h"
155 #include "../../ut.h"
156 #include "../../script_cb.h"
157 #include "../../usr_avp.h"
158 #include "../../mem/mem.h"
159 #include "../../route_struct.h"
160 #include "../../route.h"
161 #include "../../cfg/cfg.h"
162 #include "../../globals.h"
163 #include "../../timer_ticks.h"
164 #include "../../mod_fix.h"
165
166 #include "config.h"
167 #include "sip_msg.h"
168 #include "h_table.h"
169 #include "t_hooks.h"
170 #include "tm_load.h"
171 #include "ut.h"
172 #include "t_reply.h"
173 #include "uac.h"
174 #include "t_fwd.h"
175 #include "t_lookup.h"
176 #include "t_stats.h"
177 #include "callid.h"
178 #include "t_cancel.h"
179 #include "t_fifo.h"
180 #include "timer.h"
181 #include "t_msgbuilder.h"
182 #include "select.h"
183 #include "t_serial.h"
184 #include "rpc_uac.h"
185
186 MODULE_VERSION
187
188 /* fixup functions */
189 static int fixup_hostport2proxy(void** param, int param_no);
190 static int fixup_proto_hostport2proxy(void** param, int param_no);
191 static int fixup_on_failure(void** param, int param_no);
192 static int fixup_on_reply(void** param, int param_no);
193 static int fixup_on_branch(void** param, int param_no);
194 static int fixup_t_reply(void** param, int param_no);
195 static int fixup_on_sl_reply(modparam_t type, void* val);
196 static int fixup_t_relay_to(void** param, int param_no);
197
198 /* init functions */
199 static int mod_init(void);
200 static int child_init(int rank);
201
202
203 /* exported functions */
204 inline static int w_t_check(struct sip_msg* msg, char* str, char* str2);
205 inline static int w_t_lookup_cancel(struct sip_msg* msg, char* str, char* str2);
206 inline static int w_t_reply(struct sip_msg* msg, char* str, char* str2);
207 inline static int w_t_release(struct sip_msg* msg, char* str, char* str2);
208 inline static int w_t_retransmit_reply(struct sip_msg* p_msg, char* foo,
209                                 char* bar );
210 inline static int w_t_newtran(struct sip_msg* p_msg, char* foo, char* bar );
211 inline static int w_t_relay( struct sip_msg  *p_msg , char *_foo, char *_bar);
212 inline static int w_t_relay2( struct sip_msg  *p_msg , char *proxy, char*);
213 inline static int w_t_relay_to_udp( struct sip_msg  *p_msg , char *proxy,
214                                  char *);
215 inline static int w_t_relay_to_udp_uri( struct sip_msg  *p_msg , char*, char*);
216 #ifdef USE_TCP
217 inline static int w_t_relay_to_tcp( struct sip_msg  *p_msg , char *proxy,
218                                 char *);
219 inline static int w_t_relay_to_tcp_uri( struct sip_msg  *p_msg , char*, char*);
220 #endif
221 #ifdef USE_TLS
222 inline static int w_t_relay_to_tls( struct sip_msg  *p_msg , char *proxy,
223                                 char *);
224 inline static int w_t_relay_to_tls_uri( struct sip_msg  *p_msg , char*, char*);
225 #endif
226 #ifdef USE_SCTP
227 inline static int w_t_relay_to_sctp( struct sip_msg  *p_msg , char *proxy,
228                                 char *);
229 inline static int w_t_relay_to_sctp_uri( struct sip_msg*, char*, char*);
230 #endif
231 inline static int w_t_relay_to_avp(struct sip_msg* msg, char* str,char*);
232 inline static int w_t_relay_to(struct sip_msg* msg, char* str,char*);
233 inline static int w_t_replicate_uri( struct sip_msg  *p_msg ,
234                                 char *uri,       /* sip uri as string or variable */
235                                 char *_foo       /* nothing expected */ );
236 inline static int w_t_replicate( struct sip_msg  *p_msg ,
237                                 char *proxy, /* struct proxy_l *proxy expected */
238                                 char *_foo       /* nothing expected */ );
239 inline static int w_t_replicate_udp( struct sip_msg  *p_msg ,
240                                 char *proxy, /* struct proxy_l *proxy expected */
241                                 char *_foo       /* nothing expected */ );
242 #ifdef USE_TCP
243 inline static int w_t_replicate_tcp( struct sip_msg  *p_msg ,
244                                 char *proxy, /* struct proxy_l *proxy expected */
245                                 char *_foo       /* nothing expected */ );
246 #endif
247 #ifdef USE_TLS
248 inline static int w_t_replicate_tls( struct sip_msg  *p_msg ,
249                                 char *proxy, /* struct proxy_l *proxy expected */
250                                 char *_foo       /* nothing expected */ );
251 #endif
252 #ifdef USE_SCTP
253 inline static int w_t_replicate_sctp( struct sip_msg  *p_msg ,
254                                 char *proxy, /* struct proxy_l *proxy expected */
255                                 char *_foo       /* nothing expected */ );
256 #endif
257 inline static int w_t_replicate_to(struct sip_msg* msg, char* str,char*);
258 inline static int w_t_forward_nonack(struct sip_msg* msg, char* str, char* );
259 inline static int w_t_forward_nonack_uri(struct sip_msg* msg, char* str,char*);
260 inline static int w_t_forward_nonack_udp(struct sip_msg* msg, char* str,char*);
261 #ifdef USE_TCP
262 inline static int w_t_forward_nonack_tcp(struct sip_msg*, char* str,char*);
263 #endif
264 #ifdef USE_TLS
265 inline static int w_t_forward_nonack_tls(struct sip_msg*, char* str,char*);
266 #endif
267 #ifdef USE_SCTP
268 inline static int w_t_forward_nonack_sctp(struct sip_msg*, char* str,char*);
269 #endif
270 inline static int w_t_forward_nonack_to(struct sip_msg* msg, char* str,char*);
271 inline static int w_t_relay_cancel(struct sip_msg *p_msg, char *_foo, char *_bar);
272 inline static int w_t_on_negative(struct sip_msg* msg, char *go_to, char *foo);
273 inline static int w_t_on_branch(struct sip_msg* msg, char *go_to, char *foo);
274 inline static int w_t_on_reply(struct sip_msg* msg, char *go_to, char *foo );
275 inline static int t_check_status(struct sip_msg* msg, char *match, char *foo);
276 static int t_set_fr_inv(struct sip_msg* msg, char* fr_inv, char* foo);
277 static int t_set_fr_all(struct sip_msg* msg, char* fr_inv, char* fr);
278 static int w_t_reset_fr(struct sip_msg* msg, char* foo, char* bar);
279 static int w_t_set_retr(struct sip_msg* msg, char* retr_t1, char* retr_t2);
280 static int w_t_reset_retr(struct sip_msg* msg, char* foo, char* bar);
281 static int w_t_set_max_lifetime(struct sip_msg* msg, char* inv, char* noninv);
282 static int w_t_reset_max_lifetime(struct sip_msg* msg, char* foo, char* bar);
283 static int t_set_auto_inv_100(struct sip_msg* msg, char* on_off, char* foo);
284 static int t_set_disable_6xx(struct sip_msg* msg, char* on_off, char* foo);
285 static int t_set_disable_failover(struct sip_msg* msg, char* on_off, char* f);
286 static int t_branch_timeout(struct sip_msg* msg, char*, char*);
287 static int t_branch_replied(struct sip_msg* msg, char*, char*);
288 static int t_any_timeout(struct sip_msg* msg, char*, char*);
289 static int t_any_replied(struct sip_msg* msg, char*, char*);
290 static int t_is_canceled(struct sip_msg* msg, char*, char*);
291 static int t_is_expired(struct sip_msg* msg, char*, char*);
292 static int t_grep_status(struct sip_msg* msg, char*, char*);
293 static int w_t_drop_replies(struct sip_msg* msg, char* foo, char* bar);
294 static int w_t_save_lumps(struct sip_msg* msg, char* foo, char* bar);
295 static int t_check_trans(struct sip_msg* msg, char* foo, char* bar);
296
297
298 /* by default the fr timers avps are not set, so that the avps won't be
299  * searched for nothing each time a new transaction is created */
300 static char *fr_timer_param = 0 /*FR_TIMER_AVP*/;
301 static char *fr_inv_timer_param = 0 /*FR_INV_TIMER_AVP*/;
302 static char *contacts_avp_param = 0;
303
304 static rpc_export_t tm_rpc[];
305
306 static int fixup_t_check_status(void** param, int param_no);
307
308 static cmd_export_t cmds[]={
309         {"t_newtran",          w_t_newtran,             0, 0,
310                         REQUEST_ROUTE},
311         {"t_lookup_request",   w_t_check,               0, 0,
312                         REQUEST_ROUTE},
313         {"t_lookup_cancel",    w_t_lookup_cancel,       0, 0,
314                         REQUEST_ROUTE},
315         {"t_lookup_cancel",    w_t_lookup_cancel,       1, fixup_int_1,
316                         REQUEST_ROUTE},
317         {T_REPLY,              w_t_reply,               2, fixup_t_reply,
318                         REQUEST_ROUTE | FAILURE_ROUTE },
319         {"t_retransmit_reply", w_t_retransmit_reply,    0, 0,
320                         REQUEST_ROUTE},
321         {"t_release",          w_t_release,             0, 0,
322                         REQUEST_ROUTE},
323         {T_RELAY_TO_UDP,       w_t_relay_to_udp,        2, fixup_hostport2proxy,
324                         REQUEST_ROUTE|FAILURE_ROUTE},
325         {T_RELAY_TO_UDP,       w_t_relay_to_udp_uri,    0, 0,
326                         REQUEST_ROUTE|FAILURE_ROUTE},
327 #ifdef USE_TCP
328         {T_RELAY_TO_TCP,       w_t_relay_to_tcp,        2, fixup_hostport2proxy,
329                         REQUEST_ROUTE|FAILURE_ROUTE},
330         {T_RELAY_TO_TCP,       w_t_relay_to_tcp_uri,    0, 0,
331                         REQUEST_ROUTE|FAILURE_ROUTE},
332 #endif
333 #ifdef USE_TLS
334         {T_RELAY_TO_TLS,       w_t_relay_to_tls,        2, fixup_hostport2proxy,
335                         REQUEST_ROUTE|FAILURE_ROUTE},
336         {T_RELAY_TO_TLS,       w_t_relay_to_tls_uri,    0, 0,
337                         REQUEST_ROUTE|FAILURE_ROUTE},
338 #endif
339 #ifdef USE_SCTP
340         {T_RELAY_TO_SCTP,       w_t_relay_to_sctp,       2, fixup_hostport2proxy,
341                         REQUEST_ROUTE|FAILURE_ROUTE},
342         {T_RELAY_TO_SCTP,       w_t_relay_to_sctp_uri,    0, 0,
343                         REQUEST_ROUTE|FAILURE_ROUTE},
344 #endif
345         {"t_replicate",        w_t_replicate_uri,       1, fixup_var_str_1,
346                         REQUEST_ROUTE},
347         {"t_replicate",        w_t_replicate,           2, fixup_hostport2proxy,
348                         REQUEST_ROUTE},
349         {"t_replicate_udp",    w_t_replicate_udp,       2, fixup_hostport2proxy,
350                         REQUEST_ROUTE},
351 #ifdef USE_TCP
352         {"t_replicate_tcp",    w_t_replicate_tcp,       2, fixup_hostport2proxy,
353                         REQUEST_ROUTE},
354 #endif
355 #ifdef USE_TLS
356         {"t_replicate_tls",    w_t_replicate_tls,       2, fixup_hostport2proxy,
357                         REQUEST_ROUTE},
358 #endif
359 #ifdef USE_SCTP
360         {"t_replicate_sctp",    w_t_replicate_sctp,     2, fixup_hostport2proxy,
361                         REQUEST_ROUTE},
362 #endif
363         {"t_replicate_to", w_t_replicate_to,            2, fixup_proto_hostport2proxy,
364                         REQUEST_ROUTE},
365         {T_RELAY,              w_t_relay,               0, 0,
366                         REQUEST_ROUTE | FAILURE_ROUTE },
367         {T_RELAY,              w_t_relay2,              2, fixup_hostport2proxy,
368                         REQUEST_ROUTE | FAILURE_ROUTE },
369         {"t_relay_to_avp", w_t_relay_to_avp,            2, fixup_proto_hostport2proxy,
370                         REQUEST_ROUTE},
371         {"t_relay_to",                  w_t_relay_to,           0, 0,
372                         REQUEST_ROUTE | FAILURE_ROUTE },
373         {"t_relay_to",                  w_t_relay_to,           1, fixup_t_relay_to,
374                         REQUEST_ROUTE | FAILURE_ROUTE },
375         {"t_relay_to",                  w_t_relay_to,           2, fixup_t_relay_to,
376                         REQUEST_ROUTE | FAILURE_ROUTE },
377         {T_FORWARD_NONACK,     w_t_forward_nonack,      2, fixup_hostport2proxy,
378                         REQUEST_ROUTE},
379         {T_FORWARD_NONACK_URI, w_t_forward_nonack_uri,  0, 0,
380                         REQUEST_ROUTE},
381         {T_FORWARD_NONACK_UDP, w_t_forward_nonack_udp,  2, fixup_hostport2proxy,
382                         REQUEST_ROUTE},
383 #ifdef USE_TCP
384         {T_FORWARD_NONACK_TCP, w_t_forward_nonack_tcp,  2, fixup_hostport2proxy,
385                         REQUEST_ROUTE},
386 #endif
387 #ifdef USE_TLS
388         {T_FORWARD_NONACK_TLS, w_t_forward_nonack_tls,  2, fixup_hostport2proxy,
389                         REQUEST_ROUTE},
390 #endif
391 #ifdef USE_SCTP
392         {T_FORWARD_NONACK_SCTP, w_t_forward_nonack_sctp, 2, fixup_hostport2proxy,
393                         REQUEST_ROUTE},
394 #endif
395         {"t_forward_nonack_to", w_t_forward_nonack_to,  2, fixup_proto_hostport2proxy,
396                         REQUEST_ROUTE},
397         {"t_relay_cancel",     w_t_relay_cancel,        0, 0,
398                         REQUEST_ROUTE},
399         {"t_on_failure",       w_t_on_negative,         1, fixup_on_failure,
400                         REQUEST_ROUTE | FAILURE_ROUTE | ONREPLY_ROUTE },
401         {"t_on_reply",         w_t_on_reply,            1, fixup_on_reply,
402                         REQUEST_ROUTE | FAILURE_ROUTE | ONREPLY_ROUTE },
403         {"t_on_branch",       w_t_on_branch,         1, fixup_on_branch,
404                         REQUEST_ROUTE | FAILURE_ROUTE },
405         {"t_check_status",     t_check_status,          1, fixup_t_check_status,
406                         REQUEST_ROUTE | FAILURE_ROUTE | ONREPLY_ROUTE },
407         {"t_write_req",       t_write_req,              2, fixup_t_write,
408                         REQUEST_ROUTE | FAILURE_ROUTE },
409         {"t_write_unix",      t_write_unix,             2, fixup_t_write,
410                         REQUEST_ROUTE | FAILURE_ROUTE },
411         {"t_set_fr",          t_set_fr_inv,             1, fixup_var_int_1,
412                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
413         {"t_set_fr",          t_set_fr_all,             2, fixup_var_int_12,
414                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
415         {"t_reset_fr",        w_t_reset_fr,             0, 0,
416                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
417         {"t_set_retr",        w_t_set_retr,               2, fixup_var_int_12,
418                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
419         {"t_reset_retr",      w_t_reset_retr,           0, 0,
420                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
421         {"t_set_max_lifetime", w_t_set_max_lifetime,      2, fixup_var_int_12,
422                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
423         {"t_reset_max_lifetime", w_t_reset_max_lifetime, 0, 0,
424                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
425         {"t_set_auto_inv_100", t_set_auto_inv_100,       1, fixup_var_int_1,
426                                                                                                           REQUEST_ROUTE},
427         {"t_set_disable_6xx", t_set_disable_6xx,         1, fixup_var_int_1,
428                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
429         {"t_set_disable_failover", t_set_disable_failover, 1, fixup_var_int_1,
430                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
431         {"t_branch_timeout",  t_branch_timeout,         0, 0,  FAILURE_ROUTE},
432         {"t_branch_replied",  t_branch_replied,         0, 0,  FAILURE_ROUTE},
433         {"t_any_timeout",     t_any_timeout,            0, 0, 
434                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
435         {"t_any_replied",     t_any_replied,            0, 0, 
436                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
437         {"t_is_canceled",     t_is_canceled,            0, 0,
438                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
439         {"t_is_expired",      t_is_expired,             0, 0,
440                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
441         {"t_grep_status",     t_grep_status,            1, fixup_var_int_1, 
442                         REQUEST_ROUTE|ONREPLY_ROUTE|FAILURE_ROUTE|BRANCH_ROUTE },
443         {"t_drop_replies",    w_t_drop_replies,         0, 0,
444                         FAILURE_ROUTE},
445         {"t_drop_replies",    w_t_drop_replies,         1, 0,
446                         FAILURE_ROUTE},
447         {"t_save_lumps",      w_t_save_lumps,           0, 0,
448                         REQUEST_ROUTE},
449         {"t_check_trans",       t_check_trans,                          0, 0,
450                         REQUEST_ROUTE|ONREPLY_ROUTE|BRANCH_ROUTE },
451
452         {"t_load_contacts", t_load_contacts,            0, 0,
453                         REQUEST_ROUTE | FAILURE_ROUTE},
454         {"t_next_contacts", t_next_contacts,            0, 0,
455                         REQUEST_ROUTE | FAILURE_ROUTE},
456
457         /* not applicable from the script */
458         {"register_tmcb",      (cmd_function)register_tmcb,     NO_SCRIPT,   0, 0},
459         {"load_tm",            (cmd_function)load_tm,           NO_SCRIPT,   0, 0},
460         {T_REPLY_WB,           (cmd_function)t_reply_with_body, NO_SCRIPT,   0, 0},
461         {T_IS_LOCAL,           (cmd_function)t_is_local,        NO_SCRIPT,   0, 0},
462         {T_GET_TI,             (cmd_function)t_get_trans_ident, NO_SCRIPT,   0, 0},
463         {T_LOOKUP_IDENT,       (cmd_function)t_lookup_ident,    NO_SCRIPT,   0, 0},
464         {T_ADDBLIND,           (cmd_function)add_blind_uac,     NO_SCRIPT,   0, 0},
465         {"t_request_within",   (cmd_function)req_within,        NO_SCRIPT,   0, 0},
466         {"t_request_outside",  (cmd_function)req_outside,       NO_SCRIPT,   0, 0},
467         {"t_request",          (cmd_function)request,           NO_SCRIPT,   0, 0},
468         {"new_dlg_uac",        (cmd_function)new_dlg_uac,       NO_SCRIPT,   0, 0},
469         {"dlg_response_uac",   (cmd_function)dlg_response_uac,  NO_SCRIPT,   0, 0},
470         {"new_dlg_uas",        (cmd_function)new_dlg_uas,       NO_SCRIPT,   0, 0},
471         {"update_dlg_uas",     (cmd_function)update_dlg_uas,    NO_SCRIPT,   0, 0},
472         {"dlg_request_uas",    (cmd_function)dlg_request_uas,   NO_SCRIPT,   0, 0},
473         {"set_dlg_target",     (cmd_function)set_dlg_target,    NO_SCRIPT,   0, 0},
474         {"free_dlg",           (cmd_function)free_dlg,          NO_SCRIPT,   0, 0},
475         {"print_dlg",          (cmd_function)print_dlg,         NO_SCRIPT,   0, 0},
476         {T_GETT,               (cmd_function)get_t,             NO_SCRIPT,   0, 0},
477         {"calculate_hooks",    (cmd_function)w_calculate_hooks, NO_SCRIPT,   0, 0},
478         {"t_uac",              (cmd_function)t_uac,             NO_SCRIPT,   0, 0},
479         {"t_uac_with_ids",     (cmd_function)t_uac_with_ids,    NO_SCRIPT,   0, 0},
480         {"t_unref",            (cmd_function)t_unref,           NO_SCRIPT,   0, 0},
481         {"run_failure_handlers", (cmd_function)run_failure_handlers, NO_SCRIPT,   0, 0},
482         {"cancel_uacs",        (cmd_function)cancel_uacs,       NO_SCRIPT,   0, 0},
483         {"cancel_all_uacs",    (cmd_function)cancel_all_uacs,        NO_SCRIPT,   0, 0},
484 #ifdef WITH_AS_SUPPORT
485         {"ack_local_uac",      (cmd_function)ack_local_uac,     NO_SCRIPT,   0, 0},
486         {"t_get_canceled_ident",   (cmd_function)t_get_canceled_ident,  NO_SCRIPT,
487                         0, 0},
488 #endif
489         {"t_suspend",          (cmd_function)t_suspend,         NO_SCRIPT,   0, 0},
490         {"t_continue",         (cmd_function)t_continue,        NO_SCRIPT,   0, 0},
491         {0,0,0,0,0}
492 };
493
494
495 static param_export_t params[]={
496         {"ruri_matching",       PARAM_INT, &default_tm_cfg.ruri_matching         },
497         {"via1_matching",       PARAM_INT, &default_tm_cfg.via1_matching         },
498         {"fr_timer",            PARAM_INT, &default_tm_cfg.fr_timeout            },
499         {"fr_inv_timer",        PARAM_INT, &default_tm_cfg.fr_inv_timeout        },
500         {"fr_inv_timer_next",   PARAM_INT, &default_tm_cfg.fr_inv_timeout_next   },
501         {"wt_timer",            PARAM_INT, &default_tm_cfg.wait_timeout          },
502         {"delete_timer",        PARAM_INT, &default_tm_cfg.delete_timeout        },
503         {"retr_timer1",         PARAM_INT, &default_tm_cfg.rt_t1_timeout         },
504         {"retr_timer2"  ,       PARAM_INT, &default_tm_cfg.rt_t2_timeout         },
505         {"max_inv_lifetime",    PARAM_INT, &default_tm_cfg.tm_max_inv_lifetime   },
506         {"max_noninv_lifetime", PARAM_INT, &default_tm_cfg.tm_max_noninv_lifetime},
507         {"noisy_ctimer",        PARAM_INT, &default_tm_cfg.noisy_ctimer          },
508         {"auto_inv_100",        PARAM_INT, &default_tm_cfg.tm_auto_inv_100       },
509         {"auto_inv_100_reason", PARAM_STRING, &default_tm_cfg.tm_auto_inv_100_r  },
510         {"unix_tx_timeout",     PARAM_INT, &default_tm_cfg.tm_unix_tx_timeout    },
511         {"restart_fr_on_each_reply", PARAM_INT,
512                                                                         &default_tm_cfg.restart_fr_on_each_reply},
513         {"fr_timer_avp",        PARAM_STRING, &fr_timer_param                    },
514         {"fr_inv_timer_avp",    PARAM_STRING, &fr_inv_timer_param                },
515         {"tw_append",           PARAM_STRING|PARAM_USE_FUNC, 
516                                                                                                         (void*)parse_tw_append   },
517         {"pass_provisional_replies", PARAM_INT, 
518                                                                         &default_tm_cfg.pass_provisional_replies },
519         {"aggregate_challenges", PARAM_INT, &default_tm_cfg.tm_aggregate_auth    },
520         {"unmatched_cancel",    PARAM_INT, &default_tm_cfg.unmatched_cancel      },
521         {"default_code",        PARAM_INT, &default_tm_cfg.default_code          },
522         {"default_reason",      PARAM_STRING, &default_tm_cfg.default_reason     },
523         {"reparse_invite",      PARAM_INT, &default_tm_cfg.reparse_invite        },
524         {"ac_extra_hdrs",       PARAM_STR, &default_tm_cfg.ac_extra_hdrs         },
525         {"blst_503",            PARAM_INT, &default_tm_cfg.tm_blst_503           },
526         {"blst_503_def_timeout",PARAM_INT, &default_tm_cfg.tm_blst_503_default   },
527         {"blst_503_min_timeout",PARAM_INT, &default_tm_cfg.tm_blst_503_min       },
528         {"blst_503_max_timeout",PARAM_INT, &default_tm_cfg.tm_blst_503_max       },
529         {"blst_methods_add",    PARAM_INT, &default_tm_cfg.tm_blst_methods_add   },
530         {"blst_methods_lookup", PARAM_INT, &default_tm_cfg.tm_blst_methods_lookup},
531         {"cancel_b_method",     PARAM_INT, &default_tm_cfg.cancel_b_flags},
532         {"reparse_on_dns_failover", PARAM_INT, &default_tm_cfg.reparse_on_dns_failover},
533         {"on_sl_reply",         PARAM_STRING|PARAM_USE_FUNC, fixup_on_sl_reply   },
534         {"contacts_avp",        PARAM_STRING, &contacts_avp_param                },
535         {"disable_6xx_block",   PARAM_INT, &default_tm_cfg.disable_6xx           },
536         {"local_ack_mode",      PARAM_INT, &default_tm_cfg.local_ack_mode        },
537         {0,0,0}
538 };
539
540 #ifdef STATIC_TM
541 struct module_exports tm_exports = {
542 #else
543 struct module_exports exports= {
544 #endif
545         "tm",
546         /* -------- exported functions ----------- */
547         cmds,
548         tm_rpc,    /* RPC methods */
549         /* ------------ exported variables ---------- */
550         params,
551
552         mod_init, /* module initialization function */
553         (response_function) reply_received,
554         (destroy_function) tm_shutdown,
555         0, /* w_onbreak, */
556         child_init /* per-child init function */
557 };
558
559
560
561 /* helper for fixup_on_* */
562 static int fixup_routes(char* r_type, struct route_list* rt, void** param)
563 {
564         int i;
565         
566         i=route_get(rt, (char*)*param);
567         if (i==-1){
568                 LOG(L_ERR, "ERROR: tm: fixup_routes: route_get failed\n");
569                 return E_UNSPEC;
570         }
571         if (r_type && rt->rlist[i]==0){
572                 LOG(L_WARN, "WARNING: %s(\"%s\"): empty/non existing route\n",
573                                 r_type, (char*)*param);
574         }
575         *param=(void*)(long)i;
576         return 0;
577 }
578
579 static int fixup_t_reply(void** param, int param_no)
580 {
581         if (param_no == 1) {
582                 if (fixup_var_int_12(param, 1) != 0) return -1;
583         } else if (param_no == 2) {
584                 return fixup_var_str_12(param, 2);
585         }
586     return 0;
587 }
588
589 static int fixup_on_failure(void** param, int param_no)
590 {
591         if (param_no==1){
592                 return fixup_routes("t_on_failure", &failure_rt, param);
593         }
594         return 0;
595 }
596
597
598
599 static int fixup_on_reply(void** param, int param_no)
600 {
601         if (param_no==1){
602                 return fixup_routes("t_on_reply", &onreply_rt, param);
603         }
604         return 0;
605 }
606
607
608
609 static int fixup_on_branch(void** param, int param_no)
610 {
611         if (param_no==1){
612                 return fixup_routes("t_on_branch", &branch_rt, param);
613         }
614         return 0;
615 }
616
617 static int fixup_on_sl_reply(modparam_t type, void* val)
618 {
619         if ((type & PARAM_STRING) == 0) {
620                 LOG(L_ERR, "ERROR: tm: fixup_on_sl_reply: not a string parameter\n");
621                 return -1;
622         }
623
624         if (fixup_routes(0, &onreply_rt, &val))
625                 return -1;
626
627         goto_on_sl_reply = (int)(long)val;
628         return 0;
629 }
630
631
632
633 /* (char *hostname, char *port_nr) ==> (struct proxy_l *, -)  */
634 static int fixup_hostport2proxy(void** param, int param_no)
635 {
636         unsigned int port;
637         char *host;
638         int err;
639         struct proxy_l *proxy;
640         action_u_t *a;
641         str s;
642
643         DBG("TM module: fixup_hostport2proxy(%s, %d)\n", (char*)*param, param_no);
644         if (param_no==1){
645                 return 0;
646         } else if (param_no==2) {
647                 a = fixup_get_param(param, param_no, 1);
648                 host= a->u.string;
649                 port=str2s(*param, strlen(*param), &err);
650                 if (err!=0) {
651                         LOG(L_ERR, "TM module:fixup_hostport2proxy: bad port number <%s>\n",
652                                 (char*)(*param));
653                          return E_UNSPEC;
654                 }
655                 s.s = host;
656                 s.len = strlen(host);
657                 proxy=mk_proxy(&s, port, 0); /* FIXME: udp or tcp? */
658                 if (proxy==0) {
659                         LOG(L_ERR, "ERROR: fixup_hostport2proxy: bad host name in URI <%s>\n",
660                                 host );
661                         return E_BAD_ADDRESS;
662                 }
663                 /* success -- fix the first parameter to proxy now ! */
664
665                 a->u.data=proxy;
666                 return 0;
667         } else {
668                 LOG(L_ERR,"ERROR: fixup_hostport2proxy called with parameter #<>{1,2}\n");
669                 return E_BUG;
670         }
671 }
672
673 /* (char *$proto, char *$host:port) ==> (fparam, fparam)  */
674 static int fixup_proto_hostport2proxy(void** param, int param_no) {
675         int ret;
676
677         ret = fix_param(FPARAM_AVP, param);
678         if (ret <= 0) return ret;
679 /*      if (param_no = 1) {             FIXME: param_str currently does not offer INT/STR overloading
680                 ret = fix_param(FPARAM_INT, param);
681                 if (ret <= 0) return ret;
682         } */
683         if (fix_param(FPARAM_STRING, param) != 0) return -1;
684         return 0;
685 }
686
687
688 static int fixup_t_check_status(void** param, int param_no)
689 {
690         int ret;
691
692         ret = fix_param(FPARAM_AVP, param);
693         if (ret <= 0) return ret;
694
695         ret = fix_param(FPARAM_SELECT, param);
696         if (ret <= 0) return ret;
697
698         if (fix_param(FPARAM_REGEX, param) != 0) return -1;
699         return 0;
700 }
701
702
703 /***************************** init functions *****************************/
704 static int w_t_unref( struct sip_msg *foo, unsigned int flags, void *bar)
705 {
706         return t_unref(foo);
707 }
708
709
710 static int script_init( struct sip_msg *foo, unsigned int flags, void *bar)
711 {
712         /* we primarily reset all private memory here to make sure
713          * private values left over from previous message will
714          * not be used again */
715
716         /* make sure the new message will not inherit previous
717                 message's t_on_negative value
718         */
719         t_on_negative( 0 );
720         t_on_reply(0);
721         t_on_branch(0);
722         /* reset the kr status */
723         reset_kr(0);
724         /* set request mode so that multiple-mode actions know
725          * how to behave */
726         set_route_type(REQUEST_ROUTE);
727
728 #ifdef POSTPONE_MSG_CLONING
729         lumps_are_cloned = 0;
730 #endif
731         return 1;
732 }
733
734
735 static int mod_init(void)
736 {
737         DBG( "TM - (sizeof cell=%ld, sip_msg=%ld) initializing...\n",
738                         (long)sizeof(struct cell), (long)sizeof(struct sip_msg));
739
740         /* checking if we have sufficient bitmap capacity for given
741            maximum number of  branches */
742         if (MAX_BRANCHES+1>31) {
743                 LOG(L_CRIT, "Too many max UACs for UAC branch_bm_t bitmap: %d\n",
744                         MAX_BRANCHES );
745                 return -1;
746         }
747
748         if (init_callid() < 0) {
749                 LOG(L_CRIT, "Error while initializing Call-ID generator\n");
750                 return -1;
751         }
752
753         /* building the hash table*/
754         if (!init_hash_table()) {
755                 LOG(L_ERR, "ERROR: mod_init: initializing hash_table failed\n");
756                 return -1;
757         }
758
759         /* init static hidden values */
760         init_t();
761
762         if (tm_init_selects()==-1) {
763                 LOG(L_ERR, "ERROR: mod_init: select init failed\n");
764                 return -1;
765         }
766
767         /* the default timer values must be fixed-up before
768          * declaring the configuration (Miklos) */
769         if (tm_init_timers()==-1) {
770                 LOG(L_ERR, "ERROR: mod_init: timer init failed\n");
771                 return -1;
772         }
773         
774         /* the cancel branch flags must be fixed before declaring the 
775          * configuration */
776         if (cancel_b_flags_get(&default_tm_cfg.cancel_b_flags, 
777                                                         default_tm_cfg.cancel_b_flags)<0){
778                 LOG(L_ERR, "ERROR: mod_init: bad cancel branch method\n");
779                 return -1;
780         }
781
782 #ifdef USE_DNS_FAILOVER
783         if (default_tm_cfg.reparse_on_dns_failover && mhomed) {
784                 LOG(L_WARN, "WARNING: mod_init: "
785                         "reparse_on_dns_failover is enabled on a "
786                         "multihomed host -- check the readme of tm module!\n");
787         }
788 #endif
789
790         /* declare the configuration */
791         if (cfg_declare("tm", tm_cfg_def, &default_tm_cfg, cfg_sizeof(tm),
792                          &tm_cfg)) {
793                 LOG(L_ERR, "ERROR: mod_init: failed to declare the configuration\n");
794                 return -1;
795         }
796
797              /* First tm_stat initialization function only allocates the top level stat
798               * structure in shared memory, the initialization will complete in child
799               * init with init_tm_stats_child when the final value of estimated_process_count is
800               * known
801               */
802         if (init_tm_stats() < 0) {
803                 LOG(L_CRIT, "ERROR: mod_init: failed to init stats\n");
804                 return -1;
805         }
806
807         if (uac_init()==-1) {
808                 LOG(L_ERR, "ERROR: mod_init: uac_init failed\n");
809                 return -1;
810         }
811
812         if (init_tmcb_lists()!=1) {
813                 LOG(L_CRIT, "ERROR:tm:mod_init: failed to init tmcb lists\n");
814                 return -1;
815         }
816         
817         tm_init_tags();
818         init_twrite_lines();
819         if (init_twrite_sock() < 0) {
820                 LOG(L_ERR, "ERROR:tm:mod_init: Unable to create socket\n");
821                 return -1;
822         }
823
824         /* register post-script clean-up function */
825         if (register_script_cb( w_t_unref, POST_SCRIPT_CB|REQUEST_CB, 0)<0 ) {
826                 LOG(L_ERR,"ERROR:tm:mod_init: failed to register POST request "
827                         "callback\n");
828                 return -1;
829         }
830         if (register_script_cb( script_init, PRE_SCRIPT_CB|REQUEST_CB , 0)<0 ) {
831                 LOG(L_ERR,"ERROR:tm:mod_init: failed to register PRE request "
832                         "callback\n");
833                 return -1;
834         }
835
836         if (init_avp_params( fr_timer_param, fr_inv_timer_param,
837                                                  contacts_avp_param)<0 ){
838                 LOG(L_ERR,"ERROR:tm:mod_init: failed to process AVP params\n");
839                 return -1;
840         }
841 #ifdef WITH_EVENT_LOCAL_REQUEST
842         goto_on_local_req=route_lookup(&event_rt, "tm:local-request");
843         if (goto_on_local_req>=0 && event_rt.rlist[goto_on_local_req]==0)
844                 goto_on_local_req=-1; /* disable */
845 #endif /* WITH_EVENT_LOCAL_REQUEST */
846         if (goto_on_sl_reply && onreply_rt.rlist[goto_on_sl_reply]==0)
847                 WARN("empty/non existing on_sl_reply route\n");
848         tm_init = 1;
849         return 0;
850 }
851
852 static int child_init(int rank)
853 {
854         if (rank == PROC_INIT) {
855                 /* we must init stats when rank==PROC_INIT: after mod_init we know
856                  * the exact number of processes and we must init the shared structure
857                  * before any other process is starting (or else some new process
858                  * might try to use the stats before the stats array is allocated) */
859                 if (init_tm_stats_child() < 0) {
860                         ERR("Error while initializing tm statistics structures\n");
861                         return -1;
862                 }
863         }else if (child_init_callid(rank) < 0) { 
864                 /* don't init callid for PROC_INIT*/
865                 LOG(L_ERR, "ERROR: child_init: Error while initializing Call-ID"
866                                 " generator\n");
867                 return -2;
868         }
869         return 0;
870 }
871
872
873
874
875
876 /**************************** wrapper functions ***************************/
877 static int t_check_status(struct sip_msg* msg, char *p1, char *foo)
878 {
879         regmatch_t pmatch;
880         struct cell *t;
881         char *status, *s = NULL;
882         char backup;
883         int lowest_status, n, ret;
884         fparam_t* fp;
885         regex_t* re = NULL;
886         str tmp;
887         
888         fp = (fparam_t*)p1;
889         
890         /* first get the transaction */
891         if (t_check(msg, 0 ) == -1) return -1;
892         if ((t = get_t()) == 0) {
893                 LOG(L_ERR, "ERROR: t_check_status: cannot check status for a reply "
894                         "which has no T-state established\n");
895                 goto error;
896         }
897         backup = 0;
898         
899         switch(fp->type) {
900         case FPARAM_REGEX:
901                 re = fp->v.regex;
902                 break;
903                 
904         default:
905                 /* AVP or select, get the value and compile the regex */
906                 if (get_str_fparam(&tmp, msg, fp) < 0) goto error;
907                 s = pkg_malloc(tmp.len + 1);
908                 if (s == NULL) {
909                         ERR("Out of memory\n");
910                         goto error;
911                 }
912                 memcpy(s, tmp.s, tmp.len);
913                 s[tmp.len] = '\0';
914                 
915                 if ((re = pkg_malloc(sizeof(regex_t))) == 0) {
916                         ERR("No memory left\n");
917                         goto error;
918                 }
919                 
920                 if (regcomp(re, s, REG_EXTENDED|REG_ICASE|REG_NEWLINE)) {
921                         ERR("Bad regular expression '%s'\n", s);
922                         goto error;
923                 }
924                 break;
925         }
926         
927         switch(route_type) {
928         case REQUEST_ROUTE:
929                 /* use the status of the last sent reply */
930                 status = int2str( t->uas.status, 0);
931                 break;
932                 
933         case ONREPLY_ROUTE:
934                 /* use the status of the current reply */
935                 status = msg->first_line.u.reply.status.s;
936                 backup = status[msg->first_line.u.reply.status.len];
937                 status[msg->first_line.u.reply.status.len] = 0;
938                 break;
939
940         case FAILURE_ROUTE:
941                 /* use the status of the winning reply */
942                 ret = t_pick_branch( -1, 0, t, &lowest_status);
943                 if (ret == -1) {
944                         /* t_pick_branch() retuns error also when there are only
945                          * blind UACs. Let us give it another chance including the
946                          * blind branches. */
947                         LOG(L_DBG, "DEBUG: t_check_status: t_pick_branch returned error, "
948                                 "trying t_pick_branch_blind\n");
949                         ret = t_pick_branch_blind(t, &lowest_status);
950                 }
951                 if (ret < 0) {
952                         LOG(L_CRIT,"BUG:t_check_status: t_pick_branch failed to get "
953                                 " a final response in FAILURE_ROUTE\n");
954                         goto error;
955                 }
956                 status = int2str( lowest_status , 0);
957                 break;
958
959         default:
960                 LOG(L_ERR,"ERROR:t_check_status: unsupported route type %d\n",route_type);
961                 goto error;
962         }
963
964         DBG("DEBUG:t_check_status: checked status is <%s>\n",status);
965         /* do the checking */
966         n = regexec(re, status, 1, &pmatch, 0);
967
968         if (backup) status[msg->first_line.u.reply.status.len] = backup;
969         if (s) pkg_free(s);
970         if ((fp->type != FPARAM_REGEX) && re) {
971                 regfree(re);
972                 pkg_free(re);
973         }
974
975         if (n!=0) return -1;
976         return 1;
977
978  error:
979         if (s) pkg_free(s);
980         if ((fp->type != FPARAM_REGEX) && re) {
981                 regfree(re);
982                 pkg_free(re);
983         }
984         return -1;
985 }
986
987
988 inline static int w_t_check(struct sip_msg* msg, char* str, char* str2)
989 {
990         return (t_check_msg( msg , 0  )==1) ? 1 : -1;
991 }
992
993 inline static int w_t_lookup_cancel(struct sip_msg* msg, char* str, char* str2)
994 {
995         struct cell *ret;
996         int i=0;
997         if (msg->REQ_METHOD==METHOD_CANCEL) {
998                 ret = t_lookupOriginalT( msg );
999                 DBG("lookup_original: t_lookupOriginalT returned: %p\n", ret);
1000                 if (ret != T_NULL_CELL) {
1001                         /* If the parameter is set to 1, overwrite the message flags of
1002                          * the CANCEL with the flags of the INVITE */
1003                         if (str && (get_int_fparam(&i, msg, (fparam_t*)str)==0) && i)
1004                                 msg->flags = ret->uas.request->flags;
1005
1006                         /* The cell is reffed by t_lookupOriginalT, but T is not set.
1007                         So we must unref it before returning. */
1008                         UNREF(ret);
1009                         return 1;
1010                 }
1011         } else {
1012                 LOG(L_WARN, "WARNING: script error t_lookup_cancel() called for non-CANCEL request\n");
1013         }
1014         return -1;
1015 }
1016
1017 inline static int str2proto(char *s, int len) {
1018         if (len == 3 && !strncasecmp(s, "udp", 3))
1019                 return PROTO_UDP;
1020         else if (len == 3 && !strncasecmp(s, "tcp", 3))  /* tcp&tls checks will be passed in getproto() */
1021                 return PROTO_TCP;
1022         else if (len == 3 && !strncasecmp(s, "tls", 3))
1023                 return PROTO_TLS;       
1024         else if (len == 4 && !strncasecmp(s, "sctp", 4))
1025                 return PROTO_SCTP;
1026         else
1027                 return PROTO_NONE;
1028 }
1029
1030 inline static struct proxy_l* t_protoaddr2proxy(char *proto_par, char *addr_par) {
1031         struct proxy_l *proxy = 0;
1032         avp_t* avp;
1033         avp_value_t val;
1034         int proto, port, err;
1035         str s;
1036         char *c;
1037         
1038         switch(((fparam_t *)proto_par)->type) {
1039         case FPARAM_AVP:
1040                 if (!(avp = search_first_avp(((fparam_t *)proto_par)->v.avp.flags, ((fparam_t *)proto_par)->v.avp.name, &val, 0))) {
1041                         proto = PROTO_NONE;
1042                 } else {
1043                         if (avp->flags & AVP_VAL_STR) {
1044                                 proto = str2proto(val.s.s, val.s.len);
1045                         }
1046                         else {
1047                                 proto = val.n;
1048                         }
1049                 }
1050                 break;
1051
1052         case FPARAM_INT:
1053                 proto = ((fparam_t *)proto_par)->v.i;
1054                 break;
1055         case FPARAM_STRING:
1056                 proto = str2proto( ((fparam_t *)proto_par)->v.asciiz, strlen(((fparam_t *)proto_par)->v.asciiz));
1057                 break;
1058         default:
1059                 ERR("BUG: Invalid proto parameter value in t_protoaddr2proxy\n");
1060                 return 0;
1061         }
1062
1063
1064         switch(((fparam_t *)addr_par)->type) {
1065         case FPARAM_AVP:
1066                 if (!(avp = search_first_avp(((fparam_t *)addr_par)->v.avp.flags, ((fparam_t *)addr_par)->v.avp.name, &val, 0))) {
1067                         s.len = 0;
1068                 } else {
1069                         if ((avp->flags & AVP_VAL_STR) == 0) {
1070                                 LOG(L_ERR, "tm:t_protoaddr2proxy: avp <%.*s> value is not string\n",
1071                                         ((fparam_t *)addr_par)->v.avp.name.s.len, ((fparam_t *)addr_par)->v.avp.name.s.s);
1072                                 return 0;
1073                         }
1074                         s = val.s;
1075                 }
1076                 break;
1077
1078         case FPARAM_STRING:
1079                 s.s = ((fparam_t *) addr_par)->v.asciiz;
1080                 s.len = strlen(s.s);
1081                 break;
1082
1083         default:
1084                 ERR("BUG: Invalid addr parameter value in t_protoaddr2proxy\n");
1085                 return 0;
1086         }
1087
1088         port = 5060;
1089         if (s.len) {
1090                 c = memchr(s.s, ':', s.len);
1091                 if (c) {
1092                         port = str2s(c+1, s.len-(c-s.s+1), &err);
1093                         if (err!=0) {
1094                                 LOG(L_ERR, "tm:t_protoaddr2proxy: bad port number <%.*s>\n",
1095                                         s.len, s.s);
1096                                  return 0;
1097                         }
1098                         s.len = c-s.s;
1099                 }
1100         }
1101         if (!s.len) {
1102                 LOG(L_ERR, "tm: protoaddr2proxy: host name is empty\n");
1103                 return 0;
1104         }
1105         proxy=mk_proxy(&s, port, proto);
1106         if (proxy==0) {
1107                 LOG(L_ERR, "tm: protoaddr2proxy: bad host name in URI <%.*s>\n",
1108                         s.len, s.s );
1109                 return 0;
1110         }
1111         return proxy;
1112 }
1113
1114 inline static int _w_t_forward_nonack(struct sip_msg* msg, struct proxy_l* proxy,
1115         int proto)
1116 {
1117         struct cell *t;
1118         if (t_check( msg , 0 )==-1) {
1119                 LOG(L_ERR, "ERROR: forward_nonack: "
1120                                 "can't forward when no transaction was set up\n");
1121                 return -1;
1122         }
1123         t=get_t();
1124         if ( t && t!=T_UNDEFINED ) {
1125                 if (msg->REQ_METHOD==METHOD_ACK) {
1126                         LOG(L_WARN,"WARNING: you don't really want to fwd hbh ACK\n");
1127                         return -1;
1128                 }
1129                 return t_forward_nonack(t, msg, proxy, proto );
1130         } else {
1131                 DBG("DEBUG: forward_nonack: no transaction found\n");
1132                 return -1;
1133         }
1134 }
1135
1136
1137 inline static int w_t_forward_nonack( struct sip_msg* msg, char* proxy,
1138                                                                                 char* foo)
1139 {
1140         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_NONE);
1141 }
1142
1143
1144 inline static int w_t_forward_nonack_uri(struct sip_msg* msg, char *foo,
1145                                                                                                                                         char *bar)
1146 {
1147         return _w_t_forward_nonack(msg, 0, PROTO_NONE);
1148 }
1149
1150
1151 inline static int w_t_forward_nonack_udp( struct sip_msg* msg, char* proxy,
1152                                                                                 char* foo)
1153 {
1154         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_UDP);
1155 }
1156
1157
1158 #ifdef USE_TCP
1159 inline static int w_t_forward_nonack_tcp( struct sip_msg* msg, char* proxy,
1160                                                                                 char* foo)
1161 {
1162         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_TCP);
1163 }
1164 #endif
1165
1166
1167 #ifdef USE_TLS
1168 inline static int w_t_forward_nonack_tls( struct sip_msg* msg, char* proxy,
1169                                                                                 char* foo)
1170 {
1171         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_TLS);
1172 }
1173 #endif
1174
1175
1176 #ifdef USE_SCTP
1177 inline static int w_t_forward_nonack_sctp( struct sip_msg* msg, char* proxy,
1178                                                                                 char* foo)
1179 {
1180         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_SCTP);
1181 }
1182 #endif
1183
1184
1185 inline static int w_t_forward_nonack_to( struct sip_msg  *p_msg ,
1186         char *proto_par, 
1187         char *addr_par   )
1188 {
1189         struct proxy_l *proxy;
1190         int r = -1;
1191         proxy = t_protoaddr2proxy(proto_par, addr_par);
1192         if (proxy) {
1193                 r = _w_t_forward_nonack(p_msg, proxy, proxy->proto);            
1194                 free_proxy(proxy);
1195         }
1196         return r;
1197 }
1198
1199
1200 inline static int w_t_reply(struct sip_msg* msg, char* p1, char* p2)
1201 {
1202         struct cell *t;
1203         int code, ret = -1;
1204         str reason;
1205         char* r;
1206
1207         if (msg->REQ_METHOD==METHOD_ACK) {
1208                 LOG(L_WARN, "WARNING: t_reply: ACKs are not replied\n");
1209                 return -1;
1210         }
1211         if (t_check( msg , 0 )==-1) return -1;
1212         t=get_t();
1213         if (!t) {
1214                 LOG(L_ERR, "ERROR: t_reply: cannot send a t_reply to a message "
1215                         "for which no T-state has been established\n");
1216                 return -1;
1217         }
1218
1219         if (get_int_fparam(&code, msg, (fparam_t*)p1) < 0) {
1220             code = cfg_get(tm, tm_cfg, default_code);
1221         }
1222         
1223         if (get_str_fparam(&reason, msg, (fparam_t*)p2) < 0) {
1224                 r = cfg_get(tm, tm_cfg, default_reason);
1225         } else {
1226                 r = as_asciiz(&reason);
1227                 if (r == NULL) r = cfg_get(tm, tm_cfg, default_reason);
1228         }
1229         
1230         /* if called from reply_route, make sure that unsafe version
1231          * is called; we are already in a mutex and another mutex in
1232          * the safe version would lead to a deadlock
1233          */
1234          
1235         if (is_route_type(FAILURE_ROUTE)) {
1236                 DBG("DEBUG: t_reply_unsafe called from w_t_reply\n");
1237                 ret = t_reply_unsafe(t, msg, code, r);
1238         } else if (is_route_type(REQUEST_ROUTE)) {
1239                 ret = t_reply( t, msg, code, r);
1240         } else {
1241                 LOG(L_CRIT, "BUG: w_t_reply entered in unsupported mode\n");
1242                 ret = -1;
1243         }
1244
1245         if (r && (r != cfg_get(tm, tm_cfg, default_reason))) pkg_free(r);
1246         return ret;
1247 }
1248
1249
1250 inline static int w_t_release(struct sip_msg* msg, char* str, char* str2)
1251 {
1252         struct cell *t;
1253         int ret;
1254         
1255         if (t_check( msg  , 0  )==-1) return -1;
1256         t=get_t();
1257         if ( t && t!=T_UNDEFINED ) {
1258                 ret = t_release_transaction( t );
1259                 t_unref(msg);
1260                 return ret;
1261         }
1262         return 1;
1263 }
1264
1265
1266 inline static int w_t_retransmit_reply( struct sip_msg* p_msg, char* foo, char* bar)
1267 {
1268         struct cell *t;
1269
1270
1271         if (t_check( p_msg  , 0 )==-1)
1272                 return 1;
1273         t=get_t();
1274         if (t) {
1275                 if (p_msg->REQ_METHOD==METHOD_ACK) {
1276                         LOG(L_WARN, "WARNING: : ACKs transmit_replies not replied\n");
1277                         return -1;
1278                 }
1279                 return t_retransmit_reply( t );
1280         } else
1281                 return -1;
1282 }
1283
1284
1285 inline static int w_t_newtran( struct sip_msg* p_msg, char* foo, char* bar )
1286 {
1287         /* t_newtran returns 0 on error (negative value means
1288            'transaction exists' */
1289         int ret;
1290         ret = t_newtran( p_msg );
1291         if (ret==E_SCRIPT) {
1292                 LOG(L_ERR, "ERROR: t_newtran: "
1293                         "transaction already in process %p\n", get_t() );
1294         }
1295         return ret;
1296 }
1297
1298
1299 inline static int w_t_on_negative( struct sip_msg* msg, char *go_to, char *foo)
1300 {
1301         t_on_negative( (unsigned int )(long) go_to );
1302         return 1;
1303 }
1304
1305 inline static int w_t_on_branch( struct sip_msg* msg, char *go_to, char *foo)
1306 {
1307         t_on_branch( (unsigned int )(long) go_to );
1308         return 1;
1309 }
1310
1311
1312 inline static int w_t_on_reply( struct sip_msg* msg, char *go_to, char *foo )
1313 {
1314         t_on_reply( (unsigned int )(long) go_to );
1315         return 1;
1316 }
1317
1318
1319
1320 inline static int _w_t_relay_to(struct sip_msg  *p_msg ,
1321                                                                         struct proxy_l *proxy, int force_proto)
1322 {
1323         struct cell *t;
1324
1325         if (is_route_type(FAILURE_ROUTE)) {
1326                 t=get_t();
1327                 if (!t || t==T_UNDEFINED) {
1328                         LOG(L_CRIT, "BUG: w_t_relay_to: undefined T\n");
1329                         return -1;
1330                 }
1331                 if (t_forward_nonack(t, p_msg, proxy, force_proto)<=0 ) {
1332                         LOG(L_ERR, "ERROR: w_t_relay_to: t_relay_to failed\n");
1333                         /* let us save the error code, we might need it later
1334                         when the failure_route has finished (Miklos) */
1335                         tm_error=ser_error;
1336                         return -1;
1337                 }
1338                 return 1;
1339         }
1340         if (is_route_type(REQUEST_ROUTE))
1341                 return t_relay_to( p_msg, proxy, force_proto,
1342                         0 /* no replication */ );
1343         LOG(L_CRIT, "ERROR: w_t_relay_to: unsupported route type: %d\n", route_type);
1344         return 0;
1345 }
1346
1347
1348 inline static int w_t_relay_to_udp( struct sip_msg  *p_msg ,
1349                                                                         char *proxy,/* struct proxy_l * expected */
1350                                                                         char *_foo       /* nothing expected */ )
1351 {
1352         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_UDP);
1353 }
1354
1355 /* forward to uri, but force udp as transport */
1356 inline static int w_t_relay_to_udp_uri( struct sip_msg  *p_msg ,
1357                                                                                 char *_foo, char *_bar   )
1358 {
1359         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_UDP);
1360 }
1361
1362
1363 #ifdef USE_TCP
1364 inline static int w_t_relay_to_tcp( struct sip_msg  *p_msg ,
1365                                                                         char *proxy, /* struct proxy_l* */
1366                                                                         char *_foo       /* nothing expected */ )
1367 {
1368         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_TCP);
1369 }
1370
1371 /* forward to uri, but force tcp as transport */
1372 inline static int w_t_relay_to_tcp_uri( struct sip_msg  *p_msg ,
1373                                                                                 char *_foo, char *_bar   )
1374 {
1375         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_TCP);
1376 }
1377 #endif
1378
1379
1380 #ifdef USE_TLS
1381 inline static int w_t_relay_to_tls( struct sip_msg  *p_msg ,
1382                                                                         char *proxy, /* struct proxy_l* expected */
1383                                                                         char *_foo       /* nothing expected */ )
1384 {
1385         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_TLS);
1386 }
1387
1388 /* forward to uri, but force tls as transport */
1389 inline static int w_t_relay_to_tls_uri( struct sip_msg  *p_msg ,
1390                                                                                 char *_foo, char *_bar   )
1391 {
1392         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_TLS);
1393 }
1394 #endif
1395
1396
1397 #ifdef USE_SCTP
1398 inline static int w_t_relay_to_sctp( struct sip_msg  *p_msg ,
1399                                                                         char *proxy, /* struct proxy_l* */
1400                                                                         char *_foo       /* nothing expected */ )
1401 {
1402         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_SCTP);
1403 }
1404
1405 /* forward to uri, but force tcp as transport */
1406 inline static int w_t_relay_to_sctp_uri( struct sip_msg  *p_msg ,
1407                                                                                 char *_foo, char *_bar   )
1408 {
1409         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_SCTP);
1410 }
1411 #endif
1412
1413
1414 inline static int w_t_relay_to_avp( struct sip_msg  *p_msg ,
1415                                                                         char *proto_par, 
1416                                                                         char *addr_par   )
1417 {
1418         struct proxy_l *proxy;
1419         int r = -1;
1420         
1421         proxy = t_protoaddr2proxy(proto_par, addr_par);
1422         if (proxy) {
1423                 r = _w_t_relay_to(p_msg, proxy, PROTO_NONE);
1424                 free_proxy(proxy);
1425         }
1426         return r;
1427 }
1428
1429 inline static int w_t_replicate_uri(struct sip_msg  *msg ,
1430                                 char *uri,       /* sip uri as string or variable */
1431                                 char *_foo       /* nothing expected */ )
1432 {
1433         struct proxy_l *proxy;
1434         struct sip_uri turi;
1435         str suri;
1436         int r = -1;
1437
1438         memset(&turi, 0, sizeof(struct sip_uri));
1439         if(fixup_get_svalue(msg, (gparam_p)uri, &suri)!=0)
1440         {
1441                 LM_ERR("invalid replicate uri parameter");
1442                 return -1;
1443         }
1444         if(parse_uri(suri.s, suri.len, &turi)!=0)
1445         {
1446                 LM_ERR("bad replicate SIP address!\n");
1447                 return -1;
1448         }
1449
1450         proxy=mk_proxy(&turi.host, turi.port_no, turi.proto);
1451         if (proxy==0) {
1452                 LM_ERR("cannot create proxy from URI <%.*s>\n",
1453                         suri.len, suri.s );
1454                 return -1;
1455         }
1456
1457         r = t_replicate(msg, proxy, proxy->proto);
1458         free_proxy(proxy);
1459         return r;
1460
1461 }
1462
1463 inline static int w_t_replicate( struct sip_msg  *p_msg ,
1464         char *proxy, /* struct proxy_l *proxy expected */
1465         char *_foo       /* nothing expected */ )
1466 {
1467         return t_replicate(p_msg, ( struct proxy_l *) proxy, p_msg->rcv.proto );
1468 }
1469
1470 inline static int w_t_replicate_udp( struct sip_msg  *p_msg ,
1471         char *proxy, /* struct proxy_l *proxy expected */
1472         char *_foo       /* nothing expected */ )
1473 {
1474         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_UDP );
1475 }
1476
1477
1478 #ifdef USE_TCP
1479 inline static int w_t_replicate_tcp( struct sip_msg  *p_msg ,
1480         char *proxy, /* struct proxy_l *proxy expected */
1481         char *_foo       /* nothing expected */ )
1482 {
1483         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_TCP );
1484 }
1485 #endif
1486
1487
1488 #ifdef USE_TLS
1489 inline static int w_t_replicate_tls( struct sip_msg  *p_msg ,
1490         char *proxy, /* struct proxy_l *proxy expected */
1491         char *_foo       /* nothing expected */ )
1492 {
1493         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_TLS );
1494 }
1495 #endif
1496
1497
1498 #ifdef USE_SCTP
1499 inline static int w_t_replicate_sctp( struct sip_msg  *p_msg ,
1500         char *proxy, /* struct proxy_l *proxy expected */
1501         char *_foo       /* nothing expected */ )
1502 {
1503         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_SCTP );
1504 }
1505 #endif
1506
1507
1508 inline static int w_t_replicate_to( struct sip_msg  *p_msg ,
1509         char *proto_par, 
1510         char *addr_par   )
1511 {
1512         struct proxy_l *proxy;
1513         int r = -1;
1514         proxy = t_protoaddr2proxy(proto_par, addr_par);
1515         if (proxy) {
1516                 r = t_replicate(p_msg, proxy, proxy->proto);            
1517                 free_proxy(proxy);
1518         }
1519         return r;
1520 }
1521
1522 inline static int w_t_relay( struct sip_msg  *p_msg ,
1523                                                                 char *_foo, char *_bar)
1524 {
1525         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_NONE);
1526 }
1527
1528
1529 /* like t_relay but use the specified destination and port and the same proto
1530  * as the received msg */
1531 static int w_t_relay2( struct sip_msg  *p_msg , char *proxy,
1532                                                                 char *_foo)
1533 {
1534         return _w_t_relay_to(p_msg, (struct proxy_l*) proxy, p_msg->rcv.proto);
1535 }
1536
1537
1538 /* relays CANCEL at the beginning of the script */
1539 inline static int w_t_relay_cancel( struct sip_msg  *p_msg ,
1540                                                 char *_foo, char *_bar)
1541 {
1542         if (p_msg->REQ_METHOD!=METHOD_CANCEL)
1543                 return 1;
1544
1545         /* it makes no sense to use this function without reparse_invite=1 */
1546         if (!cfg_get(tm, tm_cfg, reparse_invite))
1547                 LOG(L_WARN, "WARNING: t_relay_cancel is probably used with "
1548                         "wrong configuration, check the readme for details\n");
1549
1550         return t_relay_cancel(p_msg);
1551 }
1552
1553 /* set fr_inv_timeout & or fr_timeout; 0 means: use the default value */
1554 static int t_set_fr_all(struct sip_msg* msg, char* p1, char* p2)
1555 {
1556     int fr, fr_inv;
1557
1558     if (get_int_fparam(&fr_inv, msg, (fparam_t*)p1) < 0) return -1;
1559     if (p2) {
1560         if (get_int_fparam(&fr, msg, (fparam_t*)p2) < 0) return -1;
1561     } else {
1562         fr = 0;
1563     }
1564
1565     return t_set_fr(msg, fr_inv, fr);
1566 }
1567
1568 static int t_set_fr_inv(struct sip_msg* msg, char* fr_inv, char* foo)
1569 {
1570         return t_set_fr_all(msg, fr_inv, (char*)0);
1571 }
1572
1573 /* reset fr_timer and fr_inv_timer to the default values */
1574 static int w_t_reset_fr(struct sip_msg* msg, char* foo, char* bar)
1575 {
1576         return t_reset_fr();
1577 }
1578
1579 /* set retr. intervals per transaction; 0 means: use the default value */
1580 static int w_t_set_retr(struct sip_msg* msg, char* p1, char* p2)
1581 {
1582         int t1, t2;
1583         
1584         if (get_int_fparam(&t1, msg, (fparam_t*)p1) < 0) return -1;
1585         if (p2) {
1586                 if (get_int_fparam(&t2, msg, (fparam_t*)p2) < 0) return -1;
1587         } else {
1588                 t2 = 0;
1589         }
1590 #ifdef TM_DIFF_RT_TIMEOUT
1591         return t_set_retr(msg, t1, t2);
1592 #else
1593         ERR("w_t_set_retr: support for changing retransmission intervals on "
1594                         "the fly not compiled in (re-compile tm with"
1595                         " -DTM_DIFF_RT_TIMEOUT)\n");
1596         return -1;
1597 #endif
1598 }
1599
1600 /* reset retr. t1 and t2 to the default values */
1601 int w_t_reset_retr(struct sip_msg* msg, char* foo, char* bar)
1602 {
1603 #ifdef TM_DIFF_RT_TIMEOUT
1604         return t_reset_retr();
1605 #else
1606         ERR("w_t_reset_retr: support for changing retransmission intervals on "
1607                         "the fly not compiled in (re-compile tm with"
1608                         " -DTM_DIFF_RT_TIMEOUT)\n");
1609         return -1;
1610 #endif
1611 }
1612
1613 /* set maximum transaction lifetime for inv & noninv */
1614 static int w_t_set_max_lifetime(struct sip_msg* msg, char* p1, char* p2)
1615 {
1616         int t1, t2;
1617         
1618         if (get_int_fparam(&t1, msg, (fparam_t*)p1) < 0) return -1;
1619         if (p2) {
1620                 if (get_int_fparam(&t2, msg, (fparam_t*)p2) < 0) return -1;
1621         } else {
1622                 t2 = 0;
1623         }
1624         return t_set_max_lifetime(msg, t1, t2);
1625 }
1626
1627 /* reset maximum invite/non-invite lifetime to the default value */
1628 int w_t_reset_max_lifetime(struct sip_msg* msg, char* foo, char* bar)
1629 {
1630         return t_reset_max_lifetime();
1631 }
1632
1633
1634
1635 /* helper macro, builds a function for setting a cell flag from the script.
1636    e.g. T_SET_FLAG_GEN_FUNC(t_set_foo, T_FOO) =>
1637    static int t_set_foo(struct sip_msg* msg, char*, char* )
1638    that will expect fparam as first param and will set or reset T_FOO
1639    in the current or next to be created transaction. */
1640 #define T_SET_FLAG_GEN_FUNC(fname, T_FLAG_NAME) \
1641 static int fname(struct sip_msg* msg, char* p1, char* p2) \
1642 { \
1643         int state; \
1644         struct cell* t; \
1645         unsigned int set_flags; \
1646         unsigned int reset_flags; \
1647          \
1648         if (get_int_fparam(&state, msg, (fparam_t*)p1) < 0) return -1; \
1649         t=get_t(); \
1650         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction; \
1651          * in REQUEST_ROUTE T will be set only if the transaction was already  \
1652          * created; if not -> use the static variables */ \
1653         if (!t || t==T_UNDEFINED ){ \
1654                 set_flags=get_msgid_val(user_cell_set_flags, msg->id, int); \
1655                 reset_flags=get_msgid_val(user_cell_reset_flags, msg->id, int); \
1656                 if (state){ \
1657                         /* set */ \
1658                         set_flags|= T_FLAG_NAME; \
1659                         reset_flags&=~T_FLAG_NAME; \
1660                 }else{ \
1661                         /* reset */ \
1662                         set_flags&=~T_FLAG_NAME; \
1663                         reset_flags|=T_FLAG_NAME; \
1664                 } \
1665                 set_msgid_val(user_cell_set_flags, msg->id, int, set_flags); \
1666                 set_msgid_val(user_cell_reset_flags, msg->id, int, reset_flags); \
1667         }else{ \
1668                 if (state) \
1669                         t->flags|=T_FLAG_NAME; \
1670                 else \
1671                         t->flags&=~T_FLAG_NAME; \
1672         } \
1673         return 1; \
1674 }
1675
1676
1677
1678 /* set automatically sending 100 replies on/off for the current or
1679  * next to be created transaction */
1680 T_SET_FLAG_GEN_FUNC(t_set_auto_inv_100, T_AUTO_INV_100)
1681
1682
1683 /* set 6xx handling for the current or next to be created transaction */
1684 T_SET_FLAG_GEN_FUNC(t_set_disable_6xx, T_DISABLE_6xx)
1685
1686
1687 /* disable dns failover for the current transaction */
1688 T_SET_FLAG_GEN_FUNC(t_set_disable_failover, T_DISABLE_FAILOVER)
1689
1690
1691
1692 /* script function, FAILURE_ROUTE only, returns true if the 
1693  * choosed "failure" branch failed because of a timeout, 
1694  * -1 otherwise */
1695 int t_branch_timeout(struct sip_msg* msg, char* foo, char* bar)
1696 {
1697         return (msg->msg_flags & FL_TIMEOUT)?1:-1;
1698 }
1699
1700
1701
1702 /* script function, FAILURE_ROUTE only, returns true if the 
1703  * choosed "failure" branch ever received a reply, -1 otherwise */
1704 int t_branch_replied(struct sip_msg* msg, char* foo, char* bar)
1705 {
1706         return (msg->msg_flags & FL_REPLIED)?1:-1;
1707 }
1708
1709
1710
1711 /* script function, returns: 1 if the transaction was canceled, -1 if not */
1712 int t_is_canceled(struct sip_msg* msg, char* foo, char* bar)
1713 {
1714         struct cell *t;
1715         int ret;
1716         
1717         
1718         if (t_check( msg , 0 )==-1) return -1;
1719         t=get_t();
1720         if ((t==0) || (t==T_UNDEFINED)){
1721                 LOG(L_ERR, "ERROR: t_is_canceled: cannot check a message "
1722                         "for which no T-state has been established\n");
1723                 ret=-1;
1724         }else{
1725                 ret=(t->flags & T_CANCELED)?1:-1;
1726         }
1727         return ret;
1728 }
1729
1730 /* script function, returns: 1 if the transaction lifetime interval has already elapsed, -1 if not */
1731 int t_is_expired(struct sip_msg* msg, char* foo, char* bar)
1732 {
1733         struct cell *t;
1734         int ret;
1735         
1736         
1737         if (t_check( msg , 0 )==-1) return -1;
1738         t=get_t();
1739         if ((t==0) || (t==T_UNDEFINED)){
1740                 LOG(L_ERR, "ERROR: t_is_expired: cannot check a message "
1741                         "for which no T-state has been established\n");
1742                 ret=-1;
1743         }else{
1744                 ret=(TICKS_GT(t->end_of_life, get_ticks_raw()))?-1:1;
1745         }
1746         return ret;
1747 }
1748
1749 /* script function, returns: 1 if any of the branches did timeout, -1 if not */
1750 int t_any_timeout(struct sip_msg* msg, char* foo, char* bar)
1751 {
1752         struct cell *t;
1753         int r;
1754         
1755         if (t_check( msg , 0 )==-1) return -1;
1756         t=get_t();
1757         if ((t==0) || (t==T_UNDEFINED)){
1758                 LOG(L_ERR, "ERROR: t_any_timeout: cannot check a message "
1759                         "for which no T-state has been established\n");
1760                 return -1;
1761         }else{
1762                 for (r=0; r<t->nr_of_outgoings; r++){
1763                         if (t->uac[r].request.flags & F_RB_TIMEOUT)
1764                                 return 1;
1765                 }
1766         }
1767         return -1;
1768 }
1769
1770
1771
1772 /* script function, returns: 1 if any of the branches received at leat one
1773  * reply, -1 if not */
1774 int t_any_replied(struct sip_msg* msg, char* foo, char* bar)
1775 {
1776         struct cell *t;
1777         int r;
1778         
1779         if (t_check( msg , 0 )==-1) return -1;
1780         t=get_t();
1781         if ((t==0) || (t==T_UNDEFINED)){
1782                 LOG(L_ERR, "ERROR: t_any_replied: cannot check a message "
1783                         "for which no T-state has been established\n");
1784                 return -1;
1785         }else{
1786                 for (r=0; r<t->nr_of_outgoings; r++){
1787                         if (t->uac[r].request.flags & F_RB_REPLIED)
1788                                 return 1;
1789                 }
1790         }
1791         return -1;
1792 }
1793
1794
1795
1796 /* script function, returns: 1 if any of the branches received the
1797  *  reply code "status" */
1798 int t_grep_status(struct sip_msg* msg, char* status, char* bar)
1799 {
1800         struct cell *t;
1801         int r;
1802         int code;
1803         
1804     if (get_int_fparam(&code, msg, (fparam_t*)status) < 0) return -1;
1805         if (t_check( msg , 0 )==-1) return -1;
1806         t=get_t();
1807         if ((t==0) || (t==T_UNDEFINED)){
1808                 LOG(L_ERR, "ERROR: t_any_replied: cannot check a message "
1809                         "for which no T-state has been established\n");
1810                 return -1;
1811         }else{
1812                 for (r=0; r<t->nr_of_outgoings; r++){
1813                         if ((t->uac[r].last_received==code)  && 
1814                                         (t->uac[r].request.flags & F_RB_REPLIED))
1815                                 return 1;
1816                 }
1817         }
1818         return -1;
1819 }
1820
1821 /* drop all the existing replies in failure_route to make sure
1822  * that none of them is picked up again */
1823 static int w_t_drop_replies(struct sip_msg* msg, char* foo, char* bar)
1824 {
1825         if(foo==NULL)
1826                 t_drop_replies(1);
1827         else if(*foo=='n')
1828                 t_drop_replies(0);
1829         else if(*foo=='l')
1830                 t_drop_replies(2);
1831         else
1832                 t_drop_replies(1);
1833         return 1;
1834 }
1835
1836 /* save the message lumps after t_newtran() but before t_relay() */
1837 static int w_t_save_lumps(struct sip_msg* msg, char* foo, char* bar)
1838 {
1839 #ifdef POSTPONE_MSG_CLONING
1840         struct cell *t;
1841
1842         t=get_t();
1843         if (!t || t==T_UNDEFINED) {
1844                 LOG(L_ERR, "ERROR: w_t_save_lumps: transaction has not been created yet\n");
1845                 return -1;
1846         }
1847
1848         if (save_msg_lumps(t->uas.request, msg)) {
1849                 LOG(L_ERR, "ERROR: w_t_save_lumps: "
1850                         "failed to save the message lumps\n");
1851                 return -1;
1852         }
1853         return 1;
1854 #else
1855         LOG(L_ERR, "ERROR: w_t_save_lumps: POSTPONE_MSG_CLONING is not defined,"
1856                         " thus, the functionality is not supported\n");
1857         return -1;
1858 #endif
1859 }
1860
1861 static rpc_export_t tm_rpc[] = {
1862         {"tm.cancel", rpc_cancel,   rpc_cancel_doc,   0},
1863         {"tm.reply",  rpc_reply,    rpc_reply_doc,    0},
1864         {"tm.stats",  tm_rpc_stats, tm_rpc_stats_doc, 0},
1865         {"tm.hash_stats",  tm_rpc_hash_stats, tm_rpc_hash_stats_doc, 0},
1866         {"tm.t_uac_start", rpc_t_uac_start, rpc_t_uac_start_doc, 0 },
1867         {"tm.t_uac_wait",  rpc_t_uac_wait,  rpc_t_uac_wait_doc, RET_ARRAY},
1868         {0, 0, 0, 0}
1869 };
1870
1871 /* wrapper function needed after changes in w_t_reply */
1872 int w_t_reply_wrp(struct sip_msg *m, unsigned int code, char *txt)
1873 {
1874         fparam_t c;
1875         fparam_t r;
1876         
1877         c.type = FPARAM_INT;
1878         c.orig = NULL; /* ? */
1879         c.v.i = code;
1880         
1881         r.type = FPARAM_STRING;
1882         r.orig = NULL; /* ? */
1883         r.v.asciiz = txt;
1884
1885         return w_t_reply(m, (char *)&c, (char*)&r);
1886 }
1887
1888
1889
1890 /** script function, check if a msg is assoc. to a transaction.
1891  * @return -1 (not), 1 (reply, e2e ack or cancel for an existing transaction),
1892  *          0 (request retransmission, ack to negative reply or ack to local
1893  *           transaction)
1894  * Note: the e2e ack matching works only for local e2e acks or for
1895  *       transactions with E2EACK* callbacks installed (but even in this
1896  *       case matching E2EACKs on proxied transaction is not entirely
1897  *       reliable: if the ACK  is delayed the proxied transaction might
1898  *       be already deleted when it reaches the proxy (wait_timeout))
1899  */
1900 static int t_check_trans(struct sip_msg* msg, char* foo, char* bar)
1901 {
1902         struct cell* t;
1903         
1904         if (msg->first_line.type==SIP_REPLY)
1905                 return w_t_check(msg, 0 ,0);
1906         else if (msg->REQ_METHOD==METHOD_CANCEL)
1907                 return w_t_lookup_cancel(msg, 0, 0);
1908         else{
1909                 switch(t_check_msg(msg, 0)){
1910                         case -2: /* possible e2e ack */
1911                                 return 1;
1912                         case 1: /* found */
1913                                 t=get_t();
1914                                 if (msg->REQ_METHOD==METHOD_ACK){
1915                                         /* ack to neg. reply  or ack to local trans.
1916                                            => process it and end the script */
1917                                         /* FIXME: there's no way to distinguish here 
1918                                            between acks to local trans. and neg. acks */
1919                                         if (unlikely(has_tran_tmcbs(t, TMCB_ACK_NEG_IN)))
1920                                                 run_trans_callbacks(TMCB_ACK_NEG_IN, t, msg,
1921                                                                                         0, msg->REQ_METHOD);
1922                                         t_release_transaction(t);
1923                                 } else {
1924                                         /* is a retransmission */
1925                                         if (unlikely(has_tran_tmcbs(t, TMCB_REQ_RETR_IN)))
1926                                                 run_trans_callbacks(TMCB_REQ_RETR_IN, t, msg,
1927                                                                                         0, msg->REQ_METHOD);
1928                                         t_retransmit_reply(t);
1929                                 }
1930                                 /* no need for UNREF(t); set_t(0) - the end-of-script
1931                                    t_unref callback will take care of them */
1932                                 return 0; /* return from the script */
1933                 }
1934                 /* not found or error */
1935         }
1936         return -1;
1937 }
1938
1939 static int hexatoi(str *s, unsigned int* result)
1940 {
1941         int i, xv, fact;
1942
1943         /* more than 32bit hexa? */
1944         if (s->len>8)
1945                 return -1;
1946
1947         *result = 0;
1948         fact = 1;
1949
1950         for(i=s->len-1; i>=0 ;i--)
1951         {
1952                 xv = hex2int(s->s[i]);
1953                 if(xv<0)
1954                         return -1;
1955
1956                 *result += (xv * fact);
1957                 fact *= 16;
1958         }
1959         return 0;
1960 }
1961
1962 static int fixup_t_relay_to(void** param, int param_no)
1963 {
1964
1965         int port;
1966         int proto;
1967         unsigned int flags;
1968         struct proxy_l *proxy;
1969         action_u_t *a;
1970         str s;
1971         str host;
1972
1973         s.s = (char*)*param;
1974         s.len = strlen(s.s);
1975         LM_DBG("fixing (%s, %d)\n", s.s, param_no);
1976         if (param_no==1){
1977                 a = fixup_get_param(param, param_no, 2);
1978                 if(a==NULL)
1979                 {
1980                         LM_CRIT("server error for parameter <%s>\n",s.s);
1981                         return E_UNSPEC;
1982                 }
1983                 if(a->u.string!=NULL) {
1984                         /* second parameter set, first should be proxy addr */
1985                         if (parse_phostport(s.s, &host.s, &host.len, &port, &proto)!=0){
1986                                 LM_CRIT("invalid proxy addr parameter <%s>\n",s.s);
1987                                 return E_UNSPEC;
1988                         }
1989
1990                         proxy = mk_proxy(&host, port, proto);
1991                         if (proxy==0) {
1992                                 LM_ERR("failed to build proxy structure for <%.*s>\n", host.len, host.s );
1993                                 return E_UNSPEC;
1994                         }
1995                         *(param)=proxy;
1996                         return 0;
1997                 } else {
1998                         /* no second parameter, then is proxy addr or flags */
1999                         flags = 0;
2000                         if (s.len>2 && s.s[0]=='0' && s.s[1]=='x') {
2001                                 s.s += 2;
2002                                 s.len -= 2;
2003                                 if(hexatoi(&s, &flags)<0)
2004                                 {
2005                                         LM_CRIT("invalid hexa flags <%s>\n", s.s);
2006                                         return E_UNSPEC;
2007                                 }
2008                                 a->u.data = (void*)(unsigned long int)flags;
2009                                 *(param)= 0;
2010                                 return 0;
2011                         } else {
2012                                 if(str2int(&s, &flags)==0)
2013                                 {
2014                                         a->u.data = (void*)(unsigned long int)flags;
2015                                         *(param)= 0;
2016                                         return 0;
2017                                 } else {
2018                                         /* try proxy */
2019                                         if (parse_phostport(s.s, &host.s, &host.len, &port, &proto)!=0){
2020                                                 LM_CRIT("invalid proxy addr parameter <%s>\n",s.s);
2021                                                 return E_UNSPEC;
2022                                         }
2023
2024                                         proxy = mk_proxy(&host, port, proto);
2025                                         if (proxy==0) {
2026                                                 LM_ERR("failed to build proxy structure for <%.*s>\n", host.len, host.s );
2027                                                 return E_UNSPEC;
2028                                         }
2029                                         *(param)=proxy;
2030                                         return 0;
2031                                 }
2032                         }
2033                 }
2034         } else if (param_no==2) {
2035                 /* flags */
2036                 flags = 0;
2037                 if (s.len>2 && s.s[0]=='0' && s.s[1]=='x') {
2038                         s.s += 2;
2039                         s.len -= 2;
2040                         if(hexatoi(&s, &flags)<0)
2041                         {
2042                                 LM_CRIT("invalid hexa flags <%s>\n", s.s);
2043                                 return E_UNSPEC;
2044                         }
2045                         *(param) = (void*)(unsigned long int)flags;
2046                         return 0;
2047                 } else {
2048                         if(str2int(&s, &flags)==0)
2049                         {
2050                                 *(param) = (void*)(unsigned long int)flags;
2051                                 return 0;
2052                         } else {
2053                                 LM_CRIT("invalid flags <%s>\n", s.s);
2054                                 return E_UNSPEC;
2055                         }
2056                 }
2057         } else {
2058                 LM_ERR("invalid parameter number %d\n", param_no);
2059                 return E_BUG;
2060         }
2061 }
2062
2063
2064 inline static int w_t_relay_to(struct sip_msg *msg, char *proxy, char *flags)
2065 {
2066         unsigned int fl;
2067         struct proxy_l *px;
2068         fparam_t param;
2069
2070         fl = (unsigned int)(long)(void*)flags;
2071         px = (struct proxy_l*)proxy;
2072
2073         if(flags!=0)
2074         {
2075                 memset(&param, 0, sizeof(fparam_t));
2076                 param.type = FPARAM_INT;
2077                 /* no auto 100 trying */
2078                 if(fl&1) {
2079                         param.v.i = 0;
2080                         t_set_auto_inv_100(msg, (char*)(&param), 0);
2081                 }
2082                 /* no auto negative reply - not implemented */
2083                 /*
2084                 if(fl&2) {
2085                         param.v.i = 1;
2086                         t_set_disable_internal_reply(msg, (char*)param, 0);
2087                 }
2088                 */
2089                 /* no dns failover */
2090                 if(fl&4) {
2091                         param.v.i = 1;
2092                         t_set_disable_failover(msg, (char*)(&param), 0);
2093                 }
2094         }
2095         return _w_t_relay_to(msg, px, PROTO_NONE);
2096 }
2097