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