- Spelling checked
[sip-router] / udp_server.c
1 /*
2  * $Id$
3  *
4  * Copyright (C) 2001-2003 FhG Fokus
5  *
6  * This file is part of ser, a free SIP server.
7  *
8  * ser 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  * For a license to use the ser software under conditions
14  * other than those described here, or to purchase support for this
15  * software, please contact iptel.org by e-mail at the following addresses:
16  *    info@iptel.org
17  *
18  * ser is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License 
24  * along with this program; if not, write to the Free Software 
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  *
27  * History
28  * --------
29  *  2003-01-28  packet zero-termination moved to receive_msg (jiri)
30  *  2003-02-10  undoed the above changes (andrei)
31  *  2003-03-19  replaced all the mallocs/frees w/ pkg_malloc/pkg_free (andrei)
32  *  2003-04-14  set sockopts to TOS low delay (andrei)
33  *  2004-05-03  applied multicast support patch from janakj
34  *              added set multicast ttl support (andrei)
35  *  2004-07-05  udp_rcv_loop: drop packets with 0 src port + error msg.
36  *              cleanups (andrei)
37  */
38
39
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <errno.h>
48 #include <arpa/inet.h>
49 #ifdef __linux__
50         #include <linux/types.h>
51         #include <linux/errqueue.h>
52 #endif
53
54
55 #include "udp_server.h"
56 #include "globals.h"
57 #include "config.h"
58 #include "dprint.h"
59 #include "receive.h"
60 #include "mem/mem.h"
61 #include "ip_addr.h"
62
63
64 #ifdef DBG_MSG_QA
65 /* message quality assurance -- frequently, bugs in ser have
66    been indicated by zero characters or long whitespaces
67    in generated messages; this debugging option aborts if
68    any such message is sighted
69 */
70 static int dbg_msg_qa(char *buf, int len)
71 {
72 #define _DBG_WS_LEN 3
73 #define _DBG_WS "   "
74
75         char *scan;
76         int my_len;
77         int space_cnt;
78         enum { QA_ANY, QA_SPACE, QA_EOL1 } state;
79
80
81         /* is there a zero character in there ? */      
82         if (memchr(buf, 0, len)) {
83                 LOG(L_CRIT, "BUG: message with 0 in it\n");
84                 return 0;
85         }
86
87         my_len=len;
88         scan=buf;
89         state=QA_ANY;
90         space_cnt=0;
91
92         while(my_len) {
93                 switch(*scan) {
94                         case ' ':       if (state==QA_SPACE) {
95                                                         space_cnt++;
96                                                         if (space_cnt==4) {
97                                                                 LOG(L_CRIT, "BUG(probably): DBG_MSG_QA: "
98                                                                         "too many spaces\n");
99                                                                 return 0;
100                                                         }
101                                                 } else space_cnt=0;
102                                                 state=QA_SPACE; 
103                                                 break;
104
105                         case '\r':      /* ignore */
106                                                 space_cnt=0;
107                                                 break;
108
109                         case '\n': /* don't proceed to body on EoH */
110                                                 if (state==QA_EOL1) goto qa_passed;
111                                                 space_cnt=0;
112                                                 state=QA_EOL1;
113                                                 break;
114
115                         default:        space_cnt=0;
116                                                 state=QA_ANY;
117                                                 break;
118                 }
119                 scan++;
120                 my_len--;
121         }
122
123
124 qa_passed:
125         return 1;
126 }
127
128 #endif
129
130
131 int probe_max_receive_buffer( int udp_sock )
132 {
133         int optval;
134         int ioptval;
135         unsigned int ioptvallen;
136         int foptval;
137         unsigned int foptvallen;
138         int voptval;
139         unsigned int voptvallen;
140         int phase=0;
141
142         /* jku: try to increase buffer size as much as we can */
143         ioptvallen=sizeof(ioptval);
144         if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &ioptval,
145                     &ioptvallen) == -1 )
146         {
147                 LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
148                 return -1;
149         }
150         if ( ioptval==0 ) 
151         {
152                 LOG(L_DBG, "DEBUG: udp_init: SO_RCVBUF initially set to 0; resetting to %d\n",
153                         BUFFER_INCREMENT );
154                 ioptval=BUFFER_INCREMENT;
155         } else LOG(L_INFO, "INFO: udp_init: SO_RCVBUF is initially %d\n", ioptval );
156         for (optval=ioptval; ;  ) {
157                 /* increase size; double in initial phase, add linearly later */
158                 if (phase==0) optval <<= 1; else optval+=BUFFER_INCREMENT;
159                 if (optval > maxbuffer){
160                         if (phase==1) break; 
161                         else { phase=1; optval >>=1; continue; }
162                 }
163                 LOG(L_DBG, "DEBUG: udp_init: trying SO_RCVBUF: %d\n", optval );
164                 if (setsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF,
165                         (void*)&optval, sizeof(optval)) ==-1){
166                         /* Solaris returns -1 if asked size too big; Linux ignores */
167                         LOG(L_DBG, "DEBUG: udp_init: SOL_SOCKET failed"
168                                         " for %d, phase %d: %s\n", optval, phase, strerror(errno));
169                         /* if setting buffer size failed and still in the aggressive
170                            phase, try less aggressively; otherwise give up 
171                         */
172                         if (phase==0) { phase=1; optval >>=1 ; continue; } 
173                         else break;
174                 } 
175                 /* verify if change has taken effect */
176                 /* Linux note -- otherwise I would never know that; funny thing: Linux
177                    doubles size for which we asked in setsockopt
178                 */
179                 voptvallen=sizeof(voptval);
180                 if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &voptval,
181                     &voptvallen) == -1 )
182                 {
183                         LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
184                         return -1;
185                 } else {
186                         LOG(L_DBG, "DEBUG: setting SO_RCVBUF; set=%d,verify=%d\n", 
187                                 optval, voptval);
188                         if (voptval<optval) {
189                                 LOG(L_DBG, "DEBUG: setting SO_RCVBUF has no effect\n");
190                                 /* if setting buffer size failed and still in the aggressive
191                                 phase, try less aggressively; otherwise give up 
192                                 */
193                                 if (phase==0) { phase=1; optval >>=1 ; continue; } 
194                                 else break;
195                         } 
196                 }
197         
198         } /* for ... */
199         foptvallen=sizeof(foptval);
200         if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &foptval,
201                     &foptvallen) == -1 )
202         {
203                 LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
204                 return -1;
205         }
206         LOG(L_INFO, "INFO: udp_init: SO_RCVBUF is finally %d\n", foptval );
207
208         return 0;
209
210         /* EoJKU */
211 }
212
213
214 #ifdef USE_MCAST
215
216 /*
217  * Setup multicast receiver
218  */
219 static int setup_mcast_rcvr(int sock, union sockaddr_union* addr)
220 {
221         struct ip_mreq mreq;
222 #ifdef USE_IPV6
223         struct ipv6_mreq mreq6;
224 #endif /* USE_IPV6 */
225         
226         if (addr->s.sa_family==AF_INET){
227                 memcpy(&mreq.imr_multiaddr, &addr->sin.sin_addr, 
228                        sizeof(struct in_addr));
229                 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
230                 
231                 if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq,
232                                sizeof(mreq))==-1){
233                         LOG(L_ERR, "ERROR: setup_mcast_rcvr: setsockopt: %s\n",
234                             strerror(errno));
235                         return -1;
236                 }
237                 
238                 if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, 
239                                &mcast_loopback, sizeof(mcast_loopback))==-1){
240                         LOG(L_ERR, "ERROR: setup_mcast_rcvr: setsockopt: %s\n",
241                             strerror(errno));
242                         return -1;
243                 }
244                 if (mcast_ttl>=0){
245                         if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &mcast_ttl,
246                                                 sizeof(mcast_ttl))==-1){
247                                 LOG(L_ERR, "ERROR: setup_mcast_rcvr: setosckopt (ttl):"
248                                                 " %s\n", strerror(errno));
249                                 return -1;
250                         }
251                 }
252 #ifdef USE_IPV6
253         } else if (addr->s.sa_family==AF_INET6){
254                 memcpy(&mreq6.ipv6mr_multiaddr, &addr->sin6.sin6_addr, 
255                        sizeof(struct in6_addr));
256                 mreq6.ipv6mr_interface = 0;
257 #ifdef __OS_linux
258                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6,
259 #else
260                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6,
261 #endif
262                                sizeof(mreq6))==-1){
263                         LOG(L_ERR, "ERROR: setup_mcast_rcvr: setsockopt:%s\n",
264                             strerror(errno));
265                         return -1;
266                 }
267                 
268                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 
269                                &mcast_loopback, sizeof(mcast_loopback))==-1){
270                         LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", 
271                             strerror(errno));
272                         return -1;
273                 }
274                 if (mcast_ttl>=0){
275                         if (setsockopt(sock, IPPROTO_IP, IPV6_MULTICAST_HOPS, &mcast_ttl,
276                                                 sizeof(mcast_ttl))==-1){
277                                 LOG(L_ERR, "ERROR: setup_mcast_rcvr: setosckopt (ttlv6):"
278                                                 " %s\n", strerror(errno));
279                                 return -1;
280                         }
281                 }
282 #endif /* USE_IPV6 */
283         } else {
284                 LOG(L_ERR, "ERROR: udp_init: Unsupported protocol family\n");
285                 return -1;
286         }
287         return 0;
288 }
289
290 #endif /* USE_MCAST */
291
292
293 int udp_init(struct socket_info* sock_info)
294 {
295         union sockaddr_union* addr;
296         int optval;
297         addr=&sock_info->su;
298 /*
299         addr=(union sockaddr_union*)pkg_malloc(sizeof(union sockaddr_union));
300         if (addr==0){
301                 LOG(L_ERR, "ERROR: udp_init: out of memory\n");
302                 goto error;
303         }
304 */
305         sock_info->proto=PROTO_UDP;
306         if (init_su(addr, &sock_info->address, sock_info->port_no)<0){
307                 LOG(L_ERR, "ERROR: udp_init: could not init sockaddr_union\n");
308                 goto error;
309         }
310         
311         sock_info->socket = socket(AF2PF(addr->s.sa_family), SOCK_DGRAM, 0);
312         if (sock_info->socket==-1){
313                 LOG(L_ERR, "ERROR: udp_init: socket: %s\n", strerror(errno));
314                 goto error;
315         }
316         /* set sock opts? */
317         optval=1;
318         if (setsockopt(sock_info->socket, SOL_SOCKET, SO_REUSEADDR ,
319                                         (void*)&optval, sizeof(optval)) ==-1){
320                 LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror(errno));
321                 goto error;
322         }
323         /* tos */
324         optval=IPTOS_LOWDELAY;
325         if (setsockopt(sock_info->socket, IPPROTO_IP, IP_TOS, (void*)&optval, 
326                         sizeof(optval)) ==-1){
327                 LOG(L_WARN, "WARNING: udp_init: setsockopt tos: %s\n", strerror(errno));
328                 /* continue since this is not critical */
329         }
330 #if defined (__linux__) && defined(UDP_ERRORS)
331         optval=1;
332         /* enable error receiving on unconnected sockets */
333         if(setsockopt(sock_info->socket, SOL_IP, IP_RECVERR,
334                                         (void*)&optval, sizeof(optval)) ==-1){
335                 LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror(errno));
336                 goto error;
337         }
338 #endif
339
340 #ifdef USE_MCAST
341         if ((sock_info->flags & SI_IS_MCAST) 
342             && (setup_mcast_rcvr(sock_info->socket, addr)<0)){
343                         goto error;
344         }
345 #endif /* USE_MCAST */
346
347         if ( probe_max_receive_buffer(sock_info->socket)==-1) goto error;
348         
349         if (bind(sock_info->socket,  &addr->s, sockaddru_len(*addr))==-1){
350                 LOG(L_ERR, "ERROR: udp_init: bind(%x, %p, %d) on %s: %s\n",
351                                 sock_info->socket, &addr->s, 
352                                 sockaddru_len(*addr),
353                                 sock_info->address_str.s,
354                                 strerror(errno));
355         #ifdef USE_IPV6
356                 if (addr->s.sa_family==AF_INET6)
357                         LOG(L_ERR, "ERROR: udp_init: might be caused by using a link "
358                                         " local address, try site local or global\n");
359         #endif
360                 goto error;
361         }
362
363 /*      pkg_free(addr);*/
364         return 0;
365
366 error:
367 /*      if (addr) pkg_free(addr);*/
368         return -1;
369 }
370
371
372
373 int udp_rcv_loop()
374 {
375         unsigned len;
376 #ifdef DYN_BUF
377         char* buf;
378 #else
379         static char buf [BUF_SIZE+1];
380 #endif
381         char *tmp;
382         union sockaddr_union* from;
383         unsigned int fromlen;
384         struct receive_info ri;
385
386
387         from=(union sockaddr_union*) pkg_malloc(sizeof(union sockaddr_union));
388         if (from==0){
389                 LOG(L_ERR, "ERROR: udp_rcv_loop: out of memory\n");
390                 goto error;
391         }
392         memset(from, 0 , sizeof(union sockaddr_union));
393         ri.bind_address=bind_address; /* this will not change, we do it only once*/
394         ri.dst_port=bind_address->port_no;
395         ri.dst_ip=bind_address->address;
396         ri.proto=PROTO_UDP;
397         ri.proto_reserved1=ri.proto_reserved2=0;
398         for(;;){
399 #ifdef DYN_BUF
400                 buf=pkg_malloc(BUF_SIZE+1);
401                 if (buf==0){
402                         LOG(L_ERR, "ERROR: udp_rcv_loop: could not allocate receive"
403                                          " buffer\n");
404                         goto error;
405                 }
406 #endif
407                 fromlen=sockaddru_len(bind_address->su);
408                 len=recvfrom(bind_address->socket, buf, BUF_SIZE, 0, &from->s,
409                                                                                         &fromlen);
410                 if (len==-1){
411                         if (errno==EAGAIN){
412                                 DBG("udp_rcv_loop: packet with bad checksum received\n");
413                                 continue;
414                         }
415                         LOG(L_ERR, "ERROR: udp_rcv_loop:recvfrom:[%d] %s\n",
416                                                 errno, strerror(errno));
417                         if ((errno==EINTR)||(errno==EWOULDBLOCK)|| (errno==ECONNREFUSED))
418                                 continue; /* goto skip;*/
419                         else goto error;
420                 }
421                 /* we must 0-term the messages, receive_msg expects it */
422                 buf[len]=0; /* no need to save the previous char */
423
424                 ri.src_su=*from;
425                 su2ip_addr(&ri.src_ip, from);
426                 ri.src_port=su_getport(from);
427
428 #ifndef NO_ZERO_CHECKS
429                 if (len<MIN_UDP_PACKET) {
430                         tmp=ip_addr2a(&ri.src_ip);
431                         DBG("udp_rcv_loop: probing packet received from %s %d\n",
432                                         tmp, htons(ri.src_port));
433                         continue;
434                 }
435                 if (buf[len-1]==0) {
436                         tmp=ip_addr2a(&ri.src_ip);
437                         LOG(L_WARN, "WARNING: udp_rcv_loop: "
438                                         "upstream bug - 0-terminated packet from %s %d\n",
439                                         tmp, htons(ri.src_port));
440                         len--;
441                 }
442 #endif
443 #ifdef DBG_MSG_QA
444                 if (!dbg_msg_qa(buf, len)) {
445                         LOG(L_WARN, "WARNING: an incoming message didn't pass test,"
446                                                 "  drop it: %.*s\n", len, buf );
447                         continue;
448                 }
449 #endif
450                 if (ri.src_port==0){
451                         tmp=ip_addr2a(&ri.src_ip);
452                         LOG(L_INFO, "udp_rcv_loop: dropping 0 port packet from %s\n", tmp);
453                         continue;
454                 }
455                 
456                 
457                 /* receive_msg must free buf too!*/
458                 receive_msg(buf, len, &ri);
459                 
460         /* skip: do other stuff */
461                 
462         }
463         /*
464         if (from) pkg_free(from);
465         return 0;
466         */
467         
468 error:
469         if (from) pkg_free(from);
470         return -1;
471 }
472
473
474
475
476 /* which socket to use? main socket or new one? */
477 int udp_send(struct socket_info *source, char *buf, unsigned len,
478                                                                                 union sockaddr_union*  to)
479 {
480
481         int n;
482         int tolen;
483
484 #ifdef DBG_MSG_QA
485         /* aborts on error, does nothing otherwise */
486         if (!dbg_msg_qa( buf, len )) {
487                 LOG(L_ERR, "ERROR: udp_send: dbg_msg_qa failed\n");
488                 abort();
489         }
490 #endif
491
492         tolen=sockaddru_len(*to);
493 again:
494         n=sendto(source->socket, buf, len, 0, &to->s, tolen);
495 #ifdef XL_DEBUG
496         LOG(L_INFO, "INFO: send status: %d\n", n);
497 #endif
498         if (n==-1){
499                 LOG(L_ERR, "ERROR: udp_send: sendto(sock,%p,%d,0,%p,%d): %s(%d)\n",
500                                 buf,len,to,tolen,
501                                 strerror(errno),errno);
502                 if (errno==EINTR) goto again;
503                 if (errno==EINVAL) {
504                         LOG(L_CRIT,"CRITICAL: invalid sendtoparameters\n"
505                         "one possible reason is the server is bound to localhost and\n"
506                         "attempts to send to the net\n");
507                 }
508         }
509         return n;
510 }