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