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