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