Author: Kev <klmitch@mit.edu>
[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 "supported.h"
62 #include "sys.h"
63 #include "userload.h"
64 #include "version.h"
65 #include "whowas.h"
66
67 #include "handlers.h" /* m_motd and m_lusers */
68
69 /* #include <assert.h> -- Now using assert in ircd_log.h */
70 #include <fcntl.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <sys/stat.h>
75
76 /** Count of allocated User structures. */
77 static int userCount = 0;
78
79 /** Makes sure that \a cptr has a User information block.
80  * If cli_user(cptr) != NULL, does nothing.
81  * @param[in] cptr Client to attach User struct to.
82  * @return User struct associated with \a cptr.
83  */
84 struct User *make_user(struct Client *cptr)
85 {
86   assert(0 != cptr);
87
88   if (!cli_user(cptr)) {
89     cli_user(cptr) = (struct User*) MyMalloc(sizeof(struct User));
90     assert(0 != cli_user(cptr));
91
92     /* All variables are 0 by default */
93     memset(cli_user(cptr), 0, sizeof(struct User));
94 #ifdef  DEBUGMODE
95     ++userCount;
96 #endif
97     cli_user(cptr)->refcnt = 1;
98   }
99   return cli_user(cptr);
100 }
101
102 /** Dereference \a user.
103  * User structures are reference-counted; if the refcount of \a user
104  * becomes zero, free it.
105  * @param[in] user User to dereference.
106  */
107 void free_user(struct User* user)
108 {
109   assert(0 != user);
110   assert(0 < user->refcnt);
111
112   if (--user->refcnt == 0) {
113     if (user->away)
114       MyFree(user->away);
115     /*
116      * sanity check
117      */
118     assert(0 == user->joined);
119     assert(0 == user->invited);
120     assert(0 == user->channel);
121
122     MyFree(user);
123 #ifdef  DEBUGMODE
124     --userCount;
125 #endif
126   }
127 }
128
129 /** Find number of User structs allocated and memory used by them.
130  * @param[out] count_out Receives number of User structs allocated.
131  * @param[out] bytes_out Receives number of bytes used by User structs.
132  */
133 void user_count_memory(size_t* count_out, size_t* bytes_out)
134 {
135   assert(0 != count_out);
136   assert(0 != bytes_out);
137   *count_out = userCount;
138   *bytes_out = userCount * sizeof(struct User);
139 }
140
141
142 /** Find the next client (starting at \a next) with a name that matches \a ch.
143  * Normal usage loop is:
144  * for (x = client; x = next_client(x,mask); x = x->next)
145  *     HandleMatchingClient;
146  *
147  * @param[in] next First client to check.
148  * @param[in] ch Name mask to check against.
149  * @return Next matching client found, or NULL if none.
150  */
151 struct Client *next_client(struct Client *next, const char* ch)
152 {
153   struct Client *tmp = next;
154
155   if (!tmp)
156     return NULL;
157
158   next = FindClient(ch);
159   next = next ? next : tmp;
160   if (cli_prev(tmp) == next)
161     return NULL;
162   if (next != tmp)
163     return next;
164   for (; next; next = cli_next(next))
165     if (!match(ch, cli_name(next)))
166       break;
167   return next;
168 }
169
170 /** Find the destination server for a command, and forward it if that is not us.
171  *
172  * \a server may be a nickname, server name, server mask (if \a from
173  * is a local user) or server numnick (if \a is a server or remote
174  * user).
175  *
176  * @param[in] from Client that sent the command to us.
177  * @param[in] cmd Long-form command text.
178  * @param[in] tok Token-form command text.
179  * @param[in] one Client that originated the command (ignored).
180  * @param[in] MustBeOper If non-zero and \a from is not an operator, return HUNTED_NOSUCH.
181  * @param[in] pattern Format string of arguments to command.
182  * @param[in] server Index of target name or mask in \a parv.
183  * @param[in] parc Number of valid elements in \a parv (must be less than 9).
184  * @param[in] parv Array of arguments to command.
185  * @return One of HUNTED_ISME, HUNTED_NOSUCH or HUNTED_PASS.
186  */
187 int hunt_server_cmd(struct Client *from, const char *cmd, const char *tok,
188                     struct Client *one, int MustBeOper, const char *pattern,
189                     int server, int parc, char *parv[])
190 {
191   struct Client *acptr;
192   char *to;
193
194   /* Assume it's me, if no server or an unregistered client */
195   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
196     return (HUNTED_ISME);
197
198   if (MustBeOper && !IsPrivileged(from))
199   {
200     send_reply(from, ERR_NOPRIVILEGES);
201     return HUNTED_NOSUCH;
202   }
203
204   /* Make sure it's a server */
205   if (MyUser(from)) {
206     /* Make sure it's a server */
207     if (!strchr(to, '*')) {
208       if (0 == (acptr = FindClient(to))) {
209         send_reply(from, ERR_NOSUCHSERVER, to);
210         return HUNTED_NOSUCH;
211       }
212
213       if (cli_user(acptr))
214         acptr = cli_user(acptr)->server;
215     } else if (!(acptr = find_match_server(to))) {
216       send_reply(from, ERR_NOSUCHSERVER, to);
217       return (HUNTED_NOSUCH);
218     }
219   } else if (!(acptr = FindNServer(to))) {
220     send_reply(from, SND_EXPLICIT | ERR_NOSUCHSERVER, "* :Server has disconnected");
221     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
222   }
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 /** Find the destination server for a command, and forward it (as a
243  * high-priority command) if that is not us.
244  *
245  * \a server may be a nickname, server name, server mask (if \a from
246  * is a local user) or server numnick (if \a is a server or remote
247  * user).
248  * Unlike hunt_server_cmd(), this appends the message to the
249  * high-priority message queue for the destination server.
250  *
251  * @param[in] from Client that sent the command to us.
252  * @param[in] cmd Long-form command text.
253  * @param[in] tok Token-form command text.
254  * @param[in] one Client that originated the command (ignored).
255  * @param[in] MustBeOper If non-zero and \a from is not an operator, return HUNTED_NOSUCH.
256  * @param[in] pattern Format string of arguments to command.
257  * @param[in] server Index of target name or mask in \a parv.
258  * @param[in] parc Number of valid elements in \a parv (must be less than 9).
259  * @param[in] parv Array of arguments to command.
260  * @return One of HUNTED_ISME, HUNTED_NOSUCH or HUNTED_PASS.
261  */
262 int hunt_server_prio_cmd(struct Client *from, const char *cmd, const char *tok,
263                          struct Client *one, int MustBeOper,
264                          const char *pattern, int server, int parc,
265                          char *parv[])
266 {
267   struct Client *acptr;
268   char *to;
269
270   /* Assume it's me, if no server or an unregistered client */
271   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
272     return (HUNTED_ISME);
273
274   /* Make sure it's a server */
275   if (MyUser(from)) {
276     /* Make sure it's a server */
277     if (!strchr(to, '*')) {
278       if (0 == (acptr = FindClient(to))) {
279         send_reply(from, ERR_NOSUCHSERVER, to);
280         return HUNTED_NOSUCH;
281       }
282
283       if (cli_user(acptr))
284         acptr = cli_user(acptr)->server;
285     } else if (!(acptr = find_match_server(to))) {
286       send_reply(from, ERR_NOSUCHSERVER, to);
287       return (HUNTED_NOSUCH);
288     }
289   } else if (!(acptr = FindNServer(to)))
290     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
291
292   if (IsMe(acptr))
293     return (HUNTED_ISME);
294
295   if (MustBeOper && !IsPrivileged(from)) {
296     send_reply(from, ERR_NOPRIVILEGES);
297     return HUNTED_NOSUCH;
298   }
299
300   /* assert(!IsServer(from)); SETTIME to particular destinations permitted */
301
302   parv[server] = (char *) acptr; /* HACK! HACK! HACK! ARGH! */
303
304   sendcmdto_prio_one(from, cmd, tok, acptr, pattern, parv[1], parv[2], parv[3],
305                      parv[4], parv[5], parv[6], parv[7], parv[8]);
306
307   return (HUNTED_PASS);
308 }
309
310
311 /** Copy a cleaned-up version of a username.
312  * Replace all instances of '~' and "invalid" username characters
313  * (!isIrcUi()) with underscores, truncating at USERLEN or the first
314  * control character.  \a dest and \a source may be the same buffer.
315  * @param[out] dest Destination buffer.
316  * @param[in] source Source buffer.
317  * @param[in] tilde If non-zero, prepend a '~' to \a dest.
318  */
319 static char *clean_user_id(char *dest, char *source, int tilde)
320 {
321   char ch;
322   char *d = dest;
323   char *s = source;
324   int rlen = USERLEN;
325
326   ch = *s++;                        /* Store first character to copy: */
327   if (tilde)
328   {
329     *d++ = '~';                        /* If `dest' == `source', then this overwrites `ch' */
330     --rlen;
331   }
332   while (ch && !IsCntrl(ch) && rlen--)
333   {
334     char nch = *s++;        /* Store next character to copy */
335     *d++ = IsUserChar(ch) ? ch : '_';        /* This possibly overwrites it */
336     if (nch == '~')
337       ch = '_';
338     else
339       ch = nch;
340   }
341   *d = 0;
342   return dest;
343 }
344
345 /*
346  * register_user
347  *
348  * This function is called when both NICK and USER messages
349  * have been accepted for the client, in whatever order. Only
350  * after this the USER message is propagated.
351  *
352  * NICK's must be propagated at once when received, although
353  * it would be better to delay them too until full info is
354  * available. Doing it is not so simple though, would have
355  * to implement the following:
356  *
357  * 1) user telnets in and gives only "NICK foobar" and waits
358  * 2) another user far away logs in normally with the nick
359  *    "foobar" (quite legal, as this server didn't propagate it).
360  * 3) now this server gets nick "foobar" from outside, but
361  *    has already the same defined locally. Current server
362  *    would just issue "KILL foobar" to clean out dups. But,
363  *    this is not fair. It should actually request another
364  *    nick from local user or kill him/her...
365  */
366 /** Finish registering a user who has sent both NICK and USER.
367  * For local connections, possibly check IAuth; make sure there is a
368  * matching Client config block; clean the username field; check
369  * K/k-lines; check for "hacked" looking usernames; assign a numnick;
370  * and send greeting (WELCOME, ISUPPORT, MOTD, etc).
371  * For all connections, update the invisible user and operator counts;
372  * run IPcheck against their address; and forward the NICK.
373  *
374  * @param[in] cptr Client who introduced the user.
375  * @param[in,out] sptr Client who has been fully introduced.
376  * @param[in] nick Client's new nickname.
377  * @param[in] username Client's username.
378  * @return Zero or CPTR_KILLED.
379  */
380 int register_user(struct Client *cptr, struct Client *sptr,
381                   const char *nick, char *username)
382 {
383   struct ConfItem* aconf;
384   char*            parv[4];
385   char*            tmpstr;
386   char*            tmpstr2;
387   char             c = 0;    /* not alphanum */
388   char             d = 'a';  /* not a digit */
389   short            upper = 0;
390   short            lower = 0;
391   short            pos = 0;
392   short            leadcaps = 0;
393   short            other = 0;
394   short            digits = 0;
395   short            badid = 0;
396   short            digitgroups = 0;
397   struct User*     user = cli_user(sptr);
398   int              killreason;
399   char             ip_base64[25];
400
401   user->last = CurrentTime;
402   parv[0] = cli_name(sptr);
403   parv[1] = parv[2] = NULL;
404
405   if (MyConnect(sptr))
406   {
407     static time_t last_too_many1;
408     static time_t last_too_many2;
409
410     assert(cptr == sptr);
411     assert(cli_unreg(sptr) == 0);
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   /* Send full IP address to IPv6-grokking servers. */
662   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
663                              FLAG_IPV6, FLAG_LAST_FLAG,
664                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
665                              nick, cli_hopcount(sptr) + 1, cli_lastnick(sptr),
666                              user->username, user->realhost,
667                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
668                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 1),
669                              NumNick(sptr), cli_info(sptr));
670   /* Send fake IPv6 addresses to pre-IPv6 servers. */
671   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
672                              FLAG_LAST_FLAG, FLAG_IPV6,
673                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
674                              nick, cli_hopcount(sptr) + 1, cli_lastnick(sptr),
675                              user->username, user->realhost,
676                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
677                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 0),
678                              NumNick(sptr), cli_info(sptr));
679
680   /* Send server notice mask to client */
681   if (MyUser(sptr) && (cli_snomask(sptr) != SNO_DEFAULT) && HasFlag(sptr, FLAG_SERVNOTICE))
682     send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
683
684   return 0;
685 }
686
687 /** List of user mode characters. */
688 static const struct UserMode {
689   unsigned int flag; /**< User mode constant. */
690   char         c;    /**< Character corresponding to the mode. */
691 } userModeList[] = {
692   { FLAG_OPER,        'o' },
693   { FLAG_LOCOP,       'O' },
694   { FLAG_INVISIBLE,   'i' },
695   { FLAG_WALLOP,      'w' },
696   { FLAG_SERVNOTICE,  's' },
697   { FLAG_DEAF,        'd' },
698   { FLAG_CHSERV,      'k' },
699   { FLAG_DEBUG,       'g' },
700   { FLAG_ACCOUNT,     'r' },
701   { FLAG_HIDDENHOST,  'x' }
702 };
703
704 /** Length of #userModeList. */
705 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
706
707 /*
708  * XXX - find a way to get rid of this
709  */
710 /** Nasty global buffer used for communications with umode_str() and others. */
711 static char umodeBuf[BUFSIZE];
712
713 /** Try to set a user's nickname.
714  * If \a sptr is a server, the client is being introduced for the first time.
715  * @param[in] cptr Client to set nickname.
716  * @param[in] sptr Client sending the NICK.
717  * @param[in] nick New nickname.
718  * @param[in] parc Number of arguments to NICK.
719  * @param[in] parv Argument list to NICK.
720  * @return CPTR_KILLED if \a cptr was killed, else 0.
721  */
722 int set_nick_name(struct Client* cptr, struct Client* sptr,
723                   const char* nick, int parc, char* parv[])
724 {
725   if (IsServer(sptr)) {
726     int   i;
727     const char* account = 0;
728     const char* p;
729
730     /*
731      * A server introducing a new client, change source
732      */
733     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
734     assert(0 != new_client);
735
736     cli_hopcount(new_client) = atoi(parv[2]);
737     cli_lastnick(new_client) = atoi(parv[3]);
738     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+')
739     {
740       for (p = parv[6] + 1; *p; p++)
741       {
742         for (i = 0; i < USERMODELIST_SIZE; ++i)
743         {
744           if (userModeList[i].c == *p)
745           {
746             SetFlag(new_client, userModeList[i].flag);
747             if (userModeList[i].flag == FLAG_ACCOUNT)
748               account = parv[7];
749             break;
750           }
751         }
752       }
753     }
754     client_set_privs(new_client, NULL); /* set privs on user */
755     /*
756      * Set new nick name.
757      */
758     strcpy(cli_name(new_client), nick);
759     cli_user(new_client) = make_user(new_client);
760     cli_user(new_client)->server = sptr;
761     SetRemoteNumNick(new_client, parv[parc - 2]);
762     /*
763      * IP# of remote client
764      */
765     base64toip(parv[parc - 3], &cli_ip(new_client));
766
767     add_client_to_list(new_client);
768     hAddClient(new_client);
769
770     cli_serv(sptr)->ghost = 0;        /* :server NICK means end of net.burst */
771     ircd_strncpy(cli_username(new_client), parv[4], USERLEN);
772     ircd_strncpy(cli_user(new_client)->host, parv[5], HOSTLEN);
773     ircd_strncpy(cli_user(new_client)->realhost, parv[5], HOSTLEN);
774     ircd_strncpy(cli_info(new_client), parv[parc - 1], REALLEN);
775     if (account) {
776       int len = ACCOUNTLEN;
777       if ((p = strchr(account, ':'))) {
778         len = (p++) - account;
779         cli_user(new_client)->acc_create = atoi(p);
780         Debug((DEBUG_DEBUG, "Received timestamped account in user mode; "
781                "account \"%s\", timestamp %Tu", account,
782                cli_user(new_client)->acc_create));
783       }
784       ircd_strncpy(cli_user(new_client)->account, account, len);
785     }
786     if (HasHiddenHost(new_client))
787       ircd_snprintf(0, cli_user(new_client)->host, HOSTLEN, "%s.%s",
788         account, feature_str(FEAT_HIDDEN_HOST));
789
790     return register_user(cptr, new_client, cli_name(new_client), parv[4]);
791   }
792   else if ((cli_name(sptr))[0]) {
793     /*
794      * Client changing its nick
795      *
796      * If the client belongs to me, then check to see
797      * if client is on any channels where it is currently
798      * banned.  If so, do not allow the nick change to occur.
799      */
800     if (MyUser(sptr)) {
801       const char* channel_name;
802       struct Membership *member;
803       if ((channel_name = find_no_nickchange_channel(sptr))) {
804         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
805       }
806       /*
807        * Refuse nick change if the last nick change was less
808        * then 30 seconds ago. This is intended to get rid of
809        * clone bots doing NICK FLOOD. -SeKs
810        * If someone didn't change their nick for more then 60 seconds
811        * however, allow to do two nick changes immediately after another
812        * before limiting the nick flood. -Run
813        */
814       if (CurrentTime < cli_nextnick(cptr))
815       {
816         cli_nextnick(cptr) += 2;
817         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
818                    cli_nextnick(cptr) - CurrentTime);
819         /* Send error message */
820         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cli_name(cptr));
821         /* bounce NICK to user */
822         return 0;                /* ignore nick change! */
823       }
824       else {
825         /* Limit total to 1 change per NICK_DELAY seconds: */
826         cli_nextnick(cptr) += NICK_DELAY;
827         /* However allow _maximal_ 1 extra consecutive nick change: */
828         if (cli_nextnick(cptr) < CurrentTime)
829           cli_nextnick(cptr) = CurrentTime;
830       }
831       /* Invalidate all bans against the user so we check them again */
832       for (member = (cli_user(cptr))->channel; member;
833            member = member->next_channel)
834         ClearBanValid(member);
835     }
836     /*
837      * Also set 'lastnick' to current time, if changed.
838      */
839     if (0 != ircd_strcmp(parv[0], nick))
840       cli_lastnick(sptr) = (sptr == cptr) ? TStime() : atoi(parv[2]);
841
842     /*
843      * Client just changing his/her nick. If he/she is
844      * on a channel, send note of change to all clients
845      * on that channel. Propagate notice to other servers.
846      */
847     if (IsUser(sptr)) {
848       sendcmdto_common_channels_butone(sptr, CMD_NICK, NULL, ":%s", nick);
849       add_history(sptr, 1);
850       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
851                             cli_lastnick(sptr));
852     }
853     else
854       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
855
856     if ((cli_name(sptr))[0])
857       hRemClient(sptr);
858     strcpy(cli_name(sptr), nick);
859     hAddClient(sptr);
860   }
861   else {
862     /* Local client setting NICK the first time */
863
864     strcpy(cli_name(sptr), nick);
865     if (!cli_user(sptr)) {
866       cli_user(sptr) = make_user(sptr);
867       cli_user(sptr)->server = &me;
868     }
869     hAddClient(sptr);
870
871     cli_unreg(sptr) &= ~CLIREG_NICK; /* nickname now set */
872
873     /*
874      * If the client hasn't gotten a cookie-ping yet,
875      * choose a cookie and send it. -record!jegelhof@cloud9.net
876      */
877     if (!cli_cookie(sptr)) {
878       do {
879         cli_cookie(sptr) = (ircrandom() & 0x7fffffff);
880       } while (!cli_cookie(sptr));
881       sendrawto_one(cptr, MSG_PING " :%u", cli_cookie(sptr));
882     }
883     else if (!cli_unreg(sptr)) {
884       /*
885        * USER and PONG already received, now we have NICK.
886        * register_user may reject the client and call exit_client
887        * for it - must test this and exit m_nick too !
888        */
889       cli_lastnick(sptr) = TStime();        /* Always local client */
890       if (register_user(cptr, sptr, nick, cli_user(sptr)->username) == CPTR_KILLED)
891         return CPTR_KILLED;
892     }
893   }
894   return 0;
895 }
896
897 /** Calculate the hash value for a target.
898  * @param[in] target Pointer to target, cast to unsigned int.
899  * @return Hash value constructed from the pointer.
900  */
901 static unsigned char hash_target(unsigned int target)
902 {
903   return (unsigned char) (target >> 16) ^ (target >> 8);
904 }
905
906 /** Records \a target as a recent target for \a sptr.
907  * @param[in] sptr User who has sent to a new target.
908  * @param[in] target Target to add.
909  */
910 void
911 add_target(struct Client *sptr, void *target)
912 {
913   /* Ok, this shouldn't work esp on alpha
914   */
915   unsigned char  hash = hash_target((unsigned long) target);
916   unsigned char* targets;
917   int            i;
918   assert(0 != sptr);
919   assert(cli_local(sptr));
920
921   targets = cli_targets(sptr);
922
923   /* 
924    * Already in table?
925    */
926   for (i = 0; i < MAXTARGETS; ++i) {
927     if (targets[i] == hash)
928       return;
929   }
930   /*
931    * New target
932    */
933   memmove(&targets[RESERVEDTARGETS + 1],
934           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
935   targets[RESERVEDTARGETS] = hash;
936 }
937
938 /** Check whether \a sptr can send to or join \a target yet.
939  * @param[in] sptr User trying to join a channel or send a message.
940  * @param[in] target Target of the join or message.
941  * @param[in] name Name of the target.
942  * @param[in] created If non-zero, trying to join a new channel.
943  * @return Non-zero if too many target changes; zero if okay to send.
944  */
945 int check_target_limit(struct Client *sptr, void *target, const char *name,
946     int created)
947 {
948   unsigned char hash = hash_target((unsigned long) target);
949   int            i;
950   unsigned char* targets;
951
952   assert(0 != sptr);
953   assert(cli_local(sptr));
954   targets = cli_targets(sptr);
955
956   /* If user is invited to channel, give him/her a free target */
957   if (IsChannelName(name) && IsInvited(sptr, target))
958     return 0;
959
960   /*
961    * Same target as last time?
962    */
963   if (targets[0] == hash)
964     return 0;
965   for (i = 1; i < MAXTARGETS; ++i) {
966     if (targets[i] == hash) {
967       memmove(&targets[1], &targets[0], i);
968       targets[0] = hash;
969       return 0;
970     }
971   }
972   /*
973    * New target
974    */
975   if (!created) {
976     if (CurrentTime < cli_nexttarget(sptr)) {
977       if (cli_nexttarget(sptr) - CurrentTime < TARGET_DELAY + 8) {
978         /*
979          * No server flooding
980          */
981         cli_nexttarget(sptr) += 2;
982         send_reply(sptr, ERR_TARGETTOOFAST, name,
983                    cli_nexttarget(sptr) - CurrentTime);
984       }
985       return 1;
986     }
987     else {
988       cli_nexttarget(sptr) += TARGET_DELAY;
989       if (cli_nexttarget(sptr) < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
990         cli_nexttarget(sptr) = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
991     }
992   }
993   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
994   targets[0] = hash;
995   return 0;
996 }
997
998 /** Allows a channel operator to avoid target change checks when
999  * sending messages to users on their channel.
1000  * @param[in] source User sending the message.
1001  * @param[in] nick Destination of the message.
1002  * @param[in] channel Name of channel being sent to.
1003  * @param[in] text Message to send.
1004  * @param[in] is_notice If non-zero, use CNOTICE instead of CPRIVMSG.
1005  */
1006 /* Added 971023 by Run. */
1007 int whisper(struct Client* source, const char* nick, const char* channel,
1008             const char* text, int is_notice)
1009 {
1010   struct Client*     dest;
1011   struct Channel*    chptr;
1012   struct Membership* membership;
1013
1014   assert(0 != source);
1015   assert(0 != nick);
1016   assert(0 != channel);
1017   assert(MyUser(source));
1018
1019   if (!(dest = FindUser(nick))) {
1020     return send_reply(source, ERR_NOSUCHNICK, nick);
1021   }
1022   if (!(chptr = FindChannel(channel))) {
1023     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
1024   }
1025   /*
1026    * compare both users channel lists, instead of the channels user list
1027    * since the link is the same, this should be a little faster for channels
1028    * with a lot of users
1029    */
1030   for (membership = cli_user(source)->channel; membership; membership = membership->next_channel) {
1031     if (chptr == membership->channel)
1032       break;
1033   }
1034   if (0 == membership) {
1035     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
1036   }
1037   if (!IsVoicedOrOpped(membership)) {
1038     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
1039   }
1040   /*
1041    * lookup channel in destination
1042    */
1043   assert(0 != cli_user(dest));
1044   for (membership = cli_user(dest)->channel; membership; membership = membership->next_channel) {
1045     if (chptr == membership->channel)
1046       break;
1047   }
1048   if (0 == membership || IsZombie(membership)) {
1049     return send_reply(source, ERR_USERNOTINCHANNEL, cli_name(dest), chptr->chname);
1050   }
1051   if (is_silenced(source, dest))
1052     return 0;
1053           
1054   if (cli_user(dest)->away)
1055     send_reply(source, RPL_AWAY, cli_name(dest), cli_user(dest)->away);
1056   if (is_notice)
1057     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
1058   else
1059     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
1060   return 0;
1061 }
1062
1063
1064 /** Send a user mode change for \a cptr to neighboring servers.
1065  * @param[in] cptr User whose mode is changing.
1066  * @param[in] sptr Client who sent us the mode change message.
1067  * @param[in] old Prior set of user flags.
1068  * @param[in] prop If non-zero, also include FLAG_OPER.
1069  */
1070 void send_umode_out(struct Client *cptr, struct Client *sptr,
1071                     struct Flags *old, int prop)
1072 {
1073   int i;
1074   struct Client *acptr;
1075
1076   send_umode(NULL, sptr, old, prop ? SEND_UMODES : SEND_UMODES_BUT_OPER);
1077
1078   for (i = HighestFd; i >= 0; i--)
1079   {
1080     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
1081         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
1082       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", cli_name(sptr), umodeBuf);
1083   }
1084   if (cptr && MyUser(cptr))
1085     send_umode(cptr, sptr, old, ALL_UMODES);
1086 }
1087
1088
1089 /** Call \a fmt for each Client named in \a names.
1090  * @param[in] sptr Client requesting information.
1091  * @param[in] names Space-delimited list of nicknames.
1092  * @param[in] rpl Base reply string for messages.
1093  * @param[in] fmt Formatting callback function.
1094  */
1095 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
1096 {
1097   char*          name;
1098   char*          p = 0;
1099   int            arg_count = 0;
1100   int            users_found = 0;
1101   struct Client* acptr;
1102   struct MsgBuf* mb;
1103
1104   assert(0 != sptr);
1105   assert(0 != names);
1106   assert(0 != fmt);
1107
1108   mb = msgq_make(sptr, rpl_str(rpl), cli_name(&me), cli_name(sptr));
1109
1110   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
1111     if ((acptr = FindUser(name))) {
1112       if (users_found++)
1113         msgq_append(0, mb, " ");
1114       (*fmt)(acptr, sptr, mb);
1115     }
1116     if (5 == ++arg_count)
1117       break;
1118   }
1119   send_buffer(sptr, mb, 0);
1120   msgq_clean(mb);
1121 }
1122
1123 /** Set \a flag on \a cptr and possibly hide the client's hostmask.
1124  * @param[in,out] cptr User who is getting a new flag.
1125  * @param[in] flag Some flag that affects host-hiding (FLAG_HIDDENHOST, FLAG_ACCOUNT).
1126  * @return Zero.
1127  */
1128 int
1129 hide_hostmask(struct Client *cptr, unsigned int flag)
1130 {
1131   struct Membership *chan;
1132
1133   switch (flag) {
1134   case FLAG_HIDDENHOST:
1135     /* Local users cannot set +x unless FEAT_HOST_HIDING is true. */
1136     if (MyConnect(cptr) && !feature_bool(FEAT_HOST_HIDING))
1137       return 0;
1138     break;
1139   case FLAG_ACCOUNT:
1140     /* Invalidate all bans against the user so we check them again */
1141     for (chan = (cli_user(cptr))->channel; chan;
1142          chan = chan->next_channel)
1143       ClearBanValid(chan);
1144     break;
1145   default:
1146     return 0;
1147   }
1148
1149   SetFlag(cptr, flag);
1150   if (!HasFlag(cptr, FLAG_HIDDENHOST) || !HasFlag(cptr, FLAG_ACCOUNT))
1151     return 0;
1152
1153   sendcmdto_common_channels_butone(cptr, CMD_QUIT, cptr, ":Registered");
1154   ircd_snprintf(0, cli_user(cptr)->host, HOSTLEN, "%s.%s",
1155                 cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
1156
1157   /* ok, the client is now fully hidden, so let them know -- hikari */
1158   if (MyConnect(cptr))
1159    send_reply(cptr, RPL_HOSTHIDDEN, cli_user(cptr)->host);
1160
1161   /*
1162    * Go through all channels the client was on, rejoin him
1163    * and set the modes, if any
1164    */
1165   for (chan = cli_user(cptr)->channel; chan; chan = chan->next_channel)
1166   {
1167     if (IsZombie(chan))
1168       continue;
1169     /* Send a JOIN unless the user's join has been delayed. */
1170     if (!IsDelayedJoin(chan))
1171       sendcmdto_channel_butserv_butone(cptr, CMD_JOIN, chan->channel, cptr, 0,
1172                                          "%H", chan->channel);
1173     if (IsChanOp(chan) && HasVoice(chan))
1174       sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan->channel, cptr, 0,
1175                                        "%H +ov %C %C", chan->channel, cptr,
1176                                        cptr);
1177     else if (IsChanOp(chan) || HasVoice(chan))
1178       sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan->channel, cptr, 0,
1179         "%H +%c %C", chan->channel, IsChanOp(chan) ? 'o' : 'v', cptr);
1180   }
1181   return 0;
1182 }
1183
1184 /** Set a user's mode.  This function checks that \a cptr is trying to
1185  * set his own mode, prevents local users from setting inappropriate
1186  * modes through this function, and applies any other side effects of
1187  * a successful mode change.
1188  *
1189  * @param[in,out] cptr User setting someone's mode.
1190  * @param[in] sptr Client who sent the mode change message.
1191  * @param[in] parc Number of parameters in \a parv.
1192  * @param[in] parv Parameters to MODE.
1193  * @return Zero.
1194  */
1195 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1196 {
1197   char** p;
1198   char*  m;
1199   struct Client *acptr;
1200   int what;
1201   int i;
1202   struct Flags setflags;
1203   unsigned int tmpmask = 0;
1204   int snomask_given = 0;
1205   char buf[BUFSIZE];
1206   int prop = 0;
1207   int do_host_hiding = 0;
1208
1209   what = MODE_ADD;
1210
1211   if (parc < 2)
1212     return need_more_params(sptr, "MODE");
1213
1214   if (!(acptr = FindUser(parv[1])))
1215   {
1216     if (MyConnect(sptr))
1217       send_reply(sptr, ERR_NOSUCHCHANNEL, parv[1]);
1218     return 0;
1219   }
1220
1221   if (IsServer(sptr) || sptr != acptr)
1222   {
1223     if (IsServer(cptr))
1224       sendwallto_group_butone(&me, WALL_WALLOPS, 0, 
1225                             "MODE for User %s from %s!%s", parv[1],
1226                             cli_name(cptr), cli_name(sptr));
1227     else
1228       send_reply(sptr, ERR_USERSDONTMATCH);
1229     return 0;
1230   }
1231
1232   if (parc < 3)
1233   {
1234     m = buf;
1235     *m++ = '+';
1236     for (i = 0; i < USERMODELIST_SIZE; i++)
1237     {
1238       if (HasFlag(sptr, userModeList[i].flag) &&
1239           userModeList[i].flag != FLAG_ACCOUNT)
1240         *m++ = userModeList[i].c;
1241     }
1242     *m = '\0';
1243     send_reply(sptr, RPL_UMODEIS, buf);
1244     if (HasFlag(sptr, FLAG_SERVNOTICE) && MyConnect(sptr)
1245         && cli_snomask(sptr) !=
1246         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1247       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1248     return 0;
1249   }
1250
1251   /*
1252    * find flags already set for user
1253    * why not just copy them?
1254    */
1255   setflags = cli_flags(sptr);
1256
1257   if (MyConnect(sptr))
1258     tmpmask = cli_snomask(sptr);
1259
1260   /*
1261    * parse mode change string(s)
1262    */
1263   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1264     for (m = *p; *m; m++) {
1265       switch (*m) {
1266       case '+':
1267         what = MODE_ADD;
1268         break;
1269       case '-':
1270         what = MODE_DEL;
1271         break;
1272       case 's':
1273         if (*(p + 1) && is_snomask(*(p + 1))) {
1274           snomask_given = 1;
1275           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1276           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1277         }
1278         else
1279           tmpmask = (what == MODE_ADD) ?
1280               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1281         if (tmpmask)
1282           SetServNotice(sptr);
1283         else
1284           ClearServNotice(sptr);
1285         break;
1286       case 'w':
1287         if (what == MODE_ADD)
1288           SetWallops(sptr);
1289         else
1290           ClearWallops(sptr);
1291         break;
1292       case 'o':
1293         if (what == MODE_ADD)
1294           SetOper(sptr);
1295         else {
1296           ClrFlag(sptr, FLAG_OPER);
1297           ClrFlag(sptr, FLAG_LOCOP);
1298           if (MyConnect(sptr))
1299           {
1300             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1301             cli_handler(sptr) = CLIENT_HANDLER;
1302           }
1303         }
1304         break;
1305       case 'O':
1306         if (what == MODE_ADD)
1307           SetLocOp(sptr);
1308         else
1309         { 
1310           ClrFlag(sptr, FLAG_OPER);
1311           ClrFlag(sptr, FLAG_LOCOP);
1312           if (MyConnect(sptr))
1313           {
1314             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1315             cli_handler(sptr) = CLIENT_HANDLER;
1316           }
1317         }
1318         break;
1319       case 'i':
1320         if (what == MODE_ADD)
1321           SetInvisible(sptr);
1322         else
1323           ClearInvisible(sptr);
1324         break;
1325       case 'd':
1326         if (what == MODE_ADD)
1327           SetDeaf(sptr);
1328         else
1329           ClearDeaf(sptr);
1330         break;
1331       case 'k':
1332         if (what == MODE_ADD)
1333           SetChannelService(sptr);
1334         else
1335           ClearChannelService(sptr);
1336         break;
1337       case 'g':
1338         if (what == MODE_ADD)
1339           SetDebug(sptr);
1340         else
1341           ClearDebug(sptr);
1342         break;
1343       case 'x':
1344         if (what == MODE_ADD)
1345           do_host_hiding = 1;
1346         break;
1347       default:
1348         send_reply(sptr, ERR_UMODEUNKNOWNFLAG, *m);
1349         break;
1350       }
1351     }
1352   }
1353   /*
1354    * Evaluate rules for new user mode
1355    * Stop users making themselves operators too easily:
1356    */
1357   if (!IsServer(cptr))
1358   {
1359     if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr))
1360       ClearOper(sptr);
1361     if (!FlagHas(&setflags, FLAG_LOCOP) && IsLocOp(sptr))
1362       ClearLocOp(sptr);
1363     /*
1364      * new umode; servers can set it, local users cannot;
1365      * prevents users from /kick'ing or /mode -o'ing
1366      */
1367     if (!FlagHas(&setflags, FLAG_CHSERV))
1368       ClearChannelService(sptr);
1369     /*
1370      * only send wallops to opers
1371      */
1372     if (feature_bool(FEAT_WALLOPS_OPER_ONLY) && !IsAnOper(sptr) &&
1373         !FlagHas(&setflags, FLAG_WALLOP))
1374       ClearWallops(sptr);
1375     if (feature_bool(FEAT_HIS_SNOTICES_OPER_ONLY) && MyConnect(sptr) &&
1376         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_SERVNOTICE))
1377     {
1378       ClearServNotice(sptr);
1379       set_snomask(sptr, 0, SNO_SET);
1380     }
1381     if (feature_bool(FEAT_HIS_DEBUG_OPER_ONLY) &&
1382         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_DEBUG))
1383       ClearDebug(sptr);
1384   }
1385   if (MyConnect(sptr))
1386   {
1387     if ((FlagHas(&setflags, FLAG_OPER) || FlagHas(&setflags, FLAG_LOCOP)) &&
1388         !IsAnOper(sptr))
1389       det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPERATOR);
1390
1391     if (SendServNotice(sptr))
1392     {
1393       if (tmpmask != cli_snomask(sptr))
1394         set_snomask(sptr, tmpmask, SNO_SET);
1395       if (cli_snomask(sptr) && snomask_given)
1396         send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1397     }
1398     else
1399       set_snomask(sptr, 0, SNO_SET);
1400   }
1401   /*
1402    * Compare new flags with old flags and send string which
1403    * will cause servers to update correctly.
1404    */
1405   if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr))
1406   {
1407     /* user now oper */
1408     ++UserStats.opers;
1409     client_set_privs(sptr, NULL); /* may set propagate privilege */
1410   }
1411   /* remember propagate privilege setting */
1412   if (HasPriv(sptr, PRIV_PROPAGATE))
1413     prop = 1;
1414   if (FlagHas(&setflags, FLAG_OPER) && !IsOper(sptr))
1415   {
1416     /* user no longer oper */
1417     --UserStats.opers;
1418     client_set_privs(sptr, NULL); /* will clear propagate privilege */
1419   }
1420   if (FlagHas(&setflags, FLAG_INVISIBLE) && !IsInvisible(sptr))
1421     --UserStats.inv_clients;
1422   if (!FlagHas(&setflags, FLAG_INVISIBLE) && IsInvisible(sptr))
1423     ++UserStats.inv_clients;
1424   if (!FlagHas(&setflags, FLAG_HIDDENHOST) && do_host_hiding)
1425     hide_hostmask(sptr, FLAG_HIDDENHOST);
1426   send_umode_out(cptr, sptr, &setflags, prop);
1427
1428   return 0;
1429 }
1430
1431 /** Build a mode string to describe modes for \a cptr.
1432  * @param[in] cptr Some user.
1433  * @return Pointer to a static buffer.
1434  */
1435 char *umode_str(struct Client *cptr)
1436 {
1437   /* Maximum string size: "owidgrx\0" */
1438   char *m = umodeBuf;
1439   int i;
1440   struct Flags c_flags = cli_flags(cptr);
1441
1442   if (HasPriv(cptr, PRIV_PROPAGATE))
1443     FlagSet(&c_flags, FLAG_OPER);
1444   else
1445     FlagClr(&c_flags, FLAG_OPER);
1446
1447   for (i = 0; i < USERMODELIST_SIZE; ++i)
1448   {
1449     if (FlagHas(&c_flags, userModeList[i].flag) &&
1450         userModeList[i].flag >= FLAG_GLOBAL_UMODES)
1451       *m++ = userModeList[i].c;
1452   }
1453
1454   if (IsAccount(cptr))
1455   {
1456     char* t = cli_user(cptr)->account;
1457
1458     *m++ = ' ';
1459     while ((*m++ = *t++))
1460       ; /* Empty loop */
1461
1462     if (cli_user(cptr)->acc_create) {
1463       char nbuf[20];
1464       Debug((DEBUG_DEBUG, "Sending timestamped account in user mode for "
1465              "account \"%s\"; timestamp %Tu", cli_user(cptr)->account,
1466              cli_user(cptr)->acc_create));
1467       ircd_snprintf(0, t = nbuf, sizeof(nbuf), ":%Tu",
1468                     cli_user(cptr)->acc_create);
1469       m--; /* back up over previous nul-termination */
1470       while ((*m++ = *t++))
1471         ; /* Empty loop */
1472     }
1473   }
1474
1475   *m = '\0';
1476
1477   return umodeBuf;                /* Note: static buffer, gets
1478                                    overwritten by send_umode() */
1479 }
1480
1481 /** Send a mode change string for \a sptr to \a cptr.
1482  * @param[in] cptr Destination of mode change message.
1483  * @param[in] sptr User whose mode has changed.
1484  * @param[in] old Pre-change set of modes for \a sptr.
1485  * @param[in] sendset One of ALL_UMODES, SEND_UMODES_BUT_OPER,
1486  * SEND_UMODES, to select which changed user modes to send.
1487  */
1488 void send_umode(struct Client *cptr, struct Client *sptr, struct Flags *old,
1489                 int sendset)
1490 {
1491   int i;
1492   int flag;
1493   char *m;
1494   int what = MODE_NULL;
1495
1496   /*
1497    * Build a string in umodeBuf to represent the change in the user's
1498    * mode between the new (cli_flags(sptr)) and 'old', but skipping
1499    * the modes indicated by sendset.
1500    */
1501   m = umodeBuf;
1502   *m = '\0';
1503   for (i = 0; i < USERMODELIST_SIZE; ++i)
1504   {
1505     flag = userModeList[i].flag;
1506     if (FlagHas(old, flag)
1507         == HasFlag(sptr, flag))
1508       continue;
1509     switch (sendset)
1510     {
1511     case ALL_UMODES:
1512       break;
1513     case SEND_UMODES_BUT_OPER:
1514       if (flag == FLAG_OPER)
1515         continue;
1516       /* and fall through */
1517     case SEND_UMODES:
1518       if (flag < FLAG_GLOBAL_UMODES)
1519         continue;
1520       break;      
1521     }
1522     if (FlagHas(old, flag))
1523     {
1524       if (what == MODE_DEL)
1525         *m++ = userModeList[i].c;
1526       else
1527       {
1528         what = MODE_DEL;
1529         *m++ = '-';
1530         *m++ = userModeList[i].c;
1531       }
1532     }
1533     else /* !FlagHas(old, flag) */
1534     {
1535       if (what == MODE_ADD)
1536         *m++ = userModeList[i].c;
1537       else
1538       {
1539         what = MODE_ADD;
1540         *m++ = '+';
1541         *m++ = userModeList[i].c;
1542       }
1543     }
1544   }
1545   *m = '\0';
1546   if (*umodeBuf && cptr)
1547     sendcmdto_one(sptr, CMD_MODE, cptr, "%s :%s", cli_name(sptr), umodeBuf);
1548 }
1549
1550 /**
1551  * Check to see if this resembles a sno_mask.  It is if 1) there is
1552  * at least one digit and 2) The first digit occurs before the first
1553  * alphabetic character.
1554  * @param[in] word Word to check for sno_mask-ness.
1555  * @return Non-zero if \a word looks like a server notice mask; zero if not.
1556  */
1557 int is_snomask(char *word)
1558 {
1559   if (word)
1560   {
1561     for (; *word; word++)
1562       if (IsDigit(*word))
1563         return 1;
1564       else if (IsAlpha(*word))
1565         return 0;
1566   }
1567   return 0;
1568 }
1569
1570 /** Update snomask \a oldmask according to \a arg and \a what.
1571  * @param[in] oldmask Original user mask.
1572  * @param[in] arg Update string (either a number or '+'/'-' followed by a number).
1573  * @param[in] what MODE_ADD if adding the mask.
1574  * @return New value of service notice mask.
1575  */
1576 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1577 {
1578   unsigned int sno_what;
1579   unsigned int newmask;
1580   if (*arg == '+')
1581   {
1582     arg++;
1583     if (what == MODE_ADD)
1584       sno_what = SNO_ADD;
1585     else
1586       sno_what = SNO_DEL;
1587   }
1588   else if (*arg == '-')
1589   {
1590     arg++;
1591     if (what == MODE_ADD)
1592       sno_what = SNO_DEL;
1593     else
1594       sno_what = SNO_ADD;
1595   }
1596   else
1597     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1598   /* pity we don't have strtoul everywhere */
1599   newmask = (unsigned int)atoi(arg);
1600   if (sno_what == SNO_DEL)
1601     newmask = oldmask & ~newmask;
1602   else if (sno_what == SNO_ADD)
1603     newmask |= oldmask;
1604   return newmask;
1605 }
1606
1607 /** Remove \a cptr from the singly linked list \a list.
1608  * @param[in] cptr Client to remove from list.
1609  * @param[in,out] list Pointer to head of list containing \a cptr.
1610  */
1611 static void delfrom_list(struct Client *cptr, struct SLink **list)
1612 {
1613   struct SLink* tmp;
1614   struct SLink* prv = NULL;
1615
1616   for (tmp = *list; tmp; tmp = tmp->next) {
1617     if (tmp->value.cptr == cptr) {
1618       if (prv)
1619         prv->next = tmp->next;
1620       else
1621         *list = tmp->next;
1622       free_link(tmp);
1623       break;
1624     }
1625     prv = tmp;
1626   }
1627 }
1628
1629 /** Set \a cptr's server notice mask, according to \a what.
1630  * @param[in,out] cptr Client whose snomask is updating.
1631  * @param[in] newmask Base value for new snomask.
1632  * @param[in] what One of SNO_ADD, SNO_DEL, SNO_SET, to choose operation.
1633  */
1634 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1635 {
1636   unsigned int oldmask, diffmask;        /* unsigned please */
1637   int i;
1638   struct SLink *tmp;
1639
1640   oldmask = cli_snomask(cptr);
1641
1642   if (what == SNO_ADD)
1643     newmask |= oldmask;
1644   else if (what == SNO_DEL)
1645     newmask = oldmask & ~newmask;
1646   else if (what != SNO_SET)        /* absolute set, no math needed */
1647     sendto_opmask_butone(0, SNO_OLDSNO, "setsnomask called with %d ?!", what);
1648
1649   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1650
1651   diffmask = oldmask ^ newmask;
1652
1653   for (i = 0; diffmask >> i; i++) {
1654     if (((diffmask >> i) & 1))
1655     {
1656       if (((newmask >> i) & 1))
1657       {
1658         tmp = make_link();
1659         tmp->next = opsarray[i];
1660         tmp->value.cptr = cptr;
1661         opsarray[i] = tmp;
1662       }
1663       else
1664         /* not real portable :( */
1665         delfrom_list(cptr, &opsarray[i]);
1666     }
1667   }
1668   cli_snomask(cptr) = newmask;
1669 }
1670
1671 /** Check whether \a sptr is allowed to send a message to \a acptr.
1672  * If \a sptr is a remote user, it means some server has an outdated
1673  * SILENCE list for \a acptr, so send the missing SILENCE mask(s) back
1674  * in the direction of \a sptr.  Skip the check if \a sptr is a server.
1675  * @param[in] sptr Client trying to send a message.
1676  * @param[in] acptr Destination of message.
1677  * @return Non-zero if \a sptr is SILENCEd by \a acptr, zero if not.
1678  */
1679 int is_silenced(struct Client *sptr, struct Client *acptr)
1680 {
1681   struct Ban *found;
1682   struct User *user;
1683   size_t buf_used, slen;
1684   char buf[BUFSIZE];
1685
1686   if (IsServer(sptr) || !(user = cli_user(acptr))
1687       || !(found = find_ban(sptr, user->silence)))
1688     return 0;
1689   assert(!(found->flags & BAN_EXCEPTION));
1690   if (!MyConnect(sptr)) {
1691     /* Buffer positive silence to send back. */
1692     buf_used = strlen(found->banstr);
1693     memcpy(buf, found->banstr, buf_used);
1694     /* Add exceptions to buffer. */
1695     for (found = user->silence; found; found = found->next) {
1696       if (!(found->flags & BAN_EXCEPTION))
1697         continue;
1698       slen = strlen(found->banstr);
1699       if (buf_used + slen + 4 > 400) {
1700         buf[buf_used] = '\0';
1701         sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1702         buf_used = 0;
1703       }
1704       if (buf_used)
1705         buf[buf_used++] = ',';
1706       buf[buf_used++] = '+';
1707       buf[buf_used++] = '~';
1708       memcpy(buf + buf_used, found->banstr, slen);
1709       buf_used += slen;
1710     }
1711     /* Flush silence buffer. */
1712     if (buf_used) {
1713       buf[buf_used] = '\0';
1714       sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1715       buf_used = 0;
1716     }
1717   }
1718   return 1;
1719 }
1720
1721 /** Send RPL_ISUPPORT lines to \a cptr.
1722  * @param[in] cptr Client to send ISUPPORT to.
1723  * @return Zero.
1724  */
1725 int
1726 send_supported(struct Client *cptr)
1727 {
1728   char featurebuf[512];
1729
1730   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES1, FEATURESVALUES1);
1731   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1732   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES2, FEATURESVALUES2);
1733   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1734
1735   return 0; /* convenience return, if it's ever needed */
1736 }