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