1 /*
2  * Copyright (C) 2001-2003 FhG Fokus
3  *
4  * This file is part of Kamailio, a free SIP server.
5  *
6  * Kamailio is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version
10  *
11  * Kamailio is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21 
22 /**  TM :: hash table, flags and other general defines.
23  * @file
24  * @ingroup tm
25  */
26 
27 
28 #ifndef _H_TABLE_H
29 #define _H_TABLE_H
30 
31 #include "t_stats.h"
32 
33 /* uncomment the next define if you wish to keep hash statistics*/
34 /*
35 #define TM_HASH_STATS
36 */
37 /* use hash stats always in debug mode */
38 #ifdef EXTRA_DEBUG
39 #ifndef TM_HASH_STATS
40 #define TM_HASH_STATS
41 #endif
42 #endif
43 
44 
45 #include "../../core/clist.h"
46 #include "../../core/parser/msg_parser.h"
47 #include "../../core/usr_avp.h"
48 #include "../../core/xavp.h"
49 #include "../../core/timer.h"
50 #include "../../core/flags.h"
51 #include "../../core/atomic_ops.h"
52 #include "../../core/hash_func.h"
53 #include "config.h"
54 
55 
56 struct s_table;
57 struct entry;
58 struct cell;
59 struct timer;
60 struct retr_buf;
61 struct ua_client;
62 struct async_state;
63 
64 #include "../../core/mem/shm_mem.h"
65 #include "lock.h"
66 #include "sip_msg.h"
67 #include "t_hooks.h"
68 #ifdef USE_DNS_FAILOVER
69 #include "../../core/dns_cache.h"
70 #endif
71 
72 
73 #define LOCK_HASH(_h) lock_hash((_h))
74 #define UNLOCK_HASH(_h) unlock_hash((_h))
75 
76 void lock_hash(int i);
77 void unlock_hash(int i);
78 
79 
80 #define NO_CANCEL ((char *)0)
81 #define EXTERNAL_CANCEL ((char *)-1)
82 
83 #define TYPE_LOCAL_ACK -2
84 #define TYPE_LOCAL_CANCEL -1
85 #define TYPE_REQUEST 0
86 
87 /* to be able to assess whether a script writer forgot to
88  * release a transaction and leave it for ever in memory,
89  * we mark it with operations done over it; if none of these
90  * flags is set and script is being left, it is a sign of
91  * script error and we need to release on writer's
92  * behalf
93  *
94  * REQ_FWDED means there is a UAC with final response timer
95  *     ticking. If it hits, transaction will be completed.
96  * REQ_RPLD means that a transaction has been replied -- either
97  *     it implies going to wait state, or for invite transactions
98  *     FR timer is ticking until ACK arrives
99  * REQ_RLSD means that a transaction was put on wait explicitly
100  *     from t_release_transaction
101  * REQ_EXIST means that this request is a retransmission which does not
102  *     affect transactional state
103  * REQ_ERR_DELAYED mean that tm wants to send  reply(ser_error) but it
104  *     delayed it to end-of-script to allow it to be overriden.
105  *     If this is set and all of the above flag are not => send reply
106  *     on end of script. If any of the above flags is set, do not
107  *     send (especially REQ_RPLD and REQ_RLSD).
108 */
109 enum kill_reason
110 {
111 	REQ_FWDED = 1,
112 	REQ_RPLD = 2,
113 	REQ_RLSD = 4,
114 	REQ_EXIST = 8,
115 	REQ_ERR_DELAYED = 16
116 };
117 
118 /* interval for safer force removal after t lifetime (in sec) */
119 #define TM_LIFETIME_LIMIT 90
120 
121 /* #define F_RB_T_ACTIVE		0x01  (obsolete) fr or retr active */
122 #define F_RB_T2 0x02
123 #define F_RB_RETR_DISABLED 0x04 /* retransmission disabled */
124 #define F_RB_FR_INV 0x08		/* timer switched to FR_INV */
125 #define F_RB_TIMEOUT 0x10		/* timeout */
126 #define F_RB_REPLIED 0x20		/* reply received */
127 #define F_RB_CANCELED 0x40		/* rb/branch canceled */
128 #define F_RB_DEL_TIMER 0x80		/* timer should be deleted if active */
129 #define F_RB_NH_LOOSE 0x100		/* next hop is a loose router */
130 #define F_RB_NH_STRICT 0x200	/* next hop is a strict router */
131 /* must detect when neither loose nor strict flag is set -> two flags.
132  * alternatively, 1x flag for strict/loose and 1x for loose|strict set/not */
133 #define F_RB_RELAYREPLY 0x400 /* branch under relay reply condition */
134 
135 
136 /* if canceled or intended to be canceled, return true */
137 #define uac_dont_fork(uac) ((uac)->local_cancel.buffer)
138 
139 
140 typedef struct retr_buf
141 {
142 	/* rbtype is set to status code if the buffer is a reply,
143 	 * 0 (TYPE_REQUEST) if request, -1 if local CANCEL (TYPE_LOCAL_CANCEL),
144 	 * -2 if local ACK (TYPE_LOCAL_ACK) */
145 	short rbtype;
146 	volatile unsigned short flags;   /* DISABLED, T2 */
147 	volatile unsigned short t_active; /* timer active */
148 	unsigned short branch;			 /* no more than 64k branches */
149 	int buffer_len;
150 	char *buffer;
151 	/*the cell that contains this retrans_buff*/
152 	struct cell *my_T;
153 	struct timer_ln timer;
154 	struct dest_info dst;
155 	ticks_t retr_expire;
156 	ticks_t fr_expire; /* ticks value after which fr. will fire */
157 } tm_retr_buf_t;
158 
159 
160 /* User Agent Server content */
161 
162 typedef struct ua_server
163 {
164 	struct sip_msg *request;
165 	char *end_request;
166 	struct retr_buf response;
167 	/* keep to-tags for local 200 replies for INVITE --
168 	 * we need them for dialog-wise matching of ACKs;
169 	 * the pointer shows to shmem-ed reply */
170 	str local_totag;
171 	struct cancel_reason *cancel_reas; /* pointer to cancel reason, used
172 										* for e2e cancels */
173 	unsigned int status;
174 } tm_ua_server_t;
175 
176 
177 /* User Agent Client content */
178 
179 /* UAC internal flags */
180 #define TM_UAC_FLAG_RR (1)			/* Record-Route applied */
181 #define TM_UAC_FLAG_R2 (1 << 1)		/* 2nd Record-Route applied */
182 #define TM_UAC_FLAG_FB (1 << 2)		/* Mark first entry in new branch set */
183 #define TM_UAC_FLAG_BLIND (1 << 3)	/* A blind uac */
184 
185 typedef struct ua_client
186 {
187 	/* if we store a reply (branch picking), this is where it is */
188 	struct sip_msg *reply;
189 	char *end_reply; /* pointer to end of sip_msg so we know the shm blocked
190 						* used in clone...(used in async replies) */
191 	struct retr_buf request;
192 	/* we maintain a separate copy of cancel rather than
193 	 * reuse the structure for original request; the
194 	 * original request is no longer needed but its delayed
195 	 * timer may fire and interfere with whoever tries to
196 	 * rewrite it
197 	*/
198 	struct retr_buf local_cancel;
199 	/* pointer to retransmission buffer where uri is printed;
200 	 * good for generating ACK/CANCEL */
201 #ifdef USE_DNS_FAILOVER
202 	struct dns_srv_handle dns_h;
203 #endif
204 	str uri;
205 	str path;
206 	str instance;
207 	str ruid;
208 	str location_ua;
209 	/* if we don't store, we at least want to know the status */
210 	int last_received;
211 
212 	/* internal flags per tm uac */
213 	unsigned int flags;
214 	/* per branch flags */
215 	flag_t branch_flags;
216 	/* internal processing code - (mapping over sip warning codes)
217 	 * - storing the code giving a clue of what happened internally */
218 	int icode;
219 	/**
220 	 * Resent for every rcvd 2xx reply.
221 	 * This member's as an alternative to passing the reply to the AS,
222 	 * every time a reply for local request is rcvd.
223 	 * Member can not be union'ed with local_cancel, since CANCEL can happen
224 	 * concurrently with a 2xx reply (to generate an ACK).
225 	 */
226 	struct retr_buf *local_ack;
227 	/* the route to take if no final positive reply arrived */
228 	unsigned short on_failure;
229 	/* the route to take for all failure replies */
230 	unsigned short on_branch_failure;
231 	/* the onreply_route to be processed if registered to do so */
232 	unsigned short on_reply;
233 	/* unused - keep the structure aligned to 32b */
234 	unsigned short on_unused;
235 } tm_ua_client_t;
236 
237 
238 typedef struct totag_elem
239 {
240 	struct totag_elem *next;
241 	str tag;
242 	volatile int acked;
243 } tm_totag_elem_t;
244 
245 /* structure for storing transaction state prior to suspending
246  * of async transactions */
247 typedef struct async_state
248 {
249 	unsigned int backup_route;
250 	unsigned int backup_branch;
251 	unsigned int blind_uac;
252 	unsigned int ruri_new;
253 } tm_async_state_t;
254 
255 /* transaction's flags */
256 /* is the transaction's request an INVITE? */
257 #define T_IS_INVITE_FLAG (1 << 0)
258 /* is this a transaction generated by local request? */
259 #define T_IS_LOCAL_FLAG (1 << 1)
260 /* set to one if you want to disallow silent transaction
261  * dropping when C timer hits */
262 #define T_NOISY_CTIMER_FLAG (1 << 2)
263 /* transaction canceled
264  * WARNING: this flag can be set outside reply lock from e2e_cancel().
265  * If a future flag could be affected by a race w/ e2e_cancel() the code
266  * should be changed.*/
267 #define T_CANCELED (1 << 3)
268 /* 6xx received => stop forking */
269 #define T_6xx (1 << 4)
270 
271 #define T_IN_AGONY (1 << 5)		/* set if waiting to die (delete timer)
272 								 * TODO: replace it with del on unref */
273 #define T_AUTO_INV_100 (1 << 6) /* send an 100 reply automatically  to inv. */
274 /* don't generate automatically an ACK for local transaction */
275 #define T_NO_AUTO_ACK (1 << 7)
276 
277 #define T_DISABLE_6xx (1 << 8)		/* treat 6xx as a normal reply */
278 #define T_DISABLE_FAILOVER (1 << 9) /* don't perform dns failover */
279 #define T_NO_E2E_CANCEL_REASON (1 << 10) /* don't propagate CANCEL Reason */
280 #define T_DONT_FORK (T_CANCELED | T_6xx)
281 
282 /* provisional replies must trigger callbacks for local transaction */
283 #define T_PASS_PROVISIONAL_FLAG (1 << 11)
284 #define pass_provisional(_t_) ((_t_)->flags & T_PASS_PROVISIONAL_FLAG)
285 #define T_ASYNC_CONTINUE \
286 	(1 << 12) /* Is this transaction in a continuation after being suspended */
287 
288 #define T_DISABLE_INTERNAL_REPLY \
289 	(1 << 13) /* don't send internal negative reply */
290 #define T_ADMIN_REPLY \
291 	(1 << 14) /* t reply sent by admin (e.g., from cfg script) */
292 #define T_ASYNC_SUSPENDED (1 << 15)
293 
294 /* unsigned short should be enough for a retr. timer: max. 65535 ms =>
295  * max retr. = 65 s which should be enough and saves us 2*2 bytes */
296 typedef unsigned short retr_timeout_t;
297 
298 /**
299  * extra data from SIP message context to transaction storage
300  */
301 typedef struct tm_xdata
302 {
303 	/* lists with avps */
304 	struct usr_avp *uri_avps_from;
305 	struct usr_avp *uri_avps_to;
306 	struct usr_avp *user_avps_from;
307 	struct usr_avp *user_avps_to;
308 	struct usr_avp *domain_avps_from;
309 	struct usr_avp *domain_avps_to;
310 	sr_xavp_t *xavps_list;
311 	sr_xavp_t *xavus_list;
312 	sr_xavp_t *xavis_list;
313 } tm_xdata_t;
314 
315 
316 /**
317  * links to extra data from SIP message context to transaction storage
318  */
319 typedef struct tm_xlinks
320 {
321 	/* links to lists with avps */
322 	struct usr_avp **uri_avps_from;
323 	struct usr_avp **uri_avps_to;
324 	struct usr_avp **user_avps_from;
325 	struct usr_avp **user_avps_to;
326 	struct usr_avp **domain_avps_from;
327 	struct usr_avp **domain_avps_to;
328 	sr_xavp_t **xavps_list;
329 	sr_xavp_t **xavus_list;
330 	sr_xavp_t **xavis_list;
331 } tm_xlinks_t;
332 
333 
334 /* transaction context */
335 
336 typedef struct cell
337 {
338 	/* linking data */
339 	/* WARNING: don't move or change order of next_c or prev_c
340 	 * or breakage will occur */
341 	struct cell *next_c;
342 	struct cell *prev_c;
343 	/* tells in which hash table entry the cell lives */
344 	unsigned int hash_index;
345 	/* sequence number within hash collision slot */
346 	unsigned int label;
347 	/* different information about the transaction */
348 	unsigned short flags;
349 	/* number of forks */
350 	short nr_of_outgoings;
351 
352 	/* free operations counter - debug */
353 	int fcount;
354 	/* every time the transaction/cell is referenced from somewhere this
355 	 * ref_count should be increased (via REF()) and every time the reference
356 	 * is removed the ref_count should be decreased (via UNREF()).
357 	 * This includes adding the cell to the hash table (REF() before adding)
358 	 * and removing it from the hash table (UNREF_FREE() after unlinking).
359 	 * Exception: it does not include starting/stopping timers (timers are
360 	 * forced-stopped every time when ref_count reaches 0)
361 	 * If the cell is no longer referenced (ref_count==0 after an UNREF),
362 	 * it will be automatically deleted by the UNREF() operation.
363 	 */
364 	atomic_t ref_count;
365 	/* needed for generating local ACK/CANCEL for local
366 	 * transactions; all but cseq_n include the entire
367 	 * header field value, cseq_n only Cseq number; with
368 	 * local transactions, pointers point to outbound buffer,
369 	 * with proxied transactions to inbound request */
370 	str from, callid, cseq_n, to;
371 	/* method shortcut -- for local transactions, pointer to
372 	 * outbound buffer, for proxies transactions pointer to
373 	 * original message; needed for reply matching */
374 	str method;
375 
376 	/* head of callback list */
377 	struct tmcb_head_list tmcb_hl;
378 
379 	/* bindings to wait and delete timer */
380 	struct timer_ln wait_timer; /* used also for delete */
381 	ticks_t wait_start; /* ticks when put on wait first time */
382 
383 	/* UA Server */
384 	struct ua_server uas;
385 	/* UA Clients */
386 	struct ua_client *uac;
387 
388 	/* store transaction state to be used for async transactions */
389 	struct async_state async_backup;
390 
391 	/* to-tags of 200/INVITEs which were received from downstream and
392 	 * forwarded or passed to UAC; note that there can be arbitrarily
393 	 * many due to downstream forking; */
394 	struct totag_elem *fwded_totags;
395 
396 	/* lists with avps */
397 	struct usr_avp *uri_avps_from;
398 	struct usr_avp *uri_avps_to;
399 	struct usr_avp *user_avps_from;
400 	struct usr_avp *user_avps_to;
401 	struct usr_avp *domain_avps_from;
402 	struct usr_avp *domain_avps_to;
403 	sr_xavp_t *xavps_list;
404 	sr_xavp_t *xavus_list;
405 	sr_xavp_t *xavis_list;
406 
407 	/* protection against concurrent reply processing */
408 	ser_lock_t reply_mutex;
409 	/* pid of the process that holds the reply lock */
410 	atomic_t reply_locker_pid;
411 	/* recursive reply lock count */
412 	int reply_rec_lock_level;
413 
414 	ticks_t fr_timeout;		/* final response interval for retr_bufs */
415 	ticks_t fr_inv_timeout; /* final inv. response interval for retr_bufs */
416 	retr_timeout_t rt_t1_timeout_ms; /* start retr. interval for retr_bufs */
417 	retr_timeout_t rt_t2_timeout_ms; /* maximum retr. interval for retr_bufs */
418 	ticks_t end_of_life; /* maximum lifetime */
419 
420 	/* nr of replied branch; 0..sr_dst_max_branches=branch value,
421 	 * -1 no reply, -2 local reply */
422 	short relayed_reply_branch;
423 
424 	/* the route to take if no final positive reply arrived */
425 	unsigned short on_failure;
426 	/* the route to take for all failure replies */
427 	unsigned short on_branch_failure;
428 	/* the onreply_route to be processed if registered to do so */
429 	unsigned short on_reply;
430 	/* The route to take for each downstream branch separately */
431 	unsigned short on_branch;
432 	/* branch route backup for late branch add (t_append_branch) */
433 	unsigned short on_branch_delayed;
434 
435 	/* place holder for MD5checksum, MD5_LEN bytes are extra alloc'ed */
436 	char md5[0];
437 
438 } tm_cell_t;
439 
440 
441 #if 0
442 /* warning: padding too much => big size increase */
443 #define ENTRY_PAD_TO 128 /* should be a multiple of cacheline size for
444 						 * best performance*/
445 #define ENTRY_PAD_BYTES                                            \
446 	(ENTRY_PAD_TO - 2 * sizeof(struct cell *) + sizeof(ser_lock_t) \
447 			+ sizeof(int) + 2 * sizeof(long))
448 #else
449 #define ENTRY_PAD_BYTES 0
450 #endif
451 
452 /* double-linked list of cells with hash synonyms */
453 typedef struct entry
454 {
455 	/* WARNING: don't move or change order of next_c or prev_c
456 	 * or breakage will occur */
457 	struct cell *next_c;
458 	struct cell *prev_c;
459 	/* sync mutex */
460 	ser_lock_t mutex;
461 	atomic_t locker_pid; /* pid of the process that holds the lock */
462 	int rec_lock_level;  /* recursive lock count */
463 	/* currently highest sequence number in a synonym list */
464 	unsigned int next_label;
465 #ifdef TM_HASH_STATS
466 	unsigned long acc_entries;
467 	unsigned long cur_entries;
468 #endif
469 	char _pad[ENTRY_PAD_BYTES];
470 } tm_entry_t;
471 
472 
473 /* transaction table */
474 typedef struct s_table
475 {
476 	/* table of hash entries; each of them is a list of synonyms  */
477 	struct entry entries[TABLE_ENTRIES];
478 } s_table_t;
479 
480 /* pointer to the big table where all the transaction data lives */
481 extern struct s_table *_tm_table; /* private internal stuff, don't touch
482 								 * directly */
483 
484 #define list_entry(ptr, type, member) \
485 	((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))
486 
487 #define get_retr_timer_payload(_tl_) \
488 	list_entry(_tl_, struct retr_buf, retr_timer)
489 #define get_fr_timer_payload(_tl_) list_entry(_tl_, struct retr_buf, fr_timer)
490 #define get_wait_timer_payload(_tl_) list_entry(_tl_, struct cell, wait_tl)
491 #define get_dele_timer_payload(_tl_) list_entry(_tl_, struct cell, dele_tl)
492 
493 #define get_T_from_reply_rb(_rb_) \
494 	list_entry(list_entry(_rb_, (struct ua_server), response), struct cell, uas)
495 #define get_T_from_request_rb(_rb_, _br_)                        \
496 	list_entry( list_entry( (rb_, (struct ua_client), request) - \
497 		(_br_)*sizeof(struct retr_buf), struct cell, uas)
498 #define get_T_from_cancel_rb(_rb_, _br_)                              \
499 	list_entry( list_entry( (rb_, (struct ua_client), local_cancel) - \
500 		(_br_)*sizeof(struct retr_buf), struct cell, uas)
501 
502 #define is_invite(_t_) ((_t_)->flags & T_IS_INVITE_FLAG)
503 #define is_local(_t_) ((_t_)->flags & T_IS_LOCAL_FLAG)
504 #define has_noisy_ctimer(_t_) ((_t_)->flags & T_NOISY_CTIMER_FLAG)
505 #define was_cancelled(_t_) ((_t_)->flags & T_CANCELED)
506 #define no_new_branches(_t_) ((_t_)->flags & T_6xx)
507 
508 
509 void reset_kr(void);
510 void set_kr(enum kill_reason kr);
511 enum kill_reason get_kr(void);
512 
513 #define get_tm_table() (_tm_table)
514 
515 typedef struct s_table *(*tm_get_table_f)(void);
516 struct s_table *tm_get_table(void);
517 
518 struct s_table *init_hash_table(void);
519 void free_hash_table(void);
520 
521 void free_cell_helper(tm_cell_t *dead_cell, int silent, const char *fname,
522 		unsigned int fline);
523 #define free_cell(t) free_cell_helper((t), 0, __FILE__, __LINE__)
524 #define free_cell_silent(t) free_cell_helper((t), 1, __FILE__, __LINE__)
525 
526 struct cell *build_cell(struct sip_msg *p_msg);
527 
528 #ifdef TM_HASH_STATS
529 unsigned int transaction_count(void);
530 #endif
531 
532 
533 /*  Takes an already created cell and links it into hash table on the
534  *  appropriate entry. */
insert_into_hash_table_unsafe(struct cell * p_cell,unsigned int hash)535 inline static void insert_into_hash_table_unsafe(
536 		struct cell *p_cell, unsigned int hash)
537 {
538 	p_cell->label = _tm_table->entries[hash].next_label++;
539 #ifdef EXTRA_DEBUG
540 	DEBUG("cell label: %u\n", p_cell->label);
541 #endif
542 	p_cell->hash_index = hash;
543 	/* insert at the beginning */
544 	clist_insert(&_tm_table->entries[hash], p_cell, next_c, prev_c);
545 
546 /* update stats */
547 #ifdef TM_HASH_STATS
548 	_tm_table->entries[hash].cur_entries++;
549 	_tm_table->entries[hash].acc_entries++;
550 #endif
551 	t_stats_new(is_local(p_cell));
552 }
553 
554 
555 /*  Un-link a  cell from hash_table, but the cell itself is not released */
remove_from_hash_table_unsafe(struct cell * p_cell)556 inline static void remove_from_hash_table_unsafe(struct cell *p_cell)
557 {
558 	clist_rm(p_cell, next_c, prev_c);
559 
560 	p_cell->next_c = 0;
561 	p_cell->prev_c = 0;
562 #ifdef EXTRA_DEBUG
563 #ifdef TM_HASH_STATS
564 	if(_tm_table->entries[p_cell->hash_index].cur_entries == 0) {
565 		LOG(L_CRIT, "BUG: bad things happened: cur_entries=0\n");
566 		abort();
567 	}
568 #endif
569 #endif
570 #ifdef TM_HASH_STATS
571 	_tm_table->entries[p_cell->hash_index].cur_entries--;
572 #endif
573 
574 	t_stats_deleted(is_local(p_cell));
575 }
576 
577 void tm_clean_lifetime(void);
578 
579 /**
580  * backup xdata from/to msg context to local var and use T lists
581  */
582 void tm_xdata_swap(tm_cell_t *t, tm_xlinks_t *xd, int mode);
583 
584 void tm_xdata_replace(tm_xdata_t *newxd, tm_xlinks_t *bakxd);
585 
586 #endif
587