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