2 * Copyright (c) 2003 Proofpoint, Inc. and its suppliers.
5 * By using this file, you agree to the terms and conditions set
6 * forth in the LICENSE file which can be found at the top level of
7 * the sendmail distribution.
9 * Contributed by Jose Marcio Martins da Cruz - Ecole des Mines de Paris
10 * Jose-Marcio.Martins@ensmp.fr
13 /* a part of this code is based on inetd.c for which this copyright applies: */
15 * Copyright (c) 1983, 1991, 1993, 1994
16 * The Regents of the University of California. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * 3. All advertising materials mentioning features or use of this software
27 * must display the following acknowledgement:
28 * This product includes software developed by the University of
29 * California, Berkeley and its contributors.
30 * 4. Neither the name of the University nor the names of its contributors
31 * may be used to endorse or promote products derived from this software
32 * without specific prior written permission.
34 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48 SM_RCSID("@(#)$Id: ratectrl.c,v 8.14 2013-11-22 20:51:56 ca Exp $")
50 static int client_rate __P((time_t, SOCKADDR *, int));
51 static int total_rate __P((time_t, bool));
52 static unsigned int gen_hash __P((SOCKADDR *));
53 static void rate_init __P((void));
56 ** CONNECTION_RATE_CHECK - updates connection history data
57 ** and computes connection rate for the given host
60 ** hostaddr -- IP address of SMTP client
67 ** updates connection history
70 ** For each connection, this call shall be
71 ** done only once with the value true for the
73 ** Typically, this call is done with the value
74 ** true by the father, and once again with
75 ** the value false by the children.
79 connection_rate_check(hostaddr, e)
84 int totalrate, clientrate;
85 static int clientconn = 0;
89 sm_syslog(LOG_INFO, NOQID, "connection_rate_check entering...");
92 /* update server connection rate */
93 totalrate = total_rate(now, e == NULL);
95 sm_syslog(LOG_INFO, NOQID, "global connection rate: %d", totalrate);
98 /* update client connection rate */
99 clientrate = client_rate(now, hostaddr, e == NULL ? SM_CLFL_UPDATE : SM_CLFL_NONE);
102 clientconn = count_open_connections(hostaddr);
108 sm_snprintf(s, sizeof(s), "%d", clientrate);
109 macdefine(&e->e_macro, A_TEMP, macid("{client_rate}"), s);
110 sm_snprintf(s, sizeof(s), "%d", totalrate);
111 macdefine(&e->e_macro, A_TEMP, macid("{total_rate}"), s);
112 sm_snprintf(s, sizeof(s), "%d", clientconn);
113 macdefine(&e->e_macro, A_TEMP, macid("{client_connections}"),
120 ** Data declarations needed to evaluate connection rate
123 static int CollTime = 60;
126 ** time granularity: 10s (that's one "tick")
127 ** will be initialised to ConnectionRateWindowSize/CHTSIZE
128 ** before being used the first time
131 static int ChtGran = -1;
132 static CHash_T CHashAry[CPMHSIZE];
133 static CTime_T srv_Times[CHTSIZE];
136 # define MAX_CT_STEPS 10
140 ** RATE_INIT - initialize local data
149 ** initializes static global data
157 ChtGran = ConnectionRateWindowSize / CHTSIZE;
160 memset(CHashAry, 0, sizeof(CHashAry));
161 memset(srv_Times, 0, sizeof(srv_Times));
166 ** GEN_HASH - calculate a hash value
169 ** saddr - client address
188 switch (saddr->sa.sa_family)
192 p = (char *)&saddr->sin.sin_addr;
193 addrlen = sizeof(struct in_addr);
198 p = (char *)&saddr->sin6.sin6_addr;
199 addrlen = sizeof(struct in6_addr);
201 #endif /* NETINET6 */
203 /* should not happen */
207 /* compute hash value */
208 for (i = 0; i < addrlen; ++i, ++p)
210 hv = (hv << 5) ^ (hv >> 23) ^ *p;
211 hv = (hv ^ (hv >> 16));
217 hv += (c<<11) ^ (c>>1);
218 hv ^= (d<<14) + (d<<7) + (d<<4) + d;
230 #else /* HASH_ALG == 1 */
231 # error "unsupported HASH_ALG"
232 hv = ((hv << 1) ^ (*p & 0377)) % cctx->cc_size; ???
233 #endif /* HASH_ALG == 1 */
239 ** CONN_LIMIT - Evaluate connection limits
242 ** e -- envelope (_FFR_OCC, for logging only)
243 ** now - current time in secs
244 ** saddr - client address
245 ** clflags - update data / check only / ...
246 ** hashary - hash array
247 ** ratelimit - rate limit (_FFR_OCC only)
248 ** conclimit - concurrency limit (_FFR_OCC only)
252 ** outgoing: limit exceeded?
255 ** connection rate (connections / ConnectionRateWindowSize)
259 conn_limits(e, now, saddr, clflags, hashary, ratelimit, conclimit)
271 CHash_T *chBest = NULL;
276 bool exceeded = false;
279 #if RATECTL_DEBUG || _FFR_OCC
284 hv = gen_hash(saddr);
285 ticks = now / ChtGran;
288 for (i = 0; i < MAX_CT_STEPS; ++i)
290 CHash_T *ch = &hashary[(hv + i) & CPMHMASK];
293 if (saddr->sa.sa_family == AF_INET &&
294 ch->ch_Family == AF_INET &&
295 (saddr->sin.sin_addr.s_addr == ch->ch_Addr4.s_addr ||
296 ch->ch_Addr4.s_addr == 0))
304 if (saddr->sa.sa_family == AF_INET6 &&
305 ch->ch_Family == AF_INET6 &&
306 (IN6_ARE_ADDR_EQUAL(&saddr->sin6.sin6_addr,
307 &ch->ch_Addr6) != 0 ||
308 IN6_IS_ADDR_UNSPECIFIED(&ch->ch_Addr6)))
314 #endif /* NETINET6 */
315 if (chBest == NULL || ch->ch_LTime == 0 ||
316 ch->ch_LTime < chBest->ch_LTime)
320 /* Let's update data... */
321 if ((clflags & (SM_CLFL_UPDATE|SM_CLFL_EXC)) != 0)
323 if (coll && (now - chBest->ch_LTime < CollTime))
326 ** increment the number of collisions last
327 ** CollTime for this client
333 ** Maybe shall log if collision rate is too high...
334 ** and take measures to resize tables
335 ** if this is the case
340 ** If it's not a match, then replace the data.
341 ** Note: this purges the history of a colliding entry,
342 ** which may cause "overruns", i.e., if two entries are
343 ** "cancelling" each other out, then they may exceed
344 ** the limits that are set. This might be mitigated a bit
345 ** by the above "best of 5" function however.
347 ** Alternative approach: just use the old data, which may
348 ** cause false positives however.
349 ** To activate this, deactivate the memset() call.
355 if (saddr->sa.sa_family == AF_INET)
357 chBest->ch_Family = AF_INET;
358 chBest->ch_Addr4 = saddr->sin.sin_addr;
362 if (saddr->sa.sa_family == AF_INET6)
364 chBest->ch_Family = AF_INET6;
365 chBest->ch_Addr6 = saddr->sin6.sin6_addr;
367 #endif /* NETINET6 */
368 memset(chBest->ch_Times, '\0',
369 sizeof(chBest->ch_Times));
372 chBest->ch_LTime = now;
373 ct = &chBest->ch_Times[ticks % CHTSIZE];
375 if (ct->ct_Ticks != ticks)
377 ct->ct_Ticks = ticks;
380 if ((clflags & SM_CLFL_UPDATE) != 0)
384 /* Now let's count connections on the window */
385 for (i = 0; i < CHTSIZE; ++i)
389 cth = &chBest->ch_Times[i];
390 if (cth->ct_Ticks <= ticks && cth->ct_Ticks >= ticks - CHTSIZE)
391 cnt += cth->ct_Count;
395 if (ct != NULL && ((clflags & SM_CLFL_EXC) != 0))
400 prv = &(ct->ct_Count);
404 else if (ratelimit < 0 && ct->ct_Count > 0)
408 if (chBest != NULL && ((clflags & SM_CLFL_EXC) != 0))
412 if (chBest->ch_oc < conclimit)
413 pcv = &(chBest->ch_oc);
417 else if (conclimit < 0 && chBest->ch_oc > 0)
425 #if RATECTL_DEBUG || _FFR_OCC
434 logit = exceeded || LogLevel > 11;
437 sm_syslog(LOG_DEBUG, e != NULL ? e->e_id : NOQID,
438 "conn_limits: addr=%s, flags=0x%x, rate=%d/%d, conc=%d/%d, exc=%d",
439 saddr->sa.sa_family == AF_INET
440 ? inet_ntoa(saddr->sin.sin_addr) : "???",
441 clflags, cnt, ratelimit,
443 chBest != NULL ? chBest->ch_oc : -1
456 if ((clflags & SM_CLFL_EXC) != 0)
463 ** CLIENT_RATE - Evaluate connection rate per SMTP client
466 ** now - current time in secs
467 ** saddr - client address
468 ** clflags - update data / check only
471 ** connection rate (connections / ConnectionRateWindowSize)
474 ** update static global data
478 client_rate(now, saddr, clflags)
484 return conn_limits(NULL, now, saddr, clflags, CHashAry, 0, 0);
488 ** TOTAL_RATE - Evaluate global connection rate
491 ** now - current time in secs
492 ** update - update data / check only
495 ** connection rate (connections / ConnectionRateWindowSize)
499 total_rate(now, update)
509 ticks = now / ChtGran;
511 /* Let's update data */
514 ct = &srv_Times[ticks % CHTSIZE];
516 if (ct->ct_Ticks != ticks)
518 ct->ct_Ticks = ticks;
524 /* Let's count connections on the window */
525 for (i = 0; i < CHTSIZE; ++i)
529 if (ct->ct_Ticks <= ticks && ct->ct_Ticks >= ticks - CHTSIZE)
534 sm_syslog(LOG_WARNING, NOQID,
535 "total: cnt=%d, CHTSIZE=%d, ChtGran=%d",
536 cnt, CHTSIZE, ChtGran);
542 #if RATECTL_DEBUG || _FFR_OCC
550 ticks = time(NULL) / ChtGran;
551 sm_io_fprintf(fp, SM_TIME_DEFAULT, "dump_ch\n");
552 for (i = 0; i < CPMHSIZE; i++)
554 CHash_T *ch = &CHashAry[i];
559 valid = (ch->ch_Family == AF_INET);
561 sm_io_fprintf(fp, SM_TIME_DEFAULT, "ip=%s ",
562 inet_ntoa(ch->ch_Addr4));
563 # endif /* NETINET */
565 if (ch->ch_Family == AF_INET6)
570 str = anynet_ntop(&ch->ch_Addr6, buf, sizeof(buf));
572 sm_io_fprintf(fp, SM_TIME_DEFAULT, "ip=%s ",
575 # endif /* NETINET6 */
580 for (j = 0; j < CHTSIZE; ++j)
584 cth = &ch->ch_Times[j];
585 if (cth->ct_Ticks <= ticks && cth->ct_Ticks >= ticks - CHTSIZE)
586 cnt += cth->ct_Count;
589 sm_io_fprintf(fp, SM_TIME_DEFAULT, "time=%ld cnt=%d ",
590 (long) ch->ch_LTime, cnt);
592 sm_io_fprintf(fp, SM_TIME_DEFAULT, "oc=%d", ch->ch_oc);
594 sm_io_fprintf(fp, SM_TIME_DEFAULT, "\n");
596 sm_io_flush(fp, SM_TIME_DEFAULT);
599 #endif /* RATECTL_DEBUG || _FFR_OCC */