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