e550f17d9cd7e934affc5ea6509a3bf538b6fc27
[sip-router] / src / modules / auth_diameter / tcp_comm.c
1 /*
2  * Digest Authentication - Diameter support
3  *
4  * Copyright (C) 2001-2003 FhG Fokus
5  *
6  * This file is part of Kamailio, a free SIP server.
7  *
8  * Kamailio is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  * 
13  * Kamailio is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License 
19  * along with this program; if not, write to the Free Software 
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <sys/time.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netdb.h> 
31 #include <errno.h>
32
33 /* memory management */
34 #include "../../core/mem/mem.h"
35
36 /* printing messages, dealing with strings and other utils */
37 #include "../../core/dprint.h"
38 #include "../../core/str.h"
39
40 /* headers defined by this module */
41 #include "auth_diameter.h"
42 #include "defs.h"
43 #include "tcp_comm.h"
44 #include "diameter_msg.h"
45
46 #define MAX_TRIES       10
47
48 /* it initializes the TCP connection */ 
49 int init_mytcp(char* host, int port)
50 {
51         int sockfd;
52         struct sockaddr_in serv_addr;
53         struct hostent *server;
54     
55         sockfd = socket(PF_INET, SOCK_STREAM, 0);
56         
57     if (sockfd < 0) 
58         {
59                 LM_ERR("error creating the socket\n");
60                 return -1;
61         }       
62         
63     server = gethostbyname(host);
64     if (server == NULL) 
65         {
66                 LM_ERR("error finding the host\n");
67                 return -1;
68     }
69
70     memset((char *) &serv_addr, 0, sizeof(serv_addr));
71     serv_addr.sin_family = PF_INET;
72     memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr,
73                                         server->h_length);
74     serv_addr.sin_port = htons(port);
75         
76     if (connect(sockfd, (const struct sockaddr *)&serv_addr, 
77                                                         sizeof(serv_addr)) < 0) 
78         {
79         LM_ERR("error connecting to the "
80                                                 "DIAMETER client\n");
81                 return -1;
82         }       
83
84         return sockfd;
85 }
86
87
88
89 void reset_read_buffer(rd_buf_t *rb)
90 {
91         rb->ret_code            = 0;
92         rb->chall_len           = 0;
93         if(rb->chall)
94                 pkg_free(rb->chall);
95         rb->chall                       = 0;
96
97         rb->first_4bytes        = 0;
98         rb->buf_len                     = 0;
99         if(rb->buf)
100                 pkg_free(rb->buf);
101         rb->buf                         = 0;
102 }
103
104 /* read from a socket, an AAA message buffer */
105 int do_read( int socket, rd_buf_t *p)
106 {
107         unsigned char  *ptr;
108         unsigned int   wanted_len, len;
109         int n;
110
111         if (p->buf==0)
112         {
113                 wanted_len = sizeof(p->first_4bytes) - p->buf_len;
114                 ptr = ((unsigned char*)&(p->first_4bytes)) + p->buf_len;
115         }
116         else
117         {
118                 wanted_len = p->first_4bytes - p->buf_len;
119                 ptr = p->buf + p->buf_len;
120         }
121
122         while( (n=recv( socket, ptr, wanted_len, MSG_DONTWAIT ))>0 ) 
123         {
124 //              LM_DBG("(sock=%d)  -> n=%d (expected=%d)\n", p->sock,n,wanted_len);
125                 p->buf_len += n;
126                 if (n<wanted_len)
127                 {
128                         //LM_DBG("only %d bytes read from %d expected\n",n,wanted_len);
129                         wanted_len -= n;
130                         ptr += n;
131                 }
132                 else 
133                 {
134                         if (p->buf==0)
135                         {
136                                 /* I just finished reading the first 4 bytes from msg */
137                                 len = ntohl(p->first_4bytes)&0x00ffffff;
138                                 if (len<AAA_MSG_HDR_SIZE || len>MAX_AAA_MSG_SIZE)
139                                 {
140                                         LM_ERR(" (sock=%d): invalid message "
141                                                 "length read %u (%x)\n", socket, len, p->first_4bytes);
142                                         goto error;
143                                 }
144                                 //LM_DBG("message length = %d(%x)\n",len,len);
145                                 if ( (p->buf=pkg_malloc(len))==0  )
146                                 {
147                                         LM_ERR("no more pkg memory\n");
148                                         goto error;
149                                 }
150                                 *((unsigned int*)p->buf) = p->first_4bytes;
151                                 p->buf_len = sizeof(p->first_4bytes);
152                                 p->first_4bytes = len;
153                                 /* update the reading position and len */
154                                 ptr = p->buf + p->buf_len;
155                                 wanted_len = p->first_4bytes - p->buf_len;
156                         }
157                         else
158                         {
159                                 /* I finished reading the whole message */
160                                 LM_DBG("(sock=%d): whole message read (len=%d)!\n",
161                                         socket, p->first_4bytes);
162                                 return CONN_SUCCESS;
163                         }
164                 }
165         }
166
167         if (n==0)
168         {
169                 LM_INFO("(sock=%d): FIN received\n", socket);
170                 return CONN_CLOSED;
171         }
172         if ( n==-1 && errno!=EINTR && errno!=EAGAIN )
173         {
174                 LM_ERR(" (sock=%d): n=%d , errno=%d (%s)\n",
175                         socket, n, errno, strerror(errno));
176                 goto error;
177         }
178 error:
179         return CONN_ERROR;
180 }
181
182
183 /* send a message over an already opened TCP connection */
184 int tcp_send_recv(int sockfd, char* buf, int len, rd_buf_t* rb, 
185                                         unsigned int waited_id)
186 {
187         int n, number_of_tries;
188         fd_set active_fd_set, read_fd_set;
189         struct timeval tv;
190         unsigned long int result_code;
191         AAAMessage *msg;
192         AAA_AVP *avp;
193         char serviceType;
194         unsigned int m_id;
195
196         /* try to write the message to the Diameter client */
197         while( (n=write(sockfd, buf, len))==-1 ) 
198         {
199                 if (errno==EINTR)
200                         continue;
201                 LM_ERR("write returned error: %s\n", strerror(errno));
202                 return AAA_ERROR;
203         }
204
205         if (n!=len) 
206         {
207                 LM_ERR("write gave no error but wrote less than asked\n");
208                 return AAA_ERROR;
209         }
210
211         /* wait for the answer a limited amount of time */
212         tv.tv_sec = MAX_WAIT_SEC;
213         tv.tv_usec = MAX_WAIT_USEC;
214
215         /* Initialize the set of active sockets. */
216         FD_ZERO (&active_fd_set);
217         FD_SET (sockfd, &active_fd_set);
218         number_of_tries = 0;
219
220         while(number_of_tries<MAX_TRIES)
221         {
222                 read_fd_set = active_fd_set;
223                 if (select (sockfd+1, &read_fd_set, NULL, NULL, &tv) < 0)
224                 {
225                         LM_ERR("select function failed\n");
226                         return AAA_ERROR;
227                 }
228 /*
229                 if (!FD_ISSET (sockfd, &read_fd_set))
230                 {
231                         LM_ERR("no response message received\n");
232 //                      return AAA_ERROR;
233                 }
234 */
235                 /* Data arriving on a already-connected socket. */
236                 reset_read_buffer(rb);
237                 switch( do_read(sockfd, rb) )
238                 {
239                         case CONN_ERROR:
240                                 LM_ERR("error when trying to read from socket\n");
241                                 return AAA_CONN_CLOSED;
242                         case CONN_CLOSED:
243                                 LM_ERR("connection closed by diameter client!\n");
244                                 return AAA_CONN_CLOSED;
245                 }
246                 
247                 /* obtain the structure corresponding to the message */
248                 msg = AAATranslateMessage(rb->buf, rb->buf_len, 0);     
249                 if(!msg)
250                 {
251                         LM_ERR("message structure not obtained\n");     
252                         return AAA_ERROR;
253                 }
254                 avp = AAAFindMatchingAVP(msg, NULL, AVP_SIP_MSGID,
255                                                                 vendorID, AAA_FORWARD_SEARCH);
256                 if(!avp)
257                 {
258                         LM_ERR("AVP_SIP_MSGID not found\n");
259                         return AAA_ERROR;
260                 }
261                 m_id = *((unsigned int*)(avp->data.s));
262                 LM_DBG("######## m_id=%d\n", m_id);
263                 if(m_id!=waited_id)
264                 {
265                         number_of_tries ++;
266                         LM_NOTICE("old message received\n");
267                         continue;
268                 }
269                 goto next;
270         }
271
272         LM_ERR("too many old messages received\n");
273         return AAA_TIMEOUT;
274 next:
275         /* Finally die correct answer */
276         avp = AAAFindMatchingAVP(msg, NULL, AVP_Service_Type,
277                                                         vendorID, AAA_FORWARD_SEARCH);
278         if(!avp)
279         {
280                 LM_ERR("AVP_Service_Type not found\n");
281                 return AAA_ERROR;
282         }
283         serviceType = avp->data.s[0];
284
285         result_code = ntohl(*((unsigned long int*)(msg->res_code->data.s)));
286         switch(result_code)
287         {
288                 case AAA_SUCCESS:                                       /* 2001 */
289                         rb->ret_code = AAA_AUTHORIZED;
290                         break;
291                 case AAA_AUTHENTICATION_REJECTED:       /* 4001 */
292                         if(serviceType!=SIP_AUTH_SERVICE)
293                         {
294                                 rb->ret_code = AAA_NOT_AUTHORIZED;
295                                 break;
296                         }
297                         avp = AAAFindMatchingAVP(msg, NULL, AVP_Challenge,
298                                                         vendorID, AAA_FORWARD_SEARCH);
299                         if(!avp)
300                         {
301                                 LM_ERR("AVP_Response not found\n");
302                                 rb->ret_code = AAA_SRVERR;
303                                 break;
304                         }
305                         rb->chall_len=avp->data.len;
306                         rb->chall = (unsigned char*)pkg_malloc(avp->data.len*sizeof(unsigned char));
307                         if(rb->chall == NULL)
308                         {
309                                 LM_ERR("no more pkg memory\n");
310                                 rb->ret_code = AAA_SRVERR;
311                                 break;
312                         }
313                         memcpy(rb->chall, avp->data.s, avp->data.len);
314                         rb->ret_code = AAA_CHALENGE;
315                         break;
316                 case AAA_AUTHORIZATION_REJECTED:        /* 5003 */
317                         rb->ret_code = AAA_NOT_AUTHORIZED;
318                         break;
319                 default:                                                        /* error */
320                         rb->ret_code = AAA_SRVERR;
321         }
322         
323     return rb->ret_code;        
324 }
325 void close_tcp_connection(int sfd)
326 {
327         shutdown(sfd, 2);
328 }
329
330