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