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