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