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