Author: Kev <klmitch@undernet.org>
[ircu2.10.12-pk.git] / ircd / s_user.c
1 /*
2  * IRC - Internet Relay Chat, ircd/s_user.c (formerly ircd/s_msg.c)
3  * Copyright (C) 1990 Jarkko Oikarinen and
4  *                    University of Oulu, Computing Center
5  *
6  * See file AUTHORS in IRC package for additional names of
7  * the programmers.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 1, or (at your option)
12  * any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  * $Id$
24  */
25 #include "s_user.h"
26 #include "IPcheck.h"
27 #include "channel.h"
28 #include "class.h"
29 #include "client.h"
30 #include "gline.h"
31 #include "hash.h"
32 #include "ircd.h"
33 #include "ircd_alloc.h"
34 #include "ircd_chattr.h"
35 #include "ircd_log.h"
36 #include "ircd_reply.h"
37 #include "ircd_string.h"
38 #include "list.h"
39 #include "match.h"
40 #include "msg.h"
41 #include "numeric.h"
42 #include "numnicks.h"
43 #include "parse.h"
44 #include "querycmds.h"
45 #include "random.h"
46 #include "s_bsd.h"
47 #include "s_conf.h"
48 #include "s_debug.h"
49 #include "s_misc.h"
50 #include "s_serv.h" /* max_client_count */
51 #include "send.h"
52 #include "sprintf_irc.h"
53 #include "struct.h"
54 #include "support.h"
55 #include "supported.h"
56 #include "sys.h"
57 #include "userload.h"
58 #include "version.h"
59 #include "whowas.h"
60
61 #include "handlers.h" /* m_motd and m_lusers */
62
63 #include <assert.h>
64 #include <fcntl.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sys/stat.h>
69
70
71 static int userCount = 0;
72
73 /*
74  * 'make_user' add's an User information block to a client
75  * if it was not previously allocated.
76  */
77 struct User *make_user(struct Client *cptr)
78 {
79   assert(0 != cptr);
80
81   if (!cptr->user) {
82     cptr->user = (struct User*) MyMalloc(sizeof(struct User));
83     assert(0 != cptr->user);
84
85     /* All variables are 0 by default */
86     memset(cptr->user, 0, sizeof(struct User));
87 #ifdef  DEBUGMODE
88     ++userCount;
89 #endif
90     cptr->user->refcnt = 1;
91   }
92   return cptr->user;
93 }
94
95 /*
96  * free_user
97  *
98  * Decrease user reference count by one and release block, if count reaches 0.
99  */
100 void free_user(struct User* user)
101 {
102   assert(0 != user);
103   assert(0 < user->refcnt);
104
105   if (--user->refcnt == 0) {
106     if (user->away)
107       MyFree(user->away);
108     /*
109      * sanity check
110      */
111     assert(0 == user->joined);
112     assert(0 == user->invited);
113     assert(0 == user->channel);
114
115     MyFree(user);
116 #ifdef  DEBUGMODE
117     --userCount;
118 #endif
119   }
120 }
121
122 void user_count_memory(size_t* count_out, size_t* bytes_out)
123 {
124   assert(0 != count_out);
125   assert(0 != bytes_out);
126   *count_out = userCount;
127   *bytes_out = userCount * sizeof(struct User);
128 }
129
130 /*
131  * user_set_away - set user away state
132  * returns 1 if client is away or changed away message, 0 if 
133  * client is removing away status.
134  * NOTE: this function may modify user and message, so they
135  * must be mutable.
136  */
137 int user_set_away(struct User* user, char* message)
138 {
139   char* away;
140   assert(0 != user);
141
142   away = user->away;
143
144   if (EmptyString(message)) {
145     /*
146      * Marking as not away
147      */
148     if (away) {
149       MyFree(away);
150       user->away = 0;
151     }
152   }
153   else {
154     /*
155      * Marking as away
156      */
157     unsigned int len = strlen(message);
158
159     if (len > TOPICLEN) {
160       message[TOPICLEN] = '\0';
161       len = TOPICLEN;
162     }
163     if (away)
164       away = (char*) MyRealloc(away, len + 1);
165     else
166       away = (char*) MyMalloc(len + 1);
167     assert(0 != away);
168
169     user->away = away;
170     strcpy(away, message);
171   }
172   return (user->away != 0);
173 }
174
175 /*
176  * next_client
177  *
178  * Local function to find the next matching client. The search
179  * can be continued from the specified client entry. Normal
180  * usage loop is:
181  *
182  * for (x = client; x = next_client(x,mask); x = x->next)
183  *     HandleMatchingClient;
184  *
185  */
186 struct Client *next_client(struct Client *next, const char* ch)
187 {
188   struct Client *tmp = next;
189
190   if (!tmp)
191     return NULL;
192
193   next = FindClient(ch);
194   next = next ? next : tmp;
195   if (tmp->prev == next)
196     return NULL;
197   if (next != tmp)
198     return next;
199   for (; next; next = next->next)
200     if (!match(ch, next->name))
201       break;
202   return next;
203 }
204
205 /*
206  * hunt_server
207  *
208  *    Do the basic thing in delivering the message (command)
209  *    across the relays to the specific server (server) for
210  *    actions.
211  *
212  *    Note:   The command is a format string and *MUST* be
213  *            of prefixed style (e.g. ":%s COMMAND %s ...").
214  *            Command can have only max 8 parameters.
215  *
216  *    server  parv[server] is the parameter identifying the
217  *            target server.
218  *
219  *    *WARNING*
220  *            parv[server] is replaced with the pointer to the
221  *            real servername from the matched client (I'm lazy
222  *            now --msa).
223  *
224  *    returns: (see #defines)
225  */
226 int hunt_server(int MustBeOper, struct Client *cptr, struct Client *sptr, char *command,
227     int server, int parc, char *parv[])
228 {
229   struct Client *acptr;
230   char y[8];
231
232   /* Assume it's me, if no server or an unregistered client */
233   if (parc <= server || EmptyString(parv[server]) || IsUnknown(sptr))
234     return (HUNTED_ISME);
235
236   /* Make sure it's a server */
237   if (MyUser(sptr) || Protocol(cptr) < 10)
238   {
239     /* Make sure it's a server */
240     if (!strchr(parv[server], '*')) {
241       if (0 == (acptr = FindClient(parv[server])))
242         return HUNTED_NOSUCH;
243       if (acptr->user)
244         acptr = acptr->user->server;
245     }
246     else if (!(acptr = find_match_server(parv[server])))
247     {
248       sendto_one(sptr, err_str(ERR_NOSUCHSERVER),
249           me.name, parv[0], parv[server]);
250       return (HUNTED_NOSUCH);
251     }
252   }
253   else if (!(acptr = FindNServer(parv[server])))
254     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
255
256   if (IsMe(acptr))
257     return (HUNTED_ISME);
258
259   if (MustBeOper && !IsPrivileged(sptr))
260   {
261     sendto_one(sptr, err_str(ERR_NOPRIVILEGES), me.name, sptr->name);
262     return HUNTED_NOSUCH;
263   }
264
265   strcpy(y, acptr->yxx);
266   parv[server] = y;
267
268   assert(!IsServer(sptr));
269   sendto_one(acptr, command, NumNick(sptr), parv[1], parv[2], parv[3], parv[4],
270       parv[5], parv[6], parv[7], parv[8]);
271
272   return (HUNTED_PASS);
273 }
274
275 /*
276  * 'do_nick_name' ensures that the given parameter (nick) is really a proper
277  * string for a nickname (note, the 'nick' may be modified in the process...)
278  *
279  * RETURNS the length of the final NICKNAME (0, if nickname is invalid)
280  *
281  * Nickname characters are in range 'A'..'}', '_', '-', '0'..'9'
282  *  anything outside the above set will terminate nickname.
283  * In addition, the first character cannot be '-' or a Digit.
284  *
285  * Note:
286  *  The '~'-character should be allowed, but a change should be global,
287  *  some confusion would result if only few servers allowed it...
288  */
289 int do_nick_name(char* nick)
290 {
291   char* ch  = nick;
292   char* end = ch + NICKLEN;
293   assert(0 != ch);
294
295   if (*ch == '-' || IsDigit(*ch))        /* first character in [0..9-] */
296     return 0;
297
298   for ( ; (ch < end) && *ch; ++ch)
299     if (!IsNickChar(*ch))
300       break;
301
302   *ch = '\0';
303
304   return (ch - nick);
305 }
306
307 /*
308  * clean_user_id
309  *
310  * Copy `source' to `dest', replacing all occurances of '~' and characters that
311  * are not `isIrcUi' by an underscore.
312  * Copies at most USERLEN - 1 characters or up till the first control character.
313  * If `tilde' is true, then a tilde is prepended to `dest'.
314  * Note that `dest' and `source' can point to the same area or to different
315  * non-overlapping areas.
316  */
317 static char *clean_user_id(char *dest, char *source, int tilde)
318 {
319   char ch;
320   char *d = dest;
321   char *s = source;
322   int rlen = USERLEN;
323
324   ch = *s++;                        /* Store first character to copy: */
325   if (tilde)
326   {
327     *d++ = '~';                        /* If `dest' == `source', then this overwrites `ch' */
328     --rlen;
329   }
330   while (ch && !IsCntrl(ch) && rlen--)
331   {
332     char nch = *s++;        /* Store next character to copy */
333     *d++ = IsUserChar(ch) ? ch : '_';        /* This possibly overwrites it */
334     if (nch == '~')
335       ch = '_';
336     else
337       ch = nch;
338   }
339   *d = 0;
340   return dest;
341 }
342
343 /*
344  * register_user
345  *
346  * This function is called when both NICK and USER messages
347  * have been accepted for the client, in whatever order. Only
348  * after this the USER message is propagated.
349  *
350  * NICK's must be propagated at once when received, although
351  * it would be better to delay them too until full info is
352  * available. Doing it is not so simple though, would have
353  * to implement the following:
354  *
355  * 1) user telnets in and gives only "NICK foobar" and waits
356  * 2) another user far away logs in normally with the nick
357  *    "foobar" (quite legal, as this server didn't propagate it).
358  * 3) now this server gets nick "foobar" from outside, but
359  *    has already the same defined locally. Current server
360  *    would just issue "KILL foobar" to clean out dups. But,
361  *    this is not fair. It should actually request another
362  *    nick from local user or kill him/her...
363  */
364 int register_user(struct Client *cptr, struct Client *sptr,
365                   const char *nick, char *username)
366 {
367   struct ConfItem* aconf;
368   char*            parv[3];
369   char*            tmpstr;
370   char*            tmpstr2;
371   char             c = 0;    /* not alphanum */
372   char             d = 'a';  /* not a digit */
373   short            upper = 0;
374   short            lower = 0;
375   short            pos = 0;
376   short            leadcaps = 0;
377   short            other = 0;
378   short            digits = 0;
379   short            badid = 0;
380   short            digitgroups = 0;
381   struct User*     user = sptr->user;
382   char             ip_base64[8];
383   char             featurebuf[512];
384   struct Gline*    gline;
385
386   user->last = CurrentTime;
387   parv[0] = sptr->name;
388   parv[1] = parv[2] = NULL;
389
390   if (MyConnect(sptr))
391   {
392     static time_t last_too_many1;
393     static time_t last_too_many2;
394
395     assert(cptr == sptr);
396     switch (conf_check_client(sptr))
397     {
398       case ACR_OK:
399         break;
400       case ACR_NO_AUTHORIZATION:
401         sendto_op_mask(SNO_UNAUTH, "Unauthorized connection from %s.",
402                        get_client_name(sptr, HIDE_IP));
403         ++ServerStats->is_ref;
404         return exit_client(cptr, sptr, &me,
405             "No Authorization - use another server");
406       case ACR_TOO_MANY_IN_CLASS:
407         if (CurrentTime - last_too_many1 >= (time_t) 60)
408         {
409           last_too_many1 = CurrentTime;
410           sendto_op_mask(SNO_TOOMANY, "Too many connections in class for %s.",
411                          get_client_name(sptr, HIDE_IP));
412         }
413         ++ServerStats->is_ref;
414         IPcheck_connect_fail(sptr->ip);
415         return exit_client(cptr, sptr, &me,
416             "Sorry, your connection class is full - try again later or try another server");
417       case ACR_TOO_MANY_FROM_IP:
418         if (CurrentTime - last_too_many2 >= (time_t) 60)
419         {
420           last_too_many2 = CurrentTime;
421           sendto_op_mask(SNO_TOOMANY, "Too many connections from same IP for %s.",
422                          get_client_name(sptr, HIDE_IP));
423         }
424         ++ServerStats->is_ref;
425         return exit_client(cptr, sptr, &me,
426             "Too many connections from your host");
427       case ACR_ALREADY_AUTHORIZED:
428         /* Can this ever happen? */
429       case ACR_BAD_SOCKET:
430         ++ServerStats->is_ref;
431         IPcheck_connect_fail(sptr->ip);
432         return exit_client(cptr, sptr, &me, "Unknown error -- Try again");
433     }
434     ircd_strncpy(user->host, sptr->sockhost, HOSTLEN);
435     aconf = sptr->confs->value.aconf;
436
437     clean_user_id(user->username,
438         (sptr->flags & FLAGS_GOTID) ? sptr->username : username,
439         (sptr->flags & FLAGS_DOID) && !(sptr->flags & FLAGS_GOTID));
440
441     if ((user->username[0] == '\0')
442         || ((user->username[0] == '~') && (user->username[1] == '\000')))
443       return exit_client(cptr, sptr, &me, "USER: Bogus userid.");
444
445     if (!EmptyString(aconf->passwd)
446         && !(IsDigit(*aconf->passwd) && !aconf->passwd[1])
447 #ifdef USEONE
448         && strcmp("ONE", aconf->passwd)
449 #endif
450         && strcmp(sptr->passwd, aconf->passwd))
451     {
452       ServerStats->is_ref++;
453       IPcheck_connect_fail(sptr->ip);
454       sendto_one(sptr, err_str(ERR_PASSWDMISMATCH), me.name, parv[0]);
455       return exit_client(cptr, sptr, &me, "Bad Password");
456     }
457     memset(sptr->passwd, 0, sizeof(sptr->passwd));
458     /*
459      * following block for the benefit of time-dependent K:-lines
460      */
461     if (find_kill(sptr)) {
462       ServerStats->is_ref++;
463       IPcheck_connect_fail(sptr->ip);
464       return exit_client(cptr, sptr, &me, "K-lined");
465     }
466     /*
467      * Check for mixed case usernames, meaning probably hacked.  Jon2 3-94
468      * Summary of rules now implemented in this patch:         Ensor 11-94
469      * In a mixed-case name, if first char is upper, one more upper may
470      * appear anywhere.  (A mixed-case name *must* have an upper first
471      * char, and may have one other upper.)
472      * A third upper may appear if all 3 appear at the beginning of the
473      * name, separated only by "others" (-/_/.).
474      * A single group of digits is allowed anywhere.
475      * Two groups of digits are allowed if at least one of the groups is
476      * at the beginning or the end.
477      * Only one '-', '_', or '.' is allowed (or two, if not consecutive).
478      * But not as the first or last char.
479      * No other special characters are allowed.
480      * Name must contain at least one letter.
481      */
482     tmpstr2 = tmpstr = (username[0] == '~' ? &username[1] : username);
483     while (*tmpstr && !badid)
484     {
485       pos++;
486       c = *tmpstr;
487       tmpstr++;
488       if (IsLower(c))
489       {
490         lower++;
491       }
492       else if (IsUpper(c))
493       {
494         upper++;
495         if ((leadcaps || pos == 1) && !lower && !digits)
496           leadcaps++;
497       }
498       else if (IsDigit(c))
499       {
500         digits++;
501         if (pos == 1 || !IsDigit(d))
502         {
503           digitgroups++;
504           if (digitgroups > 2)
505             badid = 1;
506         }
507       }
508       else if (c == '-' || c == '_' || c == '.')
509       {
510         other++;
511         if (pos == 1)
512           badid = 1;
513         else if (d == '-' || d == '_' || d == '.' || other > 2)
514           badid = 1;
515       }
516       else
517         badid = 1;
518       d = c;
519     }
520     if (!badid)
521     {
522       if (lower && upper && (!leadcaps || leadcaps > 3 ||
523           (upper > 2 && upper > leadcaps)))
524         badid = 1;
525       else if (digitgroups == 2 && !(IsDigit(tmpstr2[0]) || IsDigit(c)))
526         badid = 1;
527       else if ((!lower && !upper) || !IsAlnum(c))
528         badid = 1;
529     }
530     if (badid && (!(sptr->flags & FLAGS_GOTID) ||
531         strcmp(sptr->username, username) != 0))
532     {
533       ServerStats->is_ref++;
534       sendto_one(cptr, ":%s %d %s :Your username is invalid.",
535                  me.name, ERR_INVALIDUSERNAME, cptr->name);
536       sendto_one(cptr,
537                  ":%s %d %s :Connect with your real username, in lowercase.",
538                  me.name, ERR_INVALIDUSERNAME, cptr->name);
539       sendto_one(cptr, ":%s %d %s :If your mail address were foo@bar.com, "
540                  "your username would be foo.",
541                  me.name, ERR_INVALIDUSERNAME, cptr->name);
542       return exit_client(cptr, sptr, &me, "USER: Bad username");
543     }
544     Count_unknownbecomesclient(sptr, UserStats);
545   }
546   else {
547     ircd_strncpy(user->username, username, USERLEN);
548     Count_newremoteclient(UserStats, user->server);
549     if ((gline = gline_lookup(sptr)) && GlineIsActive(gline))
550       gline_resend(cptr, gline);
551   }
552   SetUser(sptr);
553
554   if (IsInvisible(sptr))
555     ++UserStats.inv_clients;
556   if (IsOper(sptr))
557     ++UserStats.opers;
558
559   if (MyConnect(sptr)) {
560     sptr->handler = CLIENT_HANDLER;
561     release_dns_reply(sptr);
562
563     sendto_one(sptr, rpl_str(RPL_WELCOME), me.name, nick, nick);
564     /*
565      * This is a duplicate of the NOTICE but see below...
566      */
567     sendto_one(sptr, rpl_str(RPL_YOURHOST), me.name, nick,
568                me.name, version);
569     sendto_one(sptr, rpl_str(RPL_CREATED), me.name, nick, creation);
570     sendto_one(sptr, rpl_str(RPL_MYINFO), me.name, parv[0], me.name, version);
571     sprintf_irc(featurebuf,FEATURES,FEATURESVALUES);
572     sendto_one(sptr, rpl_str(RPL_ISUPPORT), me.name, nick, featurebuf);
573     m_lusers(sptr, sptr, 1, parv);
574     update_load();
575 #ifdef NODEFAULTMOTD
576     m_motd(sptr, NULL, 1, parv);
577 #else
578     m_motd(sptr, sptr, 1, parv);
579 #endif
580     nextping = CurrentTime;
581     if (sptr->snomask & SNO_NOISY)
582       set_snomask(sptr, sptr->snomask & SNO_NOISY, SNO_ADD);
583 #ifdef ALLOW_SNO_CONNEXIT
584 #ifdef SNO_CONNEXIT_IP
585     sprintf_irc(sendbuf,
586                 ":%s NOTICE * :*** Notice -- Client connecting: %s (%s@%s) [%s] {%d}",
587                 me.name, nick, user->username, user->host, cptr->sock_ip,
588                 get_client_class(sptr));
589     sendbufto_op_mask(SNO_CONNEXIT);
590 #else /* SNO_CONNEXIT_IP */
591     sprintf_irc(sendbuf,
592                 ":%s NOTICE * :*** Notice -- Client connecting: %s (%s@%s)",
593                 me.name, nick, user->username, user->host);
594     sendbufto_op_mask(SNO_CONNEXIT);
595 #endif /* SNO_CONNEXIT_IP */
596 #endif /* ALLOW_SNO_CONNEXIT */
597     IPcheck_connect_succeeded(sptr);
598   }
599   else
600     /* if (IsServer(cptr)) */
601   {
602     struct Client *acptr;
603
604     acptr = user->server;
605     if (acptr->from != sptr->from)
606     {
607       sendto_one(cptr, "%s " TOK_KILL " %s%s :%s (%s != %s[%s])",
608                  NumServ(&me), NumNick(sptr), me.name, user->server->name,
609                  acptr->from->name, acptr->from->sockhost);
610       sptr->flags |= FLAGS_KILLED;
611       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
612     }
613     else
614       sptr->flags |= (acptr->flags & FLAGS_TS8);
615
616     /*
617      * Check to see if this user is being propogated
618      * as part of a net.burst, or is using protocol 9.
619      * FIXME: This can be speeded up - its stupid to check it for
620      * every NICK message in a burst again  --Run.
621      */
622     for (acptr = user->server; acptr != &me; acptr = acptr->serv->up) {
623       if (IsBurst(acptr) || Protocol(acptr) < 10)
624         break;
625     }
626     if (!IPcheck_remote_connect(sptr, (acptr != &me)))
627       /*
628        * We ran out of bits to count this
629        */
630       return exit_client(cptr, sptr, &me, "More than 255 connections from this address");
631   }
632
633   tmpstr = umode_str(sptr);
634   sendto_serv_butone(cptr, *tmpstr ?
635                      "%s " TOK_NICK " %s %d %d %s %s +%s %s %s%s :%s" :
636                      "%s " TOK_NICK " %s %d %d %s %s %s%s %s%s :%s",
637                      NumServ(user->server), nick, sptr->hopcount + 1, sptr->lastnick,
638                      user->username, user->host, tmpstr, 
639                      inttobase64(ip_base64, ntohl(sptr->ip.s_addr), 6),
640                      NumNick(sptr), sptr->info);
641
642   /* Send umode to client */
643   if (MyUser(sptr))
644   {
645     send_umode(cptr, sptr, 0, ALL_UMODES);
646     if (sptr->snomask != SNO_DEFAULT && (sptr->flags & FLAGS_SERVNOTICE))
647       sendto_one(sptr, rpl_str(RPL_SNOMASK), me.name, sptr->name,
648                  sptr->snomask, sptr->snomask);
649   }
650
651   return 0;
652 }
653
654
655 static const struct UserMode {
656   unsigned int flag;
657   char         c;
658 } userModeList[] = {
659   { FLAGS_OPER,        'o' },
660   { FLAGS_LOCOP,       'O' },
661   { FLAGS_INVISIBLE,   'i' },
662   { FLAGS_WALLOP,      'w' },
663   { FLAGS_SERVNOTICE,  's' },
664   { FLAGS_DEAF,        'd' },
665   { FLAGS_CHSERV,      'k' },
666   { FLAGS_DEBUG,       'g' }
667 };
668
669 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
670
671 #if 0
672 static int user_modes[] = {
673   FLAGS_OPER,        'o',
674   FLAGS_LOCOP,       'O',
675   FLAGS_INVISIBLE,   'i',
676   FLAGS_WALLOP,      'w',
677   FLAGS_SERVNOTICE,  's',
678   FLAGS_DEAF,        'd',
679   FLAGS_CHSERV,      'k',
680   FLAGS_DEBUG,       'g',
681   0,                  0
682 };
683 #endif
684
685 /*
686  * XXX - find a way to get rid of this
687  */
688 static char umodeBuf[BUFSIZE];
689
690 int set_nick_name(struct Client* cptr, struct Client* sptr,
691                   const char* nick, int parc, char* parv[])
692 {
693   if (IsServer(sptr)) {
694     int   i;
695     const char* p;
696
697     /*
698      * A server introducing a new client, change source
699      */
700     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
701     assert(0 != new_client);
702
703     new_client->hopcount = atoi(parv[2]);
704     new_client->lastnick = atoi(parv[3]);
705     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+') {
706       for (p = parv[6] + 1; *p; p++) {
707         for (i = 0; i < USERMODELIST_SIZE; ++i) {
708           if (userModeList[i].c == *p) {
709             new_client->flags |= userModeList[i].flag;
710             break;
711           }
712         }
713       }
714     }
715     /*
716      * Set new nick name.
717      */
718     strcpy(new_client->name, nick);
719     new_client->user = make_user(new_client);
720     new_client->user->server = sptr;
721     SetRemoteNumNick(new_client, parv[parc - 2]);
722     /*
723      * IP# of remote client
724      */
725     new_client->ip.s_addr = htonl(base64toint(parv[parc - 3]));
726
727     add_client_to_list(new_client);
728     hAddClient(new_client);
729
730     sptr->serv->ghost = 0;        /* :server NICK means end of net.burst */
731     ircd_strncpy(new_client->username, parv[4], USERLEN);
732     ircd_strncpy(new_client->user->host, parv[5], HOSTLEN);
733     ircd_strncpy(new_client->info, parv[parc - 1], REALLEN);
734     return register_user(cptr, new_client, new_client->name, parv[4]);
735   }
736   else if (sptr->name[0]) {
737     /*
738      * Client changing its nick
739      *
740      * If the client belongs to me, then check to see
741      * if client is on any channels where it is currently
742      * banned.  If so, do not allow the nick change to occur.
743      */
744     if (MyUser(sptr)) {
745       const char* channel_name;
746       if ((channel_name = find_no_nickchange_channel(sptr))) {
747         sendto_one(cptr, err_str(ERR_BANNICKCHANGE), me.name, parv[0],
748                    channel_name);
749         return 0;
750       }
751       /*
752        * Refuse nick change if the last nick change was less
753        * then 30 seconds ago. This is intended to get rid of
754        * clone bots doing NICK FLOOD. -SeKs
755        * If someone didn't change their nick for more then 60 seconds
756        * however, allow to do two nick changes immedately after another
757        * before limiting the nick flood. -Run
758        */
759       if (CurrentTime < cptr->nextnick) {
760         cptr->nextnick += 2;
761         sendto_one(cptr, err_str(ERR_NICKTOOFAST),
762             me.name, parv[0], parv[1], cptr->nextnick - CurrentTime);
763         /* Send error message */
764         sendto_prefix_one(cptr, cptr, ":%s NICK %s", parv[0], parv[0]);
765         /* bounce NICK to user */
766         return 0;                /* ignore nick change! */
767       }
768       else {
769         /* Limit total to 1 change per NICK_DELAY seconds: */
770         cptr->nextnick += NICK_DELAY;
771         /* However allow _maximal_ 1 extra consecutive nick change: */
772         if (cptr->nextnick < CurrentTime)
773           cptr->nextnick = CurrentTime;
774       }
775     }
776     /*
777      * Also set 'lastnick' to current time, if changed.
778      */
779     if (0 != ircd_strcmp(parv[0], nick))
780       sptr->lastnick = (sptr == cptr) ? TStime() : atoi(parv[2]);
781
782     /*
783      * Client just changing his/her nick. If he/she is
784      * on a channel, send note of change to all clients
785      * on that channel. Propagate notice to other servers.
786      */
787     if (IsUser(sptr)) {
788       sendto_common_channels(sptr, ":%s NICK :%s", parv[0], nick);
789       add_history(sptr, 1);
790       sendto_serv_butone(cptr,
791           "%s%s " TOK_NICK " %s " TIME_T_FMT, NumNick(sptr), nick, sptr->lastnick);
792     }
793     else
794       sendto_one(sptr, ":%s NICK :%s", parv[0], nick);
795
796     if (sptr->name[0])
797       hRemClient(sptr);
798     strcpy(sptr->name, nick);
799     hAddClient(sptr);
800   }
801   else {
802     /* Local client setting NICK the first time */
803
804     strcpy(sptr->name, nick);
805     if (!sptr->user) {
806       sptr->user = make_user(sptr);
807       sptr->user->server = &me;
808     }
809     SetLocalNumNick(sptr);
810     hAddClient(sptr);
811
812     /*
813      * If the client hasn't gotten a cookie-ping yet,
814      * choose a cookie and send it. -record!jegelhof@cloud9.net
815      */
816     if (!sptr->cookie) {
817       do {
818         sptr->cookie = (ircrandom() & 0x7fffffff);
819       } while (!sptr->cookie);
820       sendto_one(cptr, "PING :%u", sptr->cookie);
821     }
822     else if (*sptr->user->host && sptr->cookie == COOKIE_VERIFIED) {
823       /*
824        * USER and PONG already received, now we have NICK.
825        * register_user may reject the client and call exit_client
826        * for it - must test this and exit m_nick too !
827        */
828       sptr->lastnick = TStime();        /* Always local client */
829       if (register_user(cptr, sptr, nick, sptr->user->username) == CPTR_KILLED)
830         return CPTR_KILLED;
831     }
832   }
833   return 0;
834 }
835
836 static unsigned char hash_target(unsigned int target)
837 {
838   return (unsigned char) (target >> 16) ^ (target >> 8);
839 }
840
841 /*
842  * add_target
843  *
844  * sptr must be a local client!
845  *
846  * Cannonifies target for client `sptr'.
847  */
848 void add_target(struct Client *sptr, void *target)
849 {
850   unsigned char  hash = hash_target((unsigned int) target);
851   unsigned char* targets;
852   int            i;
853   assert(0 != sptr);
854   assert(sptr->local);
855
856   targets = sptr->targets;
857   /* 
858    * Already in table?
859    */
860   for (i = 0; i < MAXTARGETS; ++i) {
861     if (targets[i] == hash)
862       return;
863   }
864   /*
865    * New target
866    */
867   memmove(&targets[RESERVEDTARGETS + 1],
868           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
869   targets[RESERVEDTARGETS] = hash;
870 }
871
872 /*
873  * check_target_limit
874  *
875  * sptr must be a local client !
876  *
877  * Returns 'true' (1) when too many targets are addressed.
878  * Returns 'false' (0) when it's ok to send to this target.
879  */
880 int check_target_limit(struct Client *sptr, void *target, const char *name,
881     int created)
882 {
883   unsigned char hash = hash_target((unsigned int) target);
884   int            i;
885   unsigned char* targets;
886
887   assert(0 != sptr);
888   assert(sptr->local);
889   targets = sptr->targets;
890
891   /*
892    * Same target as last time?
893    */
894   if (targets[0] == hash)
895     return 0;
896   for (i = 1; i < MAXTARGETS; ++i) {
897     if (targets[i] == hash) {
898       memmove(&targets[1], &targets[0], i);
899       targets[0] = hash;
900       return 0;
901     }
902   }
903   /*
904    * New target
905    */
906   if (!created) {
907     if (CurrentTime < sptr->nexttarget) {
908       if (sptr->nexttarget - CurrentTime < TARGET_DELAY + 8) {
909         /*
910          * No server flooding
911          */
912         sptr->nexttarget += 2;
913         sendto_one(sptr, err_str(ERR_TARGETTOOFAST),
914                    me.name, sptr->name, name, sptr->nexttarget - CurrentTime);
915       }
916       return 1;
917     }
918     else {
919 #ifdef GODMODE
920       sendto_one(sptr, ":%s NOTICE %s :New target: %s; ft " TIME_T_FMT,
921           me.name, sptr->name, name, (CurrentTime - sptr->nexttarget) / TARGET_DELAY);
922 #endif
923       sptr->nexttarget += TARGET_DELAY;
924       if (sptr->nexttarget < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
925         sptr->nexttarget = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
926     }
927   }
928   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
929   targets[0] = hash;
930   return 0;
931 }
932
933 /*
934  * whisper - called from m_cnotice and m_cprivmsg.
935  *
936  * parv[0] = sender prefix
937  * parv[1] = nick
938  * parv[2] = #channel
939  * parv[3] = Private message text
940  *
941  * Added 971023 by Run.
942  * Reason: Allows channel operators to sent an arbitrary number of private
943  *   messages to users on their channel, avoiding the max.targets limit.
944  *   Building this into m_private would use too much cpu because we'd have
945  *   to a cross channel lookup for every private message!
946  * Note that we can't allow non-chan ops to use this command, it would be
947  *   abused by mass advertisers.
948  *
949  */
950 int whisper(struct Client* source, const char* nick, const char* channel,
951             const char* text, int is_notice)
952 {
953   struct Client*     dest;
954   struct Channel*    chptr;
955   struct Membership* membership;
956
957   assert(0 != source);
958   assert(0 != nick);
959   assert(0 != channel);
960   assert(MyUser(source));
961
962   if (!(dest = FindUser(nick))) {
963     sendto_one(source, err_str(ERR_NOSUCHNICK), me.name, source->name, nick);
964     return 0;
965   }
966   if (!(chptr = FindChannel(channel))) {
967     sendto_one(source, err_str(ERR_NOSUCHCHANNEL), me.name, source->name, channel);
968     return 0;
969   }
970   /*
971    * compare both users channel lists, instead of the channels user list
972    * since the link is the same, this should be a little faster for channels
973    * with a lot of users
974    */
975   for (membership = source->user->channel; membership; membership = membership->next_channel) {
976     if (chptr == membership->channel)
977       break;
978   }
979   if (0 == membership) {
980     sendto_one(source, err_str(ERR_NOTONCHANNEL), me.name, source->name, chptr->chname);
981     return 0;
982   }
983   if (!IsVoicedOrOpped(membership)) {
984     sendto_one(source, err_str(ERR_VOICENEEDED), me.name, source->name, chptr->chname);
985     return 0;
986   }
987   /*
988    * lookup channel in destination
989    */
990   assert(0 != dest->user);
991   for (membership = dest->user->channel; membership; membership = membership->next_channel) {
992     if (chptr == membership->channel)
993       break;
994   }
995   if (0 == membership || IsZombie(membership)) {
996     sendto_one(source, err_str(ERR_USERNOTINCHANNEL), me.name, 
997                source->name, dest->name, chptr->chname);
998     return 0;
999   }
1000   if (is_silenced(source, dest))
1001     return 0;
1002           
1003   if (dest->user->away)
1004     sendto_one(source, rpl_str(RPL_AWAY), me.name, source->name,
1005                dest->name, dest->user->away);
1006   if (MyUser(dest))
1007     sendto_prefix_one(dest, source, ":%s %s %s :%s",
1008                       source->name, is_notice ? MSG_NOTICE : MSG_PRIVATE, 
1009                       dest->name, text);
1010   else
1011     sendto_one(dest, "%s%s %s %s%s :%s",
1012                NumNick(source), is_notice ? TOK_NOTICE : TOK_PRIVATE, 
1013                NumNick(dest), text);
1014   return 0;
1015 }
1016
1017
1018 /*
1019  * added Sat Jul 25 07:30:42 EST 1992
1020  */
1021 void send_umode_out(struct Client *cptr, struct Client *sptr, int old)
1022 {
1023   int i;
1024   struct Client *acptr;
1025
1026   send_umode(NULL, sptr, old, SEND_UMODES);
1027
1028   for (i = HighestFd; i >= 0; i--) {
1029     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
1030         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
1031       sendto_one(acptr, "%s%s " TOK_MODE " %s :%s", NumNick(sptr), sptr->name, umodeBuf);
1032   }
1033   if (cptr && MyUser(cptr))
1034     send_umode(cptr, sptr, old, ALL_UMODES);
1035 }
1036
1037
1038 /*
1039  * send_user_info - send user info userip/userhost
1040  * NOTE: formatter must put info into buffer and return a pointer to the end of
1041  * the data it put in the buffer.
1042  */
1043 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
1044 {
1045   char*          sbuf;
1046   char*          name;
1047   char*          p = 0;
1048   int            arg_count = 0;
1049   int            users_found = 0;
1050   struct Client* acptr;
1051   char           buf[BUFSIZE * 2];
1052
1053   assert(0 != sptr);
1054   assert(0 != names);
1055   assert(0 != fmt);
1056
1057   sbuf = sprintf_irc(buf, rpl_str(rpl), me.name, sptr->name);
1058
1059   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
1060     if ((acptr = FindUser(name))) {
1061       if (users_found++)
1062         *sbuf++ = ' ';
1063       sbuf = (*fmt)(acptr, sbuf);
1064     }
1065     if (5 == ++arg_count)
1066       break;
1067   }
1068   if (users_found)
1069     send_buffer(sptr, buf);
1070 }
1071
1072
1073 /*
1074  * set_user_mode() added 15/10/91 By Darren Reed.
1075  *
1076  * parv[0] - sender
1077  * parv[1] - username to change mode for
1078  * parv[2] - modes to change
1079  */
1080 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1081 {
1082   char** p;
1083   char*  m;
1084   struct Client *acptr;
1085   int what;
1086   int i;
1087   int setflags;
1088   unsigned int tmpmask = 0;
1089   int snomask_given = 0;
1090   char buf[BUFSIZE];
1091
1092   what = MODE_ADD;
1093
1094   if (parc < 2)
1095     return need_more_params(sptr, "MODE");
1096
1097   if (!(acptr = FindUser(parv[1])))
1098   {
1099     if (MyConnect(sptr))
1100       sendto_one(sptr, err_str(ERR_NOSUCHCHANNEL), me.name, parv[0], parv[1]);
1101     return 0;
1102   }
1103
1104   if (IsServer(sptr) || sptr != acptr)
1105   {
1106     if (IsServer(cptr))
1107       sendto_ops_butone(NULL, &me, ":%s WALLOPS :MODE for User %s From %s!%s",
1108           me.name, parv[1], cptr->name, sptr->name);
1109     else
1110       sendto_one(sptr, err_str(ERR_USERSDONTMATCH), me.name, parv[0]);
1111     return 0;
1112   }
1113
1114   if (parc < 3)
1115   {
1116     m = buf;
1117     *m++ = '+';
1118     for (i = 0; i < USERMODELIST_SIZE; ++i) {
1119       if ( (userModeList[i].flag & sptr->flags))
1120         *m++ = userModeList[i].c;
1121     }
1122     *m = '\0';
1123     sendto_one(sptr, rpl_str(RPL_UMODEIS), me.name, parv[0], buf);
1124     if ((sptr->flags & FLAGS_SERVNOTICE) && MyConnect(sptr)
1125         && sptr->snomask !=
1126         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1127       sendto_one(sptr, rpl_str(RPL_SNOMASK), me.name, parv[0], sptr->snomask,
1128           sptr->snomask);
1129     return 0;
1130   }
1131
1132   /*
1133    * find flags already set for user
1134    * why not just copy them?
1135    */
1136   setflags = sptr->flags;
1137 #if 0
1138   setflags = 0;
1139   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1140     if (sptr->flags & userModeList[i].flag)
1141       setflags |= userModeList[i].flag;
1142   }
1143 #endif
1144   if (MyConnect(sptr))
1145     tmpmask = sptr->snomask;
1146
1147   /*
1148    * parse mode change string(s)
1149    */
1150   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1151     for (m = *p; *m; m++) {
1152       switch (*m) {
1153       case '+':
1154         what = MODE_ADD;
1155         break;
1156       case '-':
1157         what = MODE_DEL;
1158         break;
1159       case 's':
1160         if (*(p + 1) && is_snomask(*(p + 1))) {
1161           snomask_given = 1;
1162           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1163           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1164         }
1165         else
1166           tmpmask = (what == MODE_ADD) ?
1167               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1168         if (tmpmask)
1169           sptr->flags |= FLAGS_SERVNOTICE;
1170         else
1171           sptr->flags &= ~FLAGS_SERVNOTICE;
1172         break;
1173       case 'w':
1174         if (what == MODE_ADD)
1175           SetWallops(sptr);
1176         else
1177           ClearWallops(sptr);
1178         break;
1179       case 'o':
1180         if (what == MODE_ADD)
1181           SetOper(sptr);
1182         else {
1183           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1184           if (MyConnect(sptr)) {
1185             tmpmask = sptr->snomask & ~SNO_OPER;
1186             sptr->handler = CLIENT_HANDLER;
1187           }
1188         }
1189         break;
1190       case 'O':
1191         if (what == MODE_ADD)
1192           SetLocOp(sptr);
1193         else { 
1194           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1195           if (MyConnect(sptr)) {
1196             tmpmask = sptr->snomask & ~SNO_OPER;
1197             sptr->handler = CLIENT_HANDLER;
1198           }
1199         }
1200         break;
1201       case 'i':
1202         if (what == MODE_ADD)
1203           SetInvisible(sptr);
1204         else
1205           ClearInvisible(sptr);
1206         break;
1207       case 'd':
1208         if (what == MODE_ADD)
1209           SetDeaf(sptr);
1210         else
1211           ClearDeaf(sptr);
1212         break;
1213       case 'k':
1214         if (what == MODE_ADD)
1215           SetChannelService(sptr);
1216         else
1217           ClearChannelService(sptr);
1218         break;
1219       case 'g':
1220         if (what == MODE_ADD)
1221           SetDebug(sptr);
1222         else
1223           ClearDebug(sptr);
1224         break;
1225       default:
1226         break;
1227       }
1228     }
1229   }
1230   /*
1231    * Evaluate rules for new user mode
1232    * Stop users making themselves operators too easily:
1233    */
1234   if (!(setflags & FLAGS_OPER) && IsOper(sptr) && !IsServer(cptr))
1235     ClearOper(sptr);
1236   if (!(setflags & FLAGS_LOCOP) && IsLocOp(sptr) && !IsServer(cptr))
1237     ClearLocOp(sptr);
1238 #ifdef WALLOPS_OPER_ONLY
1239   /*
1240    * only send wallops to opers
1241    */
1242   if (!IsAnOper(sptr) && !(setflags & FLAGS_WALLOP) && !IsServer(cptr))
1243     ClearWallops(sptr);
1244 #endif
1245   if ((setflags & (FLAGS_OPER | FLAGS_LOCOP)) && !IsAnOper(sptr) &&
1246       MyConnect(sptr))
1247     det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPS);
1248   /*
1249    * new umode; servers can set it, local users cannot;
1250    * prevents users from /kick'ing or /mode -o'ing
1251    */
1252   if (!(setflags & FLAGS_CHSERV) && !IsServer(cptr))
1253     ClearChannelService(sptr);
1254   /*
1255    * Compare new flags with old flags and send string which
1256    * will cause servers to update correctly.
1257    */
1258   if ((setflags & FLAGS_OPER) && !IsOper(sptr))
1259     --UserStats.opers;
1260   if (!(setflags & FLAGS_OPER) && IsOper(sptr))
1261     ++UserStats.opers;
1262   if ((setflags & FLAGS_INVISIBLE) && !IsInvisible(sptr))
1263     --UserStats.inv_clients;
1264   if (!(setflags & FLAGS_INVISIBLE) && IsInvisible(sptr))
1265     ++UserStats.inv_clients;
1266   send_umode_out(cptr, sptr, setflags);
1267
1268   if (MyConnect(sptr)) {
1269     if (tmpmask != sptr->snomask)
1270       set_snomask(sptr, tmpmask, SNO_SET);
1271     if (sptr->snomask && snomask_given)
1272       sendto_one(sptr, rpl_str(RPL_SNOMASK), me.name, sptr->name,
1273                  sptr->snomask, sptr->snomask);
1274   }
1275
1276   return 0;
1277 }
1278
1279 /*
1280  * Build umode string for BURST command
1281  * --Run
1282  */
1283 char *umode_str(struct Client *cptr)
1284 {
1285   char* m = umodeBuf;                /* Maximum string size: "owidg\0" */
1286   int   i;
1287   int   c_flags;
1288
1289   c_flags = cptr->flags & SEND_UMODES;        /* cleaning up the original code */
1290
1291   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1292     if ( (c_flags & userModeList[i].flag))
1293       *m++ = userModeList[i].c;
1294   }
1295   *m = '\0';
1296
1297   return umodeBuf;                /* Note: static buffer, gets
1298                                    overwritten by send_umode() */
1299 }
1300
1301 /*
1302  * Send the MODE string for user (user) to connection cptr
1303  * -avalon
1304  */
1305 void send_umode(struct Client *cptr, struct Client *sptr, int old, int sendmask)
1306 {
1307   int i;
1308   int flag;
1309   char *m;
1310   int what = MODE_NULL;
1311
1312   /*
1313    * Build a string in umodeBuf to represent the change in the user's
1314    * mode between the new (sptr->flag) and 'old'.
1315    */
1316   m = umodeBuf;
1317   *m = '\0';
1318   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1319     flag = userModeList[i].flag;
1320     if (MyUser(sptr) && !(flag & sendmask))
1321       continue;
1322     if ( (flag & old) && !(sptr->flags & flag))
1323     {
1324       if (what == MODE_DEL)
1325         *m++ = userModeList[i].c;
1326       else
1327       {
1328         what = MODE_DEL;
1329         *m++ = '-';
1330         *m++ = userModeList[i].c;
1331       }
1332     }
1333     else if (!(flag & old) && (sptr->flags & flag))
1334     {
1335       if (what == MODE_ADD)
1336         *m++ = userModeList[i].c;
1337       else
1338       {
1339         what = MODE_ADD;
1340         *m++ = '+';
1341         *m++ = userModeList[i].c;
1342       }
1343     }
1344   }
1345   *m = '\0';
1346   if (*umodeBuf && cptr)
1347     sendto_one(cptr, ":%s MODE %s :%s", sptr->name, sptr->name, umodeBuf);
1348 }
1349
1350 /*
1351  * Check to see if this resembles a sno_mask.  It is if 1) there is
1352  * at least one digit and 2) The first digit occurs before the first
1353  * alphabetic character.
1354  */
1355 int is_snomask(char *word)
1356 {
1357   if (word)
1358   {
1359     for (; *word; word++)
1360       if (IsDigit(*word))
1361         return 1;
1362       else if (IsAlpha(*word))
1363         return 0;
1364   }
1365   return 0;
1366 }
1367
1368 /*
1369  * If it begins with a +, count this as an additive mask instead of just
1370  * a replacement.  If what == MODE_DEL, "+" has no special effect.
1371  */
1372 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1373 {
1374   unsigned int sno_what;
1375   unsigned int newmask;
1376   if (*arg == '+')
1377   {
1378     arg++;
1379     if (what == MODE_ADD)
1380       sno_what = SNO_ADD;
1381     else
1382       sno_what = SNO_DEL;
1383   }
1384   else if (*arg == '-')
1385   {
1386     arg++;
1387     if (what == MODE_ADD)
1388       sno_what = SNO_DEL;
1389     else
1390       sno_what = SNO_ADD;
1391   }
1392   else
1393     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1394   /* pity we don't have strtoul everywhere */
1395   newmask = (unsigned int)atoi(arg);
1396   if (sno_what == SNO_DEL)
1397     newmask = oldmask & ~newmask;
1398   else if (sno_what == SNO_ADD)
1399     newmask |= oldmask;
1400   return newmask;
1401 }
1402
1403 static void delfrom_list(struct Client *cptr, struct SLink **list)
1404 {
1405   struct SLink* tmp;
1406   struct SLink* prv = NULL;
1407
1408   for (tmp = *list; tmp; tmp = tmp->next) {
1409     if (tmp->value.cptr == cptr) {
1410       if (prv)
1411         prv->next = tmp->next;
1412       else
1413         *list = tmp->next;
1414       free_link(tmp);
1415       break;
1416     }
1417     prv = tmp;
1418   }
1419 }
1420
1421 /*
1422  * This function sets a Client's server notices mask, according to
1423  * the parameter 'what'.  This could be even faster, but the code
1424  * gets mighty hard to read :)
1425  */
1426 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1427 {
1428   unsigned int oldmask, diffmask;        /* unsigned please */
1429   int i;
1430   struct SLink *tmp;
1431
1432   oldmask = cptr->snomask;
1433
1434   if (what == SNO_ADD)
1435     newmask |= oldmask;
1436   else if (what == SNO_DEL)
1437     newmask = oldmask & ~newmask;
1438   else if (what != SNO_SET)        /* absolute set, no math needed */
1439     sendto_ops("setsnomask called with %d ?!", what);
1440
1441   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1442
1443   diffmask = oldmask ^ newmask;
1444
1445   for (i = 0; diffmask >> i; i++) {
1446     if (((diffmask >> i) & 1))
1447     {
1448       if (((newmask >> i) & 1))
1449       {
1450         tmp = make_link();
1451         tmp->next = opsarray[i];
1452         tmp->value.cptr = cptr;
1453         opsarray[i] = tmp;
1454       }
1455       else
1456         /* not real portable :( */
1457         delfrom_list(cptr, &opsarray[i]);
1458     }
1459   }
1460   cptr->snomask = newmask;
1461 }
1462
1463 /*
1464  * is_silenced : Does the actual check wether sptr is allowed
1465  *               to send a message to acptr.
1466  *               Both must be registered persons.
1467  * If sptr is silenced by acptr, his message should not be propagated,
1468  * but more over, if this is detected on a server not local to sptr
1469  * the SILENCE mask is sent upstream.
1470  */
1471 int is_silenced(struct Client *sptr, struct Client *acptr)
1472 {
1473   struct SLink *lp;
1474   struct User *user;
1475   static char sender[HOSTLEN + NICKLEN + USERLEN + 5];
1476   static char senderip[16 + NICKLEN + USERLEN + 5];
1477
1478   if (!(acptr->user) || !(lp = acptr->user->silence) || !(user = sptr->user))
1479     return 0;
1480   sprintf_irc(sender, "%s!%s@%s", sptr->name, user->username, user->host);
1481   sprintf_irc(senderip, "%s!%s@%s", sptr->name, user->username,
1482               ircd_ntoa((const char*) &sptr->ip));
1483   for (; lp; lp = lp->next)
1484   {
1485     if ((!(lp->flags & CHFL_SILENCE_IPMASK) && !match(lp->value.cp, sender)) ||
1486         ((lp->flags & CHFL_SILENCE_IPMASK) && !match(lp->value.cp, senderip)))
1487     {
1488       if (!MyConnect(sptr))
1489       {
1490         if (Protocol(sptr->from) < 10)
1491           sendto_one(sptr->from, ":%s SILENCE %s %s", acptr->name,
1492               sptr->name, lp->value.cp);
1493         else
1494           sendto_one(sptr->from, ":%s SILENCE %s%s %s", acptr->name,
1495               NumNick(sptr), lp->value.cp);
1496       }
1497       return 1;
1498     }
1499   }
1500   return 0;
1501 }
1502
1503 /*
1504  * del_silence
1505  *
1506  * Removes all silence masks from the list of sptr that fall within `mask'
1507  * Returns -1 if none where found, 0 otherwise.
1508  */
1509 int del_silence(struct Client *sptr, char *mask)
1510 {
1511   struct SLink **lp;
1512   struct SLink *tmp;
1513   int ret = -1;
1514
1515   for (lp = &sptr->user->silence; *lp;) {
1516     if (!mmatch(mask, (*lp)->value.cp))
1517     {
1518       tmp = *lp;
1519       *lp = tmp->next;
1520       MyFree(tmp->value.cp);
1521       free_link(tmp);
1522       ret = 0;
1523     }
1524     else
1525       lp = &(*lp)->next;
1526   }
1527   return ret;
1528 }
1529
1530 int add_silence(struct Client* sptr, const char* mask)
1531 {
1532   struct SLink *lp, **lpp;
1533   int cnt = 0, len = strlen(mask);
1534   char *ip_start;
1535
1536   for (lpp = &sptr->user->silence, lp = *lpp; lp;)
1537   {
1538     if (0 == ircd_strcmp(mask, lp->value.cp))
1539       return -1;
1540     if (!mmatch(mask, lp->value.cp))
1541     {
1542       struct SLink *tmp = lp;
1543       *lpp = lp = lp->next;
1544       MyFree(tmp->value.cp);
1545       free_link(tmp);
1546       continue;
1547     }
1548     if (MyUser(sptr))
1549     {
1550       len += strlen(lp->value.cp);
1551       if ((len > MAXSILELENGTH) || (++cnt >= MAXSILES))
1552       {
1553         sendto_one(sptr, err_str(ERR_SILELISTFULL), me.name, sptr->name, mask);
1554         return -1;
1555       }
1556       else if (!mmatch(lp->value.cp, mask))
1557         return -1;
1558     }
1559     lpp = &lp->next;
1560     lp = *lpp;
1561   }
1562   lp = make_link();
1563   memset(lp, 0, sizeof(struct SLink));
1564   lp->next = sptr->user->silence;
1565   lp->value.cp = (char*) MyMalloc(strlen(mask) + 1);
1566   assert(0 != lp->value.cp);
1567   strcpy(lp->value.cp, mask);
1568   if ((ip_start = strrchr(mask, '@')) && check_if_ipmask(ip_start + 1))
1569     lp->flags = CHFL_SILENCE_IPMASK;
1570   sptr->user->silence = lp;
1571   return 0;
1572 }
1573