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 /*
276  * 'do_nick_name' ensures that the given parameter (nick) is really a proper
277  * string for a nickname (note, the 'nick' may be modified in the process...)
278  *
279  * RETURNS the length of the final NICKNAME (0, if nickname is invalid)
280  *
281  * Nickname characters are in range 'A'..'}', '_', '-', '0'..'9'
282  *  anything outside the above set will terminate nickname.
283  * In addition, the first character cannot be '-' or a Digit.
284  *
285  * Note:
286  *  The '~'-character should be allowed, but a change should be global,
287  *  some confusion would result if only few servers allowed it...
288  */
289 int do_nick_name(char* nick)
290 {
291   char* ch  = nick;
292   char* end = ch + NICKLEN;
293   assert(0 != ch);
294
295   if (*ch == '-' || IsDigit(*ch))        /* first character in [0..9-] */
296     return 0;
297
298   for ( ; (ch < end) && *ch; ++ch)
299     if (!IsNickChar(*ch))
300       break;
301
302   *ch = '\0';
303
304   return (ch - nick);
305 }
306
307 /*
308  * clean_user_id
309  *
310  * Copy `source' to `dest', replacing all occurances of '~' and characters that
311  * are not `isIrcUi' by an underscore.
312  * Copies at most USERLEN - 1 characters or up till the first control character.
313  * If `tilde' is true, then a tilde is prepended to `dest'.
314  * Note that `dest' and `source' can point to the same area or to different
315  * non-overlapping areas.
316  */
317 static char *clean_user_id(char *dest, char *source, int tilde)
318 {
319   char ch;
320   char *d = dest;
321   char *s = source;
322   int rlen = USERLEN;
323
324   ch = *s++;                        /* Store first character to copy: */
325   if (tilde)
326   {
327     *d++ = '~';                        /* If `dest' == `source', then this overwrites `ch' */
328     --rlen;
329   }
330   while (ch && !IsCntrl(ch) && rlen--)
331   {
332     char nch = *s++;        /* Store next character to copy */
333     *d++ = IsUserChar(ch) ? ch : '_';        /* This possibly overwrites it */
334     if (nch == '~')
335       ch = '_';
336     else
337       ch = nch;
338   }
339   *d = 0;
340   return dest;
341 }
342
343 /*
344  * register_user
345  *
346  * This function is called when both NICK and USER messages
347  * have been accepted for the client, in whatever order. Only
348  * after this the USER message is propagated.
349  *
350  * NICK's must be propagated at once when received, although
351  * it would be better to delay them too until full info is
352  * available. Doing it is not so simple though, would have
353  * to implement the following:
354  *
355  * 1) user telnets in and gives only "NICK foobar" and waits
356  * 2) another user far away logs in normally with the nick
357  *    "foobar" (quite legal, as this server didn't propagate it).
358  * 3) now this server gets nick "foobar" from outside, but
359  *    has already the same defined locally. Current server
360  *    would just issue "KILL foobar" to clean out dups. But,
361  *    this is not fair. It should actually request another
362  *    nick from local user or kill him/her...
363  */
364 int register_user(struct Client *cptr, struct Client *sptr,
365                   const char *nick, char *username)
366 {
367   struct ConfItem* aconf;
368   char*            parv[3];
369   char*            tmpstr;
370   char*            tmpstr2;
371   char             c = 0;    /* not alphanum */
372   char             d = 'a';  /* not a digit */
373   short            upper = 0;
374   short            lower = 0;
375   short            pos = 0;
376   short            leadcaps = 0;
377   short            other = 0;
378   short            digits = 0;
379   short            badid = 0;
380   short            digitgroups = 0;
381   struct User*     user = sptr->user;
382   char             ip_base64[8];
383   char             featurebuf[512];
384   struct Gline*    gline;
385
386   user->last = CurrentTime;
387   parv[0] = sptr->name;
388   parv[1] = parv[2] = NULL;
389
390   if (MyConnect(sptr))
391   {
392     static time_t last_too_many1;
393     static time_t last_too_many2;
394
395     assert(cptr == sptr);
396     switch (conf_check_client(sptr))
397     {
398       case ACR_OK:
399         break;
400       case ACR_NO_AUTHORIZATION:
401         sendto_opmask_butone(0, SNO_UNAUTH, "Unauthorized connection from %s.",
402                              get_client_name(sptr, HIDE_IP));
403         ++ServerStats->is_ref;
404         return exit_client(cptr, sptr, &me,
405                            "No Authorization - use another server");
406       case ACR_TOO_MANY_IN_CLASS:
407         if (CurrentTime - last_too_many1 >= (time_t) 60)
408         {
409           last_too_many1 = CurrentTime;
410           sendto_opmask_butone(0, SNO_TOOMANY, "Too many connections in "
411                                "class for %s.",
412                                get_client_name(sptr, HIDE_IP));
413         }
414         ++ServerStats->is_ref;
415         IPcheck_connect_fail(sptr->ip);
416         return exit_client(cptr, sptr, &me,
417                            "Sorry, your connection class is full - try "
418                            "again later or try another server");
419       case ACR_TOO_MANY_FROM_IP:
420         if (CurrentTime - last_too_many2 >= (time_t) 60)
421         {
422           last_too_many2 = CurrentTime;
423           sendto_opmask_butone(0, SNO_TOOMANY, "Too many connections from "
424                                "same IP for %s.",
425                                get_client_name(sptr, HIDE_IP));
426         }
427         ++ServerStats->is_ref;
428         return exit_client(cptr, sptr, &me,
429                            "Too many connections from your host");
430       case ACR_ALREADY_AUTHORIZED:
431         /* Can this ever happen? */
432       case ACR_BAD_SOCKET:
433         ++ServerStats->is_ref;
434         IPcheck_connect_fail(sptr->ip);
435         return exit_client(cptr, sptr, &me, "Unknown error -- Try again");
436     }
437     ircd_strncpy(user->host, sptr->sockhost, HOSTLEN);
438     aconf = sptr->confs->value.aconf;
439
440     clean_user_id(user->username,
441         (sptr->flags & FLAGS_GOTID) ? sptr->username : username,
442         (sptr->flags & FLAGS_DOID) && !(sptr->flags & FLAGS_GOTID));
443
444     if ((user->username[0] == '\0')
445         || ((user->username[0] == '~') && (user->username[1] == '\000')))
446       return exit_client(cptr, sptr, &me, "USER: Bogus userid.");
447
448     if (!EmptyString(aconf->passwd)
449         && !(IsDigit(*aconf->passwd) && !aconf->passwd[1])
450 #ifdef USEONE
451         && strcmp("ONE", aconf->passwd)
452 #endif
453         && strcmp(sptr->passwd, aconf->passwd))
454     {
455       ServerStats->is_ref++;
456       IPcheck_connect_fail(sptr->ip);
457       send_reply(sptr, ERR_PASSWDMISMATCH);
458       return exit_client(cptr, sptr, &me, "Bad Password");
459     }
460     memset(sptr->passwd, 0, sizeof(sptr->passwd));
461     /*
462      * following block for the benefit of time-dependent K:-lines
463      */
464     if (find_kill(sptr)) {
465       ServerStats->is_ref++;
466       IPcheck_connect_fail(sptr->ip);
467       return exit_client(cptr, sptr, &me, "K-lined");
468     }
469     /*
470      * Check for mixed case usernames, meaning probably hacked.  Jon2 3-94
471      * Summary of rules now implemented in this patch:         Ensor 11-94
472      * In a mixed-case name, if first char is upper, one more upper may
473      * appear anywhere.  (A mixed-case name *must* have an upper first
474      * char, and may have one other upper.)
475      * A third upper may appear if all 3 appear at the beginning of the
476      * name, separated only by "others" (-/_/.).
477      * A single group of digits is allowed anywhere.
478      * Two groups of digits are allowed if at least one of the groups is
479      * at the beginning or the end.
480      * Only one '-', '_', or '.' is allowed (or two, if not consecutive).
481      * But not as the first or last char.
482      * No other special characters are allowed.
483      * Name must contain at least one letter.
484      */
485     tmpstr2 = tmpstr = (username[0] == '~' ? &username[1] : username);
486     while (*tmpstr && !badid)
487     {
488       pos++;
489       c = *tmpstr;
490       tmpstr++;
491       if (IsLower(c))
492       {
493         lower++;
494       }
495       else if (IsUpper(c))
496       {
497         upper++;
498         if ((leadcaps || pos == 1) && !lower && !digits)
499           leadcaps++;
500       }
501       else if (IsDigit(c))
502       {
503         digits++;
504         if (pos == 1 || !IsDigit(d))
505         {
506           digitgroups++;
507           if (digitgroups > 2)
508             badid = 1;
509         }
510       }
511       else if (c == '-' || c == '_' || c == '.')
512       {
513         other++;
514         if (pos == 1)
515           badid = 1;
516         else if (d == '-' || d == '_' || d == '.' || other > 2)
517           badid = 1;
518       }
519       else
520         badid = 1;
521       d = c;
522     }
523     if (!badid)
524     {
525       if (lower && upper && (!leadcaps || leadcaps > 3 ||
526           (upper > 2 && upper > leadcaps)))
527         badid = 1;
528       else if (digitgroups == 2 && !(IsDigit(tmpstr2[0]) || IsDigit(c)))
529         badid = 1;
530       else if ((!lower && !upper) || !IsAlnum(c))
531         badid = 1;
532     }
533     if (badid && (!(sptr->flags & FLAGS_GOTID) ||
534         strcmp(sptr->username, username) != 0))
535     {
536       ServerStats->is_ref++;
537
538       send_reply(cptr, RPL_EXPLICIT | ERR_INVALIDUSERNAME,
539                  ":Your username is invalid.");
540       send_reply(cptr, RPL_EXPLICIT | ERR_INVALIDUSERNAME,
541                  ":Connect with your real username, in lowercase.");
542       send_reply(cptr, RPL_EXPLICIT | ERR_INVALIDUSERNAME,
543                  ":If your mail address were foo@bar.com, your username "
544                  "would be foo.");
545       return exit_client(cptr, sptr, &me, "USER: Bad username");
546     }
547     Count_unknownbecomesclient(sptr, UserStats);
548   }
549   else {
550     ircd_strncpy(user->username, username, USERLEN);
551     Count_newremoteclient(UserStats, user->server);
552     if ((gline = gline_lookup(sptr)) && GlineIsActive(gline))
553       gline_resend(cptr, gline);
554   }
555   SetUser(sptr);
556
557   if (IsInvisible(sptr))
558     ++UserStats.inv_clients;
559   if (IsOper(sptr))
560     ++UserStats.opers;
561
562   if (MyConnect(sptr)) {
563     sptr->handler = CLIENT_HANDLER;
564     release_dns_reply(sptr);
565
566     send_reply(sptr, RPL_WELCOME, nick);
567     /*
568      * This is a duplicate of the NOTICE but see below...
569      */
570     send_reply(sptr, RPL_YOURHOST, me.name, version);
571     send_reply(sptr, RPL_CREATED, creation);
572     send_reply(sptr, RPL_MYINFO, me.name, version);
573     sprintf_irc(featurebuf,FEATURES,FEATURESVALUES);
574     send_reply(sptr, RPL_ISUPPORT, featurebuf);
575     m_lusers(sptr, sptr, 1, parv);
576     update_load();
577 #ifdef NODEFAULTMOTD
578     m_motd(sptr, NULL, 1, parv);
579 #else
580     m_motd(sptr, sptr, 1, parv);
581 #endif
582     nextping = CurrentTime;
583     if (sptr->snomask & SNO_NOISY)
584       set_snomask(sptr, sptr->snomask & SNO_NOISY, SNO_ADD);
585 #ifdef ALLOW_SNO_CONNEXIT
586 #ifdef SNO_CONNEXIT_IP
587     sendto_opmask_butone(0, SNO_CONNEXIT, "Client connecting: %s (%s@%s) "
588                          "[%s] {%d}", nick, user->username, user->host,
589                          cptr->sock_ip, get_client_class(sptr));
590 #else /* SNO_CONNEXIT_IP */
591     sendto_opmask_butone(0, SNO_CONEXIT, "Client connecting: %s (%s@%s)",
592                          nick, user->username, user->host);
593 #endif /* SNO_CONNEXIT_IP */
594 #endif /* ALLOW_SNO_CONNEXIT */
595     IPcheck_connect_succeeded(sptr);
596   }
597   else
598     /* if (IsServer(cptr)) */
599   {
600     struct Client *acptr;
601
602     acptr = user->server;
603     if (acptr->from != sptr->from)
604     {
605       sendcmdto_one(&me, CMD_KILL, cptr, "%C :%s (%s != %s[%s])",
606                     sptr, me.name, user->server->name, acptr->from->name,
607                     acptr->from->sockhost);
608       sptr->flags |= FLAGS_KILLED;
609       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
610     }
611     else
612       sptr->flags |= (acptr->flags & FLAGS_TS8);
613
614     /*
615      * Check to see if this user is being propogated
616      * as part of a net.burst, or is using protocol 9.
617      * FIXME: This can be speeded up - its stupid to check it for
618      * every NICK message in a burst again  --Run.
619      */
620     for (acptr = user->server; acptr != &me; acptr = acptr->serv->up) {
621       if (IsBurst(acptr) || Protocol(acptr) < 10)
622         break;
623     }
624     if (!IPcheck_remote_connect(sptr, (acptr != &me)))
625       /*
626        * We ran out of bits to count this
627        */
628       return exit_client(cptr, sptr, &me, "More than 255 connections from this address");
629   }
630
631   tmpstr = umode_str(sptr);
632   sendcmdto_serv_butone(user->server, CMD_NICK, cptr, *tmpstr ?
633                         "%s %d %d %s %s +%s %s %s%s :%s" :
634                         "%s %d %d %s %s %s%s %s%s :%s",
635                         nick, sptr->hopcount + 1, sptr->lastnick,
636                         user->username, user->host, tmpstr,
637                         inttobase64(ip_base64, ntohl(sptr->ip.s_addr), 6),
638                         NumNick(sptr), sptr->info);
639
640   /* Send umode to client */
641   if (MyUser(sptr))
642   {
643     send_umode(cptr, sptr, 0, ALL_UMODES);
644     if (sptr->snomask != SNO_DEFAULT && (sptr->flags & FLAGS_SERVNOTICE))
645       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
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 #if 0
669 static int user_modes[] = {
670   FLAGS_OPER,        'o',
671   FLAGS_LOCOP,       'O',
672   FLAGS_INVISIBLE,   'i',
673   FLAGS_WALLOP,      'w',
674   FLAGS_SERVNOTICE,  's',
675   FLAGS_DEAF,        'd',
676   FLAGS_CHSERV,      'k',
677   FLAGS_DEBUG,       'g',
678   0,                  0
679 };
680 #endif
681
682 /*
683  * XXX - find a way to get rid of this
684  */
685 static char umodeBuf[BUFSIZE];
686
687 int set_nick_name(struct Client* cptr, struct Client* sptr,
688                   const char* nick, int parc, char* parv[])
689 {
690   if (IsServer(sptr)) {
691     int   i;
692     const char* p;
693
694     /*
695      * A server introducing a new client, change source
696      */
697     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
698     assert(0 != new_client);
699
700     new_client->hopcount = atoi(parv[2]);
701     new_client->lastnick = atoi(parv[3]);
702     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+') {
703       for (p = parv[6] + 1; *p; p++) {
704         for (i = 0; i < USERMODELIST_SIZE; ++i) {
705           if (userModeList[i].c == *p) {
706             new_client->flags |= userModeList[i].flag;
707             break;
708           }
709         }
710       }
711     }
712     /*
713      * Set new nick name.
714      */
715     strcpy(new_client->name, nick);
716     new_client->user = make_user(new_client);
717     new_client->user->server = sptr;
718     SetRemoteNumNick(new_client, parv[parc - 2]);
719     /*
720      * IP# of remote client
721      */
722     new_client->ip.s_addr = htonl(base64toint(parv[parc - 3]));
723
724     add_client_to_list(new_client);
725     hAddClient(new_client);
726
727     sptr->serv->ghost = 0;        /* :server NICK means end of net.burst */
728     ircd_strncpy(new_client->username, parv[4], USERLEN);
729     ircd_strncpy(new_client->user->host, parv[5], HOSTLEN);
730     ircd_strncpy(new_client->info, parv[parc - 1], REALLEN);
731     return register_user(cptr, new_client, new_client->name, parv[4]);
732   }
733   else if (sptr->name[0]) {
734     /*
735      * Client changing its nick
736      *
737      * If the client belongs to me, then check to see
738      * if client is on any channels where it is currently
739      * banned.  If so, do not allow the nick change to occur.
740      */
741     if (MyUser(sptr)) {
742       const char* channel_name;
743       if ((channel_name = find_no_nickchange_channel(sptr))) {
744         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
745       }
746       /*
747        * Refuse nick change if the last nick change was less
748        * then 30 seconds ago. This is intended to get rid of
749        * clone bots doing NICK FLOOD. -SeKs
750        * If someone didn't change their nick for more then 60 seconds
751        * however, allow to do two nick changes immedately after another
752        * before limiting the nick flood. -Run
753        */
754       if (CurrentTime < cptr->nextnick) {
755         cptr->nextnick += 2;
756         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
757                    cptr->nextnick - CurrentTime);
758         /* Send error message */
759         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cptr->name);
760         /* bounce NICK to user */
761         return 0;                /* ignore nick change! */
762       }
763       else {
764         /* Limit total to 1 change per NICK_DELAY seconds: */
765         cptr->nextnick += NICK_DELAY;
766         /* However allow _maximal_ 1 extra consecutive nick change: */
767         if (cptr->nextnick < CurrentTime)
768           cptr->nextnick = CurrentTime;
769       }
770     }
771     /*
772      * Also set 'lastnick' to current time, if changed.
773      */
774     if (0 != ircd_strcmp(parv[0], nick))
775       sptr->lastnick = (sptr == cptr) ? TStime() : atoi(parv[2]);
776
777     /*
778      * Client just changing his/her nick. If he/she is
779      * on a channel, send note of change to all clients
780      * on that channel. Propagate notice to other servers.
781      */
782     if (IsUser(sptr)) {
783       sendcmdto_common_channels(sptr, CMD_NICK, ":%s", nick);
784       add_history(sptr, 1);
785       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
786                             sptr->lastnick);
787     }
788     else
789       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
790
791     if (sptr->name[0])
792       hRemClient(sptr);
793     strcpy(sptr->name, nick);
794     hAddClient(sptr);
795   }
796   else {
797     /* Local client setting NICK the first time */
798
799     strcpy(sptr->name, nick);
800     if (!sptr->user) {
801       sptr->user = make_user(sptr);
802       sptr->user->server = &me;
803     }
804     SetLocalNumNick(sptr);
805     hAddClient(sptr);
806
807     /*
808      * If the client hasn't gotten a cookie-ping yet,
809      * choose a cookie and send it. -record!jegelhof@cloud9.net
810      */
811     if (!sptr->cookie) {
812       do {
813         sptr->cookie = (ircrandom() & 0x7fffffff);
814       } while (!sptr->cookie);
815       sendrawto_one(cptr, MSG_PING " :%u", sptr->cookie);
816     }
817     else if (*sptr->user->host && sptr->cookie == COOKIE_VERIFIED) {
818       /*
819        * USER and PONG already received, now we have NICK.
820        * register_user may reject the client and call exit_client
821        * for it - must test this and exit m_nick too !
822        */
823       sptr->lastnick = TStime();        /* Always local client */
824       if (register_user(cptr, sptr, nick, sptr->user->username) == CPTR_KILLED)
825         return CPTR_KILLED;
826     }
827   }
828   return 0;
829 }
830
831 static unsigned char hash_target(unsigned int target)
832 {
833   return (unsigned char) (target >> 16) ^ (target >> 8);
834 }
835
836 /*
837  * add_target
838  *
839  * sptr must be a local client!
840  *
841  * Cannonifies target for client `sptr'.
842  */
843 void add_target(struct Client *sptr, void *target)
844 {
845   unsigned char  hash = hash_target((unsigned int) target);
846   unsigned char* targets;
847   int            i;
848   assert(0 != sptr);
849   assert(sptr->local);
850
851   targets = sptr->targets;
852   /* 
853    * Already in table?
854    */
855   for (i = 0; i < MAXTARGETS; ++i) {
856     if (targets[i] == hash)
857       return;
858   }
859   /*
860    * New target
861    */
862   memmove(&targets[RESERVEDTARGETS + 1],
863           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
864   targets[RESERVEDTARGETS] = hash;
865 }
866
867 /*
868  * check_target_limit
869  *
870  * sptr must be a local client !
871  *
872  * Returns 'true' (1) when too many targets are addressed.
873  * Returns 'false' (0) when it's ok to send to this target.
874  */
875 int check_target_limit(struct Client *sptr, void *target, const char *name,
876     int created)
877 {
878   unsigned char hash = hash_target((unsigned int) target);
879   int            i;
880   unsigned char* targets;
881
882   assert(0 != sptr);
883   assert(sptr->local);
884   targets = sptr->targets;
885
886   /*
887    * Same target as last time?
888    */
889   if (targets[0] == hash)
890     return 0;
891   for (i = 1; i < MAXTARGETS; ++i) {
892     if (targets[i] == hash) {
893       memmove(&targets[1], &targets[0], i);
894       targets[0] = hash;
895       return 0;
896     }
897   }
898   /*
899    * New target
900    */
901   if (!created) {
902     if (CurrentTime < sptr->nexttarget) {
903       if (sptr->nexttarget - CurrentTime < TARGET_DELAY + 8) {
904         /*
905          * No server flooding
906          */
907         sptr->nexttarget += 2;
908         send_reply(sptr, ERR_TARGETTOOFAST, name,
909                    sptr->nexttarget - CurrentTime);
910       }
911       return 1;
912     }
913     else {
914 #ifdef GODMODE
915       /* XXX Let's get rid of GODMODE */
916       sendto_one(sptr, ":%s NOTICE %s :New target: %s; ft " TIME_T_FMT,
917           me.name, sptr->name, name, (CurrentTime - sptr->nexttarget) / TARGET_DELAY);
918 #endif
919       sptr->nexttarget += TARGET_DELAY;
920       if (sptr->nexttarget < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
921         sptr->nexttarget = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
922     }
923   }
924   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
925   targets[0] = hash;
926   return 0;
927 }
928
929 /*
930  * whisper - called from m_cnotice and m_cprivmsg.
931  *
932  * parv[0] = sender prefix
933  * parv[1] = nick
934  * parv[2] = #channel
935  * parv[3] = Private message text
936  *
937  * Added 971023 by Run.
938  * Reason: Allows channel operators to sent an arbitrary number of private
939  *   messages to users on their channel, avoiding the max.targets limit.
940  *   Building this into m_private would use too much cpu because we'd have
941  *   to a cross channel lookup for every private message!
942  * Note that we can't allow non-chan ops to use this command, it would be
943  *   abused by mass advertisers.
944  *
945  */
946 int whisper(struct Client* source, const char* nick, const char* channel,
947             const char* text, int is_notice)
948 {
949   struct Client*     dest;
950   struct Channel*    chptr;
951   struct Membership* membership;
952
953   assert(0 != source);
954   assert(0 != nick);
955   assert(0 != channel);
956   assert(MyUser(source));
957
958   if (!(dest = FindUser(nick))) {
959     return send_reply(source, ERR_NOSUCHNICK, nick);
960   }
961   if (!(chptr = FindChannel(channel))) {
962     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
963   }
964   /*
965    * compare both users channel lists, instead of the channels user list
966    * since the link is the same, this should be a little faster for channels
967    * with a lot of users
968    */
969   for (membership = source->user->channel; membership; membership = membership->next_channel) {
970     if (chptr == membership->channel)
971       break;
972   }
973   if (0 == membership) {
974     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
975   }
976   if (!IsVoicedOrOpped(membership)) {
977     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
978   }
979   /*
980    * lookup channel in destination
981    */
982   assert(0 != dest->user);
983   for (membership = dest->user->channel; membership; membership = membership->next_channel) {
984     if (chptr == membership->channel)
985       break;
986   }
987   if (0 == membership || IsZombie(membership)) {
988     return send_reply(source, ERR_USERNOTINCHANNEL, dest->name, chptr->chname);
989   }
990   if (is_silenced(source, dest))
991     return 0;
992           
993   if (dest->user->away)
994     send_reply(source, RPL_AWAY, dest->name, dest->user->away);
995   if (is_notice)
996     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
997   else
998     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
999   return 0;
1000 }
1001
1002
1003 /*
1004  * added Sat Jul 25 07:30:42 EST 1992
1005  */
1006 void send_umode_out(struct Client *cptr, struct Client *sptr, int old)
1007 {
1008   int i;
1009   struct Client *acptr;
1010
1011   send_umode(NULL, sptr, old, SEND_UMODES);
1012
1013   for (i = HighestFd; i >= 0; i--) {
1014     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
1015         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
1016       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", sptr->name, umodeBuf);
1017   }
1018   if (cptr && MyUser(cptr))
1019     send_umode(cptr, sptr, old, ALL_UMODES);
1020 }
1021
1022
1023 /*
1024  * send_user_info - send user info userip/userhost
1025  * NOTE: formatter must put info into buffer and return a pointer to the end of
1026  * the data it put in the buffer.
1027  */
1028 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
1029 {
1030   char*          sbuf;
1031   char*          name;
1032   char*          p = 0;
1033   int            arg_count = 0;
1034   int            users_found = 0;
1035   struct Client* acptr;
1036   char           buf[BUFSIZE * 2];
1037
1038   assert(0 != sptr);
1039   assert(0 != names);
1040   assert(0 != fmt);
1041
1042   sbuf = sprintf_irc(buf, rpl_str(rpl), me.name, sptr->name);
1043
1044   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
1045     if ((acptr = FindUser(name))) {
1046       if (users_found++)
1047         *sbuf++ = ' ';
1048       sbuf = (*fmt)(acptr, sbuf);
1049     }
1050     if (5 == ++arg_count)
1051       break;
1052   }
1053   if (users_found)
1054     send_buffer(sptr, buf);
1055 }
1056
1057
1058 /*
1059  * set_user_mode() added 15/10/91 By Darren Reed.
1060  *
1061  * parv[0] - sender
1062  * parv[1] - username to change mode for
1063  * parv[2] - modes to change
1064  */
1065 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1066 {
1067   char** p;
1068   char*  m;
1069   struct Client *acptr;
1070   int what;
1071   int i;
1072   int setflags;
1073   unsigned int tmpmask = 0;
1074   int snomask_given = 0;
1075   char buf[BUFSIZE];
1076
1077   what = MODE_ADD;
1078
1079   if (parc < 2)
1080     return need_more_params(sptr, "MODE");
1081
1082   if (!(acptr = FindUser(parv[1])))
1083   {
1084     if (MyConnect(sptr))
1085       send_reply(sptr, ERR_NOSUCHCHANNEL, parv[1]);
1086     return 0;
1087   }
1088
1089   if (IsServer(sptr) || sptr != acptr)
1090   {
1091     if (IsServer(cptr))
1092       sendcmdto_flag_butone(&me, CMD_WALLOPS, 0, FLAGS_WALLOP,
1093                             ":MODE for User %s from %s!%s", parv[1],
1094                             cptr->name, sptr->name);
1095     else
1096       send_reply(sptr, ERR_USERSDONTMATCH);
1097     return 0;
1098   }
1099
1100   if (parc < 3)
1101   {
1102     m = buf;
1103     *m++ = '+';
1104     for (i = 0; i < USERMODELIST_SIZE; ++i) {
1105       if ( (userModeList[i].flag & sptr->flags))
1106         *m++ = userModeList[i].c;
1107     }
1108     *m = '\0';
1109     send_reply(sptr, RPL_UMODEIS, buf);
1110     if ((sptr->flags & FLAGS_SERVNOTICE) && MyConnect(sptr)
1111         && sptr->snomask !=
1112         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1113       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
1114     return 0;
1115   }
1116
1117   /*
1118    * find flags already set for user
1119    * why not just copy them?
1120    */
1121   setflags = sptr->flags;
1122 #if 0
1123   setflags = 0;
1124   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1125     if (sptr->flags & userModeList[i].flag)
1126       setflags |= userModeList[i].flag;
1127   }
1128 #endif
1129   if (MyConnect(sptr))
1130     tmpmask = sptr->snomask;
1131
1132   /*
1133    * parse mode change string(s)
1134    */
1135   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1136     for (m = *p; *m; m++) {
1137       switch (*m) {
1138       case '+':
1139         what = MODE_ADD;
1140         break;
1141       case '-':
1142         what = MODE_DEL;
1143         break;
1144       case 's':
1145         if (*(p + 1) && is_snomask(*(p + 1))) {
1146           snomask_given = 1;
1147           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1148           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1149         }
1150         else
1151           tmpmask = (what == MODE_ADD) ?
1152               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1153         if (tmpmask)
1154           sptr->flags |= FLAGS_SERVNOTICE;
1155         else
1156           sptr->flags &= ~FLAGS_SERVNOTICE;
1157         break;
1158       case 'w':
1159         if (what == MODE_ADD)
1160           SetWallops(sptr);
1161         else
1162           ClearWallops(sptr);
1163         break;
1164       case 'o':
1165         if (what == MODE_ADD)
1166           SetOper(sptr);
1167         else {
1168           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1169           if (MyConnect(sptr)) {
1170             tmpmask = sptr->snomask & ~SNO_OPER;
1171             sptr->handler = CLIENT_HANDLER;
1172           }
1173         }
1174         break;
1175       case 'O':
1176         if (what == MODE_ADD)
1177           SetLocOp(sptr);
1178         else { 
1179           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1180           if (MyConnect(sptr)) {
1181             tmpmask = sptr->snomask & ~SNO_OPER;
1182             sptr->handler = CLIENT_HANDLER;
1183           }
1184         }
1185         break;
1186       case 'i':
1187         if (what == MODE_ADD)
1188           SetInvisible(sptr);
1189         else
1190           ClearInvisible(sptr);
1191         break;
1192       case 'd':
1193         if (what == MODE_ADD)
1194           SetDeaf(sptr);
1195         else
1196           ClearDeaf(sptr);
1197         break;
1198       case 'k':
1199         if (what == MODE_ADD)
1200           SetChannelService(sptr);
1201         else
1202           ClearChannelService(sptr);
1203         break;
1204       case 'g':
1205         if (what == MODE_ADD)
1206           SetDebug(sptr);
1207         else
1208           ClearDebug(sptr);
1209         break;
1210       default:
1211         break;
1212       }
1213     }
1214   }
1215   /*
1216    * Evaluate rules for new user mode
1217    * Stop users making themselves operators too easily:
1218    */
1219   if (!(setflags & FLAGS_OPER) && IsOper(sptr) && !IsServer(cptr))
1220     ClearOper(sptr);
1221   if (!(setflags & FLAGS_LOCOP) && IsLocOp(sptr) && !IsServer(cptr))
1222     ClearLocOp(sptr);
1223 #ifdef WALLOPS_OPER_ONLY
1224   /*
1225    * only send wallops to opers
1226    */
1227   if (!IsAnOper(sptr) && !(setflags & FLAGS_WALLOP) && !IsServer(cptr))
1228     ClearWallops(sptr);
1229 #endif
1230   if ((setflags & (FLAGS_OPER | FLAGS_LOCOP)) && !IsAnOper(sptr) &&
1231       MyConnect(sptr))
1232     det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPS);
1233   /*
1234    * new umode; servers can set it, local users cannot;
1235    * prevents users from /kick'ing or /mode -o'ing
1236    */
1237   if (!(setflags & FLAGS_CHSERV) && !IsServer(cptr))
1238     ClearChannelService(sptr);
1239   /*
1240    * Compare new flags with old flags and send string which
1241    * will cause servers to update correctly.
1242    */
1243   if ((setflags & FLAGS_OPER) && !IsOper(sptr))
1244     --UserStats.opers;
1245   if (!(setflags & FLAGS_OPER) && IsOper(sptr))
1246     ++UserStats.opers;
1247   if ((setflags & FLAGS_INVISIBLE) && !IsInvisible(sptr))
1248     --UserStats.inv_clients;
1249   if (!(setflags & FLAGS_INVISIBLE) && IsInvisible(sptr))
1250     ++UserStats.inv_clients;
1251   send_umode_out(cptr, sptr, setflags);
1252
1253   if (MyConnect(sptr)) {
1254     if (tmpmask != sptr->snomask)
1255       set_snomask(sptr, tmpmask, SNO_SET);
1256     if (sptr->snomask && snomask_given)
1257       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
1258   }
1259
1260   return 0;
1261 }
1262
1263 /*
1264  * Build umode string for BURST command
1265  * --Run
1266  */
1267 char *umode_str(struct Client *cptr)
1268 {
1269   char* m = umodeBuf;                /* Maximum string size: "owidg\0" */
1270   int   i;
1271   int   c_flags;
1272
1273   c_flags = cptr->flags & SEND_UMODES;        /* cleaning up the original code */
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) && !(sptr->flags & 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) && (sptr->flags & 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", sptr->name, 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 = cptr->snomask;
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   cptr->snomask = 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 (!(acptr->user) || !(lp = acptr->user->silence) || !(user = sptr->user))
1463     return 0;
1464   sprintf_irc(sender, "%s!%s@%s", sptr->name, user->username, user->host);
1465   sprintf_irc(senderip, "%s!%s@%s", sptr->name, user->username,
1466               ircd_ntoa((const char*) &sptr->ip));
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, sptr->from, "%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 = &sptr->user->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 = &sptr->user->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 > MAXSILELENGTH) || (++cnt >= MAXSILES))
1532       {
1533         send_reply(sptr, ERR_SILELISTFULL, mask);
1534         return -1;
1535       }
1536       else if (!mmatch(lp->value.cp, mask))
1537         return -1;
1538     }
1539     lpp = &lp->next;
1540     lp = *lpp;
1541   }
1542   lp = make_link();
1543   memset(lp, 0, sizeof(struct SLink));
1544   lp->next = sptr->user->silence;
1545   lp->value.cp = (char*) MyMalloc(strlen(mask) + 1);
1546   assert(0 != lp->value.cp);
1547   strcpy(lp->value.cp, mask);
1548   if ((ip_start = strrchr(mask, '@')) && check_if_ipmask(ip_start + 1))
1549     lp->flags = CHFL_SILENCE_IPMASK;
1550   sptr->user->silence = lp;
1551   return 0;
1552 }
1553