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