536087b605dea442f5eea1dbe04c432e656ba7cf
[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   char *sep;
425   unsigned short listener;
426   char username[USERLEN+1], hostname[HOSTLEN+1];
427
428   /* Initialize variables. */
429   listener = 0;
430   memset(&address, 0, sizeof(address));
431   memset(&username, 0, sizeof(username));
432   memset(&hostname, 0, sizeof(hostname));
433
434   /* Parse client specifier. */
435   while (*client) {
436     struct irc_in_addr tmpaddr;
437     long tmp;
438
439     /* Try to parse as listener port number first. */
440     tmp = strtol(client, &sep, 10);
441     if (tmp && (*sep == '\0' || *sep == ',')) {
442       listener = tmp;
443       client = sep + (*sep != '\0');
444       continue;
445     }
446
447     /* Maybe username@ before an IP address or hostname? */
448     tmp = strcspn(client, ",@");
449     if (client[tmp] == '@') {
450       if (tmp > USERLEN)
451         tmp = USERLEN;
452       ircd_strncpy(username, client, tmp);
453       /* and fall through */
454       client += tmp + 1;
455     }
456
457     /* Looks like an IP address? */
458     tmp = ircd_aton(&tmpaddr, client);
459     if (tmp && (client[tmp] == '\0' || client[tmp] == ',')) {
460         memcpy(&address, &tmpaddr, sizeof(address));
461         client += tmp + (client[tmp] != '\0');
462         continue;
463     }
464
465     /* Else must be a hostname. */
466     tmp = strcspn(client, ",");
467     if (tmp > HOSTLEN)
468       tmp = HOSTLEN;
469     ircd_strncpy(hostname, client, tmp);
470     client += tmp + (client[tmp] != '\0');
471   }
472
473   /* Walk configuration to find matching Client block. */
474   for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
475     if (aconf->status != CONF_CLIENT)
476       continue;
477     if (aconf->address.port && aconf->address.port != listener) {
478       fprintf(stdout, "Listener port mismatch: %u != %u\n", aconf->address.port, listener);
479       continue;
480     }
481     if (aconf->username && match(aconf->username, username)) {
482       fprintf(stdout, "Username mismatch: %s != %s\n", aconf->username, username);
483       continue;
484     }
485     if (aconf->host && match(aconf->host, hostname)) {
486       fprintf(stdout, "Hostname mismatch: %s != %s\n", aconf->host, hostname);
487       continue;
488     }
489     if ((aconf->addrbits >= 0)
490         && !ipmask_check(&address, &aconf->address.addr, aconf->addrbits)) {
491       fprintf(stdout, "IP address mismatch: %s != %s\n", aconf->name, ircd_ntoa(&address));
492       continue;
493     }
494     fprintf(stdout, "Match! username=%s host=%s ip=%s class=%s maxlinks=%u password=%s\n",
495             (aconf->username ? aconf->username : "(null)"),
496             (aconf->host ? aconf->host : "(null)"),
497             (aconf->name ? aconf->name : "(null)"),
498             ConfClass(aconf), aconf->maximum,  aconf->passwd);
499     return aconf;
500   }
501
502   fprintf(stdout, "No matches found.\n");
503   return NULL;
504 }
505
506 /** Check whether a particular ConfItem is already attached to a
507  * Client.
508  * @param aconf ConfItem to search for
509  * @param cptr Client to check
510  * @return Non-zero if \a aconf is attached to \a cptr, zero if not.
511  */
512 static int is_attached(struct ConfItem *aconf, struct Client *cptr)
513 {
514   struct SLink *lp;
515
516   for (lp = cli_confs(cptr); lp; lp = lp->next) {
517     if (lp->value.aconf == aconf)
518       return 1;
519   }
520   return 0;
521 }
522
523 /** Associate a specific configuration entry to a *local* client (this
524  * is the one which used in accepting the connection). Note, that this
525  * automatically changes the attachment if there was an old one...
526  * @param cptr Client to attach \a aconf to
527  * @param aconf ConfItem to attach
528  * @return Authorization check result.
529  */
530 enum AuthorizationCheckResult attach_conf(struct Client *cptr, struct ConfItem *aconf)
531 {
532   struct SLink *lp;
533
534   if (is_attached(aconf, cptr))
535     return ACR_ALREADY_AUTHORIZED;
536   if (IsIllegal(aconf))
537     return ACR_NO_AUTHORIZATION;
538   if ((aconf->status & (CONF_OPERATOR | CONF_CLIENT)) &&
539       ConfLinks(aconf) >= ConfMaxLinks(aconf) && ConfMaxLinks(aconf) > 0)
540     return ACR_TOO_MANY_IN_CLASS;  /* Use this for printing error message */
541   lp = make_link();
542   lp->next = cli_confs(cptr);
543   lp->value.aconf = aconf;
544   cli_confs(cptr) = lp;
545   ++aconf->clients;
546   if (aconf->status & CONF_CLIENT_MASK)
547     ConfLinks(aconf)++;
548   return ACR_OK;
549 }
550
551 /** Return our LocalConf configuration structure.
552  * @return A pointer to #localConf.
553  */
554 const struct LocalConf* conf_get_local(void)
555 {
556   return &localConf;
557 }
558
559 /** Attach ConfItems to a client if the name passed matches that for
560  * the ConfItems or is an exact match for them.
561  * @param cptr Client getting the ConfItem attachments.
562  * @param name Filter to match ConfItem::name.
563  * @param statmask Filter to limit ConfItem::status.
564  * @return First ConfItem attached to \a cptr.
565  */
566 struct ConfItem* attach_confs_byname(struct Client* cptr, const char* name,
567                                      int statmask)
568 {
569   struct ConfItem* tmp;
570   struct ConfItem* first = NULL;
571
572   assert(0 != name);
573
574   if (HOSTLEN < strlen(name))
575     return 0;
576
577   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
578     if (0 != (tmp->status & statmask) && !IsIllegal(tmp)) {
579       assert(0 != tmp->name);
580       if (0 == match(tmp->name, name) || 0 == ircd_strcmp(tmp->name, name)) { 
581         if (ACR_OK == attach_conf(cptr, tmp) && !first)
582           first = tmp;
583       }
584     }
585   }
586   return first;
587 }
588
589 /** Attach ConfItems to a client if the host passed matches that for
590  * the ConfItems or is an exact match for them.
591  * @param cptr Client getting the ConfItem attachments.
592  * @param host Filter to match ConfItem::host.
593  * @param statmask Filter to limit ConfItem::status.
594  * @return First ConfItem attached to \a cptr.
595  */
596 struct ConfItem* attach_confs_byhost(struct Client* cptr, const char* host,
597                                      int statmask)
598 {
599   struct ConfItem* tmp;
600   struct ConfItem* first = 0;
601
602   assert(0 != host);
603   if (HOSTLEN < strlen(host))
604     return 0;
605
606   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
607     if (0 != (tmp->status & statmask) && !IsIllegal(tmp)) {
608       assert(0 != tmp->host);
609       if (0 == match(tmp->host, host) || 0 == ircd_strcmp(tmp->host, host)) { 
610         if (ACR_OK == attach_conf(cptr, tmp) && !first)
611           first = tmp;
612       }
613     }
614   }
615   return first;
616 }
617
618 /** Find a ConfItem that has the same name and user+host fields as
619  * specified.  Requires an exact match for \a name.
620  * @param name Name to match
621  * @param cptr Client to match against
622  * @param statmask Filter for ConfItem::status
623  * @return First found matching ConfItem.
624  */
625 struct ConfItem* find_conf_exact(const char* name, struct Client *cptr, int statmask)
626 {
627   struct ConfItem *tmp;
628
629   for (tmp = GlobalConfList; tmp; tmp = tmp->next) {
630     if (!(tmp->status & statmask) || !tmp->name || !tmp->host ||
631         0 != ircd_strcmp(tmp->name, name))
632       continue;
633     if (tmp->username
634         && (EmptyString(cli_username(cptr))
635             || match(tmp->username, cli_username(cptr))))
636       continue;
637     if (tmp->addrbits < 0)
638     {
639       if (match(tmp->host, cli_sockhost(cptr)))
640         continue;
641     }
642     else if (!ipmask_check(&cli_ip(cptr), &tmp->address.addr, tmp->addrbits))
643       continue;
644     if ((tmp->status & CONF_OPERATOR)
645         && (tmp->clients >= MaxLinks(tmp->conn_class)))
646       continue;
647     return tmp;
648   }
649   return 0;
650 }
651
652 /** Find a ConfItem from a list that has a name that matches \a name.
653  * @param lp List to search in.
654  * @param name Filter for ConfItem::name field; matches either exactly
655  * or as a glob.
656  * @param statmask Filter for ConfItem::status.
657  * @return First matching ConfItem from \a lp.
658  */
659 struct ConfItem* find_conf_byname(struct SLink* lp, const char* name,
660                                   int statmask)
661 {
662   struct ConfItem* tmp;
663   assert(0 != name);
664
665   if (HOSTLEN < strlen(name))
666     return 0;
667
668   for (; lp; lp = lp->next) {
669     tmp = lp->value.aconf;
670     if (0 != (tmp->status & statmask)) {
671       assert(0 != tmp->name);
672       if (0 == ircd_strcmp(tmp->name, name) || 0 == match(tmp->name, name))
673         return tmp;
674     }
675   }
676   return 0;
677 }
678
679 /** Find a ConfItem from a list that has a host that matches \a host.
680  * @param lp List to search in.
681  * @param host Filter for ConfItem::host field; matches as a glob.
682  * @param statmask Filter for ConfItem::status.
683  * @return First matching ConfItem from \a lp.
684  */
685 struct ConfItem* find_conf_byhost(struct SLink* lp, const char* host,
686                                   int statmask)
687 {
688   struct ConfItem* tmp = NULL;
689   assert(0 != host);
690
691   if (HOSTLEN < strlen(host))
692     return 0;
693
694   for (; lp; lp = lp->next) {
695     tmp = lp->value.aconf;
696     if (0 != (tmp->status & statmask)) {
697       assert(0 != tmp->host);
698       if (0 == match(tmp->host, host))
699         return tmp;
700     }
701   }
702   return 0;
703 }
704
705 /** Find a ConfItem from a list that has an address equal to \a ip.
706  * @param lp List to search in.
707  * @param ip Filter for ConfItem::address field; matches exactly.
708  * @param statmask Filter for ConfItem::status.
709  * @return First matching ConfItem from \a lp.
710  */
711 struct ConfItem* find_conf_byip(struct SLink* lp, const struct irc_in_addr* ip,
712                                 int statmask)
713 {
714   struct ConfItem* tmp;
715
716   for (; lp; lp = lp->next) {
717     tmp = lp->value.aconf;
718     if (0 != (tmp->status & statmask)
719         && !irc_in_addr_cmp(&tmp->address.addr, ip))
720       return tmp;
721   }
722   return 0;
723 }
724
725 /** Free all CRules from #cruleConfList. */
726 void conf_erase_crule_list(void)
727 {
728   struct CRuleConf* next;
729   struct CRuleConf* p = cruleConfList;
730
731   for ( ; p; p = next) {
732     next = p->next;
733     crule_free(&p->node);
734     MyFree(p->hostmask);
735     MyFree(p->rule);
736     MyFree(p);
737   }
738   cruleConfList = 0;
739 }
740
741 /** Return #cruleConfList.
742  * @return #cruleConfList
743  */
744 const struct CRuleConf* conf_get_crule_list(void)
745 {
746   return cruleConfList;
747 }
748
749 /** Free all deny rules from #denyConfList. */
750 void conf_erase_deny_list(void)
751 {
752   struct DenyConf* next;
753   struct DenyConf* p = denyConfList;
754   for ( ; p; p = next) {
755     next = p->next;
756     MyFree(p->hostmask);
757     MyFree(p->usermask);
758     MyFree(p->message);
759     MyFree(p);
760   }
761   denyConfList = 0;
762 }
763
764 /** Return #denyConfList.
765  * @return #denyConfList
766  */
767 const struct DenyConf* conf_get_deny_list(void)
768 {
769   return denyConfList;
770 }
771
772 /** Find any existing quarantine for the named channel.
773  * @param chname Channel name to search for.
774  * @return Reason for channel's quarantine, or NULL if none exists.
775  */
776 const char*
777 find_quarantine(const char *chname)
778 {
779   struct qline *qline;
780
781   for (qline = GlobalQuarantineList; qline; qline = qline->next)
782     if (!ircd_strcmp(qline->chname, chname))
783       return qline->reason;
784   return NULL;
785 }
786
787 /** Free all qline structs from #GlobalQuarantineList. */
788 void clear_quarantines(void)
789 {
790   struct qline *qline;
791   while ((qline = GlobalQuarantineList))
792   {
793     GlobalQuarantineList = qline->next;
794     MyFree(qline->reason);
795     MyFree(qline->chname);
796     MyFree(qline);
797   }
798 }
799
800 /** When non-zero, indicates that a configuration error has been seen in this pass. */
801 static int conf_error;
802 /** When non-zero, indicates that the configuration file was loaded at least once. */
803 static int conf_already_read;
804 extern FILE *yyin;
805 extern void yyparse(void);
806 extern void init_lexer(void);
807
808 /** Read configuration file.
809  * @return Zero on failure, non-zero on success. */
810 int read_configuration_file(void)
811 {
812   conf_error = 0;
813   feature_unmark(); /* unmark all features for resetting later */
814   /* Now just open an fd. The buffering isn't really needed... */
815   init_lexer();
816   yyparse();
817   fclose(yyin);
818   yyin = NULL;
819   feature_mark(); /* reset unmarked features */
820   conf_already_read = 1;
821   return 1;
822 }
823
824 /** Report an error message about the configuration file.
825  * @param msg The error to report.
826  */
827 void
828 yyerror(const char *msg)
829 {
830  sendto_opmask_butone(0, SNO_ALL, "Config file parse error line %d: %s",
831                       lineno, msg);
832  log_write(LS_CONFIG, L_ERROR, 0, "Config file parse error line %d: %s",
833            lineno, msg);
834  if (!conf_already_read)
835    fprintf(stderr, "Config file parse error line %d: %s\n", lineno, msg);
836  conf_error = 1;
837 }
838
839 /** Attach CONF_UWORLD items to a server and everything attached to it. */
840 static void
841 attach_conf_uworld(struct Client *cptr)
842 {
843   struct DLink *lp;
844
845   attach_confs_byhost(cptr, cli_name(cptr), CONF_UWORLD);
846   for (lp = cli_serv(cptr)->down; lp; lp = lp->next)
847     attach_conf_uworld(lp->value.cptr);
848 }
849
850 /** Reload the configuration file.
851  * @param cptr Client that requested rehash (if a signal, &me).
852  * @param sig Type of rehash (0 = oper-requested, 1 = signal, 2 =
853  *   oper-requested but do not restart resolver)
854  * @return CPTR_KILLED if any client was K/G-lined because of the
855  * rehash; otherwise 0.
856  */
857 int rehash(struct Client *cptr, int sig)
858 {
859   struct ConfItem** tmp = &GlobalConfList;
860   struct ConfItem*  tmp2;
861   struct Client*    acptr;
862   int               i;
863   int               ret = 0;
864   int               found_g = 0;
865
866   if (1 == sig)
867     sendto_opmask_butone(0, SNO_OLDSNO,
868                          "Got signal SIGHUP, reloading ircd conf. file");
869
870   while ((tmp2 = *tmp)) {
871     if (tmp2->clients) {
872       /*
873        * Configuration entry is still in use by some
874        * local clients, cannot delete it--mark it so
875        * that it will be deleted when the last client
876        * exits...
877        */
878       if (CONF_CLIENT == (tmp2->status & CONF_CLIENT))
879         tmp = &tmp2->next;
880       else {
881         *tmp = tmp2->next;
882         tmp2->next = 0;
883       }
884       tmp2->status |= CONF_ILLEGAL;
885     }
886     else {
887       *tmp = tmp2->next;
888       free_conf(tmp2);
889     }
890   }
891   conf_erase_crule_list();
892   conf_erase_deny_list();
893   motd_clear();
894
895   /*
896    * delete the juped nicks list
897    */
898   clearNickJupes();
899
900   clear_quarantines();
901
902   if (sig != 2)
903     restart_resolver();
904
905   class_mark_delete();
906   mark_listeners_closing();
907   iauth_mark_closing();
908
909   read_configuration_file();
910
911   log_reopen(); /* reopen log files */
912
913   iauth_close_unused();
914   close_listeners();
915   class_delete_marked();         /* unless it fails */
916
917   /*
918    * Flush out deleted I and P lines although still in use.
919    */
920   for (tmp = &GlobalConfList; (tmp2 = *tmp);) {
921     if (CONF_ILLEGAL == (tmp2->status & CONF_ILLEGAL)) {
922       *tmp = tmp2->next;
923       tmp2->next = NULL;
924       if (!tmp2->clients)
925         free_conf(tmp2);
926     }
927     else
928       tmp = &tmp2->next;
929   }
930
931   for (i = 0; i <= HighestFd; i++) {
932     if ((acptr = LocalClientArray[i])) {
933       assert(!IsMe(acptr));
934       if (IsServer(acptr))
935         det_confs_butmask(acptr, ~(CONF_UWORLD | CONF_ILLEGAL));
936       /* Because admin's are getting so uppity about people managing to
937        * get past K/G's etc, we'll "fix" the bug by actually explaining
938        * whats going on.
939        */
940       if ((found_g = find_kill(acptr))) {
941         sendto_opmask_butone(0, found_g == -2 ? SNO_GLINE : SNO_OPERKILL,
942                              found_g == -2 ? "G-line active for %s%s" :
943                              "K-line active for %s%s",
944                              IsUnknown(acptr) ? "Unregistered Client ":"",
945                              get_client_name(acptr, SHOW_IP));
946         if (exit_client(cptr, acptr, &me, found_g == -2 ? "G-lined" :
947             "K-lined") == CPTR_KILLED)
948           ret = CPTR_KILLED;
949       }
950     }
951   }
952
953   attach_conf_uworld(&me);
954
955   return ret;
956 }
957
958 /** Read configuration file for the very first time.
959  * @return Non-zero on success, zero on failure.
960  */
961
962 int init_conf(void)
963 {
964   if (read_configuration_file()) {
965     /*
966      * make sure we're sane to start if the config
967      * file read didn't get everything we need.
968      * XXX - should any of these abort the server?
969      * TODO: add warning messages
970      */
971     if (0 == localConf.name || 0 == localConf.numeric)
972       return 0;
973     if (conf_error)
974       return 0;
975
976     if (0 == localConf.location1)
977       DupString(localConf.location1, "");
978     if (0 == localConf.location2)
979       DupString(localConf.location2, "");
980     if (0 == localConf.contact)
981       DupString(localConf.contact, "");
982
983     return 1;
984   }
985   return 0;
986 }
987
988 /** Searches for a K/G-line for a client.  If one is found, notify the
989  * user and disconnect them.
990  * @param cptr Client to search for.
991  * @return 0 if client is accepted; -1 if client was locally denied
992  * (K-line); -2 if client was globally denied (G-line).
993  */
994 int find_kill(struct Client *cptr)
995 {
996   const char*      host;
997   const char*      name;
998   const char*      realname;
999   struct DenyConf* deny;
1000   struct Gline*    agline = NULL;
1001
1002   assert(0 != cptr);
1003
1004   if (!cli_user(cptr))
1005     return 0;
1006
1007   host = cli_sockhost(cptr);
1008   name = cli_user(cptr)->username;
1009   realname = cli_info(cptr);
1010
1011   assert(strlen(host) <= HOSTLEN);
1012   assert((name ? strlen(name) : 0) <= HOSTLEN);
1013   assert((realname ? strlen(realname) : 0) <= REALLEN);
1014
1015   /* 2000-07-14: Rewrote this loop for massive speed increases.
1016    *             -- Isomer
1017    */
1018   for (deny = denyConfList; deny; deny = deny->next) {
1019     if (0 != match(deny->usermask, name))
1020       continue;
1021
1022     if (EmptyString(deny->hostmask))
1023       break;
1024
1025     if (deny->flags & DENY_FLAGS_REALNAME) { /* K: by real name */
1026       if (0 == match(deny->hostmask, realname))
1027         break;
1028     } else if (deny->flags & DENY_FLAGS_IP) { /* k: by IP */
1029 #ifdef DEBUGMODE
1030       char tbuf1[SOCKIPLEN], tbuf2[SOCKIPLEN];
1031       Debug((DEBUG_DEBUG, "ip: %s network: %s/%u",
1032              ircd_ntoa_r(tbuf1, &cli_ip(cptr)), ircd_ntoa_r(tbuf2, &deny->address), deny->bits));
1033 #endif
1034       if (ipmask_check(&cli_ip(cptr), &deny->address, deny->bits))
1035         break;
1036     }
1037     else if (0 == match(deny->hostmask, host))
1038       break;
1039   }
1040   if (deny) {
1041     if (EmptyString(deny->message))
1042       send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP,
1043                  ":Connection from your host is refused on this server.");
1044     else {
1045       if (deny->flags & DENY_FLAGS_FILE)
1046         killcomment(cptr, deny->message);
1047       else
1048         send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", deny->message);
1049     }
1050   }
1051   else if ((agline = gline_lookup(cptr, 0))) {
1052     /*
1053      * find active glines
1054      * added a check against the user's IP address to find_gline() -Kev
1055      */
1056     send_reply(cptr, SND_EXPLICIT | ERR_YOUREBANNEDCREEP, ":%s.", GlineReason(agline));
1057   }
1058
1059   if (deny)
1060     return -1;
1061   if (agline)
1062     return -2;
1063
1064   return 0;
1065 }
1066
1067 /** Attempt to attach Client blocks to \a cptr.  If attach_iline()
1068  * fails for the client, emit a debugging message.
1069  * @param cptr Client to check for access.
1070  * @return Access check result.
1071  */
1072 enum AuthorizationCheckResult conf_check_client(struct Client *cptr)
1073 {
1074   enum AuthorizationCheckResult acr = ACR_OK;
1075
1076   if ((acr = attach_iline(cptr))) {
1077     Debug((DEBUG_DNS, "ch_cl: access denied: %s[%s]", 
1078           cli_name(cptr), cli_sockhost(cptr)));
1079     return acr;
1080   }
1081   return ACR_OK;
1082 }
1083
1084 /** Check access for a server given its name (passed in cptr struct).
1085  * Must check for all C/N lines which have a name which matches the
1086  * name given and a host which matches. A host alias which is the
1087  * same as the server name is also acceptable in the host field of a
1088  * C/N line.
1089  * @param cptr Peer server to check.
1090  * @return 0 if accepted, -1 if access denied.
1091  */
1092 int conf_check_server(struct Client *cptr)
1093 {
1094   struct ConfItem* c_conf = NULL;
1095   struct SLink*    lp;
1096
1097   Debug((DEBUG_DNS, "sv_cl: check access for %s[%s]", 
1098         cli_name(cptr), cli_sockhost(cptr)));
1099
1100   if (IsUnknown(cptr) && !attach_confs_byname(cptr, cli_name(cptr), CONF_SERVER)) {
1101     Debug((DEBUG_DNS, "No C/N lines for %s", cli_sockhost(cptr)));
1102     return -1;
1103   }
1104   lp = cli_confs(cptr);
1105   /*
1106    * We initiated this connection so the client should have a C and N
1107    * line already attached after passing through the connect_server()
1108    * function earlier.
1109    */
1110   if (IsConnecting(cptr) || IsHandshake(cptr)) {
1111     c_conf = find_conf_byname(lp, cli_name(cptr), CONF_SERVER);
1112     if (!c_conf) {
1113       sendto_opmask_butone(0, SNO_OLDSNO, "Connect Error: lost C:line for %s",
1114                            cli_name(cptr));
1115       det_confs_butmask(cptr, 0);
1116       return -1;
1117     }
1118   }
1119
1120   if (!c_conf) {
1121     if (cli_dns_reply(cptr)) {
1122       struct DNSReply* hp = cli_dns_reply(cptr);
1123       const char*     name = hp->h_name;
1124       /*
1125        * If we are missing a C or N line from above, search for
1126        * it under all known hostnames we have for this ip#.
1127        */
1128       if ((c_conf = find_conf_byhost(lp, hp->h_name, CONF_SERVER)))
1129         ircd_strncpy(cli_sockhost(cptr), name, HOSTLEN);
1130       else
1131         c_conf = find_conf_byip(lp, &hp->addr, CONF_SERVER);
1132     }
1133     else {
1134       /*
1135        * Check for C lines with the hostname portion the ip number
1136        * of the host the server runs on. This also checks the case where
1137        * there is a server connecting from 'localhost'.
1138        */
1139       c_conf = find_conf_byhost(lp, cli_sockhost(cptr), CONF_SERVER);
1140     }
1141   }
1142   /*
1143    * Attach by IP# only if all other checks have failed.
1144    * It is quite possible to get here with the strange things that can
1145    * happen when using DNS in the way the irc server does. -avalon
1146    */
1147   if (!c_conf)
1148     c_conf = find_conf_byip(lp, &cli_ip(cptr), CONF_SERVER);
1149   /*
1150    * detach all conf lines that got attached by attach_confs()
1151    */
1152   det_confs_butmask(cptr, 0);
1153   /*
1154    * if no Connect block, then deny access
1155    */
1156   if (!c_conf) {
1157     Debug((DEBUG_DNS, "sv_cl: access denied: %s[%s@%s]",
1158           cli_name(cptr), cli_username(cptr), cli_sockhost(cptr)));
1159     return -1;
1160   }
1161   /*
1162    * attach the Connect block to the client structure for later use.
1163    */
1164   attach_conf(cptr, c_conf);
1165
1166   if (!irc_in_addr_valid(&c_conf->address.addr))
1167     memcpy(&c_conf->address.addr, &cli_ip(cptr), sizeof(c_conf->address.addr));
1168
1169   Debug((DEBUG_DNS, "sv_cl: access ok: %s[%s]",
1170          cli_name(cptr), cli_sockhost(cptr)));
1171   return 0;
1172 }
1173