Author: Isomer <isomer@undernet.org>
[ircu2.10.12-pk.git] / ircd / channel.c
index edb42297baa0546edde0243dbbb946fce6de852d..3deebc433976e7297860ff931fe83b4f671ccc2e 100644 (file)
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- * $Id$
  */
+/** @file
+ * @brief Channel management and maintanance
+ * @version $Id$
+ */
+#include "config.h"
+
 #include "channel.h"
 #include "client.h"
+#include "destruct_event.h"
 #include "hash.h"
 #include "ircd.h"
 #include "ircd_alloc.h"
@@ -44,7 +49,6 @@
 #include "s_misc.h"
 #include "s_user.h"
 #include "send.h"
-#include "sprintf_irc.h"
 #include "struct.h"
 #include "support.h"
 #include "sys.h"
 #include <stdlib.h>
 #include <string.h>
 
+/** Linked list containing the full list of all channels */
 struct Channel* GlobalChannelList = 0;
 
+/** Number of struct Membership*'s allocated */
 static unsigned int membershipAllocCount;
+/** Freelist for struct Membership*'s */
 static struct Membership* membershipFreeList;
 
-static struct SLink *next_overlapped_ban(void);
-static int del_banid(struct Channel *, char *, int);
 void del_invite(struct Client *, struct Channel *);
 
 const char* const PartFmt1     = ":%s " MSG_PART " %s";
@@ -74,15 +79,16 @@ static struct SLink* next_ban;
 static struct SLink* prev_ban;
 static struct SLink* removed_bans_list;
 
-/*
- * Use a global variable to remember if an oper set a mode on a local channel. Ugly,
- * but the only way to do it without changing set_mode intensively.
+/**
+ * Use a global variable to remember if an oper set a mode on a local channel. 
+ * Ugly, but the only way to do it without changing set_mode intensively.
  */
 int LocalChanOperMode = 0;
 
 #if !defined(NDEBUG)
-/*
- * return the length (>=0) of a chain of links.
+/** return the length (>=0) of a chain of links.
+ * @param lp   pointer to the start of the linked list
+ * @return the number of items in the list
  */
 static int list_length(struct SLink *lp)
 {
@@ -94,6 +100,20 @@ static int list_length(struct SLink *lp)
 }
 #endif
 
+/** return the struct Membership* that represents a client on a channel
+ * This function finds a struct Membership* which holds the state about
+ * a client on a specific channel.  The code is smart enough to iterate
+ * over the channels a user is in, or the users in a channel to find the
+ * user depending on which is likely to be more efficient.
+ *
+ * @param chptr        pointer to the channel struct
+ * @param cptr pointer to the client struct
+ *
+ * @returns pointer to the struct Membership representing this client on 
+ *          this channel.  Returns NULL if the client is not on the channel.
+ *          Returns NULL if the client is actually a server.
+ * @see find_channel_member()
+ */
 struct Membership* find_member_link(struct Channel* chptr, const struct Client* cptr)
 {
   struct Membership *m;
@@ -134,11 +154,20 @@ struct Membership* find_member_link(struct Channel* chptr, const struct Client*
   return 0;
 }
 
-/*
- * find_chasing - Find the client structure for a nick name (user)
+/** Find the client structure for a nick name (user) 
+ * Find the client structure for a nick name (user)
  * using history mechanism if necessary. If the client is not found, an error
  * message (NO SUCH NICK) is generated. If the client was found
  * through the history, chasing will be 1 and otherwise 0.
+ *
+ * This function was used extensively in the P09 days, and since we now have
+ * numeric nicks is no longer quite as important.
+ *
+ * @param sptr Pointer to the client that has requested the search
+ * @param user a string represeting the client to be found
+ * @param chasing a variable set to 0 if the user was found directly, 
+ *             1 otherwise
+ * @returns a pointer the client, or NULL if the client wasn't found.
  */
 struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
 {
@@ -158,40 +187,56 @@ struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
   return who;
 }
 
-/*
+/** build up a hostmask
  * Create a string of form "foo!bar@fubar" given foo, bar and fubar
  * as the parameters.  If NULL, they become "*".
+ * @param namebuf the buffer to build the hostmask into.  Must be at least
+ *               NICKLEN+USERLEN+HOSTLEN+3 charactors long.
+ * @param nick The nickname
+ * @param name The ident
+ * @param host the hostname
+ * @returns namebuf
+ * @see make_nick_user_ip()
  */
-static char *make_nick_user_host(const char *nick, const char *name,
-                                 const char *host)
+static char *make_nick_user_host(char *namebuf, const char *nick,
+                                const char *name, const char *host)
 {
-  static char namebuf[NICKLEN + USERLEN + HOSTLEN + 3];
-  sprintf_irc(namebuf, "%s!%s@%s", nick, name, host);
+#define NUH_BUFSIZE    (NICKLEN + USERLEN + HOSTLEN + 3)
+  ircd_snprintf(0, namebuf, NUH_BUFSIZE, "%s!%s@%s", nick, name, host);
   return namebuf;
 }
 
-/*
+/** Create a hostmask using an IP address
  * Create a string of form "foo!bar@123.456.789.123" given foo, bar and the
  * IP-number as the parameters.  If NULL, they become "*".
+ *
+ * @param ipbuf Buffer at least NICKLEN+USERLEN+SOCKIPLEN+4 to hold the final
+ *             match.
+ * @param nick The nickname (or NULL for *)
+ * @param name The ident (or NULL for *)
+ * @param ip   The IP address
+ * @returns ipbuf
+ * @see make_nick_user_host()
  */
-static char *make_nick_user_ip(char *nick, char *name, struct in_addr ip)
+#define NUI_BUFSIZE    (NICKLEN + USERLEN + SOCKIPLEN + 4)
+static char *make_nick_user_ip(char *ipbuf, char *nick, char *name,
+                              const struct irc_in_addr *ip)
 {
-  static char ipbuf[NICKLEN + USERLEN + 16 + 3];
-  sprintf_irc(ipbuf, "%s!%s@%s", nick, name, ircd_ntoa((const char*) &ip));
+  ircd_snprintf(0, ipbuf, NUI_BUFSIZE, "%s!%s@%s", nick, name, ircd_ntoa(ip));
   return ipbuf;
 }
 
-/*
- * Subtract one user from channel i (and free channel
- * block, if channel became empty).
- * Returns: true  (1) if channel still exists
- *          false (0) if the channel was destroyed
+/** Decrement the count of users, and free if empty.
+ * Subtract one user from channel i (and free channel * block, if channel 
+ * became empty).
+ *
+ * @param chptr The channel to subtract one from.
+ *
+ * @returns true  (1) if channel still has members.
+ *          false (0) if the channel is now empty.
  */
 int sub1_from_channel(struct Channel* chptr)
 {
-  struct SLink *tmp;
-  struct SLink *obtmp;
-
   if (chptr->users > 1)         /* Can be 0, called for an empty channel too */
   {
     assert(0 != chptr->members);
@@ -199,6 +244,52 @@ int sub1_from_channel(struct Channel* chptr)
     return 1;
   }
 
+  chptr->users = 0;
+
+  /*
+   * Also channels without Apass set need to be kept alive,
+   * otherwise Bad Guys(tm) would be able to takeover
+   * existing channels too easily, and then set an Apass!
+   * However, if a channel without Apass becomes empty
+   * then we try to be kind to them and remove possible
+   * limiting modes.
+   */
+  chptr->mode.mode &= ~MODE_INVITEONLY;
+  chptr->mode.limit = 0;
+  /*
+   * We do NOT reset a possible key or bans because when
+   * the 'channel owners' can't get in because of a key
+   * or ban then apparently there was a fight/takeover
+   * on the channel and we want them to contact IRC opers
+   * who then will educate them on the use of Apass/upass.
+   */
+
+   if (feature_bool(FEAT_OPLEVELS)) {
+  if (TStime() - chptr->creationtime < 172800) /* Channel younger than 48 hours? */
+    schedule_destruct_event_1m(chptr);         /* Get rid of it in approximately 4-5 minutes */
+  else
+    schedule_destruct_event_48h(chptr);                /* Get rid of it in approximately 48 hours */
+   } else
+       destruct_channel(chptr);
+
+  return 0;
+}
+
+/** Destroy an empty channel
+ * This function destroys an empty channel, removing it from hashtables,
+ * and removing any resources it may have consumed.
+ *
+ * @param chptr The channel to destroy
+ *
+ * @returns 0 (success)
+ *
+ * FIXME: Change to return void, this function never fails.
+ */
+int destruct_channel(struct Channel* chptr)
+{
+  struct SLink *tmp;
+  struct SLink *obtmp;
+
   assert(0 == chptr->members);
 
   /* Channel became (or was) empty: Remove channel */
@@ -247,8 +338,7 @@ int sub1_from_channel(struct Channel* chptr)
   return 0;
 }
 
-/*
- * add_banid
+/** add a ban to a channel
  *
  * `cptr' must be the client adding the ban.
  *
@@ -266,7 +356,15 @@ int sub1_from_channel(struct Channel* chptr)
  * is reset (unless a non-zero value is returned, in which case the
  * CHFL_BAN_OVERLAPPED flag might not have been reset!).
  *
- * --Run
+ * @author Run
+ * @param cptr         Client adding the ban
+ * @param chptr        Channel to add the ban to
+ * @param change True if adding a ban, false if old bans should just be flagged
+ * @param firsttime Reset the next_overlapped_ban() iteration.
+ * @returns 
+ *     0 if the ban was added
+ *     -2 if the ban already existed and was marked CHFL_BURST_BAN_WIPEOUT
+ *     -1 otherwise
  */
 int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
                      int change, int firsttime)
@@ -310,18 +408,10 @@ int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
           len -= strlen(tmp->value.ban.banstr);
         }
         *banp = tmp->next;
-#if 0
-        /* Silently remove overlapping bans */
-        MyFree(tmp->value.ban.banstr);
-        MyFree(tmp->value.ban.who);
-        free_link(tmp);
-        tmp = 0;
-#else
         /* These will be sent to the user later as -b */
         tmp->next = removed_bans_list;
         removed_bans_list = tmp;
         removed_bans = 1;
-#endif
       }
       else if (!(tmp->flags & CHFL_BURST_BAN_WIPEOUT))
       {
@@ -358,9 +448,11 @@ int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
     assert(0 != ban->value.ban.banstr);
     strcpy(ban->value.ban.banstr, banid);
 
-    ban->value.ban.who = (char*) MyMalloc(strlen(cli_name(cptr)) + 1);
+    if (IsServer(cptr) && feature_bool(FEAT_HIS_BANWHO))
+      DupString(ban->value.ban.who, cli_name(&me));
+    else
+      DupString(ban->value.ban.who, cli_name(cptr));
     assert(0 != ban->value.ban.who);
-    strcpy(ban->value.ban.who, cli_name(cptr));
 
     ban->value.ban.when = TStime();
     ban->flags = CHFL_BAN;      /* This bit is never used I think... */
@@ -377,20 +469,9 @@ int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
   return 0;
 }
 
-static struct SLink *next_overlapped_ban(void)
-{
-  struct SLink *tmp = next_ban;
-  if (tmp)
-  {
-    struct SLink *ban;
-    for (ban = tmp->next; ban; ban = ban->next)
-      if ((ban->flags & CHFL_BAN_OVERLAPPED))
-        break;
-    next_ban = ban;
-  }
-  return tmp;
-}
-
+/** return the next ban that is removed 
+ * @returns the next ban that is removed because of overlapping
+ */
 struct SLink *next_removed_overlapped_ban(void)
 {
   struct SLink *tmp = removed_bans_list;
@@ -408,45 +489,13 @@ struct SLink *next_removed_overlapped_ban(void)
   return tmp;
 }
 
-/*
- * del_banid
+/** returns Membership * if a person is joined and not a zombie
+ * @param cptr Client
+ * @param chptr Channel
+ * @returns pointer to the client's struct Membership * on the channel if that
+ *          user is a full member of the channel, or NULL otherwise.
  *
- * If `change' is true, delete `banid' from channel `chptr'.
- * Returns `false' if removal was (or would have been) successful.
- */
-static int del_banid(struct Channel *chptr, char *banid, int change)
-{
-  struct SLink **ban;
-  struct SLink *tmp;
-
-  if (!banid)
-    return -1;
-  for (ban = &(chptr->banlist); *ban; ban = &((*ban)->next)) {
-    if (0 == ircd_strcmp(banid, (*ban)->value.ban.banstr))
-    {
-      tmp = *ban;
-      if (change)
-      {
-        struct Membership* member;
-        *ban = tmp->next;
-        MyFree(tmp->value.ban.banstr);
-        MyFree(tmp->value.ban.who);
-        free_link(tmp);
-        /*
-         * Erase ban-valid-bit, for channel members that are banned
-         */
-        for (member = chptr->members; member; member = member->next_member)
-          if (CHFL_BANVALIDMASK == (member->status & CHFL_BANVALIDMASK))
-            ClearBanValid(member);       /* `tmp' == channel member */
-      }
-      return 0;
-    }
-  }
-  return -1;
-}
-
-/*
- * find_channel_member - returns Membership * if a person is joined and not a zombie
+ * @see find_member_link()
  */
 struct Membership* find_channel_member(struct Client* cptr, struct Channel* chptr)
 {
@@ -457,14 +506,27 @@ struct Membership* find_channel_member(struct Client* cptr, struct Channel* chpt
   return (member && !IsZombie(member)) ? member : 0;
 }
 
-/*
- * is_banned - a non-zero value if banned else 0.
+/** return true if banned else false.
+ *
+ * This function returns true if the user is banned on the said channel.
+ * This function will check the ban cache if applicable, otherwise will
+ * do the comparisons and cache the result.
+ *
+ * @param cptr  The client to test
+ * @param chptr The channel
+ * @param member The Membership * of this client on this channel 
+ *               (may be NULL if the member is not on the channel).
  */
 static int is_banned(struct Client *cptr, struct Channel *chptr,
                      struct Membership* member)
 {
   struct SLink* tmp;
+  char          tmphost[HOSTLEN + 1];
+  char          nu_host[NUH_BUFSIZE];
+  char          nu_realhost[NUH_BUFSIZE];
+  char          nu_ip[NUI_BUFSIZE];
   char*         s;
+  char*         sr = NULL;
   char*         ip_s = NULL;
 
   if (!IsUser(cptr))
@@ -473,18 +535,37 @@ static int is_banned(struct Client *cptr, struct Channel *chptr,
   if (member && IsBanValid(member))
     return IsBanned(member);
 
-  s = make_nick_user_host(cli_name(cptr), (cli_user(cptr))->username,
+  s = make_nick_user_host(nu_host, cli_name(cptr), (cli_user(cptr))->username,
                          (cli_user(cptr))->host);
+  if (IsAccount(cptr))
+  {
+    if (HasHiddenHost(cptr))
+    {
+      sr = make_nick_user_host(nu_realhost, cli_name(cptr),
+                               (cli_user(cptr))->username,
+                               cli_user(cptr)->realhost);
+    }
+    else
+    {
+      ircd_snprintf(0, tmphost, HOSTLEN, "%s.%s",
+                    cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
+      sr = make_nick_user_host(nu_realhost, cli_name(cptr),
+                               cli_user(cptr)->username,
+                               tmphost);      
+    }
+  }
 
   for (tmp = chptr->banlist; tmp; tmp = tmp->next) {
     if ((tmp->flags & CHFL_BAN_IPMASK)) {
       if (!ip_s)
-        ip_s = make_nick_user_ip(cli_name(cptr), (cli_user(cptr))->username,
-                                cli_ip(cptr));
+        ip_s = make_nick_user_ip(nu_ip, cli_name(cptr),
+                                (cli_user(cptr))->username, &cli_ip(cptr));
       if (match(tmp->value.ban.banstr, ip_s) == 0)
         break;
     }
-    else if (match(tmp->value.ban.banstr, s) == 0)
+    if (match(tmp->value.ban.banstr, s) == 0)
+      break;
+    else if (sr && match(tmp->value.ban.banstr, sr) == 0)
       break;
   }
 
@@ -503,12 +584,17 @@ static int is_banned(struct Client *cptr, struct Channel *chptr,
   return (tmp != NULL);
 }
 
-/*
+/** add a user to a channel.
  * adds a user to a channel by adding another link to the channels member
  * chain.
+ *
+ * @param chptr The channel to add to.
+ * @param who   The user to add.
+ * @param flags The flags the user gets initially.
+ * @param oplevel The oplevel the user starts with.
  */
 void add_user_to_channel(struct Channel* chptr, struct Client* who,
-                                unsigned int flags)
+                                unsigned int flags, int oplevel)
 {
   assert(0 != chptr);
   assert(0 != who);
@@ -527,6 +613,7 @@ void add_user_to_channel(struct Channel* chptr, struct Client* who,
     member->user         = who;
     member->channel      = chptr;
     member->status       = flags;
+    member->oplevel      = oplevel;
 
     member->next_member  = chptr->members;
     if (member->next_member)
@@ -540,11 +627,19 @@ void add_user_to_channel(struct Channel* chptr, struct Client* who,
     member->prev_channel = 0;
     (cli_user(who))->channel = member;
 
+    if (chptr->destruct_event)
+      remove_destruct_event(chptr);
     ++chptr->users;
     ++((cli_user(who))->joined);
   }
 }
 
+/** Remove a person from a channel, given their Membership*
+ *
+ * @param member A member of a channel.
+ *
+ * @returns true if there are more people in the channel.
+ */
 static int remove_member_from_channel(struct Membership* member)
 {
   struct Channel* chptr;
@@ -559,7 +654,13 @@ static int remove_member_from_channel(struct Membership* member)
     member->prev_member->next_member = member->next_member;
   else
     member->channel->members = member->next_member; 
-      
+
+  /*
+   * If this is the last delayed-join user, may have to clear WASDELJOINS.
+   */
+  if (IsDelayedJoin(member))
+    CheckDelayedJoins(chptr);
+
   /*
    * unlink client channel list
    */
@@ -578,6 +679,11 @@ static int remove_member_from_channel(struct Membership* member)
   return sub1_from_channel(chptr);
 }
 
+/** Check if all the remaining members on the channel are zombies
+ *
+ * @returns False if the channel has any non zombie members, True otherwise.
+ * @see \ref zombie
+ */
 static int channel_all_zombies(struct Channel* chptr)
 {
   struct Membership* member;
@@ -590,6 +696,14 @@ static int channel_all_zombies(struct Channel* chptr)
 }
       
 
+/** Remove a user from a channel
+ * This is the generic entry point for removing a user from a channel, this
+ * function will remove the client from the channel, and destory the channel
+ * if there are no more normal users left.
+ *
+ * @param cptr         The client
+ * @param channel      The channel
+ */
 void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
 {
   
@@ -610,6 +724,12 @@ void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
   }
 }
 
+/** Remove a user from all channels they are on.
+ *
+ * This function removes a user from all channels they are on.
+ *
+ * @param cptr The client to remove.
+ */
 void remove_user_from_all_channels(struct Client* cptr)
 {
   struct Membership* chan;
@@ -620,6 +740,14 @@ void remove_user_from_all_channels(struct Client* cptr)
     remove_user_from_channel(cptr, chan->channel);
 }
 
+/** Check if this user is a legitimate chanop
+ *
+ * @param cptr Client to check
+ * @param chptr        Channel to check
+ *
+ * @returns True if the user is a chanop (And not a zombie), False otherwise.
+ * @see \ref zombie
+ */
 int is_chan_op(struct Client *cptr, struct Channel *chptr)
 {
   struct Membership* member;
@@ -630,17 +758,16 @@ int is_chan_op(struct Client *cptr, struct Channel *chptr)
   return 0;
 }
 
-static int is_deopped(struct Client *cptr, struct Channel *chptr)
-{
-  struct Membership* member;
-
-  assert(0 != chptr);
-  if ((member = find_member_link(chptr, cptr)))
-    return IsDeopped(member);
-
-  return (IsUser(cptr) ? 1 : 0);
-}
-
+/** Check if a user is a Zombie on a specific channel.
+ *
+ * @param cptr         The client to check.
+ * @param chptr                The channel to check.
+ *
+ * @returns True if the client (cptr) is a zombie on the channel (chptr),
+ *         False otherwise.
+ *
+ * @see \ref zombie
+ */
 int is_zombie(struct Client *cptr, struct Channel *chptr)
 {
   struct Membership* member;
@@ -652,6 +779,14 @@ int is_zombie(struct Client *cptr, struct Channel *chptr)
   return 0;
 }
 
+/** Returns if a user has voice on a channel.
+ *
+ * @param cptr         The client
+ * @param chptr        The channel
+ *
+ * @returns True if the client (cptr) is voiced on (chptr) and is not a zombie.
+ * @see \ref zombie
+ */
 int has_voice(struct Client* cptr, struct Channel* chptr)
 {
   struct Membership* member;
@@ -663,10 +798,34 @@ int has_voice(struct Client* cptr, struct Channel* chptr)
   return 0;
 }
 
-int member_can_send_to_channel(struct Membership* member)
+/** Can this member send to a channel
+ *
+ * A user can speak on a channel iff:
+ * <ol>
+ *  <li> They didn't use the Apass to gain ops.
+ *  <li> They are op'd or voice'd.
+ *  <li> You aren't banned.
+ *  <li> The channel isn't +m
+ *  <li> The channel isn't +n or you are on the channel.
+ * </ol>
+ *
+ * This function will optionally reveal a user on a delayed join channel if
+ * they are allowed to send to the channel.
+ *
+ * @param member       The membership of the user
+ * @param reveal       If true, the user will be "revealed" on a delayed
+ *                     joined channel. 
+ *
+ * @returns True if the client can speak on the channel.
+ */
+int member_can_send_to_channel(struct Membership* member, int reveal)
 {
   assert(0 != member);
 
+  /* Discourage using the Apass to get op.  They should use the upass. */
+  if (IsChannelManager(member) && *member->channel->mode.upass)
+    return 0;
+
   if (IsVoicedOrOpped(member))
     return 1;
   /*
@@ -682,10 +841,29 @@ int member_can_send_to_channel(struct Membership* member)
    */
   if (MyUser(member->user) && is_banned(member->user, member->channel, member))
     return 0;
+
+  if (IsDelayedJoin(member) && reveal)
+    RevealDelayedJoin(member);
+
   return 1;
 }
 
-int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr)
+/** Check if a client can send to a channel.
+ *
+ * Has the added check over member_can_send_to_channel() of servers can
+ * always speak.
+ *
+ * @param cptr The client to check
+ * @param chptr        The channel to check
+ * @param reveal If the user should be revealed (see 
+ *             member_can_send_to_channel())
+ *
+ * @returns true if the client is allowed to speak on the channel, false 
+ *             otherwise
+ *
+ * @see member_can_send_to_channel()
+ */
+int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr, int reveal)
 {
   struct Membership *member;
   assert(0 != cptr); 
@@ -698,23 +876,27 @@ int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr)
   member = find_channel_member(cptr, chptr);
 
   /*
-   * You can't speak if your off channel, if the channel is modeless, or
-   * +n (no external messages) or +m (moderated).
+   * You can't speak if you're off channel, and it is +n (no external messages)
+   * or +m (moderated).
    */
   if (!member) {
-    if ((chptr->mode.mode & (MODE_NOPRIVMSGS|MODE_MODERATED)) 
-       || IsModelessChannel(chptr->chname)) 
+    if ((chptr->mode.mode & (MODE_NOPRIVMSGS|MODE_MODERATED)) ||
+       ((chptr->mode.mode & MODE_REGONLY) && !IsAccount(cptr)))
       return 0;
     else
-      return 1;
+      return !is_banned(cptr, chptr, NULL);
   }
-  return member_can_send_to_channel(member); 
+  return member_can_send_to_channel(member, reveal);
 }
 
-/*
- * find_no_nickchange_channel
- * if a member and not opped or voiced and banned
- * return the name of the first channel banned on
+/** Returns the name of a channel that prevents the user from changing nick.
+ * if a member and not (opped or voiced) and (banned or moderated), return
+ * the name of the first channel banned on.
+ *
+ * @param cptr         The client
+ *
+ * @returns the name of the first channel banned on, or NULL if the user
+ *          can change nicks.
  */
 const char* find_no_nickchange_channel(struct Client* cptr)
 {
@@ -722,7 +904,9 @@ const char* find_no_nickchange_channel(struct Client* cptr)
     struct Membership* member;
     for (member = (cli_user(cptr))->channel; member;
         member = member->next_channel) {
-      if (!IsVoicedOrOpped(member) && is_banned(cptr, member->channel, member))
+        if (!IsVoicedOrOpped(member) &&
+            (is_banned(cptr, member->channel, member) ||
+             (member->channel->mode.mode & MODE_MODERATED)))
         return member->channel->chname;
     }
   }
@@ -730,13 +914,26 @@ const char* find_no_nickchange_channel(struct Client* cptr)
 }
 
 
-/*
+/** Fill mbuf/pbuf with modes from chptr
  * write the "simple" list of channel modes for channel chptr onto buffer mbuf
- * with the parameters in pbuf.
+ * with the parameters in pbuf as visible by cptr.
+ *
+ * This function will hide keys from non-op'd, non-server clients.
+ *
+ * @param cptr The client to generate the mode for.
+ * @param mbuf The buffer to write the modes into.
+ * @param pbuf  The buffer to write the mode parameters into.
+ * @param buflen The length of the buffers.
+ * @param chptr        The channel to get the modes from.
+ * @param membership The membership of this client on this channel (or NULL
+ *             if this client isn't on this channel)
+ *
  */
-void channel_modes(struct Client *cptr, char *mbuf, char *pbuf,
-                          struct Channel *chptr)
+void channel_modes(struct Client *cptr, char *mbuf, char *pbuf, int buflen,
+                          struct Channel *chptr, struct Membership *member)
 {
+  int previous_parameter = 0;
+
   assert(0 != mbuf);
   assert(0 != pbuf);
   assert(0 != chptr);
@@ -754,29 +951,80 @@ void channel_modes(struct Client *cptr, char *mbuf, char *pbuf,
     *mbuf++ = 'i';
   if (chptr->mode.mode & MODE_NOPRIVMSGS)
     *mbuf++ = 'n';
+  if (chptr->mode.mode & MODE_REGONLY)
+    *mbuf++ = 'r';
+  if (chptr->mode.mode & MODE_DELJOINS)
+    *mbuf++ = 'D';
+  else if (MyUser(cptr) && (chptr->mode.mode & MODE_WASDELJOINS))
+    *mbuf++ = 'd';
   if (chptr->mode.limit) {
     *mbuf++ = 'l';
-    sprintf_irc(pbuf, "%d", chptr->mode.limit);
+    ircd_snprintf(0, pbuf, buflen, "%u", chptr->mode.limit);
+    previous_parameter = 1;
   }
 
   if (*chptr->mode.key) {
     *mbuf++ = 'k';
+    if (previous_parameter)
+      strcat(pbuf, " ");
     if (is_chan_op(cptr, chptr) || IsServer(cptr)) {
-      if (chptr->mode.limit)
-        strcat(pbuf, " ");
       strcat(pbuf, chptr->mode.key);
-    }
+    } else
+      strcat(pbuf, "*");
+    previous_parameter = 1;
+  }
+  if (*chptr->mode.apass) {
+    *mbuf++ = 'A';
+    if (previous_parameter)
+      strcat(pbuf, " ");
+    if (IsServer(cptr)) {
+      strcat(pbuf, chptr->mode.apass);
+    } else
+      strcat(pbuf, "*");
+    previous_parameter = 1;
+  }
+  if (*chptr->mode.upass) {
+    *mbuf++ = 'U';
+    if (previous_parameter)
+      strcat(pbuf, " ");
+    if (IsServer(cptr) || (member && IsChanOp(member) && OpLevel(member) == 0)) {
+      strcat(pbuf, chptr->mode.upass);
+    } else
+      strcat(pbuf, "*");
   }
   *mbuf = '\0';
 }
 
-/*
- * send "cptr" a full list of the modes for channel chptr.
+/** Compare two members oplevel
+ *
+ * @param mp1  Pointer to a pointer to a membership
+ * @param mp2  Pointer to a pointer to a membership
+ *
+ * @returns 0 if equal, -1 if mp1 is lower, +1 otherwise.
+ *
+ * Used for qsort(3).
+ */
+int compare_member_oplevel(const void *mp1, const void *mp2)
+{
+  struct Membership const* member1 = *(struct Membership const**)mp1;
+  struct Membership const* member2 = *(struct Membership const**)mp2;
+  if (member1->oplevel == member2->oplevel)
+    return 0;
+  return (member1->oplevel < member2->oplevel) ? -1 : 1;
+}
+
+/* send "cptr" a full list of the modes for channel chptr.
+ *
+ * Sends a BURST line to cptr, bursting all the modes for the channel.
+ *
+ * @param cptr Client pointer
+ * @param chptr        Channel pointer
  */
 void send_channel_modes(struct Client *cptr, struct Channel *chptr)
 {
+  /* The order in which modes are generated is now mandatory */
   static unsigned int current_flags[4] =
-      { 0, CHFL_CHANOP | CHFL_VOICE, CHFL_VOICE, CHFL_CHANOP };
+      { 0, CHFL_VOICE, CHFL_CHANOP, CHFL_CHANOP | CHFL_VOICE };
   int                first = 1;
   int                full  = 1;
   int                flag_cnt = 0;
@@ -787,6 +1035,11 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
   char modebuf[MODEBUFLEN];
   char parabuf[MODEBUFLEN];
   struct MsgBuf *mb;
+  int                 number_of_ops = 0;
+  int                 opped_members_index = 0;
+  struct Membership** opped_members = NULL;
+  int                 last_oplevel = 0;
+  int                 feat_oplevels = (chptr->mode.mode & MODE_APASS) != 0;
 
   assert(0 != cptr);
   assert(0 != chptr); 
@@ -798,7 +1051,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
   lp2 = chptr->banlist;
 
   *modebuf = *parabuf = '\0';
-  channel_modes(cptr, modebuf, parabuf, chptr);
+  channel_modes(cptr, modebuf, parabuf, sizeof(parabuf), chptr, 0);
 
   for (first = 1; full; first = 0)      /* Loop for multiple messages */
   {
@@ -810,7 +1063,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
     mb = msgq_make(&me, "%C " TOK_BURST " %H %Tu", &me, chptr,
                   chptr->creationtime);
 
-    if (first && modebuf[1])    /* Add simple modes (iklmnpst)
+    if (first && modebuf[1])    /* Add simple modes (Aiklmnpstu)
                                  if first message */
     {
       /* prefix: "<Y> B <channel> <TS>[ <modes>[ <params>]]" */
@@ -823,52 +1076,121 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
     /*
      * Attach nicks, comma seperated " nick[:modes],nick[:modes],..."
      *
-     * Run 4 times over all members, to group the members with the
-     * same mode together
+     * First find all opless members.
+     * Run 2 times over all members, to group the members with
+     * and without voice together.
+     * Then run 2 times over all opped members (which are ordered
+     * by op-level) to also group voice and non-voice together.
      */
-    for (first = 1; flag_cnt < 4;
-         member = chptr->members, new_mode = 1, flag_cnt++)
+    for (first = 1; flag_cnt < 4; new_mode = 1, ++flag_cnt)
     {
-      for (; member; member = member->next_member)
+      while (member)
       {
-        if ((member->status & CHFL_VOICED_OR_OPPED) !=
-            current_flags[flag_cnt])
-          continue;             /* Skip members with different flags */
-       if (msgq_bufleft(mb) < NUMNICKLEN + 4)
-          /* The 4 is a possible ",:ov" */
-        {
-          full = 1;           /* Make sure we continue after
-                                 sending it so far */
-          new_mode = 1;       /* Ensure the new BURST line contains the current
-                                 mode. --Gte */
-          break;              /* Do not add this member to this message */
-        }
-       msgq_append(&me, mb, "%c%C", first ? ' ' : ',', member->user);
-        first = 0;              /* From now on, us comma's to add new nicks */
-
-        /*
-         * Do we have a nick with a new mode ?
-         * Or are we starting a new BURST line?
-         */
-        if (new_mode)
-        {
-          new_mode = 0;
-          if (IsVoicedOrOpped(member)) {
-           char tbuf[4] = ":";
+       if (flag_cnt < 2 && IsChanOp(member))
+       {
+         /*
+          * The first loop (to find all non-voice/op), we count the ops.
+          * The second loop (to find all voiced non-ops), store the ops
+          * in a dynamic array.
+          */
+         if (flag_cnt == 0)
+           ++number_of_ops;
+         else
+           opped_members[opped_members_index++] = member;
+       }
+       /* Only handle the members with the flags that we are interested in. */
+        if ((member->status & CHFL_VOICED_OR_OPPED) == current_flags[flag_cnt])
+       {
+         if (msgq_bufleft(mb) < NUMNICKLEN + 3 + MAXOPLEVELDIGITS)
+           /* The 3 + MAXOPLEVELDIGITS is a possible ",:v999". */
+         {
+           full = 1;           /* Make sure we continue after
+                                  sending it so far */
+           /* Ensure the new BURST line contains the current
+            * ":mode", except when there is no mode yet. */
+           new_mode = (flag_cnt > 0) ? 1 : 0;
+           break;              /* Do not add this member to this message */
+         }
+         msgq_append(&me, mb, "%c%C", first ? ' ' : ',', member->user);
+         first = 0;              /* From now on, use commas to add new nicks */
+
+         /*
+          * Do we have a nick with a new mode ?
+          * Or are we starting a new BURST line?
+          */
+         if (new_mode || !feat_oplevels)
+         {
+           /*
+            * This means we are at the _first_ member that has only
+            * voice, or the first member that has only ops, or the
+            * first member that has voice and ops (so we get here
+            * at most three times, plus once for every start of
+            * a continued BURST line where only these modes is current.
+            * In the two cases where the current mode includes ops,
+            * we need to add the _absolute_ value of the oplevel to the mode.
+            */
+           char tbuf[3 + MAXOPLEVELDIGITS] = ":";
            int loc = 1;
 
-            if (IsChanOp(member))
-             tbuf[loc++] = 'o';
-            if (HasVoice(member))
+           if (HasVoice(member))       /* flag_cnt == 1 or 3 */
              tbuf[loc++] = 'v';
+           if (IsChanOp(member))       /* flag_cnt == 2 or 3 */
+           {
+              /* append the absolute value of the oplevel */
+              if (feat_oplevels)
+                loc += ircd_snprintf(0, tbuf + loc, sizeof(tbuf) - loc, "%u", last_oplevel = member->oplevel);
+              else
+                tbuf[loc++] = 'o';
+           }
            tbuf[loc] = '\0';
            msgq_append(&me, mb, tbuf);
-          }
-        }
+           new_mode = 0;
+         }
+         else if (flag_cnt > 1 && last_oplevel != member->oplevel)
+         {
+           /*
+            * This can't be the first member of a (continued) BURST
+            * message because then either flag_cnt == 0 or new_mode == 1
+            * Now we need to append the incremental value of the oplevel.
+            */
+            char tbuf[2 + MAXOPLEVELDIGITS];
+           ircd_snprintf(0, tbuf, sizeof(tbuf), ":%u", member->oplevel - last_oplevel);
+           last_oplevel = member->oplevel;
+           msgq_append(&me, mb, tbuf);
+         }
+       }
+       /* Go to the next `member'. */
+       if (flag_cnt < 2)
+         member = member->next_member;
+       else
+         member = opped_members[++opped_members_index];
       }
       if (full)
-        break;
-    }
+       break;
+
+      /* Point `member' at the start of the list again. */
+      if (flag_cnt == 0)
+      {
+       member = chptr->members;
+       /* Now, after one loop, we know the number of ops and can
+        * allocate the dynamic array with pointer to the ops. */
+       opped_members = (struct Membership**)
+         MyMalloc((number_of_ops + 1) * sizeof(struct Membership*));
+       opped_members[number_of_ops] = NULL;    /* Needed for loop termination */
+      }
+      else
+      {
+       /* At the end of the second loop, sort the opped members with
+        * increasing op-level, so that we will output them in the
+        * correct order (and all op-level increments stay positive) */
+       if (flag_cnt == 1)
+         qsort(opped_members, number_of_ops,
+               sizeof(struct Membership*), compare_member_oplevel);
+       /* The third and fourth loop run only over the opped members. */
+       member = opped_members[(opped_members_index = 0)];
+      }
+
+    } /* loop over 0,+v,+o,+ov */
 
     if (!full)
     {
@@ -894,14 +1216,18 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
     msgq_clean(mb);
   }                             /* Continue when there was something
                                  that didn't fit (full==1) */
+  if (opped_members)
+    MyFree(opped_members);
+  if (feature_bool(FEAT_TOPIC_BURST) && (chptr->topic[0] != '\0'))
+      sendcmdto_one(&me, CMD_TOPIC, cptr, "%H %Tu %Tu :%s", chptr,
+                    chptr->creationtime, chptr->topic_time, chptr->topic);
 }
 
-/*
+/** Canonify a mask.
  * pretty_mask
  *
- * by Carlo Wood (Run), 05 Oct 1998.
- *
- * Canonify a mask.
+ * @author Carlo Wood (Run), 
+ * 05 Oct 1998.
  *
  * When the nick is longer then NICKLEN, it is cut off (its an error of course).
  * When the user name or host name are too long (USERLEN and HOSTLEN
@@ -914,10 +1240,14 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
  * 3)   xxx!yyy         -> nick!user@*
  * 4)   xxx@yyy         -> *!user@host
  * 5)   xxx!yyy@zzz     -> nick!user@host
+ *
+ * @param mask The uncanonified mask.
+ * @returns The updated mask in a static buffer.
  */
 char *pretty_mask(char *mask)
 {
   static char star[2] = { '*', 0 };
+  static char retmask[NUH_BUFSIZE];
   char *last_dot = NULL;
   char *ptr;
 
@@ -990,9 +1320,14 @@ char *pretty_mask(char *mask)
     host = ptr - HOSTLEN;
     *host = '*';
   }
-  return make_nick_user_host(nick, user, host);
+  return make_nick_user_host(retmask, nick, user, host);
 }
 
+/** send a banlist to a client for a channel
+ *
+ * @param cptr Client to send the banlist to.
+ * @param chptr        Channel whose banlist to send.
+ */
 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
 {
   struct SLink* lp;
@@ -1007,11 +1342,17 @@ static void send_ban_list(struct Client* cptr, struct Channel* chptr)
   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
 }
 
-/* We are now treating the <key> part of /join <channel list> <key> as a key
+/** Check a key against a keyring.
+ * We are now treating the <key> part of /join <channel list> <key> as a key
  * ring; that is, we try one key against the actual channel key, and if that
  * doesn't work, we try the next one, and so on. -Kev -Texaco
  * Returns: 0 on match, 1 otherwise
  * This version contributed by SeKs <intru@info.polymtl.ca>
+ *
+ * @param key          Key to check
+ * @param keyring      Comma seperated list of keys
+ *
+ * @returns True if the key was found and matches, false otherwise.
  */
 static int compall(char *key, char *keyring)
 {
@@ -1042,9 +1383,17 @@ top:
   goto top;                     /* and check it against the key */
 }
 
+/** Returns if a user can join a channel with a specific key.
+ *
+ * @param sptr The client trying to join
+ * @param chptr        The channel to join
+ * @param key  The key to use
+ *
+ * @returns any error that occured bitwised OR'd with MAGIC_OPER_OVERRIDE
+ *         if the oper used the magic key, 0 if no error occured.
+ */
 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
 {
-  struct SLink *lp;
   int overrideJoin = 0;  
   
   /*
@@ -1053,15 +1402,15 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
    * Now a user CAN escape anything if invited -- Isomer
    */
 
-  for (lp = (cli_user(sptr))->invited; lp; lp = lp->next)
-    if (lp->value.chptr == chptr)
-      return 0;
+  if (IsInvited(sptr, chptr))
+    return 0;
   
   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
      a HACK(4) notice will be sent if he would not have been supposed
      to join normally. */ 
   if (IsLocalChannel(chptr->chname) && HasPriv(sptr, PRIV_WALK_LCHAN) &&
-      !BadPtr(key) && compall("OVERRIDE",key) == 0)
+      !BadPtr(key) && compall("OVERRIDE",chptr->mode.key) != 0 &&
+      compall("OVERRIDE",key) == 0)
     overrideJoin = MAGIC_OPER_OVERRIDE;
 
   if (chptr->mode.mode & MODE_INVITEONLY)
@@ -1069,6 +1418,9 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
        
   if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
        return overrideJoin + ERR_CHANNELISFULL;
+
+  if ((chptr->mode.mode & MODE_REGONLY) && !IsAccount(sptr))
+       return overrideJoin + ERR_NEEDREGGEDNICK;
        
   if (is_banned(sptr, chptr, NULL))
        return overrideJoin + ERR_BANNEDFROMCHAN;
@@ -1085,8 +1437,9 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
   return 0;
 }
 
-/*
- * Remove bells and commas from channel name
+/** Remove bells and commas from channel name
+ *
+ * @param ch   Channel name to clean, modified in place.
  */
 void clean_channelname(char *cn)
 {
@@ -1111,9 +1464,17 @@ void clean_channelname(char *cn)
   }
 }
 
-/*
- *  Get Channel block for i (and allocate a new channel
+/** Get a channel block, creating if necessary.
+ *  Get Channel block for chname (and allocate a new channel
  *  block, if it didn't exists before).
+ *
+ * @param cptr         Client joining the channel.
+ * @param chname       The name of the channel to join.
+ * @param flag         set to CGT_CREATE to create the channel if it doesn't 
+ *                     exist
+ *
+ * @returns NULL if the channel is invalid, doesn't exist and CGT_CREATE 
+ *     wasn't specified or a pointer to the channel structure
  */
 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
 {
@@ -1149,6 +1510,14 @@ struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType fl
   return chptr;
 }
 
+/** invite a user to a channel.
+ *
+ * Adds an invite for a user to a channel.  Limits the number of invites
+ * to FEAT_MAXCHANNELSPERUSER.  Does not sent notification to the user.
+ *
+ * @param cptr The client to be invited.
+ * @param chptr        The channel to be invited to.
+ */
 void add_invite(struct Client *cptr, struct Channel *chptr)
 {
   struct SLink *inv, **tmp;
@@ -1178,8 +1547,11 @@ void add_invite(struct Client *cptr, struct Channel *chptr)
   (cli_user(cptr))->invites++;
 }
 
-/*
+/** Delete an invite
  * Delete Invite block from channel invite list and client invite list
+ *
+ * @param cptr Client pointer
+ * @param chptr        Channel pointer
  */
 void del_invite(struct Client *cptr, struct Channel *chptr)
 {
@@ -1205,7 +1577,13 @@ void del_invite(struct Client *cptr, struct Channel *chptr)
     }
 }
 
-/* List and skip all channels that are listen */
+/** List a set of channels
+ * Lists a series of channels that match a filter, skipping channels that 
+ * have been listed before.
+ *
+ * @param cptr Client to send the list to.
+ * @param nr   Number of channels to send this update.
+ */
 void list_next_channels(struct Client *cptr, int nr)
 {
   struct ListingArgs *args = cli_listing(cptr);
@@ -1215,16 +1593,19 @@ void list_next_channels(struct Client *cptr, int nr)
   {
     for (; chptr; chptr = chptr->next)
     {
-      if (!cli_user(cptr) || (SecretChannel(chptr) && !find_channel_member(cptr, chptr)))
+      if (!cli_user(cptr))
+        continue;
+      if (!(HasPriv(cptr, PRIV_LIST_CHAN) && IsAnOper(cptr)) && 
+          SecretChannel(chptr) && !find_channel_member(cptr, chptr))
         continue;
       if (chptr->users > args->min_users && chptr->users < args->max_users &&
           chptr->creationtime > args->min_time &&
           chptr->creationtime < args->max_time &&
-          (!args->topic_limits || (*chptr->topic &&
+          (!(args->flags & LISTARG_TOPICLIMITS) || (*chptr->topic &&
           chptr->topic_time > args->min_topic_time &&
           chptr->topic_time < args->max_topic_time)))
       {
-        if (ShowChannel(cptr,chptr))
+        if ((args->flags & LISTARG_SHOWSECRET) || ShowChannel(cptr,chptr))
          send_reply(cptr, RPL_LIST, chptr->chname, chptr->users,
                     chptr->topic);
         chptr = chptr->next;
@@ -1244,9 +1625,12 @@ void list_next_channels(struct Client *cptr, int nr)
     (cli_listing(cptr))->chptr = chptr;
     chptr->mode.mode |= MODE_LISTED;
   }
+
+  update_write(cptr);
 }
 
-/*
+/** @page zombie Explaination of Zombies
+ *
  * Consider:
  *
  *                     client
@@ -1261,7 +1645,7 @@ void list_next_channels(struct Client *cptr, int nr)
  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
  *
  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
- *    Remove the user immedeately when no users are left on the channel.
+ *    Remove the user immediately when no users are left on the channel.
  * b) On server B : remove the user (who/lp) from the channel, send a
  *    PART upstream (to A) and pass on the KICK.
  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
@@ -1291,8 +1675,18 @@ void list_next_channels(struct Client *cptr, int nr)
  *
  * --Run
  */
-void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
-                 struct Client* sptr, struct Channel* chptr)
+
+/** Turn a user on a channel into a zombie
+ * This function turns a user into a zombie (see \ref zombie)
+ *
+ * @param member  The structure representing this user on this channel.
+ * @param who    The client that is being kicked.
+ * @param cptr   The connection the kick came from.
+ * @param sptr    The client that is doing the kicking.
+ * @param chptr          The channel the user is being kicked from.
+ */
+void make_zombie(struct Membership* member, struct Client* who, 
+               struct Client* cptr, struct Client* sptr, struct Channel* chptr)
 {
   assert(0 != member);
   assert(0 != who);
@@ -1331,6 +1725,11 @@ void make_zombie(struct Membership* member, struct Client* who, struct Client* c
   */
 }
 
+/** returns the number of zombies on a channel
+ * @param chptr        Channel to count zombies in.
+ *
+ * @returns The number of zombies on the channel.
+ */
 int number_of_zombies(struct Channel *chptr)
 {
   struct Membership* member;
@@ -1344,13 +1743,20 @@ int number_of_zombies(struct Channel *chptr)
   return count;
 }
 
-/*
+/** Concatenate some strings together.
  * This helper function builds an argument string in strptr, consisting
  * of the original string, a space, and str1 and str2 concatenated (if,
  * of course, str2 is not NULL)
+ *
+ * @param strptr       The buffer to concatenate into
+ * @param strptr_i     modified offset to the position to modify
+ * @param str1         The string to contatenate from.
+ * @param str2         The second string to contatenate from.
+ * @param c            Charactor to seperate the string from str1 and str2.
  */
 static void
-build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
+build_string(char *strptr, int *strptr_i, const char *str1,
+             const char *str2, char c)
 {
   if (c)
     strptr[(*strptr_i)++] = c;
@@ -1365,9 +1771,15 @@ build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
   strptr[(*strptr_i)] = '\0';
 }
 
-/*
+/** Flush out the modes
  * This is the workhorse of our ModeBuf suite; this actually generates the
  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
+ *
+ * @param mbuf The mode buffer to flush
+ * @param all  If true, flush all modes, otherwise leave partial modes in the
+ *             buffer.
+ *
+ * @returns 0
  */
 static int
 modebuf_flush_int(struct ModeBuf *mbuf, int all)
@@ -1382,9 +1794,14 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
     MODE_TOPICLIMIT,   't',
     MODE_INVITEONLY,   'i',
     MODE_NOPRIVMSGS,   'n',
+    MODE_REGONLY,      'r',
+    MODE_DELJOINS,      'D',
+    MODE_WASDELJOINS,   'd',
 /*  MODE_KEY,          'k', */
 /*  MODE_BAN,          'b', */
-/*  MODE_LIMIT,                'l', */
+    MODE_LIMIT,                'l',
+/*  MODE_APASS,                'A', */
+/*  MODE_UPASS,                'U', */
     0x0, 0x0
   };
   int i;
@@ -1419,9 +1836,10 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
     return 0;
 
-  /* Ok, if we were given the OPMODE flag, hide the source if its a user */
-  if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
-    app_source = (cli_user(mbuf->mb_source))->server;
+  /* Ok, if we were given the OPMODE flag, or its a server, hide the source.
+   */
+  if (mbuf->mb_dest & MODEBUF_DEST_OPMODE || IsServer(mbuf->mb_source))
+    app_source = &me;
   else
     app_source = mbuf->mb_source;
 
@@ -1459,18 +1877,41 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
        bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
        totalbuflen -= IRCD_MAX(5, tmp) + 1;
       }
-    } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
+    } else if (MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS)) {
       tmp = strlen(MB_STRING(mbuf, i));
 
       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
        MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
       else {
-       bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
+       char mode_char;
+       switch(MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS))
+       {
+         case MODE_APASS:
+           mode_char = 'A';
+           break;
+         case MODE_UPASS:
+           mode_char = 'U';
+           break;
+         default:
+           mode_char = 'b';
+           break;
+       }
+       bufptr[(*bufptr_i)++] = mode_char;
+       totalbuflen -= tmp + 1;
+      }
+    } else if (MB_TYPE(mbuf, i) & MODE_KEY) {
+      tmp = (mbuf->mb_dest & MODEBUF_DEST_NOKEY ? 1 :
+            strlen(MB_STRING(mbuf, i)));
+
+      if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
+       MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
+      else {
+       bufptr[(*bufptr_i)++] = 'k';
        totalbuflen -= tmp + 1;
       }
     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
       /* if it's a limit, we also format the number */
-      sprintf_irc(limitbuf, "%d", MB_UINT(mbuf, i));
+      ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
 
       tmp = strlen(limitbuf);
 
@@ -1513,10 +1954,19 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
        build_string(strptr, strptr_i, cli_name(MB_CLIENT(mbuf, i)), 0, ' ');
 
-      /* deal with strings... */
-      else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
+      /* deal with bans... */
+      else if (MB_TYPE(mbuf, i) & MODE_BAN)
        build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
 
+      /* deal with keys... */
+      else if (MB_TYPE(mbuf, i) & MODE_KEY)
+       build_string(strptr, strptr_i, mbuf->mb_dest & MODEBUF_DEST_NOKEY ?
+                    "*" : MB_STRING(mbuf, i), 0, ' ');
+
+      /* deal with invisible passwords */
+      else if (MB_TYPE(mbuf, i) & (MODE_APASS | MODE_UPASS))
+       build_string(strptr, strptr_i, "*", 0, ' ');
+
       /*
        * deal with limit; note we cannot include the limit parameter if we're
        * removing it
@@ -1527,31 +1977,30 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
     }
 
     /* send the messages off to their destination */
-    if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
+    if (mbuf->mb_dest & MODEBUF_DEST_HACK2)
       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
-                          "[%Tu]", cli_name(app_source),
+                          "[%Tu]",
+                           cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
+                                    mbuf->mb_source : app_source),
                           mbuf->mb_channel->chname,
                           rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
                           addbuf, remstr, addstr,
                           mbuf->mb_channel->creationtime);
-      sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
-                           ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
-                           cli_name(app_source), mbuf->mb_channel->chname,
-                           rembuf_i ? "-" : "", rembuf,
-                           addbuf_i ? "+" : "", addbuf, remstr, addstr,
-                           mbuf->mb_channel->creationtime);
-    }
 
     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
-                          "%s%s%s%s%s%s [%Tu]", cli_name(app_source),
+                          "%s%s%s%s%s%s [%Tu]",
+                           cli_name(feature_bool(FEAT_HIS_SNOTICES) ? 
+                                    mbuf->mb_source : app_source),
                           mbuf->mb_channel->chname, rembuf_i ? "-" : "",
                           rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
                           mbuf->mb_channel->creationtime);
 
     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
-                          "[%Tu]", cli_name(app_source),
+                          "[%Tu]",
+                          cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
+                                    mbuf->mb_source : app_source),
                           mbuf->mb_channel->chname,
                           rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
                           addbuf, remstr, addstr,
@@ -1564,7 +2013,7 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
                addbuf_i ? "+" : "", addbuf, remstr, addstr);
 
     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
-      sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
+      sendcmdto_channel_butserv_butone(app_source, CMD_MODE, mbuf->mb_channel, NULL, 0,
                                "%H %s%s%s%s%s%s", mbuf->mb_channel,
                                rembuf_i ? "-" : "", rembuf,
                                addbuf_i ? "+" : "", addbuf, remstr, addstr);
@@ -1601,7 +2050,7 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
        build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
 
       /* deal with modes that take strings */
-      else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
+      else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN | MODE_APASS | MODE_UPASS))
        build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
 
       /*
@@ -1687,9 +2136,15 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
   return 0;
 }
 
-/*
+/** Initialise a modebuf
  * This routine just initializes a ModeBuf structure with the information
  * needed and the options given.
+ *
+ * @param mbuf         The mode buffer to initialise.
+ * @param source       The client that is performing the mode.
+ * @param connect      ?
+ * @param chan         The channel that the mode is being performed upon.
+ * @param dest         ?
  */
 void
 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
@@ -1702,6 +2157,8 @@ modebuf_init(struct ModeBuf *mbuf, struct Client *source,
   assert(0 != chan);
   assert(0 != dest);
 
+  if (IsLocalChannel(chan->chname)) dest &= ~MODEBUF_DEST_SERVER;
+
   mbuf->mb_add = 0;
   mbuf->mb_rem = 0;
   mbuf->mb_source = source;
@@ -1717,9 +2174,12 @@ modebuf_init(struct ModeBuf *mbuf, struct Client *source,
   }
 }
 
-/*
+/** Append a new mode to a modebuf
  * This routine simply adds modes to be added or deleted; do a binary OR
  * with either MODE_ADD or MODE_DEL
+ *
+ * @param mbuf         Mode buffer
+ * @param mode         MODE_ADD or MODE_DEL OR'd with MODE_PRIVATE etc.
  */
 void
 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
@@ -1728,7 +2188,8 @@ modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
 
   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
-          MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
+          MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS | MODE_REGONLY |
+           MODE_DELJOINS | MODE_WASDELJOINS);
 
   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
     return;
@@ -1742,10 +2203,15 @@ modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
   }
 }
 
-/*
+/** Append a mode that takes an int argument to the modebuf
+ *
  * This routine adds a mode to be added or deleted that takes a unsigned
  * int parameter; mode may *only* be the relevant mode flag ORed with one
  * of MODE_ADD or MODE_DEL
+ *
+ * @param mbuf         The mode buffer to append to.
+ * @param mode         The mode to append.
+ * @param uint         The argument to the mode.
  */
 void
 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
@@ -1753,6 +2219,10 @@ modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
   assert(0 != mbuf);
   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
 
+  if (mode == (MODE_LIMIT | MODE_DEL)) {
+      mbuf->mb_rem |= mode;
+      return;
+  }
   MB_TYPE(mbuf, mbuf->mb_count) = mode;
   MB_UINT(mbuf, mbuf->mb_count) = uint;
 
@@ -1762,10 +2232,15 @@ modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
     modebuf_flush_int(mbuf, 0);
 }
 
-/*
+/** append a string mode
  * This routine adds a mode to be added or deleted that takes a string
  * parameter; mode may *only* be the relevant mode flag ORed with one of
  * MODE_ADD or MODE_DEL
+ *
+ * @param mbuf         The mode buffer to append to.
+ * @param mode         The mode to append.
+ * @param string       The string parameter to append.
+ * @param free         If the string should be free'd later.
  */
 void
 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
@@ -1783,10 +2258,14 @@ modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
     modebuf_flush_int(mbuf, 0);
 }
 
-/*
+/** Append a mode on a client to a modebuf.
  * This routine adds a mode to be added or deleted that takes a client
  * parameter; mode may *only* be the relevant mode flag ORed with one of
  * MODE_ADD or MODE_DEL
+ *
+ * @param mbuf         The modebuf to append the mode to.
+ * @param mode         The mode to append.
+ * @param client       The client argument to append.
  */
 void
 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
@@ -1804,17 +2283,37 @@ modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
     modebuf_flush_int(mbuf, 0);
 }
 
-/*
- * This is the exported binding for modebuf_flush()
+/** The exported binding for modebuf_flush()
+ *
+ * @param mbuf The mode buffer to flush.
+ * 
+ * @see modebuf_flush_int()
  */
 int
 modebuf_flush(struct ModeBuf *mbuf)
 {
+  struct Membership *memb;
+
+  /* Check if MODE_WASDELJOINS should be set */
+  if (!(mbuf->mb_channel->mode.mode & (MODE_DELJOINS | MODE_WASDELJOINS))
+      && (mbuf->mb_rem & MODE_DELJOINS)) {
+    for (memb = mbuf->mb_channel->members; memb; memb = memb->next_member) {
+      if (IsDelayedJoin(memb)) {
+          mbuf->mb_channel->mode.mode |= MODE_WASDELJOINS;
+          mbuf->mb_add |= MODE_WASDELJOINS;
+          mbuf->mb_rem &= ~MODE_WASDELJOINS;
+          break;
+      }
+    }
+  }
+
   return modebuf_flush_int(mbuf, 1);
 }
 
-/*
- * This extracts the simple modes contained in mbuf
+/* This extracts the simple modes contained in mbuf
+ *
+ * @param mbuf         The mode buffer to extract the modes from.
+ * @param buf          The string buffer to write the modes into.
  */
 void
 modebuf_extract(struct ModeBuf *mbuf, char *buf)
@@ -1829,14 +2328,19 @@ modebuf_extract(struct ModeBuf *mbuf, char *buf)
     MODE_INVITEONLY,   'i',
     MODE_NOPRIVMSGS,   'n',
     MODE_KEY,          'k',
+    MODE_APASS,                'A',
+    MODE_UPASS,                'U',
 /*  MODE_BAN,          'b', */
     MODE_LIMIT,                'l',
+    MODE_REGONLY,      'r',
+    MODE_DELJOINS,      'D',
     0x0, 0x0
   };
   unsigned int add;
   int i, bufpos = 0, len;
   int *flag_p;
   char *key = 0, limitbuf[20];
+  char *apass = 0, *upass = 0;
 
   assert(0 != mbuf);
   assert(0 != buf);
@@ -1847,12 +2351,16 @@ modebuf_extract(struct ModeBuf *mbuf, char *buf)
 
   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
     if (MB_TYPE(mbuf, i) & MODE_ADD) {
-      add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT);
+      add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT | MODE_APASS | MODE_UPASS);
 
       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
        key = MB_STRING(mbuf, i);
       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
-       ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
+       ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
+      else if (MB_TYPE(mbuf, i) & MODE_UPASS)
+       upass = MB_STRING(mbuf, i);
+      else if (MB_TYPE(mbuf, i) & MODE_APASS)
+       apass = MB_STRING(mbuf, i);
     }
   }
 
@@ -1870,6 +2378,10 @@ modebuf_extract(struct ModeBuf *mbuf, char *buf)
       build_string(buf, &bufpos, key, 0, ' ');
     else if (buf[i] == 'l')
       build_string(buf, &bufpos, limitbuf, 0, ' ');
+    else if (buf[i] == 'U')
+      build_string(buf, &bufpos, upass, 0, ' ');
+    else if (buf[i] == 'A')
+      build_string(buf, &bufpos, apass, 0, ' ');
   }
 
   buf[bufpos] = '\0';
@@ -1877,8 +2389,11 @@ modebuf_extract(struct ModeBuf *mbuf, char *buf)
   return;
 }
 
-/*
- * Simple function to invalidate bans
+/** Simple function to invalidate bans
+ *
+ * This function sets all bans as being valid.
+ *
+ * @param chan The channel to operate on.
  */
 void
 mode_ban_invalidate(struct Channel *chan)
@@ -1889,8 +2404,12 @@ mode_ban_invalidate(struct Channel *chan)
     ClearBanValid(member);
 }
 
-/*
- * Simple function to drop invite structures
+/** Simple function to drop invite structures
+ *
+ * Remove all the invites on the channel.
+ *
+ * @param chan         Channel to remove invites from.
+ *
  */
 void
 mode_invite_clear(struct Channel *chan)
@@ -1900,17 +2419,20 @@ mode_invite_clear(struct Channel *chan)
 }
 
 /* What we've done for mode_parse so far... */
-#define DONE_LIMIT     0x01    /* We've set the limit */
-#define DONE_KEY       0x02    /* We've set the key */
-#define DONE_BANLIST   0x04    /* We've sent the ban list */
-#define DONE_NOTOPER   0x08    /* We've sent a "Not oper" error */
-#define DONE_BANCLEAN  0x10    /* We've cleaned bans... */
+#define DONE_LIMIT     0x01    /**< We've set the limit */
+#define DONE_KEY       0x02    /**< We've set the key */
+#define DONE_BANLIST   0x04    /**< We've sent the ban list */
+#define DONE_NOTOPER   0x08    /**< We've sent a "Not oper" error */
+#define DONE_BANCLEAN  0x10    /**< We've cleaned bans... */
+#define DONE_UPASS     0x20    /**< We've set user pass */
+#define DONE_APASS     0x40    /**< We've set admin pass */
 
 struct ParseState {
   struct ModeBuf *mbuf;
   struct Client *cptr;
   struct Client *sptr;
   struct Channel *chptr;
+  struct Membership *member;
   int parc;
   char **parv;
   unsigned int flags;
@@ -1928,9 +2450,11 @@ struct ParseState {
   } cli_change[MAXPARA];
 };
 
-/*
+/** Helper function to send "Not oper" or "Not member" messages
  * Here's a helper function to deal with sending along "Not oper" or
  * "Not member" messages
+ *
+ * @param state        Parsing State object
  */
 static void
 send_notoper(struct ParseState *state)
@@ -1944,8 +2468,11 @@ send_notoper(struct ParseState *state)
   state->done |= DONE_NOTOPER;
 }
 
-/*
+/** Parse a limit
  * Helper function to convert limits
+ *
+ * @param state                Parsing state object.
+ * @param flag_p       ?
  */
 static void
 mode_parse_limit(struct ParseState *state, int *flag_p)
@@ -1962,10 +2489,13 @@ mode_parse_limit(struct ParseState *state, int *flag_p)
       return;
     }
 
-    t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
+    t_limit = strtoul(state->parv[state->args_used++], 0, 10); /* grab arg */
     state->parc--;
     state->max_args--;
 
+    if ((int)t_limit<0) /* don't permit a negative limit */
+      return;
+
     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
        (!t_limit || t_limit == state->chptr->mode.limit))
       return;
@@ -1978,6 +2508,16 @@ mode_parse_limit(struct ParseState *state, int *flag_p)
     return;
   }
 
+  /* Can't remove a limit that's not there */
+  if (state->dir == MODE_DEL && !state->chptr->mode.limit)
+    return;
+    
+  /* Skip if this is a burst and a lower limit than this is set already */
+  if ((state->flags & MODE_PARSE_BURST) &&
+      (state->chptr->mode.mode & flag_p[0]) &&
+      (state->chptr->mode.limit < t_limit))
+    return;
+
   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
     return;
   state->done |= DONE_LIMIT;
@@ -2031,12 +2571,12 @@ mode_parse_key(struct ParseState *state, int *flag_p)
     return;
   state->done |= DONE_KEY;
 
-  t_len = KEYLEN + 1;
+  t_len = KEYLEN;
 
   /* clean up the key string */
   s = t_str;
-  while (*++s > ' ' && *s != ':' && --t_len)
-    ;
+  while (*s > ' ' && *s != ':' && *s != ',' && t_len--)
+    s++;
   *s = '\0';
 
   if (!*t_str) { /* warn if empty */
@@ -2049,6 +2589,13 @@ mode_parse_key(struct ParseState *state, int *flag_p)
   if (!state->mbuf)
     return;
 
+  /* Skip if this is a burst, we have a key already and the new key is 
+   * after the old one alphabetically */
+  if ((state->flags & MODE_PARSE_BURST) &&
+      *(state->chptr->mode.key) &&
+      ircd_strcmp(state->chptr->mode.key, t_str) <= 0)
+    return;
+
   /* can't add a key if one is set, nor can one remove the wrong key */
   if (!(state->flags & MODE_PARSE_FORCE))
     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
@@ -2079,6 +2626,245 @@ mode_parse_key(struct ParseState *state, int *flag_p)
   }
 }
 
+/*
+ * Helper function to convert user passes
+ */
+static void
+mode_parse_upass(struct ParseState *state, int *flag_p)
+{
+  char *t_str, *s;
+  int t_len;
+
+  if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
+    return;
+
+  if (state->parc <= 0) { /* warn if not enough args */
+    if (MyUser(state->sptr))
+      need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
+                      "MODE -U");
+    return;
+  }
+
+  t_str = state->parv[state->args_used++]; /* grab arg */
+  state->parc--;
+  state->max_args--;
+
+  /* If they're not an oper, they can't change modes */
+  if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
+    send_notoper(state);
+    return;
+  }
+
+  /* If a non-service user is trying to force it, refuse. */
+  if (state->flags & MODE_PARSE_FORCE && !IsChannelService(state->sptr)) {
+    send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+               "Use /JOIN", state->chptr->chname, " <AdminPass>.");
+    return;
+  }
+
+  /* If they are not the channel manager, they are not allowed to change it */
+  if (MyUser(state->sptr) && !IsChannelManager(state->member)) {
+    if (*state->chptr->mode.apass) {
+      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+         "Use /JOIN", state->chptr->chname, "<AdminPass>.");
+    } else {
+      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+         "Re-create the channel.  The channel must be *empty* for",
+         TStime() - state->chptr->creationtime >= 171000 ? "48 contiguous hours" : "a minute or two",
+         "before it can be recreated.");
+    }
+    return;
+  }
+  if (state->done & DONE_UPASS) /* allow upass to be set only once */
+    return;
+  state->done |= DONE_UPASS;
+
+  t_len = PASSLEN + 1;
+
+  /* clean up the upass string */
+  s = t_str;
+  while (*++s > ' ' && *s != ':' && --t_len)
+    ;
+  *s = '\0';
+
+  if (!*t_str) { /* warn if empty */
+    if (MyUser(state->sptr))
+      need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
+                      "MODE -U");
+    return;
+  }
+
+  if (!state->mbuf)
+    return;
+
+  if (!(state->flags & MODE_PARSE_FORCE))
+    /* can't add the upass while apass is not set */
+    if (state->dir == MODE_ADD && !*state->chptr->mode.apass) {
+      send_reply(state->sptr, ERR_UPASSNOTSET, state->chptr->chname, state->chptr->chname);
+      return;
+    }
+    /* can't add a upass if one is set, nor can one remove the wrong upass */
+    if ((state->dir == MODE_ADD && *state->chptr->mode.upass) ||
+       (state->dir == MODE_DEL &&
+        ircd_strcmp(state->chptr->mode.upass, t_str))) {
+      send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
+      return;
+    }
+
+  if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
+      !ircd_strcmp(state->chptr->mode.upass, t_str))
+    return; /* no upass change */
+
+  if (state->flags & MODE_PARSE_BOUNCE) {
+    if (*state->chptr->mode.upass) /* reset old upass */
+      modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
+                         state->chptr->mode.upass, 0);
+    else /* remove new bogus upass */
+      modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
+  } else /* send new upass */
+    modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
+
+  if (state->flags & MODE_PARSE_SET) {
+    if (state->dir == MODE_ADD) /* set the new upass */
+      ircd_strncpy(state->chptr->mode.upass, t_str, PASSLEN);
+    else /* remove the old upass */
+      *state->chptr->mode.upass = '\0';
+  }
+}
+
+/*
+ * Helper function to convert admin passes
+ */
+static void
+mode_parse_apass(struct ParseState *state, int *flag_p)
+{
+  char *t_str, *s;
+  int t_len;
+
+  if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
+    return;
+
+  if (state->parc <= 0) { /* warn if not enough args */
+    if (MyUser(state->sptr))
+      need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
+                      "MODE -A");
+    return;
+  }
+
+  t_str = state->parv[state->args_used++]; /* grab arg */
+  state->parc--;
+  state->max_args--;
+
+  /* If they're not an oper, they can't change modes */
+  if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
+    send_notoper(state);
+    return;
+  }
+
+  /* If a non-service user is trying to force it, refuse. */
+  if (state->flags & MODE_PARSE_FORCE && !IsChannelService(state->sptr)) {
+    send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+               "Use /JOIN", state->chptr->chname, " <AdminPass>.");
+    return;
+  }
+
+  /* Don't allow to change the Apass if the channel is older than 48 hours. */
+  if (TStime() - state->chptr->creationtime >= 172800 && !IsAnOper(state->sptr)) {
+    send_reply(state->sptr, ERR_CHANSECURED, state->chptr->chname);
+    return;
+  }
+
+  /* If they are not the channel manager, they are not allowed to change it */
+  if (MyUser(state->sptr) && !IsChannelManager(state->member)) {
+    if (*state->chptr->mode.apass) {
+      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+         "Use /JOIN", state->chptr->chname, "<AdminPass>.");
+    } else {
+      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
+         "Re-create the channel.  The channel must be *empty* for",
+         "at least a whole minute", "before it can be recreated.");
+    }
+    return;
+  }
+  if (state->done & DONE_APASS) /* allow apass to be set only once */
+    return;
+  state->done |= DONE_APASS;
+
+  t_len = PASSLEN + 1;
+
+  /* clean up the apass string */
+  s = t_str;
+  while (*++s > ' ' && *s != ':' && --t_len)
+    ;
+  *s = '\0';
+
+  if (!*t_str) { /* warn if empty */
+    if (MyUser(state->sptr))
+      need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
+                      "MODE -A");
+    return;
+  }
+
+  if (!state->mbuf)
+    return;
+
+  if (!(state->flags & MODE_PARSE_FORCE)) {
+    /* can't remove the apass while upass is still set */
+    if (state->dir == MODE_DEL && *state->chptr->mode.upass) {
+      send_reply(state->sptr, ERR_UPASSSET, state->chptr->chname, state->chptr->chname);
+      return;
+    }
+    /* can't add an apass if one is set, nor can one remove the wrong apass */
+    if ((state->dir == MODE_ADD && *state->chptr->mode.apass) ||
+       (state->dir == MODE_DEL && ircd_strcmp(state->chptr->mode.apass, t_str))) {
+      send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
+      return;
+    }
+  }
+
+  if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
+      !ircd_strcmp(state->chptr->mode.apass, t_str))
+    return; /* no apass change */
+
+  if (state->flags & MODE_PARSE_BOUNCE) {
+    if (*state->chptr->mode.apass) /* reset old apass */
+      modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
+                         state->chptr->mode.apass, 0);
+    else /* remove new bogus apass */
+      modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
+  } else /* send new apass */
+    modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
+
+  if (state->flags & MODE_PARSE_SET) {
+    if (state->dir == MODE_ADD) { /* set the new apass */
+      /* Make it VERY clear to the user that this is a one-time password */
+      ircd_strncpy(state->chptr->mode.apass, t_str, PASSLEN);
+      if (MyUser(state->sptr)) {
+       send_reply(state->sptr, RPL_APASSWARN,
+           "Channel Admin password (+A) set to '", state->chptr->mode.apass, "'. ",
+           "Are you SURE you want to use this as Admin password? ",
+           "You will NOT be able to change this password anymore once the channel is more than 48 hours old!");
+       send_reply(state->sptr, RPL_APASSWARN,
+           "Use \"/MODE ", state->chptr->chname, " -A ", state->chptr->mode.apass,
+           "\" to remove the password and then immediately set a new one. "
+           "IMPORTANT: YOU CANNOT RECOVER THIS PASSWORD, EVER; "
+           "WRITE THE PASSWORD DOWN (don't store this rescue password on disk)! "
+           "Now set the channel user password (+u).");
+      }
+    } else { /* remove the old apass */
+      *state->chptr->mode.apass = '\0';
+      if (MyUser(state->sptr))
+       send_reply(state->sptr, RPL_APASSWARN,
+           "WARNING: You removed the channel Admin password MODE (+A). ",
+           "If you would disconnect or leave the channel without setting a new password then you will ",
+           "not be able to set it again and lose ownership of this channel! ",
+           "SET A NEW PASSWORD NOW!", "");
+    }
+  }
+}
+
 /*
  * Helper function to convert bans
  */
@@ -2175,16 +2961,19 @@ mode_parse_ban(struct ParseState *state, int *flag_p)
     } else if (state->dir == MODE_ADD) {
       /* if the ban already exists, don't worry about it */
       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
+       newban->flags &= ~MODE_ADD; /* don't add ban at all */
+       MyFree(newban->value.ban.banstr); /* stopper a leak */
+       state->numbans--; /* deallocate last ban */
        if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
          break;
-       continue;
       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
        if (!(ban->flags & MODE_DEL))
          newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
       } else if (!mmatch(t_str, ban->value.ban.banstr))
        ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
 
-      if (!ban->next) {
+      if (!ban->next && (newban->flags & MODE_ADD))
+      {
        ban->next = newban; /* add our ban with its flags */
        break; /* get out of loop */
       }
@@ -2260,7 +3049,7 @@ mode_process_bans(struct ParseState *state)
       } else {
        if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
            (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
-            count >= feature_int(FEAT_MAXBANS))) {
+            count > feature_int(FEAT_MAXBANS))) {
          send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
                     ban->value.ban.banstr);
          count--;
@@ -2388,24 +3177,53 @@ mode_process_clients(struct ParseState *state)
        }
       }
 
-      /* don't allow local opers to be deopped on local channels */
-      if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
-         IsLocalChannel(state->chptr->chname) &&
-         HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
-       send_reply(state->sptr, ERR_ISOPERLCHAN,
-                  cli_name(state->cli_change[i].client),
-                  state->chptr->chname);
-       continue;
+      /* check deop for local user */
+      if (MyUser(state->sptr)) {
+
+       /* don't allow local opers to be deopped on local channels */
+       if (state->cli_change[i].client != state->sptr &&
+           IsLocalChannel(state->chptr->chname) &&
+           HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
+         send_reply(state->sptr, ERR_ISOPERLCHAN,
+                    cli_name(state->cli_change[i].client),
+                    state->chptr->chname);
+         continue;
+        }
+
+        if (feature_bool(FEAT_OPLEVELS)) {
+       /* don't allow to deop members with an op level that is <= our own level */
+       if (state->sptr != state->cli_change[i].client          /* but allow to deop oneself */
+               && state->member
+               && OpLevel(member) <= OpLevel(state->member)) {
+           int equal = (OpLevel(member) == OpLevel(state->member));
+           send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
+                      cli_name(state->cli_change[i].client),
+                      state->chptr->chname,
+                      OpLevel(state->member), OpLevel(member),
+                      "deop", equal ? "the same" : "a higher");
+         continue;
+       }
       }
     }
+    }
 
-    /* accumulate the change */
-    modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
-                       state->cli_change[i].client);
+    /* set op-level of member being opped */
+    if ((state->cli_change[i].flag & (MODE_ADD | MODE_CHANOP)) ==
+       (MODE_ADD | MODE_CHANOP)) {
+      /* If on a channel with upass set, someone with level x gives ops to someone else,
+         then that person gets level x-1.  On other channels, where upass is not set,
+        the level stays the same. */
+      int level_increment = *state->chptr->mode.upass ? 1 : 0;
+      /* Someone being opped by a server gets op-level 0 */
+      int old_level = (state->member == NULL) ? -level_increment : OpLevel(state->member);
+      SetOpLevel(member, old_level == MAXOPLEVEL ? MAXOPLEVEL : (old_level + level_increment));
+    }
 
     /* actually effect the change */
     if (state->flags & MODE_PARSE_SET) {
       if (state->cli_change[i].flag & MODE_ADD) {
+        if (IsDelayedJoin(member))
+          RevealDelayedJoin(member);
        member->status |= (state->cli_change[i].flag &
                           (MODE_CHANOP | MODE_VOICE));
        if (state->cli_change[i].flag & MODE_CHANOP)
@@ -2414,7 +3232,11 @@ mode_process_clients(struct ParseState *state)
        member->status &= ~(state->cli_change[i].flag &
                            (MODE_CHANOP | MODE_VOICE));
     }
-  } /* for (i = 0; state->cli_change[i].flags; i++) { */
+
+    /* accumulate the change */
+    modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
+                       state->cli_change[i].client);
+  } /* for (i = 0; state->cli_change[i].flags; i++) */
 }
 
 /*
@@ -2443,6 +3265,10 @@ mode_parse_mode(struct ParseState *state, int *flag_p)
       state->add &= ~MODE_SECRET;
       state->del |= MODE_SECRET;
     }
+    if (flag_p[0] & MODE_DELJOINS) {
+      state->add &= ~MODE_WASDELJOINS;
+      state->del |= MODE_WASDELJOINS;
+    }
   } else {
     state->add &= ~flag_p[0];
     state->del |= flag_p[0];
@@ -2460,7 +3286,8 @@ mode_parse_mode(struct ParseState *state, int *flag_p)
  */
 int
 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
-          struct Channel *chptr, int parc, char *parv[], unsigned int flags)
+          struct Channel *chptr, int parc, char *parv[], unsigned int flags,
+          struct Membership* member)
 {
   static int chan_flags[] = {
     MODE_CHANOP,       'o',
@@ -2472,8 +3299,12 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
     MODE_INVITEONLY,   'i',
     MODE_NOPRIVMSGS,   'n',
     MODE_KEY,          'k',
+    MODE_APASS,                'A',
+    MODE_UPASS,                'U',
     MODE_BAN,          'b',
     MODE_LIMIT,                'l',
+    MODE_REGONLY,      'r',
+    MODE_DELJOINS,      'D',
     MODE_ADD,          '+',
     MODE_DEL,          '-',
     0x0, 0x0
@@ -2494,6 +3325,7 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
   state.cptr = cptr;
   state.sptr = sptr;
   state.chptr = chptr;
+  state.member = member;
   state.parc = parc;
   state.parv = parv;
   state.flags = flags;
@@ -2544,6 +3376,16 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
        mode_parse_key(&state, flag_p);
        break;
 
+      case 'A': /* deal with Admin passes */
+        if (feature_bool(FEAT_OPLEVELS))
+       mode_parse_apass(&state, flag_p);
+       break;
+
+      case 'U': /* deal with user passes */
+        if (feature_bool(FEAT_OPLEVELS))
+       mode_parse_upass(&state, flag_p);
+       break;
+
       case 'b': /* deal with bans */
        mode_parse_ban(&state, flag_p);
        break;
@@ -2556,8 +3398,8 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
       default: /* deal with other modes */
        mode_parse_mode(&state, flag_p);
        break;
-      } /* switch (*modestr) */
-    } /* for (; *modestr; modestr++) */
+      } /* switch (*modestr) */
+    } /* for (; *modestr; modestr++) */
 
     if (state.flags & MODE_PARSE_BURST)
       break; /* don't interpret any more arguments */
@@ -2586,7 +3428,7 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
        break; /* break out of while loop */
       }
     }
-  } /* while (*modestr) */
+  } /* while (*modestr) */
 
   /*
    * the rest of the function finishes building resultant MODEs; if the
@@ -2623,6 +3465,12 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
                          state.chptr->mode.key, 0);
+    if (*state.chptr->mode.upass && !(state.done & DONE_UPASS))
+      modebuf_mode_string(state.mbuf, MODE_DEL | MODE_UPASS,
+                         state.chptr->mode.upass, 0);
+    if (*state.chptr->mode.apass && !(state.done & DONE_APASS))
+      modebuf_mode_string(state.mbuf, MODE_DEL | MODE_APASS,
+                         state.chptr->mode.apass, 0);
   }
 
   if (state.done & DONE_BANCLEAN) /* process bans */
@@ -2672,6 +3520,7 @@ void
 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
 {
   unsigned int len;
+  int is_local;
 
   assert(0 != jbuf);
 
@@ -2682,11 +3531,18 @@ joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
     return;
   }
 
+  is_local = IsLocalChannel(chan->chname);
+
   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
+    struct Membership *member = find_member_link(chan, jbuf->jb_source);
+    if (IsUserParting(member))
+      return;
+    SetUserParting(member);
+
     /* Send notification to channel */
-    if (!(flags & CHFL_ZOMBIE))
-      sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
+    if (!(flags & (CHFL_ZOMBIE | CHFL_DELAYED)))
+      sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_PART, chan, NULL, 0,
                                (flags & CHFL_BANNED || !jbuf->jb_comment) ?
                                ":%H" : "%H :%s", chan, jbuf->jb_comment);
     else if (MyUser(jbuf->jb_source))
@@ -2701,28 +3557,34 @@ joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
      * the original m_part.c */
 
     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
-       IsLocalChannel(chan->chname)) /* got to remove user here */
+       is_local) /* got to remove user here */
       remove_user_from_channel(jbuf->jb_source, chan);
   } else {
     /* Add user to channel */
-    add_user_to_channel(chan, jbuf->jb_source, flags);
+    if ((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))
+      add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, 0);
+    else
+      add_user_to_channel(chan, jbuf->jb_source, flags, 0);
 
     /* send notification to all servers */
-    if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !IsLocalChannel(chan->chname))
+    if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !is_local)
       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
                            "%H %Tu", chan, chan->creationtime);
 
-    /* Send the notification to the channel */
-    sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
+    if (!((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))) {
+      /* Send the notification to the channel */
+      sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, 0, "%H", chan);
 
-    /* send an op, too, if needed */
-    if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE &&
-       !IsModelessChannel(chan->chname))
-      sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
-                               chan, jbuf->jb_source);
+      /* send an op, too, if needed */
+      if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE)
+       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_MODE, chan, NULL, 0, "%H +o %C",
+                                        chan, jbuf->jb_source);
+    } else if (MyUser(jbuf->jb_source))
+      sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
   }
 
-  if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
+  if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
+      jbuf->jb_type == JOINBUF_TYPE_JOIN || is_local)
     return; /* don't send to remote */
 
   /* figure out if channel name will cause buffer to be overflowed */
@@ -2785,3 +3647,42 @@ joinbuf_flush(struct JoinBuf *jbuf)
 
   return 0;
 }
+
+/* Returns TRUE (1) if client is invited, FALSE (0) if not */
+int IsInvited(struct Client* cptr, const void* chptr)
+{
+  struct SLink *lp;
+
+  for (lp = (cli_user(cptr))->invited; lp; lp = lp->next)
+    if (lp->value.chptr == chptr)
+      return 1;
+  return 0;
+}
+
+/* RevealDelayedJoin: sends a join for a hidden user */
+
+void RevealDelayedJoin(struct Membership *member) {
+  ClearDelayedJoin(member);
+  sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, 0, ":%H",
+                                   member->channel);
+  CheckDelayedJoins(member->channel);
+}
+
+/* CheckDelayedJoins: checks and clear +d if necessary */
+
+void CheckDelayedJoins(struct Channel *chan) {
+  struct Membership *memb2;
+  
+  if (chan->mode.mode & MODE_WASDELJOINS) {
+    for (memb2=chan->members;memb2;memb2=memb2->next_member)
+      if (IsDelayedJoin(memb2))
+        break;
+    
+    if (!memb2) {
+      /* clear +d */
+      chan->mode.mode &= ~MODE_WASDELJOINS;
+      sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan, NULL, 0,
+                                       "%H -d", chan);
+    }
+  }
+}