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