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