Merge commit 'origin/ser_modules'
[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  *  2005-03-10  multicast options are now set for all the udp sockets (andrei)
38  *  2005-06-26  failure to set mcast options is not an error anymore (andrei)
39  *  2006-04-12  udp_send() switched to struct dest_info (andrei)
40  *  2006-10-13  added STUN support (vlada)
41  *  2007-08-28  disable/set MTU discover option for the udp sockets
42  *               (in linux it's enabled by default which produces udp packets
43  *                with the DF flag ser) (patch from hscholz)
44  */
45
46
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/types.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <errno.h>
55 #include <arpa/inet.h>
56 #ifdef __linux__
57         #include <linux/types.h>
58         #include <linux/errqueue.h>
59 #endif
60
61
62 #include "udp_server.h"
63 #include "globals.h"
64 #include "config.h"
65 #include "dprint.h"
66 #include "receive.h"
67 #include "mem/mem.h"
68 #include "ip_addr.h"
69 #include "cfg/cfg_struct.h"
70
71 #ifdef USE_STUN
72   #include "ser_stun.h"
73 #endif
74
75 #ifdef DBG_MSG_QA
76 /* message quality assurance -- frequently, bugs in ser have
77    been indicated by zero characters or long whitespaces
78    in generated messages; this debugging option aborts if
79    any such message is sighted
80 */
81 static int dbg_msg_qa(char *buf, int len)
82 {
83 #define _DBG_WS_LEN 3
84 #define _DBG_WS "   "
85
86         char *scan;
87         int my_len;
88         int space_cnt;
89         enum { QA_ANY, QA_SPACE, QA_EOL1 } state;
90
91
92         /* is there a zero character in there ? */      
93         if (memchr(buf, 0, len)) {
94                 LOG(L_CRIT, "BUG: message with 0 in it\n");
95                 return 0;
96         }
97
98         my_len=len;
99         scan=buf;
100         state=QA_ANY;
101         space_cnt=0;
102
103         while(my_len) {
104                 switch(*scan) {
105                         case ' ':       if (state==QA_SPACE) {
106                                                         space_cnt++;
107                                                         if (space_cnt==4) {
108                                                                 LOG(L_CRIT, "BUG(probably): DBG_MSG_QA: "
109                                                                         "too many spaces\n");
110                                                                 return 0;
111                                                         }
112                                                 } else space_cnt=0;
113                                                 state=QA_SPACE; 
114                                                 break;
115
116                         case '\r':      /* ignore */
117                                                 space_cnt=0;
118                                                 break;
119
120                         case '\n': /* don't proceed to body on EoH */
121                                                 if (state==QA_EOL1) goto qa_passed;
122                                                 space_cnt=0;
123                                                 state=QA_EOL1;
124                                                 break;
125
126                         default:        space_cnt=0;
127                                                 state=QA_ANY;
128                                                 break;
129                 }
130                 scan++;
131                 my_len--;
132         }
133
134
135 qa_passed:
136         return 1;
137 }
138
139 #endif
140
141
142 int probe_max_receive_buffer( int udp_sock )
143 {
144         int optval;
145         int ioptval;
146         unsigned int ioptvallen;
147         int foptval;
148         unsigned int foptvallen;
149         int voptval;
150         unsigned int voptvallen;
151         int phase=0;
152
153         /* jku: try to increase buffer size as much as we can */
154         ioptvallen=sizeof(ioptval);
155         if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &ioptval,
156                     &ioptvallen) == -1 )
157         {
158                 LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
159                 return -1;
160         }
161         if ( ioptval==0 ) 
162         {
163                 LOG(L_DBG, "DEBUG: udp_init: SO_RCVBUF initially set to 0; resetting to %d\n",
164                         BUFFER_INCREMENT );
165                 ioptval=BUFFER_INCREMENT;
166         } else LOG(L_INFO, "INFO: udp_init: SO_RCVBUF is initially %d\n", ioptval );
167         for (optval=ioptval; ;  ) {
168                 /* increase size; double in initial phase, add linearly later */
169                 if (phase==0) optval <<= 1; else optval+=BUFFER_INCREMENT;
170                 if (optval > maxbuffer){
171                         if (phase==1) break; 
172                         else { phase=1; optval >>=1; continue; }
173                 }
174                 LOG(L_DBG, "DEBUG: udp_init: trying SO_RCVBUF: %d\n", optval );
175                 if (setsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF,
176                         (void*)&optval, sizeof(optval)) ==-1){
177                         /* Solaris returns -1 if asked size too big; Linux ignores */
178                         LOG(L_DBG, "DEBUG: udp_init: SOL_SOCKET failed"
179                                         " for %d, phase %d: %s\n", optval, phase, strerror(errno));
180                         /* if setting buffer size failed and still in the aggressive
181                            phase, try less aggressively; otherwise give up 
182                         */
183                         if (phase==0) { phase=1; optval >>=1 ; continue; } 
184                         else break;
185                 } 
186                 /* verify if change has taken effect */
187                 /* Linux note -- otherwise I would never know that; funny thing: Linux
188                    doubles size for which we asked in setsockopt
189                 */
190                 voptvallen=sizeof(voptval);
191                 if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &voptval,
192                     &voptvallen) == -1 )
193                 {
194                         LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
195                         return -1;
196                 } else {
197                         LOG(L_DBG, "DEBUG: setting SO_RCVBUF; set=%d,verify=%d\n", 
198                                 optval, voptval);
199                         if (voptval<optval) {
200                                 LOG(L_DBG, "DEBUG: setting SO_RCVBUF has no effect\n");
201                                 /* if setting buffer size failed and still in the aggressive
202                                 phase, try less aggressively; otherwise give up 
203                                 */
204                                 if (phase==0) { phase=1; optval >>=1 ; continue; } 
205                                 else break;
206                         } 
207                 }
208         
209         } /* for ... */
210         foptvallen=sizeof(foptval);
211         if (getsockopt( udp_sock, SOL_SOCKET, SO_RCVBUF, (void*) &foptval,
212                     &foptvallen) == -1 )
213         {
214                 LOG(L_ERR, "ERROR: udp_init: getsockopt: %s\n", strerror(errno));
215                 return -1;
216         }
217         LOG(L_INFO, "INFO: udp_init: SO_RCVBUF is finally %d\n", foptval );
218
219         return 0;
220
221         /* EoJKU */
222 }
223
224
225 #ifdef USE_MCAST
226
227 /*
228  * Setup multicast receiver
229  */
230 static int setup_mcast_rcvr(int sock, union sockaddr_union* addr)
231 {
232         struct ip_mreq mreq;
233 #ifdef USE_IPV6
234         struct ipv6_mreq mreq6;
235 #endif /* USE_IPV6 */
236         
237         if (addr->s.sa_family==AF_INET){
238                 memcpy(&mreq.imr_multiaddr, &addr->sin.sin_addr, 
239                        sizeof(struct in_addr));
240                 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
241                 
242                 if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq,
243                                sizeof(mreq))==-1){
244                         LOG(L_ERR, "ERROR: setup_mcast_rcvr: setsockopt: %s\n",
245                             strerror(errno));
246                         return -1;
247                 }
248                 
249 #ifdef USE_IPV6
250         } else if (addr->s.sa_family==AF_INET6){
251                 memcpy(&mreq6.ipv6mr_multiaddr, &addr->sin6.sin6_addr, 
252                        sizeof(struct in6_addr));
253                 mreq6.ipv6mr_interface = 0;
254 #ifdef __OS_linux
255                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6,
256 #else
257                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq6,
258 #endif
259                                sizeof(mreq6))==-1){
260                         LOG(L_ERR, "ERROR: setup_mcast_rcvr: setsockopt:%s\n",
261                             strerror(errno));
262                         return -1;
263                 }
264                 
265 #endif /* USE_IPV6 */
266         } else {
267                 LOG(L_ERR, "ERROR: setup_mcast_rcvr: Unsupported protocol family\n");
268                 return -1;
269         }
270         return 0;
271 }
272
273 #endif /* USE_MCAST */
274
275
276 int udp_init(struct socket_info* sock_info)
277 {
278         union sockaddr_union* addr;
279         int optval;
280 #ifdef USE_MCAST
281         unsigned char m_ttl, m_loop;
282 #endif
283         addr=&sock_info->su;
284 /*
285         addr=(union sockaddr_union*)pkg_malloc(sizeof(union sockaddr_union));
286         if (addr==0){
287                 LOG(L_ERR, "ERROR: udp_init: out of memory\n");
288                 goto error;
289         }
290 */
291         sock_info->proto=PROTO_UDP;
292         if (init_su(addr, &sock_info->address, sock_info->port_no)<0){
293                 LOG(L_ERR, "ERROR: udp_init: could not init sockaddr_union\n");
294                 goto error;
295         }
296         
297         sock_info->socket = socket(AF2PF(addr->s.sa_family), SOCK_DGRAM, 0);
298         if (sock_info->socket==-1){
299                 LOG(L_ERR, "ERROR: udp_init: socket: %s\n", strerror(errno));
300                 goto error;
301         }
302         /* set sock opts? */
303         optval=1;
304         if (setsockopt(sock_info->socket, SOL_SOCKET, SO_REUSEADDR ,
305                                         (void*)&optval, sizeof(optval)) ==-1){
306                 LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror(errno));
307                 goto error;
308         }
309         /* tos */
310         optval = tos;
311         if (setsockopt(sock_info->socket, IPPROTO_IP, IP_TOS, (void*)&optval, 
312                         sizeof(optval)) ==-1){
313                 LOG(L_WARN, "WARNING: udp_init: setsockopt tos: %s\n", strerror(errno));
314                 /* continue since this is not critical */
315         }
316 #if defined (__OS_linux) && defined(UDP_ERRORS)
317         optval=1;
318         /* enable error receiving on unconnected sockets */
319         if(setsockopt(sock_info->socket, SOL_IP, IP_RECVERR,
320                                         (void*)&optval, sizeof(optval)) ==-1){
321                 LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror(errno));
322                 goto error;
323         }
324 #endif
325 #if defined (__OS_linux)
326         /* if pmtu_discovery=1 then set DF bit and do Path MTU discovery
327          * disabled by default */
328         optval= (pmtu_discovery) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
329         if(setsockopt(sock_info->socket, IPPROTO_IP, IP_MTU_DISCOVER,
330                         (void*)&optval, sizeof(optval)) ==-1){
331                 LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror(errno));
332                 goto error;
333         }
334 #endif
335
336 #ifdef USE_MCAST
337         if ((sock_info->flags & SI_IS_MCAST) 
338             && (setup_mcast_rcvr(sock_info->socket, addr)<0)){
339                         goto error;
340         }
341         /* set the multicast options */
342         if (addr->s.sa_family==AF_INET){
343                 m_loop=mcast_loopback;
344                 if (setsockopt(sock_info->socket, IPPROTO_IP, IP_MULTICAST_LOOP, 
345                                                 &m_loop, sizeof(m_loop))==-1){
346                         LOG(L_WARN, "WARNING: udp_init: setsockopt(IP_MULTICAST_LOOP):"
347                                                 " %s\n", strerror(errno));
348                         /* it's only a warning because we might get this error if the
349                           network interface doesn't support multicasting -- andrei */
350                 }
351                 if (mcast_ttl>=0){
352                         m_ttl=mcast_ttl;
353                         if (setsockopt(sock_info->socket, IPPROTO_IP, IP_MULTICAST_TTL,
354                                                 &m_ttl, sizeof(m_ttl))==-1){
355                                 LOG(L_WARN, "WARNING: udp_init: setsockopt (IP_MULTICAST_TTL):"
356                                                 " %s\n", strerror(errno));
357                         }
358                 }
359 #ifdef USE_IPV6
360         } else if (addr->s.sa_family==AF_INET6){
361                 if (setsockopt(sock_info->socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 
362                                                 &mcast_loopback, sizeof(mcast_loopback))==-1){
363                         LOG(L_WARN, "WARNING: udp_init: setsockopt (IPV6_MULTICAST_LOOP):"
364                                         " %s\n", strerror(errno));
365                 }
366                 if (mcast_ttl>=0){
367                         if (setsockopt(sock_info->socket, IPPROTO_IP, IPV6_MULTICAST_HOPS,
368                                                         &mcast_ttl, sizeof(mcast_ttl))==-1){
369                                 LOG(L_WARN, "WARNING: udp_init: setssckopt "
370                                                 "(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
371                         }
372                 }
373 #endif /* USE_IPV6*/
374         } else {
375                 LOG(L_ERR, "ERROR: udp_init: Unsupported protocol family %d\n",
376                                         addr->s.sa_family);
377                 goto error;
378         }
379 #endif /* USE_MCAST */
380
381         if ( probe_max_receive_buffer(sock_info->socket)==-1) goto error;
382         
383         if (bind(sock_info->socket,  &addr->s, sockaddru_len(*addr))==-1){
384                 LOG(L_ERR, "ERROR: udp_init: bind(%x, %p, %d) on %s: %s\n",
385                                 sock_info->socket, &addr->s, 
386                                 (unsigned)sockaddru_len(*addr),
387                                 sock_info->address_str.s,
388                                 strerror(errno));
389         #ifdef USE_IPV6
390                 if (addr->s.sa_family==AF_INET6)
391                         LOG(L_ERR, "ERROR: udp_init: might be caused by using a link "
392                                         " local address, try site local or global\n");
393         #endif
394                 goto error;
395         }
396
397 /*      pkg_free(addr);*/
398         return 0;
399
400 error:
401 /*      if (addr) pkg_free(addr);*/
402         return -1;
403 }
404
405
406
407 int udp_rcv_loop()
408 {
409         unsigned len;
410 #ifdef DYN_BUF
411         char* buf;
412 #else
413         static char buf [BUF_SIZE+1];
414 #endif
415         char *tmp;
416         union sockaddr_union* from;
417         unsigned int fromlen;
418         struct receive_info ri;
419
420
421         from=(union sockaddr_union*) pkg_malloc(sizeof(union sockaddr_union));
422         if (from==0){
423                 LOG(L_ERR, "ERROR: udp_rcv_loop: out of memory\n");
424                 goto error;
425         }
426         memset(from, 0 , sizeof(union sockaddr_union));
427         ri.bind_address=bind_address; /* this will not change, we do it only once*/
428         ri.dst_port=bind_address->port_no;
429         ri.dst_ip=bind_address->address;
430         ri.proto=PROTO_UDP;
431         ri.proto_reserved1=ri.proto_reserved2=0;
432
433         /* initialize the config framework */
434         if (cfg_child_init()) goto error;
435
436         for(;;){
437 #ifdef DYN_BUF
438                 buf=pkg_malloc(BUF_SIZE+1);
439                 if (buf==0){
440                         LOG(L_ERR, "ERROR: udp_rcv_loop: could not allocate receive"
441                                          " buffer\n");
442                         goto error;
443                 }
444 #endif
445                 fromlen=sockaddru_len(bind_address->su);
446                 len=recvfrom(bind_address->socket, buf, BUF_SIZE, 0, &from->s,
447                                                                                         &fromlen);
448                 if (len==-1){
449                         if (errno==EAGAIN){
450                                 DBG("udp_rcv_loop: packet with bad checksum received\n");
451                                 continue;
452                         }
453                         LOG(L_ERR, "ERROR: udp_rcv_loop:recvfrom:[%d] %s\n",
454                                                 errno, strerror(errno));
455                         if ((errno==EINTR)||(errno==EWOULDBLOCK)|| (errno==ECONNREFUSED))
456                                 continue; /* goto skip;*/
457                         else goto error;
458                 }
459                 /* we must 0-term the messages, receive_msg expects it */
460                 buf[len]=0; /* no need to save the previous char */
461
462                 ri.src_su=*from;
463                 su2ip_addr(&ri.src_ip, from);
464                 ri.src_port=su_getport(from);
465
466 #ifndef NO_ZERO_CHECKS
467 #ifdef USE_STUN
468                 /* STUN support can be switched off even if it's compiled */
469                 if (stun_allow_stun == 0 || (unsigned char)*buf != 0x00) {
470 #endif
471                   if (len<MIN_UDP_PACKET) {
472                           tmp=ip_addr2a(&ri.src_ip);
473                           DBG("udp_rcv_loop: probing packet received from %s %d\n",
474                                         tmp, htons(ri.src_port));
475                           continue;
476                   }
477 #ifdef USE_STUN
478                 }
479 #endif
480 /* historically, zero-terminated packets indicated a bug in clients
481  * that calculated wrongly packet length and included string-terminating
482  * zero; today clients exist with legitimate binary payloads and we
483  * shall not check for zero-terminated payloads
484  */
485 #ifdef TRASH_ZEROTERMINATED_PACKETS
486                 if (buf[len-1]==0) {
487                         tmp=ip_addr2a(&ri.src_ip);
488                         LOG(L_WARN, "WARNING: udp_rcv_loop: "
489                                         "upstream bug - 0-terminated packet from %s %d\n",
490                                         tmp, htons(ri.src_port));
491                         len--;
492                 }
493 #endif
494 #endif
495 #ifdef DBG_MSG_QA
496                 if (!dbg_msg_qa(buf, len)) {
497                         LOG(L_WARN, "WARNING: an incoming message didn't pass test,"
498                                                 "  drop it: %.*s\n", len, buf );
499                         continue;
500                 }
501 #endif
502                 if (ri.src_port==0){
503                         tmp=ip_addr2a(&ri.src_ip);
504                         LOG(L_INFO, "udp_rcv_loop: dropping 0 port packet from %s\n", tmp);
505                         continue;
506                 }
507                 
508                 /* update the local config */
509                 cfg_update();
510 #ifdef USE_STUN
511                         /* STUN support can be switched off even if it's compiled */
512                         if (stun_allow_stun && (unsigned char)*buf == 0x00) {
513                             /* stun_process_msg releases buf memory if necessary */
514                                 if ((stun_process_msg(buf, len, &ri)) != 0) {
515                                         continue; /* some error occurred */
516                                 }
517                         } else
518 #endif
519                 /* receive_msg must free buf too!*/
520                 receive_msg(buf, len, &ri);
521                 
522         /* skip: do other stuff */
523                 
524         }
525         /*
526         if (from) pkg_free(from);
527         return 0;
528         */
529         
530 error:
531         if (from) pkg_free(from);
532         return -1;
533 }
534
535
536
537
538 /* send buf:len over udp to dst (uses only the to and send_sock dst members)
539  * returns the numbers of bytes sent on success (>=0) and -1 on error
540  */
541 int udp_send(struct dest_info* dst, char *buf, unsigned len)
542 {
543
544         int n;
545         int tolen;
546         struct ip_addr ip; /* used only on error, for debugging */
547
548 #ifdef DBG_MSG_QA
549         /* aborts on error, does nothing otherwise */
550         if (!dbg_msg_qa( buf, len )) {
551                 LOG(L_ERR, "ERROR: udp_send: dbg_msg_qa failed\n");
552                 abort();
553         }
554 #endif
555
556         tolen=sockaddru_len(dst->to);
557 again:
558         n=sendto(dst->send_sock->socket, buf, len, 0, &dst->to.s, tolen);
559 #ifdef XL_DEBUG
560         LOG(L_INFO, "INFO: send status: %d\n", n);
561 #endif
562         if (n==-1){
563                 su2ip_addr(&ip, &dst->to);
564                 LOG(L_ERR, "ERROR: udp_send: sendto(sock,%p,%d,0,%s:%d,%d): %s(%d)\n",
565                                 buf,len, ip_addr2a(&ip), su_getport(&dst->to), tolen,
566                                 strerror(errno),errno);
567                 if (errno==EINTR) goto again;
568                 if (errno==EINVAL) {
569                         LOG(L_CRIT,"CRITICAL: invalid sendtoparameters\n"
570                         "one possible reason is the server is bound to localhost and\n"
571                         "attempts to send to the net\n");
572                 }
573         }
574         return n;
575 }