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