Fix a crash in /stats i <server> <mask>.
[ircu2.10.12-pk.git] / ircd / s_stats.c
1 /*
2  * IRC - Internet Relay Chat, ircd/s_stats.c
3  * Copyright (C) 2000 Joseph Bongaarts
4  *
5  * See file AUTHORS in IRC package for additional names of
6  * the programmers.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 1, or (at your option)
11  * any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22 #include "config.h"
23
24 #include "class.h"
25 #include "client.h"
26 #include "gline.h"
27 #include "hash.h"
28 #include "ircd.h"
29 #include "ircd_chattr.h"
30 #include "ircd_events.h"
31 #include "ircd_features.h"
32 #include "ircd_crypt.h"
33 #include "ircd_log.h"
34 #include "ircd_reply.h"
35 #include "ircd_string.h"
36 #include "listener.h"
37 #include "list.h"
38 #include "match.h"
39 #include "motd.h"
40 #include "msg.h"
41 #include "msgq.h"
42 #include "numeric.h"
43 #include "numnicks.h"
44 #include "querycmds.h"
45 #include "res.h"
46 #include "s_bsd.h"
47 #include "s_conf.h"
48 #include "s_debug.h"
49 #include "s_misc.h"
50 #include "s_serv.h"
51 #include "s_stats.h"
52 #include "s_user.h"
53 #include "send.h"
54 #include "struct.h"
55 #include "userload.h"
56
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <sys/time.h>
61
62 /** @file
63  * @brief Report configuration lines and other statistics from this
64  * server.
65  * @version $Id$
66  *
67  * Note: The info is reported in the order the server uses
68  *       it--not reversed as in ircd.conf!
69  */
70
71 /* The statsinfo array should only be used in this file, but just TRY
72  * telling the compiler that you want to forward declare a static
73  * array without specifying a length, and see how it responds.  So we
74  * forward declare it "extern".
75  */
76 extern struct StatDesc statsinfo[];
77
78 /** Report items from #GlobalConfList.
79  * Uses sd->sd_funcdata as a filter for ConfItem::status.
80  * @param[in] sptr Client requesting statistics.
81  * @param[in] sd Stats descriptor for request.
82  * @param[in] param Extra parameter from user (ignored).
83  */
84 static void
85 stats_configured_links(struct Client *sptr, const struct StatDesc* sd,
86                        char* param)
87 {
88   static char null[] = "<NULL>";
89   struct ConfItem *tmp;
90   unsigned short int port;
91   int maximum;
92   char *host, *pass, *name, *username, *hub_limit;
93
94   for (tmp = GlobalConfList; tmp; tmp = tmp->next)
95   {
96     if ((tmp->status & sd->sd_funcdata))
97     {
98       host = BadPtr(tmp->host) ? null : tmp->host;
99       pass = BadPtr(tmp->passwd) ? null : tmp->passwd;
100       name = BadPtr(tmp->name) ? null : tmp->name;
101       username = BadPtr(tmp->username) ? null : tmp->username;
102       hub_limit = BadPtr(tmp->hub_limit) ? null : tmp->hub_limit;
103       maximum = tmp->maximum;
104       port = tmp->address.port;
105
106       if (tmp->status & CONF_UWORLD)
107         send_reply(sptr, RPL_STATSULINE, host);
108       else if (tmp->status & CONF_SERVER)
109         send_reply(sptr, RPL_STATSCLINE, name, "", "*", port, maximum, hub_limit, get_conf_class(tmp));
110       else if (tmp->status & CONF_CLIENT)
111         send_reply(sptr, RPL_STATSILINE,
112                    (tmp->host ? tmp->host : "*"), maximum,
113                    (name[0] == ':' ? "0" : ""), (tmp->name ? tmp->name : "*"),
114                    port, get_conf_class(tmp));
115       else if (tmp->status & CONF_OPERATOR)
116         send_reply(sptr, RPL_STATSOLINE, username, host, name, get_conf_class(tmp));
117     }
118   }
119 }
120
121 /** Report connection rules from conf_get_crule_list().
122  * Uses sd->sd_funcdata as a filter for CRuleConf::type.
123  * @param[in] to Client requesting statistics.
124  * @param[in] sd Stats descriptor for request.
125  * @param[in] param Extra parameter from user (ignored).
126  */
127 static void
128 stats_crule_list(struct Client* to, const struct StatDesc *sd,
129                  char *param)
130 {
131   const struct CRuleConf* p = conf_get_crule_list();
132
133   for ( ; p; p = p->next)
134   {
135     if (p->type & sd->sd_funcdata)
136       send_reply(to, RPL_STATSDLINE, sd->sd_c, p->hostmask, p->rule);
137   }
138 }
139
140 /** Report active event engine name.
141  * @param[in] to Client requesting statistics.
142  * @param[in] sd Stats descriptor for request (ignored).
143  * @param[in] param Extra parameter from user (ignored).
144  */
145 static void
146 stats_engine(struct Client *to, const struct StatDesc *sd, char *param)
147 {
148   send_reply(to, RPL_STATSENGINE, engine_name());
149 }
150
151 /** Report client access lists.
152  * @param[in] to Client requesting statistics.
153  * @param[in] sd Stats descriptor for request.
154  * @param[in] param Filter for hostname or IP (NULL to show all).
155  */
156 static void
157 stats_access(struct Client *to, const struct StatDesc *sd, char *param)
158 {
159   struct ConfItem *aconf;
160   int wilds = 0;
161   int count = 1000;
162
163   if (!param)
164   {
165     stats_configured_links(to, sd, param);
166     return;
167   }
168
169   wilds = string_has_wildcards(param);
170
171   for (aconf = GlobalConfList; aconf; aconf = aconf->next)
172   {
173     if (aconf->status != CONF_CLIENT)
174       continue;
175     if (wilds ? ((aconf->host && !mmatch(aconf->host, param))
176                  || (aconf->name && !mmatch(aconf->name, param)))
177         : ((aconf->host && !match(param, aconf->host))
178            || (aconf->name && !match(param, aconf->name))))
179     {
180       send_reply(to, RPL_STATSILINE,
181                  (aconf->host ? aconf->host : "*"), aconf->maximum,
182                  (aconf->name && aconf->name[0] == ':' ? "0":""),
183                  aconf->name ? aconf->name : "*",
184                  aconf->address.port, get_conf_class(aconf));
185       if (--count == 0)
186         break;
187     }
188   }
189 }
190
191
192 /** Report DenyConf entries.
193  * @param[in] to Client requesting list.
194  */
195 static void
196 report_deny_list(struct Client* to)
197 {
198   const struct DenyConf* p = conf_get_deny_list();
199   for ( ; p; p = p->next)
200     send_reply(to, RPL_STATSKLINE, p->bits > 0 ? 'k' : 'K',
201                p->usermask ? p->usermask : "*",
202                p->hostmask ? p->hostmask : "*",
203                p->message ? p->message : "(none)",
204                p->realmask ? p->realmask : "*");
205 }
206
207 /** Report K/k-lines to a user.
208  * @param[in] sptr Client requesting statistics.
209  * @param[in] sd Stats descriptor for request (ignored).
210  * @param[in] mask Filter for hostmasks to show.
211  */
212 static void
213 stats_klines(struct Client *sptr, const struct StatDesc *sd, char *mask)
214 {
215   int wilds = 0;
216   int count = 3;
217   int limit_query = 0;
218   char *user  = 0;
219   char *host;
220   const struct DenyConf* conf;
221
222   if (!IsAnOper(sptr))
223     limit_query = 1;
224
225   if (!mask)
226   {
227     if (limit_query)
228       need_more_params(sptr, "STATS K");
229     else
230       report_deny_list(sptr);
231     return;
232   }
233
234   if (!limit_query)
235   {
236     wilds = string_has_wildcards(mask);
237     count = 1000;
238   }
239   if ((host = strchr(mask, '@')))
240   {
241     user = mask;
242     *host++ = '\0';
243   }
244   else
245     host = mask;
246
247   for (conf = conf_get_deny_list(); conf; conf = conf->next)
248   {
249     if ((!wilds && ((user || conf->hostmask) &&
250                     !match(conf->hostmask, host) &&
251                     (!user || !match(conf->usermask, user)))) ||
252         (wilds && !mmatch(host, conf->hostmask) &&
253          (!user || !mmatch(user, conf->usermask))))
254     {
255       send_reply(sptr, RPL_STATSKLINE, conf->bits > 0 ? 'k' : 'K',
256                  conf->usermask ? conf->usermask : "*",
257                  conf->hostmask ? conf->hostmask : "*",
258                  conf->message ? conf->message : "(none)",
259                  conf->realmask ? conf->realmask : "*");
260       if (--count == 0)
261         return;
262     }
263   }
264 }
265
266 /** Report on servers and/or clients connected to the network.
267  * @param[in] sptr Client requesting statistics.
268  * @param[in] sd Stats descriptor for request (ignored).
269  * @param[in] name Filter for client names to show.
270  */
271 static void
272 stats_links(struct Client* sptr, const struct StatDesc* sd, char* name)
273 {
274   struct Client *acptr;
275   int i;
276   int wilds = 0;
277
278   if (name)
279     wilds = string_has_wildcards(name);
280
281   /*
282    * Send info about connections which match, or all if the
283    * mask matches me.name.  Only restrictions are on those who
284    * are invisible not being visible to 'foreigners' who use
285    * a wild card based search to list it.
286    */
287   send_reply(sptr, SND_EXPLICIT | RPL_STATSLINKINFO, "Connection SendQ "
288              "SendM SendKBytes RcveM RcveKBytes :Open since");
289     for (i = 0; i <= HighestFd; i++)
290     {
291       if (!(acptr = LocalClientArray[i]))
292         continue;
293       /* Don't return clients when this is a request for `all' */
294       if (!name && IsUser(acptr))
295         continue;
296       /* Don't show invisible people to non opers unless they know the nick */
297       if (IsInvisible(acptr) && (!name || wilds) && !IsAnOper(acptr) &&
298           (acptr != sptr))
299         continue;
300       /* Only show the ones that match the given mask - if any */
301       if (name && wilds && match(name, cli_name(acptr)))
302         continue;
303       /* Skip all that do not match the specific query */
304       if (!(!name || wilds) && 0 != ircd_strcmp(name, cli_name(acptr)))
305         continue;
306       send_reply(sptr, SND_EXPLICIT | RPL_STATSLINKINFO,
307                  "%s %u %u %Lu %u %Lu :%Tu",
308                  (*(cli_name(acptr))) ? cli_name(acptr) : "<unregistered>",
309                  (int)MsgQLength(&(cli_sendQ(acptr))), (int)cli_sendM(acptr),
310                  (cli_sendB(acptr) >> 10), (int)cli_receiveM(acptr),
311                  (cli_receiveB(acptr) >> 10), CurrentTime - cli_firsttime(acptr));
312     }
313 }
314
315 /** Report on loaded modules.
316  * @param[in] to Client requesting statistics.
317  * @param[in] sd Stats descriptor for request (ignored).
318  * @param[in] param Extra parameter from user (ignored).
319  */
320 static void
321 stats_modules(struct Client* to, const struct StatDesc* sd, char* param)
322 {
323 crypt_mechs_t* mechs;
324
325   send_reply(to, SND_EXPLICIT | RPL_STATSLLINE, 
326    "Module  Description      Entry Point");
327
328  /* atm the only "modules" we have are the crypto mechanisms,
329     eventualy they'll be part of a global dl module list, for now
330     i'll just output data about them -- hikari */
331
332  if(crypt_mechs_root == NULL)
333   return;
334
335  mechs = crypt_mechs_root->next;
336
337  for(;;)
338  {
339   if(mechs == NULL)
340    return;
341
342   send_reply(to, SND_EXPLICIT | RPL_STATSLLINE, 
343    "%s  %s     0x%X", 
344    mechs->mech->shortname, mechs->mech->description, 
345    mechs->mech->crypt_function);
346
347   mechs = mechs->next;
348  }
349
350 }
351
352 /** Report how many times each command has been used.
353  * @param[in] to Client requesting statistics.
354  * @param[in] sd Stats descriptor for request (ignored).
355  * @param[in] param Extra parameter from user (ignored).
356  */
357 static void
358 stats_commands(struct Client* to, const struct StatDesc* sd, char* param)
359 {
360   struct Message *mptr;
361
362   for (mptr = msgtab; mptr->cmd; mptr++)
363     if (mptr->count)
364       send_reply(to, RPL_STATSCOMMANDS, mptr->cmd, mptr->count, mptr->bytes);
365 }
366
367 /** List channel quarantines.
368  * @param[in] to Client requesting statistics.
369  * @param[in] sd Stats descriptor for request (ignored).
370  * @param[in] param Filter for quarantined channel names.
371  */
372 static void
373 stats_quarantine(struct Client* to, const struct StatDesc* sd, char* param)
374 {
375   struct qline *qline;
376
377   for (qline = GlobalQuarantineList; qline; qline = qline->next)
378   {
379     if (param && match(param, qline->chname)) /* narrow search */
380       continue;
381     send_reply(to, RPL_STATSQLINE, qline->chname, qline->reason);
382   }
383 }
384
385 /** List service pseudo-command mappings.
386  * @param[in] to Client requesting statistics.
387  * @param[in] sd Stats descriptor for request (ignored).
388  * @param[in] param Extra parameter from user (ignored).
389  */
390 static void
391 stats_mapping(struct Client *to, const struct StatDesc* sd, char* param)
392 {
393   struct s_map *map;
394
395   send_reply(to, RPL_STATSRLINE, "Command", "Name", "Prepend", "Target");
396   for (map = GlobalServiceMapList; map; map = map->next) {
397     struct nick_host *nh;
398     for (nh = map->services; nh; nh = nh->next) {
399       send_reply(to, RPL_STATSRLINE, map->command, map->name,
400                  (map->prepend ? map->prepend : "*"), nh->nick);
401     }
402   }
403 }
404
405 /** Report server uptime and maximum connection/client counts.
406  * @param[in] to Client requesting statistics.
407  * @param[in] sd Stats descriptor for request (ignored).
408  * @param[in] param Extra parameter from user (ignored).
409  */
410 static void
411 stats_uptime(struct Client* to, const struct StatDesc* sd, char* param)
412 {
413   time_t nowr;
414
415   nowr = CurrentTime - cli_since(&me);
416   send_reply(to, RPL_STATSUPTIME, nowr / 86400, (nowr / 3600) % 24,
417              (nowr / 60) % 60, nowr % 60);
418   send_reply(to, RPL_STATSCONN, max_connection_count, max_client_count);
419 }
420
421 /** Verbosely report on servers connected to the network.
422  * If sd->sd_funcdata != 0, then display in a more human-friendly format.
423  * @param[in] sptr Client requesting statistics.
424  * @param[in] sd Stats descriptor for request.
425  * @param[in] param Filter for server names to display.
426  */
427 static void
428 stats_servers_verbose(struct Client* sptr, const struct StatDesc* sd,
429                       char* param)
430 {
431   struct Client *acptr;
432   const char *fmt;
433
434   /*
435    * lowercase 'v' is for human-readable,
436    * uppercase 'V' is for machine-readable
437    */
438   if (sd->sd_funcdata) {
439     send_reply(sptr, SND_EXPLICIT | RPL_STATSVERBOSE,
440                "%-20s %-20s Flags Hops Numeric   Lag  RTT   Up Down "
441                "Clients/Max Proto %-10s :Info", "Servername", "Uplink",
442                "LinkTS");
443     fmt = "%-20s %-20s %c%c%c%c  %4i %s %-4i %5i %4i %4i %4i %5i %5i P%-2i   %Tu :%s";
444   } else {
445     fmt = "%s %s %c%c%c%c %i %s %i %i %i %i %i %i %i P%i %Tu :%s";
446   }
447
448   for (acptr = GlobalClientList; acptr; acptr = cli_next(acptr))
449   {
450     if (!IsServer(acptr) && !IsMe(acptr))
451       continue;
452     /* narrow search */
453     if (param && match(param, cli_name(acptr)))
454       continue;
455     send_reply(sptr, SND_EXPLICIT | RPL_STATSVERBOSE, fmt,
456                cli_name(acptr),
457                cli_name(cli_serv(acptr)->up),
458                IsBurst(acptr) ? 'B' : '-',
459                IsBurstAck(acptr) ? 'A' : '-',
460                IsHub(acptr) ? 'H' : '-',
461                IsService(acptr) ? 'S' : '-',
462                cli_hopcount(acptr),
463                NumServ(acptr),
464                base64toint(cli_yxx(acptr)),
465                cli_serv(acptr)->lag,
466                cli_serv(acptr)->asll_rtt,
467                cli_serv(acptr)->asll_to,
468                cli_serv(acptr)->asll_from,
469                (acptr == &me ? UserStats.local_clients : cli_serv(acptr)->clients),
470                cli_serv(acptr)->nn_mask,
471                cli_serv(acptr)->prot,
472                cli_serv(acptr)->timestamp,
473                cli_info(acptr));
474   }
475 }
476
477 #ifdef DEBUGMODE
478 /** Display objects allocated (and total memory used by them) for
479  * several types of structures.
480  * @param[in] to Client requesting statistics.
481  * @param[in] sd Stats descriptor for request (ignored).
482  * @param[in] param Extra parameter from user (ignored).
483  */
484 static void
485 stats_meminfo(struct Client* to, const struct StatDesc* sd, char* param)
486 {
487   class_send_meminfo(to);
488   send_listinfo(to, 0);
489 }
490 #endif
491
492 /** Send a list of available statistics.
493  * @param[in] to Client requesting statistics.
494  * @param[in] sd Stats descriptor for request.
495  * @param[in] param Extra parameter from user (ignored).
496  */
497 static void
498 stats_help(struct Client* to, const struct StatDesc* sd, char* param)
499 {
500   struct StatDesc *asd;
501
502   /* only if it's my user */
503   if (MyUser(to))
504     for (asd = statsinfo; asd->sd_name; asd++)
505       if (asd != sd) /* don't send the help for us */
506         sendcmdto_one(&me, CMD_NOTICE, to, "%C :%c (%s) - %s", to, asd->sd_c,
507                       asd->sd_name, asd->sd_desc);
508 }
509
510 /** Contains information about all statistics. */
511 struct StatDesc statsinfo[] = {
512   { 'a', "nameservers", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_a,
513     report_dns_servers, 0,
514     "DNS servers." },
515   { 'c', "connect", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_c,
516     stats_configured_links, CONF_SERVER,
517     "Remote server connection lines." },
518   { 'd', "maskrules", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_d,
519     stats_crule_list, CRULE_MASK,
520     "Dynamic routing configuration." },
521   { 'D', "crules", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_d,
522     stats_crule_list, CRULE_ALL,
523     "Dynamic routing configuration." },
524   { 'e', "engine", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_e,
525     stats_engine, 0,
526     "Report server event loop engine." },
527   { 'f', "features", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_f,
528     feature_report, 0,
529     "Feature settings." },
530   { 'g', "glines", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_g,
531     gline_stats, 0,
532     "Global bans (G-lines)." },
533   { 'i', "access", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM), FEAT_HIS_STATS_i,
534     stats_access, CONF_CLIENT,
535     "Connection authorization lines." },
536   { 'j', "histogram", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_j,
537     msgq_histogram, 0,
538     "Message length histogram." },
539   { 'J', "jupes", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_J,
540     stats_nickjupes, 0,
541     "Nickname jupes." },
542   { 'k', "klines", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM), FEAT_HIS_STATS_k,
543     stats_klines, 0,
544     "Local bans (K-Lines)." },
545   { 'l', "links", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM | STAT_FLAG_CASESENS),
546     FEAT_HIS_STATS_l,
547     stats_links, 0,
548     "Current connections information." },
549   { 'L', "modules", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM | STAT_FLAG_CASESENS),
550     FEAT_HIS_STATS_L,
551     stats_modules, 0,
552     "Dynamically loaded modules." },
553   { 'm', "commands", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_m,
554     stats_commands, 0,
555     "Message usage information." },
556   { 'o', "operators", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_o,
557     stats_configured_links, CONF_OPERATOR,
558     "Operator information." },
559   { 'p', "ports", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM), FEAT_HIS_STATS_p,
560     show_ports, 0,
561     "Listening ports." },
562   { 'q', "quarantines", (STAT_FLAG_OPERONLY | STAT_FLAG_VARPARAM), FEAT_HIS_STATS_q,
563     stats_quarantine, 0,
564     "Quarantined channels list." },
565   { 'R', "mappings", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_R,
566     stats_mapping, 0,
567     "Service mappings." },
568 #ifdef DEBUGMODE
569   { 'r', "usage", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_r,
570     send_usage, 0,
571     "System resource usage (Debug only)." },
572 #endif
573   { 'T', "motds", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_T,
574     motd_report, 0,
575     "Configured Message Of The Day files." },
576   { 't', "locals", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_t,
577     tstats, 0,
578     "Local connection statistics (Total SND/RCV, etc)." },
579   { 'U', "uworld", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_U,
580     stats_configured_links, CONF_UWORLD,
581     "Service server information." },
582   { 'u', "uptime", (STAT_FLAG_OPERFEAT | STAT_FLAG_CASESENS), FEAT_HIS_STATS_u,
583     stats_uptime, 0,
584     "Current uptime & highest connection count." },
585   { 'v', "vservers", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM | STAT_FLAG_CASESENS), FEAT_HIS_STATS_v,
586     stats_servers_verbose, 1,
587     "Verbose server information." },
588   { 'V', "vserversmach", (STAT_FLAG_OPERFEAT | STAT_FLAG_VARPARAM | STAT_FLAG_CASESENS), FEAT_HIS_STATS_v,
589     stats_servers_verbose, 0,
590     "Verbose server information." },
591   { 'w', "userload", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_w,
592     calc_load, 0,
593     "Userload statistics." },
594 #ifdef DEBUGMODE
595   { 'x', "memusage", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_x,
596     stats_meminfo, 0,
597     "List usage information (Debug only)." },
598 #endif
599   { 'y', "classes", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_y,
600     report_classes, 0,
601     "Connection classes." },
602   { 'z', "memory", STAT_FLAG_OPERFEAT, FEAT_HIS_STATS_z,
603     count_memory, 0,
604     "Memory/Structure allocation information." },
605   { '*', "help", (STAT_FLAG_CASESENS | STAT_FLAG_VARPARAM), FEAT_LAST_F,
606     stats_help, 0,
607     "Send help for stats." },
608   { '\0', 0, FEAT_LAST_F, 0, 0, 0 }
609 };
610
611 /** Maps from characters to statistics descriptors.
612  * Statistics descriptors with no single-character alias are not included.
613  */
614 static struct StatDesc *statsmap[256];
615 /** Number of statistics descriptors. */
616 static int statscount;
617
618 /** Compare two StatDesc structures by long name (StatDesc::sd_name).
619  * @param[in] a_ Pointer to a StatDesc.
620  * @param[in] b_ Pointer to a StatDesc.
621  * @return Less than, equal to, or greater than zero if \a a_ is
622  * lexicographically less than, equal to, or greater than \a b_.
623  */
624 static int
625 stats_cmp(const void *a_, const void *b_)
626 {
627   const struct StatDesc *a = a_;
628   const struct StatDesc *b = b_;
629   return ircd_strcmp(a->sd_name, b->sd_name);
630 }
631
632 /** Compare a StatDesc's name against a string.
633  * @param[in] key Pointer to a null-terminated string.
634  * @param[in] sd_ Pointer to a StatDesc.
635  * @return Less than, equal to, or greater than zero if \a key is
636  * lexicographically less than, equal to, or greater than \a
637  * sd_->sd_name.
638  */
639 static int
640 stats_search(const void *key, const void *sd_)
641 {
642   const struct StatDesc *sd = sd_;
643   return ircd_strcmp(key, sd->sd_name);
644 }
645
646 /** Look up a stats handler.  If name_or_char is just one character
647  * long, use that as a character index; otherwise, look it up by name
648  * in #statsinfo.
649  * @param[in] name_or_char Null-terminated string to look up.
650  * @return The statistics descriptor for \a name_or_char (NULL if none).
651  */
652 const struct StatDesc *
653 stats_find(const char *name_or_char)
654 {
655   if (!name_or_char[1])
656     return statsmap[(int)name_or_char[0]];
657   else
658     return bsearch(name_or_char, statsinfo, statscount, sizeof(statsinfo[0]), stats_search);
659 }
660
661 /** Build statsmap from the statsinfo array. */
662 void
663 stats_init(void)
664 {
665   struct StatDesc *sd;
666   int i;
667
668   /* Make darn sure the statsmap array is initialized to all zeros */
669   for (i = 0; i < 256; i++)
670     statsmap[i] = 0;
671
672   /* Count number of stats entries and sort them. */
673   for (statscount = 0, sd = statsinfo; sd->sd_name; sd++, statscount++) {}
674   qsort(statsinfo, statscount, sizeof(statsinfo[0]), stats_cmp);
675
676   /* Build the mapping */
677   for (sd = statsinfo; sd->sd_name; sd++)
678   {
679     if (!sd->sd_c)
680       continue;
681     else if (sd->sd_flags & STAT_FLAG_CASESENS)
682       /* case sensitive character... */
683       statsmap[(int)sd->sd_c] = sd;
684     else
685     {
686       /* case insensitive--make sure to put in two entries */
687       statsmap[(int)ToLower((int)sd->sd_c)] = sd;
688       statsmap[(int)ToUpper((int)sd->sd_c)] = sd;
689     }
690   }
691 }