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