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