This commit was generated by cvs2svn to compensate for changes in r2,
[ircu2.10.12-pk.git] / ircd / IPcheck.c
1 /*
2  * IRC - Internet Relay Chat, ircd/IPcheck.c
3  * Copyright (C) 1998 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
20 /* This file should be edited in a window with a width of 141 characters */
21
22 #include "sys.h"
23 #include <netinet/in.h>
24 #include "h.h"
25 #include "IPcheck.h"
26 #include "querycmds.h"
27 #include "struct.h"
28 #include "s_user.h"
29 #include "s_bsd.h"
30 #include "struct.h"
31 #ifdef GODMODE
32 #include "numnicks.h"
33 #endif
34 #include "send.h"
35
36 RCSTAG_CC("$Id$");
37
38 extern aClient me;
39 extern time_t now;
40
41 /*
42  * IP number and last targets of a user that just disconnected.
43  * Used to allow a user that shortly disconnected to rejoin
44  * the channels he/she was on.
45  */
46 struct ip_targets_st {
47   struct in_addr ip;
48   unsigned char free_targets;
49   unsigned char targets[MAXTARGETS];
50 };
51
52 /* We keep one IPregistry for each IP number (for both, remote and local clients) */
53 struct IPregistry {
54   union {
55     struct in_addr ip;          /* The IP number of the registry entry. */
56     struct ip_targets_st *ptr;  /* The IP number of the registry entry, and a list of targets */
57   } ip_targets;
58   unsigned int last_connect:16; /* Time of last connect (attempt), see BITMASK below,
59                                    or time of last disconnect when `connected' is zero. */
60   unsigned int connected:8;     /* Used for IP# throttling: Number of currently on-line clients with this IP number */
61   unsigned int connect_attempts:4;      /* Used for connect speed throttling: Number of clients that connected with this IP number
62                                            or `15' when then real value is >= 15.  This value is only valid when the last connect
63                                            was less then IPCHECK_CLONE_PERIOD seconds ago, it should considered to be 0 otherwise. */
64   unsigned int free_targets:4;  /* Number of free targets that the next local client will inherit on connect,
65                                    or HAS_TARGETS_MAGIC when ip_targets.ptr is a pointer to a ip_targets_st. */
66 };
67
68 struct IPregistry_vector {
69   unsigned short length;
70   unsigned short allocated_length;
71   struct IPregistry *vector;
72 };
73
74 #define HASHTABSIZE 0x2000      /* Must be power of 2 */
75 static struct IPregistry_vector IPregistry_hashtable[HASHTABSIZE];
76
77 /*
78  * Calculate a `hash' value between 0 and HASHTABSIZE, from the internet address `in_addr'.
79  * Apply it immedeately to the table, effectively hiding the table itself.
80  */
81 #define CALCULATE_HASH(in_addr) \
82   struct IPregistry_vector *hash; \
83   do { register unsigned int ip = (in_addr).s_addr; \
84        hash = &IPregistry_hashtable[((ip >> 14) + (ip >> 7) + ip) & (HASHTABSIZE - 1)]; } while(0)
85
86 /*
87  * Fit `now' in an unsigned short, the advantage is that we use less memory `struct IPregistry::last_connect' can be smaller
88  * while the only disadvantage is that if someone reconnects after exactly 18 hours and 12 minutes, and NOBODY with the
89  * same _hash_ value for this IP-number did disconnect in the meantime, then the server will think he reconnected immedeately.
90  * In other words: No disadvantage at all.
91  */
92 #define BITMASK 0xffff          /* Same number of bits as `struct IPregistry::last_connect' */
93 #define NOW ((unsigned short)(now & BITMASK))
94 #define CONNECTED_SINCE(x) ((unsigned short)((now & BITMASK) - (x)->last_connect))
95
96 #define IPCHECK_CLONE_LIMIT 2
97 #define IPCHECK_CLONE_PERIOD 20
98 #define IPCHECK_CLONE_DELAY 600
99
100 #define HAS_TARGETS_MAGIC 15
101 #define HAS_TARGETS(entry) ((entry)->free_targets == HAS_TARGETS_MAGIC)
102
103 #if STARTTARGETS >= HAS_TARGETS_MAGIC
104 #error "That doesn't fit in 4 bits, does it?"
105 #endif
106
107 /* IP(entry) returns the `struct in_addr' of the IPregistry. */
108 #define IP(entry) (HAS_TARGETS(entry) ? (entry)->ip_targets.ptr->ip : (entry)->ip_targets.ip)
109 #define FREE_TARGETS(entry) (HAS_TARGETS(entry) ? (entry)->ip_targets.ptr->free_targets : (entry)->free_targets)
110
111 static unsigned short count = 10000, average_length = 4;
112
113 static struct IPregistry *IPregistry_add(struct IPregistry_vector *iprv)
114 {
115   if (iprv->length == iprv->allocated_length)
116   {
117     iprv->allocated_length += 4;
118     iprv->vector =
119         (struct IPregistry *)RunRealloc(iprv->vector,
120         iprv->allocated_length * sizeof(struct IPregistry));
121   }
122   return &iprv->vector[iprv->length++];
123 }
124
125 static struct IPregistry *IPregistry_find(struct IPregistry_vector *iprv,
126     struct in_addr ip)
127 {
128   if (iprv->length > 0)
129   {
130     struct IPregistry *i, *end = &iprv->vector[iprv->length];
131     for (i = &iprv->vector[0]; i < end; ++i)
132       if (IP(i).s_addr == ip.s_addr)
133         return i;
134   }
135   return NULL;
136 }
137
138 static struct IPregistry *IPregistry_find_with_expire(struct IPregistry_vector
139     *iprv, struct in_addr ip)
140 {
141   struct IPregistry *last = &iprv->vector[iprv->length - 1];    /* length always > 0 because searched element always exists */
142   struct IPregistry *curr;
143   struct IPregistry *retval = NULL;     /* Core dump if we find nothing :/ - can be removed when code is stable */
144
145   for (curr = &iprv->vector[0]; curr < last;)
146   {
147     if (IP(curr).s_addr == ip.s_addr)
148       /* `curr' is element we looked for */
149       retval = curr;
150     else if (curr->connected == 0)
151     {
152       if (CONNECTED_SINCE(curr) > 600U) /* Don't touch this number, it has statistical significance */
153       {
154         /* `curr' expired */
155         if (HAS_TARGETS(curr))
156           RunFree(curr->ip_targets.ptr);
157         *curr = *last--;
158         iprv->length--;
159         if (--count == 0)
160         {
161           /* Make ever 10000 disconnects an estimation of the average vector length */
162           count = 10000;
163           average_length =
164               (nrof.clients + nrof.unknowns + nrof.local_servers) / HASHTABSIZE;
165         }
166         /* Now check the new element (last) that was moved to this position */
167         continue;
168       }
169       else if (CONNECTED_SINCE(curr) > 120U && HAS_TARGETS(curr))
170       {
171         /* Expire storage of targets */
172         struct in_addr ip1 = curr->ip_targets.ptr->ip;
173         curr->free_targets = curr->ip_targets.ptr->free_targets;
174         RunFree(curr->ip_targets.ptr);
175         curr->ip_targets.ip = ip1;
176       }
177     }
178     /* Did not expire, check next element */
179     ++curr;
180   }
181   /* Now check the last element in the list (curr == last) */
182   if (IP(curr).s_addr == ip.s_addr)
183     /* `curr' is element we looked for */
184     retval = curr;
185   else if (curr->connected == 0)
186   {
187     if (CONNECTED_SINCE(curr) > 600U)   /* Don't touch this number, it has statistical significance */
188     {
189       /* `curr' expired */
190       if (HAS_TARGETS(curr))
191         RunFree(curr->ip_targets.ptr);
192       iprv->length--;
193       if (--count == 0)
194       {
195         /* Make ever 10000 disconnects an estimation of the average vector length */
196         count = 10000;
197         average_length =
198             (nrof.clients + nrof.unknowns + nrof.local_servers) / HASHTABSIZE;
199       }
200     }
201     else if (CONNECTED_SINCE(curr) > 120U && HAS_TARGETS(curr))
202     {
203       /* Expire storage of targets */
204       struct in_addr ip1 = curr->ip_targets.ptr->ip;
205       curr->free_targets = curr->ip_targets.ptr->free_targets;
206       RunFree(curr->ip_targets.ptr);
207       curr->ip_targets.ip = ip1;
208     }
209   }
210   /* Do we need to shrink the vector? */
211   if (iprv->allocated_length > average_length
212       && iprv->allocated_length - iprv->length >= 4)
213   {
214     struct IPregistry *newpos;
215     iprv->allocated_length = iprv->length;
216     newpos =
217         (struct IPregistry *)RunRealloc(iprv->vector,
218         iprv->allocated_length * sizeof(struct IPregistry));
219     if (newpos != iprv->vector) /* Is this ever true? */
220     {
221       retval =
222           (struct IPregistry *)((char *)retval + ((char *)newpos -
223           (char *)iprv->vector));
224       iprv->vector = newpos;
225     }
226   }
227   return retval;
228 }
229
230 static void reset_connect_time(struct IPregistry *entry)
231 {
232   unsigned int previous_free_targets;
233
234   /* Apply aging */
235   previous_free_targets =
236       FREE_TARGETS(entry) + CONNECTED_SINCE(entry) / TARGET_DELAY;
237   if (previous_free_targets > STARTTARGETS)
238     previous_free_targets = STARTTARGETS;
239   if (HAS_TARGETS(entry))
240     entry->ip_targets.ptr->free_targets = previous_free_targets;
241   else
242     entry->free_targets = previous_free_targets;
243
244   entry->last_connect = NOW;
245 }
246
247 /*
248  * IPcheck_local_connect
249  *
250  * Event:
251  *   A new connection was accept()-ed with IP number `cptr->ip.s_addr'.
252  *
253  * Action:
254  *   Update the IPcheck registry.
255  *   Return < 0 if the connection should be rejected, otherwise 0.
256  *     -1 : Throttled
257  *     -2 : Too many connections from your host
258  *
259  * Throttling:
260  *
261  * A connection should be rejected when a connection from the same IP number was
262  * received IPCHECK_CLONE_LIMIT times before this connect attempt, with
263  * reconnect intervals of IPCHECK_CLONE_PERIOD seconds or less.
264  *
265  * Free target inheritance:
266  *
267  * When the client is accepted, then the number of Free Targets
268  * of the cptr is set to the value stored in the found IPregistry
269  * structure, or left at STARTTARGETS.  This can be done by changing
270  * cptr->nexttarget to be `now - (TARGET_DELAY * (FREE_TARGETS - 1))',
271  * where FREE_TARGETS may range from 0 till STARTTARGETS.
272  */
273 int IPcheck_local_connect(aClient *cptr)
274 {
275   struct IPregistry *entry;
276   CALCULATE_HASH(cptr->ip);
277   SetIPChecked(cptr);           /* Mark that we did add/update an IPregistry entry */
278   if (!(entry = IPregistry_find(hash, cptr->ip)))
279   {
280     entry = IPregistry_add(hash);
281     entry->ip_targets.ip = cptr->ip;    /* The IP number of registry entry */
282     entry->last_connect = NOW;  /* Seconds since last connect (attempt) */
283     entry->connected = 1;       /* Number of currently connected clients with this IP number */
284     entry->connect_attempts = 1;        /* Number of clients that connected with this IP number */
285     entry->free_targets = STARTTARGETS; /* Number of free targets that a client gets on connect */
286     return 0;
287   }
288 #ifdef GODMODE
289   sendto_one(cptr,
290       "ERROR :I saw your face before my friend (connected: %u; connect_attempts %u; free_targets %u)",
291       entry->connected, entry->connect_attempts, FREE_TARGETS(entry));
292 #endif
293   /* Note that this also connects server connects.  It is hard and not interesting, to change that. */
294   if (++(entry->connected) == 0)        /* Don't allow more then 255 connects from one IP number, ever */
295     return -2;
296   if (CONNECTED_SINCE(entry) > IPCHECK_CLONE_PERIOD)
297     entry->connect_attempts = 0;
298   reset_connect_time(entry);
299   if (++(entry->connect_attempts) == 0) /* Check for overflow */
300     --(entry->connect_attempts);
301   if (entry->connect_attempts <= IPCHECK_CLONE_LIMIT)
302     cptr->nexttarget = now - (TARGET_DELAY * (FREE_TARGETS(entry) - 1));
303 #ifdef DEBUGMODE
304   else
305 #else
306   else if (now - me.since > IPCHECK_CLONE_DELAY)        /* Don't refuse connection when we just rebooted the server */
307 #endif
308     return -1;
309   return 0;
310 }
311
312 /*
313  * IPcheck_remote_connect
314  *
315  * Event:
316  *   A remote client connected to Undernet, with IP number `cptr->ip.s_addr'
317  *   and hostname `hostname'.
318  *
319  * Action:
320  *   Update the IPcheck registry.
321  *   Return -1 on failure, 0 on success.
322  */
323 int IPcheck_remote_connect(aClient *cptr, const char *UNUSED(hostname),
324     int is_burst)
325 {
326   struct IPregistry *entry;
327   CALCULATE_HASH(cptr->ip);
328   SetIPChecked(cptr);           /* Mark that we did add/update an IPregistry entry */
329   if (!(entry = IPregistry_find(hash, cptr->ip)))
330   {
331     entry = IPregistry_add(hash);
332     entry->ip_targets.ip = cptr->ip;    /* The IP number of registry entry */
333     entry->last_connect = NOW;  /* Seconds since last connect (attempt) */
334     entry->connected = 1;       /* Number of currently connected clients with this IP number */
335     entry->connect_attempts = is_burst ? 1 : 0; /* Number of clients that connected with this IP number */
336     entry->free_targets = STARTTARGETS; /* Number of free targets that a client gets on connect */
337   }
338   else
339   {
340 #ifdef GODMODE
341     sendto_one(cptr,
342         "%s NOTICE %s%s :I saw your face before my friend (connected: %u; connect_attempts %u; free_targets %u)",
343         NumServ(&me), NumNick(cptr), entry->connected, entry->connect_attempts,
344         FREE_TARGETS(entry));
345 #endif
346     if (++(entry->connected) == 0)      /* Don't allow more then 255 connects from one IP number, ever */
347       return -1;
348     if (CONNECTED_SINCE(entry) > IPCHECK_CLONE_PERIOD)
349       entry->connect_attempts = 0;
350     if (!is_burst)
351     {
352       if (++(entry->connect_attempts) == 0)     /* Check for overflow */
353         --(entry->connect_attempts);
354       reset_connect_time(entry);
355     }
356   }
357   return 0;
358 }
359
360 /*
361  * IPcheck_connect_fail
362  *
363  * Event:
364  *   This local client failed to connect due to legal reasons.
365  *
366  * Action:
367  *   Neutralize the effect of calling IPcheck_local_connect, in such
368  *   a way that the client won't be penalized when trying to reconnect
369  *   again.
370  */
371 void IPcheck_connect_fail(aClient *cptr)
372 {
373   struct IPregistry *entry;
374   CALCULATE_HASH(cptr->ip);
375   entry = IPregistry_find(hash, cptr->ip);
376   entry->connect_attempts--;
377 }
378
379 /*
380  * IPcheck_connect_succeeded
381  *
382  * Event:
383  *   A client succeeded to finish the registration.
384  *
385  * Finish IPcheck registration of a successfully, locally connected client.
386  */
387 void IPcheck_connect_succeeded(aClient *cptr)
388 {
389   struct IPregistry *entry;
390   const char *tr = "";
391   CALCULATE_HASH(cptr->ip);
392   entry = IPregistry_find(hash, cptr->ip);
393   if (HAS_TARGETS(entry))
394   {
395     memcpy(cptr->targets, entry->ip_targets.ptr->targets, MAXTARGETS);
396     tr = " tr";
397   }
398   sendto_one(cptr, ":%s NOTICE %s :on %u ca %u(%u) ft %u(%u)%s",
399       me.name, cptr->name, entry->connected, entry->connect_attempts,
400       IPCHECK_CLONE_LIMIT, FREE_TARGETS(entry), STARTTARGETS, tr);
401 }
402
403 /*
404  * IPcheck_disconnect
405  *
406  * Event:
407  *   A local client disconnected or a remote client left Undernet.
408  *
409  * Action:
410  *   Update the IPcheck registry.
411  *   Remove all expired IPregistry structures from the hash bucket
412  *     that belongs to this clients IP number.
413  */
414 void IPcheck_disconnect(aClient *cptr)
415 {
416   struct IPregistry *entry;
417   CALCULATE_HASH(cptr->ip);
418   entry = IPregistry_find_with_expire(hash, cptr->ip);
419   if (--(entry->connected) == 0)        /* If this was the last one, set `last_connect' to disconnect time (used for expiration) */
420   {
421     if (CONNECTED_SINCE(entry) > IPCHECK_CLONE_LIMIT * IPCHECK_CLONE_PERIOD)
422       entry->connect_attempts = 0;      /* Otherwise we'd penetalize for this old value if the client reconnects within 20 seconds */
423     reset_connect_time(entry);
424   }
425   if (MyConnect(cptr))
426   {
427     unsigned int inheritance;
428     /* Copy the clients targets */
429     if (HAS_TARGETS(entry))
430     {
431       entry->free_targets = entry->ip_targets.ptr->free_targets;
432       RunFree(entry->ip_targets.ptr);
433     }
434     entry->ip_targets.ptr =
435         (struct ip_targets_st *)RunMalloc(sizeof(struct ip_targets_st));
436     entry->ip_targets.ptr->ip = cptr->ip;
437     entry->ip_targets.ptr->free_targets = entry->free_targets;
438     entry->free_targets = HAS_TARGETS_MAGIC;
439     memcpy(entry->ip_targets.ptr->targets, cptr->targets, MAXTARGETS);
440     /*
441      * This calculation can be pretty unfair towards large multi-user hosts, but
442      * there is "nothing" we can do without also allowing spam bots to send more
443      * messages or by drastically increasing the ammount of memory used in the IPregistry.
444      *
445      * The problem is that when a client disconnects, leaving no free targets, then
446      * the next client from that IP number has to pay for it (getting no free targets).
447      * But ALSO the next client, and the next client, and the next client etc - until
448      * another client disconnects that DOES leave free targets.  The reason for this
449      * is that if there are 10 SPAM bots, and they all disconnect at once, then they
450      * ALL should get no free targets when reconnecting.  We'd need to store an entry
451      * per client (instead of per IP number) to avoid this.
452      */
453     if (cptr->nexttarget <= now)
454       inheritance = (now - cptr->nexttarget) / TARGET_DELAY + 1;        /* Number of free targets */
455     else
456       inheritance = 0;
457     /* Add bonus, this is pretty fuzzy, but it will help in some cases. */
458     if (now - cptr->firsttime > 600)    /* Was longer then 10 minutes online? */
459       inheritance += (now - cptr->firsttime - 600) / TARGET_DELAY;
460     /* Finally, store smallest value for Judgement Day */
461     if (inheritance < entry->ip_targets.ptr->free_targets)
462       entry->ip_targets.ptr->free_targets = inheritance;
463   }
464 }
465
466 /*
467  * IPcheck_nr
468  *
469  * Returns number of clients with the same IP number
470  */
471 unsigned short IPcheck_nr(aClient *cptr)
472 {
473   struct IPregistry *entry;
474   CALCULATE_HASH(cptr->ip);
475   entry = IPregistry_find(hash, cptr->ip);
476   return (entry ? entry->connected : 0);
477 }