Author: Ghostwolf <foxxe@wtfs.net>
[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  * $Id$
24  */
25 #include "config.h"
26
27 #include "s_user.h"
28 #include "IPcheck.h"
29 #include "channel.h"
30 #include "class.h"
31 #include "client.h"
32 #include "hash.h"
33 #include "ircd.h"
34 #include "ircd_alloc.h"
35 #include "ircd_chattr.h"
36 #include "ircd_features.h"
37 #include "ircd_log.h"
38 #include "ircd_policy.h"
39 #include "ircd_reply.h"
40 #include "ircd_snprintf.h"
41 #include "ircd_string.h"
42 #include "list.h"
43 #include "match.h"
44 #include "motd.h"
45 #include "msg.h"
46 #include "msgq.h"
47 #include "numeric.h"
48 #include "numnicks.h"
49 #include "parse.h"
50 #include "querycmds.h"
51 #include "random.h"
52 #include "s_bsd.h"
53 #include "s_conf.h"
54 #include "s_debug.h"
55 #include "s_misc.h"
56 #include "s_serv.h" /* max_client_count */
57 #include "send.h"
58 #include "struct.h"
59 #include "support.h"
60 #include "supported.h"
61 #include "sys.h"
62 #include "userload.h"
63 #include "version.h"
64 #include "whowas.h"
65
66 #include "handlers.h" /* m_motd and m_lusers */
67
68 #include <assert.h>
69 #include <fcntl.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <sys/stat.h>
74
75
76 static int userCount = 0;
77
78 /*
79  * 'make_user' add's an User information block to a client
80  * if it was not previously allocated.
81  */
82 struct User *make_user(struct Client *cptr)
83 {
84   assert(0 != cptr);
85
86   if (!cli_user(cptr)) {
87     cli_user(cptr) = (struct User*) MyMalloc(sizeof(struct User));
88     assert(0 != cli_user(cptr));
89
90     /* All variables are 0 by default */
91     memset(cli_user(cptr), 0, sizeof(struct User));
92 #ifdef  DEBUGMODE
93     ++userCount;
94 #endif
95     cli_user(cptr)->refcnt = 1;
96   }
97   return cli_user(cptr);
98 }
99
100 /*
101  * free_user
102  *
103  * Decrease user reference count by one and release block, if count reaches 0.
104  */
105 void free_user(struct User* user)
106 {
107   assert(0 != user);
108   assert(0 < user->refcnt);
109
110   if (--user->refcnt == 0) {
111     if (user->away)
112       MyFree(user->away);
113     /*
114      * sanity check
115      */
116     assert(0 == user->joined);
117     assert(0 == user->invited);
118     assert(0 == user->channel);
119
120     MyFree(user);
121 #ifdef  DEBUGMODE
122     --userCount;
123 #endif
124   }
125 }
126
127 void user_count_memory(size_t* count_out, size_t* bytes_out)
128 {
129   assert(0 != count_out);
130   assert(0 != bytes_out);
131   *count_out = userCount;
132   *bytes_out = userCount * sizeof(struct User);
133 }
134
135
136 /*
137  * next_client
138  *
139  * Local function to find the next matching client. The search
140  * can be continued from the specified client entry. Normal
141  * usage loop is:
142  *
143  * for (x = client; x = next_client(x,mask); x = x->next)
144  *     HandleMatchingClient;
145  *
146  */
147 struct Client *next_client(struct Client *next, const char* ch)
148 {
149   struct Client *tmp = next;
150
151   if (!tmp)
152     return NULL;
153
154   next = FindClient(ch);
155   next = next ? next : tmp;
156   if (cli_prev(tmp) == next)
157     return NULL;
158   if (next != tmp)
159     return next;
160   for (; next; next = cli_next(next))
161     if (!match(ch, cli_name(next)))
162       break;
163   return next;
164 }
165
166 /*
167  * hunt_server
168  *
169  *    Do the basic thing in delivering the message (command)
170  *    across the relays to the specific server (server) for
171  *    actions.
172  *
173  *    Note:   The command is a format string and *MUST* be
174  *            of prefixed style (e.g. ":%s COMMAND %s ...").
175  *            Command can have only max 8 parameters.
176  *
177  *    server  parv[server] is the parameter identifying the
178  *            target server.
179  *
180  *    *WARNING*
181  *            parv[server] is replaced with the pointer to the
182  *            real servername from the matched client (I'm lazy
183  *            now --msa).
184  *
185  *    returns: (see #defines)
186  */
187 int hunt_server_cmd(struct Client *from, const char *cmd, const char *tok,
188                     struct Client *one, int MustBeOper, const char *pattern,
189                     int server, int parc, char *parv[])
190 {
191   struct Client *acptr;
192   char *to;
193
194   /* Assume it's me, if no server or an unregistered client */
195   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
196     return (HUNTED_ISME);
197
198   if (MustBeOper && !IsPrivileged(from))
199   {
200     send_reply(from, ERR_NOPRIVILEGES);
201     return HUNTED_NOSUCH;
202   }
203
204   /* Make sure it's a server */
205   if (MyUser(from)) {
206     /* Make sure it's a server */
207     if (!strchr(to, '*')) {
208       if (0 == (acptr = FindClient(to)))
209         return HUNTED_NOSUCH;
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     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
219
220   if (IsMe(acptr))
221     return (HUNTED_ISME);
222
223   if (MustBeOper && !IsPrivileged(from)) {
224     send_reply(from, ERR_NOPRIVILEGES);
225     return HUNTED_NOSUCH;
226   }
227
228   assert(!IsServer(from));
229
230   parv[server] = (char *) acptr; /* HACK! HACK! HACK! ARGH! */
231
232   sendcmdto_one(from, cmd, tok, acptr, pattern, parv[1], parv[2], parv[3],
233                 parv[4], parv[5], parv[6], parv[7], parv[8]);
234
235   return (HUNTED_PASS);
236 }
237
238 int hunt_server_prio_cmd(struct Client *from, const char *cmd, const char *tok,
239                          struct Client *one, int MustBeOper,
240                          const char *pattern, int server, int parc,
241                          char *parv[])
242 {
243   struct Client *acptr;
244   char *to;
245
246   /* Assume it's me, if no server or an unregistered client */
247   if (parc <= server || EmptyString((to = parv[server])) || IsUnknown(from))
248     return (HUNTED_ISME);
249
250   /* Make sure it's a server */
251   if (MyUser(from)) {
252     /* Make sure it's a server */
253     if (!strchr(to, '*')) {
254       if (0 == (acptr = FindClient(to)))
255         return HUNTED_NOSUCH;
256
257       if (cli_user(acptr))
258         acptr = cli_user(acptr)->server;
259     } else if (!(acptr = find_match_server(to))) {
260       send_reply(from, ERR_NOSUCHSERVER, to);
261       return (HUNTED_NOSUCH);
262     }
263   } else if (!(acptr = FindNServer(to)))
264     return (HUNTED_NOSUCH);        /* Server broke off in the meantime */
265
266   if (IsMe(acptr))
267     return (HUNTED_ISME);
268
269   if (MustBeOper && !IsPrivileged(from)) {
270     send_reply(from, ERR_NOPRIVILEGES);
271     return HUNTED_NOSUCH;
272   }
273
274   assert(!IsServer(from));
275
276   parv[server] = (char *) acptr; /* HACK! HACK! HACK! ARGH! */
277
278   sendcmdto_prio_one(from, cmd, tok, acptr, pattern, parv[1], parv[2], parv[3],
279                      parv[4], parv[5], parv[6], parv[7], parv[8]);
280
281   return (HUNTED_PASS);
282 }
283
284 /*
285  * 'do_nick_name' ensures that the given parameter (nick) is really a proper
286  * string for a nickname (note, the 'nick' may be modified in the process...)
287  *
288  * RETURNS the length of the final NICKNAME (0, if nickname is invalid)
289  *
290  * Nickname characters are in range 'A'..'}', '_', '-', '0'..'9'
291  *  anything outside the above set will terminate nickname.
292  * In addition, the first character cannot be '-' or a Digit.
293  *
294  * Note:
295  *  The '~'-character should be allowed, but a change should be global,
296  *  some confusion would result if only few servers allowed it...
297  */
298 int do_nick_name(char* nick)
299 {
300   char* ch  = nick;
301   char* end = ch + NICKLEN;
302   assert(0 != ch);
303
304   if (*ch == '-' || IsDigit(*ch))        /* first character in [0..9-] */
305     return 0;
306
307   for ( ; (ch < end) && *ch; ++ch)
308     if (!IsNickChar(*ch))
309       break;
310
311   *ch = '\0';
312
313   return (ch - nick);
314 }
315
316 /*
317  * clean_user_id
318  *
319  * Copy `source' to `dest', replacing all occurances of '~' and characters that
320  * are not `isIrcUi' by an underscore.
321  * Copies at most USERLEN - 1 characters or up till the first control character.
322  * If `tilde' is true, then a tilde is prepended to `dest'.
323  * Note that `dest' and `source' can point to the same area or to different
324  * non-overlapping areas.
325  */
326 static char *clean_user_id(char *dest, char *source, int tilde)
327 {
328   char ch;
329   char *d = dest;
330   char *s = source;
331   int rlen = USERLEN;
332
333   ch = *s++;                        /* Store first character to copy: */
334   if (tilde)
335   {
336     *d++ = '~';                        /* If `dest' == `source', then this overwrites `ch' */
337     --rlen;
338   }
339   while (ch && !IsCntrl(ch) && rlen--)
340   {
341     char nch = *s++;        /* Store next character to copy */
342     *d++ = IsUserChar(ch) ? ch : '_';        /* This possibly overwrites it */
343     if (nch == '~')
344       ch = '_';
345     else
346       ch = nch;
347   }
348   *d = 0;
349   return dest;
350 }
351
352 /*
353  * register_user
354  *
355  * This function is called when both NICK and USER messages
356  * have been accepted for the client, in whatever order. Only
357  * after this the USER message is propagated.
358  *
359  * NICK's must be propagated at once when received, although
360  * it would be better to delay them too until full info is
361  * available. Doing it is not so simple though, would have
362  * to implement the following:
363  *
364  * 1) user telnets in and gives only "NICK foobar" and waits
365  * 2) another user far away logs in normally with the nick
366  *    "foobar" (quite legal, as this server didn't propagate it).
367  * 3) now this server gets nick "foobar" from outside, but
368  *    has already the same defined locally. Current server
369  *    would just issue "KILL foobar" to clean out dups. But,
370  *    this is not fair. It should actually request another
371  *    nick from local user or kill him/her...
372  */
373 int register_user(struct Client *cptr, struct Client *sptr,
374                   const char *nick, char *username)
375 {
376   struct ConfItem* aconf;
377   char*            parv[3];
378   char*            tmpstr;
379   char*            tmpstr2;
380   char             c = 0;    /* not alphanum */
381   char             d = 'a';  /* not a digit */
382   short            upper = 0;
383   short            lower = 0;
384   short            pos = 0;
385   short            leadcaps = 0;
386   short            other = 0;
387   short            digits = 0;
388   short            badid = 0;
389   short            digitgroups = 0;
390   struct User*     user = cli_user(sptr);
391   char             ip_base64[8];
392
393   user->last = CurrentTime;
394   parv[0] = cli_name(sptr);
395   parv[1] = parv[2] = NULL;
396
397   if (MyConnect(sptr))
398   {
399     static time_t last_too_many1;
400     static time_t last_too_many2;
401
402     assert(cptr == sptr);
403     switch (conf_check_client(sptr))
404     {
405       case ACR_OK:
406         break;
407       case ACR_NO_AUTHORIZATION:
408         sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
409                              get_client_name(sptr, HIDE_IP));
410         ++ServerStats->is_ref;
411         return exit_client(cptr, sptr, &me,
412                            "No Authorization - use another server");
413       case ACR_TOO_MANY_IN_CLASS:
414         if (CurrentTime - last_too_many1 >= (time_t) 60)
415         {
416           last_too_many1 = CurrentTime;
417           sendto_opmask_butone(0, SNO_TOOMANY, "Too many connections in "
418                                "class %i for %s.", get_client_class(sptr),
419                                get_client_name(sptr, SHOW_IP));
420         }
421         ++ServerStats->is_ref;
422         IPcheck_connect_fail(cli_ip(sptr));
423         return exit_client(cptr, sptr, &me,
424                            "Sorry, your connection class is full - try "
425                            "again later or try another server");
426       case ACR_TOO_MANY_FROM_IP:
427         if (CurrentTime - last_too_many2 >= (time_t) 60)
428         {
429           last_too_many2 = CurrentTime;
430           sendto_opmask_butone(0, SNO_TOOMANY, "Too many connections from "
431                                "same IP for %s.",
432                                get_client_name(sptr, SHOW_IP));
433         }
434         ++ServerStats->is_ref;
435         return exit_client(cptr, sptr, &me,
436                            "Too many connections from your host");
437       case ACR_ALREADY_AUTHORIZED:
438         /* Can this ever happen? */
439       case ACR_BAD_SOCKET:
440         ++ServerStats->is_ref;
441         IPcheck_connect_fail(cli_ip(sptr));
442         return exit_client(cptr, sptr, &me, "Unknown error -- Try again");
443     }
444     ircd_strncpy(user->host, cli_sockhost(sptr), HOSTLEN);
445     ircd_strncpy(user->realhost, cli_sockhost(sptr), HOSTLEN);
446     aconf = cli_confs(sptr)->value.aconf;
447
448     clean_user_id(user->username,
449         (cli_flags(sptr) & FLAGS_GOTID) ? cli_username(sptr) : username,
450         (cli_flags(sptr) & FLAGS_DOID) && !(cli_flags(sptr) & FLAGS_GOTID));
451
452     if ((user->username[0] == '\0')
453         || ((user->username[0] == '~') && (user->username[1] == '\000')))
454       return exit_client(cptr, sptr, &me, "USER: Bogus userid.");
455
456     if (!EmptyString(aconf->passwd)
457         && !(IsDigit(*aconf->passwd) && !aconf->passwd[1])
458         && strcmp(cli_passwd(sptr), aconf->passwd))
459     {
460       ServerStats->is_ref++;
461       IPcheck_connect_fail(cli_ip(sptr));
462       send_reply(sptr, ERR_PASSWDMISMATCH);
463       return exit_client(cptr, sptr, &me, "Bad Password");
464     }
465     memset(cli_passwd(sptr), 0, sizeof(cli_passwd(sptr)));
466     /*
467      * following block for the benefit of time-dependent K:-lines
468      */
469     if (find_kill(sptr)) {
470       ServerStats->is_ref++;
471       IPcheck_connect_fail(cli_ip(sptr));
472       return exit_client(cptr, sptr, &me, "K-lined");
473     }
474     /*
475      * Check for mixed case usernames, meaning probably hacked.  Jon2 3-94
476      * Summary of rules now implemented in this patch:         Ensor 11-94
477      * In a mixed-case name, if first char is upper, one more upper may
478      * appear anywhere.  (A mixed-case name *must* have an upper first
479      * char, and may have one other upper.)
480      * A third upper may appear if all 3 appear at the beginning of the
481      * name, separated only by "others" (-/_/.).
482      * A single group of digits is allowed anywhere.
483      * Two groups of digits are allowed if at least one of the groups is
484      * at the beginning or the end.
485      * Only one '-', '_', or '.' is allowed (or two, if not consecutive).
486      * But not as the first or last char.
487      * No other special characters are allowed.
488      * Name must contain at least one letter.
489      */
490     tmpstr2 = tmpstr = (username[0] == '~' ? &username[1] : username);
491     while (*tmpstr && !badid)
492     {
493       pos++;
494       c = *tmpstr;
495       tmpstr++;
496       if (IsLower(c))
497       {
498         lower++;
499       }
500       else if (IsUpper(c))
501       {
502         upper++;
503         if ((leadcaps || pos == 1) && !lower && !digits)
504           leadcaps++;
505       }
506       else if (IsDigit(c))
507       {
508         digits++;
509         if (pos == 1 || !IsDigit(d))
510         {
511           digitgroups++;
512           if (digitgroups > 2)
513             badid = 1;
514         }
515       }
516       else if (c == '-' || c == '_' || c == '.')
517       {
518         other++;
519         if (pos == 1)
520           badid = 1;
521         else if (d == '-' || d == '_' || d == '.' || other > 2)
522           badid = 1;
523       }
524       else
525         badid = 1;
526       d = c;
527     }
528     if (!badid)
529     {
530       if (lower && upper && (!leadcaps || leadcaps > 3 ||
531           (upper > 2 && upper > leadcaps)))
532         badid = 1;
533       else if (digitgroups == 2 && !(IsDigit(tmpstr2[0]) || IsDigit(c)))
534         badid = 1;
535       else if ((!lower && !upper) || !IsAlnum(c))
536         badid = 1;
537     }
538     if (badid && (!(cli_flags(sptr) & FLAGS_GOTID) ||
539         strcmp(cli_username(sptr), username) != 0))
540     {
541       ServerStats->is_ref++;
542
543       send_reply(cptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
544                  ":Your username is invalid.");
545       send_reply(cptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
546                  ":Connect with your real username, in lowercase.");
547       send_reply(cptr, SND_EXPLICIT | ERR_INVALIDUSERNAME,
548                  ":If your mail address were foo@bar.com, your username "
549                  "would be foo.");
550       return exit_client(cptr, sptr, &me, "USER: Bad username");
551     }
552     Count_unknownbecomesclient(sptr, UserStats);
553   }
554   else {
555     ircd_strncpy(user->username, username, USERLEN);
556     Count_newremoteclient(UserStats, user->server);
557   }
558   SetUser(sptr);
559
560   if (IsInvisible(sptr))
561     ++UserStats.inv_clients;
562   if (IsOper(sptr))
563     ++UserStats.opers;
564
565   if (MyConnect(sptr)) {
566     cli_handler(sptr) = CLIENT_HANDLER;
567     release_dns_reply(sptr);
568
569     send_reply(sptr, RPL_WELCOME, nick);
570     /*
571      * This is a duplicate of the NOTICE but see below...
572      */
573     send_reply(sptr, RPL_YOURHOST, cli_name(&me), version);
574     send_reply(sptr, RPL_CREATED, creation);
575     send_reply(sptr, RPL_MYINFO, cli_name(&me), version);
576     send_supported(sptr);
577     m_lusers(sptr, sptr, 1, parv);
578     update_load();
579     motd_signon(sptr);
580 /*      nextping = CurrentTime; */
581     if (cli_snomask(sptr) & SNO_NOISY)
582       set_snomask(sptr, cli_snomask(sptr) & SNO_NOISY, SNO_ADD);
583     IPcheck_connect_succeeded(sptr);
584   }
585   else
586     /* if (IsServer(cptr)) */
587   {
588     struct Client *acptr;
589
590     acptr = user->server;
591     if (cli_from(acptr) != cli_from(sptr))
592     {
593       sendcmdto_one(&me, CMD_KILL, cptr, "%C :%s (%s != %s[%s])",
594                     sptr, cli_name(&me), cli_name(user->server), cli_name(cli_from(acptr)),
595                     cli_sockhost(cli_from(acptr)));
596       cli_flags(sptr) |= FLAGS_KILLED;
597       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
598     }
599     else
600       cli_flags(sptr) |= (cli_flags(acptr) & FLAGS_TS8);
601
602     /*
603      * Check to see if this user is being propogated
604      * as part of a net.burst, or is using protocol 9.
605      * FIXME: This can be speeded up - its stupid to check it for
606      * every NICK message in a burst again  --Run.
607      */
608     for (acptr = user->server; acptr != &me; acptr = cli_serv(acptr)->up) {
609       if (IsBurst(acptr) || Protocol(acptr) < 10)
610         break;
611     }
612     if (!IPcheck_remote_connect(sptr, (acptr != &me))) {
613       /*
614        * We ran out of bits to count this
615        */
616       sendcmdto_one(&me, CMD_KILL, sptr, "%C :%s (Too many connections from your host -- Ghost)",
617                     sptr, cli_name(&me));
618       return exit_client(cptr, sptr, &me,"Too many connections from your host -- throttled");
619     }
620   }
621   tmpstr = umode_str(sptr);
622   sendcmdto_serv_butone(user->server, CMD_NICK, cptr,
623                         "%s %d %Tu %s %s %s%s%s%s %s%s :%s",
624                         nick, cli_hopcount(sptr) + 1, cli_lastnick(sptr),
625                         user->username, user->realhost,
626                         *tmpstr ? "+" : "", tmpstr, *tmpstr ? " " : "",
627                         inttobase64(ip_base64, ntohl(cli_ip(sptr).s_addr), 6),
628                         NumNick(sptr), cli_info(sptr));
629   
630   /* Send umode to client */
631   if (MyUser(sptr))
632   {
633     send_umode(cptr, sptr, 0, ALL_UMODES);
634     if (cli_snomask(sptr) != SNO_DEFAULT && (cli_flags(sptr) & FLAGS_SERVNOTICE))
635       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
636   }
637
638   return 0;
639 }
640
641
642 static const struct UserMode {
643   unsigned int flag;
644   char         c;
645 } userModeList[] = {
646   { FLAGS_OPER,        'o' },
647   { FLAGS_LOCOP,       'O' },
648   { FLAGS_INVISIBLE,   'i' },
649   { FLAGS_WALLOP,      'w' },
650   { FLAGS_SERVNOTICE,  's' },
651   { FLAGS_DEAF,        'd' },
652   { FLAGS_CHSERV,      'k' },
653   { FLAGS_DEBUG,       'g' },
654   { FLAGS_ACCOUNT,     'r' },
655   { FLAGS_HIDDENHOST,  'x' }
656 };
657
658 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
659
660 /*
661  * XXX - find a way to get rid of this
662  */
663 static char umodeBuf[BUFSIZE];
664
665 int set_nick_name(struct Client* cptr, struct Client* sptr,
666                   const char* nick, int parc, char* parv[])
667 {
668   if (IsServer(sptr)) {
669     int   i;
670     const char* account = 0;
671     const char* p;
672
673     /*
674      * A server introducing a new client, change source
675      */
676     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
677     assert(0 != new_client);
678
679     cli_hopcount(new_client) = atoi(parv[2]);
680     cli_lastnick(new_client) = atoi(parv[3]);
681     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+') {
682       for (p = parv[6] + 1; *p; p++) {
683         for (i = 0; i < USERMODELIST_SIZE; ++i) {
684           if (userModeList[i].c == *p) {
685             cli_flags(new_client) |= userModeList[i].flag;
686             if (userModeList[i].flag & FLAGS_ACCOUNT)
687               account = parv[7];
688             break;
689           }
690         }
691       }
692     }
693     client_set_privs(new_client); /* set privs on user */
694     /*
695      * Set new nick name.
696      */
697     strcpy(cli_name(new_client), nick);
698     cli_user(new_client) = make_user(new_client);
699     cli_user(new_client)->server = sptr;
700     SetRemoteNumNick(new_client, parv[parc - 2]);
701     /*
702      * IP# of remote client
703      */
704     cli_ip(new_client).s_addr = htonl(base64toint(parv[parc - 3]));
705
706     add_client_to_list(new_client);
707     hAddClient(new_client);
708
709     cli_serv(sptr)->ghost = 0;        /* :server NICK means end of net.burst */
710     ircd_strncpy(cli_username(new_client), parv[4], USERLEN);
711     ircd_strncpy(cli_user(new_client)->host, parv[5], HOSTLEN);
712     ircd_strncpy(cli_user(new_client)->realhost, parv[5], HOSTLEN);
713     ircd_strncpy(cli_info(new_client), parv[parc - 1], REALLEN);
714     if (account)
715       ircd_strncpy(cli_user(new_client)->account, account, ACCOUNTLEN);
716     if (HasHiddenHost(new_client))
717       ircd_snprintf(0, cli_user(new_client)->host, HOSTLEN, "%s.%s",
718         account, feature_str(FEAT_HIDDEN_HOST));
719
720     return register_user(cptr, new_client, cli_name(new_client), parv[4]);
721   }
722   else if ((cli_name(sptr))[0]) {
723     /*
724      * Client changing its nick
725      *
726      * If the client belongs to me, then check to see
727      * if client is on any channels where it is currently
728      * banned.  If so, do not allow the nick change to occur.
729      */
730     if (MyUser(sptr)) {
731       const char* channel_name;
732       if ((channel_name = find_no_nickchange_channel(sptr))) {
733         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
734       }
735       /*
736        * Refuse nick change if the last nick change was less
737        * then 30 seconds ago. This is intended to get rid of
738        * clone bots doing NICK FLOOD. -SeKs
739        * If someone didn't change their nick for more then 60 seconds
740        * however, allow to do two nick changes immedately after another
741        * before limiting the nick flood. -Run
742        */
743       if (CurrentTime < cli_nextnick(cptr)) {
744         cli_nextnick(cptr) += 2;
745         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
746                    cli_nextnick(cptr) - CurrentTime);
747         /* Send error message */
748         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cli_name(cptr));
749         /* bounce NICK to user */
750         return 0;                /* ignore nick change! */
751       }
752       else {
753         /* Limit total to 1 change per NICK_DELAY seconds: */
754         cli_nextnick(cptr) += NICK_DELAY;
755         /* However allow _maximal_ 1 extra consecutive nick change: */
756         if (cli_nextnick(cptr) < CurrentTime)
757           cli_nextnick(cptr) = CurrentTime;
758       }
759     }
760     /*
761      * Also set 'lastnick' to current time, if changed.
762      */
763     if (0 != ircd_strcmp(parv[0], nick))
764       cli_lastnick(sptr) = (sptr == cptr) ? TStime() : atoi(parv[2]);
765
766     /*
767      * Client just changing his/her nick. If he/she is
768      * on a channel, send note of change to all clients
769      * on that channel. Propagate notice to other servers.
770      */
771     if (IsUser(sptr)) {
772       sendcmdto_common_channels_butone(sptr, CMD_NICK, NULL, ":%s", nick);
773       add_history(sptr, 1);
774       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
775                             cli_lastnick(sptr));
776     }
777     else
778       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
779
780     if ((cli_name(sptr))[0])
781       hRemClient(sptr);
782     strcpy(cli_name(sptr), nick);
783     hAddClient(sptr);
784   }
785   else {
786     /* Local client setting NICK the first time */
787
788     strcpy(cli_name(sptr), nick);
789     if (!cli_user(sptr)) {
790       cli_user(sptr) = make_user(sptr);
791       cli_user(sptr)->server = &me;
792     }
793     SetLocalNumNick(sptr);
794     hAddClient(sptr);
795
796     /*
797      * If the client hasn't gotten a cookie-ping yet,
798      * choose a cookie and send it. -record!jegelhof@cloud9.net
799      */
800     if (!cli_cookie(sptr)) {
801       do {
802         cli_cookie(sptr) = (ircrandom() & 0x7fffffff);
803       } while (!cli_cookie(sptr));
804       sendrawto_one(cptr, MSG_PING " :%u", cli_cookie(sptr));
805     }
806     else if (*(cli_user(sptr))->host && cli_cookie(sptr) == COOKIE_VERIFIED) {
807       /*
808        * USER and PONG already received, now we have NICK.
809        * register_user may reject the client and call exit_client
810        * for it - must test this and exit m_nick too !
811        */
812       cli_lastnick(sptr) = TStime();        /* Always local client */
813       if (register_user(cptr, sptr, nick, cli_user(sptr)->username) == CPTR_KILLED)
814         return CPTR_KILLED;
815     }
816   }
817   return 0;
818 }
819
820 static unsigned char hash_target(unsigned int target)
821 {
822   return (unsigned char) (target >> 16) ^ (target >> 8);
823 }
824
825 /*
826  * add_target
827  *
828  * sptr must be a local client!
829  *
830  * Cannonifies target for client `sptr'.
831  */
832 void add_target(struct Client *sptr, void *target)
833 {
834   /* Ok, this shouldn't work esp on alpha
835   */
836   unsigned char  hash = hash_target((unsigned long) target);
837   unsigned char* targets;
838   int            i;
839   assert(0 != sptr);
840   assert(cli_local(sptr));
841
842   targets = cli_targets(sptr);
843   /* 
844    * Already in table?
845    */
846   for (i = 0; i < MAXTARGETS; ++i) {
847     if (targets[i] == hash)
848       return;
849   }
850   /*
851    * New target
852    */
853   memmove(&targets[RESERVEDTARGETS + 1],
854           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
855   targets[RESERVEDTARGETS] = hash;
856 }
857
858 /*
859  * check_target_limit
860  *
861  * sptr must be a local client !
862  *
863  * Returns 'true' (1) when too many targets are addressed.
864  * Returns 'false' (0) when it's ok to send to this target.
865  */
866 int check_target_limit(struct Client *sptr, void *target, const char *name,
867     int created)
868 {
869   unsigned char hash = hash_target((unsigned long) target);
870   int            i;
871   unsigned char* targets;
872
873   assert(0 != sptr);
874   assert(cli_local(sptr));
875   targets = cli_targets(sptr);
876
877   /*
878    * Same target as last time?
879    */
880   if (targets[0] == hash)
881     return 0;
882   for (i = 1; i < MAXTARGETS; ++i) {
883     if (targets[i] == hash) {
884       memmove(&targets[1], &targets[0], i);
885       targets[0] = hash;
886       return 0;
887     }
888   }
889   /*
890    * New target
891    */
892   if (!created) {
893     if (CurrentTime < cli_nexttarget(sptr)) {
894       if (cli_nexttarget(sptr) - CurrentTime < TARGET_DELAY + 8) {
895         /*
896          * No server flooding
897          */
898         cli_nexttarget(sptr) += 2;
899         send_reply(sptr, ERR_TARGETTOOFAST, name,
900                    cli_nexttarget(sptr) - CurrentTime);
901       }
902       return 1;
903     }
904     else {
905       cli_nexttarget(sptr) += TARGET_DELAY;
906       if (cli_nexttarget(sptr) < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
907         cli_nexttarget(sptr) = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
908     }
909   }
910   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
911   targets[0] = hash;
912   return 0;
913 }
914
915 /*
916  * whisper - called from m_cnotice and m_cprivmsg.
917  *
918  * parv[0] = sender prefix
919  * parv[1] = nick
920  * parv[2] = #channel
921  * parv[3] = Private message text
922  *
923  * Added 971023 by Run.
924  * Reason: Allows channel operators to sent an arbitrary number of private
925  *   messages to users on their channel, avoiding the max.targets limit.
926  *   Building this into m_private would use too much cpu because we'd have
927  *   to a cross channel lookup for every private message!
928  * Note that we can't allow non-chan ops to use this command, it would be
929  *   abused by mass advertisers.
930  *
931  */
932 int whisper(struct Client* source, const char* nick, const char* channel,
933             const char* text, int is_notice)
934 {
935   struct Client*     dest;
936   struct Channel*    chptr;
937   struct Membership* membership;
938
939   assert(0 != source);
940   assert(0 != nick);
941   assert(0 != channel);
942   assert(MyUser(source));
943
944   if (!(dest = FindUser(nick))) {
945     return send_reply(source, ERR_NOSUCHNICK, nick);
946   }
947   if (!(chptr = FindChannel(channel))) {
948     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
949   }
950   /*
951    * compare both users channel lists, instead of the channels user list
952    * since the link is the same, this should be a little faster for channels
953    * with a lot of users
954    */
955   for (membership = cli_user(source)->channel; membership; membership = membership->next_channel) {
956     if (chptr == membership->channel)
957       break;
958   }
959   if (0 == membership) {
960     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
961   }
962   if (!IsVoicedOrOpped(membership)) {
963     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
964   }
965   /*
966    * lookup channel in destination
967    */
968   assert(0 != cli_user(dest));
969   for (membership = cli_user(dest)->channel; membership; membership = membership->next_channel) {
970     if (chptr == membership->channel)
971       break;
972   }
973   if (0 == membership || IsZombie(membership)) {
974     return send_reply(source, ERR_USERNOTINCHANNEL, cli_name(dest), chptr->chname);
975   }
976   if (is_silenced(source, dest))
977     return 0;
978           
979   if (cli_user(dest)->away)
980     send_reply(source, RPL_AWAY, cli_name(dest), cli_user(dest)->away);
981   if (is_notice)
982     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
983   else
984     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
985   return 0;
986 }
987
988
989 /*
990  * added Sat Jul 25 07:30:42 EST 1992
991  */
992 void send_umode_out(struct Client *cptr, struct Client *sptr, int old,
993                     int prop)
994 {
995   int i;
996   struct Client *acptr;
997
998   send_umode(NULL, sptr, old, SEND_UMODES & ~(prop ? 0 : FLAGS_OPER));
999
1000   for (i = HighestFd; i >= 0; i--) {
1001     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
1002         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
1003       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", cli_name(sptr), umodeBuf);
1004   }
1005   if (cptr && MyUser(cptr))
1006     send_umode(cptr, sptr, old, ALL_UMODES);
1007 }
1008
1009
1010 /*
1011  * send_user_info - send user info userip/userhost
1012  * NOTE: formatter must put info into buffer and return a pointer to the end of
1013  * the data it put in the buffer.
1014  */
1015 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
1016 {
1017   char*          name;
1018   char*          p = 0;
1019   int            arg_count = 0;
1020   int            users_found = 0;
1021   struct Client* acptr;
1022   struct MsgBuf* mb;
1023
1024   assert(0 != sptr);
1025   assert(0 != names);
1026   assert(0 != fmt);
1027
1028   mb = msgq_make(sptr, rpl_str(rpl), cli_name(&me), cli_name(sptr));
1029
1030   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
1031     if ((acptr = FindUser(name))) {
1032       if (users_found++)
1033         msgq_append(0, mb, " ");
1034       (*fmt)(acptr, mb);
1035     }
1036     if (5 == ++arg_count)
1037       break;
1038   }
1039   send_buffer(sptr, mb, 0);
1040   msgq_clean(mb);
1041 }
1042
1043 /*
1044  * hide_hostmask()
1045  *
1046  * If, after setting the flags, the user has both HiddenHost and Account
1047  * set, its hostmask is changed.
1048  */
1049 #define FLAGS_HOST_HIDDEN       (FLAGS_ACCOUNT|FLAGS_HIDDENHOST)
1050 int hide_hostmask(struct Client *cptr, unsigned int flags)
1051 {
1052   struct Membership *chan;
1053   int newflags;
1054
1055   if (MyConnect(cptr) && !feature_bool(FEAT_HOST_HIDING))
1056     flags &= ~FLAGS_HIDDENHOST;
1057     
1058   newflags = cli_flags(cptr) | flags;
1059   if ((newflags & FLAGS_HOST_HIDDEN) != FLAGS_HOST_HIDDEN) {
1060     /* The user doesn't have both flags, don't change the hostmask */
1061     cli_flags(cptr) |= flags;
1062     return 0;
1063   }
1064
1065   sendcmdto_common_channels_butone(cptr, CMD_QUIT, cptr, ":Registered");
1066   ircd_snprintf(0, cli_user(cptr)->host, HOSTLEN, "%s.%s",
1067     cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
1068   cli_flags(cptr) |= flags;
1069
1070   /*
1071    * Go through all channels the client was on, rejoin him
1072    * and set the modes, if any
1073    */
1074   for (chan = cli_user(cptr)->channel; chan; chan = chan->next_channel) {
1075     sendcmdto_channel_butserv_butone(cptr, CMD_JOIN, chan->channel, cptr,
1076       "%H", chan->channel);
1077     if (IsChanOp(chan) && HasVoice(chan)) {
1078       sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan->channel, cptr,
1079         "%H +ov %C %C", chan->channel, cptr, cptr);
1080     } else if (IsChanOp(chan) || HasVoice(chan)) {
1081       sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan->channel, cptr,
1082         "%H +%c %C", chan->channel, IsChanOp(chan) ? 'o' : 'v', cptr);
1083     }
1084   }
1085   return 0;
1086 }
1087
1088
1089 /*
1090  * set_user_mode() added 15/10/91 By Darren Reed.
1091  *
1092  * parv[0] - sender
1093  * parv[1] - username to change mode for
1094  * parv[2] - modes to change
1095  */
1096 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1097 {
1098   char** p;
1099   char*  m;
1100   struct Client *acptr;
1101   int what;
1102   int i;
1103   int setflags;
1104   unsigned int tmpmask = 0;
1105   int snomask_given = 0;
1106   char buf[BUFSIZE];
1107   int prop = 0;
1108   int do_host_hiding = 0;
1109
1110   what = MODE_ADD;
1111
1112   if (parc < 2)
1113     return need_more_params(sptr, "MODE");
1114
1115   if (!(acptr = FindUser(parv[1])))
1116   {
1117     if (MyConnect(sptr))
1118       send_reply(sptr, ERR_NOSUCHCHANNEL, parv[1]);
1119     return 0;
1120   }
1121
1122   if (IsServer(sptr) || sptr != acptr)
1123   {
1124     if (IsServer(cptr))
1125       sendwallto_group_butone(&me, WALL_WALLOPS, 0, 
1126                             "MODE for User %s from %s!%s", parv[1],
1127                             cli_name(cptr), cli_name(sptr));
1128     else
1129       send_reply(sptr, ERR_USERSDONTMATCH);
1130     return 0;
1131   }
1132
1133   if (parc < 3)
1134   {
1135     m = buf;
1136     *m++ = '+';
1137     for (i = 0; i < USERMODELIST_SIZE; ++i) {
1138       if ((userModeList[i].flag & cli_flags(sptr)) &&
1139           !(userModeList[i].flag & FLAGS_ACCOUNT))
1140         *m++ = userModeList[i].c;
1141     }
1142     *m = '\0';
1143     send_reply(sptr, RPL_UMODEIS, buf);
1144     if ((cli_flags(sptr) & FLAGS_SERVNOTICE) && MyConnect(sptr)
1145         && cli_snomask(sptr) !=
1146         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1147       send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1148     return 0;
1149   }
1150
1151   /*
1152    * find flags already set for user
1153    * why not just copy them?
1154    */
1155   setflags = cli_flags(sptr);
1156
1157   if (MyConnect(sptr))
1158     tmpmask = cli_snomask(sptr);
1159
1160   /*
1161    * parse mode change string(s)
1162    */
1163   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1164     for (m = *p; *m; m++) {
1165       switch (*m) {
1166       case '+':
1167         what = MODE_ADD;
1168         break;
1169       case '-':
1170         what = MODE_DEL;
1171         break;
1172       case 's':
1173         if (*(p + 1) && is_snomask(*(p + 1))) {
1174           snomask_given = 1;
1175           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1176           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1177         }
1178         else
1179           tmpmask = (what == MODE_ADD) ?
1180               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1181         if (tmpmask)
1182           SetServNotice(sptr);
1183         else
1184           ClearServNotice(sptr);
1185         break;
1186       case 'w':
1187         if (what == MODE_ADD)
1188           SetWallops(sptr);
1189         else
1190           ClearWallops(sptr);
1191         break;
1192       case 'o':
1193         if (what == MODE_ADD)
1194           SetOper(sptr);
1195         else {
1196           cli_flags(sptr) &= ~(FLAGS_OPER | FLAGS_LOCOP);
1197           if (MyConnect(sptr)) {
1198             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1199             cli_handler(sptr) = CLIENT_HANDLER;
1200           }
1201         }
1202         break;
1203       case 'O':
1204         if (what == MODE_ADD)
1205           SetLocOp(sptr);
1206         else { 
1207           cli_flags(sptr) &= ~(FLAGS_OPER | FLAGS_LOCOP);
1208           if (MyConnect(sptr)) {
1209             tmpmask = cli_snomask(sptr) & ~SNO_OPER;
1210             cli_handler(sptr) = CLIENT_HANDLER;
1211           }
1212         }
1213         break;
1214       case 'i':
1215         if (what == MODE_ADD)
1216           SetInvisible(sptr);
1217         else
1218           ClearInvisible(sptr);
1219         break;
1220       case 'd':
1221         if (what == MODE_ADD)
1222           SetDeaf(sptr);
1223         else
1224           ClearDeaf(sptr);
1225         break;
1226       case 'k':
1227         if (what == MODE_ADD)
1228           SetChannelService(sptr);
1229         else
1230           ClearChannelService(sptr);
1231         break;
1232       case 'g':
1233         if (what == MODE_ADD)
1234           SetDebug(sptr);
1235         else
1236           ClearDebug(sptr);
1237         break;
1238       case 'x':
1239         if (what == MODE_ADD)
1240           do_host_hiding = 1;
1241         break;
1242       default:
1243         break;
1244       }
1245     }
1246   }
1247   /*
1248    * Evaluate rules for new user mode
1249    * Stop users making themselves operators too easily:
1250    */
1251   if (!IsServer(cptr)) {
1252     if (!(setflags & FLAGS_OPER) && IsOper(sptr))
1253       ClearOper(sptr);
1254     if (!(setflags & FLAGS_LOCOP) && IsLocOp(sptr))
1255       ClearLocOp(sptr);
1256     /*
1257      * new umode; servers can set it, local users cannot;
1258      * prevents users from /kick'ing or /mode -o'ing
1259      */
1260     if (!(setflags & FLAGS_CHSERV))
1261       ClearChannelService(sptr);
1262     /*
1263      * only send wallops to opers
1264      */
1265     if (feature_bool(FEAT_WALLOPS_OPER_ONLY) && !IsAnOper(sptr) &&
1266         !(setflags & FLAGS_WALLOP))
1267       ClearWallops(sptr);
1268 #ifdef SERVNOTICE_OPER_ONLY
1269     if (MyConnect(sptr) && !IsAnOper(sptr) && !(setflags & FLAGS_SERVNOTICE)) {
1270       ClearServNotice(sptr);
1271       set_snomask(sptr, 0, SNO_SET);
1272     }
1273 #endif
1274 #ifdef DEBUG_OPER_ONLY
1275     if (!IsAnOper(sptr) && !(setflags & FLAGS_DEBUG))
1276       ClearDebug(sptr);
1277 #endif
1278   }
1279   if (MyConnect(sptr)) {
1280     if ((setflags & (FLAGS_OPER | FLAGS_LOCOP)) && !IsAnOper(sptr))
1281       det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPS);
1282
1283     if (SendServNotice(sptr)) {
1284       if (tmpmask != cli_snomask(sptr))
1285         set_snomask(sptr, tmpmask, SNO_SET);
1286       if (cli_snomask(sptr) && snomask_given)
1287         send_reply(sptr, RPL_SNOMASK, cli_snomask(sptr), cli_snomask(sptr));
1288     } else
1289       set_snomask(sptr, 0, SNO_SET);
1290   }
1291   /*
1292    * Compare new flags with old flags and send string which
1293    * will cause servers to update correctly.
1294    */
1295   if (!(setflags & FLAGS_OPER) && IsOper(sptr)) { /* user now oper */
1296     ++UserStats.opers;
1297     client_set_privs(sptr); /* may set propagate privilege */
1298   }
1299   if (HasPriv(sptr, PRIV_PROPAGATE)) /* remember propagate privilege setting */
1300     prop = 1;
1301   if ((setflags & FLAGS_OPER) && !IsOper(sptr)) { /* user no longer oper */
1302     --UserStats.opers;
1303     client_set_privs(sptr); /* will clear propagate privilege */
1304   }
1305   if ((setflags & FLAGS_INVISIBLE) && !IsInvisible(sptr))
1306     --UserStats.inv_clients;
1307   if (!(setflags & FLAGS_INVISIBLE) && IsInvisible(sptr))
1308     ++UserStats.inv_clients;
1309   if (!(setflags & FLAGS_HIDDENHOST) && do_host_hiding)
1310     hide_hostmask(sptr, FLAGS_HIDDENHOST);
1311   send_umode_out(cptr, sptr, setflags, prop);
1312
1313   return 0;
1314 }
1315
1316 /*
1317  * Build umode string for BURST command
1318  * --Run
1319  */
1320 char *umode_str(struct Client *cptr)
1321 {
1322   char* m = umodeBuf;                /* Maximum string size: "owidg\0" */
1323   int   i;
1324   int   c_flags;
1325
1326   c_flags = cli_flags(cptr) & SEND_UMODES; /* cleaning up the original code */
1327   if (HasPriv(cptr, PRIV_PROPAGATE))
1328     c_flags |= FLAGS_OPER;
1329   else
1330     c_flags &= ~FLAGS_OPER;
1331
1332   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1333     if ( (c_flags & userModeList[i].flag))
1334       *m++ = userModeList[i].c;
1335   }
1336
1337   if (IsAccount(cptr)) {
1338     char* t = cli_user(cptr)->account;
1339
1340     *m++ = ' ';
1341     while ((*m++ = *t++))
1342       ; /* Empty loop */
1343   }
1344
1345   *m = '\0';
1346
1347   return umodeBuf;                /* Note: static buffer, gets
1348                                    overwritten by send_umode() */
1349 }
1350
1351 /*
1352  * Send the MODE string for user (user) to connection cptr
1353  * -avalon
1354  */
1355 void send_umode(struct Client *cptr, struct Client *sptr, int old, int sendmask)
1356 {
1357   int i;
1358   int flag;
1359   char *m;
1360   int what = MODE_NULL;
1361
1362   /*
1363    * Build a string in umodeBuf to represent the change in the user's
1364    * mode between the new (sptr->flag) and 'old'.
1365    */
1366   m = umodeBuf;
1367   *m = '\0';
1368   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1369     flag = userModeList[i].flag;
1370     if (MyUser(sptr) && !(flag & sendmask))
1371       continue;
1372     if ( (flag & old) && !(cli_flags(sptr) & flag))
1373     {
1374       if (what == MODE_DEL)
1375         *m++ = userModeList[i].c;
1376       else
1377       {
1378         what = MODE_DEL;
1379         *m++ = '-';
1380         *m++ = userModeList[i].c;
1381       }
1382     }
1383     else if (!(flag & old) && (cli_flags(sptr) & flag))
1384     {
1385       if (what == MODE_ADD)
1386         *m++ = userModeList[i].c;
1387       else
1388       {
1389         what = MODE_ADD;
1390         *m++ = '+';
1391         *m++ = userModeList[i].c;
1392       }
1393     }
1394   }
1395   *m = '\0';
1396   if (*umodeBuf && cptr)
1397     sendcmdto_one(sptr, CMD_MODE, cptr, "%s :%s", cli_name(sptr), umodeBuf);
1398 }
1399
1400 /*
1401  * Check to see if this resembles a sno_mask.  It is if 1) there is
1402  * at least one digit and 2) The first digit occurs before the first
1403  * alphabetic character.
1404  */
1405 int is_snomask(char *word)
1406 {
1407   if (word)
1408   {
1409     for (; *word; word++)
1410       if (IsDigit(*word))
1411         return 1;
1412       else if (IsAlpha(*word))
1413         return 0;
1414   }
1415   return 0;
1416 }
1417
1418 /*
1419  * If it begins with a +, count this as an additive mask instead of just
1420  * a replacement.  If what == MODE_DEL, "+" has no special effect.
1421  */
1422 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1423 {
1424   unsigned int sno_what;
1425   unsigned int newmask;
1426   if (*arg == '+')
1427   {
1428     arg++;
1429     if (what == MODE_ADD)
1430       sno_what = SNO_ADD;
1431     else
1432       sno_what = SNO_DEL;
1433   }
1434   else if (*arg == '-')
1435   {
1436     arg++;
1437     if (what == MODE_ADD)
1438       sno_what = SNO_DEL;
1439     else
1440       sno_what = SNO_ADD;
1441   }
1442   else
1443     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1444   /* pity we don't have strtoul everywhere */
1445   newmask = (unsigned int)atoi(arg);
1446   if (sno_what == SNO_DEL)
1447     newmask = oldmask & ~newmask;
1448   else if (sno_what == SNO_ADD)
1449     newmask |= oldmask;
1450   return newmask;
1451 }
1452
1453 static void delfrom_list(struct Client *cptr, struct SLink **list)
1454 {
1455   struct SLink* tmp;
1456   struct SLink* prv = NULL;
1457
1458   for (tmp = *list; tmp; tmp = tmp->next) {
1459     if (tmp->value.cptr == cptr) {
1460       if (prv)
1461         prv->next = tmp->next;
1462       else
1463         *list = tmp->next;
1464       free_link(tmp);
1465       break;
1466     }
1467     prv = tmp;
1468   }
1469 }
1470
1471 /*
1472  * This function sets a Client's server notices mask, according to
1473  * the parameter 'what'.  This could be even faster, but the code
1474  * gets mighty hard to read :)
1475  */
1476 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1477 {
1478   unsigned int oldmask, diffmask;        /* unsigned please */
1479   int i;
1480   struct SLink *tmp;
1481
1482   oldmask = cli_snomask(cptr);
1483
1484   if (what == SNO_ADD)
1485     newmask |= oldmask;
1486   else if (what == SNO_DEL)
1487     newmask = oldmask & ~newmask;
1488   else if (what != SNO_SET)        /* absolute set, no math needed */
1489     sendto_opmask_butone(0, SNO_OLDSNO, "setsnomask called with %d ?!", what);
1490
1491   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1492
1493   diffmask = oldmask ^ newmask;
1494
1495   for (i = 0; diffmask >> i; i++) {
1496     if (((diffmask >> i) & 1))
1497     {
1498       if (((newmask >> i) & 1))
1499       {
1500         tmp = make_link();
1501         tmp->next = opsarray[i];
1502         tmp->value.cptr = cptr;
1503         opsarray[i] = tmp;
1504       }
1505       else
1506         /* not real portable :( */
1507         delfrom_list(cptr, &opsarray[i]);
1508     }
1509   }
1510   cli_snomask(cptr) = newmask;
1511 }
1512
1513 /*
1514  * is_silenced : Does the actual check wether sptr is allowed
1515  *               to send a message to acptr.
1516  *               Both must be registered persons.
1517  * If sptr is silenced by acptr, his message should not be propagated,
1518  * but more over, if this is detected on a server not local to sptr
1519  * the SILENCE mask is sent upstream.
1520  */
1521 int is_silenced(struct Client *sptr, struct Client *acptr)
1522 {
1523   struct SLink *lp;
1524   struct User *user;
1525   static char sender[HOSTLEN + NICKLEN + USERLEN + 5];
1526   static char senderip[16 + NICKLEN + USERLEN + 5];
1527   static char senderh[HOSTLEN + ACCOUNTLEN + USERLEN + 6];
1528
1529   if (!cli_user(acptr) || !(lp = cli_user(acptr)->silence) || !(user = cli_user(sptr)))
1530     return 0;
1531   ircd_snprintf(0, sender, sizeof(sender), "%s!%s@%s", cli_name(sptr),
1532                 user->username, user->host);
1533   ircd_snprintf(0, senderip, sizeof(senderip), "%s!%s@%s", cli_name(sptr),
1534                 user->username, ircd_ntoa((const char*) &(cli_ip(sptr))));
1535   if (HasHiddenHost(sptr))
1536     ircd_snprintf(0, senderh, sizeof(senderh), "%s!%s@%s", cli_name(sptr),
1537                   user->username, user->realhost);
1538   for (; lp; lp = lp->next)
1539   {
1540     if ((!(lp->flags & CHFL_SILENCE_IPMASK) && (!match(lp->value.cp, sender) ||
1541         (HasHiddenHost(sptr) && !match(lp->value.cp, senderh)))) ||
1542         ((lp->flags & CHFL_SILENCE_IPMASK) && !match(lp->value.cp, senderip)))
1543     {
1544       if (!MyConnect(sptr))
1545       {
1546         sendcmdto_one(acptr, CMD_SILENCE, cli_from(sptr), "%C %s", sptr,
1547                       lp->value.cp);
1548       }
1549       return 1;
1550     }
1551   }
1552   return 0;
1553 }
1554
1555 /*
1556  * del_silence
1557  *
1558  * Removes all silence masks from the list of sptr that fall within `mask'
1559  * Returns -1 if none where found, 0 otherwise.
1560  */
1561 int del_silence(struct Client *sptr, char *mask)
1562 {
1563   struct SLink **lp;
1564   struct SLink *tmp;
1565   int ret = -1;
1566
1567   for (lp = &(cli_user(sptr))->silence; *lp;) {
1568     if (!mmatch(mask, (*lp)->value.cp))
1569     {
1570       tmp = *lp;
1571       *lp = tmp->next;
1572       MyFree(tmp->value.cp);
1573       free_link(tmp);
1574       ret = 0;
1575     }
1576     else
1577       lp = &(*lp)->next;
1578   }
1579   return ret;
1580 }
1581
1582 int add_silence(struct Client* sptr, const char* mask)
1583 {
1584   struct SLink *lp, **lpp;
1585   int cnt = 0, len = strlen(mask);
1586   char *ip_start;
1587
1588   for (lpp = &(cli_user(sptr))->silence, lp = *lpp; lp;)
1589   {
1590     if (0 == ircd_strcmp(mask, lp->value.cp))
1591       return -1;
1592     if (!mmatch(mask, lp->value.cp))
1593     {
1594       struct SLink *tmp = lp;
1595       *lpp = lp = lp->next;
1596       MyFree(tmp->value.cp);
1597       free_link(tmp);
1598       continue;
1599     }
1600     if (MyUser(sptr))
1601     {
1602       len += strlen(lp->value.cp);
1603       if ((len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXSILES))) ||
1604           (++cnt >= feature_int(FEAT_MAXSILES)))
1605       {
1606         send_reply(sptr, ERR_SILELISTFULL, mask);
1607         return -1;
1608       }
1609       else if (!mmatch(lp->value.cp, mask))
1610         return -1;
1611     }
1612     lpp = &lp->next;
1613     lp = *lpp;
1614   }
1615   lp = make_link();
1616   memset(lp, 0, sizeof(struct SLink));
1617   lp->next = cli_user(sptr)->silence;
1618   lp->value.cp = (char*) MyMalloc(strlen(mask) + 1);
1619   assert(0 != lp->value.cp);
1620   strcpy(lp->value.cp, mask);
1621   if ((ip_start = strrchr(mask, '@')) && check_if_ipmask(ip_start + 1))
1622     lp->flags = CHFL_SILENCE_IPMASK;
1623   cli_user(sptr)->silence = lp;
1624   return 0;
1625 }
1626
1627 int
1628 send_supported(struct Client *cptr)
1629 {
1630   char featurebuf[512];
1631
1632   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES1, FEATURESVALUES1);
1633   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1634   ircd_snprintf(0, featurebuf, sizeof(featurebuf), FEATURES2, FEATURESVALUES2);
1635   send_reply(cptr, RPL_ISUPPORT, featurebuf);
1636
1637   return 0; /* convenience return, if it's ever needed */
1638 }