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