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