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