]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/channel.c
0b194a0968bae23f89c56798a9f300e13b55fb99
[ngircd-alex.git] / src / ngircd / channel.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2014 Alexander Barton (alex@barton.de) and Contributors.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12 #define __channel_c__
13
14 #include "portab.h"
15
16 /**
17  * @file
18  * Channel management
19  */
20
21 #include <assert.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <strings.h>
27 #include <time.h>
28
29 #include "conn-func.h"
30
31 #include "channel.h"
32
33 #include "irc-write.h"
34 #include "conf.h"
35 #include "hash.h"
36 #include "log.h"
37 #include "messages.h"
38 #include "match.h"
39 #include "parse.h"
40 #include "irc-mode.h"
41
42 #define REMOVE_PART 0
43 #define REMOVE_QUIT 1
44 #define REMOVE_KICK 2
45
46 static CHANNEL *My_Channels;
47 static CL2CHAN *My_Cl2Chan;
48
49 static CL2CHAN *Get_Cl2Chan PARAMS(( CHANNEL *Chan, CLIENT *Client ));
50 static CL2CHAN *Add_Client PARAMS(( CHANNEL *Chan, CLIENT *Client ));
51 static bool Remove_Client PARAMS(( int Type, CHANNEL *Chan, CLIENT *Client, CLIENT *Origin, const char *Reason, bool InformServer ));
52 static CL2CHAN *Get_First_Cl2Chan PARAMS(( CLIENT *Client, CHANNEL *Chan ));
53 static CL2CHAN *Get_Next_Cl2Chan PARAMS(( CL2CHAN *Start, CLIENT *Client, CHANNEL *Chan ));
54 static void Delete_Channel PARAMS(( CHANNEL *Chan ));
55 static void Free_Channel PARAMS(( CHANNEL *Chan ));
56 static void Set_KeyFile PARAMS((CHANNEL *Chan, const char *KeyFile));
57
58
59 GLOBAL void
60 Channel_Init( void )
61 {
62         My_Channels = NULL;
63         My_Cl2Chan = NULL;
64 } /* Channel_Init */
65
66
67 GLOBAL struct list_head *
68 Channel_GetListBans(CHANNEL *c)
69 {
70         assert(c != NULL);
71         return &c->list_bans;
72 }
73
74
75 GLOBAL struct list_head *
76 Channel_GetListExcepts(CHANNEL *c)
77 {
78         assert(c != NULL);
79         return &c->list_excepts;
80 }
81
82
83 GLOBAL struct list_head *
84 Channel_GetListInvites(CHANNEL *c)
85 {
86         assert(c != NULL);
87         return &c->list_invites;
88 }
89
90
91 /**
92  * Generate predefined persistent channels and &SERVER
93  */
94 GLOBAL void
95 Channel_InitPredefined( void )
96 {
97         CHANNEL *new_chan;
98         REQUEST Req;
99         const struct Conf_Channel *conf_chan;
100         char *c;
101         char modes[COMMAND_LEN], name[CHANNEL_NAME_LEN];
102         size_t i, n, channel_count = array_length(&Conf_Channels, sizeof(*conf_chan));
103
104         conf_chan = array_start(&Conf_Channels);
105
106         assert(channel_count == 0 || conf_chan != NULL);
107
108         for (i = 0; i < channel_count; i++, conf_chan++) {
109                 if (!conf_chan->name[0])
110                         continue;
111                 if (!Channel_IsValidName(conf_chan->name)) {
112                         Log(LOG_ERR,
113                             "Can't create pre-defined channel: invalid name: \"%s\"",
114                             conf_chan->name);
115                         continue;
116                 }
117
118                 new_chan = Channel_Search(conf_chan->name);
119                 if (new_chan) {
120                         Log(LOG_INFO,
121                             "Can't create pre-defined channel \"%s\": name already in use.",
122                             conf_chan->name);
123                         Set_KeyFile(new_chan, conf_chan->keyfile);
124                         continue;
125                 }
126
127                 new_chan = Channel_Create(conf_chan->name);
128                 if (!new_chan) {
129                         Log(LOG_ERR, "Can't create pre-defined channel \"%s\"!",
130                                                         conf_chan->name);
131                         continue;
132                 }
133                 Log(LOG_INFO, "Created pre-defined channel \"%s\".",
134                                                 conf_chan->name);
135
136                 Channel_ModeAdd(new_chan, 'P');
137
138                 if (conf_chan->topic[0])
139                         Channel_SetTopic(new_chan, NULL, conf_chan->topic);
140
141                 /* Evaluate modes strings with fake requests */
142                 if(conf_chan->modes_num) {
143                         /* Prepare fake request structure */
144                         strlcpy(name, conf_chan->name, sizeof(name));
145                         Log(LOG_INFO, "Evaluating predefined channel modes for \"%s\".", name);
146                         Req.argv[0] = name;
147                         Req.prefix = Client_ID(Client_ThisServer());
148                         Req.command = "MODE";
149
150                         /* Iterate over channel modes strings */
151                         for (n = 0; n < conf_chan->modes_num; n++) {
152                                 Req.argc = 1;
153                                 strlcpy(modes, conf_chan->modes[n], sizeof(modes));
154                                 Log(LOG_DEBUG, "Evaluate \"MODE %s %s\".", name, modes);
155                                 c = strtok(modes, " ");
156                                 while (c && Req.argc < 15) {
157                                         Req.argv[Req.argc++] = c;
158                                         c = strtok(0, " ");
159                                 }
160                                 if(Req.argc > 1)
161                                         IRC_MODE(Client_ThisServer(), &Req);
162
163                                 /* Original channel modes srings are no longer needed */
164                                 free(conf_chan->modes[n]);
165                         }
166                 }
167
168                 Channel_SetKey(new_chan, conf_chan->key);
169                 Channel_SetMaxUsers(new_chan, conf_chan->maxusers);
170                 Set_KeyFile(new_chan, conf_chan->keyfile);
171         }
172         if (channel_count)
173                 array_free(&Conf_Channels);
174
175         /* Make sure the local &SERVER channel exists */
176         if (!Channel_Search("&SERVER")) {
177                 new_chan = Channel_Create("&SERVER");
178                 if (new_chan) {
179                         Channel_SetModes(new_chan, "mnPt");
180                         Channel_SetTopic(new_chan, Client_ThisServer(),
181                                          "Server Messages");
182                 } else
183                         Log(LOG_ERR, "Failed to create \"&SERVER\" channel!");
184         } else
185                 LogDebug("Required channel \"&SERVER\" already exists, ok.");
186 } /* Channel_InitPredefined */
187
188
189 static void
190 Free_Channel(CHANNEL *chan)
191 {
192         array_free(&chan->topic);
193         array_free(&chan->keyfile);
194         Lists_Free(&chan->list_bans);
195         Lists_Free(&chan->list_excepts);
196         Lists_Free(&chan->list_invites);
197
198         free(chan);
199 }
200
201
202 GLOBAL void
203 Channel_Exit( void )
204 {
205         CHANNEL *c, *c_next;
206         CL2CHAN *cl2chan, *cl2chan_next;
207
208         /* free struct Channel */
209         c = My_Channels;
210         while (c) {
211                 c_next = c->next;
212                 Free_Channel(c);
213                 c = c_next;
214         }
215
216         /* Free Channel allocation table */
217         cl2chan = My_Cl2Chan;
218         while (cl2chan) {
219                 cl2chan_next = cl2chan->next;
220                 free(cl2chan);
221                 cl2chan = cl2chan_next;
222         }
223 } /* Channel_Exit */
224
225
226 /**
227  * Join Channel
228  * This function lets a client join a channel.  First, the function
229  * checks that the specified channel name is valid and that the client
230  * isn't already a member.  If the specified channel doesn't exist,
231  * a new channel is created.  Client is added to channel by function
232  * Add_Client().
233  */
234 GLOBAL bool
235 Channel_Join( CLIENT *Client, const char *Name )
236 {
237         CHANNEL *chan;
238
239         assert(Client != NULL);
240         assert(Name != NULL);
241
242         /* Check that the channel name is valid */
243         if (! Channel_IsValidName(Name)) {
244                 IRC_WriteErrClient(Client, ERR_NOSUCHCHANNEL_MSG,
245                                    Client_ID(Client), Name);
246                 return false;
247         }
248
249         chan = Channel_Search(Name);
250         if(chan) {
251                 /* Check if the client is already in the channel */
252                 if (Get_Cl2Chan(chan, Client))
253                         return false;
254         } else {
255                 /* If the specified channel does not exist, the channel
256                  * is now created */
257                 chan = Channel_Create(Name);
258                 if (!chan)
259                         return false;
260         }
261
262         /* Add user to Channel */
263         if (! Add_Client(chan, Client))
264                 return false;
265
266         return true;
267 } /* Channel_Join */
268
269
270 /**
271  * Part client from channel.
272  * This function lets a client part from a channel. First, the function checks
273  * if the channel exists and the client is a member of it and sends out
274  * appropriate error messages if not. The real work is done by the function
275  * Remove_Client().
276  */
277 GLOBAL bool
278 Channel_Part(CLIENT * Client, CLIENT * Origin, const char *Name, const char *Reason)
279 {
280         CHANNEL *chan;
281
282         assert(Client != NULL);
283         assert(Name != NULL);
284         assert(Reason != NULL);
285
286         /* Check that specified channel exists */
287         chan = Channel_Search(Name);
288         if (!chan) {
289                 IRC_WriteErrClient(Client, ERR_NOSUCHCHANNEL_MSG,
290                                    Client_ID(Client), Name);
291                 return false;
292         }
293
294         /* Check that the client is in the channel */
295         if (!Get_Cl2Chan(chan, Client)) {
296                 IRC_WriteErrClient(Client, ERR_NOTONCHANNEL_MSG,
297                                    Client_ID(Client), Name);
298                 return false;
299         }
300
301         if (Conf_MorePrivacy)
302                 Reason = "";
303
304         /* Part client from channel */
305         if (!Remove_Client(REMOVE_PART, chan, Client, Origin, Reason, true))
306                 return false;
307         else
308                 return true;
309 } /* Channel_Part */
310
311
312 /**
313  * Kick user from Channel
314  */
315 GLOBAL void
316 Channel_Kick(CLIENT *Peer, CLIENT *Target, CLIENT *Origin, const char *Name,
317              const char *Reason )
318 {
319         CHANNEL *chan;
320         bool can_kick = false;
321
322         assert(Peer != NULL);
323         assert(Target != NULL);
324         assert(Origin != NULL);
325         assert(Name != NULL);
326         assert(Reason != NULL);
327
328         /* Check that channel exists */
329         chan = Channel_Search( Name );
330         if (!chan) {
331                 IRC_WriteErrClient(Origin, ERR_NOSUCHCHANNEL_MSG,
332                                    Client_ID(Origin), Name);
333                 return;
334         }
335
336         if (Client_Type(Peer) != CLIENT_SERVER &&
337             Client_Type(Origin) != CLIENT_SERVICE) {
338                 /* Check that user is on the specified channel */
339                 if (!Channel_IsMemberOf(chan, Origin)) {
340                         IRC_WriteErrClient(Origin, ERR_NOTONCHANNEL_MSG,
341                                            Client_ID(Origin), Name);
342                         return;
343                 }
344         }
345
346         /* Check that the client to be kicked is on the specified channel */
347         if (!Channel_IsMemberOf(chan, Target)) {
348                 IRC_WriteErrClient(Origin, ERR_USERNOTINCHANNEL_MSG,
349                                    Client_ID(Origin), Client_ID(Target), Name );
350                 return;
351         }
352
353         if(Client_Type(Peer) == CLIENT_USER) {
354                 /* Channel mode 'Q' and user mode 'q' on target: nobody but
355                  * IRC Operators and servers can kick the target user */
356                 if ((Channel_HasMode(chan, 'Q')
357                      || Client_HasMode(Target, 'q')
358                      || Client_Type(Target) == CLIENT_SERVICE)
359                     && !Client_HasMode(Origin, 'o')) {
360                         IRC_WriteErrClient(Origin, ERR_KICKDENY_MSG,
361                                            Client_ID(Origin), Name,
362                                            Client_ID(Target));
363                         return;
364                 }
365
366                 /* Check if client has the rights to kick target */
367
368                 /* Owner can kick everyone */
369                 if (Channel_UserHasMode(chan, Peer, 'q'))
370                         can_kick = true;
371
372                 /* Admin can't kick owner */
373                 else if (Channel_UserHasMode(chan, Peer, 'a') &&
374                     !Channel_UserHasMode(chan, Target, 'q'))
375                         can_kick = true;
376
377                 /* Op can't kick owner | admin */
378                 else if (Channel_UserHasMode(chan, Peer, 'o') &&
379                     !Channel_UserHasMode(chan, Target, 'q') &&
380                     !Channel_UserHasMode(chan, Target, 'a'))
381                         can_kick = true;
382
383                 /* Half Op can't kick owner | admin | op */
384                 else if (Channel_UserHasMode(chan, Peer, 'h') &&
385                     !Channel_UserHasMode(chan, Target, 'q') &&
386                     !Channel_UserHasMode(chan, Target, 'a') &&
387                     !Channel_UserHasMode(chan, Target, 'o'))
388                         can_kick = true;
389
390                 /* IRC operators & IRCd with OperCanMode enabled
391                  * can kick anyways regardless of privilege */
392                 else if(Client_HasMode(Origin, 'o') && Conf_OperCanMode)
393                     can_kick = true;
394
395                 if(!can_kick) {
396                         IRC_WriteErrClient(Origin, ERR_CHANOPPRIVTOOLOW_MSG,
397                                            Client_ID(Origin), Name);
398                         return;
399                 }
400         }
401
402         /* Kick Client from channel */
403         Remove_Client( REMOVE_KICK, chan, Target, Origin, Reason, true);
404 } /* Channel_Kick */
405
406
407 GLOBAL void
408 Channel_Quit( CLIENT *Client, const char *Reason )
409 {
410         CHANNEL *c, *next_c;
411
412         assert( Client != NULL );
413         assert( Reason != NULL );
414
415         if (Conf_MorePrivacy)
416                 Reason = "";
417
418         IRC_WriteStrRelatedPrefix( Client, Client, false, "QUIT :%s", Reason );
419
420         c = My_Channels;
421         while( c )
422         {
423                 next_c = c->next;
424                 Remove_Client( REMOVE_QUIT, c, Client, Client, Reason, false );
425                 c = next_c;
426         }
427 } /* Channel_Quit */
428
429
430 /**
431  * Get number of channels this server knows and that are "visible" to
432  * the given client. If no client is given, all channels will be counted.
433  *
434  * @param Client The client to check or NULL.
435  * @return Number of channels visible to the client.
436  */
437 GLOBAL unsigned long
438 Channel_CountVisible (CLIENT *Client)
439 {
440         CHANNEL *c;
441         unsigned long count = 0;
442
443         c = My_Channels;
444         while(c) {
445                 if (Client) {
446                         if (!Channel_HasMode(c, 's')
447                             || Channel_IsMemberOf(c, Client))
448                                 count++;
449                 } else
450                         count++;
451                 c = c->next;
452         }
453         return count;
454 }
455
456
457 GLOBAL unsigned long
458 Channel_MemberCount( CHANNEL *Chan )
459 {
460         CL2CHAN *cl2chan;
461         unsigned long count = 0;
462
463         assert( Chan != NULL );
464
465         cl2chan = My_Cl2Chan;
466         while( cl2chan )
467         {
468                 if( cl2chan->channel == Chan ) count++;
469                 cl2chan = cl2chan->next;
470         }
471         return count;
472 } /* Channel_MemberCount */
473
474
475 GLOBAL int
476 Channel_CountForUser( CLIENT *Client )
477 {
478         /* Count number of channels a user is member of. */
479
480         CL2CHAN *cl2chan;
481         int count = 0;
482
483         assert( Client != NULL );
484
485         cl2chan = My_Cl2Chan;
486         while( cl2chan )
487         {
488                 if( cl2chan->client == Client ) count++;
489                 cl2chan = cl2chan->next;
490         }
491
492         return count;
493 } /* Channel_CountForUser */
494
495
496 GLOBAL const char *
497 Channel_Name( const CHANNEL *Chan )
498 {
499         assert( Chan != NULL );
500         return Chan->name;
501 } /* Channel_Name */
502
503
504 GLOBAL char *
505 Channel_Modes( CHANNEL *Chan )
506 {
507         assert( Chan != NULL );
508         return Chan->modes;
509 } /* Channel_Modes */
510
511
512 GLOBAL bool
513 Channel_HasMode( CHANNEL *Chan, char Mode )
514 {
515         assert( Chan != NULL );
516         return strchr( Chan->modes, Mode ) != NULL;
517 } /* Channel_HasMode */
518
519
520 GLOBAL char *
521 Channel_Key( CHANNEL *Chan )
522 {
523         assert( Chan != NULL );
524         return Chan->key;
525 } /* Channel_Key */
526
527
528 GLOBAL unsigned long
529 Channel_MaxUsers( CHANNEL *Chan )
530 {
531         assert( Chan != NULL );
532         return Chan->maxusers;
533 } /* Channel_MaxUsers */
534
535
536 GLOBAL CHANNEL *
537 Channel_First( void )
538 {
539         return My_Channels;
540 } /* Channel_First */
541
542
543 GLOBAL CHANNEL *
544 Channel_Next( CHANNEL *Chan )
545 {
546         assert( Chan != NULL );
547         return Chan->next;
548 } /* Channel_Next */
549
550
551 GLOBAL CHANNEL *
552 Channel_Search( const char *Name )
553 {
554         /* Search channel structure */
555
556         CHANNEL *c;
557         UINT32 search_hash;
558
559         assert( Name != NULL );
560
561         search_hash = Hash( Name );
562         c = My_Channels;
563         while( c )
564         {
565                 if( search_hash == c->hash )
566                 {
567                         /* hash hit */
568                         if( strcasecmp( Name, c->name ) == 0 ) return c;
569                 }
570                 c = c->next;
571         }
572         return NULL;
573 } /* Channel_Search */
574
575
576 GLOBAL CL2CHAN *
577 Channel_FirstMember( CHANNEL *Chan )
578 {
579         assert( Chan != NULL );
580         return Get_First_Cl2Chan( NULL, Chan );
581 } /* Channel_FirstMember */
582
583
584 GLOBAL CL2CHAN *
585 Channel_NextMember( CHANNEL *Chan, CL2CHAN *Cl2Chan )
586 {
587         assert( Chan != NULL );
588         assert( Cl2Chan != NULL );
589         return Get_Next_Cl2Chan( Cl2Chan->next, NULL, Chan );
590 } /* Channel_NextMember */
591
592
593 GLOBAL CL2CHAN *
594 Channel_FirstChannelOf( CLIENT *Client )
595 {
596         assert( Client != NULL );
597         return Get_First_Cl2Chan( Client, NULL );
598 } /* Channel_FirstChannelOf */
599
600
601 GLOBAL CL2CHAN *
602 Channel_NextChannelOf( CLIENT *Client, CL2CHAN *Cl2Chan )
603 {
604         assert( Client != NULL );
605         assert( Cl2Chan != NULL );
606         return Get_Next_Cl2Chan( Cl2Chan->next, Client, NULL );
607 } /* Channel_NextChannelOf */
608
609
610 GLOBAL CLIENT *
611 Channel_GetClient( CL2CHAN *Cl2Chan )
612 {
613         assert( Cl2Chan != NULL );
614         return Cl2Chan->client;
615 } /* Channel_GetClient */
616
617
618 GLOBAL CHANNEL *
619 Channel_GetChannel( CL2CHAN *Cl2Chan )
620 {
621         assert( Cl2Chan != NULL );
622         return Cl2Chan->channel;
623 } /* Channel_GetChannel */
624
625
626 GLOBAL bool
627 Channel_IsValidName( const char *Name )
628 {
629         assert( Name != NULL );
630
631 #ifdef STRICT_RFC
632         if (strlen(Name) <= 1)
633                 return false;
634 #endif
635         if (strchr("#&+", Name[0]) == NULL)
636                 return false;
637         if (strlen(Name) >= CHANNEL_NAME_LEN)
638                 return false;
639
640         return Name[strcspn(Name, " ,:\007")] == 0;
641 } /* Channel_IsValidName */
642
643
644 GLOBAL bool
645 Channel_ModeAdd( CHANNEL *Chan, char Mode )
646 {
647         /* set Mode.
648          * If the channel already had this mode, return false.
649          * If the channel mode was newly set return true.
650          */
651
652         char x[2];
653
654         assert( Chan != NULL );
655
656         x[0] = Mode; x[1] = '\0';
657         if( ! Channel_HasMode( Chan, x[0] ))
658         {
659                 /* Channel does not have this mode yet, set it */
660                 strlcat( Chan->modes, x, sizeof( Chan->modes ));
661                 return true;
662         }
663         else return false;
664 } /* Channel_ModeAdd */
665
666
667 GLOBAL bool
668 Channel_ModeDel( CHANNEL *Chan, char Mode )
669 {
670         /* Delete mode.
671          * if the mode was removed return true.
672          * if the channel did not have the mode, return false.
673         */
674         char *p;
675
676         assert( Chan != NULL );
677
678         p = strchr( Chan->modes, Mode );
679         if( ! p ) return false;
680
681         /* Channel has mode -> delete */
682         while( *p )
683         {
684                 *p = *(p + 1);
685                 p++;
686         }
687         return true;
688 } /* Channel_ModeDel */
689
690
691 GLOBAL bool
692 Channel_UserModeAdd( CHANNEL *Chan, CLIENT *Client, char Mode )
693 {
694         /* Set Channel-User-Mode.
695          * if mode was newly set, return true.
696          * if the User already had this channel-mode, return false.
697          */
698
699         CL2CHAN *cl2chan;
700         char x[2];
701
702         assert( Chan != NULL );
703         assert( Client != NULL );
704
705         cl2chan = Get_Cl2Chan( Chan, Client );
706         assert( cl2chan != NULL );
707
708         x[0] = Mode; x[1] = '\0';
709         if( ! strchr( cl2chan->modes, x[0] ))
710         {
711                 /* mode not set, -> set it */
712                 strlcat( cl2chan->modes, x, sizeof( cl2chan->modes ));
713                 return true;
714         }
715         else return false;
716 } /* Channel_UserModeAdd */
717
718
719 GLOBAL bool
720 Channel_UserModeDel( CHANNEL *Chan, CLIENT *Client, char Mode )
721 {
722         /* Delete Channel-User-Mode.
723          * If Mode was removed, return true.
724          * If User did not have the Channel-Mode, return false.
725          */
726
727         CL2CHAN *cl2chan;
728         char *p;
729
730         assert( Chan != NULL );
731         assert( Client != NULL );
732
733         cl2chan = Get_Cl2Chan( Chan, Client );
734         assert( cl2chan != NULL );
735
736         p = strchr( cl2chan->modes, Mode );
737         if( ! p ) return false;
738
739         /* Client has Mode -> delete */
740         while( *p )
741         {
742                 *p = *(p + 1);
743                 p++;
744         }
745         return true;
746 } /* Channel_UserModeDel */
747
748
749 GLOBAL char *
750 Channel_UserModes( CHANNEL *Chan, CLIENT *Client )
751 {
752         /* return Users' Channel-Modes */
753
754         CL2CHAN *cl2chan;
755
756         assert( Chan != NULL );
757         assert( Client != NULL );
758
759         cl2chan = Get_Cl2Chan( Chan, Client );
760         assert( cl2chan != NULL );
761
762         return cl2chan->modes;
763 } /* Channel_UserModes */
764
765
766 GLOBAL bool
767 Channel_UserHasMode( CHANNEL *Chan, CLIENT *Client, char Mode )
768 {
769         return strchr(Channel_UserModes(Chan, Client), Mode) != NULL;
770 } /* Channel_UserHasMode */
771
772
773 GLOBAL bool
774 Channel_IsMemberOf( CHANNEL *Chan, CLIENT *Client )
775 {
776         /* Test if Client is on Channel Chan */
777
778         assert( Chan != NULL );
779         assert( Client != NULL );
780         return Get_Cl2Chan(Chan, Client) != NULL;
781 } /* Channel_IsMemberOf */
782
783
784 GLOBAL char *
785 Channel_Topic( CHANNEL *Chan )
786 {
787         char *ret;
788         assert( Chan != NULL );
789         ret = array_start(&Chan->topic);
790         return ret ? ret : "";
791 } /* Channel_Topic */
792
793
794 #ifndef STRICT_RFC
795
796 GLOBAL unsigned int
797 Channel_TopicTime(CHANNEL *Chan)
798 {
799         assert(Chan != NULL);
800         return (unsigned int) Chan->topic_time;
801 } /* Channel_TopicTime */
802
803
804 GLOBAL char *
805 Channel_TopicWho(CHANNEL *Chan)
806 {
807         assert(Chan != NULL);
808         return Chan->topic_who;
809 } /* Channel_TopicWho */
810
811
812 GLOBAL unsigned int
813 Channel_CreationTime(CHANNEL *Chan)
814 {
815         assert(Chan != NULL);
816         return (unsigned int) Chan->creation_time;
817 } /* Channel_CreationTime */
818
819 #endif
820
821
822 GLOBAL void
823 Channel_SetTopic(CHANNEL *Chan, CLIENT *Client, const char *Topic)
824 {
825         size_t len;
826         assert( Chan != NULL );
827         assert( Topic != NULL );
828
829         len = strlen(Topic);
830         if (len < array_bytes(&Chan->topic))
831                 array_free(&Chan->topic);
832
833         if (len >= COMMAND_LEN || !array_copyb(&Chan->topic, Topic, len+1))
834                 Log(LOG_WARNING, "could not set new Topic \"%s\" on %s: %s",
835                                         Topic, Chan->name, strerror(errno));
836 #ifndef STRICT_RFC
837         Chan->topic_time = time(NULL);
838         if (Client != NULL && Client_Type(Client) != CLIENT_SERVER)
839                 strlcpy(Chan->topic_who, Client_ID(Client),
840                         sizeof Chan->topic_who);
841         else
842                 strlcpy(Chan->topic_who, DEFAULT_TOPIC_ID,
843                         sizeof Chan->topic_who);
844 #else
845         (void) Client;
846 #endif
847 } /* Channel_SetTopic */
848
849
850 GLOBAL void
851 Channel_SetModes( CHANNEL *Chan, const char *Modes )
852 {
853         assert( Chan != NULL );
854         assert( Modes != NULL );
855
856         strlcpy( Chan->modes, Modes, sizeof( Chan->modes ));
857 } /* Channel_SetModes */
858
859
860 GLOBAL void
861 Channel_SetKey( CHANNEL *Chan, const char *Key )
862 {
863         assert( Chan != NULL );
864         assert( Key != NULL );
865
866         strlcpy( Chan->key, Key, sizeof( Chan->key ));
867         LogDebug("Channel %s: Key is now \"%s\".", Chan->name, Chan->key );
868 } /* Channel_SetKey */
869
870
871 GLOBAL void
872 Channel_SetMaxUsers(CHANNEL *Chan, unsigned long Count)
873 {
874         assert( Chan != NULL );
875
876         Chan->maxusers = Count;
877         LogDebug("Channel %s: Member limit is now %lu.", Chan->name, Chan->maxusers );
878 } /* Channel_SetMaxUsers */
879
880
881 /**
882  * Check if a client is allowed to send to a specific channel.
883  *
884  * @param Chan The channel to check.
885  * @param From The client that wants to send.
886  * @return true if the client is allowed to send, false otherwise.
887  */
888 static bool
889 Can_Send_To_Channel(CHANNEL *Chan, CLIENT *From)
890 {
891         bool is_member, has_voice, is_halfop, is_op, is_chanadmin, is_owner;
892
893         is_member = has_voice = is_halfop = is_op = is_chanadmin = is_owner = false;
894
895         /* The server itself always can send messages :-) */
896         if (Client_ThisServer() == From)
897                 return true;
898
899         if (Channel_IsMemberOf(Chan, From)) {
900                 is_member = true;
901                 if (Channel_UserHasMode(Chan, From, 'v'))
902                         has_voice = true;
903                 if (Channel_UserHasMode(Chan, From, 'h'))
904                         is_halfop = true;
905                 if (Channel_UserHasMode(Chan, From, 'o'))
906                         is_op = true;
907                 if (Channel_UserHasMode(Chan, From, 'a'))
908                         is_chanadmin = true;
909                 if (Channel_UserHasMode(Chan, From, 'q'))
910                         is_owner = true;
911         }
912
913         /*
914          * Is the client allowed to write to channel?
915          *
916          * If channel mode n set: non-members cannot send to channel.
917          * If channel mode m set: need voice.
918          */
919         if (Channel_HasMode(Chan, 'n') && !is_member)
920                 return false;
921
922         if (Channel_HasMode(Chan, 'M') && !Client_HasMode(From, 'R')
923             && !Client_HasMode(From, 'o'))
924                 return false;
925
926         if (has_voice || is_halfop || is_op || is_chanadmin || is_owner)
927                 return true;
928
929         if (Channel_HasMode(Chan, 'm'))
930                 return false;
931
932         if (Lists_Check(&Chan->list_excepts, From))
933                 return true;
934
935         return !Lists_Check(&Chan->list_bans, From);
936 }
937
938
939 GLOBAL bool
940 Channel_Write(CHANNEL *Chan, CLIENT *From, CLIENT *Client, const char *Command,
941               bool SendErrors, const char *Text)
942 {
943         if (!Can_Send_To_Channel(Chan, From)) {
944                 if (! SendErrors)
945                         return CONNECTED;       /* no error, see RFC 2812 */
946                 if (Channel_HasMode(Chan, 'M'))
947                         return IRC_WriteErrClient(From, ERR_NEEDREGGEDNICK_MSG,
948                                                   Client_ID(From), Channel_Name(Chan));
949                 else
950                         return IRC_WriteErrClient(From, ERR_CANNOTSENDTOCHAN_MSG,
951                                           Client_ID(From), Channel_Name(Chan));
952         }
953
954         if (Client_Conn(From) > NONE)
955                 Conn_UpdateIdle(Client_Conn(From));
956
957         IRC_WriteStrChannelPrefix(Client, Chan, From, true, "%s %s :%s",
958                                   Command, Channel_Name(Chan), Text);
959         return CONNECTED;
960 }
961
962
963 GLOBAL CHANNEL *
964 Channel_Create( const char *Name )
965 {
966         /* Create new CHANNEL structure and add it to linked list */
967         CHANNEL *c;
968
969         assert( Name != NULL );
970
971         c = (CHANNEL *)malloc( sizeof( CHANNEL ));
972         if( ! c )
973         {
974                 Log( LOG_EMERG, "Can't allocate memory! [New_Chan]" );
975                 return NULL;
976         }
977         memset( c, 0, sizeof( CHANNEL ));
978         strlcpy( c->name, Name, sizeof( c->name ));
979         c->hash = Hash( c->name );
980         c->next = My_Channels;
981 #ifndef STRICT_RFC
982         c->creation_time = time(NULL);
983 #endif
984         My_Channels = c;
985         LogDebug("Created new channel structure for \"%s\".", Name);
986         return c;
987 } /* Channel_Create */
988
989
990 static CL2CHAN *
991 Get_Cl2Chan( CHANNEL *Chan, CLIENT *Client )
992 {
993         CL2CHAN *cl2chan;
994
995         assert( Chan != NULL );
996         assert( Client != NULL );
997
998         cl2chan = My_Cl2Chan;
999         while( cl2chan )
1000         {
1001                 if(( cl2chan->channel == Chan ) && ( cl2chan->client == Client )) return cl2chan;
1002                 cl2chan = cl2chan->next;
1003         }
1004         return NULL;
1005 } /* Get_Cl2Chan */
1006
1007
1008 static CL2CHAN *
1009 Add_Client( CHANNEL *Chan, CLIENT *Client )
1010 {
1011         CL2CHAN *cl2chan;
1012
1013         assert( Chan != NULL );
1014         assert( Client != NULL );
1015
1016         /* Create new CL2CHAN structure */
1017         cl2chan = (CL2CHAN *)malloc( sizeof( CL2CHAN ));
1018         if( ! cl2chan )
1019         {
1020                 Log( LOG_EMERG, "Can't allocate memory! [Add_Client]" );
1021                 return NULL;
1022         }
1023         cl2chan->channel = Chan;
1024         cl2chan->client = Client;
1025         strcpy( cl2chan->modes, "" );
1026
1027         /* concatenate */
1028         cl2chan->next = My_Cl2Chan;
1029         My_Cl2Chan = cl2chan;
1030
1031         LogDebug("User \"%s\" joined channel \"%s\".", Client_Mask(Client), Chan->name);
1032
1033         return cl2chan;
1034 } /* Add_Client */
1035
1036
1037 static bool
1038 Remove_Client( int Type, CHANNEL *Chan, CLIENT *Client, CLIENT *Origin, const char *Reason, bool InformServer )
1039 {
1040         CL2CHAN *cl2chan, *last_cl2chan;
1041         CHANNEL *c;
1042
1043         assert( Chan != NULL );
1044         assert( Client != NULL );
1045         assert( Origin != NULL );
1046         assert( Reason != NULL );
1047
1048         /* Do not inform other servers if the channel is local to this server,
1049          * regardless of what the caller requested! */
1050         if(InformServer)
1051                 InformServer = !Channel_IsLocal(Chan);
1052
1053         last_cl2chan = NULL;
1054         cl2chan = My_Cl2Chan;
1055         while( cl2chan )
1056         {
1057                 if(( cl2chan->channel == Chan ) && ( cl2chan->client == Client )) break;
1058                 last_cl2chan = cl2chan;
1059                 cl2chan = cl2chan->next;
1060         }
1061         if( ! cl2chan ) return false;
1062
1063         c = cl2chan->channel;
1064         assert( c != NULL );
1065
1066         /* maintain cl2chan list */
1067         if( last_cl2chan ) last_cl2chan->next = cl2chan->next;
1068         else My_Cl2Chan = cl2chan->next;
1069         free( cl2chan );
1070
1071         switch( Type )
1072         {
1073                 case REMOVE_QUIT:
1074                         /* QUIT: other servers have already been notified,
1075                          * see Client_Destroy(); so only inform other clients
1076                          * in same channel. */
1077                         assert( InformServer == false );
1078                         LogDebug("User \"%s\" left channel \"%s\" (%s).",
1079                                         Client_Mask( Client ), c->name, Reason );
1080                         break;
1081                 case REMOVE_KICK:
1082                         /* User was KICKed: inform other servers (public
1083                          * channels) and all users in the channel */
1084                         if( InformServer )
1085                                 IRC_WriteStrServersPrefix( Client_NextHop( Origin ),
1086                                         Origin, "KICK %s %s :%s", c->name, Client_ID( Client ), Reason);
1087                         IRC_WriteStrChannelPrefix(Client, c, Origin, false, "KICK %s %s :%s",
1088                                                         c->name, Client_ID( Client ), Reason );
1089                         if ((Client_Conn(Client) > NONE) &&
1090                                         (Client_Type(Client) == CLIENT_USER))
1091                         {
1092                                 IRC_WriteStrClientPrefix(Client, Origin, "KICK %s %s :%s",
1093                                                                 c->name, Client_ID( Client ), Reason);
1094                         }
1095                         LogDebug("User \"%s\" has been kicked off \"%s\" by \"%s\": %s.",
1096                                 Client_Mask( Client ), c->name, Client_ID(Origin), Reason);
1097                         break;
1098                 default: /* PART */
1099                         if (Conf_MorePrivacy)
1100                                 Reason = "";
1101
1102                         if (InformServer)
1103                                 IRC_WriteStrServersPrefix(Origin, Client, "PART %s :%s", c->name, Reason);
1104
1105                         IRC_WriteStrChannelPrefix(Origin, c, Client, false, "PART %s :%s",
1106                                                                         c->name, Reason);
1107
1108                         if ((Client_Conn(Origin) > NONE) &&
1109                                         (Client_Type(Origin) == CLIENT_USER))
1110                         {
1111                                 IRC_WriteStrClientPrefix( Origin, Client, "PART %s :%s", c->name, Reason);
1112                                 LogDebug("User \"%s\" left channel \"%s\" (%s).",
1113                                         Client_Mask(Client), c->name, Reason);
1114                         }
1115         }
1116
1117         /* When channel is empty and is not pre-defined, delete */
1118         if( ! Channel_HasMode( Chan, 'P' ))
1119         {
1120                 if( ! Get_First_Cl2Chan( NULL, Chan )) Delete_Channel( Chan );
1121         }
1122
1123         return true;
1124 } /* Remove_Client */
1125
1126
1127 GLOBAL bool
1128 Channel_AddBan(CHANNEL *c, const char *mask, const char *who )
1129 {
1130         struct list_head *h = Channel_GetListBans(c);
1131         LogDebug("Adding \"%s\" to \"%s\" ban list", mask, Channel_Name(c));
1132         return Lists_Add(h, mask, time(NULL), who, false);
1133 }
1134
1135
1136 GLOBAL bool
1137 Channel_AddExcept(CHANNEL *c, const char *mask, const char *who )
1138 {
1139         struct list_head *h = Channel_GetListExcepts(c);
1140         LogDebug("Adding \"%s\" to \"%s\" exception list", mask, Channel_Name(c));
1141         return Lists_Add(h, mask, time(NULL), who, false);
1142 }
1143
1144
1145 GLOBAL bool
1146 Channel_AddInvite(CHANNEL *c, const char *mask, bool onlyonce, const char *who )
1147 {
1148         struct list_head *h = Channel_GetListInvites(c);
1149         LogDebug("Adding \"%s\" to \"%s\" invite list", mask, Channel_Name(c));
1150         return Lists_Add(h, mask, time(NULL), who, onlyonce);
1151 }
1152
1153
1154 static bool
1155 ShowChannelList(struct list_head *head, CLIENT *Client, CHANNEL *Channel,
1156                 char *msg, char *msg_end)
1157 {
1158         struct list_elem *e;
1159
1160         assert (Client != NULL);
1161         assert (Channel != NULL);
1162
1163         e = Lists_GetFirst(head);
1164         while (e) {
1165                 if (!IRC_WriteStrClient(Client, msg, Client_ID(Client),
1166                                         Channel_Name(Channel),
1167                                         Lists_GetMask(e),
1168                                         Lists_GetReason(e),
1169                                         Lists_GetValidity(e)))
1170                         return DISCONNECTED;
1171                 e = Lists_GetNext(e);
1172         }
1173
1174         return IRC_WriteStrClient(Client, msg_end, Client_ID(Client),
1175                                   Channel_Name(Channel));
1176 }
1177
1178
1179 GLOBAL bool
1180 Channel_ShowBans( CLIENT *Client, CHANNEL *Channel )
1181 {
1182         struct list_head *h;
1183
1184         assert( Channel != NULL );
1185
1186         h = Channel_GetListBans(Channel);
1187         return ShowChannelList(h, Client, Channel, RPL_BANLIST_MSG,
1188                                RPL_ENDOFBANLIST_MSG);
1189 }
1190
1191
1192 GLOBAL bool
1193 Channel_ShowExcepts( CLIENT *Client, CHANNEL *Channel )
1194 {
1195         struct list_head *h;
1196
1197         assert( Channel != NULL );
1198
1199         h = Channel_GetListExcepts(Channel);
1200         return ShowChannelList(h, Client, Channel, RPL_EXCEPTLIST_MSG,
1201                                RPL_ENDOFEXCEPTLIST_MSG);
1202 }
1203
1204
1205 GLOBAL bool
1206 Channel_ShowInvites( CLIENT *Client, CHANNEL *Channel )
1207 {
1208         struct list_head *h;
1209
1210         assert( Channel != NULL );
1211
1212         h = Channel_GetListInvites(Channel);
1213         return ShowChannelList(h, Client, Channel, RPL_INVITELIST_MSG,
1214                                RPL_ENDOFINVITELIST_MSG);
1215 }
1216
1217
1218 /**
1219  * Log a message to the local &SERVER channel, if it exists.
1220  */
1221 GLOBAL void
1222 Channel_LogServer(const char *msg)
1223 {
1224         CHANNEL *sc;
1225         CLIENT *c;
1226
1227         assert(msg != NULL);
1228
1229         sc = Channel_Search("&SERVER");
1230         if (!sc)
1231                 return;
1232
1233         c = Client_ThisServer();
1234         Channel_Write(sc, c, c, "PRIVMSG", false, msg);
1235 } /* Channel_LogServer */
1236
1237
1238 GLOBAL bool
1239 Channel_CheckKey(CHANNEL *Chan, CLIENT *Client, const char *Key)
1240 {
1241         char *file_name, line[COMMAND_LEN], *nick, *pass;
1242         FILE *fd;
1243
1244         assert(Chan != NULL);
1245         assert(Client != NULL);
1246         assert(Key != NULL);
1247
1248         if (!Channel_HasMode(Chan, 'k'))
1249                 return true;
1250         if (*Key == '\0')
1251                 return false;
1252         if (strcmp(Chan->key, Key) == 0)
1253                 return true;
1254
1255         file_name = array_start(&Chan->keyfile);
1256         if (!file_name)
1257                 return false;
1258         fd = fopen(file_name, "r");
1259         if (!fd) {
1260                 Log(LOG_ERR, "Can't open channel key file \"%s\" for %s: %s",
1261                     file_name, Chan->name, strerror(errno));
1262                 return false;
1263         }
1264
1265         while (fgets(line, (int)sizeof(line), fd) != NULL) {
1266                 ngt_TrimStr(line);
1267                 if (! (nick = strchr(line, ':')))
1268                         continue;
1269                 *nick++ = '\0';
1270                 if (!Match(line, Client_User(Client)))
1271                         continue;
1272                 if (! (pass = strchr(nick, ':')))
1273                         continue;
1274                 *pass++ = '\0';
1275                 if (!Match(nick, Client_ID(Client)))
1276                         continue;
1277                 if (strcmp(Key, pass) != 0)
1278                         continue;
1279
1280                 fclose(fd);
1281                 return true;
1282         }
1283         fclose(fd);
1284         return false;
1285 } /* Channel_CheckKey */
1286
1287
1288 static CL2CHAN *
1289 Get_First_Cl2Chan( CLIENT *Client, CHANNEL *Chan )
1290 {
1291         return Get_Next_Cl2Chan( My_Cl2Chan, Client, Chan );
1292 } /* Get_First_Cl2Chan */
1293
1294
1295 static CL2CHAN *
1296 Get_Next_Cl2Chan( CL2CHAN *Start, CLIENT *Client, CHANNEL *Channel )
1297 {
1298         CL2CHAN *cl2chan;
1299
1300         assert( Client != NULL || Channel != NULL );
1301
1302         cl2chan = Start;
1303         while( cl2chan )
1304         {
1305                 if(( Client ) && ( cl2chan->client == Client )) return cl2chan;
1306                 if(( Channel ) && ( cl2chan->channel == Channel )) return cl2chan;
1307                 cl2chan = cl2chan->next;
1308         }
1309         return NULL;
1310 } /* Get_Next_Cl2Chan */
1311
1312
1313 /**
1314  * Remove a channel and free all of its data structures.
1315  */
1316 static void
1317 Delete_Channel(CHANNEL *Chan)
1318 {
1319         CHANNEL *chan, *last_chan;
1320
1321         last_chan = NULL;
1322         chan = My_Channels;
1323         while (chan) {
1324                 if (chan == Chan)
1325                         break;
1326                 last_chan = chan;
1327                 chan = chan->next;
1328         }
1329
1330         assert(chan != NULL);
1331         if (!chan)
1332                 return;
1333
1334         /* maintain channel list */
1335         if (last_chan)
1336                 last_chan->next = chan->next;
1337         else
1338                 My_Channels = chan->next;
1339
1340         LogDebug("Freed channel structure for \"%s\".", Chan->name);
1341         Free_Channel(Chan);
1342 } /* Delete_Channel */
1343
1344
1345 static void
1346 Set_KeyFile(CHANNEL *Chan, const char *KeyFile)
1347 {
1348         size_t len;
1349
1350         assert(Chan != NULL);
1351         assert(KeyFile != NULL);
1352
1353         len = strlen(KeyFile);
1354         if (len < array_bytes(&Chan->keyfile)) {
1355                 Log(LOG_INFO, "Channel key file of %s removed.", Chan->name);
1356                 array_free(&Chan->keyfile);
1357         }
1358
1359         if (len < 1)
1360                 return;
1361
1362         if (!array_copyb(&Chan->keyfile, KeyFile, len+1))
1363                 Log(LOG_WARNING,
1364                     "Could not set new channel key file \"%s\" for %s: %s",
1365                     KeyFile, Chan->name, strerror(errno));
1366         else
1367                 Log(LOG_INFO|LOG_snotice,
1368                     "New local channel key file \"%s\" for %s activated.",
1369                     KeyFile, Chan->name);
1370 } /* Set_KeyFile */
1371
1372
1373 /* -eof- */