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