Merge pull request #1105 from sergey-safarov/spec_update9
[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 "stats.h"
43 #include "ip_addr.h"
44 #include "script_cb.h"
45 #include "nonsip_hooks.h"
46 #include "dset.h"
47 #include "usr_avp.h"
48 #ifdef WITH_XAVP
49 #include "xavp.h"
50 #endif
51 #include "select_buf.h"
52
53 #include "tcp_server.h" /* for tcpconn_add_alias */
54 #include "tcp_options.h" /* for access to tcp_accept_aliases*/
55 #include "cfg/cfg.h"
56 #include "core_stats.h"
57 #include "kemi.h"
58
59 #ifdef DEBUG_DMALLOC
60 #include <mem/dmalloc.h>
61 #endif
62
63 int _sr_ip_free_bind = 0;
64
65 unsigned int msg_no=0;
66 /* address preset vars */
67 str default_global_address={0,0};
68 str default_global_port={0,0};
69 str default_via_address={0,0};
70 str default_via_port={0,0};
71
72 /**
73  * increment msg_no and return the new value
74  */
75 unsigned int inc_msg_no(void)
76 {
77         return ++msg_no;
78 }
79
80 /**
81  *
82  */
83 int sip_check_fline(char* buf, unsigned int len)
84 {
85         char *p;
86         int m;
87
88         m = 0;
89         for(p=buf; p<buf+len; p++) {
90                 /* first check if is a reply - starts with SIP/2.0 */
91                 if(m==0) {
92                         if(*p==' ' || *p=='\t' || *p=='\r' || *p=='\n') continue;
93                         if(buf+len-p<10) return -1;
94                         if(strncmp(p, "SIP/2.0 ", 8)==0) {
95                                 LM_DBG("first line indicates a SIP reply\n");
96                                 return 0;
97                         }
98                         m=1;
99                 } else {
100                         /* check if a request - before end of first line is SIP/2.0 */
101                         if(*p!='\r' && *p!='\n') continue;
102                         if(p-10>=buf) {
103                                 if(strncmp(p-8, " SIP/2.0", 8)==0) {
104                                         LM_DBG("first line indicates a SIP request\n");
105                                         return 0;
106                                 }
107                         }
108                         return -1;
109                 }
110         }
111         return -1;
112 }
113
114 /** Receive message
115  *  WARNING: buf must be 0 terminated (buf[len]=0) or some things might
116  * break (e.g.: modules/textops)
117  */
118 int receive_msg(char* buf, unsigned int len, struct receive_info* rcv_info)
119 {
120         struct sip_msg* msg;
121         struct run_act_ctx ctx;
122         struct run_act_ctx *bctx;
123         int ret;
124 #ifdef STATS
125         int skipped = 1;
126         int stats_on = 1;
127 #else
128         int stats_on = 0;
129 #endif
130         struct timeval tvb, tve;
131         struct timezone tz;
132         unsigned int diff = 0;
133         str inb;
134         sr_net_info_t netinfo;
135         sr_kemi_eng_t *keng = NULL;
136
137         if(sr_event_enabled(SREV_NET_DATA_RECV)) {
138                 if(sip_check_fline(buf, len)==0) {
139                         memset(&netinfo, 0, sizeof(sr_net_info_t));
140                         netinfo.data.s = buf;
141                         netinfo.data.len = len;
142                         netinfo.rcv = rcv_info;
143                         sr_event_exec(SREV_NET_DATA_RECV, (void*)&netinfo);
144                 }
145         }
146
147         inb.s = buf;
148         inb.len = len;
149         sr_event_exec(SREV_NET_DATA_IN, (void*)&inb);
150         len = inb.len;
151
152         msg=pkg_malloc(sizeof(struct sip_msg));
153         if (msg==0) {
154                 LM_ERR("no mem for sip_msg\n");
155                 goto error00;
156         }
157         msg_no++;
158         /* number of vias parsed -- good for diagnostic info in replies */
159         via_cnt=0;
160
161         memset(msg,0, sizeof(struct sip_msg)); /* init everything to 0 */
162         /* fill in msg */
163         msg->buf=buf;
164         msg->len=len;
165         /* zero termination (termination of orig message bellow not that
166          * useful as most of the work is done with scratch-pad; -jiri  */
167         /* buf[len]=0; */ /* WARNING: zero term removed! */
168         msg->rcv=*rcv_info;
169         msg->id=msg_no;
170         msg->pid=my_pid();
171         msg->set_global_address=default_global_address;
172         msg->set_global_port=default_global_port;
173
174         if(likely(sr_msg_time==1)) msg_set_time(msg);
175
176         if (parse_msg(buf,len, msg)!=0){
177                 if((ret=sr_event_exec(SREV_RCV_NOSIP, (void*)msg))<NONSIP_MSG_DROP) {
178                         LOG(cfg_get(core, core_cfg, corelog),
179                                 "core parsing of SIP message failed (%s:%d/%d)\n",
180                                 ip_addr2a(&msg->rcv.src_ip), (int)msg->rcv.src_port,
181                                 (int)msg->rcv.proto);
182                         sr_core_ert_run(msg, SR_CORE_ERT_RECEIVE_PARSE_ERROR);
183                 }
184                 else if(ret == NONSIP_MSG_DROP) goto error02;
185         }
186
187         parse_headers(msg, HDR_FROM_F|HDR_TO_F|HDR_CALLID_F|HDR_CSEQ_F, 0);
188         LM_DBG("--- received sip message - %s - call-id: [%.*s] - cseq: [%.*s]\n",
189                         (msg->first_line.type==SIP_REQUEST)?"request":"reply",
190                         (msg->callid && msg->callid->body.s)?msg->callid->body.len:0,
191                         (msg->callid && msg->callid->body.s)?msg->callid->body.s:"",
192                         (msg->cseq && msg->cseq->body.s)?msg->cseq->body.len:0,
193                         (msg->cseq && msg->cseq->body.s)?msg->cseq->body.s:"");
194
195         /* set log prefix */
196         log_prefix_set(msg);
197
198         /* ... clear branches from previous message */
199         clear_branches();
200
201         if (msg->first_line.type==SIP_REQUEST){
202                 ruri_mark_new(); /* ruri is usable for forking (not consumed yet) */
203                 if (!IS_SIP(msg)){
204                         if ((ret=nonsip_msg_run_hooks(msg))!=NONSIP_MSG_ACCEPT){
205                                 if (unlikely(ret==NONSIP_MSG_ERROR))
206                                         goto error03;
207                                 goto end; /* drop the message */
208                         }
209                 }
210                 /* sanity checks */
211                 if ((msg->via1==0) || (msg->via1->error!=PARSE_OK)){
212                         /* no via, send back error ? */
213                         LM_ERR("no via found in request\n");
214                         STATS_BAD_MSG();
215                         goto error02;
216                 }
217                 /* check if necessary to add receive?->moved to forward_req */
218                 /* check for the alias stuff */
219 #ifdef USE_TCP
220                 if (msg->via1->alias && cfg_get(tcp, tcp_cfg, accept_aliases) &&
221                                 (((rcv_info->proto==PROTO_TCP) && !tcp_disable)
222 #ifdef USE_TLS
223                                         || ((rcv_info->proto==PROTO_TLS) && !tls_disable)
224 #endif
225                                 )
226                         ){
227                         if (tcpconn_add_alias(rcv_info->proto_reserved1, msg->via1->port,
228                                                                         rcv_info->proto)!=0){
229                                 LM_ERR("tcp alias failed\n");
230                                 /* continue */
231                         }
232                 }
233 #endif
234
235         /*      skip: */
236                 LM_DBG("preparing to run routing scripts...\n");
237                 if(is_printable(cfg_get(core, core_cfg, latency_cfg_log))
238                                 || stats_on==1) {
239                         gettimeofday( & tvb, &tz );
240                 }
241                 /* execute pre-script callbacks, if any; -jiri */
242                 /* if some of the callbacks said not to continue with
243                  * script processing, don't do so
244                  * if we are here basic sanity checks are already done
245                  * (like presence of at least one via), so you can count
246                  * on via1 being parsed in a pre-script callback --andrei
247                 */
248                 if (exec_pre_script_cb(msg, REQUEST_CB_TYPE)==0 )
249                 {
250                         STATS_REQ_FWD_DROP();
251                         goto end; /* drop the request */
252                 }
253
254                 set_route_type(REQUEST_ROUTE);
255                 /* exec the routing script */
256                 if(unlikely(main_rt.rlist[DEFAULT_RT]==NULL)) {
257                         keng = sr_kemi_eng_get();
258                         if(keng==NULL) {
259                                 LM_ERR("no config routing engine registered\n");
260                                 goto error_req;
261                         }
262                         if(keng->froute(msg, REQUEST_ROUTE, NULL, NULL)<0) {
263                                 LM_NOTICE("negative return code from engine function\n");
264                         }
265                 } else {
266                         if (run_top_route(main_rt.rlist[DEFAULT_RT], msg, 0)<0){
267                                 LM_WARN("error while trying script\n");
268                                 goto error_req;
269                         }
270                 }
271
272                 if(is_printable(cfg_get(core, core_cfg, latency_cfg_log))
273                                 || stats_on==1) {
274                         gettimeofday( & tve, &tz );
275                         diff = (tve.tv_sec-tvb.tv_sec)*1000000+(tve.tv_usec-tvb.tv_usec);
276                         LOG(cfg_get(core, core_cfg, latency_cfg_log),
277                                         "request-route executed in: %d usec\n", diff);
278 #ifdef STATS
279                         stats->processed_requests++;
280                         stats->acc_req_time += diff;
281                         STATS_RX_REQUEST( msg->first_line.u.request.method_value );
282 #endif
283                 }
284
285                 /* execute post request-script callbacks */
286                 exec_post_script_cb(msg, REQUEST_CB_TYPE);
287         }else if (msg->first_line.type==SIP_REPLY){
288                 /* sanity checks */
289                 if ((msg->via1==0) || (msg->via1->error!=PARSE_OK)){
290                         /* no via, send back error ? */
291                         LM_ERR("no via found in reply\n");
292                         STATS_BAD_RPL();
293                         goto error02;
294                 }
295
296                 if(is_printable(cfg_get(core, core_cfg, latency_cfg_log))
297                                 || stats_on==1) {
298                         gettimeofday( & tvb, &tz );
299                 }
300 #ifdef STATS
301                 STATS_RX_RESPONSE ( msg->first_line.u.reply.statuscode / 100 );
302 #endif
303
304                 /* execute pre-script callbacks, if any; -jiri */
305                 /* if some of the callbacks said not to continue with
306                  * script processing, don't do so
307                  * if we are here basic sanity checks are already done
308                  * (like presence of at least one via), so you can count
309                  * on via1 being parsed in a pre-script callback --andrei
310                 */
311                 if (exec_pre_script_cb(msg, ONREPLY_CB_TYPE)==0 )
312                 {
313                         STATS_RPL_FWD_DROP();
314                         goto end; /* drop the reply */
315                 }
316
317                 /* exec the onreply routing script */
318                 keng = sr_kemi_eng_get();
319                 if (onreply_rt.rlist[DEFAULT_RT]!=NULL || keng!=NULL){
320                         set_route_type(CORE_ONREPLY_ROUTE);
321                         ret = 1;
322                         if(unlikely(keng!=NULL)) {
323                                 bctx = sr_kemi_act_ctx_get();
324                                 init_run_actions_ctx(&ctx);
325                                 sr_kemi_act_ctx_set(&ctx);
326                                 ret = keng->froute(msg, CORE_ONREPLY_ROUTE, NULL, NULL);
327                                 sr_kemi_act_ctx_set(bctx);
328                         } else {
329                                 ret=run_top_route(onreply_rt.rlist[DEFAULT_RT], msg, &ctx);
330                         }
331 #ifndef NO_ONREPLY_ROUTE_ERROR
332                         if (unlikely(ret<0)){
333                                 LM_WARN("error while trying onreply script\n");
334                                 goto error_rpl;
335                         }else
336 #endif /* NO_ONREPLY_ROUTE_ERROR */
337                         if (unlikely(ret==0 || (ctx.run_flags&DROP_R_F))){
338                                 STATS_RPL_FWD_DROP();
339                                 goto skip_send_reply; /* drop the message, no error */
340                         }
341                 }
342                 /* send the msg */
343                 forward_reply(msg);
344         skip_send_reply:
345                 if(is_printable(cfg_get(core, core_cfg, latency_cfg_log))
346                                 || stats_on==1) {
347                         gettimeofday( & tve, &tz );
348                         diff = (tve.tv_sec-tvb.tv_sec)*1000000+(tve.tv_usec-tvb.tv_usec);
349                         LOG(cfg_get(core, core_cfg, latency_cfg_log),
350                                         "reply-route executed in: %d usec\n", diff);
351 #ifdef STATS
352                         stats->processed_responses++;
353                         stats->acc_res_time+=diff;
354 #endif
355                 }
356
357                 /* execute post reply-script callbacks */
358                 exec_post_script_cb(msg, ONREPLY_CB_TYPE);
359         }
360
361 end:
362 #ifdef STATS
363         skipped = 0;
364 #endif
365         /* free possible loaded avps -bogdan */
366         reset_avps();
367 #ifdef WITH_XAVP
368         xavp_reset_list();
369 #endif
370         LM_DBG("cleaning up\n");
371         free_sip_msg(msg);
372         pkg_free(msg);
373 #ifdef STATS
374         if (skipped) STATS_RX_DROPS;
375 #endif
376         /* reset log prefix */
377         log_prefix_set(NULL);
378         return 0;
379
380 #ifndef NO_ONREPLY_ROUTE_ERROR
381 error_rpl:
382         /* execute post reply-script callbacks */
383         exec_post_script_cb(msg, ONREPLY_CB_TYPE);
384         reset_avps();
385 #ifdef WITH_XAVP
386         xavp_reset_list();
387 #endif
388         goto error02;
389 #endif /* NO_ONREPLY_ROUTE_ERROR */
390 error_req:
391         LM_DBG("error:...\n");
392         /* execute post request-script callbacks */
393         exec_post_script_cb(msg, REQUEST_CB_TYPE);
394 error03:
395         /* free possible loaded avps -bogdan */
396         reset_avps();
397 #ifdef WITH_XAVP
398         xavp_reset_list();
399 #endif
400 error02:
401         free_sip_msg(msg);
402         pkg_free(msg);
403 error00:
404         STATS_RX_DROPS;
405         /* reset log prefix */
406         log_prefix_set(NULL);
407         return -1;
408 }
409