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