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