Fix some memory counting buglets.
[ircu2.10.12-pk.git] / ircd / s_conf.c
1 /*
2  * IRC - Internet Relay Chat, ircd/s_conf.c
3  * Copyright (C) 1990 Jarkko Oikarinen and
4  *                    University of Oulu, Computing Center
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 1, or (at your option)
9  * any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 /** @file
21  * @brief ircd configuration file driver
22  * @version $Id$
23  */
24 #include "config.h"
25
26 #include "s_conf.h"
27 #include "IPcheck.h"
28 #include "class.h"
29 #include "client.h"
30 #include "crule.h"
31 #include "ircd_features.h"
32 #include "fileio.h"
33 #include "gline.h"
34 #include "hash.h"
35 #include "ircd.h"
36 #include "ircd_alloc.h"
37 #include "ircd_auth.h"
38 #include "ircd_chattr.h"
39 #include "ircd_log.h"
40 #include "ircd_reply.h"
41 #include "ircd_snprintf.h"
42 #include "ircd_string.h"
43 #include "list.h"
44 #include "listener.h"
45 #include "match.h"
46 #include "motd.h"
47 #include "numeric.h"
48 #include "numnicks.h"
49 #include "opercmds.h"
50 #include "parse.h"
51 #include "res.h"
52 #include "s_bsd.h"
53 #include "s_debug.h"
54 #include "s_misc.h"
55 #include "send.h"
56 #include "struct.h"
57 #include "sys.h"
58
59 /* #include <assert.h> -- Now using assert in ircd_log.h */
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68
69 /** Global list of all ConfItem structures. */
70 struct ConfItem  *GlobalConfList;
71 /** Count of items in #GlobalConfList. */
72 int              GlobalConfCount;
73 /** Global list of service mappings. */
74 struct s_map     *GlobalServiceMapList;
75 /** Global list of channel quarantines. */
76 struct qline     *GlobalQuarantineList;
77
78 /** Current line number in scanner input. */
79 int lineno;
80
81 /** Configuration information for #me. */
82 struct LocalConf   localConf;
83 /** Global list of connection rules. */
84 struct CRuleConf*  cruleConfList;
85 /** Global list of K-lines. */
86 struct DenyConf*   denyConfList;
87
88 /** Tell a user that they are banned, dumping the message from a file.
89  * @param sptr Client being rejected
90  * @param filename Send this file's contents to \a sptr
91  */
92 static void killcomment(struct Client* sptr, const char* filename)
93 {
94   FBFILE*     file = 0;
95   char        line[80];
96   struct stat sb;
97   struct tm*  tm;
98
99   if (NULL == (file = fbopen(filename, "r"))) {
100     send_reply(sptr, ERR_NOMOTD);
101     send_reply(sptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP,
102                ":Connection from your host is refused on this server.");
103     return;
104   }
105   fbstat(&sb, file);
106   tm = localtime((time_t*) &sb.st_mtime);        /* NetBSD needs cast */
107   while (fbgets(line, sizeof(line) - 1, file)) {
108     char* end = line + strlen(line);
109     while (end > line) {
110       --end;
111       if ('\n' == *end || '\r' == *end)
112         *end = '\0';
113       else
114         break;
115     }
116     send_reply(sptr, RPL_MOTD, line);
117   }
118   send_reply(sptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP,
119              ":Connection from your host is refused on this server.");
120   fbclose(file);
121 }
122
123 /** Allocate a new struct ConfItem and link it to #GlobalConfList.
124  * @return Newly allocated structure.
125  */
126 struct ConfItem* make_conf(int type)
127 {
128   struct ConfItem* aconf;
129
130   aconf = (struct ConfItem*) MyMalloc(sizeof(struct ConfItem));
131   assert(0 != aconf);
132   ++GlobalConfCount;
133   memset(aconf, 0, sizeof(struct ConfItem));
134   aconf->status  = type;
135   aconf->next    = GlobalConfList;
136   GlobalConfList = aconf;
137   return aconf;
138 }
139
140 /** Free a struct ConfItem and any resources it owns.
141  * @param aconf Item to free.
142  */
143 void free_conf(struct ConfItem *aconf)
144 {
145   Debug((DEBUG_DEBUG, "free_conf: %s %s %d",
146          aconf->host ? aconf->host : "*",
147          aconf->name ? aconf->name : "*",
148          aconf->address.port));
149   if (aconf->dns_pending)
150     delete_resolver_queries(aconf);
151   MyFree(aconf->username);
152   MyFree(aconf->host);
153   MyFree(aconf->origin_name);
154   if (aconf->passwd)
155     memset(aconf->passwd, 0, strlen(aconf->passwd));
156   MyFree(aconf->passwd);
157   MyFree(aconf->name);
158   MyFree(aconf->hub_limit);
159   MyFree(aconf);
160   --GlobalConfCount;
161 }
162
163 /** Disassociate configuration from the client.
164  * @param cptr Client to operate on.
165  * @param aconf ConfItem to detach.
166  */
167 static void detach_conf(struct Client* cptr, struct ConfItem* aconf)
168 {
169   struct SLink** lp;
170   struct SLink*  tmp;
171
172   assert(0 != aconf);
173   assert(0 != cptr);
174   assert(0 < aconf->clients);
175
176   lp = &(cli_confs(cptr));
177
178   while (*lp) {
179     if ((*lp)->value.aconf == aconf) {
180       if (aconf->conn_class && (aconf->status & CONF_CLIENT_MASK) && ConfLinks(aconf) > 0)
181         --ConfLinks(aconf);
182
183       assert(0 < aconf->clients);
184       if (0 == --aconf->clients && IsIllegal(aconf))
185         free_conf(aconf);
186       tmp = *lp;
187       *lp = tmp->next;
188       free_link(tmp);
189       return;
190     }
191     lp = &((*lp)->next);
192   }
193 }
194
195 /** Parse a user\@host mask into username and host or IP parts.
196  * If \a host contains no username part, set \a aconf->username to
197  * NULL.  If the host part of \a host looks like an IP mask, set \a
198  * aconf->addrbits and \a aconf->address to match.  Otherwise, set
199  * \a aconf->host, and set \a aconf->addrbits to -1.
200  * @param[in,out] aconf Configuration item to set.
201  * @param[in] host user\@host mask to parse.
202  */
203 void conf_parse_userhost(struct ConfItem *aconf, char *host)
204 {
205   char *host_part;
206   unsigned char addrbits;
207
208   MyFree(aconf->username);
209   MyFree(aconf->host);
210   host_part = strchr(host, '@');
211   if (host_part) {
212     *host_part = '\0';
213     DupString(aconf->username, host);
214     host_part++;
215   } else {
216     aconf->username = NULL;
217     host_part = host;
218   }
219   DupString(aconf->host, host_part);
220   if (ipmask_parse(aconf->host, &aconf->address.addr, &addrbits))
221     aconf->addrbits = addrbits;
222   else
223     aconf->addrbits = -1;
224   MyFree(host);
225 }
226
227 /** Copies a completed DNS query into its ConfItem.
228  * @param vptr Pointer to struct ConfItem for the block.
229  * @param hp DNS reply, or NULL if the lookup failed.
230  */
231 static void conf_dns_callback(void* vptr, struct DNSReply* hp)
232 {
233   struct ConfItem* aconf = (struct ConfItem*) vptr;
234   assert(aconf);
235   aconf->dns_pending = 0;
236   if (hp) {
237     memcpy(&aconf->address.addr, &hp->addr, sizeof(aconf->address.addr));
238     MyFree(hp);
239   }
240 }
241
242 /** Start a nameserver lookup of the conf host.  If the conf entry is
243  * currently doing a lookup, do nothing.
244  * @param aconf ConfItem for which to start a request.
245  */
246 static void conf_dns_lookup(struct ConfItem* aconf)
247 {
248   if (!aconf->dns_pending) {
249     char            buf[HOSTLEN + 1];
250     struct DNSQuery query;
251     query.vptr     = aconf;
252     query.callback = conf_dns_callback;
253     host_from_uh(buf, aconf->host, HOSTLEN);
254     buf[HOSTLEN] = '\0';
255
256     gethost_byname(buf, &query);
257     aconf->dns_pending = 1;
258   }
259 }
260
261
262 /** Start lookups of all addresses in the conf line.  The origin must
263  * be a numeric IP address.  If the remote host field is not an IP
264  * address, start a DNS lookup for it.
265  * @param aconf Connection to do lookups for.
266  */
267 void
268 lookup_confhost(struct ConfItem *aconf)
269 {
270   if (EmptyString(aconf->host) || EmptyString(aconf->name)) {
271     Debug((DEBUG_ERROR, "Host/server name error: (%s) (%s)",
272            aconf->host, aconf->name));
273     return;
274   }
275   if (aconf->origin_name
276       && !ircd_aton(&aconf->origin.addr, aconf->origin_name)) {
277     Debug((DEBUG_ERROR, "Origin name error: (%s) (%s)",
278         aconf->origin_name, aconf->name));
279   }
280   /*
281    * Do name lookup now on hostnames given and store the
282    * ip numbers in conf structure.
283    */
284   if (IsIP6Char(*aconf->host)) {
285     if (!ircd_aton(&aconf->address.addr, aconf->host)) {
286       Debug((DEBUG_ERROR, "Host/server name error: (%s) (%s)",
287           aconf->host, aconf->name));
288     }
289   }
290   else
291     conf_dns_lookup(aconf);
292 }
293
294 /** Find a server by name or hostname.
295  * @param name Server name to find.
296  * @return Pointer to the corresponding ConfItem, or NULL if none exists.
297  */
298 struct ConfItem* conf_find_server(const char* name)
299 {
300   struct ConfItem* conf;
301   assert(0 != name);
302
303   for (conf = GlobalConfList; conf; conf = conf->next) {
304     if (CONF_SERVER == conf->status) {
305       /*
306        * Check first servernames, then try hostnames.
307        * XXX - match returns 0 if there _is_ a match... guess they
308        * haven't decided what true is yet
309        */
310       if (0 == match(name, conf->name))
311         return conf;
312     }
313   }
314   return 0;
315 }
316
317 /** Evaluate connection rules.
318  * @param name Name of server to check
319  * @param mask Filter for CRule types (only consider if type & \a mask != 0).
320  * @return Name of rule that forbids the connection; NULL if no prohibitions.
321  */
322 const char* conf_eval_crule(const char* name, int mask)
323 {
324   struct CRuleConf* p = cruleConfList;
325   assert(0 != name);
326
327   for ( ; p; p = p->next) {
328     if (0 != (p->type & mask) && 0 == match(p->hostmask, name)) {
329       if (crule_eval(p->node))
330         return p->rule;
331     }
332   }
333   return 0;
334 }
335
336 /** Remove all conf entries from the client except those which match
337  * the status field mask.
338  * @param cptr Client to operate on.
339  * @param mask ConfItem types to keep.
340  */
341 void det_confs_butmask(struct Client* cptr, int mask)
342 {
343   struct SLink* link;
344   struct SLink* next;
345   assert(0 != cptr);
346
347   for (link = cli_confs(cptr); link; link = next) {
348     next = link->next;
349     if ((link->value.aconf->status & mask) == 0)
350       detach_conf(cptr, link->value.aconf);
351   }
352 }
353
354 /** Check client limits and attach Client block.
355  * If there are more connections from the IP than \a aconf->maximum
356  * allows, return ACR_TOO_MANY_FROM_IP.  Otherwise, attach \a aconf to
357  * \a cptr.
358  * @param cptr Client getting \a aconf.
359  * @param aconf Configuration item to attach.
360  * @return Authorization check result.
361  */
362 static enum AuthorizationCheckResult
363 check_limit_and_attach(struct Client* cptr, struct ConfItem* aconf)
364 {
365   if (IPcheck_nr(cptr) > aconf->maximum)
366     return ACR_TOO_MANY_FROM_IP;
367   return attach_conf(cptr, aconf);
368 }
369
370 /** Find the first (best) Client block to attach.
371  * @param cptr Client for whom to check rules.
372  * @return Authorization check result.
373  */
374 enum AuthorizationCheckResult attach_iline(struct Client* cptr)
375 {
376   struct ConfItem* aconf;
377   struct DNSReply* hp;
378
379   assert(0 != cptr);
380
381   hp = cli_dns_reply(cptr);
382   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
383     if (aconf->status != CONF_CLIENT)
384       continue;
385     /* If you change any of this logic, please make corresponding
386      * changes in conf_debug_iline() below.
387      */
388     if (aconf->address.port && aconf->address.port != cli_listener(cptr)->addr.port)
389       continue;
390     if (aconf->username) {
391       SetFlag(cptr, FLAG_DOID);
392       if (match(aconf->username, cli_username(cptr)))
393         continue;
394     }
395     if (aconf->host && (!hp || match(aconf->host, hp->h_name)))
396       continue;
397     if ((aconf->addrbits >= 0)
398         && !ipmask_check(&cli_ip(cptr), &aconf->address.addr, aconf->addrbits))
399       continue;
400     return check_limit_and_attach(cptr, aconf);
401   }
402   return ACR_NO_AUTHORIZATION;
403 }
404
405 /** Interpret \a client as a client specifier and show which Client
406  * block(s) match that client.
407  *
408  * The client specifier may contain an IP address, hostname, listener
409  * port, or a combination of those separated by commas.  IP addresses
410  * and hostnamese may be preceded by "username@"; the last given
411  * username will be used for the match.
412  *
413  * @param[in] client Client specifier.
414  * @return Matching Client block structure.
415  */
416 struct ConfItem *conf_debug_iline(const char *client)
417 {
418   struct irc_in_addr address;
419   struct ConfItem *aconf;
420   struct DenyConf *deny;
421   char *sep;
422   unsigned short listener;
423   char username[USERLEN+1], hostname[HOSTLEN+1], realname[REALLEN+1];
424
425   /* Initialize variables. */
426   listener = 0;
427   memset(&address, 0, sizeof(address));
428   memset(&username, 0, sizeof(username));
429   memset(&hostname, 0, sizeof(hostname));
430   memset(&realname, 0, sizeof(realname));
431
432   /* Parse client specifier. */
433   while (*client) {
434     struct irc_in_addr tmpaddr;
435     long tmp;
436
437     /* Try to parse as listener port number first. */
438     tmp = strtol(client, &sep, 10);
439     if (tmp && (*sep == '\0' || *sep == ',')) {
440       listener = tmp;
441       client = sep + (*sep != '\0');
442       continue;
443     }
444
445     /* Maybe username@ before an IP address or hostname? */
446     tmp = strcspn(client, ",@");
447     if (client[tmp] == '@') {
448       if (tmp > USERLEN)
449         tmp = USERLEN;
450       ircd_strncpy(username, client, tmp);
451       /* and fall through */
452       client += tmp + 1;
453     }
454
455     /* Looks like an IP address? */
456     tmp = ircd_aton(&tmpaddr, client);
457     if (tmp && (client[tmp] == '\0' || client[tmp] == ',')) {
458         memcpy(&address, &tmpaddr, sizeof(address));
459         client += tmp + (client[tmp] != '\0');
460         continue;
461     }
462
463     /* Realname? */
464     if (client[0] == '$' && client[1] == 'R') {
465       client += 2;
466       for (tmp = 0; *client != '\0' && *client != ',' && tmp < REALLEN; ++client, ++tmp) {
467         if (*client == '\\')
468           realname[tmp] = *++client;
469         else
470           realname[tmp] = *client;
471       }
472       continue;
473     }
474
475     /* Else must be a hostname. */
476     tmp = strcspn(client, ",");
477     if (tmp > HOSTLEN)
478       tmp = HOSTLEN;
479     ircd_strncpy(hostname, client, tmp);
480     client += tmp + (client[tmp] != '\0');
481   }
482
483   /* Walk configuration to find matching Client block. */
484   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
485     if (aconf->status != CONF_CLIENT)
486       continue;
487     if (aconf->address.port && aconf->address.port != listener) {
488       fprintf(stdout, "Listener port mismatch: %u != %u\n", aconf->address.port, listener);
489       continue;
490     }
491     if (aconf->username && match(aconf->username, username)) {
492       fprintf(stdout, "Username mismatch: %s != %s\n", aconf->username, username);
493       continue;
494     }
495     if (aconf->host && match(aconf->host, hostname)) {
496       fprintf(stdout, "Hostname mismatch: %s != %s\n", aconf->host, hostname);
497       continue;
498     }
499     if ((aconf->addrbits >= 0)
500         && !ipmask_check(&address, &aconf->address.addr, aconf->addrbits)) {
501       fprintf(stdout, "IP address mismatch: %s != %s\n", aconf->name, ircd_ntoa(&address));
502       continue;
503     }
504     fprintf(stdout, "Match! username=%s host=%s ip=%s class=%s maxlinks=%u password=%s\n",
505             (aconf->username ? aconf->username : "(null)"),
506             (aconf->host ? aconf->host : "(null)"),
507             (aconf->name ? aconf->name : "(null)"),
508             ConfClass(aconf), aconf->maximum,  aconf->passwd);
509     break;
510   }
511
512   /* If no authorization, say so and exit. */
513   if (!aconf)
514   {
515     fprintf(stdout, "No authorization found.\n");
516     return NULL;
517   }
518
519   /* Look for a Kill block with the user's name on it. */
520   for (deny = denyConfList; deny; deny = deny->next) {
521     if (deny->usermask && match(deny->usermask, username))
522       continue;
523     if (deny->realmask && match(deny->realmask, realname))
524       continue;
525     if (deny->bits > 0) {
526       if (!ipmask_check(&address, &deny->address, deny->bits))
527         continue;
528     } else if (deny->hostmask && match(deny->hostmask, hostname))
529       continue;
530
531     /* Looks like a match; report it. */
532     fprintf(stdout, "Denied! usermask=%s realmask=\"%s\" hostmask=%s (bits=%u)\n",
533             deny->usermask ? deny->usermask : "(null)",
534             deny->realmask ? deny->realmask : "(null)",
535             deny->hostmask ? deny->hostmask : "(null)",
536             deny->bits);
537   }
538
539   return aconf;
540 }
541
542 /** Check whether a particular ConfItem is already attached to a
543  * Client.
544  * @param aconf ConfItem to search for
545  * @param cptr Client to check
546  * @return Non-zero if \a aconf is attached to \a cptr, zero if not.
547  */
548 static int is_attached(struct ConfItem *aconf, struct Client *cptr)
549 {
550   struct SLink *lp;
551
552   for (lp = cli_confs(cptr); lp; lp = lp->next) {
553     if (lp->value.aconf == aconf)
554       return 1;
555   }
556   return 0;
557 }
558
559 /** Associate a specific configuration entry to a *local* client (this
560  * is the one which used in accepting the connection). Note, that this
561  * automatically changes the attachment if there was an old one...
562  * @param cptr Client to attach \a aconf to
563  * @param aconf ConfItem to attach
564  * @return Authorization check result.
565  */
566 enum AuthorizationCheckResult attach_conf(struct Client *cptr, struct ConfItem *aconf)
567 {
568   struct SLink *lp;
569
570   if (is_attached(aconf, cptr))
571     return ACR_ALREADY_AUTHORIZED;
572   if (IsIllegal(aconf))
573     return ACR_NO_AUTHORIZATION;
574   if ((aconf->status & (CONF_OPERATOR | CONF_CLIENT)) &&
575       ConfLinks(aconf) >= ConfMaxLinks(aconf) && ConfMaxLinks(aconf) > 0)
576     return ACR_TOO_MANY_IN_CLASS;  /* Use this for printing error message */
577   lp = make_link();
578   lp->next = cli_confs(cptr);
579   lp->value.aconf = aconf;
580   cli_confs(cptr) = lp;
581   ++aconf->clients;
582   if (aconf->status & CONF_CLIENT_MASK)
583     ConfLinks(aconf)++;
584   return ACR_OK;
585 }
586
587 /** Return our LocalConf configuration structure.
588  * @return A pointer to #localConf.
589  */
590 const struct LocalConf* conf_get_local(void)
591 {
592   return &localConf;
593 }
594
595 /** Attach ConfItems to a client if the name passed matches that for
596  * the ConfItems or is an exact match for them.
597  * @param cptr Client getting the ConfItem attachments.
598  * @param name Filter to match ConfItem::name.
599  * @param statmask Filter to limit ConfItem::status.
600  * @return First ConfItem attached to \a cptr.
601  */
602 struct ConfItem* attach_confs_byname(struct Client* cptr, const char* name,
603                                      int statmask)
604 {
605   struct ConfItem* tmp;
606   struct ConfItem* first = NULL;
607
608   assert(0 != name);
609
610   if (HOSTLEN < strlen(name))
611     return 0;
612
613   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
614     if (0 != (tmp->status & statmask) && !IsIllegal(tmp)) {
615       assert(0 != tmp->name);
616       if (0 == match(tmp->name, name) || 0 == ircd_strcmp(tmp->name, name)) { 
617         if (ACR_OK == attach_conf(cptr, tmp) && !first)
618           first = tmp;
619       }
620     }
621   }
622   return first;
623 }
624
625 /** Attach ConfItems to a client if the host passed matches that for
626  * the ConfItems or is an exact match for them.
627  * @param cptr Client getting the ConfItem attachments.
628  * @param host Filter to match ConfItem::host.
629  * @param statmask Filter to limit ConfItem::status.
630  * @return First ConfItem attached to \a cptr.
631  */
632 struct ConfItem* attach_confs_byhost(struct Client* cptr, const char* host,
633                                      int statmask)
634 {
635   struct ConfItem* tmp;
636   struct ConfItem* first = 0;
637
638   assert(0 != host);
639   if (HOSTLEN < strlen(host))
640     return 0;
641
642   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
643     if (0 != (tmp->status & statmask) && !IsIllegal(tmp)) {
644       assert(0 != tmp->host);
645       if (0 == match(tmp->host, host) || 0 == ircd_strcmp(tmp->host, host)) { 
646         if (ACR_OK == attach_conf(cptr, tmp) && !first)
647           first = tmp;
648       }
649     }
650   }
651   return first;
652 }
653
654 /** Find a ConfItem that has the same name and user+host fields as
655  * specified.  Requires an exact match for \a name.
656  * @param name Name to match
657  * @param cptr Client to match against
658  * @param statmask Filter for ConfItem::status
659  * @return First found matching ConfItem.
660  */
661 struct ConfItem* find_conf_exact(const char* name, struct Client *cptr, int statmask)
662 {
663   struct ConfItem *tmp;
664
665   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
666     if (!(tmp->status & statmask) || !tmp->name || !tmp->host ||
667         0 != ircd_strcmp(tmp->name, name))
668       continue;
669     if (tmp->username
670         && (EmptyString(cli_username(cptr))
671             || match(tmp->username, cli_username(cptr))))
672       continue;
673     if (tmp->addrbits < 0)
674     {
675       if (match(tmp->host, cli_sockhost(cptr)))
676         continue;
677     }
678     else if (!ipmask_check(&cli_ip(cptr), &tmp->address.addr, tmp->addrbits))
679       continue;
680     if ((tmp->status & CONF_OPERATOR)
681         && (tmp->clients >= MaxLinks(tmp->conn_class)))
682       continue;
683     return tmp;
684   }
685   return 0;
686 }
687
688 /** Find a ConfItem from a list that has a name that matches \a name.
689  * @param lp List to search in.
690  * @param name Filter for ConfItem::name field; matches either exactly
691  * or as a glob.
692  * @param statmask Filter for ConfItem::status.
693  * @return First matching ConfItem from \a lp.
694  */
695 struct ConfItem* find_conf_byname(struct SLink* lp, const char* name,
696                                   int statmask)
697 {
698   struct ConfItem* tmp;
699   assert(0 != name);
700
701   if (HOSTLEN < strlen(name))
702     return 0;
703
704   for (; lp; lp = lp->next) {
705     tmp = lp->value.aconf;
706     if (0 != (tmp->status & statmask)) {
707       assert(0 != tmp->name);
708       if (0 == ircd_strcmp(tmp->name, name) || 0 == match(tmp->name, name))
709         return tmp;
710     }
711   }
712   return 0;
713 }
714
715 /** Find a ConfItem from a list that has a host that matches \a host.
716  * @param lp List to search in.
717  * @param host Filter for ConfItem::host field; matches as a glob.
718  * @param statmask Filter for ConfItem::status.
719  * @return First matching ConfItem from \a lp.
720  */
721 struct ConfItem* find_conf_byhost(struct SLink* lp, const char* host,
722                                   int statmask)
723 {
724   struct ConfItem* tmp = NULL;
725   assert(0 != host);
726
727   if (HOSTLEN < strlen(host))
728     return 0;
729
730   for (; lp; lp = lp->next) {
731     tmp = lp->value.aconf;
732     if (0 != (tmp->status & statmask)) {
733       assert(0 != tmp->host);
734       if (0 == match(tmp->host, host))
735         return tmp;
736     }
737   }
738   return 0;
739 }
740
741 /** Find a ConfItem from a list that has an address equal to \a ip.
742  * @param lp List to search in.
743  * @param ip Filter for ConfItem::address field; matches exactly.
744  * @param statmask Filter for ConfItem::status.
745  * @return First matching ConfItem from \a lp.
746  */
747 struct ConfItem* find_conf_byip(struct SLink* lp, const struct irc_in_addr* ip,
748                                 int statmask)
749 {
750   struct ConfItem* tmp;
751
752   for (; lp; lp = lp->next) {
753     tmp = lp->value.aconf;
754     if (0 != (tmp->status & statmask)
755         && !irc_in_addr_cmp(&tmp->address.addr, ip))
756       return tmp;
757   }
758   return 0;
759 }
760
761 /** Free all CRules from #cruleConfList. */
762 void conf_erase_crule_list(void)
763 {
764   struct CRuleConf* next;
765   struct CRuleConf* p = cruleConfList;
766
767   for ( ; p; p = next) {
768     next = p->next;
769     crule_free(&p->node);
770     MyFree(p->hostmask);
771     MyFree(p->rule);
772     MyFree(p);
773   }
774   cruleConfList = 0;
775 }
776
777 /** Return #cruleConfList.
778  * @return #cruleConfList
779  */
780 const struct CRuleConf* conf_get_crule_list(void)
781 {
782   return cruleConfList;
783 }
784
785 /** Free all deny rules from #denyConfList. */
786 void conf_erase_deny_list(void)
787 {
788   struct DenyConf* next;
789   struct DenyConf* p = denyConfList;
790   for ( ; p; p = next) {
791     next = p->next;
792     MyFree(p->hostmask);
793     MyFree(p->usermask);
794     MyFree(p->message);
795     MyFree(p->realmask);
796     MyFree(p);
797   }
798   denyConfList = 0;
799 }
800
801 /** Return #denyConfList.
802  * @return #denyConfList
803  */
804 const struct DenyConf* conf_get_deny_list(void)
805 {
806   return denyConfList;
807 }
808
809 /** Find any existing quarantine for the named channel.
810  * @param chname Channel name to search for.
811  * @return Reason for channel's quarantine, or NULL if none exists.
812  */
813 const char*
814 find_quarantine(const char *chname)
815 {
816   struct qline *qline;
817
818   for (qline = GlobalQuarantineList; qline; qline = qline->next)
819     if (!ircd_strcmp(qline->chname, chname))
820       return qline->reason;
821   return NULL;
822 }
823
824 /** Free all qline structs from #GlobalQuarantineList. */
825 void clear_quarantines(void)
826 {
827   struct qline *qline;
828   while ((qline = GlobalQuarantineList))
829   {
830     GlobalQuarantineList = qline->next;
831     MyFree(qline->reason);
832     MyFree(qline->chname);
833     MyFree(qline);
834   }
835 }
836
837 /** When non-zero, indicates that a configuration error has been seen in this pass. */
838 static int conf_error;
839 /** When non-zero, indicates that the configuration file was loaded at least once. */
840 static int conf_already_read;
841 extern FILE *yyin;
842 extern void yyparse(void);
843 extern void init_lexer(void);
844
845 /** Read configuration file.
846  * @return Zero on failure, non-zero on success. */
847 int read_configuration_file(void)
848 {
849   conf_error = 0;
850   feature_unmark(); /* unmark all features for resetting later */
851   /* Now just open an fd. The buffering isn't really needed... */
852   init_lexer();
853   yyparse();
854   fclose(yyin);
855   yyin = NULL;
856   feature_mark(); /* reset unmarked features */
857   conf_already_read = 1;
858   return 1;
859 }
860
861 /** Report an error message about the configuration file.
862  * @param msg The error to report.
863  */
864 void
865 yyerror(const char *msg)
866 {
867  sendto_opmask_butone(0, SNO_ALL, "Config file parse error line %d: %s",
868                       lineno, msg);
869  log_write(LS_CONFIG, L_ERROR, 0, "Config file parse error line %d: %s",
870            lineno, msg);
871  if (!conf_already_read)
872    fprintf(stderr, "Config file parse error line %d: %s\n", lineno, msg);
873  conf_error = 1;
874 }
875
876 /** Attach CONF_UWORLD items to a server and everything attached to it. */
877 static void
878 attach_conf_uworld(struct Client *cptr)
879 {
880   struct DLink *lp;
881
882   attach_confs_byhost(cptr, cli_name(cptr), CONF_UWORLD);
883   for (lp = cli_serv(cptr)->down; lp; lp = lp->next)
884     attach_conf_uworld(lp->value.cptr);
885 }
886
887 /** Reload the configuration file.
888  * @param cptr Client that requested rehash (if a signal, &me).
889  * @param sig Type of rehash (0 = oper-requested, 1 = signal, 2 =
890  *   oper-requested but do not restart resolver)
891  * @return CPTR_KILLED if any client was K/G-lined because of the
892  * rehash; otherwise 0.
893  */
894 int rehash(struct Client *cptr, int sig)
895 {
896   struct ConfItem** tmp = &GlobalConfList;
897   struct ConfItem*  tmp2;
898   struct Client*    acptr;
899   int               i;
900   int               ret = 0;
901   int               found_g = 0;
902
903   if (1 == sig)
904     sendto_opmask_butone(0, SNO_OLDSNO,
905                          "Got signal SIGHUP, reloading ircd conf. file");
906
907   while ((tmp2 = *tmp)) {
908     if (tmp2->clients) {
909       /*
910        * Configuration entry is still in use by some
911        * local clients, cannot delete it--mark it so
912        * that it will be deleted when the last client
913        * exits...
914        */
915       if (CONF_CLIENT == (tmp2->status & CONF_CLIENT))
916         tmp = &tmp2->next;
917       else {
918         *tmp = tmp2->next;
919         tmp2->next = 0;
920       }
921       tmp2->status |= CONF_ILLEGAL;
922     }
923     else {
924       *tmp = tmp2->next;
925       free_conf(tmp2);
926     }
927   }
928   conf_erase_crule_list();
929   conf_erase_deny_list();
930   motd_clear();
931
932   /*
933    * delete the juped nicks list
934    */
935   clearNickJupes();
936
937   clear_quarantines();
938
939   if (sig != 2)
940     restart_resolver();
941
942   class_mark_delete();
943   mark_listeners_closing();
944   iauth_mark_closing();
945
946   read_configuration_file();
947
948   log_reopen(); /* reopen log files */
949
950   iauth_close_unused();
951   close_listeners();
952   class_delete_marked();         /* unless it fails */
953
954   /*
955    * Flush out deleted I and P lines although still in use.
956    */
957   for (tmp = &GlobalConfList; (tmp2 = *tmp);) {
958     if (CONF_ILLEGAL == (tmp2->status & CONF_ILLEGAL)) {
959       *tmp = tmp2->next;
960       tmp2->next = NULL;
961       if (!tmp2->clients)
962         free_conf(tmp2);
963     }
964     else
965       tmp = &tmp2->next;
966   }
967
968   for (i = 0; i <= HighestFd; i++) {
969     if ((acptr = LocalClientArray[i])) {
970       assert(!IsMe(acptr));
971       if (IsServer(acptr))
972         det_confs_butmask(acptr, ~(CONF_UWORLD | CONF_ILLEGAL));
973       /* Because admin's are getting so uppity about people managing to
974        * get past K/G's etc, we'll "fix" the bug by actually explaining
975        * whats going on.
976        */
977       if ((found_g = find_kill(acptr))) {
978         sendto_opmask_butone(0, found_g == -2 ? SNO_GLINE : SNO_OPERKILL,
979                              found_g == -2 ? "G-line active for %s%s" :
980                              "K-line active for %s%s",
981                              IsUnknown(acptr) ? "Unregistered Client ":"",
982                              get_client_name(acptr, SHOW_IP));
983         if (exit_client(cptr, acptr, &me, found_g == -2 ? "G-lined" :
984             "K-lined") == CPTR_KILLED)
985           ret = CPTR_KILLED;
986       }
987     }
988   }
989
990   attach_conf_uworld(&me);
991
992   return ret;
993 }
994
995 /** Read configuration file for the very first time.
996  * @return Non-zero on success, zero on failure.
997  */
998
999 int init_conf(void)
1000 {
1001   if (read_configuration_file()) {
1002     /*
1003      * make sure we're sane to start if the config
1004      * file read didn't get everything we need.
1005      * XXX - should any of these abort the server?
1006      * TODO: add warning messages
1007      */
1008     if (0 == localConf.name || 0 == localConf.numeric)
1009       return 0;
1010     if (conf_error)
1011       return 0;
1012
1013     if (0 == localConf.location1)
1014       DupString(localConf.location1, "");
1015     if (0 == localConf.location2)
1016       DupString(localConf.location2, "");
1017     if (0 == localConf.contact)
1018       DupString(localConf.contact, "");
1019
1020     return 1;
1021   }
1022   return 0;
1023 }
1024
1025 /** Searches for a K/G-line for a client.  If one is found, notify the
1026  * user and disconnect them.
1027  * @param cptr Client to search for.
1028  * @return 0 if client is accepted; -1 if client was locally denied
1029  * (K-line); -2 if client was globally denied (G-line).
1030  */
1031 int find_kill(struct Client *cptr)
1032 {
1033   const char*      host;
1034   const char*      name;
1035   const char*      realname;
1036   struct DenyConf* deny;
1037   struct Gline*    agline = NULL;
1038
1039   assert(0 != cptr);
1040
1041   if (!cli_user(cptr))
1042     return 0;
1043
1044   host = cli_sockhost(cptr);
1045   name = cli_user(cptr)->username;
1046   realname = cli_info(cptr);
1047
1048   assert(strlen(host) <= HOSTLEN);
1049   assert((name ? strlen(name) : 0) <= HOSTLEN);
1050   assert((realname ? strlen(realname) : 0) <= REALLEN);
1051
1052   /* 2000-07-14: Rewrote this loop for massive speed increases.
1053    *             -- Isomer
1054    */
1055   for (deny = denyConfList; deny; deny = deny->next) {
1056     if (deny->usermask && match(deny->usermask, name))
1057       continue;
1058     if (deny->realmask && match(deny->realmask, realname))
1059       continue;
1060     if (deny->bits > 0) {
1061       if (!ipmask_check(&cli_ip(cptr), &deny->address, deny->bits))
1062         continue;
1063     } else if (deny->hostmask && match(deny->hostmask, host))
1064       continue;
1065
1066     if (EmptyString(deny->message))
1067       send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP,
1068                  ":Connection from your host is refused on this server.");
1069     else {
1070       if (deny->flags & DENY_FLAGS_FILE)
1071         killcomment(cptr, deny->message);
1072       else
1073         send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", deny->message);
1074     }
1075     return -1;
1076   }
1077
1078   if ((agline = gline_lookup(cptr, 0))) {
1079     /*
1080      * find active glines
1081      * added a check against the user's IP address to find_gline() -Kev
1082      */
1083     send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", GlineReason(agline));
1084     return -2;
1085   }
1086
1087   return 0;
1088 }
1089
1090 /** Attempt to attach Client blocks to \a cptr.  If attach_iline()
1091  * fails for the client, emit a debugging message.
1092  * @param cptr Client to check for access.
1093  * @return Access check result.
1094  */
1095 enum AuthorizationCheckResult conf_check_client(struct Client *cptr)
1096 {
1097   enum AuthorizationCheckResult acr = ACR_OK;
1098
1099   if ((acr = attach_iline(cptr))) {
1100     Debug((DEBUG_DNS, "ch_cl: access denied: %s[%s]", 
1101           cli_name(cptr), cli_sockhost(cptr)));
1102     return acr;
1103   }
1104   return ACR_OK;
1105 }
1106
1107 /** Check access for a server given its name (passed in cptr struct).
1108  * Must check for all C/N lines which have a name which matches the
1109  * name given and a host which matches. A host alias which is the
1110  * same as the server name is also acceptable in the host field of a
1111  * C/N line.
1112  * @param cptr Peer server to check.
1113  * @return 0 if accepted, -1 if access denied.
1114  */
1115 int conf_check_server(struct Client *cptr)
1116 {
1117   struct ConfItem* c_conf = NULL;
1118   struct SLink*    lp;
1119
1120   Debug((DEBUG_DNS, "sv_cl: check access for %s[%s]", 
1121         cli_name(cptr), cli_sockhost(cptr)));
1122
1123   if (IsUnknown(cptr) && !attach_confs_byname(cptr, cli_name(cptr), CONF_SERVER)) {
1124     Debug((DEBUG_DNS, "No C/N lines for %s", cli_sockhost(cptr)));
1125     return -1;
1126   }
1127   lp = cli_confs(cptr);
1128   /*
1129    * We initiated this connection so the client should have a C and N
1130    * line already attached after passing through the connect_server()
1131    * function earlier.
1132    */
1133   if (IsConnecting(cptr) || IsHandshake(cptr)) {
1134     c_conf = find_conf_byname(lp, cli_name(cptr), CONF_SERVER);
1135     if (!c_conf) {
1136       sendto_opmask_butone(0, SNO_OLDSNO,
1137                            "Connect Error: lost Connect block for %s",
1138                            cli_name(cptr));
1139       det_confs_butmask(cptr, 0);
1140       return -1;
1141     }
1142   }
1143
1144   if (!c_conf) {
1145     if (cli_dns_reply(cptr)) {
1146       struct DNSReply* hp = cli_dns_reply(cptr);
1147       const char*     name = hp->h_name;
1148       /*
1149        * If we are missing a C or N line from above, search for
1150        * it under all known hostnames we have for this ip#.
1151        */
1152       if ((c_conf = find_conf_byhost(lp, hp->h_name, CONF_SERVER)))
1153         ircd_strncpy(cli_sockhost(cptr), name, HOSTLEN);
1154       else
1155         c_conf = find_conf_byip(lp, &hp->addr, CONF_SERVER);
1156     }
1157     else {
1158       /*
1159        * Check for C lines with the hostname portion the ip number
1160        * of the host the server runs on. This also checks the case where
1161        * there is a server connecting from 'localhost'.
1162        */
1163       c_conf = find_conf_byhost(lp, cli_sockhost(cptr), CONF_SERVER);
1164     }
1165   }
1166   /*
1167    * Attach by IP# only if all other checks have failed.
1168    * It is quite possible to get here with the strange things that can
1169    * happen when using DNS in the way the irc server does. -avalon
1170    */
1171   if (!c_conf)
1172     c_conf = find_conf_byip(lp, &cli_ip(cptr), CONF_SERVER);
1173   /*
1174    * detach all conf lines that got attached by attach_confs()
1175    */
1176   det_confs_butmask(cptr, 0);
1177   /*
1178    * if no Connect block, then deny access
1179    */
1180   if (!c_conf) {
1181     Debug((DEBUG_DNS, "sv_cl: access denied: %s[%s@%s]",
1182           cli_name(cptr), cli_username(cptr), cli_sockhost(cptr)));
1183     return -1;
1184   }
1185   /*
1186    * attach the Connect block to the client structure for later use.
1187    */
1188   attach_conf(cptr, c_conf);
1189
1190   if (!irc_in_addr_valid(&c_conf->address.addr))
1191     memcpy(&c_conf->address.addr, &cli_ip(cptr), sizeof(c_conf->address.addr));
1192
1193   Debug((DEBUG_DNS, "sv_cl: access ok: %s[%s]",
1194          cli_name(cptr), cli_sockhost(cptr)));
1195   return 0;
1196 }
1197