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