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       /* XXX sendto_one used with ERR_INVALIDUSERNAME--explanations */
538       sendto_one(cptr, ":%s %d %s :Your username is invalid.",
539                  me.name, ERR_INVALIDUSERNAME, cptr->name);
540       sendto_one(cptr,
541                  ":%s %d %s :Connect with your real username, in lowercase.",
542                  me.name, ERR_INVALIDUSERNAME, cptr->name);
543       sendto_one(cptr, ":%s %d %s :If your mail address were foo@bar.com, "
544                  "your username would be foo.",
545                  me.name, ERR_INVALIDUSERNAME, cptr->name);
546       return exit_client(cptr, sptr, &me, "USER: Bad username");
547     }
548     Count_unknownbecomesclient(sptr, UserStats);
549   }
550   else {
551     ircd_strncpy(user->username, username, USERLEN);
552     Count_newremoteclient(UserStats, user->server);
553     if ((gline = gline_lookup(sptr)) && GlineIsActive(gline))
554       gline_resend(cptr, gline);
555   }
556   SetUser(sptr);
557
558   if (IsInvisible(sptr))
559     ++UserStats.inv_clients;
560   if (IsOper(sptr))
561     ++UserStats.opers;
562
563   if (MyConnect(sptr)) {
564     sptr->handler = CLIENT_HANDLER;
565     release_dns_reply(sptr);
566
567     send_reply(sptr, RPL_WELCOME, nick);
568     /*
569      * This is a duplicate of the NOTICE but see below...
570      */
571     send_reply(sptr, RPL_YOURHOST, me.name, version);
572     send_reply(sptr, RPL_CREATED, creation);
573     send_reply(sptr, RPL_MYINFO, me.name, version);
574     sprintf_irc(featurebuf,FEATURES,FEATURESVALUES);
575     send_reply(sptr, RPL_ISUPPORT, featurebuf);
576     m_lusers(sptr, sptr, 1, parv);
577     update_load();
578 #ifdef NODEFAULTMOTD
579     m_motd(sptr, NULL, 1, parv);
580 #else
581     m_motd(sptr, sptr, 1, parv);
582 #endif
583     nextping = CurrentTime;
584     if (sptr->snomask & SNO_NOISY)
585       set_snomask(sptr, sptr->snomask & SNO_NOISY, SNO_ADD);
586 #ifdef ALLOW_SNO_CONNEXIT
587 #ifdef SNO_CONNEXIT_IP
588     sendto_opmask_butone(0, SNO_CONNEXIT, "Client connecting: %s (%s@%s) "
589                          "[%s] {%d}", nick, user->username, user->host,
590                          cptr->sock_ip, get_client_class(sptr));
591 #else /* SNO_CONNEXIT_IP */
592     sendto_opmask_butone(0, SNO_CONEXIT, "Client connecting: %s (%s@%s)",
593                          nick, user->username, user->host);
594 #endif /* SNO_CONNEXIT_IP */
595 #endif /* ALLOW_SNO_CONNEXIT */
596     IPcheck_connect_succeeded(sptr);
597   }
598   else
599     /* if (IsServer(cptr)) */
600   {
601     struct Client *acptr;
602
603     acptr = user->server;
604     if (acptr->from != sptr->from)
605     {
606       sendcmdto_one(&me, CMD_KILL, cptr, "%C :%s (%s != %s[%s])",
607                     sptr, me.name, user->server->name, acptr->from->name,
608                     acptr->from->sockhost);
609       sptr->flags |= FLAGS_KILLED;
610       return exit_client(cptr, sptr, &me, "NICK server wrong direction");
611     }
612     else
613       sptr->flags |= (acptr->flags & FLAGS_TS8);
614
615     /*
616      * Check to see if this user is being propogated
617      * as part of a net.burst, or is using protocol 9.
618      * FIXME: This can be speeded up - its stupid to check it for
619      * every NICK message in a burst again  --Run.
620      */
621     for (acptr = user->server; acptr != &me; acptr = acptr->serv->up) {
622       if (IsBurst(acptr) || Protocol(acptr) < 10)
623         break;
624     }
625     if (!IPcheck_remote_connect(sptr, (acptr != &me)))
626       /*
627        * We ran out of bits to count this
628        */
629       return exit_client(cptr, sptr, &me, "More than 255 connections from this address");
630   }
631
632   tmpstr = umode_str(sptr);
633   sendcmdto_serv_butone(user->server, CMD_NICK, cptr, *tmpstr ?
634                         "%s %d %d %s %s +%s %s %s%s :%s" :
635                         "%s %d %d %s %s %s%s %s%s :%s",
636                         nick, sptr->hopcount + 1, sptr->lastnick,
637                         user->username, user->host, tmpstr,
638                         inttobase64(ip_base64, ntohl(sptr->ip.s_addr), 6),
639                         NumNick(sptr), sptr->info);
640
641   /* Send umode to client */
642   if (MyUser(sptr))
643   {
644     send_umode(cptr, sptr, 0, ALL_UMODES);
645     if (sptr->snomask != SNO_DEFAULT && (sptr->flags & FLAGS_SERVNOTICE))
646       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
647   }
648
649   return 0;
650 }
651
652
653 static const struct UserMode {
654   unsigned int flag;
655   char         c;
656 } userModeList[] = {
657   { FLAGS_OPER,        'o' },
658   { FLAGS_LOCOP,       'O' },
659   { FLAGS_INVISIBLE,   'i' },
660   { FLAGS_WALLOP,      'w' },
661   { FLAGS_SERVNOTICE,  's' },
662   { FLAGS_DEAF,        'd' },
663   { FLAGS_CHSERV,      'k' },
664   { FLAGS_DEBUG,       'g' }
665 };
666
667 #define USERMODELIST_SIZE sizeof(userModeList) / sizeof(struct UserMode)
668
669 #if 0
670 static int user_modes[] = {
671   FLAGS_OPER,        'o',
672   FLAGS_LOCOP,       'O',
673   FLAGS_INVISIBLE,   'i',
674   FLAGS_WALLOP,      'w',
675   FLAGS_SERVNOTICE,  's',
676   FLAGS_DEAF,        'd',
677   FLAGS_CHSERV,      'k',
678   FLAGS_DEBUG,       'g',
679   0,                  0
680 };
681 #endif
682
683 /*
684  * XXX - find a way to get rid of this
685  */
686 static char umodeBuf[BUFSIZE];
687
688 int set_nick_name(struct Client* cptr, struct Client* sptr,
689                   const char* nick, int parc, char* parv[])
690 {
691   if (IsServer(sptr)) {
692     int   i;
693     const char* p;
694
695     /*
696      * A server introducing a new client, change source
697      */
698     struct Client* new_client = make_client(cptr, STAT_UNKNOWN);
699     assert(0 != new_client);
700
701     new_client->hopcount = atoi(parv[2]);
702     new_client->lastnick = atoi(parv[3]);
703     if (Protocol(cptr) > 9 && parc > 7 && *parv[6] == '+') {
704       for (p = parv[6] + 1; *p; p++) {
705         for (i = 0; i < USERMODELIST_SIZE; ++i) {
706           if (userModeList[i].c == *p) {
707             new_client->flags |= userModeList[i].flag;
708             break;
709           }
710         }
711       }
712     }
713     /*
714      * Set new nick name.
715      */
716     strcpy(new_client->name, nick);
717     new_client->user = make_user(new_client);
718     new_client->user->server = sptr;
719     SetRemoteNumNick(new_client, parv[parc - 2]);
720     /*
721      * IP# of remote client
722      */
723     new_client->ip.s_addr = htonl(base64toint(parv[parc - 3]));
724
725     add_client_to_list(new_client);
726     hAddClient(new_client);
727
728     sptr->serv->ghost = 0;        /* :server NICK means end of net.burst */
729     ircd_strncpy(new_client->username, parv[4], USERLEN);
730     ircd_strncpy(new_client->user->host, parv[5], HOSTLEN);
731     ircd_strncpy(new_client->info, parv[parc - 1], REALLEN);
732     return register_user(cptr, new_client, new_client->name, parv[4]);
733   }
734   else if (sptr->name[0]) {
735     /*
736      * Client changing its nick
737      *
738      * If the client belongs to me, then check to see
739      * if client is on any channels where it is currently
740      * banned.  If so, do not allow the nick change to occur.
741      */
742     if (MyUser(sptr)) {
743       const char* channel_name;
744       if ((channel_name = find_no_nickchange_channel(sptr))) {
745         return send_reply(cptr, ERR_BANNICKCHANGE, channel_name);
746       }
747       /*
748        * Refuse nick change if the last nick change was less
749        * then 30 seconds ago. This is intended to get rid of
750        * clone bots doing NICK FLOOD. -SeKs
751        * If someone didn't change their nick for more then 60 seconds
752        * however, allow to do two nick changes immedately after another
753        * before limiting the nick flood. -Run
754        */
755       if (CurrentTime < cptr->nextnick) {
756         cptr->nextnick += 2;
757         send_reply(cptr, ERR_NICKTOOFAST, parv[1],
758                    cptr->nextnick - CurrentTime);
759         /* Send error message */
760         sendcmdto_one(cptr, CMD_NICK, cptr, "%s", cptr->name);
761         /* bounce NICK to user */
762         return 0;                /* ignore nick change! */
763       }
764       else {
765         /* Limit total to 1 change per NICK_DELAY seconds: */
766         cptr->nextnick += NICK_DELAY;
767         /* However allow _maximal_ 1 extra consecutive nick change: */
768         if (cptr->nextnick < CurrentTime)
769           cptr->nextnick = CurrentTime;
770       }
771     }
772     /*
773      * Also set 'lastnick' to current time, if changed.
774      */
775     if (0 != ircd_strcmp(parv[0], nick))
776       sptr->lastnick = (sptr == cptr) ? TStime() : atoi(parv[2]);
777
778     /*
779      * Client just changing his/her nick. If he/she is
780      * on a channel, send note of change to all clients
781      * on that channel. Propagate notice to other servers.
782      */
783     if (IsUser(sptr)) {
784       sendcmdto_common_channels(sptr, CMD_NICK, ":%s", nick);
785       add_history(sptr, 1);
786       sendcmdto_serv_butone(sptr, CMD_NICK, cptr, "%s %Tu", nick,
787                             sptr->lastnick);
788     }
789     else
790       sendcmdto_one(sptr, CMD_NICK, sptr, ":%s", nick);
791
792     if (sptr->name[0])
793       hRemClient(sptr);
794     strcpy(sptr->name, nick);
795     hAddClient(sptr);
796   }
797   else {
798     /* Local client setting NICK the first time */
799
800     strcpy(sptr->name, nick);
801     if (!sptr->user) {
802       sptr->user = make_user(sptr);
803       sptr->user->server = &me;
804     }
805     SetLocalNumNick(sptr);
806     hAddClient(sptr);
807
808     /*
809      * If the client hasn't gotten a cookie-ping yet,
810      * choose a cookie and send it. -record!jegelhof@cloud9.net
811      */
812     if (!sptr->cookie) {
813       do {
814         sptr->cookie = (ircrandom() & 0x7fffffff);
815       } while (!sptr->cookie);
816       /* XXX sendto_one used to send PING--must be very careful! */
817       sendto_one(cptr, "PING :%u", sptr->cookie);
818     }
819     else if (*sptr->user->host && sptr->cookie == COOKIE_VERIFIED) {
820       /*
821        * USER and PONG already received, now we have NICK.
822        * register_user may reject the client and call exit_client
823        * for it - must test this and exit m_nick too !
824        */
825       sptr->lastnick = TStime();        /* Always local client */
826       if (register_user(cptr, sptr, nick, sptr->user->username) == CPTR_KILLED)
827         return CPTR_KILLED;
828     }
829   }
830   return 0;
831 }
832
833 static unsigned char hash_target(unsigned int target)
834 {
835   return (unsigned char) (target >> 16) ^ (target >> 8);
836 }
837
838 /*
839  * add_target
840  *
841  * sptr must be a local client!
842  *
843  * Cannonifies target for client `sptr'.
844  */
845 void add_target(struct Client *sptr, void *target)
846 {
847   unsigned char  hash = hash_target((unsigned int) target);
848   unsigned char* targets;
849   int            i;
850   assert(0 != sptr);
851   assert(sptr->local);
852
853   targets = sptr->targets;
854   /* 
855    * Already in table?
856    */
857   for (i = 0; i < MAXTARGETS; ++i) {
858     if (targets[i] == hash)
859       return;
860   }
861   /*
862    * New target
863    */
864   memmove(&targets[RESERVEDTARGETS + 1],
865           &targets[RESERVEDTARGETS], MAXTARGETS - RESERVEDTARGETS - 1);
866   targets[RESERVEDTARGETS] = hash;
867 }
868
869 /*
870  * check_target_limit
871  *
872  * sptr must be a local client !
873  *
874  * Returns 'true' (1) when too many targets are addressed.
875  * Returns 'false' (0) when it's ok to send to this target.
876  */
877 int check_target_limit(struct Client *sptr, void *target, const char *name,
878     int created)
879 {
880   unsigned char hash = hash_target((unsigned int) target);
881   int            i;
882   unsigned char* targets;
883
884   assert(0 != sptr);
885   assert(sptr->local);
886   targets = sptr->targets;
887
888   /*
889    * Same target as last time?
890    */
891   if (targets[0] == hash)
892     return 0;
893   for (i = 1; i < MAXTARGETS; ++i) {
894     if (targets[i] == hash) {
895       memmove(&targets[1], &targets[0], i);
896       targets[0] = hash;
897       return 0;
898     }
899   }
900   /*
901    * New target
902    */
903   if (!created) {
904     if (CurrentTime < sptr->nexttarget) {
905       if (sptr->nexttarget - CurrentTime < TARGET_DELAY + 8) {
906         /*
907          * No server flooding
908          */
909         sptr->nexttarget += 2;
910         send_reply(sptr, ERR_TARGETTOOFAST, name,
911                    sptr->nexttarget - CurrentTime);
912       }
913       return 1;
914     }
915     else {
916 #ifdef GODMODE
917       /* XXX Let's get rid of GODMODE */
918       sendto_one(sptr, ":%s NOTICE %s :New target: %s; ft " TIME_T_FMT,
919           me.name, sptr->name, name, (CurrentTime - sptr->nexttarget) / TARGET_DELAY);
920 #endif
921       sptr->nexttarget += TARGET_DELAY;
922       if (sptr->nexttarget < CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1)))
923         sptr->nexttarget = CurrentTime - (TARGET_DELAY * (MAXTARGETS - 1));
924     }
925   }
926   memmove(&targets[1], &targets[0], MAXTARGETS - 1);
927   targets[0] = hash;
928   return 0;
929 }
930
931 /*
932  * whisper - called from m_cnotice and m_cprivmsg.
933  *
934  * parv[0] = sender prefix
935  * parv[1] = nick
936  * parv[2] = #channel
937  * parv[3] = Private message text
938  *
939  * Added 971023 by Run.
940  * Reason: Allows channel operators to sent an arbitrary number of private
941  *   messages to users on their channel, avoiding the max.targets limit.
942  *   Building this into m_private would use too much cpu because we'd have
943  *   to a cross channel lookup for every private message!
944  * Note that we can't allow non-chan ops to use this command, it would be
945  *   abused by mass advertisers.
946  *
947  */
948 int whisper(struct Client* source, const char* nick, const char* channel,
949             const char* text, int is_notice)
950 {
951   struct Client*     dest;
952   struct Channel*    chptr;
953   struct Membership* membership;
954
955   assert(0 != source);
956   assert(0 != nick);
957   assert(0 != channel);
958   assert(MyUser(source));
959
960   if (!(dest = FindUser(nick))) {
961     return send_reply(source, ERR_NOSUCHNICK, nick);
962   }
963   if (!(chptr = FindChannel(channel))) {
964     return send_reply(source, ERR_NOSUCHCHANNEL, channel);
965   }
966   /*
967    * compare both users channel lists, instead of the channels user list
968    * since the link is the same, this should be a little faster for channels
969    * with a lot of users
970    */
971   for (membership = source->user->channel; membership; membership = membership->next_channel) {
972     if (chptr == membership->channel)
973       break;
974   }
975   if (0 == membership) {
976     return send_reply(source, ERR_NOTONCHANNEL, chptr->chname);
977   }
978   if (!IsVoicedOrOpped(membership)) {
979     return send_reply(source, ERR_VOICENEEDED, chptr->chname);
980   }
981   /*
982    * lookup channel in destination
983    */
984   assert(0 != dest->user);
985   for (membership = dest->user->channel; membership; membership = membership->next_channel) {
986     if (chptr == membership->channel)
987       break;
988   }
989   if (0 == membership || IsZombie(membership)) {
990     return send_reply(source, ERR_USERNOTINCHANNEL, dest->name, chptr->chname);
991   }
992   if (is_silenced(source, dest))
993     return 0;
994           
995   if (dest->user->away)
996     send_reply(source, RPL_AWAY, dest->name, dest->user->away);
997   if (is_notice)
998     sendcmdto_one(source, CMD_NOTICE, dest, "%C :%s", dest, text);
999   else
1000     sendcmdto_one(source, CMD_PRIVATE, dest, "%C :%s", dest, text);
1001   return 0;
1002 }
1003
1004
1005 /*
1006  * added Sat Jul 25 07:30:42 EST 1992
1007  */
1008 void send_umode_out(struct Client *cptr, struct Client *sptr, int old)
1009 {
1010   int i;
1011   struct Client *acptr;
1012
1013   send_umode(NULL, sptr, old, SEND_UMODES);
1014
1015   for (i = HighestFd; i >= 0; i--) {
1016     if ((acptr = LocalClientArray[i]) && IsServer(acptr) &&
1017         (acptr != cptr) && (acptr != sptr) && *umodeBuf)
1018       sendcmdto_one(sptr, CMD_MODE, acptr, "%s :%s", sptr->name, umodeBuf);
1019   }
1020   if (cptr && MyUser(cptr))
1021     send_umode(cptr, sptr, old, ALL_UMODES);
1022 }
1023
1024
1025 /*
1026  * send_user_info - send user info userip/userhost
1027  * NOTE: formatter must put info into buffer and return a pointer to the end of
1028  * the data it put in the buffer.
1029  */
1030 void send_user_info(struct Client* sptr, char* names, int rpl, InfoFormatter fmt)
1031 {
1032   char*          sbuf;
1033   char*          name;
1034   char*          p = 0;
1035   int            arg_count = 0;
1036   int            users_found = 0;
1037   struct Client* acptr;
1038   char           buf[BUFSIZE * 2];
1039
1040   assert(0 != sptr);
1041   assert(0 != names);
1042   assert(0 != fmt);
1043
1044   sbuf = sprintf_irc(buf, rpl_str(rpl), me.name, sptr->name);
1045
1046   for (name = ircd_strtok(&p, names, " "); name; name = ircd_strtok(&p, 0, " ")) {
1047     if ((acptr = FindUser(name))) {
1048       if (users_found++)
1049         *sbuf++ = ' ';
1050       sbuf = (*fmt)(acptr, sbuf);
1051     }
1052     if (5 == ++arg_count)
1053       break;
1054   }
1055   if (users_found)
1056     send_buffer(sptr, buf);
1057 }
1058
1059
1060 /*
1061  * set_user_mode() added 15/10/91 By Darren Reed.
1062  *
1063  * parv[0] - sender
1064  * parv[1] - username to change mode for
1065  * parv[2] - modes to change
1066  */
1067 int set_user_mode(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
1068 {
1069   char** p;
1070   char*  m;
1071   struct Client *acptr;
1072   int what;
1073   int i;
1074   int setflags;
1075   unsigned int tmpmask = 0;
1076   int snomask_given = 0;
1077   char buf[BUFSIZE];
1078
1079   what = MODE_ADD;
1080
1081   if (parc < 2)
1082     return need_more_params(sptr, "MODE");
1083
1084   if (!(acptr = FindUser(parv[1])))
1085   {
1086     if (MyConnect(sptr))
1087       send_reply(sptr, ERR_NOSUCHCHANNEL, parv[1]);
1088     return 0;
1089   }
1090
1091   if (IsServer(sptr) || sptr != acptr)
1092   {
1093     if (IsServer(cptr))
1094       sendcmdto_flag_butone(&me, CMD_WALLOPS, 0, FLAGS_WALLOP,
1095                             ":MODE for User %s from %s!%s", parv[1],
1096                             cptr->name, sptr->name);
1097     else
1098       send_reply(sptr, ERR_USERSDONTMATCH);
1099     return 0;
1100   }
1101
1102   if (parc < 3)
1103   {
1104     m = buf;
1105     *m++ = '+';
1106     for (i = 0; i < USERMODELIST_SIZE; ++i) {
1107       if ( (userModeList[i].flag & sptr->flags))
1108         *m++ = userModeList[i].c;
1109     }
1110     *m = '\0';
1111     send_reply(sptr, RPL_UMODEIS, buf);
1112     if ((sptr->flags & FLAGS_SERVNOTICE) && MyConnect(sptr)
1113         && sptr->snomask !=
1114         (unsigned int)(IsOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT))
1115       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
1116     return 0;
1117   }
1118
1119   /*
1120    * find flags already set for user
1121    * why not just copy them?
1122    */
1123   setflags = sptr->flags;
1124 #if 0
1125   setflags = 0;
1126   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1127     if (sptr->flags & userModeList[i].flag)
1128       setflags |= userModeList[i].flag;
1129   }
1130 #endif
1131   if (MyConnect(sptr))
1132     tmpmask = sptr->snomask;
1133
1134   /*
1135    * parse mode change string(s)
1136    */
1137   for (p = &parv[2]; *p; p++) {       /* p is changed in loop too */
1138     for (m = *p; *m; m++) {
1139       switch (*m) {
1140       case '+':
1141         what = MODE_ADD;
1142         break;
1143       case '-':
1144         what = MODE_DEL;
1145         break;
1146       case 's':
1147         if (*(p + 1) && is_snomask(*(p + 1))) {
1148           snomask_given = 1;
1149           tmpmask = umode_make_snomask(tmpmask, *++p, what);
1150           tmpmask &= (IsAnOper(sptr) ? SNO_ALL : SNO_USER);
1151         }
1152         else
1153           tmpmask = (what == MODE_ADD) ?
1154               (IsAnOper(sptr) ? SNO_OPERDEFAULT : SNO_DEFAULT) : 0;
1155         if (tmpmask)
1156           sptr->flags |= FLAGS_SERVNOTICE;
1157         else
1158           sptr->flags &= ~FLAGS_SERVNOTICE;
1159         break;
1160       case 'w':
1161         if (what == MODE_ADD)
1162           SetWallops(sptr);
1163         else
1164           ClearWallops(sptr);
1165         break;
1166       case 'o':
1167         if (what == MODE_ADD)
1168           SetOper(sptr);
1169         else {
1170           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1171           if (MyConnect(sptr)) {
1172             tmpmask = sptr->snomask & ~SNO_OPER;
1173             sptr->handler = CLIENT_HANDLER;
1174           }
1175         }
1176         break;
1177       case 'O':
1178         if (what == MODE_ADD)
1179           SetLocOp(sptr);
1180         else { 
1181           sptr->flags &= ~(FLAGS_OPER | FLAGS_LOCOP);
1182           if (MyConnect(sptr)) {
1183             tmpmask = sptr->snomask & ~SNO_OPER;
1184             sptr->handler = CLIENT_HANDLER;
1185           }
1186         }
1187         break;
1188       case 'i':
1189         if (what == MODE_ADD)
1190           SetInvisible(sptr);
1191         else
1192           ClearInvisible(sptr);
1193         break;
1194       case 'd':
1195         if (what == MODE_ADD)
1196           SetDeaf(sptr);
1197         else
1198           ClearDeaf(sptr);
1199         break;
1200       case 'k':
1201         if (what == MODE_ADD)
1202           SetChannelService(sptr);
1203         else
1204           ClearChannelService(sptr);
1205         break;
1206       case 'g':
1207         if (what == MODE_ADD)
1208           SetDebug(sptr);
1209         else
1210           ClearDebug(sptr);
1211         break;
1212       default:
1213         break;
1214       }
1215     }
1216   }
1217   /*
1218    * Evaluate rules for new user mode
1219    * Stop users making themselves operators too easily:
1220    */
1221   if (!(setflags & FLAGS_OPER) && IsOper(sptr) && !IsServer(cptr))
1222     ClearOper(sptr);
1223   if (!(setflags & FLAGS_LOCOP) && IsLocOp(sptr) && !IsServer(cptr))
1224     ClearLocOp(sptr);
1225 #ifdef WALLOPS_OPER_ONLY
1226   /*
1227    * only send wallops to opers
1228    */
1229   if (!IsAnOper(sptr) && !(setflags & FLAGS_WALLOP) && !IsServer(cptr))
1230     ClearWallops(sptr);
1231 #endif
1232   if ((setflags & (FLAGS_OPER | FLAGS_LOCOP)) && !IsAnOper(sptr) &&
1233       MyConnect(sptr))
1234     det_confs_butmask(sptr, CONF_CLIENT & ~CONF_OPS);
1235   /*
1236    * new umode; servers can set it, local users cannot;
1237    * prevents users from /kick'ing or /mode -o'ing
1238    */
1239   if (!(setflags & FLAGS_CHSERV) && !IsServer(cptr))
1240     ClearChannelService(sptr);
1241   /*
1242    * Compare new flags with old flags and send string which
1243    * will cause servers to update correctly.
1244    */
1245   if ((setflags & FLAGS_OPER) && !IsOper(sptr))
1246     --UserStats.opers;
1247   if (!(setflags & FLAGS_OPER) && IsOper(sptr))
1248     ++UserStats.opers;
1249   if ((setflags & FLAGS_INVISIBLE) && !IsInvisible(sptr))
1250     --UserStats.inv_clients;
1251   if (!(setflags & FLAGS_INVISIBLE) && IsInvisible(sptr))
1252     ++UserStats.inv_clients;
1253   send_umode_out(cptr, sptr, setflags);
1254
1255   if (MyConnect(sptr)) {
1256     if (tmpmask != sptr->snomask)
1257       set_snomask(sptr, tmpmask, SNO_SET);
1258     if (sptr->snomask && snomask_given)
1259       send_reply(sptr, RPL_SNOMASK, sptr->snomask, sptr->snomask);
1260   }
1261
1262   return 0;
1263 }
1264
1265 /*
1266  * Build umode string for BURST command
1267  * --Run
1268  */
1269 char *umode_str(struct Client *cptr)
1270 {
1271   char* m = umodeBuf;                /* Maximum string size: "owidg\0" */
1272   int   i;
1273   int   c_flags;
1274
1275   c_flags = cptr->flags & SEND_UMODES;        /* cleaning up the original code */
1276
1277   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1278     if ( (c_flags & userModeList[i].flag))
1279       *m++ = userModeList[i].c;
1280   }
1281   *m = '\0';
1282
1283   return umodeBuf;                /* Note: static buffer, gets
1284                                    overwritten by send_umode() */
1285 }
1286
1287 /*
1288  * Send the MODE string for user (user) to connection cptr
1289  * -avalon
1290  */
1291 void send_umode(struct Client *cptr, struct Client *sptr, int old, int sendmask)
1292 {
1293   int i;
1294   int flag;
1295   char *m;
1296   int what = MODE_NULL;
1297
1298   /*
1299    * Build a string in umodeBuf to represent the change in the user's
1300    * mode between the new (sptr->flag) and 'old'.
1301    */
1302   m = umodeBuf;
1303   *m = '\0';
1304   for (i = 0; i < USERMODELIST_SIZE; ++i) {
1305     flag = userModeList[i].flag;
1306     if (MyUser(sptr) && !(flag & sendmask))
1307       continue;
1308     if ( (flag & old) && !(sptr->flags & flag))
1309     {
1310       if (what == MODE_DEL)
1311         *m++ = userModeList[i].c;
1312       else
1313       {
1314         what = MODE_DEL;
1315         *m++ = '-';
1316         *m++ = userModeList[i].c;
1317       }
1318     }
1319     else if (!(flag & old) && (sptr->flags & flag))
1320     {
1321       if (what == MODE_ADD)
1322         *m++ = userModeList[i].c;
1323       else
1324       {
1325         what = MODE_ADD;
1326         *m++ = '+';
1327         *m++ = userModeList[i].c;
1328       }
1329     }
1330   }
1331   *m = '\0';
1332   if (*umodeBuf && cptr)
1333     sendcmdto_one(sptr, CMD_MODE, cptr, "%s :%s", sptr->name, umodeBuf);
1334 }
1335
1336 /*
1337  * Check to see if this resembles a sno_mask.  It is if 1) there is
1338  * at least one digit and 2) The first digit occurs before the first
1339  * alphabetic character.
1340  */
1341 int is_snomask(char *word)
1342 {
1343   if (word)
1344   {
1345     for (; *word; word++)
1346       if (IsDigit(*word))
1347         return 1;
1348       else if (IsAlpha(*word))
1349         return 0;
1350   }
1351   return 0;
1352 }
1353
1354 /*
1355  * If it begins with a +, count this as an additive mask instead of just
1356  * a replacement.  If what == MODE_DEL, "+" has no special effect.
1357  */
1358 unsigned int umode_make_snomask(unsigned int oldmask, char *arg, int what)
1359 {
1360   unsigned int sno_what;
1361   unsigned int newmask;
1362   if (*arg == '+')
1363   {
1364     arg++;
1365     if (what == MODE_ADD)
1366       sno_what = SNO_ADD;
1367     else
1368       sno_what = SNO_DEL;
1369   }
1370   else if (*arg == '-')
1371   {
1372     arg++;
1373     if (what == MODE_ADD)
1374       sno_what = SNO_DEL;
1375     else
1376       sno_what = SNO_ADD;
1377   }
1378   else
1379     sno_what = (what == MODE_ADD) ? SNO_SET : SNO_DEL;
1380   /* pity we don't have strtoul everywhere */
1381   newmask = (unsigned int)atoi(arg);
1382   if (sno_what == SNO_DEL)
1383     newmask = oldmask & ~newmask;
1384   else if (sno_what == SNO_ADD)
1385     newmask |= oldmask;
1386   return newmask;
1387 }
1388
1389 static void delfrom_list(struct Client *cptr, struct SLink **list)
1390 {
1391   struct SLink* tmp;
1392   struct SLink* prv = NULL;
1393
1394   for (tmp = *list; tmp; tmp = tmp->next) {
1395     if (tmp->value.cptr == cptr) {
1396       if (prv)
1397         prv->next = tmp->next;
1398       else
1399         *list = tmp->next;
1400       free_link(tmp);
1401       break;
1402     }
1403     prv = tmp;
1404   }
1405 }
1406
1407 /*
1408  * This function sets a Client's server notices mask, according to
1409  * the parameter 'what'.  This could be even faster, but the code
1410  * gets mighty hard to read :)
1411  */
1412 void set_snomask(struct Client *cptr, unsigned int newmask, int what)
1413 {
1414   unsigned int oldmask, diffmask;        /* unsigned please */
1415   int i;
1416   struct SLink *tmp;
1417
1418   oldmask = cptr->snomask;
1419
1420   if (what == SNO_ADD)
1421     newmask |= oldmask;
1422   else if (what == SNO_DEL)
1423     newmask = oldmask & ~newmask;
1424   else if (what != SNO_SET)        /* absolute set, no math needed */
1425     sendto_opmask_butone(0, SNO_OLDSNO, "setsnomask called with %d ?!", what);
1426
1427   newmask &= (IsAnOper(cptr) ? SNO_ALL : SNO_USER);
1428
1429   diffmask = oldmask ^ newmask;
1430
1431   for (i = 0; diffmask >> i; i++) {
1432     if (((diffmask >> i) & 1))
1433     {
1434       if (((newmask >> i) & 1))
1435       {
1436         tmp = make_link();
1437         tmp->next = opsarray[i];
1438         tmp->value.cptr = cptr;
1439         opsarray[i] = tmp;
1440       }
1441       else
1442         /* not real portable :( */
1443         delfrom_list(cptr, &opsarray[i]);
1444     }
1445   }
1446   cptr->snomask = newmask;
1447 }
1448
1449 /*
1450  * is_silenced : Does the actual check wether sptr is allowed
1451  *               to send a message to acptr.
1452  *               Both must be registered persons.
1453  * If sptr is silenced by acptr, his message should not be propagated,
1454  * but more over, if this is detected on a server not local to sptr
1455  * the SILENCE mask is sent upstream.
1456  */
1457 int is_silenced(struct Client *sptr, struct Client *acptr)
1458 {
1459   struct SLink *lp;
1460   struct User *user;
1461   static char sender[HOSTLEN + NICKLEN + USERLEN + 5];
1462   static char senderip[16 + NICKLEN + USERLEN + 5];
1463
1464   if (!(acptr->user) || !(lp = acptr->user->silence) || !(user = sptr->user))
1465     return 0;
1466   sprintf_irc(sender, "%s!%s@%s", sptr->name, user->username, user->host);
1467   sprintf_irc(senderip, "%s!%s@%s", sptr->name, user->username,
1468               ircd_ntoa((const char*) &sptr->ip));
1469   for (; lp; lp = lp->next)
1470   {
1471     if ((!(lp->flags & CHFL_SILENCE_IPMASK) && !match(lp->value.cp, sender)) ||
1472         ((lp->flags & CHFL_SILENCE_IPMASK) && !match(lp->value.cp, senderip)))
1473     {
1474       if (!MyConnect(sptr))
1475       {
1476         sendcmdto_one(acptr, CMD_SILENCE, sptr->from, "%C %s", sptr,
1477                       lp->value.cp);
1478       }
1479       return 1;
1480     }
1481   }
1482   return 0;
1483 }
1484
1485 /*
1486  * del_silence
1487  *
1488  * Removes all silence masks from the list of sptr that fall within `mask'
1489  * Returns -1 if none where found, 0 otherwise.
1490  */
1491 int del_silence(struct Client *sptr, char *mask)
1492 {
1493   struct SLink **lp;
1494   struct SLink *tmp;
1495   int ret = -1;
1496
1497   for (lp = &sptr->user->silence; *lp;) {
1498     if (!mmatch(mask, (*lp)->value.cp))
1499     {
1500       tmp = *lp;
1501       *lp = tmp->next;
1502       MyFree(tmp->value.cp);
1503       free_link(tmp);
1504       ret = 0;
1505     }
1506     else
1507       lp = &(*lp)->next;
1508   }
1509   return ret;
1510 }
1511
1512 int add_silence(struct Client* sptr, const char* mask)
1513 {
1514   struct SLink *lp, **lpp;
1515   int cnt = 0, len = strlen(mask);
1516   char *ip_start;
1517
1518   for (lpp = &sptr->user->silence, lp = *lpp; lp;)
1519   {
1520     if (0 == ircd_strcmp(mask, lp->value.cp))
1521       return -1;
1522     if (!mmatch(mask, lp->value.cp))
1523     {
1524       struct SLink *tmp = lp;
1525       *lpp = lp = lp->next;
1526       MyFree(tmp->value.cp);
1527       free_link(tmp);
1528       continue;
1529     }
1530     if (MyUser(sptr))
1531     {
1532       len += strlen(lp->value.cp);
1533       if ((len > MAXSILELENGTH) || (++cnt >= MAXSILES))
1534       {
1535         send_reply(sptr, ERR_SILELISTFULL, mask);
1536         return -1;
1537       }
1538       else if (!mmatch(lp->value.cp, mask))
1539         return -1;
1540     }
1541     lpp = &lp->next;
1542     lp = *lpp;
1543   }
1544   lp = make_link();
1545   memset(lp, 0, sizeof(struct SLink));
1546   lp->next = sptr->user->silence;
1547   lp->value.cp = (char*) MyMalloc(strlen(mask) + 1);
1548   assert(0 != lp->value.cp);
1549   strcpy(lp->value.cp, mask);
1550   if ((ip_start = strrchr(mask, '@')) && check_if_ipmask(ip_start + 1))
1551     lp->flags = CHFL_SILENCE_IPMASK;
1552   sptr->user->silence = lp;
1553   return 0;
1554 }
1555