Bump patchlevel; add more epoll support; assertion check in
[ircu2.10.12-pk.git] / ircd / channel.c
index b264db71fb3051e0d6d2f218ead60c73f4c94d0e..1912d16275899a6a9470964f39fa45e40ccb6ab8 100644 (file)
@@ -18,7 +18,7 @@
  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  */
 /** @file
- * @brief Channel management and maintanance
+ * @brief Channel management and maintenance
  * @version $Id$
  */
 #include "config.h"
@@ -67,6 +67,10 @@ static unsigned int membershipAllocCount;
 static struct Membership* membershipFreeList;
 /** Freelist for struct Ban*'s */
 static struct Ban* free_bans;
+/** Number of ban structures allocated. */
+static size_t bans_alloc;
+/** Number of ban structures in use. */
+static size_t bans_inuse;
 
 #if !defined(NDEBUG)
 /** return the length (>=0) of a chain of links.
@@ -91,10 +95,8 @@ static void
 set_ban_mask(struct Ban *ban, const char *banstr)
 {
   char *sep;
-  MyFree(ban->banstr);
-  if (!banstr)
-    return;
-  DupString(ban->banstr, banstr);
+  assert(banstr != NULL);
+  ircd_strncpy(ban->banstr, banstr, sizeof(ban->banstr) - 1);
   sep = strrchr(banstr, '@');
   if (sep) {
     ban->nu_len = sep - banstr;
@@ -117,6 +119,9 @@ make_ban(const char *banstr)
   }
   else if (!(ban = MyMalloc(sizeof(*ban))))
     return NULL;
+  else
+    bans_alloc++;
+  bans_inuse++;
   memset(ban, 0, sizeof(*ban));
   set_ban_mask(ban, banstr);
   return ban;
@@ -128,10 +133,22 @@ make_ban(const char *banstr)
 void
 free_ban(struct Ban *ban)
 {
-  MyFree(ban->who);
-  MyFree(ban->banstr);
   ban->next = free_bans;
   free_bans = ban;
+  bans_inuse--;
+}
+
+/** Report ban usage to \a cptr.
+ * @param[in] cptr Client requesting information.
+ */
+void bans_send_meminfo(struct Client *cptr)
+{
+  struct Ban *ban;
+  size_t num_free;
+  for (num_free = 0, ban = free_bans; ban; ban = ban->next)
+    num_free++;
+  send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":Bans: inuse %zu(%zu) free %zu alloc %zu",
+            bans_inuse, bans_inuse * sizeof(*ban), num_free, bans_alloc);
 }
 
 /** return the struct Membership* that represents a client on a channel
@@ -198,7 +215,7 @@ struct Membership* find_member_link(struct Channel* chptr, const struct Client*
  * numeric nicks is no longer quite as important.
  *
  * @param sptr Pointer to the client that has requested the search
- * @param user a string represeting the client to be found
+ * @param user a string representing the client to be found
  * @param chasing a variable set to 0 if the user was found directly, 
  *             1 otherwise
  * @returns a pointer the client, or NULL if the client wasn't found.
@@ -241,25 +258,16 @@ int sub1_from_channel(struct Channel* chptr)
 
   chptr->users = 0;
 
-  /*
-   * Also channels without Apass set need to be kept alive,
-   * otherwise Bad Guys(tm) would be able to takeover
-   * existing channels too easily, and then set an Apass!
-   * However, if a channel without Apass becomes empty
-   * then we try to be kind to them and remove possible
-   * limiting modes.
-   */
-  chptr->mode.mode &= ~MODE_INVITEONLY;
-  chptr->mode.limit = 0;
-  /*
-   * We do NOT reset a possible key or bans because when
-   * the 'channel owners' can't get in because of a key
-   * or ban then apparently there was a fight/takeover
-   * on the channel and we want them to contact IRC opers
-   * who then will educate them on the use of Apass/upass.
+  /* There is a semantics problem here: Assuming no fragments across a
+   * split, a channel without Apass could be maliciously destroyed and
+   * recreated, and someone could set apass on the new instance.
+   *
+   * This could be fixed by preserving the empty non-Apass channel for
+   * the same time as if it had an Apass (but removing +i and +l), and
+   * reopping the first user to rejoin.  However, preventing net rides
+   * requires a backwards-incompatible protocol change..
    */
-
-  if (!(chptr->mode.mode & MODE_APASS))         /* If no Apass, destroy now. */
+  if (!chptr->mode.apass[0])         /* If no Apass, destroy now. */
     destruct_channel(chptr);
   else if (TStime() - chptr->creationtime < 172800)    /* Channel younger than 48 hours? */
     schedule_destruct_event_1m(chptr);         /* Get rid of it in approximately 4-5 minutes */
@@ -329,7 +337,7 @@ struct Membership* find_channel_member(struct Client* cptr, struct Channel* chpt
   return (member && !IsZombie(member)) ? member : 0;
 }
 
-/** Searches for a ban from a banlist that matches a user.
+/** Searches for a ban from a ban list that matches a user.
  * @param[in] cptr The client to test.
  * @param[in] banlist The list of bans to test.
  * @return Pointer to a matching ban, or NULL if none exit.
@@ -338,12 +346,15 @@ struct Ban *find_ban(struct Client *cptr, struct Ban *banlist)
 {
   char        nu[NICKLEN + USERLEN + 2];
   char        tmphost[HOSTLEN + 1];
+  char        iphost[SOCKIPLEN + 1];
+  char       *hostmask;
   char       *sr;
   struct Ban *found;
 
   /* Build nick!user and alternate host names. */
   ircd_snprintf(0, nu, sizeof(nu), "%s!%s",
                 cli_name(cptr), cli_user(cptr)->username);
+  ircd_ntoa_r(iphost, &cli_ip(cptr));
   if (!IsAccount(cptr))
     sr = NULL;
   else if (HasHiddenHost(cptr))
@@ -368,10 +379,12 @@ struct Ban *find_ban(struct Client *cptr, struct Ban *banlist)
     if (res)
       continue;
     /* Compare host portion of ban. */
-    if (!((banlist->flags & BAN_IPMASK)
-         && ipmask_check(&cli_ip(cptr), &banlist->address, banlist->addrbits))
-        && match(banlist->banstr + banlist->nu_len + 1, cli_user(cptr)->host)
-        && !(sr && match(banlist->banstr + banlist->nu_len + 1, sr) == 0))
+    hostmask = banlist->banstr + banlist->nu_len + 1;
+    if (((banlist->flags & BAN_IPMASK)
+         ? !ipmask_check(&cli_ip(cptr), &banlist->address, banlist->addrbits)
+         : match(hostmask, iphost))
+        && match(hostmask, cli_user(cptr)->host)
+        && !(sr && match(hostmask, sr) == 0))
       continue;
     /* If an exception matches, no ban can match. */
     if (banlist->flags & BAN_EXCEPTION)
@@ -519,7 +532,7 @@ static int channel_all_zombies(struct Channel* chptr)
 
 /** Remove a user from a channel
  * This is the generic entry point for removing a user from a channel, this
- * function will remove the client from the channel, and destory the channel
+ * function will remove the client from the channel, and destroy the channel
  * if there are no more normal users left.
  *
  * @param cptr         The client
@@ -650,11 +663,14 @@ int member_can_send_to_channel(struct Membership* member, int reveal)
   if (IsVoicedOrOpped(member))
     return 1;
   /*
-   * If it's moderated, and you aren't a priviledged user, you can't
+   * If it's moderated, and you aren't a privileged user, you can't
    * speak.  
    */
   if (member->channel->mode.mode & MODE_MODERATED)
     return 0;
+  /* If only logged in users may join and you're not one, you can't speak. */
+  if (member->channel->mode.mode & MODE_REGONLY && !IsAccount(member->user))
+    return 0;
   /*
    * If you're banned then you can't speak either.
    * but because of the amount of CPU time that is_banned chews
@@ -860,7 +876,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
   int                 opped_members_index = 0;
   struct Membership** opped_members = NULL;
   int                 last_oplevel = 0;
-  int                 feat_oplevels = (chptr->mode.mode & MODE_APASS) != 0;
+  int                 feat_oplevels = (chptr->mode.apass[0]) != '\0';
 
   assert(0 != cptr);
   assert(0 != chptr); 
@@ -895,7 +911,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
     }
 
     /*
-     * Attach nicks, comma seperated " nick[:modes],nick[:modes],..."
+     * Attach nicks, comma separated " nick[:modes],nick[:modes],..."
      *
      * First find all opless members.
      * Run 2 times over all members, to group the members with
@@ -939,7 +955,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
           * Do we have a nick with a new mode ?
           * Or are we starting a new BURST line?
           */
-         if (new_mode || !feat_oplevels)
+         if (new_mode)
          {
            /*
             * This means we are at the _first_ member that has only
@@ -967,7 +983,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
            msgq_append(&me, mb, tbuf);
            new_mode = 0;
          }
-         else if (flag_cnt > 1 && last_oplevel != member->oplevel)
+         else if (feat_oplevels && flag_cnt > 1 && last_oplevel != member->oplevel)
          {
            /*
             * This can't be the first member of a (continued) BURST
@@ -1015,7 +1031,7 @@ void send_channel_modes(struct Client *cptr, struct Channel *chptr)
 
     if (!full)
     {
-      /* Attach all bans, space seperated " :%ban ban ..." */
+      /* Attach all bans, space separated " :%ban ban ..." */
       for (first = 2; lp2; lp2 = lp2->next)
       {
         len = strlen(lp2->banstr);
@@ -1093,9 +1109,10 @@ char *pretty_mask(char *mask)
       user = mask;
       host = ++ptr;
     }
-    else if (*ptr == '.')
+    else if (*ptr == '.' || *ptr == ':')
     {
-      /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
+      /* Case 2: Found character specific to IP or hostname (without
+       * finding a '!' or '@' yet) */
       last_dot = ptr;
       continue;
     }
@@ -1172,7 +1189,7 @@ static void send_ban_list(struct Client* cptr, struct Channel* chptr)
  * This version contributed by SeKs \<intru@info.polymtl.ca\>
  *
  * @param key          Key to check
- * @param keyring      Comma seperated list of keys
+ * @param keyring      Comma separated list of keys
  *
  * @returns True if the key was found and matches, false otherwise.
  */
@@ -1211,8 +1228,8 @@ top:
  * @param chptr        The channel to join
  * @param key  The key to use
  *
- * @returns any error that occured bitwised OR'd with MAGIC_OPER_OVERRIDE
- *         if the oper used the magic key, 0 if no error occured.
+ * @returns any error that occurred bit-wise OR'd with MAGIC_OPER_OVERRIDE
+ *         if the oper used the magic key, 0 if no error occurred.
  */
 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
 {
@@ -1268,7 +1285,8 @@ void clean_channelname(char *cn)
   int i;
 
   for (i = 0; cn[i]; i++) {
-    if (i >= CHANNELLEN || !IsChannelChar(cn[i])) {
+    if (i >= IRCD_MIN(CHANNELLEN, feature_int(FEAT_CHANNELLEN))
+        || !IsChannelChar(cn[i])) {
       cn[i] = '\0';
       return;
     }
@@ -1450,7 +1468,7 @@ void del_invite(struct Client *cptr, struct Channel *chptr)
  *
  * We also need to turn 'who' into a zombie on servers 1 and 6,
  * because a KICK from 'who' (kicking someone else in that direction)
- * can arrive there afterwards - which should not be bounced itself.
+ * can arrive there afterward - which should not be bounced itself.
  * Therefore case a) also applies for servers 1 and 6.
  *
  * --Run
@@ -1530,9 +1548,9 @@ int number_of_zombies(struct Channel *chptr)
  *
  * @param strptr       The buffer to concatenate into
  * @param strptr_i     modified offset to the position to modify
- * @param str1         The string to contatenate from.
+ * @param str1         The string to concatenate from.
  * @param str2         The second string to contatenate from.
- * @param c            Charactor to seperate the string from str1 and str2.
+ * @param c            Charactor to separate the string from str1 and str2.
  */
 static void
 build_string(char *strptr, int *strptr_i, const char *str1,
@@ -1618,8 +1636,8 @@ modebuf_flush_int(struct ModeBuf *mbuf, int all)
 
   /* Ok, if we were given the OPMODE flag, or its a server, hide the source.
    */
-  if (mbuf->mb_dest & MODEBUF_DEST_OPMODE || IsServer(mbuf->mb_source))
-    app_source = &me;
+  if (mbuf->mb_dest & MODEBUF_DEST_OPMODE || IsServer(mbuf->mb_source) || IsMe(mbuf->mb_source))
+    app_source = &his;
   else
     app_source = mbuf->mb_source;
 
@@ -2436,9 +2454,10 @@ mode_parse_upass(struct ParseState *state, int *flag_p)
   }
 
   /* If a non-service user is trying to force it, refuse. */
-  if (state->flags & MODE_PARSE_FORCE && !IsChannelService(state->sptr)) {
+  if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
+      && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-               "Use /JOIN", state->chptr->chname, " <AdminPass>.");
+               state->chptr->chname);
     return;
   }
 
@@ -2446,16 +2465,15 @@ mode_parse_upass(struct ParseState *state, int *flag_p)
   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
     if (*state->chptr->mode.apass) {
       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-         "Use /JOIN", state->chptr->chname, "<AdminPass>.");
+                 state->chptr->chname);
+    } else if (TStime() - state->chptr->creationtime >= 171000) {
+      send_reply(state->sptr, ERR_NOMANAGER_LONG, state->chptr->chname);
     } else {
-      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-         "Re-create the channel.  The channel must be *empty* for",
-         TStime() - state->chptr->creationtime >= 171000 ? "48 contiguous hours" : "a minute or two",
-         "before it can be recreated.");
+      send_reply(state->sptr, ERR_NOMANAGER_SHORT, state->chptr->chname);
     }
     return;
   }
+
   if (state->done & DONE_UPASS) /* allow upass to be set only once */
     return;
   state->done |= DONE_UPASS;
@@ -2478,12 +2496,17 @@ mode_parse_upass(struct ParseState *state, int *flag_p)
   if (!state->mbuf)
     return;
 
-  if (!(state->flags & MODE_PARSE_FORCE))
+  if (!(state->flags & MODE_PARSE_FORCE)) {
     /* can't add the upass while apass is not set */
     if (state->dir == MODE_ADD && !*state->chptr->mode.apass) {
       send_reply(state->sptr, ERR_UPASSNOTSET, state->chptr->chname, state->chptr->chname);
       return;
     }
+    /* cannot set a +U password that is the same as +A */
+    if (state->dir == MODE_ADD && !ircd_strcmp(state->chptr->mode.apass, t_str)) {
+      send_reply(state->sptr, ERR_UPASS_SAME_APASS, state->chptr->chname);
+      return;
+    }
     /* can't add a upass if one is set, nor can one remove the wrong upass */
     if ((state->dir == MODE_ADD && *state->chptr->mode.upass) ||
        (state->dir == MODE_DEL &&
@@ -2491,6 +2514,7 @@ mode_parse_upass(struct ParseState *state, int *flag_p)
       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
       return;
     }
+  }
 
   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
       !ircd_strcmp(state->chptr->mode.upass, t_str))
@@ -2519,6 +2543,7 @@ mode_parse_upass(struct ParseState *state, int *flag_p)
 static void
 mode_parse_apass(struct ParseState *state, int *flag_p)
 {
+  struct Membership *memb;
   char *t_str, *s;
   int t_len;
 
@@ -2543,9 +2568,10 @@ mode_parse_apass(struct ParseState *state, int *flag_p)
   }
 
   /* If a non-service user is trying to force it, refuse. */
-  if (state->flags & MODE_PARSE_FORCE && !IsChannelService(state->sptr)) {
+  if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
+      && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-               "Use /JOIN", state->chptr->chname, " <AdminPass>.");
+               state->chptr->chname);
     return;
   }
 
@@ -2559,15 +2585,15 @@ mode_parse_apass(struct ParseState *state, int *flag_p)
   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
     if (*state->chptr->mode.apass) {
       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-         "Use /JOIN", state->chptr->chname, "<AdminPass>.");
+                 state->chptr->chname);
+    } else if (TStime() - state->chptr->creationtime >= 171000) {
+      send_reply(state->sptr, ERR_NOMANAGER_LONG, state->chptr->chname);
     } else {
-      send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
-         "Re-create the channel.  The channel must be *empty* for",
-         "at least a whole minute", "before it can be recreated.");
+      send_reply(state->sptr, ERR_NOMANAGER_SHORT, state->chptr->chname);
     }
     return;
   }
+
   if (state->done & DONE_APASS) /* allow apass to be set only once */
     return;
   state->done |= DONE_APASS;
@@ -2622,25 +2648,22 @@ mode_parse_apass(struct ParseState *state, int *flag_p)
       /* Make it VERY clear to the user that this is a one-time password */
       ircd_strncpy(state->chptr->mode.apass, t_str, PASSLEN);
       if (MyUser(state->sptr)) {
-       send_reply(state->sptr, RPL_APASSWARN,
-           "Channel Admin password (+A) set to '", state->chptr->mode.apass, "'. ",
-           "Are you SURE you want to use this as Admin password? ",
-           "You will NOT be able to change this password anymore once the channel is more than 48 hours old!");
-       send_reply(state->sptr, RPL_APASSWARN,
-           "Use \"/MODE ", state->chptr->chname, " -A ", state->chptr->mode.apass,
-           "\" to remove the password and then immediately set a new one. "
-           "IMPORTANT: YOU CANNOT RECOVER THIS PASSWORD, EVER; "
-           "WRITE THE PASSWORD DOWN (don't store this rescue password on disk)! "
-           "Now set the channel user password (+U).");
+       send_reply(state->sptr, RPL_APASSWARN_SET, state->chptr->mode.apass);
+       send_reply(state->sptr, RPL_APASSWARN_SECRET, state->chptr->chname,
+                   state->chptr->mode.apass);
       }
+      /* Give the channel manager level 0 ops. */
+      if (!(state->flags & MODE_PARSE_FORCE) && IsChannelManager(state->member))
+        SetOpLevel(state->member, 0);
     } else { /* remove the old apass */
       *state->chptr->mode.apass = '\0';
       if (MyUser(state->sptr))
-       send_reply(state->sptr, RPL_APASSWARN,
-           "WARNING: You removed the channel Admin password MODE (+A). ",
-           "If you would disconnect or leave the channel without setting a new password then you will ",
-           "not be able to set it again and lose ownership of this channel! ",
-           "SET A NEW PASSWORD NOW!", "");
+        send_reply(state->sptr, RPL_APASSWARN_CLEAR);
+      /* Revert everyone to MAXOPLEVEL. */
+      for (memb = state->chptr->members; memb; memb = memb->next_member) {
+        if (memb->status & MODE_CHANOP)
+          memb->oplevel = MAXOPLEVEL;
+      }
     }
   }
 }
@@ -2689,6 +2712,7 @@ bmatch(struct Ban *old_ban, struct Ban *new_ban)
  *
  * @param[in,out] banlist Pointer to head of list.
  * @param[in] newban Ban (or exception) to add (or remove).
+ * @param[in] do_free If non-zero, free \a newban on failure.
  * @return Zero if \a newban could be applied, non-zero if not.
  */
 int apply_ban(struct Ban **banlist, struct Ban *newban, int do_free)
@@ -2734,8 +2758,6 @@ int apply_ban(struct Ban **banlist, struct Ban *newban, int do_free)
     /* If no matches were found, fail. */
     if (do_free)
       free_ban(newban);
-    else
-      MyFree(newban->banstr);
     return 3;
   }
   if (do_free)
@@ -2795,10 +2817,9 @@ mode_parse_ban(struct ParseState *state, int *flag_p)
   newban = state->banlist + (state->numbans++);
   newban->next = 0;
   newban->flags = ((state->dir == MODE_ADD) ? BAN_ADD : BAN_DEL)
-      | (*flag_p == 'b' ? 0 : BAN_EXCEPTION);
-  newban->banstr = NULL;
+      | (*flag_p == MODE_BAN ? 0 : BAN_EXCEPTION);
   set_ban_mask(newban, collapse(pretty_mask(t_str)));
-  newban->who = cli_name(state->sptr);
+  ircd_strncpy(newban->who, IsUser(state->sptr) ? cli_name(state->sptr) : "*", NICKLEN);
   newban->when = TStime();
   apply_ban(&state->chptr->banlist, newban, 0);
 }
@@ -2830,12 +2851,12 @@ mode_process_bans(struct ParseState *state)
       count--;
       len -= banlen;
 
-      MyFree(ban->banstr);
-
       continue;
     } else if (ban->flags & BAN_DEL) { /* Deleted a ban? */
+      char *bandup;
+      DupString(bandup, ban->banstr);
       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
-                         ban->banstr, 1);
+                         bandup, 1);
 
       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
        if (prevban) /* clip it out of the list... */
@@ -2845,9 +2866,6 @@ mode_process_bans(struct ParseState *state)
 
        count--;
        len -= banlen;
-
-        ban->banstr = NULL; /* modebuf_mode_string() gave ownership of
-                             * the ban string to state->mbuf */
         free_ban(ban);
 
        changed++;
@@ -2865,7 +2883,6 @@ mode_process_bans(struct ParseState *state)
          !(state->flags & MODE_PARSE_BOUNCE)) {
        count--;
        len -= banlen;
-        MyFree(ban->banstr);
       } else {
        if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
            (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
@@ -2874,15 +2891,16 @@ mode_process_bans(struct ParseState *state)
                     ban->banstr);
          count--;
          len -= banlen;
-          MyFree(ban->banstr);
        } else {
+          char *bandup;
          /* add the ban to the buffer */
+          DupString(bandup, ban->banstr);
          modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
-                             ban->banstr, 1);
+                             bandup, 1);
 
          if (state->flags & MODE_PARSE_SET) { /* create a new ban */
            newban = make_ban(ban->banstr);
-           DupString(newban->who, ban->who);
+            strcpy(newban->who, ban->who);
            newban->when = ban->when;
            newban->flags = ban->flags & BAN_IPMASK;
 
@@ -3007,11 +3025,11 @@ mode_process_clients(struct ParseState *state)
          continue;
         }
 
-        if (feature_bool(FEAT_OPLEVELS)) {
        /* don't allow to deop members with an op level that is <= our own level */
        if (state->sptr != state->cli_change[i].client          /* but allow to deop oneself */
-               && state->member
-               && OpLevel(member) <= OpLevel(state->member)) {
+            && state->chptr->mode.apass[0]
+            && state->member
+            && OpLevel(member) <= OpLevel(state->member)) {
            int equal = (OpLevel(member) == OpLevel(state->member));
            send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
                       cli_name(state->cli_change[i].client),
@@ -3020,20 +3038,24 @@ mode_process_clients(struct ParseState *state)
                       "deop", equal ? "the same" : "a higher");
          continue;
        }
-      }
     }
     }
 
     /* set op-level of member being opped */
     if ((state->cli_change[i].flag & (MODE_ADD | MODE_CHANOP)) ==
        (MODE_ADD | MODE_CHANOP)) {
-      /* If on a channel with upass set, someone with level x gives ops to someone else,
-         then that person gets level x-1.  On other channels, where upass is not set,
-        the level stays the same. */
-      int level_increment = *state->chptr->mode.upass ? 1 : 0;
-      /* Someone being opped by a server gets op-level 0 */
-      int old_level = (state->member == NULL) ? -level_increment : OpLevel(state->member);
-      SetOpLevel(member, old_level == MAXOPLEVEL ? MAXOPLEVEL : (old_level + level_increment));
+      /* If being opped by an outsider, get oplevel 0 for an apass
+       *   channel, else MAXOPLEVEL.
+       * Otherwise, if not an apass channel, or state->member has
+       *   MAXOPLEVEL, get oplevel MAXOPLEVEL.
+       * Otherwise, get state->member's oplevel+1.
+       */
+      if (!state->member)
+        SetOpLevel(member, state->chptr->mode.apass[0] ? 0 : MAXOPLEVEL);
+      else if (!state->chptr->mode.apass[0] || OpLevel(state->member) == MAXOPLEVEL)
+        SetOpLevel(member, MAXOPLEVEL);
+      else
+        SetOpLevel(member, OpLevel(state->member) + 1);
     }
 
     /* actually effect the change */
@@ -3156,7 +3178,7 @@ mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
 
   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
     state.banlist[i].next = 0;
-    state.banlist[i].who = 0;
+    state.banlist[i].who[0] = '\0';
     state.banlist[i].when = 0;
     state.banlist[i].flags = 0;
     state.cli_change[i].flag = 0;
@@ -3376,24 +3398,35 @@ joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
        is_local) /* got to remove user here */
       remove_user_from_channel(jbuf->jb_source, chan);
   } else {
+    int oplevel = !chan->mode.apass[0] ? MAXOPLEVEL
+        : (flags & CHFL_CHANNEL_MANAGER) ? 0
+        : 1;
     /* Add user to channel */
     if ((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))
-      add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, 0);
+      add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, oplevel);
     else
-      add_user_to_channel(chan, jbuf->jb_source, flags, 0);
+      add_user_to_channel(chan, jbuf->jb_source, flags, oplevel);
 
     /* send notification to all servers */
     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !is_local)
-      sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
-                           "%H %Tu", chan, chan->creationtime);
+    {
+      if (flags & CHFL_CHANOP) {
+        assert(oplevel == 0 || oplevel == 1);
+        sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
+                              "%u:%H %Tu", oplevel, chan, chan->creationtime);
+      } else
+        sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
+                              "%H %Tu", chan, chan->creationtime);
+    }
 
     if (!((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))) {
       /* Send the notification to the channel */
       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, 0, "%H", chan);
 
       /* send an op, too, if needed */
-      if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE)
-       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_MODE, chan, NULL, 0, "%H +o %C",
+      if (flags & CHFL_CHANOP && (oplevel < MAXOPLEVEL || !MyUser(jbuf->jb_source)))
+       sendcmdto_channel_butserv_butone((chan->mode.apass[0] ? &his : jbuf->jb_source),
+                                         CMD_MODE, chan, NULL, 0, "%H +o %C",
                                         chan, jbuf->jb_source);
     } else if (MyUser(jbuf->jb_source))
       sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
@@ -3477,7 +3510,8 @@ int IsInvited(struct Client* cptr, const void* chptr)
 
 /* RevealDelayedJoin: sends a join for a hidden user */
 
-void RevealDelayedJoin(struct Membership *member) {
+void RevealDelayedJoin(struct Membership *member)
+{
   ClearDelayedJoin(member);
   sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, 0, ":%H",
                                    member->channel);
@@ -3486,18 +3520,19 @@ void RevealDelayedJoin(struct Membership *member) {
 
 /* CheckDelayedJoins: checks and clear +d if necessary */
 
-void CheckDelayedJoins(struct Channel *chan) {
+void CheckDelayedJoins(struct Channel *chan)
+{
   struct Membership *memb2;
-  
+
   if (chan->mode.mode & MODE_WASDELJOINS) {
     for (memb2=chan->members;memb2;memb2=memb2->next_member)
       if (IsDelayedJoin(memb2))
         break;
-    
+
     if (!memb2) {
       /* clear +d */
       chan->mode.mode &= ~MODE_WASDELJOINS;
-      sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan, NULL, 0,
+      sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan, NULL, 0,
                                        "%H -d", chan);
     }
   }