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