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