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                 if(strlen((char*)*param)<=1
593                                 && (*(char*)(*param)==0 || *(char*)(*param)=='0')) {
594                         *param = (void*)0;
595                         return 0;
596                 }
597                 return fixup_routes("t_on_failure", &failure_rt, param);
598         }
599         return 0;
600 }
601
602
603
604 static int fixup_on_reply(void** param, int param_no)
605 {
606         if (param_no==1){
607                 if(strlen((char*)*param)<=1
608                                 && (*(char*)(*param)==0 || *(char*)(*param)=='0')) {
609                         *param = (void*)0;
610                         return 0;
611                 }
612                 return fixup_routes("t_on_reply", &onreply_rt, param);
613         }
614         return 0;
615 }
616
617
618
619 static int fixup_on_branch(void** param, int param_no)
620 {
621         if (param_no==1){
622                 if(strlen((char*)*param)<=1
623                                 && (*(char*)(*param)==0 || *(char*)(*param)=='0')) {
624                         *param = (void*)0;
625                         return 0;
626                 }
627                 return fixup_routes("t_on_branch", &branch_rt, param);
628         }
629         return 0;
630 }
631
632 static int fixup_on_sl_reply(modparam_t type, void* val)
633 {
634         if ((type & PARAM_STRING) == 0) {
635                 LOG(L_ERR, "ERROR: tm: fixup_on_sl_reply: not a string parameter\n");
636                 return -1;
637         }
638
639         if (fixup_routes(0, &onreply_rt, &val))
640                 return -1;
641
642         goto_on_sl_reply = (int)(long)val;
643         return 0;
644 }
645
646
647
648 /* (char *hostname, char *port_nr) ==> (struct proxy_l *, -)  */
649 static int fixup_hostport2proxy(void** param, int param_no)
650 {
651         unsigned int port;
652         char *host;
653         int err;
654         struct proxy_l *proxy;
655         action_u_t *a;
656         str s;
657
658         DBG("TM module: fixup_hostport2proxy(%s, %d)\n", (char*)*param, param_no);
659         if (param_no==1){
660                 return 0;
661         } else if (param_no==2) {
662                 a = fixup_get_param(param, param_no, 1);
663                 host= a->u.string;
664                 port=str2s(*param, strlen(*param), &err);
665                 if (err!=0) {
666                         LOG(L_ERR, "TM module:fixup_hostport2proxy: bad port number <%s>\n",
667                                 (char*)(*param));
668                          return E_UNSPEC;
669                 }
670                 s.s = host;
671                 s.len = strlen(host);
672                 proxy=mk_proxy(&s, port, 0); /* FIXME: udp or tcp? */
673                 if (proxy==0) {
674                         LOG(L_ERR, "ERROR: fixup_hostport2proxy: bad host name in URI <%s>\n",
675                                 host );
676                         return E_BAD_ADDRESS;
677                 }
678                 /* success -- fix the first parameter to proxy now ! */
679
680                 a->u.data=proxy;
681                 return 0;
682         } else {
683                 LOG(L_ERR,"ERROR: fixup_hostport2proxy called with parameter #<>{1,2}\n");
684                 return E_BUG;
685         }
686 }
687
688 /* (char *$proto, char *$host:port) ==> (fparam, fparam)  */
689 static int fixup_proto_hostport2proxy(void** param, int param_no) {
690         int ret;
691
692         ret = fix_param(FPARAM_AVP, param);
693         if (ret <= 0) return ret;
694 /*      if (param_no = 1) {             FIXME: param_str currently does not offer INT/STR overloading
695                 ret = fix_param(FPARAM_INT, param);
696                 if (ret <= 0) return ret;
697         } */
698         if (fix_param(FPARAM_STRING, param) != 0) return -1;
699         return 0;
700 }
701
702
703 static int fixup_t_check_status(void** param, int param_no)
704 {
705         int ret;
706
707         ret = fix_param(FPARAM_AVP, param);
708         if (ret <= 0) return ret;
709
710         ret = fix_param(FPARAM_SELECT, param);
711         if (ret <= 0) return ret;
712
713         if (fix_param(FPARAM_REGEX, param) != 0) return -1;
714         return 0;
715 }
716
717
718 /***************************** init functions *****************************/
719 static int w_t_unref( struct sip_msg *foo, unsigned int flags, void *bar)
720 {
721         return t_unref(foo);
722 }
723
724
725 static int script_init( struct sip_msg *foo, unsigned int flags, void *bar)
726 {
727         /* we primarily reset all private memory here to make sure
728          * private values left over from previous message will
729          * not be used again */
730
731         /* make sure the new message will not inherit previous
732                 message's t_on_negative value
733         */
734         t_on_negative( 0 );
735         t_on_reply(0);
736         t_on_branch(0);
737         /* reset the kr status */
738         reset_kr(0);
739         /* set request mode so that multiple-mode actions know
740          * how to behave */
741         set_route_type(REQUEST_ROUTE);
742
743 #ifdef POSTPONE_MSG_CLONING
744         lumps_are_cloned = 0;
745 #endif
746         return 1;
747 }
748
749
750 static int mod_init(void)
751 {
752         DBG( "TM - (sizeof cell=%ld, sip_msg=%ld) initializing...\n",
753                         (long)sizeof(struct cell), (long)sizeof(struct sip_msg));
754
755         /* checking if we have sufficient bitmap capacity for given
756            maximum number of  branches */
757         if (MAX_BRANCHES+1>31) {
758                 LOG(L_CRIT, "Too many max UACs for UAC branch_bm_t bitmap: %d\n",
759                         MAX_BRANCHES );
760                 return -1;
761         }
762
763         if (init_callid() < 0) {
764                 LOG(L_CRIT, "Error while initializing Call-ID generator\n");
765                 return -1;
766         }
767
768         /* building the hash table*/
769         if (!init_hash_table()) {
770                 LOG(L_ERR, "ERROR: mod_init: initializing hash_table failed\n");
771                 return -1;
772         }
773
774         /* init static hidden values */
775         init_t();
776
777         if (tm_init_selects()==-1) {
778                 LOG(L_ERR, "ERROR: mod_init: select init failed\n");
779                 return -1;
780         }
781
782         /* the default timer values must be fixed-up before
783          * declaring the configuration (Miklos) */
784         if (tm_init_timers()==-1) {
785                 LOG(L_ERR, "ERROR: mod_init: timer init failed\n");
786                 return -1;
787         }
788         
789         /* the cancel branch flags must be fixed before declaring the 
790          * configuration */
791         if (cancel_b_flags_get(&default_tm_cfg.cancel_b_flags, 
792                                                         default_tm_cfg.cancel_b_flags)<0){
793                 LOG(L_ERR, "ERROR: mod_init: bad cancel branch method\n");
794                 return -1;
795         }
796
797 #ifdef USE_DNS_FAILOVER
798         if (default_tm_cfg.reparse_on_dns_failover && mhomed) {
799                 LOG(L_WARN, "WARNING: mod_init: "
800                         "reparse_on_dns_failover is enabled on a "
801                         "multihomed host -- check the readme of tm module!\n");
802         }
803 #endif
804
805         /* declare the configuration */
806         if (cfg_declare("tm", tm_cfg_def, &default_tm_cfg, cfg_sizeof(tm),
807                          &tm_cfg)) {
808                 LOG(L_ERR, "ERROR: mod_init: failed to declare the configuration\n");
809                 return -1;
810         }
811
812              /* First tm_stat initialization function only allocates the top level stat
813               * structure in shared memory, the initialization will complete in child
814               * init with init_tm_stats_child when the final value of estimated_process_count is
815               * known
816               */
817         if (init_tm_stats() < 0) {
818                 LOG(L_CRIT, "ERROR: mod_init: failed to init stats\n");
819                 return -1;
820         }
821
822         if (uac_init()==-1) {
823                 LOG(L_ERR, "ERROR: mod_init: uac_init failed\n");
824                 return -1;
825         }
826
827         if (init_tmcb_lists()!=1) {
828                 LOG(L_CRIT, "ERROR:tm:mod_init: failed to init tmcb lists\n");
829                 return -1;
830         }
831         
832         tm_init_tags();
833         init_twrite_lines();
834         if (init_twrite_sock() < 0) {
835                 LOG(L_ERR, "ERROR:tm:mod_init: Unable to create socket\n");
836                 return -1;
837         }
838
839         /* register post-script clean-up function */
840         if (register_script_cb( w_t_unref, POST_SCRIPT_CB|REQUEST_CB, 0)<0 ) {
841                 LOG(L_ERR,"ERROR:tm:mod_init: failed to register POST request "
842                         "callback\n");
843                 return -1;
844         }
845         if (register_script_cb( script_init, PRE_SCRIPT_CB|REQUEST_CB , 0)<0 ) {
846                 LOG(L_ERR,"ERROR:tm:mod_init: failed to register PRE request "
847                         "callback\n");
848                 return -1;
849         }
850
851         if (init_avp_params( fr_timer_param, fr_inv_timer_param,
852                                                  contacts_avp_param)<0 ){
853                 LOG(L_ERR,"ERROR:tm:mod_init: failed to process AVP params\n");
854                 return -1;
855         }
856 #ifdef WITH_EVENT_LOCAL_REQUEST
857         goto_on_local_req=route_lookup(&event_rt, "tm:local-request");
858         if (goto_on_local_req>=0 && event_rt.rlist[goto_on_local_req]==0)
859                 goto_on_local_req=-1; /* disable */
860 #endif /* WITH_EVENT_LOCAL_REQUEST */
861         if (goto_on_sl_reply && onreply_rt.rlist[goto_on_sl_reply]==0)
862                 WARN("empty/non existing on_sl_reply route\n");
863         tm_init = 1;
864         return 0;
865 }
866
867 static int child_init(int rank)
868 {
869         if (rank == PROC_INIT) {
870                 /* we must init stats when rank==PROC_INIT: after mod_init we know
871                  * the exact number of processes and we must init the shared structure
872                  * before any other process is starting (or else some new process
873                  * might try to use the stats before the stats array is allocated) */
874                 if (init_tm_stats_child() < 0) {
875                         ERR("Error while initializing tm statistics structures\n");
876                         return -1;
877                 }
878         }else if (child_init_callid(rank) < 0) { 
879                 /* don't init callid for PROC_INIT*/
880                 LOG(L_ERR, "ERROR: child_init: Error while initializing Call-ID"
881                                 " generator\n");
882                 return -2;
883         }
884         return 0;
885 }
886
887
888
889
890
891 /**************************** wrapper functions ***************************/
892 static int t_check_status(struct sip_msg* msg, char *p1, char *foo)
893 {
894         regmatch_t pmatch;
895         struct cell *t;
896         char *status, *s = NULL;
897         char backup;
898         int lowest_status, n, ret;
899         fparam_t* fp;
900         regex_t* re = NULL;
901         str tmp;
902         
903         fp = (fparam_t*)p1;
904         
905         /* first get the transaction */
906         if (t_check(msg, 0 ) == -1) return -1;
907         if ((t = get_t()) == 0) {
908                 LOG(L_ERR, "ERROR: t_check_status: cannot check status for a reply "
909                         "which has no T-state established\n");
910                 goto error;
911         }
912         backup = 0;
913         
914         switch(fp->type) {
915         case FPARAM_REGEX:
916                 re = fp->v.regex;
917                 break;
918                 
919         default:
920                 /* AVP or select, get the value and compile the regex */
921                 if (get_str_fparam(&tmp, msg, fp) < 0) goto error;
922                 s = pkg_malloc(tmp.len + 1);
923                 if (s == NULL) {
924                         ERR("Out of memory\n");
925                         goto error;
926                 }
927                 memcpy(s, tmp.s, tmp.len);
928                 s[tmp.len] = '\0';
929                 
930                 if ((re = pkg_malloc(sizeof(regex_t))) == 0) {
931                         ERR("No memory left\n");
932                         goto error;
933                 }
934                 
935                 if (regcomp(re, s, REG_EXTENDED|REG_ICASE|REG_NEWLINE)) {
936                         ERR("Bad regular expression '%s'\n", s);
937                         goto error;
938                 }
939                 break;
940         }
941         
942         switch(route_type) {
943         case REQUEST_ROUTE:
944                 /* use the status of the last sent reply */
945                 status = int2str( t->uas.status, 0);
946                 break;
947                 
948         case ONREPLY_ROUTE:
949                 /* use the status of the current reply */
950                 status = msg->first_line.u.reply.status.s;
951                 backup = status[msg->first_line.u.reply.status.len];
952                 status[msg->first_line.u.reply.status.len] = 0;
953                 break;
954
955         case FAILURE_ROUTE:
956                 /* use the status of the winning reply */
957                 ret = t_pick_branch( -1, 0, t, &lowest_status);
958                 if (ret == -1) {
959                         /* t_pick_branch() retuns error also when there are only
960                          * blind UACs. Let us give it another chance including the
961                          * blind branches. */
962                         LOG(L_DBG, "DEBUG: t_check_status: t_pick_branch returned error, "
963                                 "trying t_pick_branch_blind\n");
964                         ret = t_pick_branch_blind(t, &lowest_status);
965                 }
966                 if (ret < 0) {
967                         LOG(L_CRIT,"BUG:t_check_status: t_pick_branch failed to get "
968                                 " a final response in FAILURE_ROUTE\n");
969                         goto error;
970                 }
971                 status = int2str( lowest_status , 0);
972                 break;
973
974         default:
975                 LOG(L_ERR,"ERROR:t_check_status: unsupported route type %d\n",route_type);
976                 goto error;
977         }
978
979         DBG("DEBUG:t_check_status: checked status is <%s>\n",status);
980         /* do the checking */
981         n = regexec(re, status, 1, &pmatch, 0);
982
983         if (backup) status[msg->first_line.u.reply.status.len] = backup;
984         if (s) pkg_free(s);
985         if ((fp->type != FPARAM_REGEX) && re) {
986                 regfree(re);
987                 pkg_free(re);
988         }
989
990         if (n!=0) return -1;
991         return 1;
992
993  error:
994         if (s) pkg_free(s);
995         if ((fp->type != FPARAM_REGEX) && re) {
996                 regfree(re);
997                 pkg_free(re);
998         }
999         return -1;
1000 }
1001
1002
1003 inline static int w_t_check(struct sip_msg* msg, char* str, char* str2)
1004 {
1005         return (t_check_msg( msg , 0  )==1) ? 1 : -1;
1006 }
1007
1008 inline static int w_t_lookup_cancel(struct sip_msg* msg, char* str, char* str2)
1009 {
1010         struct cell *ret;
1011         int i=0;
1012         if (msg->REQ_METHOD==METHOD_CANCEL) {
1013                 ret = t_lookupOriginalT( msg );
1014                 DBG("lookup_original: t_lookupOriginalT returned: %p\n", ret);
1015                 if (ret != T_NULL_CELL) {
1016                         /* If the parameter is set to 1, overwrite the message flags of
1017                          * the CANCEL with the flags of the INVITE */
1018                         if (str && (get_int_fparam(&i, msg, (fparam_t*)str)==0) && i)
1019                                 msg->flags = ret->uas.request->flags;
1020
1021                         /* The cell is reffed by t_lookupOriginalT, but T is not set.
1022                         So we must unref it before returning. */
1023                         UNREF(ret);
1024                         return 1;
1025                 }
1026         } else {
1027                 LOG(L_WARN, "WARNING: script error t_lookup_cancel() called for non-CANCEL request\n");
1028         }
1029         return -1;
1030 }
1031
1032 inline static int str2proto(char *s, int len) {
1033         if (len == 3 && !strncasecmp(s, "udp", 3))
1034                 return PROTO_UDP;
1035         else if (len == 3 && !strncasecmp(s, "tcp", 3))  /* tcp&tls checks will be passed in getproto() */
1036                 return PROTO_TCP;
1037         else if (len == 3 && !strncasecmp(s, "tls", 3))
1038                 return PROTO_TLS;       
1039         else if (len == 4 && !strncasecmp(s, "sctp", 4))
1040                 return PROTO_SCTP;
1041         else
1042                 return PROTO_NONE;
1043 }
1044
1045 inline static struct proxy_l* t_protoaddr2proxy(char *proto_par, char *addr_par) {
1046         struct proxy_l *proxy = 0;
1047         avp_t* avp;
1048         avp_value_t val;
1049         int proto, port, err;
1050         str s;
1051         char *c;
1052         
1053         switch(((fparam_t *)proto_par)->type) {
1054         case FPARAM_AVP:
1055                 if (!(avp = search_first_avp(((fparam_t *)proto_par)->v.avp.flags, ((fparam_t *)proto_par)->v.avp.name, &val, 0))) {
1056                         proto = PROTO_NONE;
1057                 } else {
1058                         if (avp->flags & AVP_VAL_STR) {
1059                                 proto = str2proto(val.s.s, val.s.len);
1060                         }
1061                         else {
1062                                 proto = val.n;
1063                         }
1064                 }
1065                 break;
1066
1067         case FPARAM_INT:
1068                 proto = ((fparam_t *)proto_par)->v.i;
1069                 break;
1070         case FPARAM_STRING:
1071                 proto = str2proto( ((fparam_t *)proto_par)->v.asciiz, strlen(((fparam_t *)proto_par)->v.asciiz));
1072                 break;
1073         default:
1074                 ERR("BUG: Invalid proto parameter value in t_protoaddr2proxy\n");
1075                 return 0;
1076         }
1077
1078
1079         switch(((fparam_t *)addr_par)->type) {
1080         case FPARAM_AVP:
1081                 if (!(avp = search_first_avp(((fparam_t *)addr_par)->v.avp.flags, ((fparam_t *)addr_par)->v.avp.name, &val, 0))) {
1082                         s.len = 0;
1083                 } else {
1084                         if ((avp->flags & AVP_VAL_STR) == 0) {
1085                                 LOG(L_ERR, "tm:t_protoaddr2proxy: avp <%.*s> value is not string\n",
1086                                         ((fparam_t *)addr_par)->v.avp.name.s.len, ((fparam_t *)addr_par)->v.avp.name.s.s);
1087                                 return 0;
1088                         }
1089                         s = val.s;
1090                 }
1091                 break;
1092
1093         case FPARAM_STRING:
1094                 s.s = ((fparam_t *) addr_par)->v.asciiz;
1095                 s.len = strlen(s.s);
1096                 break;
1097
1098         default:
1099                 ERR("BUG: Invalid addr parameter value in t_protoaddr2proxy\n");
1100                 return 0;
1101         }
1102
1103         port = 5060;
1104         if (s.len) {
1105                 c = memchr(s.s, ':', s.len);
1106                 if (c) {
1107                         port = str2s(c+1, s.len-(c-s.s+1), &err);
1108                         if (err!=0) {
1109                                 LOG(L_ERR, "tm:t_protoaddr2proxy: bad port number <%.*s>\n",
1110                                         s.len, s.s);
1111                                  return 0;
1112                         }
1113                         s.len = c-s.s;
1114                 }
1115         }
1116         if (!s.len) {
1117                 LOG(L_ERR, "tm: protoaddr2proxy: host name is empty\n");
1118                 return 0;
1119         }
1120         proxy=mk_proxy(&s, port, proto);
1121         if (proxy==0) {
1122                 LOG(L_ERR, "tm: protoaddr2proxy: bad host name in URI <%.*s>\n",
1123                         s.len, s.s );
1124                 return 0;
1125         }
1126         return proxy;
1127 }
1128
1129 inline static int _w_t_forward_nonack(struct sip_msg* msg, struct proxy_l* proxy,
1130         int proto)
1131 {
1132         struct cell *t;
1133         if (t_check( msg , 0 )==-1) {
1134                 LOG(L_ERR, "ERROR: forward_nonack: "
1135                                 "can't forward when no transaction was set up\n");
1136                 return -1;
1137         }
1138         t=get_t();
1139         if ( t && t!=T_UNDEFINED ) {
1140                 if (msg->REQ_METHOD==METHOD_ACK) {
1141                         LOG(L_WARN,"WARNING: you don't really want to fwd hbh ACK\n");
1142                         return -1;
1143                 }
1144                 return t_forward_nonack(t, msg, proxy, proto );
1145         } else {
1146                 DBG("DEBUG: forward_nonack: no transaction found\n");
1147                 return -1;
1148         }
1149 }
1150
1151
1152 inline static int w_t_forward_nonack( struct sip_msg* msg, char* proxy,
1153                                                                                 char* foo)
1154 {
1155         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_NONE);
1156 }
1157
1158
1159 inline static int w_t_forward_nonack_uri(struct sip_msg* msg, char *foo,
1160                                                                                                                                         char *bar)
1161 {
1162         return _w_t_forward_nonack(msg, 0, PROTO_NONE);
1163 }
1164
1165
1166 inline static int w_t_forward_nonack_udp( struct sip_msg* msg, char* proxy,
1167                                                                                 char* foo)
1168 {
1169         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_UDP);
1170 }
1171
1172
1173 #ifdef USE_TCP
1174 inline static int w_t_forward_nonack_tcp( struct sip_msg* msg, char* proxy,
1175                                                                                 char* foo)
1176 {
1177         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_TCP);
1178 }
1179 #endif
1180
1181
1182 #ifdef USE_TLS
1183 inline static int w_t_forward_nonack_tls( struct sip_msg* msg, char* proxy,
1184                                                                                 char* foo)
1185 {
1186         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_TLS);
1187 }
1188 #endif
1189
1190
1191 #ifdef USE_SCTP
1192 inline static int w_t_forward_nonack_sctp( struct sip_msg* msg, char* proxy,
1193                                                                                 char* foo)
1194 {
1195         return _w_t_forward_nonack(msg, ( struct proxy_l *) proxy, PROTO_SCTP);
1196 }
1197 #endif
1198
1199
1200 inline static int w_t_forward_nonack_to( struct sip_msg  *p_msg ,
1201         char *proto_par, 
1202         char *addr_par   )
1203 {
1204         struct proxy_l *proxy;
1205         int r = -1;
1206         proxy = t_protoaddr2proxy(proto_par, addr_par);
1207         if (proxy) {
1208                 r = _w_t_forward_nonack(p_msg, proxy, proxy->proto);            
1209                 free_proxy(proxy);
1210         }
1211         return r;
1212 }
1213
1214
1215 inline static int w_t_reply(struct sip_msg* msg, char* p1, char* p2)
1216 {
1217         struct cell *t;
1218         int code, ret = -1;
1219         str reason;
1220         char* r;
1221
1222         if (msg->REQ_METHOD==METHOD_ACK) {
1223                 LOG(L_WARN, "WARNING: t_reply: ACKs are not replied\n");
1224                 return -1;
1225         }
1226         if (t_check( msg , 0 )==-1) return -1;
1227         t=get_t();
1228         if (!t) {
1229                 LOG(L_ERR, "ERROR: t_reply: cannot send a t_reply to a message "
1230                         "for which no T-state has been established\n");
1231                 return -1;
1232         }
1233
1234         if (get_int_fparam(&code, msg, (fparam_t*)p1) < 0) {
1235             code = cfg_get(tm, tm_cfg, default_code);
1236         }
1237         
1238         if (get_str_fparam(&reason, msg, (fparam_t*)p2) < 0) {
1239                 r = cfg_get(tm, tm_cfg, default_reason);
1240         } else {
1241                 r = as_asciiz(&reason);
1242                 if (r == NULL) r = cfg_get(tm, tm_cfg, default_reason);
1243         }
1244         
1245         /* if called from reply_route, make sure that unsafe version
1246          * is called; we are already in a mutex and another mutex in
1247          * the safe version would lead to a deadlock
1248          */
1249          
1250         if (is_route_type(FAILURE_ROUTE)) {
1251                 DBG("DEBUG: t_reply_unsafe called from w_t_reply\n");
1252                 ret = t_reply_unsafe(t, msg, code, r);
1253         } else if (is_route_type(REQUEST_ROUTE)) {
1254                 ret = t_reply( t, msg, code, r);
1255         } else {
1256                 LOG(L_CRIT, "BUG: w_t_reply entered in unsupported mode\n");
1257                 ret = -1;
1258         }
1259
1260         if (r && (r != cfg_get(tm, tm_cfg, default_reason))) pkg_free(r);
1261         return ret;
1262 }
1263
1264
1265 inline static int w_t_release(struct sip_msg* msg, char* str, char* str2)
1266 {
1267         struct cell *t;
1268         int ret;
1269         
1270         if (t_check( msg  , 0  )==-1) return -1;
1271         t=get_t();
1272         if ( t && t!=T_UNDEFINED ) {
1273                 ret = t_release_transaction( t );
1274                 t_unref(msg);
1275                 return ret;
1276         }
1277         return 1;
1278 }
1279
1280
1281 inline static int w_t_retransmit_reply( struct sip_msg* p_msg, char* foo, char* bar)
1282 {
1283         struct cell *t;
1284
1285
1286         if (t_check( p_msg  , 0 )==-1)
1287                 return 1;
1288         t=get_t();
1289         if (t) {
1290                 if (p_msg->REQ_METHOD==METHOD_ACK) {
1291                         LOG(L_WARN, "WARNING: : ACKs transmit_replies not replied\n");
1292                         return -1;
1293                 }
1294                 return t_retransmit_reply( t );
1295         } else
1296                 return -1;
1297 }
1298
1299
1300 inline static int w_t_newtran( struct sip_msg* p_msg, char* foo, char* bar )
1301 {
1302         /* t_newtran returns 0 on error (negative value means
1303            'transaction exists' */
1304         int ret;
1305         ret = t_newtran( p_msg );
1306         if (ret==E_SCRIPT) {
1307                 LOG(L_ERR, "ERROR: t_newtran: "
1308                         "transaction already in process %p\n", get_t() );
1309         }
1310         return ret;
1311 }
1312
1313
1314 inline static int w_t_on_negative( struct sip_msg* msg, char *go_to, char *foo)
1315 {
1316         t_on_negative( (unsigned int )(long) go_to );
1317         return 1;
1318 }
1319
1320 inline static int w_t_on_branch( struct sip_msg* msg, char *go_to, char *foo)
1321 {
1322         t_on_branch( (unsigned int )(long) go_to );
1323         return 1;
1324 }
1325
1326
1327 inline static int w_t_on_reply( struct sip_msg* msg, char *go_to, char *foo )
1328 {
1329         t_on_reply( (unsigned int )(long) go_to );
1330         return 1;
1331 }
1332
1333
1334
1335 inline static int _w_t_relay_to(struct sip_msg  *p_msg ,
1336                                                                         struct proxy_l *proxy, int force_proto)
1337 {
1338         struct cell *t;
1339
1340         if (is_route_type(FAILURE_ROUTE)) {
1341                 t=get_t();
1342                 if (!t || t==T_UNDEFINED) {
1343                         LOG(L_CRIT, "BUG: w_t_relay_to: undefined T\n");
1344                         return -1;
1345                 }
1346                 if (t_forward_nonack(t, p_msg, proxy, force_proto)<=0 ) {
1347                         LOG(L_ERR, "ERROR: w_t_relay_to: t_relay_to failed\n");
1348                         /* let us save the error code, we might need it later
1349                         when the failure_route has finished (Miklos) */
1350                         tm_error=ser_error;
1351                         return -1;
1352                 }
1353                 return 1;
1354         }
1355         if (is_route_type(REQUEST_ROUTE))
1356                 return t_relay_to( p_msg, proxy, force_proto,
1357                         0 /* no replication */ );
1358         LOG(L_CRIT, "ERROR: w_t_relay_to: unsupported route type: %d\n", route_type);
1359         return 0;
1360 }
1361
1362
1363 inline static int w_t_relay_to_udp( struct sip_msg  *p_msg ,
1364                                                                         char *proxy,/* struct proxy_l * expected */
1365                                                                         char *_foo       /* nothing expected */ )
1366 {
1367         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_UDP);
1368 }
1369
1370 /* forward to uri, but force udp as transport */
1371 inline static int w_t_relay_to_udp_uri( struct sip_msg  *p_msg ,
1372                                                                                 char *_foo, char *_bar   )
1373 {
1374         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_UDP);
1375 }
1376
1377
1378 #ifdef USE_TCP
1379 inline static int w_t_relay_to_tcp( struct sip_msg  *p_msg ,
1380                                                                         char *proxy, /* struct proxy_l* */
1381                                                                         char *_foo       /* nothing expected */ )
1382 {
1383         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_TCP);
1384 }
1385
1386 /* forward to uri, but force tcp as transport */
1387 inline static int w_t_relay_to_tcp_uri( struct sip_msg  *p_msg ,
1388                                                                                 char *_foo, char *_bar   )
1389 {
1390         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_TCP);
1391 }
1392 #endif
1393
1394
1395 #ifdef USE_TLS
1396 inline static int w_t_relay_to_tls( struct sip_msg  *p_msg ,
1397                                                                         char *proxy, /* struct proxy_l* expected */
1398                                                                         char *_foo       /* nothing expected */ )
1399 {
1400         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_TLS);
1401 }
1402
1403 /* forward to uri, but force tls as transport */
1404 inline static int w_t_relay_to_tls_uri( struct sip_msg  *p_msg ,
1405                                                                                 char *_foo, char *_bar   )
1406 {
1407         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_TLS);
1408 }
1409 #endif
1410
1411
1412 #ifdef USE_SCTP
1413 inline static int w_t_relay_to_sctp( struct sip_msg  *p_msg ,
1414                                                                         char *proxy, /* struct proxy_l* */
1415                                                                         char *_foo       /* nothing expected */ )
1416 {
1417         return _w_t_relay_to( p_msg, ( struct proxy_l *) proxy, PROTO_SCTP);
1418 }
1419
1420 /* forward to uri, but force tcp as transport */
1421 inline static int w_t_relay_to_sctp_uri( struct sip_msg  *p_msg ,
1422                                                                                 char *_foo, char *_bar   )
1423 {
1424         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_SCTP);
1425 }
1426 #endif
1427
1428
1429 inline static int w_t_relay_to_avp( struct sip_msg  *p_msg ,
1430                                                                         char *proto_par, 
1431                                                                         char *addr_par   )
1432 {
1433         struct proxy_l *proxy;
1434         int r = -1;
1435         
1436         proxy = t_protoaddr2proxy(proto_par, addr_par);
1437         if (proxy) {
1438                 r = _w_t_relay_to(p_msg, proxy, PROTO_NONE);
1439                 free_proxy(proxy);
1440         }
1441         return r;
1442 }
1443
1444 inline static int w_t_replicate_uri(struct sip_msg  *msg ,
1445                                 char *uri,       /* sip uri as string or variable */
1446                                 char *_foo       /* nothing expected */ )
1447 {
1448         struct proxy_l *proxy;
1449         struct sip_uri turi;
1450         str suri;
1451         int r = -1;
1452
1453         memset(&turi, 0, sizeof(struct sip_uri));
1454         if(fixup_get_svalue(msg, (gparam_p)uri, &suri)!=0)
1455         {
1456                 LM_ERR("invalid replicate uri parameter");
1457                 return -1;
1458         }
1459         if(parse_uri(suri.s, suri.len, &turi)!=0)
1460         {
1461                 LM_ERR("bad replicate SIP address!\n");
1462                 return -1;
1463         }
1464
1465         proxy=mk_proxy(&turi.host, turi.port_no, turi.proto);
1466         if (proxy==0) {
1467                 LM_ERR("cannot create proxy from URI <%.*s>\n",
1468                         suri.len, suri.s );
1469                 return -1;
1470         }
1471
1472         r = t_replicate(msg, proxy, proxy->proto);
1473         free_proxy(proxy);
1474         return r;
1475
1476 }
1477
1478 inline static int w_t_replicate( struct sip_msg  *p_msg ,
1479         char *proxy, /* struct proxy_l *proxy expected */
1480         char *_foo       /* nothing expected */ )
1481 {
1482         return t_replicate(p_msg, ( struct proxy_l *) proxy, p_msg->rcv.proto );
1483 }
1484
1485 inline static int w_t_replicate_udp( struct sip_msg  *p_msg ,
1486         char *proxy, /* struct proxy_l *proxy expected */
1487         char *_foo       /* nothing expected */ )
1488 {
1489         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_UDP );
1490 }
1491
1492
1493 #ifdef USE_TCP
1494 inline static int w_t_replicate_tcp( struct sip_msg  *p_msg ,
1495         char *proxy, /* struct proxy_l *proxy expected */
1496         char *_foo       /* nothing expected */ )
1497 {
1498         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_TCP );
1499 }
1500 #endif
1501
1502
1503 #ifdef USE_TLS
1504 inline static int w_t_replicate_tls( struct sip_msg  *p_msg ,
1505         char *proxy, /* struct proxy_l *proxy expected */
1506         char *_foo       /* nothing expected */ )
1507 {
1508         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_TLS );
1509 }
1510 #endif
1511
1512
1513 #ifdef USE_SCTP
1514 inline static int w_t_replicate_sctp( struct sip_msg  *p_msg ,
1515         char *proxy, /* struct proxy_l *proxy expected */
1516         char *_foo       /* nothing expected */ )
1517 {
1518         return t_replicate(p_msg, ( struct proxy_l *) proxy, PROTO_SCTP );
1519 }
1520 #endif
1521
1522
1523 inline static int w_t_replicate_to( struct sip_msg  *p_msg ,
1524         char *proto_par, 
1525         char *addr_par   )
1526 {
1527         struct proxy_l *proxy;
1528         int r = -1;
1529         proxy = t_protoaddr2proxy(proto_par, addr_par);
1530         if (proxy) {
1531                 r = t_replicate(p_msg, proxy, proxy->proto);            
1532                 free_proxy(proxy);
1533         }
1534         return r;
1535 }
1536
1537 inline static int w_t_relay( struct sip_msg  *p_msg ,
1538                                                                 char *_foo, char *_bar)
1539 {
1540         return _w_t_relay_to(p_msg, (struct proxy_l *)0, PROTO_NONE);
1541 }
1542
1543
1544 /* like t_relay but use the specified destination and port and the same proto
1545  * as the received msg */
1546 static int w_t_relay2( struct sip_msg  *p_msg , char *proxy,
1547                                                                 char *_foo)
1548 {
1549         return _w_t_relay_to(p_msg, (struct proxy_l*) proxy, p_msg->rcv.proto);
1550 }
1551
1552
1553 /* relays CANCEL at the beginning of the script */
1554 inline static int w_t_relay_cancel( struct sip_msg  *p_msg ,
1555                                                 char *_foo, char *_bar)
1556 {
1557         if (p_msg->REQ_METHOD!=METHOD_CANCEL)
1558                 return 1;
1559
1560         /* it makes no sense to use this function without reparse_invite=1 */
1561         if (!cfg_get(tm, tm_cfg, reparse_invite))
1562                 LOG(L_WARN, "WARNING: t_relay_cancel is probably used with "
1563                         "wrong configuration, check the readme for details\n");
1564
1565         return t_relay_cancel(p_msg);
1566 }
1567
1568 /* set fr_inv_timeout & or fr_timeout; 0 means: use the default value */
1569 static int t_set_fr_all(struct sip_msg* msg, char* p1, char* p2)
1570 {
1571     int fr, fr_inv;
1572
1573     if (get_int_fparam(&fr_inv, msg, (fparam_t*)p1) < 0) return -1;
1574     if (p2) {
1575         if (get_int_fparam(&fr, msg, (fparam_t*)p2) < 0) return -1;
1576     } else {
1577         fr = 0;
1578     }
1579
1580     return t_set_fr(msg, fr_inv, fr);
1581 }
1582
1583 static int t_set_fr_inv(struct sip_msg* msg, char* fr_inv, char* foo)
1584 {
1585         return t_set_fr_all(msg, fr_inv, (char*)0);
1586 }
1587
1588 /* reset fr_timer and fr_inv_timer to the default values */
1589 static int w_t_reset_fr(struct sip_msg* msg, char* foo, char* bar)
1590 {
1591         return t_reset_fr();
1592 }
1593
1594 /* set retr. intervals per transaction; 0 means: use the default value */
1595 static int w_t_set_retr(struct sip_msg* msg, char* p1, char* p2)
1596 {
1597         int t1, t2;
1598         
1599         if (get_int_fparam(&t1, msg, (fparam_t*)p1) < 0) return -1;
1600         if (p2) {
1601                 if (get_int_fparam(&t2, msg, (fparam_t*)p2) < 0) return -1;
1602         } else {
1603                 t2 = 0;
1604         }
1605 #ifdef TM_DIFF_RT_TIMEOUT
1606         return t_set_retr(msg, t1, t2);
1607 #else
1608         ERR("w_t_set_retr: support for changing retransmission intervals on "
1609                         "the fly not compiled in (re-compile tm with"
1610                         " -DTM_DIFF_RT_TIMEOUT)\n");
1611         return -1;
1612 #endif
1613 }
1614
1615 /* reset retr. t1 and t2 to the default values */
1616 int w_t_reset_retr(struct sip_msg* msg, char* foo, char* bar)
1617 {
1618 #ifdef TM_DIFF_RT_TIMEOUT
1619         return t_reset_retr();
1620 #else
1621         ERR("w_t_reset_retr: support for changing retransmission intervals on "
1622                         "the fly not compiled in (re-compile tm with"
1623                         " -DTM_DIFF_RT_TIMEOUT)\n");
1624         return -1;
1625 #endif
1626 }
1627
1628 /* set maximum transaction lifetime for inv & noninv */
1629 static int w_t_set_max_lifetime(struct sip_msg* msg, char* p1, char* p2)
1630 {
1631         int t1, t2;
1632         
1633         if (get_int_fparam(&t1, msg, (fparam_t*)p1) < 0) return -1;
1634         if (p2) {
1635                 if (get_int_fparam(&t2, msg, (fparam_t*)p2) < 0) return -1;
1636         } else {
1637                 t2 = 0;
1638         }
1639         return t_set_max_lifetime(msg, t1, t2);
1640 }
1641
1642 /* reset maximum invite/non-invite lifetime to the default value */
1643 int w_t_reset_max_lifetime(struct sip_msg* msg, char* foo, char* bar)
1644 {
1645         return t_reset_max_lifetime();
1646 }
1647
1648
1649
1650 /* helper macro, builds a function for setting a cell flag from the script.
1651    e.g. T_SET_FLAG_GEN_FUNC(t_set_foo, T_FOO) =>
1652    static int t_set_foo(struct sip_msg* msg, char*, char* )
1653    that will expect fparam as first param and will set or reset T_FOO
1654    in the current or next to be created transaction. */
1655 #define T_SET_FLAG_GEN_FUNC(fname, T_FLAG_NAME) \
1656 static int fname(struct sip_msg* msg, char* p1, char* p2) \
1657 { \
1658         int state; \
1659         struct cell* t; \
1660         unsigned int set_flags; \
1661         unsigned int reset_flags; \
1662          \
1663         if (get_int_fparam(&state, msg, (fparam_t*)p1) < 0) return -1; \
1664         t=get_t(); \
1665         /* in REPLY_ROUTE and FAILURE_ROUTE T will be set to current transaction; \
1666          * in REQUEST_ROUTE T will be set only if the transaction was already  \
1667          * created; if not -> use the static variables */ \
1668         if (!t || t==T_UNDEFINED ){ \
1669                 set_flags=get_msgid_val(user_cell_set_flags, msg->id, int); \
1670                 reset_flags=get_msgid_val(user_cell_reset_flags, msg->id, int); \
1671                 if (state){ \
1672                         /* set */ \
1673                         set_flags|= T_FLAG_NAME; \
1674                         reset_flags&=~T_FLAG_NAME; \
1675                 }else{ \
1676                         /* reset */ \
1677                         set_flags&=~T_FLAG_NAME; \
1678                         reset_flags|=T_FLAG_NAME; \
1679                 } \
1680                 set_msgid_val(user_cell_set_flags, msg->id, int, set_flags); \
1681                 set_msgid_val(user_cell_reset_flags, msg->id, int, reset_flags); \
1682         }else{ \
1683                 if (state) \
1684                         t->flags|=T_FLAG_NAME; \
1685                 else \
1686                         t->flags&=~T_FLAG_NAME; \
1687         } \
1688         return 1; \
1689 }
1690
1691
1692
1693 /* set automatically sending 100 replies on/off for the current or
1694  * next to be created transaction */
1695 T_SET_FLAG_GEN_FUNC(t_set_auto_inv_100, T_AUTO_INV_100)
1696
1697
1698 /* set 6xx handling for the current or next to be created transaction */
1699 T_SET_FLAG_GEN_FUNC(t_set_disable_6xx, T_DISABLE_6xx)
1700
1701
1702 /* disable dns failover for the current transaction */
1703 T_SET_FLAG_GEN_FUNC(t_set_disable_failover, T_DISABLE_FAILOVER)
1704
1705
1706
1707 /* script function, FAILURE_ROUTE only, returns true if the 
1708  * choosed "failure" branch failed because of a timeout, 
1709  * -1 otherwise */
1710 int t_branch_timeout(struct sip_msg* msg, char* foo, char* bar)
1711 {
1712         return (msg->msg_flags & FL_TIMEOUT)?1:-1;
1713 }
1714
1715
1716
1717 /* script function, FAILURE_ROUTE only, returns true if the 
1718  * choosed "failure" branch ever received a reply, -1 otherwise */
1719 int t_branch_replied(struct sip_msg* msg, char* foo, char* bar)
1720 {
1721         return (msg->msg_flags & FL_REPLIED)?1:-1;
1722 }
1723
1724
1725
1726 /* script function, returns: 1 if the transaction was canceled, -1 if not */
1727 int t_is_canceled(struct sip_msg* msg, char* foo, char* bar)
1728 {
1729         struct cell *t;
1730         int ret;
1731         
1732         
1733         if (t_check( msg , 0 )==-1) return -1;
1734         t=get_t();
1735         if ((t==0) || (t==T_UNDEFINED)){
1736                 LOG(L_ERR, "ERROR: t_is_canceled: cannot check a message "
1737                         "for which no T-state has been established\n");
1738                 ret=-1;
1739         }else{
1740                 ret=(t->flags & T_CANCELED)?1:-1;
1741         }
1742         return ret;
1743 }
1744
1745 /* script function, returns: 1 if the transaction lifetime interval has already elapsed, -1 if not */
1746 int t_is_expired(struct sip_msg* msg, char* foo, char* bar)
1747 {
1748         struct cell *t;
1749         int ret;
1750         
1751         
1752         if (t_check( msg , 0 )==-1) return -1;
1753         t=get_t();
1754         if ((t==0) || (t==T_UNDEFINED)){
1755                 LOG(L_ERR, "ERROR: t_is_expired: cannot check a message "
1756                         "for which no T-state has been established\n");
1757                 ret=-1;
1758         }else{
1759                 ret=(TICKS_GT(t->end_of_life, get_ticks_raw()))?-1:1;
1760         }
1761         return ret;
1762 }
1763
1764 /* script function, returns: 1 if any of the branches did timeout, -1 if not */
1765 int t_any_timeout(struct sip_msg* msg, char* foo, char* bar)
1766 {
1767         struct cell *t;
1768         int r;
1769         
1770         if (t_check( msg , 0 )==-1) return -1;
1771         t=get_t();
1772         if ((t==0) || (t==T_UNDEFINED)){
1773                 LOG(L_ERR, "ERROR: t_any_timeout: cannot check a message "
1774                         "for which no T-state has been established\n");
1775                 return -1;
1776         }else{
1777                 for (r=0; r<t->nr_of_outgoings; r++){
1778                         if (t->uac[r].request.flags & F_RB_TIMEOUT)
1779                                 return 1;
1780                 }
1781         }
1782         return -1;
1783 }
1784
1785
1786
1787 /* script function, returns: 1 if any of the branches received at leat one
1788  * reply, -1 if not */
1789 int t_any_replied(struct sip_msg* msg, char* foo, char* bar)
1790 {
1791         struct cell *t;
1792         int r;
1793         
1794         if (t_check( msg , 0 )==-1) return -1;
1795         t=get_t();
1796         if ((t==0) || (t==T_UNDEFINED)){
1797                 LOG(L_ERR, "ERROR: t_any_replied: cannot check a message "
1798                         "for which no T-state has been established\n");
1799                 return -1;
1800         }else{
1801                 for (r=0; r<t->nr_of_outgoings; r++){
1802                         if (t->uac[r].request.flags & F_RB_REPLIED)
1803                                 return 1;
1804                 }
1805         }
1806         return -1;
1807 }
1808
1809
1810
1811 /* script function, returns: 1 if any of the branches received the
1812  *  reply code "status" */
1813 int t_grep_status(struct sip_msg* msg, char* status, char* bar)
1814 {
1815         struct cell *t;
1816         int r;
1817         int code;
1818         
1819     if (get_int_fparam(&code, msg, (fparam_t*)status) < 0) return -1;
1820         if (t_check( msg , 0 )==-1) return -1;
1821         t=get_t();
1822         if ((t==0) || (t==T_UNDEFINED)){
1823                 LOG(L_ERR, "ERROR: t_any_replied: cannot check a message "
1824                         "for which no T-state has been established\n");
1825                 return -1;
1826         }else{
1827                 for (r=0; r<t->nr_of_outgoings; r++){
1828                         if ((t->uac[r].last_received==code)  && 
1829                                         (t->uac[r].request.flags & F_RB_REPLIED))
1830                                 return 1;
1831                 }
1832         }
1833         return -1;
1834 }
1835
1836 /* drop all the existing replies in failure_route to make sure
1837  * that none of them is picked up again */
1838 static int w_t_drop_replies(struct sip_msg* msg, char* foo, char* bar)
1839 {
1840         if(foo==NULL)
1841                 t_drop_replies(1);
1842         else if(*foo=='n')
1843                 t_drop_replies(0);
1844         else if(*foo=='l')
1845                 t_drop_replies(2);
1846         else
1847                 t_drop_replies(1);
1848         return 1;
1849 }
1850
1851 /* save the message lumps after t_newtran() but before t_relay() */
1852 static int w_t_save_lumps(struct sip_msg* msg, char* foo, char* bar)
1853 {
1854 #ifdef POSTPONE_MSG_CLONING
1855         struct cell *t;
1856
1857         t=get_t();
1858         if (!t || t==T_UNDEFINED) {
1859                 LOG(L_ERR, "ERROR: w_t_save_lumps: transaction has not been created yet\n");
1860                 return -1;
1861         }
1862
1863         if (save_msg_lumps(t->uas.request, msg)) {
1864                 LOG(L_ERR, "ERROR: w_t_save_lumps: "
1865                         "failed to save the message lumps\n");
1866                 return -1;
1867         }
1868         return 1;
1869 #else
1870         LOG(L_ERR, "ERROR: w_t_save_lumps: POSTPONE_MSG_CLONING is not defined,"
1871                         " thus, the functionality is not supported\n");
1872         return -1;
1873 #endif
1874 }
1875
1876 static rpc_export_t tm_rpc[] = {
1877         {"tm.cancel", rpc_cancel,   rpc_cancel_doc,   0},
1878         {"tm.reply",  rpc_reply,    rpc_reply_doc,    0},
1879         {"tm.stats",  tm_rpc_stats, tm_rpc_stats_doc, 0},
1880         {"tm.hash_stats",  tm_rpc_hash_stats, tm_rpc_hash_stats_doc, 0},
1881         {"tm.t_uac_start", rpc_t_uac_start, rpc_t_uac_start_doc, 0 },
1882         {"tm.t_uac_wait",  rpc_t_uac_wait,  rpc_t_uac_wait_doc, RET_ARRAY},
1883         {0, 0, 0, 0}
1884 };
1885
1886 /* wrapper function needed after changes in w_t_reply */
1887 int w_t_reply_wrp(struct sip_msg *m, unsigned int code, char *txt)
1888 {
1889         fparam_t c;
1890         fparam_t r;
1891         
1892         c.type = FPARAM_INT;
1893         c.orig = NULL; /* ? */
1894         c.v.i = code;
1895         
1896         r.type = FPARAM_STRING;
1897         r.orig = NULL; /* ? */
1898         r.v.asciiz = txt;
1899
1900         return w_t_reply(m, (char *)&c, (char*)&r);
1901 }
1902
1903
1904
1905 /** script function, check if a msg is assoc. to a transaction.
1906  * @return -1 (not), 1 (reply, e2e ack or cancel for an existing transaction),
1907  *          0 (request retransmission, ack to negative reply or ack to local
1908  *           transaction)
1909  * Note: the e2e ack matching works only for local e2e acks or for
1910  *       transactions with E2EACK* callbacks installed (but even in this
1911  *       case matching E2EACKs on proxied transaction is not entirely
1912  *       reliable: if the ACK  is delayed the proxied transaction might
1913  *       be already deleted when it reaches the proxy (wait_timeout))
1914  */
1915 static int t_check_trans(struct sip_msg* msg, char* foo, char* bar)
1916 {
1917         struct cell* t;
1918         
1919         if (msg->first_line.type==SIP_REPLY)
1920                 return w_t_check(msg, 0 ,0);
1921         else if (msg->REQ_METHOD==METHOD_CANCEL)
1922                 return w_t_lookup_cancel(msg, 0, 0);
1923         else{
1924                 switch(t_check_msg(msg, 0)){
1925                         case -2: /* possible e2e ack */
1926                                 return 1;
1927                         case 1: /* found */
1928                                 t=get_t();
1929                                 if (msg->REQ_METHOD==METHOD_ACK){
1930                                         /* ack to neg. reply  or ack to local trans.
1931                                            => process it and end the script */
1932                                         /* FIXME: there's no way to distinguish here 
1933                                            between acks to local trans. and neg. acks */
1934                                         if (unlikely(has_tran_tmcbs(t, TMCB_ACK_NEG_IN)))
1935                                                 run_trans_callbacks(TMCB_ACK_NEG_IN, t, msg,
1936                                                                                         0, msg->REQ_METHOD);
1937                                         t_release_transaction(t);
1938                                 } else {
1939                                         /* is a retransmission */
1940                                         if (unlikely(has_tran_tmcbs(t, TMCB_REQ_RETR_IN)))
1941                                                 run_trans_callbacks(TMCB_REQ_RETR_IN, t, msg,
1942                                                                                         0, msg->REQ_METHOD);
1943                                         t_retransmit_reply(t);
1944                                 }
1945                                 /* no need for UNREF(t); set_t(0) - the end-of-script
1946                                    t_unref callback will take care of them */
1947                                 return 0; /* return from the script */
1948                 }
1949                 /* not found or error */
1950         }
1951         return -1;
1952 }
1953
1954 static int hexatoi(str *s, unsigned int* result)
1955 {
1956         int i, xv, fact;
1957
1958         /* more than 32bit hexa? */
1959         if (s->len>8)
1960                 return -1;
1961
1962         *result = 0;
1963         fact = 1;
1964
1965         for(i=s->len-1; i>=0 ;i--)
1966         {
1967                 xv = hex2int(s->s[i]);
1968                 if(xv<0)
1969                         return -1;
1970
1971                 *result += (xv * fact);
1972                 fact *= 16;
1973         }
1974         return 0;
1975 }
1976
1977 static int fixup_t_relay_to(void** param, int param_no)
1978 {
1979
1980         int port;
1981         int proto;
1982         unsigned int flags;
1983         struct proxy_l *proxy;
1984         action_u_t *a;
1985         str s;
1986         str host;
1987
1988         s.s = (char*)*param;
1989         s.len = strlen(s.s);
1990         LM_DBG("fixing (%s, %d)\n", s.s, param_no);
1991         if (param_no==1){
1992                 a = fixup_get_param(param, param_no, 2);
1993                 if(a==NULL)
1994                 {
1995                         LM_CRIT("server error for parameter <%s>\n",s.s);
1996                         return E_UNSPEC;
1997                 }
1998                 if(a->u.string!=NULL) {
1999                         /* second parameter set, first should be proxy addr */
2000                         if (parse_phostport(s.s, &host.s, &host.len, &port, &proto)!=0){
2001                                 LM_CRIT("invalid proxy addr parameter <%s>\n",s.s);
2002                                 return E_UNSPEC;
2003                         }
2004
2005                         proxy = mk_proxy(&host, port, proto);
2006                         if (proxy==0) {
2007                                 LM_ERR("failed to build proxy structure for <%.*s>\n", host.len, host.s );
2008                                 return E_UNSPEC;
2009                         }
2010                         *(param)=proxy;
2011                         return 0;
2012                 } else {
2013                         /* no second parameter, then is proxy addr or flags */
2014                         flags = 0;
2015                         if (s.len>2 && s.s[0]=='0' && s.s[1]=='x') {
2016                                 s.s += 2;
2017                                 s.len -= 2;
2018                                 if(hexatoi(&s, &flags)<0)
2019                                 {
2020                                         LM_CRIT("invalid hexa flags <%s>\n", s.s);
2021                                         return E_UNSPEC;
2022                                 }
2023                                 a->u.data = (void*)(unsigned long int)flags;
2024                                 *(param)= 0;
2025                                 return 0;
2026                         } else {
2027                                 if(str2int(&s, &flags)==0)
2028                                 {
2029                                         a->u.data = (void*)(unsigned long int)flags;
2030                                         *(param)= 0;
2031                                         return 0;
2032                                 } else {
2033                                         /* try proxy */
2034                                         if (parse_phostport(s.s, &host.s, &host.len, &port, &proto)!=0){
2035                                                 LM_CRIT("invalid proxy addr parameter <%s>\n",s.s);
2036                                                 return E_UNSPEC;
2037                                         }
2038
2039                                         proxy = mk_proxy(&host, port, proto);
2040                                         if (proxy==0) {
2041                                                 LM_ERR("failed to build proxy structure for <%.*s>\n", host.len, host.s );
2042                                                 return E_UNSPEC;
2043                                         }
2044                                         *(param)=proxy;
2045                                         return 0;
2046                                 }
2047                         }
2048                 }
2049         } else if (param_no==2) {
2050                 /* flags */
2051                 flags = 0;
2052                 if (s.len>2 && s.s[0]=='0' && s.s[1]=='x') {
2053                         s.s += 2;
2054                         s.len -= 2;
2055                         if(hexatoi(&s, &flags)<0)
2056                         {
2057                                 LM_CRIT("invalid hexa flags <%s>\n", s.s);
2058                                 return E_UNSPEC;
2059                         }
2060                         *(param) = (void*)(unsigned long int)flags;
2061                         return 0;
2062                 } else {
2063                         if(str2int(&s, &flags)==0)
2064                         {
2065                                 *(param) = (void*)(unsigned long int)flags;
2066                                 return 0;
2067                         } else {
2068                                 LM_CRIT("invalid flags <%s>\n", s.s);
2069                                 return E_UNSPEC;
2070                         }
2071                 }
2072         } else {
2073                 LM_ERR("invalid parameter number %d\n", param_no);
2074                 return E_BUG;
2075         }
2076 }
2077
2078
2079 inline static int w_t_relay_to(struct sip_msg *msg, char *proxy, char *flags)
2080 {
2081         unsigned int fl;
2082         struct proxy_l *px;
2083         fparam_t param;
2084
2085         fl = (unsigned int)(long)(void*)flags;
2086         px = (struct proxy_l*)proxy;
2087
2088         if(flags!=0)
2089         {
2090                 memset(&param, 0, sizeof(fparam_t));
2091                 param.type = FPARAM_INT;
2092                 /* no auto 100 trying */
2093                 if(fl&1) {
2094                         param.v.i = 0;
2095                         t_set_auto_inv_100(msg, (char*)(&param), 0);
2096                 }
2097                 /* no auto negative reply - not implemented */
2098                 /*
2099                 if(fl&2) {
2100                         param.v.i = 1;
2101                         t_set_disable_internal_reply(msg, (char*)param, 0);
2102                 }
2103                 */
2104                 /* no dns failover */
2105                 if(fl&4) {
2106                         param.v.i = 1;
2107                         t_set_disable_failover(msg, (char*)(&param), 0);
2108                 }
2109         }
2110         return _w_t_relay_to(msg, px, PROTO_NONE);
2111 }
2112