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