Author: Perry Lorier <isomer@undernet.org>
[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_chattr.h"
38 #include "ircd_features.h"
39 #include "ircd_log.h"
40 #include "ircd_reply.h"
41 #include "ircd_snprintf.h"
42 #include "ircd_string.h"
43 #include "list.h"
44 #include "match.h"
45 #include "motd.h"
46 #include "msg.h"
47 #include "msgq.h"
48 #include "numeric.h"
49 #include "numnicks.h"
50 #include "parse.h"
51 #include "querycmds.h"
52 #include "random.h"
53 #include "s_auth.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     ++userCount;
95     cli_user(cptr)->refcnt = 1;
96   }
97   return cli_user(cptr);
98 }
99
100 /** Dereference \a user.
101  * User structures are reference-counted; if the refcount of \a user
102  * becomes zero, free it.
103  * @param[in] user User to dereference.
104  */
105 void free_user(struct User* user)
106 {
107   assert(0 != user);
108   assert(0 < user->refcnt);
109
110   if (--user->refcnt == 0) {
111     if (user->away)
112       MyFree(user->away);
113     /*
114      * sanity check
115      */
116     assert(0 == user->joined);
117     assert(0 == user->invited);
118     assert(0 == user->channel);
119
120     MyFree(user);
121     assert(userCount>0);
122     --userCount;
123   }
124 }
125
126 /** Find number of User structs allocated and memory used by them.
127  * @param[out] count_out Receives number of User structs allocated.
128  * @param[out] bytes_out Receives number of bytes used by User structs.
129  */
130 void user_count_memory(size_t* count_out, size_t* bytes_out)
131 {
132   assert(0 != count_out);
133   assert(0 != bytes_out);
134   *count_out = userCount;
135   *bytes_out = userCount * sizeof(struct User);
136 }
137
138
139 /** Find the next client (starting at \a next) with a name that matches \a ch.
140  * Normal usage loop is:
141  * for (x = client; x = next_client(x,mask); x = x->next)
142  *     HandleMatchingClient;
143  *
144  * @param[in] next First client to check.
145  * @param[in] ch Name mask to check against.
146  * @return Next matching client found, or NULL if none.
147  */
148 struct Client *next_client(struct Client *next, const char* ch)
149 {
150   struct Client *tmp = next;
151
152   if (!tmp)
153     return NULL;
154
155   next = FindClient(ch);
156   next = next ? next : tmp;
157   if (cli_prev(tmp) == next)
158     return NULL;
159   if (next != tmp)
160     return next;
161   for (; next; next = cli_next(next))
162     if (!match(ch, cli_name(next)))
163       break;
164   return next;
165 }
166
167 /** Find the destination server for a command, and forward it if that is not us.
168  *
169  * \a server may be a nickname, server name, server mask (if \a from
170  * is a local user) or server numnick (if \a is a server or remote
171  * user).
172  *
173  * @param[in] from Client that sent the command to us.
174  * @param[in] cmd Long-form command text.
175  * @param[in] tok Token-form command text.
176  * @param[in] one Client that originated the command (ignored).
177  * @param[in] MustBeOper If non-zero and \a from is not an operator, return HUNTED_NOSUCH.
178  * @param[in] pattern Format string of arguments to command.
179  * @param[in] server Index of target name or mask in \a parv.
180  * @param[in] parc Number of valid elements in \a parv (must be less than 9).
181  * @param[in] parv Array of arguments to command.
182  * @return One of HUNTED_ISME, HUNTED_NOSUCH or HUNTED_PASS.
183  */
184 int hunt_server_cmd(struct Client *from, const char *cmd, const char *tok,
185                     struct Client *one, int MustBeOper, const char *pattern,
186                     int server, int parc, char *parv[])
187 {
188   struct Client *acptr;
189   char *to;
190
191   /* Assume it's me, if no server or an unregistered client */
192   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
193     return (HUNTED_ISME);
194
195   if (MustBeOper && !IsPrivileged(from))
196   {
197     send_reply(from, ERR_NOPRIVILEGES);
198     return HUNTED_NOSUCH;
199   }
200
201   /* Make sure it's a server */
202   if (MyUser(from)) {
203     /* Make sure it's a server */
204     if (!strchr(to, '*')) {
205       if (0 == (acptr = FindClient(to))) {
206         send_reply(from, ERR_NOSUCHSERVER, to);
207         return HUNTED_NOSUCH;
208       }
209
210       if (cli_user(acptr))
211         acptr = cli_user(acptr)->server;
212     } else if (!(acptr = find_match_server(to))) {
213       send_reply(from, ERR_NOSUCHSERVER, to);
214       return (HUNTED_NOSUCH);
215     }
216   } else if (!(acptr = FindNServer(to))) {
217     send_reply(from, SND_EXPLICIT | ERR_NOSUCHSERVER, "* :Server has disconnected");
218     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
219   }
220
221   if (IsMe(acptr))
222     return (HUNTED_ISME);
223
224   if (MustBeOper && !IsPrivileged(from)) {
225     send_reply(from, ERR_NOPRIVILEGES);
226     return HUNTED_NOSUCH;
227   }
228
229   /* assert(!IsServer(from)); */
230
231   parv[server] = (char *) acptr; /* HACK! HACK! HACK! ARGH! */
232
233   sendcmdto_one(from, cmd, tok, acptr, pattern, parv[1], parv[2], parv[3],
234                 parv[4], parv[5], parv[6], parv[7], parv[8]);
235
236   return (HUNTED_PASS);
237 }
238
239 /** Find the destination server for a command, and forward it (as a
240  * high-priority command) if that is not us.
241  *
242  * \a server may be a nickname, server name, server mask (if \a from
243  * is a local user) or server numnick (if \a is a server or remote
244  * user).
245  * Unlike hunt_server_cmd(), this appends the message to the
246  * high-priority message queue for the destination server.
247  *
248  * @param[in] from Client that sent the command to us.
249  * @param[in] cmd Long-form command text.
250  * @param[in] tok Token-form command text.
251  * @param[in] one Client that originated the command (ignored).
252  * @param[in] MustBeOper If non-zero and \a from is not an operator, return HUNTED_NOSUCH.
253  * @param[in] pattern Format string of arguments to command.
254  * @param[in] server Index of target name or mask in \a parv.
255  * @param[in] parc Number of valid elements in \a parv (must be less than 9).
256  * @param[in] parv Array of arguments to command.
257  * @return One of HUNTED_ISME, HUNTED_NOSUCH or HUNTED_PASS.
258  */
259 int hunt_server_prio_cmd(struct Client *from, const char *cmd, const char *tok,
260                          struct Client *one, int MustBeOper,
261                          const char *pattern, int server, int parc,
262                          char *parv[])
263 {
264   struct Client *acptr;
265   char *to;
266
267   /* Assume it's me, if no server or an unregistered client */
268   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
269     return (HUNTED_ISME);
270
271   /* Make sure it's a server */
272   if (MyUser(from)) {
273     /* Make sure it's a server */
274     if (!strchr(to, '*')) {
275       if (0 == (acptr = FindClient(to))) {
276         send_reply(from, ERR_NOSUCHSERVER, to);
277         return HUNTED_NOSUCH;
278       }
279
280       if (cli_user(acptr))
281         acptr = cli_user(acptr)->server;
282     } else if (!(acptr = find_match_server(to))) {
283       send_reply(from, ERR_NOSUCHSERVER, to);
284       return (HUNTED_NOSUCH);
285     }
286   } else if (!(acptr = FindNServer(to)))
287     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
288
289   if (IsMe(acptr))
290     return (HUNTED_ISME);
291
292   if (MustBeOper && !IsPrivileged(from)) {
293     send_reply(from, ERR_NOPRIVILEGES);
294     return HUNTED_NOSUCH;
295   }
296
297   /* assert(!IsServer(from)); SETTIME to particular destinations permitted */
298
299   parv[server] = (char *) acptr; /* HACK! HACK! HACK! ARGH! */
300
301   sendcmdto_prio_one(from, cmd, tok, acptr, pattern, parv[1], parv[2], parv[3],
302                      parv[4], parv[5], parv[6], parv[7], parv[8]);
303
304   return (HUNTED_PASS);
305 }
306
307
308 /*
309  * register_user
310  *
311  * This function is called when both NICK and USER messages
312  * have been accepted for the client, in whatever order. Only
313  * after this the USER message is propagated.
314  *
315  * NICK's must be propagated at once when received, although
316  * it would be better to delay them too until full info is
317  * available. Doing it is not so simple though, would have
318  * to implement the following:
319  *
320  * 1) user telnets in and gives only "NICK foobar" and waits
321  * 2) another user far away logs in normally with the nick
322  *    "foobar" (quite legal, as this server didn't propagate it).
323  * 3) now this server gets nick "foobar" from outside, but
324  *    has already the same defined locally. Current server
325  *    would just issue "KILL foobar" to clean out dups. But,
326  *    this is not fair. It should actually request another
327  *    nick from local user or kill him/her...
328  */
329 /** Finish registering a user who has sent both NICK and USER.
330  * For local connections, possibly check IAuth; make sure there is a
331  * matching Client config block; clean the username field; check
332  * K/k-lines; check for "hacked" looking usernames; assign a numnick;
333  * and send greeting (WELCOME, ISUPPORT, MOTD, etc).
334  * For all connections, update the invisible user and operator counts;
335  * run IPcheck against their address; and forward the NICK.
336  *
337  * @param[in] cptr Client who introduced the user.
338  * @param[in,out] sptr Client who has been fully introduced.
339  * @return Zero or CPTR_KILLED.
340  */
341 int register_user(struct Client *cptr, struct Client *sptr)
342 {
343   char*            parv[4];
344   char*            tmpstr;
345   struct User*     user = cli_user(sptr);
346   char             ip_base64[25];
347
348   user->last = CurrentTime;
349   parv[0] = cli_name(sptr);
350   parv[1] = parv[2] = NULL;
351
352   if (MyConnect(sptr))
353   {
354     assert(cptr == sptr);
355
356     Count_unknownbecomesclient(sptr, UserStats);
357
358     SetUser(sptr);
359     cli_handler(sptr) = CLIENT_HANDLER;
360     SetLocalNumNick(sptr);
361     send_reply(sptr,
362                RPL_WELCOME,
363                feature_str(FEAT_NETWORK),
364                feature_str(FEAT_PROVIDER) ? " via " : "",
365                feature_str(FEAT_PROVIDER) ? feature_str(FEAT_PROVIDER) : "",
366                cli_name(sptr));
367     /*
368      * This is a duplicate of the NOTICE but see below...
369      */
370     send_reply(sptr, RPL_YOURHOST, cli_name(&me), version);
371     send_reply(sptr, RPL_CREATED, creation);
372     send_reply(sptr, RPL_MYINFO, cli_name(&me), version, infousermodes,
373                infochanmodes, infochanmodeswithparams);
374     send_supported(sptr);
375     m_lusers(sptr, sptr, 1, parv);
376     update_load();
377     motd_signon(sptr);
378     if (cli_snomask(sptr) & SNO_NOISY)
379       set_snomask(sptr, cli_snomask(sptr) & SNO_NOISY, SNO_ADD);
380     if (feature_bool(FEAT_CONNEXIT_NOTICES))
381       sendto_opmask_butone(0, SNO_CONNEXIT,
382                            "Client connecting: %s (%s@%s) [%s] {%s} [%s] <%s%s>",
383                            cli_name(sptr), user->username, user->host,
384                            cli_sock_ip(sptr), get_client_class(sptr),
385                            cli_info(sptr), NumNick(cptr) /* two %s's */);
386
387     IPcheck_connect_succeeded(sptr);
388     /*
389      * Set user's initial modes
390      */
391     tmpstr = (char*)client_get_default_umode(sptr);
392     if (tmpstr) for (; *tmpstr; ++tmpstr) {
393       switch (*tmpstr) {
394       case 's':
395         if (!feature_bool(FEAT_HIS_SNOTICES_OPER_ONLY)) {
396           SetServNotice(sptr);
397           set_snomask(sptr, SNO_DEFAULT, SNO_SET);
398         }
399         break;
400       case 'w':
401         if (!feature_bool(FEAT_WALLOPS_OPER_ONLY))
402           SetWallops(sptr);
403         break;
404       case 'i':
405         SetInvisible(sptr);
406         break;
407       case 'd':
408         SetDeaf(sptr);
409         break;
410       case 'g':
411         if (!feature_bool(FEAT_HIS_DEBUG_OPER_ONLY))
412           SetDebug(sptr);
413         break;
414       }
415     }
416   }
417   else {
418     struct Client *acptr = user->server;
419
420     Count_newremoteclient(UserStats, acptr);
421
422     if (cli_from(acptr) != cli_from(sptr))
423     {
424       sendcmdto_one(&me, CMD_KILL, cptr, "%C :%s (%s != %s[%s])",
425                     sptr, cli_name(&me), cli_name(user->server), cli_name(cli_from(acptr)),
426                     cli_sockhost(cli_from(acptr)));
427       SetFlag(sptr, FLAG_KILLED);
428       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
429     }
430     else if (HasFlag(acptr, FLAG_TS8))
431       SetFlag(sptr, FLAG_TS8);
432
433     /*
434      * Check to see if this user is being propagated
435      * as part of a net.burst, or is using protocol 9.
436      * FIXME: This can be sped up - its stupid to check it for
437      * every NICK message in a burst again  --Run.
438      */
439     for (; acptr != &me; acptr = cli_serv(acptr)->up)
440     {
441       if (IsBurst(acptr) || Protocol(acptr) < 10)
442         break;
443     }
444     if (!IPcheck_remote_connect(sptr, (acptr != &me)))
445     {
446       /*
447        * We ran out of bits to count this
448        */
449       sendcmdto_one(&me, CMD_KILL, sptr, "%C :%s (Too many connections from your host -- Ghost)",
450                     sptr, cli_name(&me));
451       return exit_client(cptr, sptr, &me,"Too many connections from your host -- throttled");
452     }
453     SetUser(sptr);
454   }
455
456   /* If they get both +x and an account during registration, hide
457    * their hostmask here.  Calling hide_hostmask() from IAuth's
458    * account assignment causes a numeric reply during registration.
459    */
460   if (HasHiddenHost(sptr))
461     hide_hostmask(sptr, FLAG_HIDDENHOST);
462
463   tmpstr = umode_str(sptr);
464   /* Send full IP address to IPv6-grokking servers. */
465   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
466                              FLAG_IPV6, FLAG_LAST_FLAG,
467                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
468                              cli_name(sptr), cli_hopcount(sptr) + 1,
469                              cli_lastnick(sptr),
470                              user->username, user->realhost,
471                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
472                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 1),
473                              NumNick(sptr), cli_info(sptr));
474   /* Send fake IPv6 addresses to pre-IPv6 servers. */
475   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
476                              FLAG_LAST_FLAG, FLAG_IPV6,
477                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
478                              cli_name(sptr), cli_hopcount(sptr) + 1,
479                              cli_lastnick(sptr),
480                              user->username, user->realhost,
481                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
482                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 0),
483                              NumNick(sptr), cli_info(sptr));
484
485   /* Send user mode to client */
486   if (MyUser(sptr))
487   {
488     static struct Flags flags; /* automatically initialized to zeros */
489     /* To avoid sending +r to the client due to auth-on-connect, set
490      * the "old" FLAG_ACCOUNT bit to match the client's value.
491      */
492     if (IsAccount(cptr))
493       FlagSet(&flags, FLAG_ACCOUNT);
494     else
495       FlagClr(&flags, FLAG_ACCOUNT);
496     send_umode(cptr, sptr, &flags, ALL_UMODES);
497     if ((cli_snomask(sptr) != SNO_DEFAULT) && HasFlag(sptr, FLAG_SERVNOTICE))
498       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
499   }
500   return 0;
501 }
502
503 /** List of user mode characters. */
504 static const struct UserMode {
505   unsigned int flag; /**< User mode constant. */
506   char         c;    /**< Character corresponding to the mode. */
507 } userModeList[] = {
508   { FLAG_OPER,        'o' },
509   { FLAG_LOCOP,       'O' },
510   { FLAG_INVISIBLE,   'i' },
511   { FLAG_WALLOP,      'w' },
512   { FLAG_SERVNOTICE,  's' },
513   { FLAG_DEAF,        'd' },
514   { FLAG_CHSERV,      'k' },
515   { FLAG_DEBUG,       'g' },
516   { FLAG_ACCOUNT,     'r' },
517   { FLAG_HIDDENHOST,  'x' }
518 };
519
520 /** Length of #userModeList. */
521 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
522
523 /*
524  * XXX - find a way to get rid of this
525  */
526 /** Nasty global buffer used for communications with umode_str() and others. */
527 static char umodeBuf[BUFSIZE];
528
529 /** Try to set a user's nickname.
530  * If \a sptr is a server, the client is being introduced for the first time.
531  * @param[in] cptr Client to set nickname.
532  * @param[in] sptr Client sending the NICK.
533  * @param[in] nick New nickname.
534  * @param[in] parc Number of arguments to NICK.
535  * @param[in] parv Argument list to NICK.
536  * @return CPTR_KILLED if \a cptr was killed, else 0.
537  */
538 int set_nick_name(struct Client* cptr, struct Client* sptr,
539                   const char* nick, int parc, char* parv[])
540 {
541   if (IsServer(sptr)) {
542     int   i;
543     const char* account = 0;
544     const char* p;
545
546     /*
547      * A server introducing a new client, change source
548      */
549     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
550     assert(0 != new_client);
551
552     cli_hopcount(new_client) = atoi(parv[2]);
553     cli_lastnick(new_client) = atoi(parv[3]);
554     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+')
555     {
556       for (p = parv[6] + 1; *p; p++)
557       {
558         for (i = 0; i < USERMODELIST_SIZE; ++i)
559         {
560           if (userModeList[i].c == *p)
561           {
562             SetFlag(new_client, userModeList[i].flag);
563             if (userModeList[i].flag == FLAG_ACCOUNT)
564               account = parv[7];
565             break;
566           }
567         }
568       }
569     }
570     client_set_privs(new_client, NULL); /* set privs on user */
571     /*
572      * Set new nick name.
573      */
574     strcpy(cli_name(new_client), nick);
575     cli_user(new_client) = make_user(new_client);
576     cli_user(new_client)->server = sptr;
577     SetRemoteNumNick(new_client, parv[parc - 2]);
578     /*
579      * IP# of remote client
580      */
581     base64toip(parv[parc - 3], &cli_ip(new_client));
582
583     add_client_to_list(new_client);
584     hAddClient(new_client);
585
586     cli_serv(sptr)->ghost = 0;        /* :server NICK means end of net.burst */
587     ircd_strncpy(cli_username(new_client), parv[4], USERLEN);
588     ircd_strncpy(cli_user(new_client)->username, parv[4], USERLEN);
589     ircd_strncpy(cli_user(new_client)->host, parv[5], HOSTLEN);
590     ircd_strncpy(cli_user(new_client)->realhost, parv[5], HOSTLEN);
591     ircd_strncpy(cli_info(new_client), parv[parc - 1], REALLEN);
592     if (account) {
593       int len = ACCOUNTLEN;
594       if ((p = strchr(account, ':'))) {
595         len = (p++) - account;
596         cli_user(new_client)->acc_create = atoi(p);
597         Debug((DEBUG_DEBUG, "Received timestamped account in user mode; "
598                "account \"%s\", timestamp %Tu", account,
599                cli_user(new_client)->acc_create));
600       }
601       ircd_strncpy(cli_user(new_client)->account, account, len);
602     }
603     if (HasHiddenHost(new_client))
604       ircd_snprintf(0, cli_user(new_client)->host, HOSTLEN, "%s.%s",
605                     cli_user(new_client)->account,
606                     feature_str(FEAT_HIDDEN_HOST));
607
608     return register_user(cptr, new_client);
609   }
610   else if ((cli_name(sptr))[0]) {
611     /*
612      * Client changing its nick
613      *
614      * If the client belongs to me, then check to see
615      * if client is on any channels where it is currently
616      * banned.  If so, do not allow the nick change to occur.
617      */
618     if (MyUser(sptr)) {
619       const char* channel_name;
620       struct Membership *member;
621       if ((channel_name = find_no_nickchange_channel(sptr))) {
622         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
623       }
624       /*
625        * Refuse nick change if the last nick change was less
626        * then 30 seconds ago. This is intended to get rid of
627        * clone bots doing NICK FLOOD. -SeKs
628        * If someone didn't change their nick for more then 60 seconds
629        * however, allow to do two nick changes immediately after another
630        * before limiting the nick flood. -Run
631        */
632       if (CurrentTime < cli_nextnick(cptr))
633       {
634         cli_nextnick(cptr) += 2;
635         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
636                    cli_nextnick(cptr) - CurrentTime);
637         /* Send error message */
638         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cli_name(cptr));
639         /* bounce NICK to user */
640         return 0;                /* ignore nick change! */
641       }
642       else {
643         /* Limit total to 1 change per NICK_DELAY seconds: */
644         cli_nextnick(cptr) += NICK_DELAY;
645         /* However allow _maximal_ 1 extra consecutive nick change: */
646         if (cli_nextnick(cptr) < CurrentTime)
647           cli_nextnick(cptr) = CurrentTime;
648       }
649       /* Invalidate all bans against the user so we check them again */
650       for (member = (cli_user(cptr))->channel; member;
651            member = member->next_channel)
652         ClearBanValid(member);
653     }
654     /*
655      * Also set 'lastnick' to current time, if changed.
656      */
657     if (0 != ircd_strcmp(parv[0], nick))
658       cli_lastnick(sptr) = (sptr == cptr) ? TStime() : atoi(parv[2]);
659
660     /*
661      * Client just changing his/her nick. If he/she is
662      * on a channel, send note of change to all clients
663      * on that channel. Propagate notice to other servers.
664      */
665     if (IsUser(sptr)) {
666       sendcmdto_common_channels_butone(sptr, CMD_NICK, NULL, ":%s", nick);
667       add_history(sptr, 1);
668       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
669                             cli_lastnick(sptr));
670     }
671     else
672       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
673
674     if ((cli_name(sptr))[0])
675       hRemClient(sptr);
676     strcpy(cli_name(sptr), nick);
677     hAddClient(sptr);
678   }
679   else {
680     /* Local client setting NICK the first time */
681     strcpy(cli_name(sptr), nick);
682     hAddClient(sptr);
683     return auth_set_nick(cli_auth(sptr), nick);
684   }
685   return 0;
686 }
687
688 /** Calculate the hash value for a target.
689  * @param[in] target Pointer to target, cast to unsigned int.
690  * @return Hash value constructed from the pointer.
691  */
692 static unsigned char hash_target(unsigned int target)
693 {
694   return (unsigned char) (target >> 16) ^ (target >> 8);
695 }
696
697 /** Records \a target as a recent target for \a sptr.
698  * @param[in] sptr User who has sent to a new target.
699  * @param[in] target Target to add.
700  */
701 void
702 add_target(struct Client *sptr, void *target)
703 {
704   /* Ok, this shouldn't work esp on alpha
705   */
706   unsigned char  hash = hash_target((unsigned long) target);
707   unsigned char* targets;
708   int            i;
709   assert(0 != sptr);
710   assert(cli_local(sptr));
711
712   targets = cli_targets(sptr);
713
714   /* 
715    * Already in table?
716    */
717   for (i = 0; i < MAXTARGETS; ++i) {
718     if (targets[i] == hash)
719       return;
720   }
721   /*
722    * New target
723    */
724   memmove(&targets[RESERVEDTARGETS + 1],
725           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
726   targets[RESERVEDTARGETS] = hash;
727 }
728
729 /** Check whether \a sptr can send to or join \a target yet.
730  * @param[in] sptr User trying to join a channel or send a message.
731  * @param[in] target Target of the join or message.
732  * @param[in] name Name of the target.
733  * @param[in] created If non-zero, trying to join a new channel.
734  * @return Non-zero if too many target changes; zero if okay to send.
735  */
736 int check_target_limit(struct Client *sptr, void *target, const char *name,
737     int created)
738 {
739   unsigned char hash = hash_target((unsigned long) target);
740   int            i;
741   unsigned char* targets;
742
743   assert(0 != sptr);
744   assert(cli_local(sptr));
745   targets = cli_targets(sptr);
746
747   /* If user is invited to channel, give him/her a free target */
748   if (IsChannelName(name) && IsInvited(sptr, target))
749     return 0;
750
751   /*
752    * Same target as last time?
753    */
754   if (targets[0] == hash)
755     return 0;
756   for (i = 1; i < MAXTARGETS; ++i) {
757     if (targets[i] == hash) {
758       memmove(&targets[1], &targets[0], i);
759       targets[0] = hash;
760       return 0;
761     }
762   }
763   /*
764    * New target
765    */
766   if (!created) {
767     if (CurrentTime < cli_nexttarget(sptr)) {
768       if (cli_nexttarget(sptr) - CurrentTime < TARGET_DELAY + 8) {
769         /*
770          * No server flooding
771          */
772         cli_nexttarget(sptr) += 2;
773         send_reply(sptr, ERR_TARGETTOOFAST, name,
774                    cli_nexttarget(sptr) - CurrentTime);
775       }
776       return 1;
777     }
778     else {
779       cli_nexttarget(sptr) += TARGET_DELAY;
780       if (cli_nexttarget(sptr) < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
781         cli_nexttarget(sptr) = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
782     }
783   }
784   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
785   targets[0] = hash;
786   return 0;
787 }
788
789 /** Allows a channel operator to avoid target change checks when
790  * sending messages to users on their channel.
791  * @param[in] source User sending the message.
792  * @param[in] nick Destination of the message.
793  * @param[in] channel Name of channel being sent to.
794  * @param[in] text Message to send.
795  * @param[in] is_notice If non-zero, use CNOTICE instead of CPRIVMSG.
796  */
797 /* Added 971023 by Run. */
798 int whisper(struct Client* source, const char* nick, const char* channel,
799             const char* text, int is_notice)
800 {
801   struct Client*     dest;
802   struct Channel*    chptr;
803   struct Membership* membership;
804
805   assert(0 != source);
806   assert(0 != nick);
807   assert(0 != channel);
808   assert(MyUser(source));
809
810   if (!(dest = FindUser(nick))) {
811     return send_reply(source, ERR_NOSUCHNICK, nick);
812   }
813   if (!(chptr = FindChannel(channel))) {
814     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
815   }
816   /*
817    * compare both users channel lists, instead of the channels user list
818    * since the link is the same, this should be a little faster for channels
819    * with a lot of users
820    */
821   for (membership = cli_user(source)->channel; membership; membership = membership->next_channel) {
822     if (chptr == membership->channel)
823       break;
824   }
825   if (0 == membership) {
826     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
827   }
828   if (!IsVoicedOrOpped(membership)) {
829     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
830   }
831   /*
832    * lookup channel in destination
833    */
834   assert(0 != cli_user(dest));
835   for (membership = cli_user(dest)->channel; membership; membership = membership->next_channel) {
836     if (chptr == membership->channel)
837       break;
838   }
839   if (0 == membership || IsZombie(membership)) {
840     return send_reply(source, ERR_USERNOTINCHANNEL, cli_name(dest), chptr->chname);
841   }
842   if (is_silenced(source, dest))
843     return 0;
844           
845   if (cli_user(dest)->away)
846     send_reply(source, RPL_AWAY, cli_name(dest), cli_user(dest)->away);
847   if (is_notice)
848     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
849   else
850     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
851   return 0;
852 }
853
854
855 /** Send a user mode change for \a cptr to neighboring servers.
856  * @param[in] cptr User whose mode is changing.
857  * @param[in] sptr Client who sent us the mode change message.
858  * @param[in] old Prior set of user flags.
859  * @param[in] prop If non-zero, also include FLAG_OPER.
860  */
861 void send_umode_out(struct Client *cptr, struct Client *sptr,
862                     struct Flags *old, int prop)
863 {
864   int i;
865   struct Client *acptr;
866
867   send_umode(NULL, sptr, old, prop ? SEND_UMODES : SEND_UMODES_BUT_OPER);
868
869   for (i = HighestFd; i >= 0; i--)
870   {
871     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
872         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
873       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", cli_name(sptr), umodeBuf);
874   }
875   if (cptr && MyUser(cptr))
876     send_umode(cptr, sptr, old, ALL_UMODES);
877 }
878
879
880 /** Call \a fmt for each Client named in \a names.
881  * @param[in] sptr Client requesting information.
882  * @param[in] names Space-delimited list of nicknames.
883  * @param[in] rpl Base reply string for messages.
884  * @param[in] fmt Formatting callback function.
885  */
886 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
887 {
888   char*          name;
889   char*          p = 0;
890   int            arg_count = 0;
891   int            users_found = 0;
892   struct Client* acptr;
893   struct MsgBuf* mb;
894
895   assert(0 != sptr);
896   assert(0 != names);
897   assert(0 != fmt);
898
899   mb = msgq_make(sptr, rpl_str(rpl), cli_name(&me), cli_name(sptr));
900
901   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
902     if ((acptr = FindUser(name))) {
903       if (users_found++)
904         msgq_append(0, mb, " ");
905       (*fmt)(acptr, sptr, mb);
906     }
907     if (5 == ++arg_count)
908       break;
909   }
910   send_buffer(sptr, mb, 0);
911   msgq_clean(mb);
912 }
913
914 /** Set \a flag on \a cptr and possibly hide the client's hostmask.
915  * @param[in,out] cptr User who is getting a new flag.
916  * @param[in] flag Some flag that affects host-hiding (FLAG_HIDDENHOST, FLAG_ACCOUNT).
917  * @return Zero.
918  */
919 int
920 hide_hostmask(struct Client *cptr, unsigned int flag)
921 {
922   struct Membership *chan;
923
924   switch (flag) {
925   case FLAG_HIDDENHOST:
926     /* Local users cannot set +x unless FEAT_HOST_HIDING is true. */
927     if (MyConnect(cptr) && !feature_bool(FEAT_HOST_HIDING))
928       return 0;
929     break;
930   case FLAG_ACCOUNT:
931     /* Invalidate all bans against the user so we check them again */
932     for (chan = (cli_user(cptr))->channel; chan;
933          chan = chan->next_channel)
934       ClearBanValid(chan);
935     break;
936   default:
937     return 0;
938   }
939
940   SetFlag(cptr, flag);
941   if (!HasFlag(cptr, FLAG_HIDDENHOST) || !HasFlag(cptr, FLAG_ACCOUNT))
942     return 0;
943
944   sendcmdto_common_channels_butone(cptr, CMD_QUIT, cptr, ":Registered");
945   ircd_snprintf(0, cli_user(cptr)->host, HOSTLEN, "%s.%s",
946                 cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
947
948   /* ok, the client is now fully hidden, so let them know -- hikari */
949   if (MyConnect(cptr))
950    send_reply(cptr, RPL_HOSTHIDDEN, cli_user(cptr)->host);
951
952   /*
953    * Go through all channels the client was on, rejoin him
954    * and set the modes, if any
955    */
956   for (chan = cli_user(cptr)->channel; chan; chan = chan->next_channel)
957   {
958     if (IsZombie(chan))
959       continue;
960     /* Send a JOIN unless the user's join has been delayed. */
961     if (!IsDelayedJoin(chan))
962       sendcmdto_channel_butserv_butone(cptr, CMD_JOIN, chan->channel, cptr, 0,
963                                          "%H", chan->channel);
964     if (IsChanOp(chan) && HasVoice(chan))
965       sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan->channel, cptr, 0,
966                                        "%H +ov %C %C", chan->channel, cptr,
967                                        cptr);
968     else if (IsChanOp(chan) || HasVoice(chan))
969       sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan->channel, cptr, 0,
970         "%H +%c %C", chan->channel, IsChanOp(chan) ? 'o' : 'v', cptr);
971   }
972   return 0;
973 }
974
975 /** Set a user's mode.  This function checks that \a cptr is trying to
976  * set his own mode, prevents local users from setting inappropriate
977  * modes through this function, and applies any other side effects of
978  * a successful mode change.
979  *
980  * @param[in,out] cptr User setting someone's mode.
981  * @param[in] sptr Client who sent the mode change message.
982  * @param[in] parc Number of parameters in \a parv.
983  * @param[in] parv Parameters to MODE.
984  * @param[in] allow_modes ALLOWMODES_ANY for any mode, ALLOWMODES_DEFAULT for 
985  *                        only permitting legitimate default user modes.
986  * @return Zero.
987  */
988 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, 
989                 char *parv[], int allow_modes)
990 {
991   char** p;
992   char*  m;
993   int what;
994   int i;
995   struct Flags setflags;
996   unsigned int tmpmask = 0;
997   int snomask_given = 0;
998   char buf[BUFSIZE];
999   int prop = 0;
1000   int do_host_hiding = 0;
1001
1002   what = MODE_ADD;
1003
1004   if (parc < 3)
1005   {
1006     m = buf;
1007     *m++ = '+';
1008     for (i = 0; i < USERMODELIST_SIZE; i++)
1009     {
1010       if (HasFlag(sptr, userModeList[i].flag) &&
1011           userModeList[i].flag != FLAG_ACCOUNT)
1012         *m++ = userModeList[i].c;
1013     }
1014     *m = '\0';
1015     send_reply(sptr, RPL_UMODEIS, buf);
1016     if (HasFlag(sptr, FLAG_SERVNOTICE) && MyConnect(sptr)
1017         && cli_snomask(sptr) !=
1018         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1019       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1020     return 0;
1021   }
1022
1023   /*
1024    * find flags already set for user
1025    * why not just copy them?
1026    */
1027   setflags = cli_flags(sptr);
1028
1029   if (MyConnect(sptr))
1030     tmpmask = cli_snomask(sptr);
1031
1032   /*
1033    * parse mode change string(s)
1034    */
1035   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1036     for (m = *p; *m; m++) {
1037       switch (*m) {
1038       case '+':
1039         what = MODE_ADD;
1040         break;
1041       case '-':
1042         what = MODE_DEL;
1043         break;
1044       case 's':
1045         if (*(p + 1) && is_snomask(*(p + 1))) {
1046           snomask_given = 1;
1047           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1048           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1049         }
1050         else
1051           tmpmask = (what == MODE_ADD) ?
1052               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1053         if (tmpmask)
1054           SetServNotice(sptr);
1055         else
1056           ClearServNotice(sptr);
1057         break;
1058       case 'w':
1059         if (what == MODE_ADD)
1060           SetWallops(sptr);
1061         else
1062           ClearWallops(sptr);
1063         break;
1064       case 'o':
1065         if (what == MODE_ADD)
1066           SetOper(sptr);
1067         else {
1068           ClrFlag(sptr, FLAG_OPER);
1069           ClrFlag(sptr, FLAG_LOCOP);
1070           if (MyConnect(sptr))
1071           {
1072             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1073             cli_handler(sptr) = CLIENT_HANDLER;
1074           }
1075         }
1076         break;
1077       case 'O':
1078         if (what == MODE_ADD)
1079           SetLocOp(sptr);
1080         else
1081         { 
1082           ClrFlag(sptr, FLAG_OPER);
1083           ClrFlag(sptr, FLAG_LOCOP);
1084           if (MyConnect(sptr))
1085           {
1086             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1087             cli_handler(sptr) = CLIENT_HANDLER;
1088           }
1089         }
1090         break;
1091       case 'i':
1092         if (what == MODE_ADD)
1093           SetInvisible(sptr);
1094         else
1095           ClearInvisible(sptr);
1096         break;
1097       case 'd':
1098         if (what == MODE_ADD)
1099           SetDeaf(sptr);
1100         else
1101           ClearDeaf(sptr);
1102         break;
1103       case 'k':
1104         if (what == MODE_ADD)
1105           SetChannelService(sptr);
1106         else
1107           ClearChannelService(sptr);
1108         break;
1109       case 'g':
1110         if (what == MODE_ADD)
1111           SetDebug(sptr);
1112         else
1113           ClearDebug(sptr);
1114         break;
1115       case 'x':
1116         if (what == MODE_ADD)
1117           do_host_hiding = 1;
1118         break;
1119       default:
1120         send_reply(sptr, ERR_UMODEUNKNOWNFLAG, *m);
1121         break;
1122       }
1123     }
1124   }
1125   /*
1126    * Evaluate rules for new user mode
1127    * Stop users making themselves operators too easily:
1128    */
1129   if (!IsServer(cptr))
1130   {
1131     if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr))
1132       ClearOper(sptr);
1133     if (!FlagHas(&setflags, FLAG_LOCOP) && IsLocOp(sptr))
1134       ClearLocOp(sptr);
1135     /*
1136      * new umode; servers can set it, local users cannot;
1137      * prevents users from /kick'ing or /mode -o'ing
1138      */
1139     if (!FlagHas(&setflags, FLAG_CHSERV))
1140       ClearChannelService(sptr);
1141     /*
1142      * only send wallops to opers
1143      */
1144     if (feature_bool(FEAT_WALLOPS_OPER_ONLY) && !IsAnOper(sptr) &&
1145         !FlagHas(&setflags, FLAG_WALLOP))
1146       ClearWallops(sptr);
1147     if (feature_bool(FEAT_HIS_SNOTICES_OPER_ONLY) && MyConnect(sptr) &&
1148         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_SERVNOTICE))
1149     {
1150       ClearServNotice(sptr);
1151       set_snomask(sptr, 0, SNO_SET);
1152     }
1153     if (feature_bool(FEAT_HIS_DEBUG_OPER_ONLY) &&
1154         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_DEBUG))
1155       ClearDebug(sptr);
1156   }
1157   if (MyConnect(sptr))
1158   {
1159     if ((FlagHas(&setflags, FLAG_OPER) || FlagHas(&setflags, FLAG_LOCOP)) &&
1160         !IsAnOper(sptr))
1161       det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPERATOR);
1162
1163     if (SendServNotice(sptr))
1164     {
1165       if (tmpmask != cli_snomask(sptr))
1166         set_snomask(sptr, tmpmask, SNO_SET);
1167       if (cli_snomask(sptr) && snomask_given)
1168         send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1169     }
1170     else
1171       set_snomask(sptr, 0, SNO_SET);
1172   }
1173   /*
1174    * Compare new flags with old flags and send string which
1175    * will cause servers to update correctly.
1176    */
1177   if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr))
1178   {
1179     /* user now oper */
1180     ++UserStats.opers;
1181     client_set_privs(sptr, NULL); /* may set propagate privilege */
1182   }
1183   /* remember propagate privilege setting */
1184   if (HasPriv(sptr, PRIV_PROPAGATE))
1185     prop = 1;
1186   if (FlagHas(&setflags, FLAG_OPER) && !IsOper(sptr))
1187   {
1188     /* user no longer oper */
1189     assert(UserStats.opers > 0);
1190     --UserStats.opers;
1191     client_set_privs(sptr, NULL); /* will clear propagate privilege */
1192   }
1193   if (FlagHas(&setflags, FLAG_INVISIBLE) && !IsInvisible(sptr)) {
1194     assert(UserStats.inv_clients > 0);
1195     --UserStats.inv_clients;
1196   }
1197   if (!FlagHas(&setflags, FLAG_INVISIBLE) && IsInvisible(sptr))
1198     ++UserStats.inv_clients;
1199   if (!FlagHas(&setflags, FLAG_HIDDENHOST) && do_host_hiding && allow_modes != ALLOWMODES_DEFAULT)
1200     hide_hostmask(sptr, FLAG_HIDDENHOST);
1201   if (IsRegistered(sptr))
1202     send_umode_out(cptr, sptr, &setflags, prop);
1203
1204   assert(UserStats.opers <= UserStats.clients + UserStats.unknowns);
1205   assert(UserStats.inv_clients <= UserStats.clients + UserStats.unknowns);
1206   return 0;
1207 }
1208
1209 /** Build a mode string to describe modes for \a cptr.
1210  * @param[in] cptr Some user.
1211  * @return Pointer to a static buffer.
1212  */
1213 char *umode_str(struct Client *cptr)
1214 {
1215   /* Maximum string size: "owidgrx\0" */
1216   char *m = umodeBuf;
1217   int i;
1218   struct Flags c_flags = cli_flags(cptr);
1219
1220   if (!HasPriv(cptr, PRIV_PROPAGATE))
1221     FlagClr(&c_flags, FLAG_OPER);
1222
1223   for (i = 0; i < USERMODELIST_SIZE; ++i)
1224   {
1225     if (FlagHas(&c_flags, userModeList[i].flag) &&
1226         userModeList[i].flag >= FLAG_GLOBAL_UMODES)
1227       *m++ = userModeList[i].c;
1228   }
1229
1230   if (IsAccount(cptr))
1231   {
1232     char* t = cli_user(cptr)->account;
1233
1234     *m++ = ' ';
1235     while ((*m++ = *t++))
1236       ; /* Empty loop */
1237
1238     if (cli_user(cptr)->acc_create) {
1239       char nbuf[20];
1240       Debug((DEBUG_DEBUG, "Sending timestamped account in user mode for "
1241              "account \"%s\"; timestamp %Tu", cli_user(cptr)->account,
1242              cli_user(cptr)->acc_create));
1243       ircd_snprintf(0, t = nbuf, sizeof(nbuf), ":%Tu",
1244                     cli_user(cptr)->acc_create);
1245       m--; /* back up over previous nul-termination */
1246       while ((*m++ = *t++))
1247         ; /* Empty loop */
1248     }
1249   }
1250
1251   *m = '\0';
1252
1253   return umodeBuf;                /* Note: static buffer, gets
1254                                    overwritten by send_umode() */
1255 }
1256
1257 /** Send a mode change string for \a sptr to \a cptr.
1258  * @param[in] cptr Destination of mode change message.
1259  * @param[in] sptr User whose mode has changed.
1260  * @param[in] old Pre-change set of modes for \a sptr.
1261  * @param[in] sendset One of ALL_UMODES, SEND_UMODES_BUT_OPER,
1262  * SEND_UMODES, to select which changed user modes to send.
1263  */
1264 void send_umode(struct Client *cptr, struct Client *sptr, struct Flags *old,
1265                 int sendset)
1266 {
1267   int i;
1268   int flag;
1269   char *m;
1270   int what = MODE_NULL;
1271
1272   /*
1273    * Build a string in umodeBuf to represent the change in the user's
1274    * mode between the new (cli_flags(sptr)) and 'old', but skipping
1275    * the modes indicated by sendset.
1276    */
1277   m = umodeBuf;
1278   *m = '\0';
1279   for (i = 0; i < USERMODELIST_SIZE; ++i)
1280   {
1281     flag = userModeList[i].flag;
1282     if (FlagHas(old, flag)
1283         == HasFlag(sptr, flag))
1284       continue;
1285     switch (sendset)
1286     {
1287     case ALL_UMODES:
1288       break;
1289     case SEND_UMODES_BUT_OPER:
1290       if (flag == FLAG_OPER)
1291         continue;
1292       /* and fall through */
1293     case SEND_UMODES:
1294       if (flag < FLAG_GLOBAL_UMODES)
1295         continue;
1296       break;      
1297     }
1298     if (FlagHas(old, flag))
1299     {
1300       if (what == MODE_DEL)
1301         *m++ = userModeList[i].c;
1302       else
1303       {
1304         what = MODE_DEL;
1305         *m++ = '-';
1306         *m++ = userModeList[i].c;
1307       }
1308     }
1309     else /* !FlagHas(old, flag) */
1310     {
1311       if (what == MODE_ADD)
1312         *m++ = userModeList[i].c;
1313       else
1314       {
1315         what = MODE_ADD;
1316         *m++ = '+';
1317         *m++ = userModeList[i].c;
1318       }
1319     }
1320   }
1321   *m = '\0';
1322   if (*umodeBuf && cptr)
1323     sendcmdto_one(sptr, CMD_MODE, cptr, "%s :%s", cli_name(sptr), umodeBuf);
1324 }
1325
1326 /**
1327  * Check to see if this resembles a sno_mask.  It is if 1) there is
1328  * at least one digit and 2) The first digit occurs before the first
1329  * alphabetic character.
1330  * @param[in] word Word to check for sno_mask-ness.
1331  * @return Non-zero if \a word looks like a server notice mask; zero if not.
1332  */
1333 int is_snomask(char *word)
1334 {
1335   if (word)
1336   {
1337     for (; *word; word++)
1338       if (IsDigit(*word))
1339         return 1;
1340       else if (IsAlpha(*word))
1341         return 0;
1342   }
1343   return 0;
1344 }
1345
1346 /** Update snomask \a oldmask according to \a arg and \a what.
1347  * @param[in] oldmask Original user mask.
1348  * @param[in] arg Update string (either a number or '+'/'-' followed by a number).
1349  * @param[in] what MODE_ADD if adding the mask.
1350  * @return New value of service notice mask.
1351  */
1352 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1353 {
1354   unsigned int sno_what;
1355   unsigned int newmask;
1356   if (*arg == '+')
1357   {
1358     arg++;
1359     if (what == MODE_ADD)
1360       sno_what = SNO_ADD;
1361     else
1362       sno_what = SNO_DEL;
1363   }
1364   else if (*arg == '-')
1365   {
1366     arg++;
1367     if (what == MODE_ADD)
1368       sno_what = SNO_DEL;
1369     else
1370       sno_what = SNO_ADD;
1371   }
1372   else
1373     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1374   /* pity we don't have strtoul everywhere */
1375   newmask = (unsigned int)atoi(arg);
1376   if (sno_what == SNO_DEL)
1377     newmask = oldmask & ~newmask;
1378   else if (sno_what == SNO_ADD)
1379     newmask |= oldmask;
1380   return newmask;
1381 }
1382
1383 /** Remove \a cptr from the singly linked list \a list.
1384  * @param[in] cptr Client to remove from list.
1385  * @param[in,out] list Pointer to head of list containing \a cptr.
1386  */
1387 static void delfrom_list(struct Client *cptr, struct SLink **list)
1388 {
1389   struct SLink* tmp;
1390   struct SLink* prv = NULL;
1391
1392   for (tmp = *list; tmp; tmp = tmp->next) {
1393     if (tmp->value.cptr == cptr) {
1394       if (prv)
1395         prv->next = tmp->next;
1396       else
1397         *list = tmp->next;
1398       free_link(tmp);
1399       break;
1400     }
1401     prv = tmp;
1402   }
1403 }
1404
1405 /** Set \a cptr's server notice mask, according to \a what.
1406  * @param[in,out] cptr Client whose snomask is updating.
1407  * @param[in] newmask Base value for new snomask.
1408  * @param[in] what One of SNO_ADD, SNO_DEL, SNO_SET, to choose operation.
1409  */
1410 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1411 {
1412   unsigned int oldmask, diffmask;        /* unsigned please */
1413   int i;
1414   struct SLink *tmp;
1415
1416   oldmask = cli_snomask(cptr);
1417
1418   if (what == SNO_ADD)
1419     newmask |= oldmask;
1420   else if (what == SNO_DEL)
1421     newmask = oldmask & ~newmask;
1422   else if (what != SNO_SET)        /* absolute set, no math needed */
1423     sendto_opmask_butone(0, SNO_OLDSNO, "setsnomask called with %d ?!", what);
1424
1425   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1426
1427   diffmask = oldmask ^ newmask;
1428
1429   for (i = 0; diffmask >> i; i++) {
1430     if (((diffmask >> i) & 1))
1431     {
1432       if (((newmask >> i) & 1))
1433       {
1434         tmp = make_link();
1435         tmp->next = opsarray[i];
1436         tmp->value.cptr = cptr;
1437         opsarray[i] = tmp;
1438       }
1439       else
1440         /* not real portable :( */
1441         delfrom_list(cptr, &opsarray[i]);
1442     }
1443   }
1444   cli_snomask(cptr) = newmask;
1445 }
1446
1447 /** Check whether \a sptr is allowed to send a message to \a acptr.
1448  * If \a sptr is a remote user, it means some server has an outdated
1449  * SILENCE list for \a acptr, so send the missing SILENCE mask(s) back
1450  * in the direction of \a sptr.  Skip the check if \a sptr is a server.
1451  * @param[in] sptr Client trying to send a message.
1452  * @param[in] acptr Destination of message.
1453  * @return Non-zero if \a sptr is SILENCEd by \a acptr, zero if not.
1454  */
1455 int is_silenced(struct Client *sptr, struct Client *acptr)
1456 {
1457   struct Ban *found;
1458   struct User *user;
1459   size_t buf_used, slen;
1460   char buf[BUFSIZE];
1461
1462   if (IsServer(sptr) || !(user = cli_user(acptr))
1463       || !(found = find_ban(sptr, user->silence)))
1464     return 0;
1465   assert(!(found->flags & BAN_EXCEPTION));
1466   if (!MyConnect(sptr)) {
1467     /* Buffer positive silence to send back. */
1468     buf_used = strlen(found->banstr);
1469     memcpy(buf, found->banstr, buf_used);
1470     /* Add exceptions to buffer. */
1471     for (found = user->silence; found; found = found->next) {
1472       if (!(found->flags & BAN_EXCEPTION))
1473         continue;
1474       slen = strlen(found->banstr);
1475       if (buf_used + slen + 4 > 400) {
1476         buf[buf_used] = '\0';
1477         sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1478         buf_used = 0;
1479       }
1480       if (buf_used)
1481         buf[buf_used++] = ',';
1482       buf[buf_used++] = '+';
1483       buf[buf_used++] = '~';
1484       memcpy(buf + buf_used, found->banstr, slen);
1485       buf_used += slen;
1486     }
1487     /* Flush silence buffer. */
1488     if (buf_used) {
1489       buf[buf_used] = '\0';
1490       sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1491       buf_used = 0;
1492     }
1493   }
1494   return 1;
1495 }
1496
1497 /** Send RPL_ISUPPORT lines to \a cptr.
1498  * @param[in] cptr Client to send ISUPPORT to.
1499  * @return Zero.
1500  */
1501 int
1502 send_supported(struct Client *cptr)
1503 {
1504   char featurebuf[512];
1505
1506   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES1, FEATURESVALUES1);
1507   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1508   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES2, FEATURESVALUES2);
1509   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1510
1511   return 0; /* convenience return, if it's ever needed */
1512 }