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