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