Author: Kev <klmitch@mit.edu>
[ircu2.10.12-pk.git] / ircd / channel.c
index 209158f2f92e46568eb65a086cbe6e97f5671429..9c5d22371a1fde0362ad4b79d21bc1e5d413c929 100644 (file)
@@ -21,7 +21,6 @@
  */
 #include "channel.h"
 #include "client.h"
-#include "gline.h"        /* bad_channel */
 #include "hash.h"
 #include "ircd.h"
 #include "ircd_alloc.h"
@@ -43,6 +42,7 @@
 #include "sprintf_irc.h"
 #include "struct.h"
 #include "support.h"
+#include "sys.h"
 #include "whowas.h"
 
 #include <assert.h>
@@ -107,7 +107,7 @@ struct Membership* find_member_link(struct Channel* chptr, const struct Client*
       assert(m->channel == chptr);
       if (m->user == cptr)
         return m;
-      m=m->next_member;
+      m = m->next_member;
     }
   }
   /* Users on the other hand aren't allowed on more than 15 channels.  50%
@@ -120,7 +120,7 @@ struct Membership* find_member_link(struct Channel* chptr, const struct Client*
      assert(m->user == cptr);
      if (m->channel == chptr)
        return m;
-     m=m->next_channel;
+     m = m->next_channel;
    }
   }
   return 0;
@@ -142,7 +142,7 @@ struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
     return who;
 
   if (!(who = get_history(user, KILLCHASETIMELIMIT))) {
-    sendto_one(sptr, err_str(ERR_NOSUCHNICK), me.name, sptr->name, user);
+    send_reply(sptr, ERR_NOSUCHNICK, user);
     return 0;
   }
   if (chasing)
@@ -361,8 +361,7 @@ int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
   }
   if (MyUser(cptr) && !removed_bans && (len > MAXBANLENGTH || (cnt >= MAXBANS)))
   {
-    sendto_one(cptr, err_str(ERR_BANLISTFULL), me.name, cptr->name,
-        chptr->chname, banid);
+    send_reply(cptr, ERR_BANLISTFULL, chptr->chname, banid);
     return -1;
   }
   if (change)
@@ -380,7 +379,7 @@ int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
     assert(0 != ban->value.ban.who);
     strcpy(ban->value.ban.who, cptr->name);
 
-    ban->value.ban.when = CurrentTime;
+    ban->value.ban.when = TStime();
     ban->flags = CHFL_BAN;      /* This bit is never used I think... */
     if ((ip_start = strrchr(banid, '@')) && check_if_ipmask(ip_start + 1))
       ban->flags |= CHFL_BAN_IPMASK;
@@ -798,7 +797,7 @@ static int send_mode_list(struct Client *cptr, char *chname,
       name = lp->value.ban.banstr;
     else
       name = lp->value.cptr->name;
-    if (strlen(parabuf) + strlen(name) + 11 < (size_t)MODEBUFLEN)
+    if (strlen(parabuf) + strlen(name) + 11 < MODEBUFLEN)
     {
       strcat(parabuf, " ");
       strcat(parabuf, name);
@@ -1077,11 +1076,10 @@ static void send_ban_list(struct Client* cptr, struct Channel* chptr)
   assert(0 != chptr);
 
   for (lp = chptr->banlist; lp; lp = lp->next)
-    sendto_one(cptr, rpl_str(RPL_BANLIST), me.name, cptr->name,
-               chptr->chname, lp->value.ban.banstr, lp->value.ban.who,
-               lp->value.ban.when);
-  sendto_one(cptr, rpl_str(RPL_ENDOFBANLIST), me.name, cptr->name,
-             chptr->chname);
+    send_reply(cptr, RPL_BANLIST, chptr->chname, lp->value.ban.banstr,
+              lp->value.ban.who, lp->value.ban.when);
+
+  send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
 }
 
 /*
@@ -1222,8 +1220,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
         if (!(member_x = find_member_link(chptr, who)) ||
             (MyUser(sptr) && IsZombie(member_x)))
         {
-          sendto_one(cptr, err_str(ERR_USERNOTINCHANNEL),
-              me.name, cptr->name, who->name, chptr->chname);
+         send_reply(cptr, ERR_USERNOTINCHANNEL, who->name, chptr->chname);
           break;
         }
         /*
@@ -1234,8 +1231,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
            * XXX - CHECKME
            */
           if (MyUser(cptr)) {
-            sendto_one(cptr, err_str(ERR_ISCHANSERVICE), me.name,
-                       cptr->name, parv[0], chptr->chname);
+           send_reply(cptr, ERR_ISCHANSERVICE, parv[0], chptr->chname);
             break;
            }
            else {
@@ -1251,8 +1247,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
         if (whatt == MODE_DEL && IsOperOnLocalChannel(who, chptr->chname) &&
             (who != sptr) && MyUser(cptr) && *curr == 'o')
         {
-          sendto_one(cptr, err_str(ERR_ISOPERLCHAN), me.name,
-                     cptr->name, parv[0], chptr->chname);
+         send_reply(cptr, ERR_ISOPERLCHAN, parv[0], chptr->chname);
           break;
         }
 #endif
@@ -1299,13 +1294,12 @@ int set_mode(struct Client* cptr, struct Client* sptr,
         if (whatt == MODE_ADD)
         {
           if (*mode->key && !IsServer(cptr))
-            sendto_one(cptr, err_str(ERR_KEYSET),
-                me.name, cptr->name, chptr->chname);
+           send_reply(cptr, ERR_KEYSET, chptr->chname);
           else if (!*mode->key || IsServer(cptr))
           {
             lp = &chops[opcnt++];
             lp->value.cp = *parv;
-            if (strlen(lp->value.cp) > (size_t)KEYLEN)
+            if (strlen(lp->value.cp) > KEYLEN)
               lp->value.cp[KEYLEN] = '\0';
             lp->flags = MODE_KEY | MODE_ADD;
             keychange = 1;
@@ -1413,8 +1407,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
             newmode &= ~*ip;
         }
         else if (!IsServer(cptr))
-          sendto_one(cptr, err_str(ERR_UNKNOWNMODE),
-              me.name, cptr->name, *curr);
+         send_reply(cptr, ERR_UNKNOWNMODE, *curr);
         break;
     }
     curr++;
@@ -1666,14 +1659,14 @@ int set_mode(struct Client* cptr, struct Client* sptr,
       }
 
       /* What could be added: cp+' '+' '+<TS>+'\0' */
-      if (len + strlen(cp) + 13 > (size_t)MODEBUFLEN ||
-          nlen + strlen(cp) + NUMNICKLEN + 12 > (size_t)MODEBUFLEN)
+      if (len + strlen(cp) + 13 > MODEBUFLEN ||
+          nlen + strlen(cp) + NUMNICKLEN + 12 > MODEBUFLEN)
         break;
 
       switch (lp->flags & MODE_WPARAS)
       {
         case MODE_KEY:
-          if (strlen(cp) > (size_t)KEYLEN)
+          if (strlen(cp) > KEYLEN)
             *(cp + KEYLEN) = '\0';
           if ((whatt == MODE_ADD && (*mode->key == '\0' ||
                0 != ircd_strcmp(mode->key, cp))) ||
@@ -1957,9 +1950,8 @@ int set_mode(struct Client* cptr, struct Client* sptr,
   /* Bounce here */
   if (!hacknotice && *bmodebuf && chptr->creationtime)
   {
-    sendto_one(cptr, "%s " TOK_MODE " %s %s %s " TIME_T_FMT,
-               NumServ(&me), chptr->chname, bmodebuf, nbparambuf,
-               *badop == 2 ? (time_t) 0 : chptr->creationtime);
+    sendcmdto_one(&me, CMD_MODE, cptr, "%H %s %s %Tu", chptr, bmodebuf,
+                 nbparambuf, *badop == 2 ? (time_t) 0 : chptr->creationtime);
   }
   /* If there are possibly bans to re-add, bounce them now */
   if (add_banid_called && bounce)
@@ -1971,6 +1963,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
     {
       len[0] = strlen(ban[0]->value.ban.banstr);
       cnt = 1;                  /* We already got one ban :) */
+      /* XXX sendbuf used to send ban bounces! */
       sblen = sprintf_irc(sendbuf, ":%s MODE %s +b",
           me.name, chptr->chname) - sendbuf;
       total_len = sblen + 1 + len[0];   /* 1 = ' ' */
@@ -2008,6 +2001,7 @@ int set_mode(struct Client* cptr, struct Client* sptr,
     struct Membership* member_z;
     struct Client *acptr;
     if (IsServer(sptr))
+      /* XXX sendbuf used to send ban bounces! */
       psblen = sprintf_irc(sendbuf, ":%s MODE %s -b",
           sptr->name, chptr->chname) - sendbuf;
     else                        /* We rely on IsRegistered(sptr) being true for MODE */
@@ -2044,9 +2038,11 @@ int set_mode(struct Client* cptr, struct Client* sptr,
         MyFree(banstr[cnt]);
         sblen += len[cnt];
       }
-      for (member_z = chptr->members; member_z; member_z = member_z->next_member)
-        if (MyConnect(acptr = member_z->user) && !IsZombie(member_z))
+      for (member_z = chptr->members; member_z; member_z = member_z->next_member) {
+        acptr = member_z->user;
+        if (MyConnect(acptr) && !IsZombie(member_z))
           sendbufto_one(acptr);
+      }
       if (delayed)
       {
         banstr[0] = banstr[delayed - 1];
@@ -2097,7 +2093,17 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
 {
   struct SLink *lp;
   int overrideJoin = 0;  
+  
+  /*
+   * Now a banned user CAN join if invited -- Nemesi
+   * Now a user CAN escape channel limit if invited -- bfriendly
+   * Now a user CAN escape anything if invited -- Isomer
+   */
 
+  for (lp = sptr->user->invited; lp; lp = lp->next)
+    if (lp->value.chptr == chptr)
+      return 0;
+  
 #ifdef OPER_WALK_THROUGH_LMODES
   /* 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
@@ -2107,36 +2113,25 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
     overrideJoin = MAGIC_OPER_OVERRIDE;
   }
 #endif
-  /*
-   * Now a banned user CAN join if invited -- Nemesi
-   * Now a user CAN escape channel limit if invited -- bfriendly
-   */
-  if ((chptr->mode.mode & MODE_INVITEONLY) || (is_banned(sptr, chptr, NULL)
-      || (chptr->mode.limit && chptr->users >= chptr->mode.limit)))
-  {
-    for (lp = sptr->user->invited; lp; lp = lp->next)
-      if (lp->value.chptr == chptr)
-        break;
-    if (!lp)
-    {
-      if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
-        return (overrideJoin + ERR_CHANNELISFULL);
-      /*
-       * This can return an "Invite only" msg instead of the "You are banned"
-       * if _both_ conditions are true, but who can say what is more
-       * appropriate ? checking again IsBanned would be _SO_ cpu-xpensive !
-       */
-      return overrideJoin + ((chptr->mode.mode & MODE_INVITEONLY) ?
-          ERR_INVITEONLYCHAN : ERR_BANNEDFROMCHAN);
-    }
-  }
 
+  if (chptr->mode.mode & MODE_INVITEONLY)
+       return overrideJoin + ERR_INVITEONLYCHAN;
+       
+  if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
+       return overrideJoin + ERR_CHANNELISFULL;
+       
+  if (is_banned(sptr, chptr, NULL))
+       return overrideJoin + ERR_BANNEDFROMCHAN;
+  
   /*
    * now using compall (above) to test against a whole key ring -Kev
    */
   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
-    return overrideJoin + (ERR_BADCHANNELKEY);
+    return overrideJoin + ERR_BADCHANNELKEY;
 
+  if (overrideJoin)    
+       return ERR_DONTCHEAT;
+       
   return 0;
 }
 
@@ -2278,9 +2273,8 @@ void list_next_channels(struct Client *cptr, int nr)
           chptr->topic_time < args->max_topic_time)))
       {
         if (ShowChannel(cptr,chptr))
-          sendto_one(cptr, rpl_str(RPL_LIST), me.name, cptr->name,
-            chptr->chname,
-            chptr->users, chptr->topic);
+         send_reply(cptr, RPL_LIST, chptr->chname, chptr->users,
+                    chptr->topic);
         chptr = chptr->next;
         break;
       }
@@ -2289,7 +2283,7 @@ void list_next_channels(struct Client *cptr, int nr)
     {
       MyFree(cptr->listing);
       cptr->listing = NULL;
-      sendto_one(cptr, rpl_str(RPL_LISTEND), me.name, cptr->name);
+      send_reply(cptr, RPL_LISTEND);
       break;
     }
   }
@@ -2300,7 +2294,7 @@ void list_next_channels(struct Client *cptr, int nr)
   }
 }
 
-
+/* XXX AIEEEE! sendbuf is an institution here :( */
 void add_token_to_sendbuf(char *token, size_t *sblenp, int *firstp,
     int *send_itp, char is_a_ban, int mode)
 {
@@ -2365,6 +2359,7 @@ void cancel_mode(struct Client *sptr, struct Channel *chptr, char m,
   
   if (*count == -1)             /* initialize ? */
   {
+    /* XXX sendbuf used! */
     sbp = sbpi =
         sprintf_irc(sendbuf, ":%s MODE %s -", sptr->name, chptr->chname);
     pb = parabuf;
@@ -2474,7 +2469,7 @@ void make_zombie(struct Membership* member, struct Client* who, struct Client* c
   if (MyUser(who))      /* server 4 */
   {
     if (IsServer(cptr)) /* Case b) ? */
-      sendto_one(cptr, PartFmt1, who->name, chptr->chname);
+      sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
     remove_user_from_channel(who, chptr);
     return;
   }
@@ -2509,6 +2504,7 @@ int number_of_zombies(struct Channel *chptr)
   return count;
 }
 
+/* XXX we can probably get rid of send_user_joins */
 void send_user_joins(struct Client *cptr, struct Client *user)
 {
   struct Membership* chan;
@@ -2572,7 +2568,7 @@ void send_user_joins(struct Client *cptr, struct Client *user)
  * This function prepares sendbuf with the server notices and wallops
  *   to be sent for all hacks.  -Ghostwolf 18-May-97
  */
-
+/* XXX let's get rid of this if we can */
 void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
                       char *parv[], int badop, int mtype)
 {
@@ -2656,3 +2652,1200 @@ void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
     }
   }
 }
+
+/*
+ * 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)
+ */
+static void
+build_string(char *strptr, int *strptr_i, char *str1, char *str2)
+{
+  strptr[(*strptr_i)++] = ' ';
+
+  while (*str1)
+    strptr[(*strptr_i)++] = *(str1++);
+
+  if (str2)
+    while (*str2)
+      strptr[(*strptr_i)++] = *(str2++);
+
+  strptr[(*strptr_i)] = '\0';
+}
+
+/*
+ * This is the workhorse of our ModeBuf suite; this actually generates the
+ * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
+ */
+static int
+modebuf_flush_int(struct ModeBuf *mbuf, int all)
+{
+  /* we only need the flags that don't take args right now */
+  static int flags[] = {
+/*  MODE_CHANOP,       'o', */
+/*  MODE_VOICE,                'v', */
+    MODE_PRIVATE,      'p',
+    MODE_SECRET,       's',
+    MODE_MODERATED,    'm',
+    MODE_TOPICLIMIT,   't',
+    MODE_INVITEONLY,   'i',
+    MODE_NOPRIVMSGS,   'n',
+/*  MODE_KEY,          'k', */
+/*  MODE_BAN,          'b', */
+/*  MODE_LIMIT,                'l', */
+    0x0, 0x0
+  };
+  int i;
+  int *flag_p;
+
+  struct Client *app_source; /* where the MODE appears to come from */
+
+  char addbuf[20]; /* accumulates +psmtin, etc. */
+  int addbuf_i = 0;
+  char rembuf[20]; /* accumulates -psmtin, etc. */
+  int rembuf_i = 0;
+  char *bufptr; /* we make use of indirection to simplify the code */
+  int *bufptr_i;
+
+  char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
+  int addstr_i;
+  char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
+  int remstr_i;
+  char *strptr; /* more indirection to simplify the code */
+  int *strptr_i;
+
+  int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
+  int tmp;
+
+  char limitbuf[20]; /* convert limits to strings */
+
+  unsigned int limitdel = MODE_LIMIT;
+
+  assert(0 != mbuf);
+
+  /* If the ModeBuf is empty, we have nothing to do */
+  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 = mbuf->mb_source->user->server;
+  else
+    app_source = mbuf->mb_source;
+
+  /*
+   * Account for user we're bouncing; we have to get it in on the first
+   * bounced MODE, or we could have problems
+   */
+  if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
+    totalbuflen -= 6; /* numeric nick == 5, plus one space */
+
+  /* Calculate the simple flags */
+  for (flag_p = flags; flag_p[0]; flag_p += 2) {
+    if (*flag_p & mbuf->mb_add)
+      addbuf[addbuf_i++] = flag_p[1];
+    else if (*flag_p & mbuf->mb_rem)
+      rembuf[rembuf_i++] = flag_p[1];
+  }
+
+  /* Now go through the modes with arguments... */
+  for (i = 0; i < mbuf->mb_count; i++) {
+    if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
+      bufptr = addbuf;
+      bufptr_i = &addbuf_i;
+    } else {
+      bufptr = rembuf;
+      bufptr_i = &rembuf_i;
+    }
+
+    if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
+      tmp = strlen(MB_CLIENT(mbuf, i)->name);
+
+      if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
+       MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
+      else {
+       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)) {
+      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';
+       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));
+
+      tmp = strlen(limitbuf);
+
+      if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
+       MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
+      else {
+       bufptr[(*bufptr_i)++] = 'l';
+       totalbuflen -= tmp + 1;
+      }
+    }
+  }
+
+  /* terminate the mode strings */
+  addbuf[addbuf_i] = '\0';
+  rembuf[rembuf_i] = '\0';
+
+  /* If we're building a user visible MODE or HACK... */
+  if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
+                      MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
+                      MODEBUF_DEST_LOG)) {
+    /* Set up the parameter strings */
+    addstr[0] = '\0';
+    addstr_i = 0;
+    remstr[0] = '\0';
+    remstr_i = 0;
+
+    for (i = 0; i < mbuf->mb_count; i++) {
+      if (MB_TYPE(mbuf, i) & MODE_SAVE)
+       continue;
+
+      if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
+       strptr = addstr;
+       strptr_i = &addstr_i;
+      } else {
+       strptr = remstr;
+       strptr_i = &remstr_i;
+      }
+
+      /* deal with clients... */
+      if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
+       build_string(strptr, strptr_i, MB_CLIENT(mbuf, i)->name, 0);
+
+      /* deal with strings... */
+      else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
+       build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0);
+
+      /*
+       * deal with limit; note we cannot include the limit parameter if we're
+       * removing it
+       */
+      else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
+              (MODE_ADD | MODE_LIMIT))
+       build_string(strptr, strptr_i, limitbuf, 0);
+    }
+
+    /* send the messages off to their destination */
+    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]", app_source->name, 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]",
+                           app_source->name, 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]", app_source->name,
+                          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]", app_source->name, mbuf->mb_channel->chname,
+                          rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
+                          addbuf, remstr, addstr,
+                          mbuf->mb_channel->creationtime);
+
+#ifdef OPATH
+    if (mbuf->mb_dest & MODEBUF_DEST_LOG) {
+      write_log(OPATH, "%Tu %#C OPMODE %H %s%s%s%s%s%s\n", TStime(),
+               mbuf->mb_source, mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
+               addbuf_i ? "+" : "", addbuf, remstr, addstr);
+    }
+#endif
+
+    if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
+      sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
+                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
+                               rembuf_i ? "-" : "", rembuf,
+                               addbuf_i ? "+" : "", addbuf, remstr, addstr);
+  }
+
+  /* Now are we supposed to propagate to other servers? */
+  if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
+    /* set up parameter string */
+    addstr[0] = '\0';
+    addstr_i = 0;
+    remstr[0] = '\0';
+    remstr_i = 0;
+
+    /*
+     * limit is supressed if we're removing it; we have to figure out which
+     * direction is the direction for it to be removed, though...
+     */
+    limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
+
+    for (i = 0; i < mbuf->mb_count; i++) {
+      if (MB_TYPE(mbuf, i) & MODE_SAVE)
+       continue;
+
+      if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
+       strptr = addstr;
+       strptr_i = &addstr_i;
+      } else {
+       strptr = remstr;
+       strptr_i = &remstr_i;
+      }
+
+      /* deal with modes that take clients */
+      if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
+       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))
+       build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0);
+
+      /*
+       * deal with the limit.  Logic here is complicated; if HACK2 is set,
+       * we're bouncing the mode, so sense is reversed, and we have to
+       * include the original limit if it looks like it's being removed
+       */
+      else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
+       build_string(strptr, strptr_i, limitbuf, 0);
+    }
+
+    /* we were told to deop the source */
+    if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
+      addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
+      addbuf[addbuf_i] = '\0'; /* terminate the string... */
+      build_string(addstr, &addstr_i, NumNick(mbuf->mb_source)); /* add user */
+
+      /* mark that we've done this, so we don't do it again */
+      mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
+    }
+
+    if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
+      /* If OPMODE was set, we're propagating the mode as an OPMODE message */
+      sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
+                           "%H %s%s%s%s%s%s", mbuf->mb_channel,
+                           rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
+                           addbuf, remstr, addstr);
+    } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
+      /*
+       * If HACK2 was set, we're bouncing; we send the MODE back to the
+       * connection we got it from with the senses reversed and a TS of 0;
+       * origin is us
+       */
+      sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
+                   mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
+                   rembuf_i ? "+" : "", rembuf, addstr, remstr,
+                   mbuf->mb_channel->creationtime);
+    } else {
+      /*
+       * We're propagating a normal MODE command to the rest of the network;
+       * we send the actual channel TS unless this is a HACK3 or a HACK4
+       */
+      if (IsServer(mbuf->mb_source))
+       sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
+                             "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
+                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
+                             addbuf, remstr, addstr,
+                             (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
+                             mbuf->mb_channel->creationtime);
+      else
+       sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
+                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
+                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
+                             addbuf, remstr, addstr);
+    }
+  }
+
+  /* We've drained the ModeBuf... */
+  mbuf->mb_add = 0;
+  mbuf->mb_rem = 0;
+  mbuf->mb_count = 0;
+
+  /* reinitialize the mode-with-arg slots */
+  for (i = 0; i < MAXMODEPARAMS; i++) {
+    /* If we saved any, pack them down */
+    if (MB_TYPE(mbuf, i) & MODE_SAVE) {
+      mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
+      MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
+
+      if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
+       continue;
+    } else if (MB_TYPE(mbuf, i) & MODE_FREE)
+      MyFree(MB_STRING(mbuf, i)); /* free string if needed */
+
+    MB_TYPE(mbuf, i) = 0;
+    MB_UINT(mbuf, i) = 0;
+  }
+
+  /* If we're supposed to flush it all, do so--all hail tail recursion */
+  if (all && mbuf->mb_count)
+    return modebuf_flush_int(mbuf, 1);
+
+  return 0;
+}
+
+/*
+ * This routine just initializes a ModeBuf structure with the information
+ * needed and the options given.
+ */
+void
+modebuf_init(struct ModeBuf *mbuf, struct Client *source,
+            struct Client *connect, struct Channel *chan, unsigned int dest)
+{
+  int i;
+
+  assert(0 != mbuf);
+  assert(0 != source);
+  assert(0 != chan);
+  assert(0 != dest);
+
+  mbuf->mb_add = 0;
+  mbuf->mb_rem = 0;
+  mbuf->mb_source = source;
+  mbuf->mb_connect = connect;
+  mbuf->mb_channel = chan;
+  mbuf->mb_dest = dest;
+  mbuf->mb_count = 0;
+
+  /* clear each mode-with-parameter slot */
+  for (i = 0; i < MAXMODEPARAMS; i++) {
+    MB_TYPE(mbuf, i) = 0;
+    MB_UINT(mbuf, i) = 0;
+  }
+}
+
+/*
+ * This routine simply adds modes to be added or deleted; do a binary OR
+ * with either MODE_ADD or MODE_DEL
+ */
+void
+modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
+{
+  assert(0 != mbuf);
+  assert(0 != (mode & (MODE_ADD | MODE_DEL)));
+
+  mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
+          MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
+
+  if (mode & MODE_ADD) {
+    mbuf->mb_rem &= ~mode;
+    mbuf->mb_add |= mode;
+  } else {
+    mbuf->mb_add &= ~mode;
+    mbuf->mb_rem |= mode;
+  }
+}
+
+/*
+ * 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
+ */
+void
+modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
+{
+  assert(0 != mbuf);
+  assert(0 != (mode & (MODE_ADD | MODE_DEL)));
+
+  MB_TYPE(mbuf, mbuf->mb_count) = mode;
+  MB_UINT(mbuf, mbuf->mb_count) = uint;
+
+  /* when we've reached the maximal count, flush the buffer */
+  if (++mbuf->mb_count >=
+      (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
+    modebuf_flush_int(mbuf, 0);
+}
+
+/*
+ * 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
+ */
+void
+modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
+                   int free)
+{
+  assert(0 != mbuf);
+  assert(0 != (mode & (MODE_ADD | MODE_DEL)));
+
+  MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
+  MB_STRING(mbuf, mbuf->mb_count) = string;
+
+  /* when we've reached the maximal count, flush the buffer */
+  if (++mbuf->mb_count >=
+      (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
+    modebuf_flush_int(mbuf, 0);
+}
+
+/*
+ * 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
+ */
+void
+modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
+                   struct Client *client)
+{
+  assert(0 != mbuf);
+  assert(0 != (mode & (MODE_ADD | MODE_DEL)));
+
+  MB_TYPE(mbuf, mbuf->mb_count) = mode;
+  MB_CLIENT(mbuf, mbuf->mb_count) = client;
+
+  /* when we've reached the maximal count, flush the buffer */
+  if (++mbuf->mb_count >=
+      (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
+    modebuf_flush_int(mbuf, 0);
+}
+
+/*
+ * This is the exported binding for modebuf_flush()
+ */
+int
+modebuf_flush(struct ModeBuf *mbuf)
+{
+  return modebuf_flush_int(mbuf, 1);
+}
+
+/*
+ * Simple function to invalidate bans
+ */
+void
+mode_ban_invalidate(struct Channel *chan)
+{
+  struct Membership *member;
+
+  for (member = chan->members; member; member = member->next_member)
+    ClearBanValid(member);
+}
+
+/*
+ * Simple function to drop invite structures
+ */
+void
+mode_invite_clear(struct Channel *chan)
+{
+  while (chan->invites)
+    del_invite(chan->invites->value.cptr, 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... */
+
+struct ParseState {
+  struct ModeBuf *mbuf;
+  struct Client *cptr;
+  struct Client *sptr;
+  struct Channel *chptr;
+  int parc;
+  char **parv;
+  unsigned int flags;
+  unsigned int dir;
+  unsigned int done;
+  int args_used;
+  int max_args;
+  int numbans;
+  struct SLink banlist[MAXPARA];
+  struct {
+    unsigned int flag;
+    struct Client *client;
+  } cli_change[MAXPARA];
+};
+
+/*
+ * Here's a helper function to deal with sending along "Not oper" or
+ * "Not member" messages
+ */
+static void
+send_notoper(struct ParseState *state)
+{
+  if (state->done & DONE_NOTOPER)
+    return;
+
+  send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
+            ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
+
+  state->done |= DONE_NOTOPER;
+}
+
+/*
+ * Helper function to convert limits
+ */
+static void
+mode_parse_limit(struct ParseState *state, int *flag_p)
+{
+  unsigned int t_limit;
+
+  if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
+    if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
+      return;
+
+    if (state->parc <= 0) { /* warn if not enough args */
+      if (MyUser(state->sptr))
+       need_more_params(state->sptr, "MODE +l");
+      return;
+    }
+
+    t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
+    state->parc--;
+    state->max_args--;
+
+    if (!t_limit) /* if it was zero, ignore it */
+      return;
+  } else
+    t_limit = state->chptr->mode.limit;
+
+  /* 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 (state->done & DONE_LIMIT) /* allow limit to be set only once */
+    return;
+  state->done |= DONE_LIMIT;
+
+  assert(0 != state->mbuf);
+
+  modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
+
+  if (state->flags & MODE_PARSE_SET) { /* set the limit */
+    if (state->dir & MODE_ADD) {
+      state->chptr->mode.mode |= flag_p[0];
+      state->chptr->mode.limit = t_limit;
+    } else {
+      state->chptr->mode.mode &= flag_p[0];
+      state->chptr->mode.limit = 0;
+    }
+  }
+}
+
+/*
+ * Helper function to convert keys
+ */
+static void
+mode_parse_key(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 +k" :
+                      "MODE -k");
+    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 (state->done & DONE_KEY) /* allow key to be set only once */
+    return;
+  state->done |= DONE_KEY;
+
+  t_len = KEYLEN + 1;
+
+  /* clean up the key 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 +k" :
+                      "MODE -k");
+    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) ||
+       (state->dir == MODE_DEL &&
+        ircd_strcmp(state->chptr->mode.key, t_str))) {
+      send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
+      return;
+    }
+
+  assert(0 != state->mbuf);
+
+  if (state->flags & MODE_PARSE_BOUNCE) {
+    if (*state->chptr->mode.key) /* reset old key */
+      modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
+                         state->chptr->mode.key, 0);
+    else /* remove new bogus key */
+      modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
+  } else /* send new key */
+    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 key */
+      ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
+    else /* remove the old key */
+      *state->chptr->mode.key = '\0';
+  }
+}
+
+/*
+ * Helper function to convert bans
+ */
+static void
+mode_parse_ban(struct ParseState *state, int *flag_p)
+{
+  char *t_str, *s;
+  struct SLink *ban, *newban = 0;
+
+  if (state->parc <= 0) { /* Not enough args, send ban list */
+    if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
+      send_ban_list(state->sptr, state->chptr);
+      state->done |= DONE_BANLIST;
+    }
+
+    return;
+  }
+
+  if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
+    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 ((s = strchr(t_str, ' ')))
+    *s = '\0';
+
+  if (!*t_str || *t_str == ':') { /* warn if empty */
+    if (MyUser(state->sptr))
+      need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
+                      "MODE -b");
+    return;
+  }
+
+  t_str = collapse(pretty_mask(t_str));
+
+  /* remember the ban for the moment... */
+  if (state->dir == MODE_ADD) {
+    newban = state->banlist + (state->numbans++);
+    newban->next = 0;
+
+    DupString(newban->value.ban.banstr, t_str);
+    newban->value.ban.who = state->sptr->name;
+    newban->value.ban.when = TStime();
+
+    newban->flags = CHFL_BAN | MODE_ADD;
+
+    if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
+      newban->flags |= CHFL_BAN_IPMASK;
+  }
+
+  if (!state->chptr->banlist) {
+    state->chptr->banlist = newban; /* add our ban with its flags */
+    state->done |= DONE_BANCLEAN;
+    return;
+  }
+
+  /* Go through all bans */
+  for (ban = state->chptr->banlist; ban; ban = ban->next) {
+    /* first, clean the ban flags up a bit */
+    if (!(state->done & DONE_BANCLEAN))
+      /* Note: We're overloading *lots* of bits here; be careful! */
+      ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
+
+    /* Bit meanings:
+     *
+     * MODE_ADD                   - Ban was added; if we're bouncing modes,
+     *                      then we'll remove it below; otherwise,
+     *                      we'll have to allocate a real ban
+     *
+     * MODE_DEL                   - Ban was marked for deletion; if we're
+     *                      bouncing modes, we'll have to re-add it,
+     *                      otherwise, we'll have to remove it
+     *
+     * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
+     *                      with a ban already set; if we're
+     *                      bouncing modes, we'll have to bounce
+     *                      this one; otherwise, we'll just ignore
+     *                      it when we process added bans
+     */
+
+    if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
+      ban->flags |= MODE_DEL; /* delete one ban */
+
+      if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
+       break;
+    } 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)) {
+       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) {
+       ban->next = newban; /* add our ban with its flags */
+       break; /* get out of loop */
+      }
+    }
+  }
+  state->done |= DONE_BANCLEAN;
+}
+
+/*
+ * This is the bottom half of the ban processor
+ */
+static void
+mode_process_bans(struct ParseState *state)
+{
+  struct SLink *ban, *newban, *prevban, *nextban;
+  int count = 0;
+  int len = 0;
+  int banlen;
+  int changed = 0;
+
+  for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
+    count++;
+    banlen = strlen(ban->value.ban.banstr);
+    len += banlen;
+    nextban = ban->next;
+
+    if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
+      if (prevban)
+       prevban->next = 0; /* Break the list; ban isn't a real ban */
+      else
+       state->chptr->banlist = 0;
+
+      count--;
+      len -= banlen;
+
+      MyFree(ban->value.ban.banstr);
+
+      continue;
+    } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
+      modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
+                         ban->value.ban.banstr,
+                         state->flags & MODE_PARSE_SET);
+
+      if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
+       if (prevban) /* clip it out of the list... */
+         prevban->next = ban->next;
+       else
+         state->chptr->banlist = ban->next;
+
+       count--;
+       len -= banlen;
+
+       MyFree(ban->value.ban.who);
+       free_link(ban);
+
+       changed++;
+       continue; /* next ban; keep prevban like it is */
+      } else
+       ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
+    } else if (ban->flags & MODE_ADD) { /* adding a ban? */
+      if (prevban)
+       prevban->next = 0; /* Break the list; ban isn't a real ban */
+      else
+       state->chptr->banlist = 0;
+
+      /* If we're supposed to ignore it, do so. */
+      if (ban->flags & CHFL_BAN_OVERLAPPED &&
+         !(state->flags & MODE_PARSE_BOUNCE)) {
+       count--;
+       len -= banlen;
+
+       MyFree(ban->value.ban.banstr);
+      } else {
+       if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
+           (len > MAXBANLENGTH || count >= MAXBANS)) {
+         send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
+                    ban->value.ban.banstr);
+         count--;
+         len -= banlen;
+
+         MyFree(ban->value.ban.banstr);
+       } else {
+         /* add the ban to the buffer */
+         modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
+                             ban->value.ban.banstr,
+                             !(state->flags & MODE_PARSE_SET));
+
+         if (state->flags & MODE_PARSE_SET) { /* create a new ban */
+           newban = make_link();
+           newban->value.ban.banstr = ban->value.ban.banstr;
+           DupString(newban->value.ban.who, ban->value.ban.who);
+           newban->value.ban.when = ban->value.ban.when;
+           newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
+
+           newban->next = state->chptr->banlist; /* and link it in */
+           state->chptr->banlist = newban;
+
+           changed++;
+         }
+       }
+      }
+    }
+
+    prevban = ban;
+  } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
+
+  if (changed) /* if we changed the ban list, we must invalidate the bans */
+    mode_ban_invalidate(state->chptr);
+}
+
+/*
+ * Helper function to process client changes
+ */
+static void
+mode_parse_client(struct ParseState *state, int *flag_p)
+{
+  char *t_str;
+  struct Client *acptr;
+  int i;
+
+  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 ?
+                      (flag_p[0] == MODE_CHANOP ? "MODE +o" : "MODE +v") :
+                      (flag_p[0] == MODE_CHANOP ? "MODE -o" : "MODE -v"));
+    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 (MyUser(state->sptr)) /* find client we're manipulating */
+    acptr = find_chasing(state->sptr, t_str, NULL);
+  else
+    acptr = findNUser(t_str);
+
+  if (!acptr)
+    return; /* find_chasing() already reported an error to the user */
+
+  for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
+    if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
+                                      state->cli_change[i].flag & flag_p[0]))
+      break; /* found a slot */
+
+  /* Store what we're doing to them */
+  state->cli_change[i].flag = state->dir | flag_p[0];
+  state->cli_change[i].client = acptr;
+}
+
+/*
+ * Helper function to process the changed client list
+ */
+static void
+mode_process_clients(struct ParseState *state)
+{
+  int i;
+  struct Membership *member;
+
+  for (i = 0; state->cli_change[i].flag; i++) {
+    assert(0 != state->cli_change[i].client);
+
+    /* look up member link */
+    if (!(member = find_member_link(state->chptr,
+                                   state->cli_change[i].client)) ||
+       (MyUser(state->sptr) && IsZombie(member))) {
+      if (MyUser(state->sptr))
+       send_reply(state->sptr, ERR_USERNOTINCHANNEL,
+                  state->cli_change[i].client->name, state->chptr->chname);
+      continue;
+    }
+
+    if ((state->cli_change[i].flag & MODE_ADD &&
+        (state->cli_change[i].flag & member->status)) ||
+       (state->cli_change[i].flag & MODE_DEL &&
+        !(state->cli_change[i].flag & member->status)))
+      continue; /* no change made, don't do anything */
+
+    /* see if the deop is allowed */
+    if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
+       (MODE_DEL | MODE_CHANOP)) {
+      /* prevent +k users from being deopped */
+      if (IsChannelService(state->cli_change[i].client)) {
+       if (state->flags & MODE_PARSE_FORCE) /* it was forced */
+         sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
+                              state->chptr,
+                              (IsServer(state->sptr) ? state->sptr->name :
+                               state->sptr->user->server->name));
+
+       else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
+         send_reply(state->sptr, ERR_ISCHANSERVICE,
+                    state->cli_change[i].client->name, state->chptr->chname);
+         continue;
+       }
+      }
+
+#ifdef NO_OPER_DEOP_LCHAN
+      /* don't allow local opers to be deopped on local channels */
+      if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
+         IsOperOnLocalChannel(state->cli_change[i].client,
+                              state->chptr->chname)) {
+       send_reply(state->sptr, ERR_ISOPERLCHAN,
+                  state->cli_change[i].client->name, state->chptr->chname);
+       continue;
+      }
+#endif
+    }
+
+    /* accumulate the change */
+    modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
+                       state->cli_change[i].client);
+
+    /* actually effect the change */
+    if (state->flags & MODE_PARSE_SET) {
+      if (state->cli_change[i].flag & MODE_ADD) {
+       member->status |= (state->cli_change[i].flag &
+                          (MODE_CHANOP | MODE_VOICE));
+       if (state->cli_change[i].flag & MODE_CHANOP)
+         ClearDeopped(member);
+      } else
+       member->status &= ~(state->cli_change[i].flag &
+                           (MODE_CHANOP | MODE_VOICE));
+    }
+  } /* for (i = 0; state->cli_change[i].flags; i++) { */
+}
+
+/*
+ * Helper function to process the simple modes
+ */
+static void
+mode_parse_mode(struct ParseState *state, int *flag_p)
+{
+  if ((state->dir == MODE_ADD &&  (flag_p[0] & state->chptr->mode.mode)) ||
+      (state->dir == MODE_DEL && !(flag_p[0] & state->chptr->mode.mode)))
+    return; /* no change */
+
+  /* If they're not an oper, they can't change modes */
+  if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
+    send_notoper(state);
+    return;
+  }
+
+  assert(0 != state->mbuf);
+
+  modebuf_mode(state->mbuf, state->dir | flag_p[0]);
+
+  /* make +p and +s mutually exclusive */
+  if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
+    if (flag_p[0] == MODE_SECRET && (state->chptr->mode.mode & MODE_PRIVATE))
+      modebuf_mode(state->mbuf, MODE_DEL | MODE_PRIVATE);
+    else if (flag_p[0] == MODE_PRIVATE &&
+            (state->chptr->mode.mode & MODE_SECRET))
+      modebuf_mode(state->mbuf, MODE_DEL | MODE_SECRET);
+  }
+
+  if (state->flags & MODE_PARSE_SET) { /* set the flags */
+    if (state->dir == MODE_ADD) { /* add the mode to the channel */
+      state->chptr->mode.mode |= flag_p[0];
+
+      /* make +p and +s mutually exclusive */
+      if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
+       if (flag_p[0] == MODE_PRIVATE)
+         state->chptr->mode.mode &= ~MODE_SECRET;
+       else
+         state->chptr->mode.mode &= ~MODE_PRIVATE;
+      }
+    } else /* remove the mode from the channel */
+      state->chptr->mode.mode &= ~flag_p[0];
+  }
+
+  /* Clear out invite structures if we're removing invites */
+  if (state->flags & MODE_PARSE_SET && state->dir == MODE_DEL &&
+      flag_p[0] == MODE_INVITEONLY)
+    mode_invite_clear(state->chptr);
+}
+
+/*
+ * This routine is intended to parse MODE or OPMODE commands and effect the
+ * changes (or just build the bounce buffer).  We pass the starting offset
+ * as a 
+ */
+int
+mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
+          struct Channel *chptr, int parc, char *parv[], unsigned int flags)
+{
+  static int chan_flags[] = {
+    MODE_CHANOP,       'o',
+    MODE_VOICE,                'v',
+    MODE_PRIVATE,      'p',
+    MODE_SECRET,       's',
+    MODE_MODERATED,    'm',
+    MODE_TOPICLIMIT,   't',
+    MODE_INVITEONLY,   'i',
+    MODE_NOPRIVMSGS,   'n',
+    MODE_KEY,          'k',
+    MODE_BAN,          'b',
+    MODE_LIMIT,                'l',
+    MODE_ADD,          '+',
+    MODE_DEL,          '-',
+    0x0, 0x0
+  };
+  int i;
+  int *flag_p;
+  char *modestr;
+  struct ParseState state;
+
+  assert(0 != cptr);
+  assert(0 != sptr);
+  assert(0 != chptr);
+  assert(0 != parc);
+  assert(0 != parv);
+
+  state.mbuf = mbuf;
+  state.cptr = cptr;
+  state.sptr = sptr;
+  state.chptr = chptr;
+  state.parc = parc;
+  state.parv = parv;
+  state.flags = flags;
+  state.dir = MODE_ADD;
+  state.done = 0;
+  state.args_used = 0;
+  state.max_args = MAXMODEPARAMS;
+  state.numbans = 0;
+
+  for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
+    state.banlist[i].next = 0;
+    state.banlist[i].value.ban.banstr = 0;
+    state.banlist[i].value.ban.who = 0;
+    state.banlist[i].value.ban.when = 0;
+    state.banlist[i].flags = 0;
+    state.cli_change[i].flag = 0;
+    state.cli_change[i].client = 0;
+  }
+
+  modestr = state.parv[state.args_used++];
+  state.parc--;
+
+  while (*modestr) {
+    for (; *modestr; modestr++) {
+      for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
+       if (flag_p[1] == *modestr)
+         break;
+
+      if (!flag_p[0]) { /* didn't find it?  complain and continue */
+       if (MyUser(state.sptr))
+         send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
+       continue;
+      }
+
+      switch (*modestr) {
+      case '+': /* switch direction to MODE_ADD */
+      case '-': /* switch direction to MODE_DEL */
+       state.dir = flag_p[0];
+       break;
+
+      case 'l': /* deal with limits */
+       mode_parse_limit(&state, flag_p);
+       break;
+
+      case 'k': /* deal with keys */
+       mode_parse_key(&state, flag_p);
+       break;
+
+      case 'b': /* deal with bans */
+       mode_parse_ban(&state, flag_p);
+       break;
+
+      case 'o': /* deal with ops/voice */
+      case 'v':
+       mode_parse_client(&state, flag_p);
+       break;
+
+      default: /* deal with other modes */
+       mode_parse_mode(&state, flag_p);
+       break;
+      } /* switch (*modestr) { */
+    } /* for (; *modestr; modestr++) { */
+
+    if (state.parc > 0) { /* process next argument in string */
+      modestr = state.parv[state.args_used++];
+      state.parc--;
+
+      /* is it a TS? */
+      if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
+       time_t recv_ts;
+
+       if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
+         break;                     /* we're then going to bounce the mode! */
+
+       recv_ts = atoi(modestr);
+
+       if (recv_ts && recv_ts < state.chptr->creationtime)
+         state.chptr->creationtime = recv_ts; /* respect earlier TS */
+
+       break; /* break out of while loop */
+      } else if (state.flags & MODE_PARSE_STRICT ||
+                (MyUser(state.sptr) && state.max_args <= 0)) {
+       state.parc++; /* we didn't actually gobble the argument */
+       state.args_used--;
+       break; /* break out of while loop */
+      }
+    }
+  } /* while (*modestr) { */
+
+  /*
+   * the rest of the function finishes building resultant MODEs; if the
+   * origin isn't a member or an oper, skip it.
+   */
+  if (state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
+    return state.args_used; /* tell our parent how many args we gobbled */
+
+  assert(0 != state.mbuf);
+
+  if (state.done & DONE_BANCLEAN) /* process bans */
+    mode_process_bans(&state);
+
+  /* process client changes */
+  if (state.cli_change[0].flag)
+    mode_process_clients(&state);
+
+  return state.args_used; /* tell our parent how many args we gobbled */
+}