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