Fixes to improve portability (especially to OS X, Solaris, OpenBSD).
[ircu2.10.12-pk.git] / ircd / uping.c
1 /*
2  * IRC - Internet Relay Chat, ircd/uping.c
3  * Copyright (C) 1994 Carlo Wood ( Run @ undernet.org )
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  * $Id$
20  */
21 #include "config.h"
22
23 #include "uping.h"
24 #include "client.h"
25 #include "ircd.h"
26 #include "ircd_alloc.h"
27 #include "ircd_events.h"
28 #include "ircd_log.h"
29 #include "ircd_osdep.h"
30 #include "ircd_string.h"
31 #include "match.h"
32 #include "msg.h"
33 #include "numeric.h"
34 #include "numnicks.h"
35 #include "s_bsd.h"    /* VirtualHost */
36 #include "s_conf.h"
37 #include "s_debug.h"
38 #include "s_misc.h"
39 #include "s_user.h"
40 #include "send.h"
41 #include "sys.h"
42
43 #include <arpa/inet.h>
44 #include <assert.h>
45 #include <errno.h>
46 #include <netdb.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/socket.h>
51 #include <sys/time.h>
52 #include <unistd.h>
53
54 #define UPINGTIMEOUT 60   /* Timeout waiting for ping responses */
55
56 #ifndef INADDR_NONE
57 #define INADDR_NONE 0xffffffff
58 #endif
59
60 static struct UPing* pingList = 0;
61 int UPingFileDescriptor       = -1; /* UDP listener socket for upings */
62
63 static struct Socket upingSock;
64
65 /*
66  * pings_begin - iterator function for ping list 
67  */
68 struct UPing* uping_begin(void)
69 {
70   return pingList;
71 }
72
73 /*
74  * pings_erase - removes ping struct from ping list
75  */
76 static void uping_erase(struct UPing* p)
77 {
78   struct UPing* it;
79   struct UPing* last = 0;
80
81   assert(0 != p);
82   
83   for (it = pingList; it; last = it, it = it->next) {
84     if (p == it) {
85       if (last)
86         last->next = p->next;
87       else
88         pingList = p->next;
89       break;
90     }
91   }
92 }
93
94 /* Called when the event engine detects activity on the UPing socket */
95 static void uping_echo_callback(struct Event* ev)
96 {
97   assert(ev_type(ev) == ET_READ || ev_type(ev) == ET_ERROR);
98
99   uping_echo();
100 }
101
102 /*
103  * Setup a UDP socket and listen for incoming packets
104  */
105 int uping_init(void)
106 {
107   struct sockaddr_in from = { 0 };
108   int fd;
109
110   memset(&from, 0, sizeof(from));
111   from.sin_addr = VirtualHost.sin_addr;
112   from.sin_port = htons(atoi(UDP_PORT));
113   from.sin_family = AF_INET;
114
115   if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
116     Debug((DEBUG_ERROR, "UPING: UDP listener socket call failed: %s", 
117            (strerror(errno)) ? strerror(errno) : "Unknown error"));
118     return -1;
119   }
120   if (!os_set_reuseaddr(fd)) {
121     log_write(LS_SOCKET, L_ERROR, 0,
122               "UPING: set reuseaddr on UDP listener failed: %m (fd %d)", fd);
123     Debug((DEBUG_ERROR, "UPING: set reuseaddr on UDP listener failed: %s",
124            (strerror(errno)) ? strerror(errno) : "Unknown error"));
125     close(fd);
126     return -1;
127   }
128   if (bind(fd, (struct sockaddr*) &from, sizeof(from)) == -1) {
129     log_write(LS_SOCKET, L_ERROR, 0,
130               "UPING: bind on UDP listener (%d fd %d) failed: %m",
131               htons(from.sin_port), fd);
132     Debug((DEBUG_ERROR, "UPING: bind on UDP listener failed : %s",
133            (strerror(errno)) ? strerror(errno) : "Unknown error"));
134     close(fd);
135     return -1;
136   }
137   if (!os_set_nonblocking(fd)) {
138     Debug((DEBUG_ERROR, "UPING: set non-blocking: %s",
139            (strerror(errno)) ? strerror(errno) : "Unknown error"));
140     close(fd);
141     return -1;
142   }
143   if (!socket_add(&upingSock, uping_echo_callback, 0, SS_DATAGRAM,
144                   SOCK_EVENT_READABLE, fd)) {
145     Debug((DEBUG_ERROR, "UPING: Unable to queue fd to event system"));
146     close(fd);
147     return -1;
148   }
149   UPingFileDescriptor = fd;
150   return fd;
151 }
152
153
154 /*
155  * max # of pings set to 15/sec.
156  */
157 void uping_echo()
158 {
159   struct sockaddr_in from = { 0 };
160   unsigned int       len = 0;
161   static time_t      last = 0;
162   static int         counter = 0;
163   char               buf[BUFSIZE + 1];
164
165   Debug((DEBUG_DEBUG, "UPING: uping_echo"));
166
167   if (IO_SUCCESS != os_recvfrom_nonb(UPingFileDescriptor, buf, BUFSIZE, &len, &from))
168     return;
169   /*
170    * count em even if we're getting flooded so we can tell we're getting
171    * flooded.
172    */
173   ++ServerStats->uping_recv;
174   if (CurrentTime == last) {
175     if (++counter > 10)
176       return;
177   }
178   else {
179     counter = 0;
180     last    = CurrentTime;
181   }
182   if (len < 19)
183     return;
184   sendto(UPingFileDescriptor, buf, len, 0, (struct sockaddr*) &from, sizeof(from));
185 }
186
187
188 /* Callback when socket has data to read */
189 static void uping_read_callback(struct Event* ev)
190 {
191   struct UPing *pptr;
192
193   assert(0 != ev_socket(ev));
194   assert(0 != s_data(ev_socket(ev)));
195
196   pptr = (struct UPing*) s_data(ev_socket(ev));
197
198   Debug((DEBUG_SEND, "uping_read_callback called, %p (%d)", pptr,
199          ev_type(ev)));
200
201   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
202     pptr->freeable &= ~UPING_PENDING_SOCKET;
203
204     if (!pptr->freeable)
205       MyFree(pptr); /* done with it, finally */
206   } else {
207     assert(ev_type(ev) == ET_READ || ev_type(ev) == ET_ERROR);
208
209     uping_read(pptr); /* read uping response */
210   }
211 }
212
213 /* Callback to send another ping */
214 static void uping_sender_callback(struct Event* ev)
215 {
216   struct UPing *pptr;
217
218   assert(0 != ev_timer(ev));
219   assert(0 != t_data(ev_timer(ev)));
220
221   pptr = (struct UPing*) t_data(ev_timer(ev));
222
223   Debug((DEBUG_SEND, "uping_sender_callback called, %p (%d)", pptr,
224          ev_type(ev)));
225
226   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
227     pptr->freeable &= ~UPING_PENDING_SENDER;
228
229     if (!pptr->freeable)
230       MyFree(pptr); /* done with it, finally */
231   } else {
232     assert(ev_type(ev) == ET_EXPIRE);
233
234     pptr->lastsent = CurrentTime; /* store last ping time */
235     uping_send(pptr); /* send a ping */
236
237     if (pptr->sent == pptr->count) /* done sending pings, don't send more */
238       timer_del(ev_timer(ev));
239   }
240 }
241
242 /* Callback to kill a ping */
243 static void uping_killer_callback(struct Event* ev)
244 {
245   struct UPing *pptr;
246
247   assert(0 != ev_timer(ev));
248   assert(0 != t_data(ev_timer(ev)));
249
250   pptr = (struct UPing*) t_data(ev_timer(ev));
251
252   Debug((DEBUG_SEND, "uping_killer_callback called, %p (%d)", pptr,
253          ev_type(ev)));
254
255   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
256     pptr->freeable &= ~UPING_PENDING_KILLER;
257
258     if (!pptr->freeable)
259       MyFree(pptr); /* done with it, finally */
260   } else {
261     assert(ev_type(ev) == ET_EXPIRE);
262
263     uping_end(pptr); /* <FUDD>kill the uping, kill the uping!</FUDD> */
264   }
265 }
266
267 /*
268  * start_ping
269  */
270 static void uping_start(struct UPing* pptr)
271 {
272   assert(0 != pptr);
273
274   timer_add(timer_init(&pptr->sender), uping_sender_callback, (void*) pptr,
275             TT_PERIODIC, 1);
276   timer_add(timer_init(&pptr->killer), uping_killer_callback, (void*) pptr,
277             TT_RELATIVE, UPINGTIMEOUT);
278   pptr->freeable |= UPING_PENDING_SENDER | UPING_PENDING_KILLER;
279
280   sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :Sending %d ping%s to %s",
281                 pptr->client, pptr->count, (pptr->count == 1) ? "" : "s",
282                 pptr->name);
283   pptr->active = 1;
284 }
285
286 /*
287  * uping_send
288  *
289  */
290 void uping_send(struct UPing* pptr)
291 {
292   struct timeval tv;
293   char buf[BUFSIZE + 1];
294
295   assert(0 != pptr);
296   if (pptr->sent == pptr->count)
297     return;
298   memset(buf, 0, sizeof(buf));
299
300   gettimeofday(&tv, NULL);
301   sprintf(buf, " %10lu%c%6lu", (unsigned long)tv.tv_sec, '\0', (unsigned long)tv.tv_usec);
302
303   Debug((DEBUG_SEND, "send_ping: sending [%s %s] to %s.%d on %d",
304           buf, &buf[12],
305           ircd_ntoa((const char*) &pptr->sin.sin_addr), ntohs(pptr->sin.sin_port),
306           pptr->fd));
307
308   if (sendto(pptr->fd, buf, BUFSIZE, 0, (struct sockaddr*) &pptr->sin,
309              sizeof(struct sockaddr_in)) != BUFSIZE)
310   {
311     const char* msg = strerror(errno);
312     if (!msg)
313       msg = "Unknown error";
314     if (pptr->client)
315       sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: send failed: "
316                     "%s", pptr->client, msg);
317     Debug((DEBUG_DEBUG, "UPING: send_ping: sendto failed on %d: %s", pptr->fd, msg));
318     uping_end(pptr);
319     return;
320   }
321   ++pptr->sent;
322 }
323
324 /*
325  * read_ping
326  */
327 void uping_read(struct UPing* pptr)
328 {
329   struct sockaddr_in sin;
330   struct timeval     tv;
331   unsigned int       len;
332   unsigned int       pingtime;
333   char*              s;
334   char               buf[BUFSIZE + 1];
335   IOResult           ior;
336
337   assert(0 != pptr);
338
339   gettimeofday(&tv, NULL);
340
341   ior = os_recvfrom_nonb(pptr->fd, buf, BUFSIZE, &len, &sin);
342   if (IO_BLOCKED == ior)
343     return;
344   else if (IO_FAILURE == ior) {
345     const char* msg = strerror(errno);
346     if (!msg)
347       msg = "Unknown error";
348     sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: receive error: "
349                   "%s", pptr->client, msg);
350     uping_end(pptr);
351     return;
352   }    
353
354   if (len < 19)
355     return;                     /* Broken packet */
356    
357   ++pptr->received;
358
359   buf[len] = 0;
360   pingtime = (tv.tv_sec - atol(&buf[1])) * 1000
361              + (tv.tv_usec - atol(buf + strlen(buf) + 1)) / 1000;
362
363   pptr->ms_ave += pingtime;
364   if (!pptr->ms_min || pptr->ms_min > pingtime)
365     pptr->ms_min = pingtime;
366   if (pingtime > pptr->ms_max)
367     pptr->ms_max = pingtime;
368
369   timer_chg(&pptr->killer, TT_RELATIVE, UPINGTIMEOUT);
370
371   s = pptr->buf + strlen(pptr->buf);
372   sprintf(s, " %u", pingtime);
373
374   if (pptr->received == pptr->count)
375     uping_end(pptr);
376   return;
377 }
378
379 int uping_server(struct Client* sptr, struct ConfItem* aconf, int port, int count)
380 {
381   int fd;
382   struct UPing* pptr;
383
384   assert(0 != sptr);
385   assert(0 != aconf);
386
387   if (INADDR_NONE == aconf->ipnum.s_addr) {
388     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Host lookup failed for "
389                   "%s", sptr, aconf->name);
390     return 0;
391   }
392
393   if (IsUPing(sptr))
394     uping_cancel(sptr, sptr);  /* Cancel previous ping request */
395
396   if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
397     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Unable to create udp "
398                   "ping socket", sptr);
399     return 0;
400   }
401
402   if (!os_set_nonblocking(fd)) {
403     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Can't set fd non-"
404                   "blocking", sptr);
405     close(fd);
406     return 0;
407   }
408   pptr = (struct UPing*) MyMalloc(sizeof(struct UPing));
409   assert(0 != pptr);
410   memset(pptr, 0, sizeof(struct UPing));
411
412   if (!socket_add(&pptr->socket, uping_read_callback, (void*) pptr,
413                   SS_DATAGRAM, SOCK_EVENT_READABLE, fd)) {
414     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Can't queue fd for "
415                   "reading", sptr);
416     close(fd);
417     MyFree(pptr);
418     return 0;
419   }
420
421   pptr->fd                  = fd;
422   pptr->sin.sin_port        = htons(port);
423   pptr->sin.sin_addr.s_addr = aconf->ipnum.s_addr;
424   pptr->sin.sin_family      = AF_INET;
425   pptr->count               = IRCD_MIN(20, count);
426   pptr->client              = sptr;
427   pptr->index               = -1;
428   pptr->freeable            = UPING_PENDING_SOCKET;
429   strcpy(pptr->name, aconf->name);
430
431   pptr->next = pingList;
432   pingList   = pptr;
433
434   SetUPing(sptr);
435   uping_start(pptr);
436   return 0;
437 }
438
439
440 void uping_end(struct UPing* pptr)
441 {
442   Debug((DEBUG_DEBUG, "uping_end: %p", pptr));
443
444   if (pptr->client) {
445     if (pptr->lastsent) {
446       if (0 < pptr->received) {
447         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING %s%s",
448                       pptr->client, pptr->name, pptr->buf);
449         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING Stats: "
450                       "sent %d recvd %d ; min/avg/max = %1lu/%1lu/%1lu ms",
451                       pptr->client, pptr->sent, pptr->received, pptr->ms_min,
452                       (2 * pptr->ms_ave) / (2 * pptr->received), pptr->ms_max);
453       } else
454         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: no response "
455                       "from %s within %d seconds", pptr->client, pptr->name,
456                       UPINGTIMEOUT);
457     } else
458       sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: Could not "
459                     "start ping to %s", pptr->client, pptr->name);
460   }
461
462   close(pptr->fd);
463   pptr->fd = -1;
464   uping_erase(pptr);
465   if (pptr->client)
466     ClearUPing(pptr->client);
467   if (pptr->freeable & UPING_PENDING_SOCKET)
468     socket_del(&pptr->socket);
469   if (pptr->freeable & UPING_PENDING_SENDER)
470     timer_del(&pptr->sender);
471   if (pptr->freeable & UPING_PENDING_KILLER)
472     timer_del(&pptr->killer);
473 }
474
475 void uping_cancel(struct Client *sptr, struct Client* acptr)
476 {
477   struct UPing* ping;
478   struct UPing* ping_next;
479
480   Debug((DEBUG_DEBUG, "UPING: cancelling uping for %s", cli_name(sptr)));
481   for (ping = pingList; ping; ping = ping_next) {
482     ping_next = ping->next;
483     if (sptr == ping->client) {
484       ping->client = acptr;
485       uping_end(ping);
486     }
487   }
488   ClearUPing(sptr);
489 }
490
491