Author: Michael Poole <mdpoole@troilus.org>
[ircu2.10.12-pk.git] / ircd / m_join.c
index 91d04d34489f06ed94fc68b669514c5eac5a8606..e0049667ca8a1eb691f603312e453ad0bb8688b6 100644 (file)
  * $Id$
  */
 
-/*
- * m_functions execute protocol messages on this server:
- *
- *    cptr    is always NON-NULL, pointing to a *LOCAL* client
- *            structure (with an open socket connected!). This
- *            identifies the physical socket where the message
- *            originated (or which caused the m_function to be
- *            executed--some m_functions may call others...).
- *
- *    sptr    is the source of the message, defined by the
- *            prefix part of the message if present. If not
- *            or prefix not found, then sptr==cptr.
- *
- *            (!IsServer(cptr)) => (cptr == sptr), because
- *            prefixes are taken *only* from servers...
- *
- *            (IsServer(cptr))
- *                    (sptr == cptr) => the message didn't
- *                    have the prefix.
- *
- *                    (sptr != cptr && IsServer(sptr) means
- *                    the prefix specified servername. (?)
- *
- *                    (sptr != cptr && !IsServer(sptr) means
- *                    that message originated from a remote
- *                    user (not local).
- *
- *            combining
- *
- *            (!IsServer(sptr)) means that, sptr can safely
- *            taken as defining the target structure of the
- *            message in this server.
- *
- *    *Always* true (if 'parse' and others are working correct):
- *
- *    1)      sptr->from == cptr  (note: cptr->from == cptr)
- *
- *    2)      MyConnect(sptr) <=> sptr == cptr (e.g. sptr
- *            *cannot* be a local connection, unless it's
- *            actually cptr!). [MyConnect(x) should probably
- *            be defined as (x == x->from) --msa ]
- *
- *    parc    number of variable parameter strings (if zero,
- *            parv is allowed to be NULL)
- *
- *    parv    a NULL terminated list of parameter pointers,
- *
- *                    parv[0], sender (prefix string), if not present
- *                            this points to an empty string.
- *                    parv[1]...parv[parc-1]
- *                            pointers to additional parameters
- *                    parv[parc] == NULL, *always*
- *
- *            note:   it is guaranteed that parv[0]..parv[parc-1] are all
- *                    non-NULL pointers.
- */
-#if 0
-/*
- * No need to include handlers.h here the signatures must match
- * and we don't need to force a rebuild of all the handlers everytime
- * we add a new one to the list. --Bleep
- */
-#include "handlers.h"
-#endif /* 0 */
+#include "config.h"
+
 #include "channel.h"
 #include "client.h"
 #include "gline.h"
 #include "hash.h"
 #include "ircd.h"
 #include "ircd_chattr.h"
+#include "ircd_features.h"
+#include "ircd_log.h"
 #include "ircd_reply.h"
 #include "ircd_string.h"
 #include "msg.h"
 #include "numeric.h"
 #include "numnicks.h"
+#include "s_debug.h"
 #include "s_user.h"
 #include "send.h"
+#include "sys.h"
 
-#include <assert.h>
+/* #include <assert.h> -- Now using assert in ircd_log.h */
 #include <stdlib.h>
 #include <string.h>
 
-#if !defined(XXX_BOGUS_TEMP_HACK)
-#include "handlers.h"      /* m_names */
-#endif
-
-/*
- * m_join - generic message handler
+/** Searches for and handles a 0 in a join list.
+ * @param[in] cptr Client that sent us the message.
+ * @param[in] sptr Original source of message.
+ * @param[in] chanlist List of channels to join.
+ * @return First token in \a chanlist after the final 0 entry, which
+ * may be its nul terminator (if the final entry is a 0 entry).
  */
-int m_join(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
+static char *
+last0(struct Client *cptr, struct Client *sptr, char *chanlist)
 {
-  static char     jbuf[BUFSIZE];
-  static char     mbuf[BUFSIZE];
-  struct Membership* member;
-  struct Channel* chptr;
-  char*           name;
-  char*           keysOrTS = NULL;
-  int             i = 0;
-  int             zombie = 0;
-  int             sendcreate = 0;
-  unsigned int    flags = 0;
-  size_t          jlen = 0;
-  size_t          mlen = 0;
-  size_t*         buflen;
-  char*           p = NULL;
-  char*           bufptr;
+  char *p;
+  int join0 = 0;
 
+  for (p = chanlist; p[0]; p++) /* find last "JOIN 0" */
+    if (p[0] == '0' && (p[1] == ',' || p[1] == '\0')) {
+      if (p[1] == ',')
+        p++;
+      chanlist = p + 1;
+      join0 = 1;
+    } else {
+      while (p[0] != ',' && p[0] != '\0') /* skip past channel name */
+       p++;
+
+      if (!p[0]) /* hit the end */
+       break;
+    }
+
+  if (join0) {
+    struct JoinBuf part;
+    struct Membership *member;
+
+    joinbuf_init(&part, sptr, cptr, JOINBUF_TYPE_PARTALL,
+                 "Left all channels", 0);
+
+    joinbuf_join(&part, 0, 0);
+
+    while ((member = cli_user(sptr)->channel))
+      joinbuf_join(&part, member->channel,
+                   IsZombie(member) ? CHFL_ZOMBIE :
+                   IsDelayedJoin(member) ? CHFL_DELAYED :
+                   0);
+
+    joinbuf_flush(&part);
+  }
+
+  return chanlist;
+}
+
+/** Handle a JOIN message from a client connection.
+ * See @ref m_functions for discussion of the arguments.
+ * @param[in] cptr Client that sent us the message.
+ * @param[in] sptr Original source of message.
+ * @param[in] parc Number of arguments.
+ * @param[in] parv Argument vector.
+ */
+int m_join(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
+{
+  struct Channel *chptr;
+  struct JoinBuf join;
+  struct JoinBuf create;
+  struct Gline *gline;
+  char *p = 0;
+  char *chanlist;
+  char *name;
+  char *keys;
 
   if (parc < 2 || *parv[1] == '\0')
     return need_more_params(sptr, "JOIN");
 
-  for (p = parv[1]; *p; p++)    /* find the last "JOIN 0" in the line -Kev */
-    if (*p == '0'
-        && (*(p + 1) == ',' || *(p + 1) == '\0' || !IsChannelChar(*(p + 1))))
+  joinbuf_init(&join, sptr, cptr, JOINBUF_TYPE_JOIN, 0, 0);
+  joinbuf_init(&create, sptr, cptr, JOINBUF_TYPE_CREATE, 0, TStime());
+
+  chanlist = last0(cptr, sptr, parv[1]); /* find last "JOIN 0" */
+
+  keys = parv[2]; /* remember where keys are */
+
+  for (name = ircd_strtok(&p, chanlist, ","); name;
+       name = ircd_strtok(&p, 0, ",")) {
+    char *key = 0;
+
+    /* If we have any more keys, take the first for this channel. */
+    if (!BadPtr(keys)
+        && (keys = strchr(key = keys, ',')))
+      *keys++ = '\0';
+
+    /* Empty keys are the same as no keys. */
+    if (key && !key[0])
+      key = 0;
+
+    if (!IsChannelName(name) || !strIsIrcCh(name))
     {
-      /* If it's a single "0", remember the place; we will start parsing
-         the channels after the last 0 in the line -Kev */
-      parv[1] = p;
-      if (!*(p + 1))
-        break;
-      p++;
+      /* bad channel name */
+      send_reply(sptr, ERR_NOSUCHCHANNEL, name);
+      continue;
     }
-    else
-    {                           /* Step through to the next comma or until the
-                                   end of the line, in an attempt to save CPU
-                                   -Kev */
-      while (*p != ',' && *p != '\0')
-        p++;
-      if (!*p)
-        break;
+
+    if (cli_user(sptr)->joined >= feature_int(FEAT_MAXCHANNELSPERUSER)
+       && !HasPriv(sptr, PRIV_CHAN_LIMIT)) {
+      send_reply(sptr, ERR_TOOMANYCHANNELS, name);
+      break; /* no point processing the other channels */
     }
 
-  keysOrTS = parv[2];           /* Remember where our keys are or the TS is;
-                                   parv[2] needs to be NULL for the call to
-                                   m_names below -Kev */
-  parv[2] = p = NULL;
-
-  *jbuf = *mbuf = '\0';         /* clear both join and mode buffers -Kev */
-  /*
-   *  Rebuild list of channels joined to be the actual result of the
-   *  JOIN.  Note that "JOIN 0" is the destructive problem.
-   */
-  for (name = ircd_strtok(&p, parv[1], ","); name; name = ircd_strtok(&p, NULL, ","))
-  {
-    size_t len;
-    if (MyConnect(sptr))
-      clean_channelname(name);
-    else if (IsLocalChannel(name))
+    /* BADCHANed channel */
+    if ((gline = gline_find(name, GLINE_BADCHAN | GLINE_EXACT)) &&
+       GlineIsActive(gline) && !IsAnOper(sptr)) {
+      send_reply(sptr, ERR_BANNEDFROMCHAN, name);
       continue;
-    if (*name == '0' && *(name + 1) == '\0')
-    {
-      /* Remove the user from all his channels -Kev */
-      while ((member = sptr->user->channel))
-      {
-        chptr = member->channel;
-        if (!IsZombie(member))
-          sendto_channel_butserv(chptr, sptr, PartFmt2,
-              parv[0], chptr->chname, "Left all channels");
-        remove_user_from_channel(sptr, chptr);
-      }
-      /* Just in case */
-      *mbuf = *jbuf = '\0';
-      mlen = jlen = 0;
     }
-    else
-    {                           /* not a /join 0, so treat it as
-                                   a /join #channel -Kev */
-      if (!IsChannelName(name))
-      {
-        if (MyUser(sptr))
-          sendto_one(sptr, err_str(ERR_NOSUCHCHANNEL), me.name, parv[0], name);
+
+    if (!(chptr = FindChannel(name))) {
+      if (((name[0] == '&') && !feature_bool(FEAT_LOCAL_CHANNELS))
+          || strlen(name) > IRCD_MIN(CHANNELLEN, feature_int(FEAT_CHANNELLEN))) {
+        send_reply(sptr, ERR_NOSUCHCHANNEL, name);
         continue;
       }
 
-      if (MyConnect(sptr))
-      {
-#ifdef BADCHAN
-        if (bad_channel(name) && !IsAnOper(sptr))
-        {
-          sendto_one(sptr, err_str(ERR_BADCHANNAME), me.name, parv[0], name);
-          continue;
-        }
-#endif
-        /*
-         * Local client is first to enter previously nonexistant
-         * channel so make them (rightfully) the Channel Operator.
-         * This looks kind of ugly because we try to avoid calling the strlen()
-         */
-        if (ChannelExists(name))
-        {
-          flags = CHFL_DEOPPED;
-          sendcreate = 0;
-        }
-        else if (strlen(name) > CHANNELLEN)
-        {
-          *(name + CHANNELLEN) = '\0';
-          if (ChannelExists(name))
-          {
-            flags = CHFL_DEOPPED;
-            sendcreate = 0;
-          }
-          else
-          {
-            flags = IsModelessChannel(name) ? CHFL_DEOPPED : CHFL_CHANOP;
-            sendcreate = 1;
-          }
-        }
-        else
-        {
-          flags = IsModelessChannel(name) ? CHFL_DEOPPED : CHFL_CHANOP;
-          sendcreate = 1;
-        }
+      if (!(chptr = get_channel(sptr, name, CGT_CREATE)))
+        continue;
 
-#ifdef OPER_NO_CHAN_LIMIT
-        /*
-         * Opers are allowed to join any number of channels
-         */
-        if (sptr->user->joined >= MAXCHANNELSPERUSER && !IsAnOper(sptr))
-#else
-        if (sptr->user->joined >= MAXCHANNELSPERUSER)
-#endif
-        {
-          chptr = get_channel(sptr, name, CGT_NO_CREATE);
-          sendto_one(sptr, err_str(ERR_TOOMANYCHANNELS),
-                     me.name, parv[0], chptr ? chptr->chname : name);
-          /*
-           * Can't return, else he won't get on ANY channels!
-           * Break out of the for loop instead.  -Kev
-           */
-          break;
-        }
+      /* Try to add the new channel as a recent target for the user. */
+      if (check_target_limit(sptr, chptr, chptr->chname, 0)) {
+        chptr->members = 0;
+        destruct_channel(chptr);
+        continue;
       }
-      chptr = get_channel(sptr, name, CGT_CREATE);
-      if (chptr && (member = find_member_link(chptr, sptr)))
+
+      joinbuf_join(&create, chptr, CHFL_CHANOP | CHFL_CHANNEL_MANAGER);
+    } else if (find_member_link(chptr, sptr)) {
+      continue; /* already on channel */
+    } else if (check_target_limit(sptr, chptr, chptr->chname, 0)) {
+      continue;
+    } else {
+      int flags = CHFL_DEOPPED;
+      int err = 0;
+
+      /* Check Apass/Upass -- since we only ever look at a single
+       * "key" per channel now, this hampers brute force attacks. */
+      if (key && !strcmp(key, chptr->mode.apass))
+        flags = CHFL_CHANOP | CHFL_CHANNEL_MANAGER;
+      else if (key && !strcmp(key, chptr->mode.upass))
+        flags = CHFL_CHANOP;
+      else if (chptr->users == 0 && !chptr->mode.apass[0]) {
+        /* Joining a zombie channel (zannel): give ops and increment TS. */
+        flags = CHFL_CHANOP;
+        chptr->creationtime++;
+      } else if (IsInvited(sptr, chptr)) {
+        /* Invites bypass these other checks. */
+      } else if (chptr->mode.mode & MODE_INVITEONLY)
+        err = ERR_INVITEONLYCHAN;
+      else if (chptr->mode.limit && (chptr->users >= chptr->mode.limit))
+        err = ERR_CHANNELISFULL;
+      else if ((chptr->mode.mode & MODE_REGONLY) && !IsAccount(sptr))
+        err = ERR_NEEDREGGEDNICK;
+      else if (find_ban(sptr, chptr->banlist))
+        err = ERR_BANNEDFROMCHAN;
+      else if (*chptr->mode.key && (!key || strcmp(key, chptr->mode.key)))
+        err = ERR_BADCHANNELKEY;
+
+      /* An oper with WALK_LCHAN privilege can join a local channel
+       * he otherwise could not join by using "OVERRIDE" as the key.
+       * This will generate a HACK(4) notice, but fails if the oper
+       * could normally join the channel. */
+      if (IsLocalChannel(chptr->chname)
+          && HasPriv(sptr, PRIV_WALK_LCHAN)
+          && !(flags & CHFL_CHANOP)
+          && key && !strcmp(key, "OVERRIDE"))
       {
-        if (IsZombie(member))
-        {
-          zombie = 1;
-          flags = member->status & (CHFL_DEOPPED | CHFL_SERVOPOK);
-          remove_user_from_channel(sptr, chptr);
-          chptr = get_channel(sptr, name, CGT_CREATE);
+        switch (err) {
+        case 0:
+          if (strcmp(chptr->mode.key, "OVERRIDE")
+              && strcmp(chptr->mode.apass, "OVERRIDE")
+              && strcmp(chptr->mode.upass, "OVERRIDE")) {
+            send_reply(sptr, ERR_DONTCHEAT, chptr->chname);
+            continue;
+          }
+          break;
+        case ERR_INVITEONLYCHAN: err = 'i'; break;
+        case ERR_CHANNELISFULL:  err = 'l'; break;
+        case ERR_BANNEDFROMCHAN: err = 'b'; break;
+        case ERR_BADCHANNELKEY:  err = 'k'; break;
+        case ERR_NEEDREGGEDNICK: err = 'r'; break;
+        default: err = '?'; break;
         }
-        else
-          continue;
-      }
-      name = chptr->chname;
-      if (!chptr->creationtime) /* A remote JOIN created this channel ? */
-        chptr->creationtime = MAGIC_REMOTE_JOIN_TS;
-      if (parc > 2)
-      {
-        if (chptr->creationtime == MAGIC_REMOTE_JOIN_TS)
-          chptr->creationtime = atoi(keysOrTS);
-        else
-          parc = 2;             /* Don't pass it on */
-      }
-      if (!zombie)
-      {
-        if (!MyConnect(sptr))
-          flags = CHFL_DEOPPED;
-        if (sptr->flags & FLAGS_TS8)
-          flags |= CHFL_SERVOPOK;
+        /* send accountability notice */
+        if (err)
+          sendto_opmask_butone(0, SNO_HACK4, "OPER JOIN: %C JOIN %H "
+                               "(overriding +%c)", sptr, chptr, err);
+        err = 0;
       }
-      if (MyConnect(sptr))
-      {
-        int created = chptr->users == 0;
-        if (check_target_limit(sptr, chptr, chptr->chname, created))
-        {
-          if (created)          /* Did we create the channel? */
-            sub1_from_channel(chptr);   /* Remove it again! */
-          continue;
-        }
-        if ((i = can_join(sptr, chptr, keysOrTS)))
-        {
-#ifdef OPER_WALK_THROUGH_LMODES
-         if (i > MAGIC_OPER_OVERRIDE)
-         {
-           switch(i - MAGIC_OPER_OVERRIDE)
-           {
-           case ERR_CHANNELISFULL: i = 'l'; break;
-           case ERR_INVITEONLYCHAN: i = 'i'; break;
-           case ERR_BANNEDFROMCHAN: i = 'b'; break;
-           case ERR_BADCHANNELKEY: i = 'k'; break;
-           }
-           sendto_op_mask(SNO_HACK4,"OPER JOIN: %s JOIN %s (overriding +%c)",sptr->name,chptr->chname,i);
-         }
-         else
-         {
-            sendto_one(sptr, err_str(i), me.name, parv[0], chptr->chname);
-           continue;
-         }
-#else    
-          sendto_one(sptr, err_str(i), me.name, parv[0], chptr->chname);
-          continue;
-#endif
+
+      /* Is there some reason the user may not join? */
+      if (err) {
+        switch(err) {
+          case ERR_NEEDREGGEDNICK:
+            send_reply(sptr, 
+                       ERR_NEEDREGGEDNICK, 
+                       chptr->chname, 
+                       feature_str(FEAT_URLREG));            
+            break;
+          default:
+            send_reply(sptr, err, chptr->chname);
+            break;
         }
+        continue;
       }
-      /*
-       * Complete user entry to the new channel (if any)
-       */
-      add_user_to_channel(chptr, sptr, flags);
 
-      /*
-       * Notify all other users on the new channel
-       */
-      sendto_channel_butserv(chptr, sptr, ":%s JOIN :%s", parv[0], name);
-
-      if (MyUser(sptr))
-      {
-        del_invite(sptr, chptr);
-        if (chptr->topic[0] != '\0')
-        {
-          sendto_one(sptr, rpl_str(RPL_TOPIC), me.name,
-              parv[0], name, chptr->topic);
-          sendto_one(sptr, rpl_str(RPL_TOPICWHOTIME), me.name, parv[0], name,
-              chptr->topic_nick, chptr->topic_time);
-        }
-        parv[1] = name;
-        m_names(cptr, sptr, 2, parv);
+      joinbuf_join(&join, chptr, flags);
+      if (flags & CHFL_CHANOP) {
+        struct ModeBuf mbuf;
+       /* Always let the server op him: this is needed on a net with older servers
+          because they 'destruct' channels immediately when they become empty without
+          sending out a DESTRUCT message. As a result, they would always bounce a mode
+          (as HACK(2)) when the user ops himself.
+           (There is also no particularly good reason to have the user op himself.)
+        */
+       modebuf_init(&mbuf, &me, cptr, chptr, MODEBUF_DEST_SERVER);
+       modebuf_mode_client(&mbuf, MODE_ADD | MODE_CHANOP, sptr,
+                            chptr->mode.apass[0] ? ((flags & CHFL_CHANNEL_MANAGER) ? 0 : 1) : MAXOPLEVEL);
+       modebuf_flush(&mbuf);
       }
     }
 
-    /* Select proper buffer; mbuf for creation, jbuf otherwise */
-
-    if (*name == '&')
-      continue;                 /* Head off local channels at the pass */
+    del_invite(sptr, chptr);
 
-    bufptr = (sendcreate == 0) ? jbuf : mbuf;
-    buflen = (sendcreate == 0) ? &jlen : &mlen;
-    len = strlen(name);
-    if (*buflen < BUFSIZE - len - 2)
-    {
-      if (*bufptr)
-      {
-        strcat(bufptr, ",");    /* Add to join buf */
-        *buflen += 1;
-      }
-      strncat(bufptr, name, BUFSIZE - *buflen - 1);
-      *buflen += len;
+    if (chptr->topic[0]) {
+      send_reply(sptr, RPL_TOPIC, chptr->chname, chptr->topic);
+      send_reply(sptr, RPL_TOPICWHOTIME, chptr->chname, chptr->topic_nick,
+                chptr->topic_time);
     }
-    sendcreate = 0;             /* Reset sendcreate */
-  }
 
-  if (*jbuf)                    /* Propgate joins to P10 servers */
-    sendto_serv_butone(cptr, 
-        parc > 2 ? "%s%s " TOK_JOIN " %s %s" : "%s%s " TOK_JOIN " %s", NumNick(sptr), jbuf, keysOrTS);
-  if (*mbuf)                    /* and now creation events */
-    sendto_serv_butone(cptr, "%s%s " TOK_CREATE " %s " TIME_T_FMT,
-        NumNick(sptr), mbuf, TStime());
-
-  if (MyUser(sptr))
-  {                             /* shouldn't ever set TS for remote JOIN's */
-    if (*jbuf)
-    {                           /* check for channels that need TS's */
-      p = NULL;
-      for (name = ircd_strtok(&p, jbuf, ","); name; name = ircd_strtok(&p, NULL, ","))
-      {
-        chptr = get_channel(sptr, name, CGT_NO_CREATE);
-        if (chptr && chptr->mode.mode & MODE_SENDTS)
-        {                       /* send a TS? */
-          sendto_serv_butone(cptr, "%s " TOK_MODE " %s + " TIME_T_FMT, NumServ(&me),
-              chptr->chname, chptr->creationtime);      /* ok, send TS */
-          chptr->mode.mode &= ~MODE_SENDTS;     /* reset flag */
-        }
-      }
-    }
+    do_names(sptr, chptr, NAMES_ALL|NAMES_EON); /* send /names list */
   }
+
+  joinbuf_flush(&join); /* must be first, if there's a JOIN 0 */
+  joinbuf_flush(&create);
+
   return 0;
 }
 
-/*
- * ms_join - server message handler
+/** Handle a JOIN message from a server connection.
+ * See @ref m_functions for discussion of the arguments.
+ * @param[in] cptr Client that sent us the message.
+ * @param[in] sptr Original source of message.
+ * @param[in] parc Number of arguments.
+ * @param[in] parv Argument vector.
  */
-int ms_join(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
+int ms_join(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
 {
-  static char     jbuf[BUFSIZE];
-  static char     mbuf[BUFSIZE];
-  struct Membership* member;
-  struct Channel* chptr;
-  char*           name;
-  char*           keysOrTS = NULL;
-  int             i = 0;
-  int             zombie = 0;
-  int             sendcreate = 0;
-  unsigned int    flags = 0;
-  size_t          jlen = 0;
-  size_t          mlen = 0;
-  size_t*         buflen;
-  char*           p = NULL;
-  char*           bufptr;
-
-  /*
-   * Doesn't make sense having a server join a channel, and besides
-   * the server cores.
-   */
+  struct Membership *member;
+  struct Channel *chptr;
+  struct JoinBuf join;
+  unsigned int flags;
+  time_t creation = 0;
+  char *p = 0;
+  char *chanlist;
+  char *name;
+
   if (IsServer(sptr))
-    return 0;
+  {
+    return protocol_violation(cptr,
+                              "%s tried to JOIN %s, duh!",
+                              cli_name(sptr),
+                              (parc < 2 || *parv[1] == '\0') ? "a channel" :
+                                                               parv[1]
+                              );
+  }
 
   if (parc < 2 || *parv[1] == '\0')
     return need_more_params(sptr, "JOIN");
 
-  keysOrTS = parv[2];           /* Remember where our keys are or the TS is;
-                                   parv[2] needs to be NULL for the call to
-                                   m_names below -Kev */
-  parv[2] = p = NULL;
-
-  *jbuf = *mbuf = '\0';         /* clear both join and mode buffers -Kev */
-  /*
-   *  Rebuild list of channels joined to be the actual result of the
-   *  JOIN.  Note that "JOIN 0" is the destructive problem.
-   */
-  for (name = ircd_strtok(&p, parv[1], ","); name; name = ircd_strtok(&p, NULL, ","))
-  {
-    size_t len;
-    if (IsLocalChannel(name))
-      continue;
+  if (parc > 2 && parv[2])
+    creation = atoi(parv[2]);
 
-    if (!IsChannelName(name))
-    {
-      sendto_one(sptr, err_str(ERR_NOSUCHCHANNEL), me.name, parv[0], name);
-      continue;
-    }
+  joinbuf_init(&join, sptr, cptr, JOINBUF_TYPE_JOIN, 0, 0);
 
-    chptr = get_channel(sptr, name, CGT_CREATE);
-    if (chptr && (member = find_member_link(chptr, sptr)))
-    {
-      if (!IsZombie(member))
-       continue;
+  chanlist = last0(cptr, sptr, parv[1]); /* find last "JOIN 0" */
 
-      /* If they are a zombie, make them really part
-       * and rejoin
-       */              
-      zombie = 1;
-      flags = member->status & (CHFL_DEOPPED | CHFL_SERVOPOK);
-      remove_user_from_channel(sptr, chptr);
-      chptr = get_channel(sptr, name, CGT_CREATE);
-      
-    }
-    
-    name = chptr->chname;
-    
-    if (!chptr->creationtime) /* A remote JOIN created this channel ? */
-      chptr->creationtime = MAGIC_REMOTE_JOIN_TS;
-      
-    if (parc > 2)
-    {
-      if (chptr->creationtime == MAGIC_REMOTE_JOIN_TS)
-        chptr->creationtime = atoi(keysOrTS);
-      else
-        parc = 2;             /* Don't pass it on */
-    }
-    
-    if (!zombie)
-    {
-      if (sptr->flags & FLAGS_TS8)
-        flags |= CHFL_SERVOPOK;
-    }
-    
-    /*
-     * Complete user entry to the new channel (if any)
-     */
-    add_user_to_channel(chptr, sptr, flags);
-
-    /*
-     * Notify all other users on the new channel
-     */
-    sendto_channel_butserv(chptr, sptr, ":%s JOIN :%s", parv[0], name);
-
-    /* Select proper buffer; mbuf for creation, jbuf otherwise */
-
-    if (*name == '&')
-      continue;                 /* Head off local channels at the pass */
-
-    bufptr = (sendcreate == 0) ? jbuf : mbuf;
-    buflen = (sendcreate == 0) ? &jlen : &mlen;
-    len = strlen(name);
-    
-    if (*buflen < BUFSIZE - len - 2)
-    {
-      if (*bufptr)
-      {
-        strcat(bufptr, ",");    /* Add to join buf */
-        *buflen += 1;
-      }
-      strncat(bufptr, name, BUFSIZE - *buflen - 1);
-      *buflen += len;
-    }
-    sendcreate = 0;             /* Reset sendcreate */
-  }
-
-  if (*jbuf)                    /* Propgate joins to P10 servers */
-    sendto_serv_butone(cptr, 
-        parc > 2 ? "%s%s " TOK_JOIN " %s %s" : "%s%s " TOK_JOIN " %s", NumNick(sptr), jbuf, keysOrTS);
-  if (*mbuf)                    /* and now creation events */
-    sendto_serv_butone(cptr, "%s%s " TOK_CREATE " %s " TIME_T_FMT,
-        NumNick(sptr), mbuf, TStime());
-
-  return 0;
-}
+  for (name = ircd_strtok(&p, chanlist, ","); name;
+       name = ircd_strtok(&p, 0, ",")) {
 
+    flags = CHFL_DEOPPED;
 
-#if 0
-/*
- * m_join
- *
- * parv[0] = sender prefix
- * parv[1] = channel
- * parv[2] = channel keys (client), or channel TS (server)
- */
-int m_join(struct Client *cptr, struct Client *sptr, int parc, char *parv[])
-{
-  static char     jbuf[BUFSIZE];
-  static char     mbuf[BUFSIZE];
-  struct Membership* member;
-  struct Channel* chptr;
-  char*           name;
-  char*           keysOrTS = NULL;
-  int             i = 0;
-  int             zombie = 0;
-  int             sendcreate = 0;
-  unsigned int    flags = 0;
-  size_t          jlen = 0;
-  size_t          mlen = 0;
-  size_t*         buflen;
-  char*           p = NULL;
-  char*           bufptr;
-
-  /*
-   * Doesn't make sense having a server join a channel, and besides
-   * the server cores.
-   */
-  if (IsServer(sptr))
-    return 0;
-
-  if (parc < 2 || *parv[1] == '\0')
-    return need_more_params(sptr, "JOIN");
-
-  for (p = parv[1]; *p; p++)    /* find the last "JOIN 0" in the line -Kev */
-    if (*p == '0'
-        && (*(p + 1) == ',' || *(p + 1) == '\0' || !IsChannelChar(*(p + 1))))
+    if (IsLocalChannel(name) || !IsChannelName(name))
     {
-      /* If it's a single "0", remember the place; we will start parsing
-         the channels after the last 0 in the line -Kev */
-      parv[1] = p;
-      if (!*(p + 1))
-        break;
-      p++;
-    }
-    else
-    {                           /* Step through to the next comma or until the
-                                   end of the line, in an attempt to save CPU
-                                   -Kev */
-      while (*p != ',' && *p != '\0')
-        p++;
-      if (!*p)
-        break;
+      protocol_violation(cptr, "%s tried to join %s", cli_name(sptr), name);
+      continue;
     }
 
-  keysOrTS = parv[2];           /* Remember where our keys are or the TS is;
-                                   parv[2] needs to be NULL for the call to
-                                   m_names below -Kev */
-  parv[2] = p = NULL;
-
-  *jbuf = *mbuf = '\0';         /* clear both join and mode buffers -Kev */
-  /*
-   *  Rebuild list of channels joined to be the actual result of the
-   *  JOIN.  Note that "JOIN 0" is the destructive problem.
-   */
-  for (name = ircd_strtok(&p, parv[1], ","); name; name = ircd_strtok(&p, NULL, ","))
-  {
-    size_t len;
-    if (MyConnect(sptr))
-      clean_channelname(name);
-    else if (IsLocalChannel(name))
-      continue;
-    if (*name == '0' && *(name + 1) == '\0')
+    if (!(chptr = FindChannel(name)))
     {
-      /* Remove the user from all his channels -Kev */
-      while ((member = sptr->user->channel))
+      /* No channel exists, so create one */
+      if (!(chptr = get_channel(sptr, name, CGT_CREATE)))
       {
-        chptr = member->channel;
-        if (!IsZombie(member))
-          sendto_channel_butserv(chptr, sptr, PartFmt2,
-              parv[0], chptr->chname, "Left all channels");
-        remove_user_from_channel(sptr, chptr);
-      }
-      /* Just in case */
-      *mbuf = *jbuf = '\0';
-      mlen = jlen = 0;
-    }
-    else
-    {                           /* not a /join 0, so treat it as
-                                   a /join #channel -Kev */
-      if (!IsChannelName(name))
-      {
-        if (MyUser(sptr))
-          sendto_one(sptr, err_str(ERR_NOSUCHCHANNEL), me.name, parv[0], name);
-        continue;
+        protocol_violation(sptr,"couldn't get channel %s for %s",
+                          name,cli_name(sptr));
+       continue;
       }
+      flags |= HasFlag(sptr, FLAG_TS8) ? CHFL_SERVOPOK : 0;
 
-      if (MyConnect(sptr))
+      chptr->creationtime = creation;
+    }
+    else { /* We have a valid channel? */
+      if ((member = find_member_link(chptr, sptr)))
       {
-#ifdef BADCHAN
-        if (bad_channel(name) && !IsAnOper(sptr))
-        {
-          sendto_one(sptr, err_str(ERR_BADCHANNAME), me.name, parv[0], name);
-          continue;
-        }
-#endif
-        /*
-         * Local client is first to enter previously nonexistant
-         * channel so make them (rightfully) the Channel Operator.
-         * This looks kind of ugly because we try to avoid calling the strlen()
-         */
-        if (ChannelExists(name))
-        {
-          flags = CHFL_DEOPPED;
-          sendcreate = 0;
-        }
-        else if (strlen(name) > CHANNELLEN)
-        {
-          *(name + CHANNELLEN) = '\0';
-          if (ChannelExists(name))
-          {
-            flags = CHFL_DEOPPED;
-            sendcreate = 0;
-          }
-          else
-          {
-            flags = IsModelessChannel(name) ? CHFL_DEOPPED : CHFL_CHANOP;
-            sendcreate = 1;
-          }
-        }
-        else
-        {
-          flags = IsModelessChannel(name) ? CHFL_DEOPPED : CHFL_CHANOP;
-          sendcreate = 1;
-        }
+       /* It is impossible to get here --Run */
+       if (!IsZombie(member)) /* already on channel */
+         continue;
 
-#ifdef OPER_NO_CHAN_LIMIT
-        /*
-         * Opers are allowed to join any number of channels
-         */
-        if (sptr->user->joined >= MAXCHANNELSPERUSER && !IsAnOper(sptr))
-#else
-        if (sptr->user->joined >= MAXCHANNELSPERUSER)
-#endif
-        {
-          chptr = get_channel(sptr, name, CGT_NO_CREATE);
-          sendto_one(sptr, err_str(ERR_TOOMANYCHANNELS),
-                     me.name, parv[0], chptr ? chptr->chname : name);
-          /*
-           * Can't return, else he won't get on ANY channels!
-           * Break out of the for loop instead.  -Kev
-           */
-          break;
-        }
+       flags = member->status & (CHFL_DEOPPED | CHFL_SERVOPOK);
+       remove_user_from_channel(sptr, chptr);
+       chptr = FindChannel(name);
       }
-      chptr = get_channel(sptr, name, CGT_CREATE);
-      if (chptr && (member = find_member_link(chptr, sptr)))
-      {
-        if (IsZombie(member))
-        {
-          zombie = 1;
-          flags = member->status & (CHFL_DEOPPED | CHFL_SERVOPOK);
-          remove_user_from_channel(sptr, chptr);
-          chptr = get_channel(sptr, name, CGT_CREATE);
+      else
+        flags |= HasFlag(sptr, FLAG_TS8) ? CHFL_SERVOPOK : 0;
+      /* Always copy the timestamp when it is older, that is the only way to
+         ensure network-wide synchronization of creation times.
+         We now also copy a creation time that only 1 second younger...
+         this is needed because the timestamp must be incremented
+         by one when someone joins an existing, but empty, channel.
+         However, this is only necessary when the channel is still
+         empty (also here) and when this channel doesn't have +A set.
+
+         To prevent this from allowing net-rides on the channel, we
+         clear all modes from the channel.
+
+         (Scenario for a net ride: c1 - s1 - s2 - c2, with c1 the only
+         user in the channel; c1 parts and rejoins, gaining ops.
+         Before s2 sees c1's part, c2 joins the channel and parts
+         immediately.  s1 sees c1 part, c1 create, c2 join, c2 part;
+         c2's join resets the timestamp.  s2 sees c2 join, c2 part, c1
+         part, c1 create; but since s2 sees the channel as a zannel or
+         non-existent, it does not bounce the create with the newer
+         timestamp.)
+      */
+      if (creation && (creation < chptr->creationtime ||
+                      (!chptr->mode.apass[0] && chptr->users == 0))) {
+        struct Membership *member;
+        struct ModeBuf mbuf;
+
+       chptr->creationtime = creation;
+        /* Wipe out the current modes on the channel. */
+        modebuf_init(&mbuf, sptr, cptr, chptr, MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK3);
+
+        modebuf_mode(&mbuf, MODE_DEL | chptr->mode.mode);
+        chptr->mode.mode &= MODE_BURSTADDED | MODE_WASDELJOINS;
+
+        if (chptr->mode.limit) {
+          modebuf_mode_uint(&mbuf, MODE_DEL | MODE_LIMIT, chptr->mode.limit);
+          chptr->mode.limit = 0;
         }
-        else
-          continue;
-      }
-      name = chptr->chname;
-      if (!chptr->creationtime) /* A remote JOIN created this channel ? */
-        chptr->creationtime = MAGIC_REMOTE_JOIN_TS;
-      if (parc > 2)
-      {
-        if (chptr->creationtime == MAGIC_REMOTE_JOIN_TS)
-          chptr->creationtime = atoi(keysOrTS);
-        else
-          parc = 2;             /* Don't pass it on */
-      }
-      if (!zombie)
-      {
-        if (!MyConnect(sptr))
-          flags = CHFL_DEOPPED;
-        if (sptr->flags & FLAGS_TS8)
-          flags |= CHFL_SERVOPOK;
-      }
-      if (MyConnect(sptr))
-      {
-        int created = chptr->users == 0;
-        if (check_target_limit(sptr, chptr, chptr->chname, created))
-        {
-          if (created)          /* Did we create the channel? */
-            sub1_from_channel(chptr);   /* Remove it again! */
-          continue;
+
+        if (chptr->mode.key[0]) {
+          modebuf_mode_string(&mbuf, MODE_DEL | MODE_KEY, chptr->mode.key, 0);
+          chptr->mode.key[0] = '\0';
         }
-        if ((i = can_join(sptr, chptr, keysOrTS)))
-        {
-          sendto_one(sptr, err_str(i), me.name, parv[0], chptr->chname);
-#ifdef OPER_WALK_THROUGH_LMODES
-         if (i > MAGIC_OPER_OVERRIDE)
-         {
-           switch(i - MAGIC_OPER_OVERRIDE)
-           {
-           case ERR_CHANNELISFULL: i = 'l'; break;
-           case ERR_INVITEONLYCHAN: i = 'i'; break;
-           case ERR_BANNEDFROMCHAN: i = 'b'; break;
-           case ERR_BADCHANNELKEY: i = 'k'; break;
-           }
-           sendto_op_mask(SNO_HACK4,"OPER JOIN: %s JOIN %s (overriding +%c)",sptr->name,chptr->chname,i);
-         }
-         else
-           continue;     
-#else    
-          continue;
-#endif
+
+        if (chptr->mode.upass[0]) {
+          modebuf_mode_string(&mbuf, MODE_DEL | MODE_UPASS, chptr->mode.upass, 0);
+          chptr->mode.upass[0] = '\0';
         }
-      }
-      /*
-       * Complete user entry to the new channel (if any)
-       */
-      add_user_to_channel(chptr, sptr, flags);
 
-      /*
-       * Notify all other users on the new channel
-       */
-      sendto_channel_butserv(chptr, sptr, ":%s JOIN :%s", parv[0], name);
+        if (chptr->mode.apass[0]) {
+          modebuf_mode_string(&mbuf, MODE_DEL | MODE_APASS, chptr->mode.apass, 0);
+          chptr->mode.apass[0] = '\0';
+        }
 
-      if (MyUser(sptr))
-      {
-        del_invite(sptr, chptr);
-        if (chptr->topic[0] != '\0')
+        for (member = chptr->members; member; member = member->next_member)
         {
-          sendto_one(sptr, rpl_str(RPL_TOPIC), me.name,
-              parv[0], name, chptr->topic);
-          sendto_one(sptr, rpl_str(RPL_TOPICWHOTIME), me.name, parv[0], name,
-              chptr->topic_nick, chptr->topic_time);
+          if (IsChanOp(member)) {
+            modebuf_mode_client(&mbuf, MODE_DEL | MODE_CHANOP, member->user, OpLevel(member));
+           member->status &= ~CHFL_CHANOP;
+         }
+          if (HasVoice(member)) {
+            modebuf_mode_client(&mbuf, MODE_DEL | MODE_VOICE, member->user, OpLevel(member));
+           member->status &= ~CHFL_VOICE;
+          }
         }
-        parv[1] = name;
-        m_names(cptr, sptr, 2, parv);
+        modebuf_flush(&mbuf);
       }
     }
 
-    /* Select proper buffer; mbuf for creation, jbuf otherwise */
-
-    if (*name == '&')
-      continue;                 /* Head off local channels at the pass */
-
-    bufptr = (sendcreate == 0) ? jbuf : mbuf;
-    buflen = (sendcreate == 0) ? &jlen : &mlen;
-    len = strlen(name);
-    if (*buflen < BUFSIZE - len - 2)
-    {
-      if (*bufptr)
-      {
-        strcat(bufptr, ",");    /* Add to join buf */
-        *buflen += 1;
-      }
-      strncat(bufptr, name, BUFSIZE - *buflen - 1);
-      *buflen += len;
-    }
-    sendcreate = 0;             /* Reset sendcreate */
+    joinbuf_join(&join, chptr, flags);
   }
 
-  if (*jbuf)                    /* Propgate joins to P10 servers */
-    sendto_serv_butone(cptr, 
-        parc > 2 ? "%s%s " TOK_JOIN " %s %s" : "%s%s " TOK_JOIN " %s", NumNick(sptr), jbuf, keysOrTS);
-  if (*mbuf)                    /* and now creation events */
-    sendto_serv_butone(cptr, "%s%s " TOK_CREATE " %s " TIME_T_FMT,
-        NumNick(sptr), mbuf, TStime());
-
-  if (MyUser(sptr))
-  {                             /* shouldn't ever set TS for remote JOIN's */
-    if (*jbuf)
-    {                           /* check for channels that need TS's */
-      p = NULL;
-      for (name = ircd_strtok(&p, jbuf, ","); name; name = ircd_strtok(&p, NULL, ","))
-      {
-        chptr = get_channel(sptr, name, CGT_NO_CREATE);
-        if (chptr && chptr->mode.mode & MODE_SENDTS)
-        {                       /* send a TS? */
-          sendto_serv_butone(cptr, "%s " TOK_MODE " %s + " TIME_T_FMT, NumServ(&me),
-              chptr->chname, chptr->creationtime);      /* ok, send TS */
-          chptr->mode.mode &= ~MODE_SENDTS;     /* reset flag */
-        }
-      }
-    }
-  }
+  joinbuf_flush(&join); /* flush joins... */
+
   return 0;
 }
-#endif /* 0 */