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