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