Author: Isomer <isomer@coders.net>
[ircu2.10.12-pk.git] / ircd / channel.c
index 7fbf8e926d66cda8e4a109c360fff74fd01caba6..e1ab4aec5f4f89c6a1bd0d1623b36a0769498f3d 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)
@@ -193,10 +193,10 @@ static void sendmodeto_one(struct Client* cptr, const char* from,
                            const char* param, time_t creationtime)
 {
   if (IsServer(cptr) && DoesOp(mode) && creationtime)
-    sendto_one(cptr, ":%s MODE %s %s %s " TIME_T_FMT,
+    sendto_one(cptr, ":%s MODE %s %s %s " TIME_T_FMT, /* XXX DEAD */
                from, name, mode, param, creationtime);
   else
-    sendto_one(cptr, ":%s MODE %s %s %s", from, name, mode, param);
+    sendto_one(cptr, ":%s MODE %s %s %s", from, name, mode, param); /* XXX DEAD */
 }
 #endif /* 0 */
 
@@ -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;
@@ -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,8 +1294,7 @@ 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++];
@@ -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++;
@@ -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 */
@@ -2099,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
@@ -2109,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;
 }
 
@@ -2147,20 +2140,22 @@ int can_join(struct Client *sptr, struct Channel *chptr, char *key)
  */
 void clean_channelname(char *cn)
 {
-  for (; *cn; ++cn) {
-    if (!IsChannelChar(*cn)) {
-      *cn = '\0';
+  int i;
+
+  for (i = 0; cn[i]; i++) {
+    if (i >= CHANNELLEN || !IsChannelChar(cn[i])) {
+      cn[i] = '\0';
       return;
     }
-    if (IsChannelLower(*cn)) {
-      *cn = ToLower(*cn);
+    if (IsChannelLower(cn[i])) {
+      cn[i] = ToLower(cn[i]);
 #ifndef FIXME
       /*
        * Remove for .08+
        * toupper(0xd0)
        */
-      if ((unsigned char)(*cn) == 0xd0)
-        *cn = (char) 0xf0;
+      if ((unsigned char)(cn[i]) == 0xd0)
+        cn[i] = (char) 0xf0;
 #endif
     }
   }
@@ -2280,9 +2275,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;
       }
@@ -2291,7 +2285,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;
     }
   }
@@ -2302,7 +2296,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)
 {
@@ -2367,6 +2361,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;
@@ -2476,7 +2471,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;
   }
@@ -2511,6 +2506,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;
@@ -2544,7 +2540,7 @@ void send_user_joins(struct Client *cptr, struct Client *user)
       if (cnt)
       {
         buf[len - 1] = '\0';
-        sendto_one(cptr, "%s", buf);
+        sendto_one(cptr, "%s", buf); /* XXX Possibly DEAD */
       }
       *buf = ':';
       strcpy(buf + 1, user->name);
@@ -2562,7 +2558,7 @@ void send_user_joins(struct Client *cptr, struct Client *user)
     }
   }
   if (*buf && cnt)
-    sendto_one(cptr, "%s", buf);
+    sendto_one(cptr, "%s", buf); /* XXX Possibly DEAD */
 }
 
 /*
@@ -2574,7 +2570,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)
 {
@@ -2623,22 +2619,22 @@ void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
           ":%s NOTICE * :*** Notice -- %sHACK(%d): %s MODE %s %s%s ["
           TIME_T_FMT "]", me.name, (badop == 3) ? "BOUNCE or " : "", badop,
           parv[0], parv[1], parv[2], params, chptr->creationtime);
-      sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop ==
+      sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop == /* XXX DYING */
           4) ? SNO_HACK4 : SNO_HACK2);
 
       if ((IsServer(sptr)) && (badop == 2))
       {
         sprintf_irc(sendbuf, ":%s DESYNCH :HACK: %s MODE %s %s%s",
             me.name, parv[0], parv[1], parv[2], params);
-        sendbufto_serv_butone(cptr);
+        sendbufto_serv_butone(cptr); /* XXX DYING */
       }
       break;
     }
     case 2:                     /* No conversion is needed for CREATE; the only numnick is sptr */
     {
-      sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s",
+      sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s", /* XXX DYING */
           me.name, sptr->name, chptr->chname, parv[2]);
-      sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s",
+      sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s", /* XXX DYING */
           sptr->name, chptr->chname, parv[2]);
       break;
     }
@@ -2653,134 +2649,22 @@ void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
         sprintf_irc(sendbuf,
             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s <%s> :%s",
             me.name, sptr->name, parv[1], parv[2], parv[3]);
-      sendbufto_op_mask(SNO_HACK4);
+      sendbufto_op_mask(SNO_HACK4); /* XXX DYING */
       break;
     }
   }
 }
 
-/*
- * 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(mbuf);
-}
-
-/*
- * 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)
-{
-  assert(0 != mbuf);
-  assert(0 != (mode & (MODE_ADD | MODE_DEL)));
-
-  MB_TYPE(mbuf, mbuf->mb_count) = mode;
-  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(mbuf);
-}
-
-/*
- * 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(mbuf);
-}
-
 /*
  * 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)
+build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
 {
-  strptr[(*strptr_i)++] = ' ';
+  if (c)
+    strptr[(*strptr_i)++] = c;
 
   while (*str1)
     strptr[(*strptr_i)++] = *(str1++);
@@ -2796,8 +2680,8 @@ build_string(char *strptr, int *strptr_i, char *str1, char *str2)
  * This is the workhorse of our ModeBuf suite; this actually generates the
  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
  */
-int
-modebuf_flush(struct ModeBuf *mbuf)
+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[] = {
@@ -2826,14 +2710,17 @@ modebuf_flush(struct ModeBuf *mbuf)
   char *bufptr; /* we make use of indirection to simplify the code */
   int *bufptr_i;
 
-  char addstr[MODEBUFLEN]; /* accumulates MODE parameters to add */
+  char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
   int addstr_i;
-  char remstr[MODEBUFLEN]; /* accumulates MODE parameters to remove */
+  char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
   int remstr_i;
   char *strptr; /* more indirection to simplify the code */
   int *strptr_i;
 
-  char limitbuf[10]; /* convert limits to strings */
+  int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
+  int tmp;
+
+  char limitbuf[20]; /* convert limits to strings */
 
   unsigned int limitdel = MODE_LIMIT;
 
@@ -2849,6 +2736,13 @@ modebuf_flush(struct ModeBuf *mbuf)
   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)
@@ -2867,19 +2761,36 @@ modebuf_flush(struct ModeBuf *mbuf)
       bufptr_i = &rembuf_i;
     }
 
-    if (MB_TYPE(mbuf, i) & MODE_CHANOP)
-      bufptr[(*bufptr_i)++] = 'o';
-    else if (MB_TYPE(mbuf, i) & MODE_VOICE)
-      bufptr[(*bufptr_i)++] = 'v';
-    else if (MB_TYPE(mbuf, i) & MODE_KEY)
-      bufptr[(*bufptr_i)++] = 'k';
-    else if (MB_TYPE(mbuf, i) & MODE_BAN)
-      bufptr[(*bufptr_i)++] = 'b';
-    else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
-      bufptr[(*bufptr_i)++] = 'l';
+    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;
+      }
     }
   }
 
@@ -2889,7 +2800,8 @@ modebuf_flush(struct ModeBuf *mbuf)
 
   /* 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_HACK3   | MODEBUF_DEST_HACK4 |
+                      MODEBUF_DEST_LOG)) {
     /* Set up the parameter strings */
     addstr[0] = '\0';
     addstr_i = 0;
@@ -2897,6 +2809,9 @@ modebuf_flush(struct ModeBuf *mbuf)
     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;
@@ -2907,11 +2822,11 @@ modebuf_flush(struct ModeBuf *mbuf)
 
       /* deal with clients... */
       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
-       build_string(strptr, strptr_i, MB_CLIENT(mbuf, i)->name, 0);
+       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);
+       build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
 
       /*
        * deal with limit; note we cannot include the limit parameter if we're
@@ -2919,42 +2834,51 @@ modebuf_flush(struct ModeBuf *mbuf)
        */
       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
               (MODE_ADD | MODE_LIMIT))
-       build_string(strptr, strptr_i, limitbuf, 0);
+       build_string(strptr, strptr_i, limitbuf, 0, ' ');
     }
 
     /* send the messages off to their destination */
     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
-      sendto_op_mask(SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s [" TIME_T_FMT
-                    "]", app_source->name, mbuf->mb_channel->chname,
-                    addbuf_i ? "+" : "", addbuf, rembuf_i ? "-" : "", rembuf,
-                    addstr, remstr, mbuf->mb_channel->creationtime);
-      sendto_serv_butone(mbuf->mb_connect, "%s " TOK_DESYNCH
-                        " :HACK: %s MODE %s %s%s%s%s%s%s [" TIME_T_FMT "]",
-                        NumServ(&me), app_source->name,
-                        mbuf->mb_channel->chname, addbuf_i ? "+" : "", addbuf,
-                        rembuf_i ? "-" : "", rembuf, addstr, remstr,
-                        mbuf->mb_channel->creationtime);
+      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_op_mask(SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s %s%s%s%s%s%s ["
-                    TIME_T_FMT "]", app_source->name,
-                    mbuf->mb_channel->chname, addbuf_i ? "+" : "", addbuf,
-                    rembuf_i ? "-" : "", rembuf, addstr, remstr,
-                    mbuf->mb_channel->creationtime);
+      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_op_mask(SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s [" TIME_T_FMT
-                    "]", app_source->name, mbuf->mb_channel->chname,
-                    addbuf_i ? "+" : "", addbuf, rembuf_i ? "-" : "", rembuf,
-                    addstr, remstr, mbuf->mb_channel->creationtime);
+      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)
-      sendto_channel_butserv(mbuf->mb_channel, app_source,
-                            ":%s MODE %s %s%s%s%s%s%s", app_source->name,
-                            mbuf->mb_channel->chname, addbuf_i ? "+" : "",
-                            addbuf, rembuf_i ? "-" : "", rembuf, addstr,
-                            remstr);
+      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? */
@@ -2972,6 +2896,9 @@ modebuf_flush(struct ModeBuf *mbuf)
     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;
@@ -2982,11 +2909,11 @@ modebuf_flush(struct ModeBuf *mbuf)
 
       /* 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)));
+       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);
+       build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
 
       /*
        * deal with the limit.  Logic here is complicated; if HACK2 is set,
@@ -2994,14 +2921,14 @@ modebuf_flush(struct ModeBuf *mbuf)
        * 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);
+       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 */
+      build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
 
       /* mark that we've done this, so we don't do it again */
       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
@@ -3009,50 +2936,37 @@ modebuf_flush(struct ModeBuf *mbuf)
 
     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
-      if (IsServer(mbuf->mb_source))
-       sendto_serv_butone(mbuf->mb_connect, "%s " TOK_OPMODE
-                          " %s %s%s%s%s%s%s", NumServ(mbuf->mb_source),
-                          mbuf->mb_channel->chname, addbuf_i ? "+" : "",
-                          addbuf, rembuf_i ? "-" : "", rembuf, addstr,
-                          remstr);
-      else
-       sendto_serv_butone(mbuf->mb_connect, "%s%s " TOK_OPMODE
-                          " %s %s%s%s%s%s%s", NumNick(mbuf->mb_source),
-                          mbuf->mb_channel->chname, addbuf_i ? "+" : "",
-                          addbuf, rembuf_i ? "-" : "", rembuf, addstr,
-                          remstr);
+      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
        */
-      sendto_one(mbuf->mb_connect, "%s " TOK_MODE " %s %s%s%s%s%s%s "
-                TIME_T_FMT, NumServ(&me), mbuf->mb_channel->chname,
-                rembuf_i ? "+" : "", rembuf, addbuf_i ? "-" : "", addbuf,
-                remstr, addstr, 0);
+      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))
-       sendto_serv_butone(mbuf->mb_connect, "%s " TOK_MODE " %s %s%s%s%s%s%s "
-                          TIME_T_FMT, NumServ(mbuf->mb_source),
-                          mbuf->mb_channel->chname, addbuf_i ? "+" : "",
-                          addbuf, rembuf_i ? "-" : "", rembuf, addstr,
-                          remstr, (mbuf->mb_dest & (MODEBUF_DEST_HACK3 |
-                                                    MODEBUF_DEST_HACK4)) ? 0 :
-                          mbuf->mb_channel->creationtime);
+       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
-       sendto_serv_butone(mbuf->mb_connect, "%s%s " TOK_MODE
-                          " %s %s%s%s%s%s%s " TIME_T_FMT,
-                          NumNick(mbuf->mb_source), mbuf->mb_channel->chname,
-                          addbuf_i ? "+" : "", addbuf, rembuf_i ? "-" : "",
-                          rembuf, addstr, remstr,
-                          (mbuf->mb_dest & (MODEBUF_DEST_HACK3 |
-                                            MODEBUF_DEST_HACK4)) ? 0 :
-                          mbuf->mb_channel->creationtime);
+       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);
     }
   }
 
@@ -3063,10 +2977,1016 @@ modebuf_flush(struct ModeBuf *mbuf)
 
   /* 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 */
+}
+
+/*
+ * Initialize a join buffer
+ */
+void
+joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
+            struct Client *connect, unsigned int type, char *comment,
+            time_t create)
+{
+  int i;
+
+  assert(0 != jbuf);
+  assert(0 != source);
+  assert(0 != connect);
+
+  jbuf->jb_source = source; /* just initialize struct JoinBuf */
+  jbuf->jb_connect = connect;
+  jbuf->jb_type = type;
+  jbuf->jb_comment = comment;
+  jbuf->jb_create = create;
+  jbuf->jb_count = 0;
+  jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
+                      type == JOINBUF_TYPE_PART ||
+                      type == JOINBUF_TYPE_PARTALL) ?
+                     STARTJOINLEN : STARTCREATELEN) +
+                    (comment ? strlen(comment) + 2 : 0));
+
+  for (i = 0; i < MAXJOINARGS; i++)
+    jbuf->jb_channels[i] = 0;
+}
+
+/*
+ * Add a channel to the join buffer
+ */
+void
+joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
+{
+  unsigned int len;
+
+  assert(0 != jbuf);
+
+  if (chan) {
+    if (jbuf->jb_type == JOINBUF_TYPE_PART ||
+       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
+      /* Send notification to channel */
+      if (!(flags & CHFL_ZOMBIE))
+       sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
+                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
+                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
+      else if (MyUser(jbuf->jb_source))
+       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
+                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
+                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
+       /* XXX: Shouldn't we send a PART here anyway? */
+
+    } else {
+      /* Add user to channel */
+      add_user_to_channel(chan, jbuf->jb_source, flags);
+
+      /* Send the notification to the channel */
+      sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
+
+      /* send an op, too, if needed */
+      if (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);
+    }
+
+    if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
+      return; /* don't send to remote */
+  }
+
+  /* figure out if channel name will cause buffer to be overflowed */
+  len = chan ? strlen(chan->chname) + 1 : 2;
+  if (jbuf->jb_strlen + len > IRC_BUFSIZE)
+    joinbuf_flush(jbuf);
+
+  /* add channel to list of channels to send and update counts */
+  jbuf->jb_channels[jbuf->jb_count++] = chan;
+  jbuf->jb_strlen += len;
+
+  /* if we've used up all slots, flush */
+  if (jbuf->jb_count >= MAXJOINARGS)
+    joinbuf_flush(jbuf);
+}
+
+/*
+ * Flush the channel list to remote servers
+ */
+int
+joinbuf_flush(struct JoinBuf *jbuf)
+{
+  char chanlist[IRC_BUFSIZE];
+  int chanlist_i = 0;
+  int i;
+
+  if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL)
+    return 0; /* no joins to process */
+
+  for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
+    build_string(chanlist, &chanlist_i,
+                jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
+                i == 0 ? '\0' : ',');
+    if (JOINBUF_TYPE_PART == jbuf->jb_type)
+      /* Remove user from channel */
+      remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
+
+    jbuf->jb_channels[i] = 0; /* mark slot empty */
+  }
+
+  jbuf->jb_count = 0; /* reset base counters */
+  jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_JOIN ||
+                     jbuf->jb_type == JOINBUF_TYPE_PART ?
+                     STARTJOINLEN : STARTCREATELEN) +
+                    (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
+
+  /* and send the appropriate command */
+  switch (jbuf->jb_type) {
+  case JOINBUF_TYPE_JOIN:
+    sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
+                         "%s", chanlist);
+    break;
+
+  case JOINBUF_TYPE_CREATE:
+    sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
+                         "%s %Tu", chanlist, jbuf->jb_create);
+    break;
+
+  case JOINBUF_TYPE_PART:
+    sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
+                         jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
+                         jbuf->jb_comment);
+    break;
+  }
+
+  return 0;
+}