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