6982577515bdd7e752b5320ba7eb7b6050df1f7a
[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 /** @file
20  * @brief UDP ping implementation.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "uping.h"
26 #include "client.h"
27 #include "ircd.h"
28 #include "ircd_alloc.h"
29 #include "ircd_events.h"
30 #include "ircd_log.h"
31 #include "ircd_osdep.h"
32 #include "ircd_string.h"
33 #include "match.h"
34 #include "msg.h"
35 #include "numeric.h"
36 #include "numnicks.h"
37 #include "s_bsd.h"    /* VirtualHost */
38 #include "s_conf.h"
39 #include "s_debug.h"
40 #include "s_misc.h"
41 #include "s_user.h"
42 #include "send.h"
43 #include "sys.h"
44
45 /* #include <assert.h> -- Now using assert in ircd_log.h */
46 #include <errno.h>
47 #include <netdb.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sys/socket.h>
52 #include <sys/time.h>
53 #include <unistd.h>
54
55 #define UPINGTIMEOUT 60   /**< Timeout waiting for ping responses */
56
57 static struct UPing* pingList = 0; /**< Linked list of UPing structs */
58 static int UPingFileDescriptor       = -1; /**< UDP listener socket for upings */
59 static struct Socket upingSock; /**< Socket struct for upings */
60
61 /** Start iteration of uping list.
62  * @return Start of uping list.
63  */
64 struct UPing* uping_begin(void)
65 {
66   return pingList;
67 }
68
69 /** Removes \a p from uping list.
70  * @param[in,out] p UPing to remove from list.
71  */
72 static void uping_erase(struct UPing* p)
73 {
74   struct UPing* it;
75   struct UPing* last = 0;
76
77   assert(0 != p);
78
79   for (it = pingList; it; last = it, it = it->next) {
80     if (p == it) {
81       if (last)
82         last->next = p->next;
83       else
84         pingList = p->next;
85       break;
86     }
87   }
88 }
89
90 /** Callback for uping listener socket.
91  * @param[in] ev I/O event for uping socket.
92  */
93 static void uping_echo_callback(struct Event* ev)
94 {
95   assert(ev_type(ev) == ET_READ || ev_type(ev) == ET_ERROR);
96
97   uping_echo();
98 }
99
100 /** Initialize a UDP socket for upings.
101  * @returns File descriptor of UDP socket (-1 on error).
102  */
103 int uping_init(void)
104 {
105   struct irc_sockaddr from;
106   int fd;
107
108   memcpy(&from, &VirtualHost, sizeof(from));
109   from.port = atoi(UDP_PORT);
110
111   fd = os_socket(&from, SOCK_DGRAM, "UDP listener socket");
112   if (fd < 0)
113     return -1;
114   if (!socket_add(&upingSock, uping_echo_callback, 0, SS_DATAGRAM,
115                   SOCK_EVENT_READABLE, fd)) {
116     Debug((DEBUG_ERROR, "UPING: Unable to queue fd to event system"));
117     close(fd);
118     return -1;
119   }
120   UPingFileDescriptor = fd;
121   return fd;
122 }
123
124
125 /** Read a uping from the socket and respond (but not more than 10
126  * times per second).
127  */
128 void uping_echo()
129 {
130   struct irc_sockaddr from;
131   unsigned int       len = 0;
132   static time_t      last = 0;
133   static int         counter = 0;
134   char               buf[BUFSIZE + 1];
135
136   Debug((DEBUG_DEBUG, "UPING: uping_echo"));
137
138   if (IO_SUCCESS != os_recvfrom_nonb(UPingFileDescriptor, buf, BUFSIZE, &len, &from))
139     return;
140   /*
141    * count em even if we're getting flooded so we can tell we're getting
142    * flooded.
143    */
144   ++ServerStats->uping_recv;
145   if (CurrentTime == last) {
146     if (++counter > 10)
147       return;
148   }
149   else {
150     counter = 0;
151     last    = CurrentTime;
152   }
153   if (len < 19)
154     return;
155   os_sendto_nonb(UPingFileDescriptor, buf, len, NULL, 0, &from);
156 }
157
158
159 /** Callback for socket activity on an outbound uping socket.
160  * @param[in] ev I/O event for socket.
161  */
162 static void uping_read_callback(struct Event* ev)
163 {
164   struct UPing *pptr;
165
166   assert(0 != ev_socket(ev));
167   assert(0 != s_data(ev_socket(ev)));
168
169   pptr = (struct UPing*) s_data(ev_socket(ev));
170
171   Debug((DEBUG_SEND, "uping_read_callback called, %p (%d)", pptr,
172          ev_type(ev)));
173
174   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
175     pptr->freeable &= ~UPING_PENDING_SOCKET;
176
177     if (!pptr->freeable)
178       MyFree(pptr); /* done with it, finally */
179   } else {
180     assert(ev_type(ev) == ET_READ || ev_type(ev) == ET_ERROR);
181
182     uping_read(pptr); /* read uping response */
183   }
184 }
185
186 /** Timer callback to send another outbound uping.
187  * @param[in] ev Event for uping timer.
188  */
189 static void uping_sender_callback(struct Event* ev)
190 {
191   struct UPing *pptr;
192
193   assert(0 != ev_timer(ev));
194   assert(0 != t_data(ev_timer(ev)));
195
196   pptr = (struct UPing*) t_data(ev_timer(ev));
197
198   Debug((DEBUG_SEND, "uping_sender_callback called, %p (%d)", pptr,
199          ev_type(ev)));
200
201   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
202     pptr->freeable &= ~UPING_PENDING_SENDER;
203
204     if (!pptr->freeable)
205       MyFree(pptr); /* done with it, finally */
206   } else {
207     assert(ev_type(ev) == ET_EXPIRE);
208
209     pptr->lastsent = CurrentTime; /* store last ping time */
210     uping_send(pptr); /* send a ping */
211
212     if (pptr->sent == pptr->count) /* done sending pings, don't send more */
213       timer_del(ev_timer(ev));
214   }
215 }
216
217 /** Timer callback to stop upings.
218  * @param[in] ev Event for uping expiration.
219  */
220 static void uping_killer_callback(struct Event* ev)
221 {
222   struct UPing *pptr;
223
224   assert(0 != ev_timer(ev));
225   assert(0 != t_data(ev_timer(ev)));
226
227   pptr = (struct UPing*) t_data(ev_timer(ev));
228
229   Debug((DEBUG_SEND, "uping_killer_callback called, %p (%d)", pptr,
230          ev_type(ev)));
231
232   if (ev_type(ev) == ET_DESTROY) { /* being destroyed */
233     pptr->freeable &= ~UPING_PENDING_KILLER;
234
235     if (!pptr->freeable)
236       MyFree(pptr); /* done with it, finally */
237   } else {
238     assert(ev_type(ev) == ET_EXPIRE);
239
240     uping_end(pptr); /* <FUDD>kill the uping, kill the uping!</FUDD> */
241   }
242 }
243
244 /** Start a uping.
245  * This sets up the timers, UPing flags, and sends a notice to the
246  * requesting client.
247  */
248 static void uping_start(struct UPing* pptr)
249 {
250   assert(0 != pptr);
251
252   timer_add(timer_init(&pptr->sender), uping_sender_callback, (void*) pptr,
253             TT_PERIODIC, 1);
254   timer_add(timer_init(&pptr->killer), uping_killer_callback, (void*) pptr,
255             TT_RELATIVE, UPINGTIMEOUT);
256   pptr->freeable |= UPING_PENDING_SENDER | UPING_PENDING_KILLER;
257
258   sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :Sending %d ping%s to %s",
259                 pptr->client, pptr->count, (pptr->count == 1) ? "" : "s",
260                 pptr->name);
261   pptr->active = 1;
262 }
263
264 /** Send a uping to another server.
265  * @param[in] pptr Descriptor for uping.
266  */
267 void uping_send(struct UPing* pptr)
268 {
269   struct timeval tv;
270   char buf[BUFSIZE + 1];
271
272   assert(0 != pptr);
273   if (pptr->sent == pptr->count)
274     return;
275   memset(buf, 0, sizeof(buf));
276
277   gettimeofday(&tv, NULL);
278   sprintf(buf, " %10lu%c%6lu", (unsigned long)tv.tv_sec, '\0', (unsigned long)tv.tv_usec);
279
280   Debug((DEBUG_SEND, "send_ping: sending [%s %s] to %s.%d on %d",
281           buf, &buf[12],
282           ircd_ntoa(&pptr->addr.addr), pptr->addr.port,
283           pptr->fd));
284
285   if (os_sendto_nonb(pptr->fd, buf, BUFSIZE, NULL, 0, &pptr->addr) != IO_SUCCESS)
286   {
287     const char* msg = strerror(errno);
288     if (!msg)
289       msg = "Unknown error";
290     if (pptr->client)
291       sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: send failed: "
292                     "%s", pptr->client, msg);
293     Debug((DEBUG_DEBUG, "UPING: send_ping: sendto failed on %d: %s", pptr->fd, msg));
294     uping_end(pptr);
295     return;
296   }
297   ++pptr->sent;
298 }
299
300 /** Read the response from an outbound uping.
301  * @param[in] pptr UPing to check.
302  */
303 void uping_read(struct UPing* pptr)
304 {
305   struct irc_sockaddr sin;
306   struct timeval     tv;
307   unsigned int       len;
308   unsigned int       pingtime;
309   char*              s;
310   char               buf[BUFSIZE + 1];
311   IOResult           ior;
312
313   assert(0 != pptr);
314
315   gettimeofday(&tv, NULL);
316
317   ior = os_recvfrom_nonb(pptr->fd, buf, BUFSIZE, &len, &sin);
318   if (IO_BLOCKED == ior)
319     return;
320   else if (IO_FAILURE == ior) {
321     const char* msg = strerror(errno);
322     if (!msg)
323       msg = "Unknown error";
324     sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: receive error: "
325                   "%s", pptr->client, msg);
326     uping_end(pptr);
327     return;
328   }
329
330   if (len < 19)
331     return;                     /* Broken packet */
332
333   ++pptr->received;
334
335   buf[len] = 0;
336   pingtime = (tv.tv_sec - atol(&buf[1])) * 1000
337              + (tv.tv_usec - atol(buf + strlen(buf) + 1)) / 1000;
338
339   pptr->ms_ave += pingtime;
340   if (!pptr->ms_min || pptr->ms_min > pingtime)
341     pptr->ms_min = pingtime;
342   if (pingtime > pptr->ms_max)
343     pptr->ms_max = pingtime;
344
345   timer_chg(&pptr->killer, TT_RELATIVE, UPINGTIMEOUT);
346
347   s = pptr->buf + strlen(pptr->buf);
348   sprintf(s, " %u", pingtime);
349
350   if (pptr->received == pptr->count)
351     uping_end(pptr);
352   return;
353 }
354
355 /** Start sending upings to a server.
356  * @param[in] sptr Client requesting the upings.
357  * @param[in] aconf ConfItem containing the address to ping.
358  * @param[in] port Port number to ping.
359  * @param[in] count Number of times to ping (should be at least 20).
360  * @return Zero.
361  */
362 int uping_server(struct Client* sptr, struct ConfItem* aconf, int port, int count)
363 {
364   int fd;
365   struct UPing* pptr;
366
367   assert(0 != sptr);
368   assert(0 != aconf);
369
370   if (!irc_in_addr_valid(&aconf->address.addr)) {
371     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Host lookup failed for "
372                   "%s", sptr, aconf->name);
373     return 0;
374   }
375
376   if (IsUPing(sptr))
377     uping_cancel(sptr, sptr);  /* Cancel previous ping request */
378
379   fd = os_socket(NULL, SOCK_DGRAM, "UDP ping socket");
380   if (fd < 0)
381     return 0;
382
383   pptr = (struct UPing*) MyMalloc(sizeof(struct UPing));
384   assert(0 != pptr);
385   memset(pptr, 0, sizeof(struct UPing));
386
387   if (!socket_add(&pptr->socket, uping_read_callback, (void*) pptr,
388                   SS_DATAGRAM, SOCK_EVENT_READABLE, fd)) {
389     sendcmdto_one(&me, CMD_NOTICE, sptr, "%C :UPING: Can't queue fd for "
390                   "reading", sptr);
391     close(fd);
392     MyFree(pptr);
393     return 0;
394   }
395
396   pptr->fd                  = fd;
397   memcpy(&pptr->addr.addr, &aconf->address.addr, sizeof(pptr->addr.addr));
398   pptr->addr.port           = port;
399   pptr->count               = IRCD_MIN(20, count);
400   pptr->client              = sptr;
401   pptr->freeable            = UPING_PENDING_SOCKET;
402   strcpy(pptr->name, aconf->name);
403
404   pptr->next = pingList;
405   pingList   = pptr;
406
407   SetUPing(sptr);
408   uping_start(pptr);
409   return 0;
410 }
411
412 /** Clean up a UPing structure, reporting results to the requester.
413  * @param[in,out] pptr UPing results.
414  */
415 void uping_end(struct UPing* pptr)
416 {
417   Debug((DEBUG_DEBUG, "uping_end: %p", pptr));
418
419   if (pptr->client) {
420     if (pptr->lastsent) {
421       if (0 < pptr->received) {
422         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING %s%s",
423                       pptr->client, pptr->name, pptr->buf);
424         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING Stats: "
425                       "sent %d recvd %d ; min/avg/max = %1lu/%1lu/%1lu ms",
426                       pptr->client, pptr->sent, pptr->received, pptr->ms_min,
427                       (2 * pptr->ms_ave) / (2 * pptr->received), pptr->ms_max);
428       } else
429         sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: no response "
430                       "from %s within %d seconds", pptr->client, pptr->name,
431                       UPINGTIMEOUT);
432     } else
433       sendcmdto_one(&me, CMD_NOTICE, pptr->client, "%C :UPING: Could not "
434                     "start ping to %s", pptr->client, pptr->name);
435   }
436
437   close(pptr->fd);
438   pptr->fd = -1;
439   uping_erase(pptr);
440   if (pptr->client)
441     ClearUPing(pptr->client);
442   if (pptr->freeable & UPING_PENDING_SOCKET)
443     socket_del(&pptr->socket);
444   if (pptr->freeable & UPING_PENDING_SENDER)
445     timer_del(&pptr->sender);
446   if (pptr->freeable & UPING_PENDING_KILLER)
447     timer_del(&pptr->killer);
448 }
449
450 /** Change notifications for any upings by \a sptr.
451  * @param[in] sptr Client to stop notifying.
452  * @param[in] acptr New client to notify (or NULL).
453  */
454 void uping_cancel(struct Client *sptr, struct Client* acptr)
455 {
456   struct UPing* ping;
457   struct UPing* ping_next;
458
459   Debug((DEBUG_DEBUG, "UPING: cancelling uping for %s", cli_name(sptr)));
460   for (ping = pingList; ping; ping = ping_next) {
461     ping_next = ping->next;
462     if (sptr == ping->client) {
463       ping->client = acptr;
464       uping_end(ping);
465     }
466   }
467   ClearUPing(sptr);
468 }
469
470