632e185b5348bfa146b473cf193342ff7743f448
[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   }
404   else {
405     struct Client *acptr = user->server;
406
407     if (cli_from(acptr) != cli_from(sptr))
408     {
409       sendcmdto_one(&me, CMD_KILL, cptr, "%C :%s (%s != %s[%s])",
410                     sptr, cli_name(&me), cli_name(user->server), cli_name(cli_from(acptr)),
411                     cli_sockhost(cli_from(acptr)));
412       SetFlag(sptr, FLAG_KILLED);
413       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
414     }
415     else if (HasFlag(acptr, FLAG_TS8))
416       SetFlag(sptr, FLAG_TS8);
417
418     /*
419      * Check to see if this user is being propagated
420      * as part of a net.burst, or is using protocol 9.
421      * FIXME: This can be sped up - its stupid to check it for
422      * every NICK message in a burst again  --Run.
423      */
424     for (; acptr != &me; acptr = cli_serv(acptr)->up)
425     {
426       if (IsBurst(acptr) || Protocol(acptr) < 10)
427         break;
428     }
429     if (!IPcheck_remote_connect(sptr, (acptr != &me)))
430     {
431       /*
432        * We ran out of bits to count this
433        */
434       sendcmdto_one(&me, CMD_KILL, sptr, "%C :%s (Too many connections from your host -- Ghost)",
435                     sptr, cli_name(&me));
436       return exit_client(cptr, sptr, &me,"Too many connections from your host -- throttled");
437     }
438     SetUser(sptr);
439   }
440
441   /* If they get both +x and an account during registration, hide
442    * their hostmask here.  Calling hide_hostmask() from IAuth's
443    * account assignment causes a numeric reply during registration.
444    */
445   if (HasHiddenHost(sptr))
446     hide_hostmask(sptr, FLAG_HIDDENHOST);
447   if (IsInvisible(sptr))
448     ++UserStats.inv_clients;
449   if (IsOper(sptr))
450     ++UserStats.opers;
451
452   tmpstr = umode_str(sptr);
453   /* Send full IP address to IPv6-grokking servers. */
454   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
455                              FLAG_IPV6, FLAG_LAST_FLAG,
456                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
457                              cli_name(sptr), cli_hopcount(sptr) + 1,
458                              cli_lastnick(sptr),
459                              user->username, user->realhost,
460                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
461                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 1),
462                              NumNick(sptr), cli_info(sptr));
463   /* Send fake IPv6 addresses to pre-IPv6 servers. */
464   sendcmdto_flag_serv_butone(user->server, CMD_NICK, cptr,
465                              FLAG_LAST_FLAG, FLAG_IPV6,
466                              "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
467                              cli_name(sptr), cli_hopcount(sptr) + 1,
468                              cli_lastnick(sptr),
469                              user->username, user->realhost,
470                              *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
471                              iptobase64(ip_base64, &cli_ip(sptr), sizeof(ip_base64), 0),
472                              NumNick(sptr), cli_info(sptr));
473
474   /* Send user mode to client */
475   if (MyUser(sptr))
476   {
477     static struct Flags flags; /* automatically initialized to zeros */
478     /* To avoid sending +r to the client due to auth-on-connect, set
479      * the "old" FLAG_ACCOUNT bit to match the client's value.
480      */
481     if (IsAccount(cptr))
482       FlagSet(&flags, FLAG_ACCOUNT);
483     else
484       FlagClr(&flags, FLAG_ACCOUNT);
485     client_set_privs(sptr, NULL);
486     send_umode(cptr, sptr, &flags, ALL_UMODES);
487     if ((cli_snomask(sptr) != SNO_DEFAULT) && HasFlag(sptr, FLAG_SERVNOTICE))
488       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
489   }
490   return 0;
491 }
492
493 /** List of user mode characters. */
494 static const struct UserMode {
495   unsigned int flag; /**< User mode constant. */
496   char         c;    /**< Character corresponding to the mode. */
497 } userModeList[] = {
498   { FLAG_OPER,        'o' },
499   { FLAG_LOCOP,       'O' },
500   { FLAG_INVISIBLE,   'i' },
501   { FLAG_WALLOP,      'w' },
502   { FLAG_SERVNOTICE,  's' },
503   { FLAG_DEAF,        'd' },
504   { FLAG_CHSERV,      'k' },
505   { FLAG_DEBUG,       'g' },
506   { FLAG_ACCOUNT,     'r' },
507   { FLAG_HIDDENHOST,  'x' },
508   { FLAG_SSLCONN,     'S' }
509 };
510
511 /** Length of #userModeList. */
512 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
513
514 /*
515  * XXX - find a way to get rid of this
516  */
517 /** Nasty global buffer used for communications with umode_str() and others. */
518 static char umodeBuf[BUFSIZE];
519
520 /** Try to set a user's nickname.
521  * If \a sptr is a server, the client is being introduced for the first time.
522  * @param[in] cptr Client to set nickname.
523  * @param[in] sptr Client sending the NICK.
524  * @param[in] nick New nickname.
525  * @param[in] parc Number of arguments to NICK.
526  * @param[in] parv Argument list to NICK.
527  * @return CPTR_KILLED if \a cptr was killed, else 0.
528  */
529 int set_nick_name(struct Client* cptr, struct Client* sptr,
530                   const char* nick, int parc, char* parv[])
531 {
532   if (IsServer(sptr)) {
533
534     /*
535      * A server introducing a new client, change source
536      */
537     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
538     assert(0 != new_client);
539
540     cli_hopcount(new_client) = atoi(parv[2]);
541     cli_lastnick(new_client) = atoi(parv[3]);
542
543     /*
544      * Set new nick name.
545      */
546     strcpy(cli_name(new_client), nick);
547     cli_user(new_client) = make_user(new_client);
548     cli_user(new_client)->server = sptr;
549     SetRemoteNumNick(new_client, parv[parc - 2]);
550     /*
551      * IP# of remote client
552      */
553     base64toip(parv[parc - 3], &cli_ip(new_client));
554
555     add_client_to_list(new_client);
556     hAddClient(new_client);
557
558     cli_serv(sptr)->ghost = 0;        /* :server NICK means end of net.burst */
559     ircd_strncpy(cli_username(new_client), parv[4], USERLEN);
560     ircd_strncpy(cli_user(new_client)->username, parv[4], USERLEN);
561     ircd_strncpy(cli_user(new_client)->host, parv[5], HOSTLEN);
562     ircd_strncpy(cli_user(new_client)->realhost, parv[5], HOSTLEN);
563     ircd_strncpy(cli_info(new_client), parv[parc - 1], REALLEN);
564
565     Count_newremoteclient(UserStats, sptr);
566
567     if (parc > 7 && *parv[6] == '+') {
568       /* (parc-4) -3 for the ip, numeric nick, realname */
569       set_user_mode(cptr, new_client, parc-7, parv+4, ALLOWMODES_ANY);
570     }
571
572     return register_user(cptr, new_client);
573   }
574   else if ((cli_name(sptr))[0]) {
575     /*
576      * Client changing its nick
577      *
578      * If the client belongs to me, then check to see
579      * if client is on any channels where it is currently
580      * banned.  If so, do not allow the nick change to occur.
581      */
582     if (MyUser(sptr)) {
583       const char* channel_name;
584       struct Membership *member;
585       if ((channel_name = find_no_nickchange_channel(sptr))) {
586         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
587       }
588       /*
589        * Refuse nick change if the last nick change was less
590        * then 30 seconds ago. This is intended to get rid of
591        * clone bots doing NICK FLOOD. -SeKs
592        * If someone didn't change their nick for more then 60 seconds
593        * however, allow to do two nick changes immediately after another
594        * before limiting the nick flood. -Run
595        */
596       if (CurrentTime < cli_nextnick(cptr))
597       {
598         cli_nextnick(cptr) += 2;
599         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
600                    cli_nextnick(cptr) - CurrentTime);
601         /* Send error message */
602         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cli_name(cptr));
603         /* bounce NICK to user */
604         return 0;                /* ignore nick change! */
605       }
606       else {
607         /* Limit total to 1 change per NICK_DELAY seconds: */
608         cli_nextnick(cptr) += NICK_DELAY;
609         /* However allow _maximal_ 1 extra consecutive nick change: */
610         if (cli_nextnick(cptr) < CurrentTime)
611           cli_nextnick(cptr) = CurrentTime;
612       }
613       /* Invalidate all bans against the user so we check them again */
614       for (member = (cli_user(cptr))->channel; member;
615            member = member->next_channel)
616         ClearBanValid(member);
617     }
618     /*
619      * Also set 'lastnick' to current time, if changed.
620      */
621     if (0 != ircd_strcmp(parv[0], nick))
622       cli_lastnick(sptr) = (sptr == cptr) ? TStime() : atoi(parv[2]);
623
624     /*
625      * Client just changing his/her nick. If he/she is
626      * on a channel, send note of change to all clients
627      * on that channel. Propagate notice to other servers.
628      */
629     if (IsUser(sptr)) {
630       sendcmdto_common_channels_butone(sptr, CMD_NICK, NULL, ":%s", nick);
631       add_history(sptr, 1);
632       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
633                             cli_lastnick(sptr));
634     }
635     else
636       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
637
638     if ((cli_name(sptr))[0])
639       hRemClient(sptr);
640     strcpy(cli_name(sptr), nick);
641     hAddClient(sptr);
642   }
643   else {
644     /* Local client setting NICK the first time */
645     strcpy(cli_name(sptr), nick);
646     hAddClient(sptr);
647     return auth_set_nick(cli_auth(sptr), nick);
648   }
649   return 0;
650 }
651
652 /** Calculate the hash value for a target.
653  * @param[in] target Pointer to target, cast to unsigned int.
654  * @return Hash value constructed from the pointer.
655  */
656 static unsigned char hash_target(unsigned int target)
657 {
658   return (unsigned char) (target >> 16) ^ (target >> 8);
659 }
660
661 /** Records \a target as a recent target for \a sptr.
662  * @param[in] sptr User who has sent to a new target.
663  * @param[in] target Target to add.
664  */
665 void
666 add_target(struct Client *sptr, void *target)
667 {
668   /* Ok, this shouldn't work esp on alpha
669   */
670   unsigned char  hash = hash_target((unsigned long) target);
671   unsigned char* targets;
672   int            i;
673   assert(0 != sptr);
674   assert(cli_local(sptr));
675
676   targets = cli_targets(sptr);
677
678   /* 
679    * Already in table?
680    */
681   for (i = 0; i < MAXTARGETS; ++i) {
682     if (targets[i] == hash)
683       return;
684   }
685   /*
686    * New target
687    */
688   memmove(&targets[RESERVEDTARGETS + 1],
689           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
690   targets[RESERVEDTARGETS] = hash;
691 }
692
693 /** Check whether \a sptr can send to or join \a target yet.
694  * @param[in] sptr User trying to join a channel or send a message.
695  * @param[in] target Target of the join or message.
696  * @param[in] name Name of the target.
697  * @param[in] created If non-zero, trying to join a new channel.
698  * @return Non-zero if too many target changes; zero if okay to send.
699  */
700 int check_target_limit(struct Client *sptr, void *target, const char *name,
701     int created)
702 {
703   unsigned char hash = hash_target((unsigned long) target);
704   int            i;
705   unsigned char* targets;
706
707   assert(0 != sptr);
708   assert(cli_local(sptr));
709   targets = cli_targets(sptr);
710
711   /*
712    * Same target as last time?
713    */
714   if (targets[0] == hash)
715     return 0;
716   for (i = 1; i < MAXTARGETS; ++i) {
717     if (targets[i] == hash) {
718       memmove(&targets[1], &targets[0], i);
719       targets[0] = hash;
720       return 0;
721     }
722   }
723   /*
724    * New target
725    */
726   if (!created) {
727     if (CurrentTime < cli_nexttarget(sptr)) {
728       /* If user is invited to channel, give him/her a free target */
729       if (IsChannelName(name) && IsInvited(sptr, target))
730         return 0;
731
732       if (cli_nexttarget(sptr) - CurrentTime < TARGET_DELAY + 8) {
733         /*
734          * No server flooding
735          */
736         cli_nexttarget(sptr) += 2;
737         send_reply(sptr, ERR_TARGETTOOFAST, name,
738                    cli_nexttarget(sptr) - CurrentTime);
739       }
740       return 1;
741     }
742     else {
743       cli_nexttarget(sptr) += TARGET_DELAY;
744       if (cli_nexttarget(sptr) < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
745         cli_nexttarget(sptr) = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
746     }
747   }
748   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
749   targets[0] = hash;
750   return 0;
751 }
752
753 /** Allows a channel operator to avoid target change checks when
754  * sending messages to users on their channel.
755  * @param[in] source User sending the message.
756  * @param[in] nick Destination of the message.
757  * @param[in] channel Name of channel being sent to.
758  * @param[in] text Message to send.
759  * @param[in] is_notice If non-zero, use CNOTICE instead of CPRIVMSG.
760  */
761 /* Added 971023 by Run. */
762 int whisper(struct Client* source, const char* nick, const char* channel,
763             const char* text, int is_notice)
764 {
765   struct Client*     dest;
766   struct Channel*    chptr;
767   struct Membership* membership;
768
769   assert(0 != source);
770   assert(0 != nick);
771   assert(0 != channel);
772   assert(MyUser(source));
773
774   if (!(dest = FindUser(nick))) {
775     return send_reply(source, ERR_NOSUCHNICK, nick);
776   }
777   if (!(chptr = FindChannel(channel))) {
778     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
779   }
780   /*
781    * compare both users channel lists, instead of the channels user list
782    * since the link is the same, this should be a little faster for channels
783    * with a lot of users
784    */
785   for (membership = cli_user(source)->channel; membership; membership = membership->next_channel) {
786     if (chptr == membership->channel)
787       break;
788   }
789   if (0 == membership) {
790     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
791   }
792   if (!IsVoicedOrOpped(membership)) {
793     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
794   }
795   /*
796    * lookup channel in destination
797    */
798   assert(0 != cli_user(dest));
799   for (membership = cli_user(dest)->channel; membership; membership = membership->next_channel) {
800     if (chptr == membership->channel)
801       break;
802   }
803   if (0 == membership || IsZombie(membership)) {
804     return send_reply(source, ERR_USERNOTINCHANNEL, cli_name(dest), chptr->chname);
805   }
806   if (is_silenced(source, dest))
807     return 0;
808           
809   if (is_notice)
810     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
811   else
812   {
813     if (cli_user(dest)->away)
814       send_reply(source, RPL_AWAY, cli_name(dest), cli_user(dest)->away);
815     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
816   }
817   return 0;
818 }
819
820
821 /** Send a user mode change for \a cptr to neighboring servers.
822  * @param[in] cptr User whose mode is changing.
823  * @param[in] sptr Client who sent us the mode change message.
824  * @param[in] old Prior set of user flags.
825  * @param[in] prop If non-zero, also include FLAG_OPER.
826  */
827 void send_umode_out(struct Client *cptr, struct Client *sptr,
828                     struct Flags *old, int prop)
829 {
830   int i;
831   struct Client *acptr;
832
833   send_umode(NULL, sptr, old, prop ? SEND_UMODES : SEND_UMODES_BUT_OPER);
834
835   for (i = HighestFd; i >= 0; i--)
836   {
837     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
838         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
839       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", cli_name(sptr), umodeBuf);
840   }
841   if (cptr && MyUser(cptr))
842     send_umode(cptr, sptr, old, ALL_UMODES);
843 }
844
845
846 /** Call \a fmt for each Client named in \a names.
847  * @param[in] sptr Client requesting information.
848  * @param[in] names Space-delimited list of nicknames.
849  * @param[in] rpl Base reply string for messages.
850  * @param[in] fmt Formatting callback function.
851  */
852 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
853 {
854   char*          name;
855   char*          p = 0;
856   int            arg_count = 0;
857   int            users_found = 0;
858   struct Client* acptr;
859   struct MsgBuf* mb;
860
861   assert(0 != sptr);
862   assert(0 != names);
863   assert(0 != fmt);
864
865   mb = msgq_make(sptr, rpl_str(rpl), cli_name(&me), cli_name(sptr));
866
867   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
868     if ((acptr = FindUser(name))) {
869       if (users_found++)
870         msgq_append(0, mb, " ");
871       (*fmt)(acptr, sptr, mb);
872     }
873     if (5 == ++arg_count)
874       break;
875   }
876   send_buffer(sptr, mb, 0);
877   msgq_clean(mb);
878 }
879
880 /** Set \a flag on \a cptr and possibly hide the client's hostmask.
881  * @param[in,out] cptr User who is getting a new flag.
882  * @param[in] flag Some flag that affects host-hiding (FLAG_HIDDENHOST, FLAG_ACCOUNT).
883  * @return Zero.
884  */
885 int
886 hide_hostmask(struct Client *cptr, unsigned int flag)
887 {
888   struct Membership *chan;
889
890   switch (flag) {
891   case FLAG_HIDDENHOST:
892     /* Local users cannot set +x unless FEAT_HOST_HIDING is true. */
893     if (MyConnect(cptr) && !feature_bool(FEAT_HOST_HIDING))
894       return 0;
895     break;
896   case FLAG_ACCOUNT:
897     /* Invalidate all bans against the user so we check them again */
898     for (chan = (cli_user(cptr))->channel; chan;
899          chan = chan->next_channel)
900       ClearBanValid(chan);
901     break;
902   default:
903     return 0;
904   }
905
906   SetFlag(cptr, flag);
907   if (!HasFlag(cptr, FLAG_HIDDENHOST) || !HasFlag(cptr, FLAG_ACCOUNT))
908     return 0;
909
910   sendcmdto_common_channels_butone(cptr, CMD_QUIT, cptr, ":Registered");
911   ircd_snprintf(0, cli_user(cptr)->host, HOSTLEN, "%s.%s",
912                 cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
913
914   /* ok, the client is now fully hidden, so let them know -- hikari */
915   if (MyConnect(cptr))
916    send_reply(cptr, RPL_HOSTHIDDEN, cli_user(cptr)->host);
917
918   /*
919    * Go through all channels the client was on, rejoin him
920    * and set the modes, if any
921    */
922   for (chan = cli_user(cptr)->channel; chan; chan = chan->next_channel)
923   {
924     if (IsZombie(chan))
925       continue;
926     /* Send a JOIN unless the user's join has been delayed. */
927     if (!IsDelayedJoin(chan))
928       sendcmdto_channel_butserv_butone(cptr, CMD_JOIN, chan->channel, cptr, 0,
929                                          "%H", chan->channel);
930     if (IsChanOp(chan) && HasVoice(chan))
931       sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan->channel, cptr, 0,
932                                        "%H +ov %C %C", chan->channel, cptr,
933                                        cptr);
934     else if (IsChanOp(chan) || HasVoice(chan))
935       sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan->channel, cptr, 0,
936         "%H +%c %C", chan->channel, IsChanOp(chan) ? 'o' : 'v', cptr);
937   }
938   return 0;
939 }
940
941 /** Set a user's mode.  This function checks that \a cptr is trying to
942  * set his own mode, prevents local users from setting inappropriate
943  * modes through this function, and applies any other side effects of
944  * a successful mode change.
945  *
946  * @param[in,out] cptr User setting someone's mode.
947  * @param[in] sptr Client who sent the mode change message.
948  * @param[in] parc Number of parameters in \a parv.
949  * @param[in] parv Parameters to MODE.
950  * @param[in] allow_modes ALLOWMODES_ANY for any mode, ALLOWMODES_DEFAULT for 
951  *                        only permitting legitimate default user modes.
952  * @return Zero.
953  */
954 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, 
955                 char *parv[], int allow_modes)
956 {
957   char** p;
958   char*  m;
959   int what;
960   int i;
961   struct Flags setflags;
962   unsigned int tmpmask = 0;
963   int snomask_given = 0;
964   char buf[BUFSIZE];
965   int prop = 0;
966   int do_host_hiding = 0;
967   char* account = NULL;
968
969   what = MODE_ADD;
970
971   if (parc < 3)
972   {
973     m = buf;
974     *m++ = '+';
975     for (i = 0; i < USERMODELIST_SIZE; i++)
976     {
977       if (HasFlag(sptr, userModeList[i].flag) &&
978           userModeList[i].flag != FLAG_ACCOUNT)
979         *m++ = userModeList[i].c;
980     }
981     *m = '\0';
982     send_reply(sptr, RPL_UMODEIS, buf);
983     if (HasFlag(sptr, FLAG_SERVNOTICE) && MyConnect(sptr)
984         && cli_snomask(sptr) !=
985         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
986       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
987     return 0;
988   }
989
990   /*
991    * find flags already set for user
992    * why not just copy them?
993    */
994   setflags = cli_flags(sptr);
995
996   if (MyConnect(sptr))
997     tmpmask = cli_snomask(sptr);
998
999   /*
1000    * parse mode change string(s)
1001    */
1002   for (p = &parv[2]; *p && p<&parv[parc]; p++) {       /* p is changed in loop too */
1003     for (m = *p; *m; m++) {
1004       switch (*m) {
1005       case '+':
1006         what = MODE_ADD;
1007         break;
1008       case '-':
1009         what = MODE_DEL;
1010         break;
1011       case 's':
1012         if (*(p + 1) && is_snomask(*(p + 1))) {
1013           snomask_given = 1;
1014           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1015           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1016         }
1017         else
1018           tmpmask = (what == MODE_ADD) ?
1019               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1020         if (tmpmask)
1021           SetServNotice(sptr);
1022         else
1023           ClearServNotice(sptr);
1024         break;
1025       case 'w':
1026         if (what == MODE_ADD)
1027           SetWallops(sptr);
1028         else
1029           ClearWallops(sptr);
1030         break;
1031       case 'o':
1032         if (what == MODE_ADD)
1033           SetOper(sptr);
1034         else {
1035           ClrFlag(sptr, FLAG_OPER);
1036           ClrFlag(sptr, FLAG_LOCOP);
1037           if (MyConnect(sptr))
1038           {
1039             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1040             cli_handler(sptr) = CLIENT_HANDLER;
1041           }
1042         }
1043         break;
1044       case 'O':
1045         if (what == MODE_ADD)
1046           SetLocOp(sptr);
1047         else
1048         { 
1049           ClrFlag(sptr, FLAG_OPER);
1050           ClrFlag(sptr, FLAG_LOCOP);
1051           if (MyConnect(sptr))
1052           {
1053             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1054             cli_handler(sptr) = CLIENT_HANDLER;
1055           }
1056         }
1057         break;
1058       case 'i':
1059         if (what == MODE_ADD)
1060           SetInvisible(sptr);
1061         else
1062           ClearInvisible(sptr);
1063         break;
1064       case 'd':
1065         if (what == MODE_ADD)
1066           SetDeaf(sptr);
1067         else
1068           ClearDeaf(sptr);
1069         break;
1070       case 'k':
1071         if (what == MODE_ADD)
1072           SetChannelService(sptr);
1073         else
1074           ClearChannelService(sptr);
1075         break;
1076       case 'g':
1077         if (what == MODE_ADD)
1078           SetDebug(sptr);
1079         else
1080           ClearDebug(sptr);
1081         break;
1082       case 'x':
1083         if (what == MODE_ADD)
1084           do_host_hiding = 1;
1085       case 'S':
1086         if (what == MODE_ADD)
1087           SetSSLConn(sptr);
1088         else
1089           ClearSSLConn(sptr);
1090         break;
1091         break;
1092       case 'r':
1093         if (*(p + 1) && (what == MODE_ADD)) {
1094           account = *(++p);
1095           SetAccount(sptr);
1096         }
1097         /* There is no -r */
1098         break;
1099       default:
1100         send_reply(sptr, ERR_UMODEUNKNOWNFLAG, *m);
1101         break;
1102       }
1103     }
1104   }
1105   /*
1106    * Evaluate rules for new user mode
1107    * Stop users making themselves operators too easily:
1108    */
1109   if (!IsServer(cptr))
1110   {
1111     if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr))
1112       ClearOper(sptr);
1113     if (!FlagHas(&setflags, FLAG_LOCOP) && IsLocOp(sptr))
1114       ClearLocOp(sptr);
1115     if (!FlagHas(&setflags, FLAG_ACCOUNT) && IsAccount(sptr))
1116       ClrFlag(sptr, FLAG_ACCOUNT);
1117     if (!FlagHas(&setflags, FLAG_SSLCONN) && IsSSLConn(sptr))
1118       ClrFlag(sptr, FLAG_SSLCONN);
1119     else if (FlagHas(&setflags, FLAG_SSLCONN) && !IsSSLConn(sptr))
1120       SetFlag(sptr, FLAG_SSLCONN);
1121     /*
1122      * new umode; servers can set it, local users cannot;
1123      * prevents users from /kick'ing or /mode -o'ing
1124      */
1125     if (!FlagHas(&setflags, FLAG_CHSERV))
1126       ClearChannelService(sptr);
1127     /*
1128      * only send wallops to opers
1129      */
1130     if (feature_bool(FEAT_WALLOPS_OPER_ONLY) && !IsAnOper(sptr) &&
1131         !FlagHas(&setflags, FLAG_WALLOP))
1132       ClearWallops(sptr);
1133     if (feature_bool(FEAT_HIS_SNOTICES_OPER_ONLY) && MyConnect(sptr) &&
1134         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_SERVNOTICE))
1135     {
1136       ClearServNotice(sptr);
1137       set_snomask(sptr, 0, SNO_SET);
1138     }
1139     if (feature_bool(FEAT_HIS_DEBUG_OPER_ONLY) &&
1140         !IsAnOper(sptr) && !FlagHas(&setflags, FLAG_DEBUG))
1141       ClearDebug(sptr);
1142   }
1143   if (MyConnect(sptr))
1144   {
1145     if ((FlagHas(&setflags, FLAG_OPER) || FlagHas(&setflags, FLAG_LOCOP)) &&
1146         !IsAnOper(sptr))
1147     {
1148       det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPERATOR);
1149       client_set_privs(sptr, NULL);
1150     }
1151
1152     if (SendServNotice(sptr))
1153     {
1154       if (tmpmask != cli_snomask(sptr))
1155         set_snomask(sptr, tmpmask, SNO_SET);
1156       if (cli_snomask(sptr) && snomask_given)
1157         send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1158     }
1159     else
1160       set_snomask(sptr, 0, SNO_SET);
1161   }
1162   /*
1163    * Compare new flags with old flags and send string which
1164    * will cause servers to update correctly.
1165    */
1166   if (!FlagHas(&setflags, FLAG_ACCOUNT) && IsAccount(sptr)) {
1167       int len = ACCOUNTLEN;
1168       char *ts;
1169       if ((ts = strchr(account, ':'))) {
1170         len = (ts++) - account;
1171         cli_user(sptr)->acc_create = atoi(ts);
1172         Debug((DEBUG_DEBUG, "Received timestamped account in user mode; "
1173               "account \"%s\", timestamp %Tu", account,
1174               cli_user(sptr)->acc_create));
1175       }
1176       ircd_strncpy(cli_user(sptr)->account, account, len);
1177   }
1178   if (!FlagHas(&setflags, FLAG_HIDDENHOST) && do_host_hiding && allow_modes != ALLOWMODES_DEFAULT)
1179     hide_hostmask(sptr, FLAG_HIDDENHOST);
1180
1181   if (IsRegistered(sptr)) {
1182     if (!FlagHas(&setflags, FLAG_OPER) && IsOper(sptr)) {
1183       /* user now oper */
1184       ++UserStats.opers;
1185       client_set_privs(sptr, NULL); /* may set propagate privilege */
1186     }
1187     /* remember propagate privilege setting */
1188     if (HasPriv(sptr, PRIV_PROPAGATE)) {
1189       prop = 1;
1190     }
1191     if (FlagHas(&setflags, FLAG_OPER) && !IsOper(sptr)) {
1192       /* user no longer oper */
1193       assert(UserStats.opers > 0);
1194       --UserStats.opers;
1195       client_set_privs(sptr, NULL); /* will clear propagate privilege */
1196     }
1197     if (FlagHas(&setflags, FLAG_INVISIBLE) && !IsInvisible(sptr)) {
1198       assert(UserStats.inv_clients > 0);
1199       --UserStats.inv_clients;
1200     }
1201     if (!FlagHas(&setflags, FLAG_INVISIBLE) && IsInvisible(sptr)) {
1202       ++UserStats.inv_clients;
1203     }
1204     assert(UserStats.opers <= UserStats.clients + UserStats.unknowns);
1205     assert(UserStats.inv_clients <= UserStats.clients + UserStats.unknowns);
1206     send_umode_out(cptr, sptr, &setflags, prop);
1207   }
1208
1209   return 0;
1210 }
1211
1212 /** Build a mode string to describe modes for \a cptr.
1213  * @param[in] cptr Some user.
1214  * @return Pointer to a static buffer.
1215  */
1216 char *umode_str(struct Client *cptr)
1217 {
1218   /* Maximum string size: "owidgrx\0" */
1219   char *m = umodeBuf;
1220   int i;
1221   struct Flags c_flags = cli_flags(cptr);
1222
1223   if (!HasPriv(cptr, PRIV_PROPAGATE))
1224     FlagClr(&c_flags, FLAG_OPER);
1225
1226   for (i = 0; i < USERMODELIST_SIZE; ++i)
1227   {
1228     if (FlagHas(&c_flags, userModeList[i].flag) &&
1229         userModeList[i].flag >= FLAG_GLOBAL_UMODES)
1230       *m++ = userModeList[i].c;
1231   }
1232
1233   if (IsAccount(cptr))
1234   {
1235     char* t = cli_user(cptr)->account;
1236
1237     *m++ = ' ';
1238     while ((*m++ = *t++))
1239       ; /* Empty loop */
1240
1241     if (cli_user(cptr)->acc_create) {
1242       char nbuf[20];
1243       Debug((DEBUG_DEBUG, "Sending timestamped account in user mode for "
1244              "account \"%s\"; timestamp %Tu", cli_user(cptr)->account,
1245              cli_user(cptr)->acc_create));
1246       ircd_snprintf(0, t = nbuf, sizeof(nbuf), ":%Tu",
1247                     cli_user(cptr)->acc_create);
1248       m--; /* back up over previous nul-termination */
1249       while ((*m++ = *t++))
1250         ; /* Empty loop */
1251     }
1252   }
1253
1254   *m = '\0';
1255
1256   return umodeBuf;                /* Note: static buffer, gets
1257                                    overwritten by send_umode() */
1258 }
1259
1260 /** Send a mode change string for \a sptr to \a cptr.
1261  * @param[in] cptr Destination of mode change message.
1262  * @param[in] sptr User whose mode has changed.
1263  * @param[in] old Pre-change set of modes for \a sptr.
1264  * @param[in] sendset One of ALL_UMODES, SEND_UMODES_BUT_OPER,
1265  * SEND_UMODES, to select which changed user modes to send.
1266  */
1267 void send_umode(struct Client *cptr, struct Client *sptr, struct Flags *old,
1268                 int sendset)
1269 {
1270   int i;
1271   int flag;
1272   char *m;
1273   int what = MODE_NULL;
1274
1275   /*
1276    * Build a string in umodeBuf to represent the change in the user's
1277    * mode between the new (cli_flags(sptr)) and 'old', but skipping
1278    * the modes indicated by sendset.
1279    */
1280   m = umodeBuf;
1281   *m = '\0';
1282   for (i = 0; i < USERMODELIST_SIZE; ++i)
1283   {
1284     flag = userModeList[i].flag;
1285     if (FlagHas(old, flag)
1286         == HasFlag(sptr, flag))
1287       continue;
1288     switch (sendset)
1289     {
1290     case ALL_UMODES:
1291       break;
1292     case SEND_UMODES_BUT_OPER:
1293       if (flag == FLAG_OPER)
1294         continue;
1295       /* and fall through */
1296     case SEND_UMODES:
1297       if (flag < FLAG_GLOBAL_UMODES)
1298         continue;
1299       break;      
1300     }
1301     if (FlagHas(old, flag))
1302     {
1303       if (what == MODE_DEL)
1304         *m++ = userModeList[i].c;
1305       else
1306       {
1307         what = MODE_DEL;
1308         *m++ = '-';
1309         *m++ = userModeList[i].c;
1310       }
1311     }
1312     else /* !FlagHas(old, flag) */
1313     {
1314       if (what == MODE_ADD)
1315         *m++ = userModeList[i].c;
1316       else
1317       {
1318         what = MODE_ADD;
1319         *m++ = '+';
1320         *m++ = userModeList[i].c;
1321       }
1322     }
1323   }
1324   *m = '\0';
1325   if (*umodeBuf && cptr)
1326     sendcmdto_one(sptr, CMD_MODE, cptr, "%s :%s", cli_name(sptr), umodeBuf);
1327 }
1328
1329 /**
1330  * Check to see if this resembles a sno_mask.  It is if 1) there is
1331  * at least one digit and 2) The first digit occurs before the first
1332  * alphabetic character.
1333  * @param[in] word Word to check for sno_mask-ness.
1334  * @return Non-zero if \a word looks like a server notice mask; zero if not.
1335  */
1336 int is_snomask(char *word)
1337 {
1338   if (word)
1339   {
1340     for (; *word; word++)
1341       if (IsDigit(*word))
1342         return 1;
1343       else if (IsAlpha(*word))
1344         return 0;
1345   }
1346   return 0;
1347 }
1348
1349 /** Update snomask \a oldmask according to \a arg and \a what.
1350  * @param[in] oldmask Original user mask.
1351  * @param[in] arg Update string (either a number or '+'/'-' followed by a number).
1352  * @param[in] what MODE_ADD if adding the mask.
1353  * @return New value of service notice mask.
1354  */
1355 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1356 {
1357   unsigned int sno_what;
1358   unsigned int newmask;
1359   if (*arg == '+')
1360   {
1361     arg++;
1362     if (what == MODE_ADD)
1363       sno_what = SNO_ADD;
1364     else
1365       sno_what = SNO_DEL;
1366   }
1367   else if (*arg == '-')
1368   {
1369     arg++;
1370     if (what == MODE_ADD)
1371       sno_what = SNO_DEL;
1372     else
1373       sno_what = SNO_ADD;
1374   }
1375   else
1376     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1377   /* pity we don't have strtoul everywhere */
1378   newmask = (unsigned int)atoi(arg);
1379   if (sno_what == SNO_DEL)
1380     newmask = oldmask & ~newmask;
1381   else if (sno_what == SNO_ADD)
1382     newmask |= oldmask;
1383   return newmask;
1384 }
1385
1386 /** Remove \a cptr from the singly linked list \a list.
1387  * @param[in] cptr Client to remove from list.
1388  * @param[in,out] list Pointer to head of list containing \a cptr.
1389  */
1390 static void delfrom_list(struct Client *cptr, struct SLink **list)
1391 {
1392   struct SLink* tmp;
1393   struct SLink* prv = NULL;
1394
1395   for (tmp = *list; tmp; tmp = tmp->next) {
1396     if (tmp->value.cptr == cptr) {
1397       if (prv)
1398         prv->next = tmp->next;
1399       else
1400         *list = tmp->next;
1401       free_link(tmp);
1402       break;
1403     }
1404     prv = tmp;
1405   }
1406 }
1407
1408 /** Set \a cptr's server notice mask, according to \a what.
1409  * @param[in,out] cptr Client whose snomask is updating.
1410  * @param[in] newmask Base value for new snomask.
1411  * @param[in] what One of SNO_ADD, SNO_DEL, SNO_SET, to choose operation.
1412  */
1413 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1414 {
1415   unsigned int oldmask, diffmask;        /* unsigned please */
1416   int i;
1417   struct SLink *tmp;
1418
1419   oldmask = cli_snomask(cptr);
1420
1421   if (what == SNO_ADD)
1422     newmask |= oldmask;
1423   else if (what == SNO_DEL)
1424     newmask = oldmask & ~newmask;
1425   else if (what != SNO_SET)        /* absolute set, no math needed */
1426     sendto_opmask_butone(0, SNO_OLDSNO, "setsnomask called with %d ?!", what);
1427
1428   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1429
1430   diffmask = oldmask ^ newmask;
1431
1432   for (i = 0; diffmask >> i; i++) {
1433     if (((diffmask >> i) & 1))
1434     {
1435       if (((newmask >> i) & 1))
1436       {
1437         tmp = make_link();
1438         tmp->next = opsarray[i];
1439         tmp->value.cptr = cptr;
1440         opsarray[i] = tmp;
1441       }
1442       else
1443         /* not real portable :( */
1444         delfrom_list(cptr, &opsarray[i]);
1445     }
1446   }
1447   cli_snomask(cptr) = newmask;
1448 }
1449
1450 /** Check whether \a sptr is allowed to send a message to \a acptr.
1451  * If \a sptr is a remote user, it means some server has an outdated
1452  * SILENCE list for \a acptr, so send the missing SILENCE mask(s) back
1453  * in the direction of \a sptr.  Skip the check if \a sptr is a server.
1454  * @param[in] sptr Client trying to send a message.
1455  * @param[in] acptr Destination of message.
1456  * @return Non-zero if \a sptr is SILENCEd by \a acptr, zero if not.
1457  */
1458 int is_silenced(struct Client *sptr, struct Client *acptr)
1459 {
1460   struct Ban *found;
1461   struct User *user;
1462   size_t buf_used, slen;
1463   char buf[BUFSIZE];
1464
1465   if (IsServer(sptr) || !(user = cli_user(acptr))
1466       || !(found = find_ban(sptr, user->silence)))
1467     return 0;
1468   assert(!(found->flags & BAN_EXCEPTION));
1469   if (!MyConnect(sptr)) {
1470     /* Buffer positive silence to send back. */
1471     buf_used = strlen(found->banstr);
1472     memcpy(buf, found->banstr, buf_used);
1473     /* Add exceptions to buffer. */
1474     for (found = user->silence; found; found = found->next) {
1475       if (!(found->flags & BAN_EXCEPTION))
1476         continue;
1477       slen = strlen(found->banstr);
1478       if (buf_used + slen + 4 > 400) {
1479         buf[buf_used] = '\0';
1480         sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1481         buf_used = 0;
1482       }
1483       if (buf_used)
1484         buf[buf_used++] = ',';
1485       buf[buf_used++] = '+';
1486       buf[buf_used++] = '~';
1487       memcpy(buf + buf_used, found->banstr, slen);
1488       buf_used += slen;
1489     }
1490     /* Flush silence buffer. */
1491     if (buf_used) {
1492       buf[buf_used] = '\0';
1493       sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr, buf);
1494       buf_used = 0;
1495     }
1496   }
1497   return 1;
1498 }
1499
1500 /** Send RPL_ISUPPORT lines to \a cptr.
1501  * @param[in] cptr Client to send ISUPPORT to.
1502  * @return Zero.
1503  */
1504 int
1505 send_supported(struct Client *cptr)
1506 {
1507   char featurebuf[512];
1508
1509   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES1, FEATURESVALUES1);
1510   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1511   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES2, FEATURESVALUES2);
1512   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1513
1514   return 0; /* convenience return, if it's ever needed */
1515 }
1516
1517 /* vim: shiftwidth=2 
1518  */