445e173835460ddd05ff280f40656ec94406b299
[sip-router] / receive.c
1 /* 
2  *$Id$
3  */
4
5 #include <string.h>
6
7 #include "receive.h"
8 #include "dprint.h"
9 #include "route.h"
10 #include "msg_parser.h"
11 #include "forward.h"
12
13
14 int receive_msg(char* buf, unsigned int len)
15 {
16         struct sip_msg msg;
17         struct route_elem *re;
18         char * orig;
19
20         /* make a copy of the message */
21         orig=(char*) malloc(len);
22         if (orig==0){
23                 DPrint("ERROR: memory allocation failure\n");
24                 goto error1;
25         }
26         memcpy(orig, buf, len);
27         
28         if (parse_msg(buf,len, &msg)!=0){
29                 goto error;
30         }
31         
32         if (msg.first_line.type==SIP_REQUEST){
33                 /* sanity checks */
34                 if (msg.via1.error!=VIA_PARSE_OK){
35                         /* no via, send back error ? */
36                         goto skip;
37                 }
38                 /* check if neccesarry to add receive? */
39                 
40                 /* find route */
41                 re=route_match(  msg.first_line.u.request.method,
42                                                  msg.first_line.u.request.uri,
43                                                  &rlist
44                                           );
45                 if (re==0){
46                         /* no route found, send back error msg? */
47                         DPrint("WARNING: no route found!\n");
48                         goto skip;
49                 }
50                 re->tx++;
51                 /* send msg */
52                 forward_request(orig, buf, len, &msg, re);
53                 DPrint(" found route to: %s\n", re->host.h_name);
54         }else if (msg.first_line.type==SIP_REPLY){
55                 /* sanity checks */
56                 if (msg.via1.error!=VIA_PARSE_OK){
57                         /* no via, send back error ? */
58                         goto skip;
59                 }
60                 if (msg.via2.error!=VIA_PARSE_OK){
61                         /* no second via => error? */
62                         goto skip;
63                 }
64                 /* check if via1 == us */
65                 
66                 /* send the msg */
67                 forward_reply(orig, buf, len, &msg);
68                 DPrint(" reply forwarded to %s:%d\n", 
69                                         msg.via2.host,
70                                         (unsigned short) msg.via2.port
71                                 );
72         }
73 skip:
74         free(orig);
75         return 0;
76 error:
77         free(orig);
78 error1:
79         return -1;
80 }
81