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