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