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