33dd7f17eb47690968bfe48157455eda1d4ff617
[sip-router] / src / core / receive.c
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 /*!
23  * \file
24  * \brief Kamailio core ::
25  * \ingroup core
26  * Module: \ref core
27  */
28
29
30 #include <string.h>
31 #include <stdlib.h>
32 #include <sys/time.h>
33
34 #include "receive.h"
35 #include "globals.h"
36 #include "dprint.h"
37 #include "route.h"
38 #include "parser/msg_parser.h"
39 #include "forward.h"
40 #include "action.h"
41 #include "mem/mem.h"
42 #include "ip_addr.h"
43 #include "script_cb.h"
44 #include "nonsip_hooks.h"
45 #include "dset.h"
46 #include "fmsg.h"
47 #include "usr_avp.h"
48 #include "xavp.h"
49 #include "select_buf.h"
50 #include "locking.h"
51
52 #include "tcp_server.h"  /* for tcpconn_add_alias */
53 #include "tcp_options.h" /* for access to tcp_accept_aliases*/
54 #include "cfg/cfg.h"
55 #include "core_stats.h"
56 #include "kemi.h"
57
58 #ifdef DEBUG_DMALLOC
59 #include <mem/dmalloc.h>
60 #endif
61
62 int _sr_ip_free_bind = 0;
63
64 unsigned int msg_no = 0;
65 /* address preset vars */
66 str default_global_address = {0, 0};
67 str default_global_port = {0, 0};
68 str default_via_address = {0, 0};
69 str default_via_port = {0, 0};
70
71 int ksr_route_locks_size = 0;
72 static rec_lock_set_t* ksr_route_locks_set = NULL;
73
74 int ksr_route_locks_set_init(void)
75 {
76         if(ksr_route_locks_set!=NULL || ksr_route_locks_size<=0)
77                 return 0;
78
79         ksr_route_locks_set = rec_lock_set_alloc(ksr_route_locks_size);
80         if(ksr_route_locks_set==NULL) {
81                 LM_ERR("failed to allocate route locks set\n");
82                 return -1;
83         }
84         if(rec_lock_set_init(ksr_route_locks_set)==NULL) {
85                 LM_ERR("failed to init route locks set\n");
86                 return -1;
87         }
88         return 0;
89 }
90
91 void ksr_route_locks_set_destroy(void)
92 {
93         if(ksr_route_locks_set==NULL)
94                 return;
95
96         rec_lock_set_destroy(ksr_route_locks_set);
97         rec_lock_set_dealloc(ksr_route_locks_set);
98         ksr_route_locks_set = NULL;
99 }
100
101 /**
102  * increment msg_no and return the new value
103  */
104 unsigned int inc_msg_no(void)
105 {
106         return ++msg_no;
107 }
108
109 /**
110  *
111  */
112 int sip_check_fline(char *buf, unsigned int len)
113 {
114         char *p;
115         int m;
116
117         m = 0;
118         for(p = buf; p < buf + len; p++) {
119                 /* first check if is a reply - starts with SIP/2.0 */
120                 if(m == 0) {
121                         if(*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
122                                 continue;
123                         if(buf + len - p < 10)
124                                 return -1;
125                         if(strncmp(p, "SIP/2.0 ", 8) == 0) {
126                                 LM_DBG("first line indicates a SIP reply\n");
127                                 return 0;
128                         }
129                         m = 1;
130                 } else {
131                         /* check if a request - before end of first line is SIP/2.0 */
132                         if(*p != '\r' && *p != '\n')
133                                 continue;
134                         if(p - 10 >= buf) {
135                                 if(strncmp(p - 8, " SIP/2.0", 8) == 0) {
136                                         LM_DBG("first line indicates a SIP request\n");
137                                         return 0;
138                                 }
139                         }
140                         return -1;
141                 }
142         }
143         return -1;
144 }
145
146 /**
147  *
148  */
149 static sr_net_info_t *ksr_evrt_rcvnetinfo = NULL;
150 int ksr_evrt_received_mode = 0;
151 str kemi_received_route_callback = STR_NULL;
152
153 /**
154  *
155  */
156 sr_net_info_t *ksr_evrt_rcvnetinfo_get(void)
157 {
158         return ksr_evrt_rcvnetinfo;
159 }
160
161 /**
162  *
163  */
164 int ksr_evrt_received(char *buf, unsigned int len, receive_info_t *rcv_info)
165 {
166         sr_kemi_eng_t *keng = NULL;
167         sr_net_info_t netinfo;
168         int ret = 0;
169         int rt = -1;
170         run_act_ctx_t ra_ctx;
171         run_act_ctx_t *bctx = NULL;
172         sip_msg_t *fmsg = NULL;
173         str evname = str_init("core:msg-received");
174
175         if(len==0 || rcv_info==NULL || buf==NULL) {
176                 LM_ERR("required parameters are not available\n");
177                 return -1;
178         }
179
180         if(kemi_received_route_callback.len>0) {
181                 keng = sr_kemi_eng_get();
182                 if(keng == NULL) {
183                         LM_DBG("kemi enabled with no core:msg-receive event route callback\n");
184                         return 0;
185                 }
186         } else {
187                 rt = route_lookup(&event_rt, evname.s);
188                 if (rt < 0 || event_rt.rlist[rt] == NULL) {
189                         LM_DBG("event route core:msg-received not defined\n");
190                         return 0;
191                 }
192         }
193         memset(&netinfo, 0, sizeof(sr_net_info_t));
194         netinfo.data.s = buf;
195         netinfo.data.len = len;
196         netinfo.rcv = rcv_info;
197
198         ksr_evrt_rcvnetinfo = &netinfo;
199         set_route_type(REQUEST_ROUTE);
200         fmsg = faked_msg_get_next();
201         init_run_actions_ctx(&ra_ctx);
202         if(keng) {
203                 bctx = sr_kemi_act_ctx_get();
204                 sr_kemi_act_ctx_set(&ra_ctx);
205                 ret=sr_kemi_route(keng, fmsg, REQUEST_ROUTE,
206                                 &kemi_received_route_callback, NULL);
207                 sr_kemi_act_ctx_set(bctx);
208         } else {
209                 ret=run_actions(&ra_ctx, event_rt.rlist[rt], fmsg);
210         }
211         if(ra_ctx.run_flags&DROP_R_F) {
212                 LM_DBG("dropping received message\n");
213                 ret = -1;
214         }
215         ksr_evrt_rcvnetinfo = NULL;
216
217         return ret;
218 }
219
220 /** Receive message
221  *  WARNING: buf must be 0 terminated (buf[len]=0) or some things might
222  * break (e.g.: modules/textops)
223  */
224 int receive_msg(char *buf, unsigned int len, struct receive_info *rcv_info)
225 {
226         struct sip_msg *msg;
227         struct run_act_ctx ctx;
228         struct run_act_ctx *bctx;
229         int ret;
230         struct timeval tvb, tve;
231         struct timezone tz;
232         unsigned int diff = 0;
233         str inb;
234         sr_net_info_t netinfo;
235         sr_kemi_eng_t *keng = NULL;
236         sr_event_param_t evp = {0};
237         unsigned int cidlockidx = 0;
238         unsigned int cidlockset = 0;
239         int errsipmsg = 0;
240         int exectime = 0;
241
242         if(ksr_evrt_received_mode!=0) {
243                 if(ksr_evrt_received(buf, len, rcv_info)<0) {
244                         LM_DBG("dropping the received message\n");
245                         goto error00;
246                 }
247         }
248         if(sr_event_enabled(SREV_NET_DATA_RECV)) {
249                 if(sip_check_fline(buf, len) == 0) {
250                         memset(&netinfo, 0, sizeof(sr_net_info_t));
251                         netinfo.data.s = buf;
252                         netinfo.data.len = len;
253                         netinfo.rcv = rcv_info;
254                         evp.data = (void *)&netinfo;
255                         sr_event_exec(SREV_NET_DATA_RECV, &evp);
256                 }
257         }
258
259         inb.s = buf;
260         inb.len = len;
261         evp.data = (void *)&inb;
262         evp.rcv = rcv_info;
263         sr_event_exec(SREV_NET_DATA_IN, &evp);
264         len = inb.len;
265
266         msg = pkg_malloc(sizeof(struct sip_msg));
267         if(unlikely(msg == 0)) {
268                 PKG_MEM_ERROR;
269                 goto error00;
270         }
271         msg_no++;
272         /* number of vias parsed -- good for diagnostic info in replies */
273         via_cnt = 0;
274
275         memset(msg, 0, sizeof(struct sip_msg)); /* init everything to 0 */
276         /* fill in msg */
277         msg->buf = buf;
278         msg->len = len;
279         /* zero termination (termination of orig message below not that
280          * useful as most of the work is done with scratch-pad; -jiri  */
281         /* buf[len]=0; */ /* WARNING: zero term removed! */
282         msg->rcv = *rcv_info;
283         msg->id = msg_no;
284         msg->pid = my_pid();
285         msg->set_global_address = default_global_address;
286         msg->set_global_port = default_global_port;
287
288         if(likely(sr_msg_time == 1))
289                 msg_set_time(msg);
290
291         if(parse_msg(buf, len, msg) != 0) {
292                 errsipmsg = 1;
293                 evp.data = (void *)msg;
294                 if((ret = sr_event_exec(SREV_RCV_NOSIP, &evp)) < NONSIP_MSG_DROP) {
295                         LM_DBG("attempt of nonsip message processing failed\n");
296                 } else if(ret == NONSIP_MSG_DROP) {
297                         LM_DBG("nonsip message processing completed\n");
298                         goto error02;
299                 }
300         }
301         if(errsipmsg==1) {
302                 LOG(cfg_get(core, core_cfg, corelog),
303                                 "core parsing of SIP message failed (%s:%d/%d)\n",
304                                 ip_addr2a(&msg->rcv.src_ip), (int)msg->rcv.src_port,
305                                 (int)msg->rcv.proto);
306                 sr_core_ert_run(msg, SR_CORE_ERT_RECEIVE_PARSE_ERROR);
307                 goto error02;
308         }
309
310         if(unlikely(parse_headers(msg, HDR_FROM_F | HDR_TO_F | HDR_CALLID_F | HDR_CSEQ_F, 0)
311                         < 0)) {
312                 LM_WARN("parsing relevant headers failed\n");
313         }
314         LM_DBG("--- received sip message - %s - call-id: [%.*s] - cseq: [%.*s]\n",
315                         (msg->first_line.type == SIP_REQUEST) ? "request" : "reply",
316                         (msg->callid && msg->callid->body.s) ? msg->callid->body.len : 0,
317                         (msg->callid && msg->callid->body.s) ? msg->callid->body.s : "",
318                         (msg->cseq && msg->cseq->body.s) ? msg->cseq->body.len : 0,
319                         (msg->cseq && msg->cseq->body.s) ? msg->cseq->body.s : "");
320
321         /* set log prefix */
322         log_prefix_set(msg);
323
324         /* ... clear branches from previous message */
325         clear_branches();
326
327         if(unlikely(ksr_route_locks_set!=NULL && msg->callid && msg->callid->body.s
328                         && msg->callid->body.len >0)) {
329                 cidlockidx = get_hash1_raw(msg->callid->body.s, msg->callid->body.len);
330                 cidlockidx = cidlockidx % ksr_route_locks_set->size;
331                 cidlockset = 1;
332         }
333
334
335         if(is_printable(cfg_get(core, core_cfg, latency_cfg_log))) {
336                 exectime = 1;
337         }
338
339         if(msg->first_line.type == SIP_REQUEST) {
340                 ruri_mark_new(); /* ruri is usable for forking (not consumed yet) */
341                 if(!IS_SIP(msg)) {
342                         if((ret = nonsip_msg_run_hooks(msg)) != NONSIP_MSG_ACCEPT) {
343                                 if(unlikely(ret == NONSIP_MSG_ERROR))
344                                         goto error03;
345                                 goto end; /* drop the message */
346                         }
347                 }
348                 /* sanity checks */
349                 if(unlikely((msg->via1 == 0) || (msg->via1->error != PARSE_OK))) {
350                         /* no via, send back error ? */
351                         LM_ERR("no via found in request\n");
352                         STATS_BAD_MSG();
353                         goto error02;
354                 }
355 /* check if necessary to add receive?->moved to forward_req */
356 /* check for the alias stuff */
357 #ifdef USE_TCP
358                 if(msg->via1->alias && cfg_get(tcp, tcp_cfg, accept_aliases)
359                                 && (((rcv_info->proto == PROTO_TCP) && !tcp_disable)
360 #ifdef USE_TLS
361                                                    || ((rcv_info->proto == PROTO_TLS) && !tls_disable)
362 #endif
363                                                                    )) {
364                         if(tcpconn_add_alias(rcv_info->proto_reserved1, msg->via1->port,
365                                            rcv_info->proto)
366                                         != 0) {
367                                 LM_ERR("tcp alias failed\n");
368                                 /* continue */
369                         }
370                 }
371 #endif
372
373                 /*      skip: */
374                 LM_DBG("preparing to run routing scripts...\n");
375                 if(exectime) {
376                         gettimeofday(&tvb, &tz);
377                 }
378                 /* execute pre-script callbacks, if any; -jiri */
379                 /* if some of the callbacks said not to continue with
380                  * script processing, don't do so
381                  * if we are here basic sanity checks are already done
382                  * (like presence of at least one via), so you can count
383                  * on via1 being parsed in a pre-script callback --andrei
384                 */
385                 if(exec_pre_script_cb(msg, REQUEST_CB_TYPE) == 0) {
386                         STATS_REQ_FWD_DROP();
387                         goto end; /* drop the request */
388                 }
389
390                 set_route_type(REQUEST_ROUTE);
391                 /* exec the routing script */
392                 if(unlikely(main_rt.rlist[DEFAULT_RT] == NULL)) {
393                         keng = sr_kemi_eng_get();
394                         if(keng == NULL) {
395                                 LM_ERR("no request_route {...} and no other config routing"
396                                                 " engine registered\n");
397                                 goto error_req;
398                         }
399                         if(unlikely(cidlockset)) {
400                                 rec_lock_set_get(ksr_route_locks_set, cidlockidx);
401                                 if(sr_kemi_route(keng, msg, REQUEST_ROUTE, NULL, NULL) < 0)
402                                         LM_NOTICE("negative return code from engine function\n");
403                                 rec_lock_set_release(ksr_route_locks_set, cidlockidx);
404                         } else {
405                                 if(sr_kemi_route(keng, msg, REQUEST_ROUTE, NULL, NULL) < 0)
406                                         LM_NOTICE("negative return code from engine function\n");
407                         }
408                 } else {
409                         if(unlikely(cidlockset)) {
410                                 rec_lock_set_get(ksr_route_locks_set, cidlockidx);
411                                 if(run_top_route(main_rt.rlist[DEFAULT_RT], msg, 0) < 0) {
412                                         rec_lock_set_release(ksr_route_locks_set, cidlockidx);
413                                         LM_WARN("error while trying script\n");
414                                         goto error_req;
415                                 }
416                                 rec_lock_set_release(ksr_route_locks_set, cidlockidx);
417                         } else {
418                                 if(run_top_route(main_rt.rlist[DEFAULT_RT], msg, 0) < 0) {
419                                         LM_WARN("error while trying script\n");
420                                         goto error_req;
421                                 }
422                         }
423                 }
424
425                 if(exectime) {
426                         gettimeofday(&tve, &tz);
427                         diff = (tve.tv_sec - tvb.tv_sec) * 1000000
428                                    + (tve.tv_usec - tvb.tv_usec);
429                         if (cfg_get(core, core_cfg, latency_limit_cfg) == 0
430                                         || cfg_get(core, core_cfg, latency_limit_cfg) <= diff) {
431                                 LOG(cfg_get(core, core_cfg, latency_cfg_log),
432                                                 "request-route executed in: %d usec\n", diff);
433                         }
434                 }
435
436                 /* execute post request-script callbacks */
437                 exec_post_script_cb(msg, REQUEST_CB_TYPE);
438         } else if(msg->first_line.type == SIP_REPLY) {
439                 /* sanity checks */
440                 if((msg->via1 == 0) || (msg->via1->error != PARSE_OK)) {
441                         /* no via, send back error ? */
442                         LM_ERR("no via found in reply\n");
443                         STATS_BAD_RPL();
444                         goto error02;
445                 }
446
447                 if(exectime) {
448                         gettimeofday(&tvb, &tz);
449                 }
450
451                 /* execute pre-script callbacks, if any; -jiri */
452                 /* if some of the callbacks said not to continue with
453                  * script processing, don't do so
454                  * if we are here basic sanity checks are already done
455                  * (like presence of at least one via), so you can count
456                  * on via1 being parsed in a pre-script callback --andrei
457                 */
458                 if(exec_pre_script_cb(msg, ONREPLY_CB_TYPE) == 0) {
459                         STATS_RPL_FWD_DROP();
460                         goto end; /* drop the reply */
461                 }
462
463                 /* exec the onreply routing script */
464                 if(kemi_reply_route_callback.len>0) {
465                         keng = sr_kemi_eng_get();
466                 }
467                 if(onreply_rt.rlist[DEFAULT_RT] != NULL || keng != NULL) {
468                         set_route_type(CORE_ONREPLY_ROUTE);
469                         ret = 1;
470                         if(unlikely(keng != NULL)) {
471                                 bctx = sr_kemi_act_ctx_get();
472                                 init_run_actions_ctx(&ctx);
473                                 sr_kemi_act_ctx_set(&ctx);
474                                 if(unlikely(cidlockset)) {
475                                         rec_lock_set_get(ksr_route_locks_set, cidlockidx);
476                                         ret = sr_kemi_route(keng, msg, CORE_ONREPLY_ROUTE, NULL, NULL);
477                                         rec_lock_set_release(ksr_route_locks_set, cidlockidx);
478                                 } else {
479                                         ret = sr_kemi_route(keng, msg, CORE_ONREPLY_ROUTE, NULL, NULL);
480                                 }
481                                 sr_kemi_act_ctx_set(bctx);
482                         } else {
483                                 if(unlikely(cidlockset)) {
484                                         rec_lock_set_get(ksr_route_locks_set, cidlockidx);
485                                         ret = run_top_route(onreply_rt.rlist[DEFAULT_RT], msg, &ctx);
486                                         rec_lock_set_release(ksr_route_locks_set, cidlockidx);
487                                 } else  {
488                                         ret = run_top_route(onreply_rt.rlist[DEFAULT_RT], msg, &ctx);
489                                 }
490                         }
491 #ifndef NO_ONREPLY_ROUTE_ERROR
492                         if(unlikely(ret < 0)) {
493                                 LM_WARN("error while trying onreply script\n");
494                                 goto error_rpl;
495                         } else
496 #endif /* NO_ONREPLY_ROUTE_ERROR */
497                                 if(unlikely(ret == 0 || (ctx.run_flags & DROP_R_F))) {
498                                         STATS_RPL_FWD_DROP();
499                                         LM_DBG("drop flag set - skip forwarding the reply\n");
500                                         goto skip_send_reply; /* drop the message, no error */
501                                 }
502                 }
503                 /* send the msg */
504                 forward_reply(msg);
505         skip_send_reply:
506                 if(exectime) {
507                         gettimeofday(&tve, &tz);
508                         diff = (tve.tv_sec - tvb.tv_sec) * 1000000
509                                    + (tve.tv_usec - tvb.tv_usec);
510                         if (cfg_get(core, core_cfg, latency_limit_cfg) == 0
511                                         || cfg_get(core, core_cfg, latency_limit_cfg) <= diff) {
512                                 LOG(cfg_get(core, core_cfg, latency_cfg_log),
513                                                 "reply-route executed in: %d usec\n", diff);
514                         }
515                 }
516
517                 /* execute post reply-script callbacks */
518                 exec_post_script_cb(msg, ONREPLY_CB_TYPE);
519         }
520
521 end:
522         ksr_msg_env_reset();
523         LM_DBG("cleaning up\n");
524         free_sip_msg(msg);
525         pkg_free(msg);
526         /* reset log prefix */
527         log_prefix_set(NULL);
528         return 0;
529
530 #ifndef NO_ONREPLY_ROUTE_ERROR
531 error_rpl:
532         /* execute post reply-script callbacks */
533         exec_post_script_cb(msg, ONREPLY_CB_TYPE);
534         goto error02;
535 #endif /* NO_ONREPLY_ROUTE_ERROR */
536 error_req:
537         LM_DBG("error:...\n");
538         /* execute post request-script callbacks */
539         exec_post_script_cb(msg, REQUEST_CB_TYPE);
540 error03:
541 error02:
542         free_sip_msg(msg);
543         pkg_free(msg);
544 error00:
545         ksr_msg_env_reset();
546         /* reset log prefix */
547         log_prefix_set(NULL);
548         return -1;
549 }
550
551 /**
552  * clean up msg environment, such as avp and xavp lists
553  */
554 void ksr_msg_env_reset(void)
555 {
556         reset_avps();
557         xavp_reset_list();
558 }