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