]> jfr.im git - irc/evilnet/x3.git/blobdiff - src/nickserv.c
Merge branch 'master' of github.com:evilnet/x3
[irc/evilnet/x3.git] / src / nickserv.c
index dcce44c10c556eeff9866c5c08f62194d4efbb6a..7435a4528125eb0c0ca3447c50971e332b7ce9cf 100644 (file)
@@ -1,4 +1,3 @@
-
 /* nickserv.c - Nick/authentication service
  * Copyright 2000-2004 srvx Development Team
  *
@@ -19,6 +18,7 @@
  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
  */
 
+#include "base64.h"
 #include "chanserv.h"
 #include "conf.h"
 #include "config.h"
@@ -65,6 +65,8 @@
 #define KEY_HANDLE_EXPIRE_FREQ "handle_expire_freq"
 #define KEY_ACCOUNT_EXPIRE_FREQ "account_expire_freq"
 #define KEY_HANDLE_EXPIRE_DELAY        "handle_expire_delay"
+#define KEY_NICK_EXPIRE_FREQ "nick_expire_freq"
+#define KEY_NICK_EXPIRE_DELAY "nick_expire_delay"
 #define KEY_ACCOUNT_EXPIRE_DELAY "account_expire_delay"
 #define KEY_NOCHAN_HANDLE_EXPIRE_DELAY "nochan_handle_expire_delay"
 #define KEY_NOCHAN_ACCOUNT_EXPIRE_DELAY "nochan_account_expire_delay"
@@ -88,6 +90,7 @@
 #define KEY_ID "id"
 #define KEY_PASSWD "passwd"
 #define KEY_NICKS "nicks"
+#define KEY_NICKS_EX "nicks_ex"
 #define KEY_MASKS "masks"
 #define KEY_SSLFPS "sslfps"
 #define KEY_IGNORES "ignores"
@@ -218,7 +221,7 @@ static const struct message_entry msgtab[] = {
     { "NSMSG_NICK_NOT_REGISTERED", "Nick $b%s$b has not been registered to any account." },
     { "NSMSG_HANDLE_NOT_FOUND", "Could not find your account -- did you register yet?" },
     { "NSMSG_ALREADY_AUTHED", "You are already authed to account $b%s$b; you must reconnect to auth to a different account." },
-    { "NSMSG_USE_AUTHCOOKIE", "Your hostmask is not valid for account $b%1$s$b.  Please use the $bauthcookie$b command to grant yourself access.  (/msg $S authcookie %1$s)" },
+    { "NSMSG_USE_AUTHCOOKIE", "Your hostmask is not valid for account $b%1$s$b.  Please use the $bauthcookie$b command to grant yourself access.  (/msg $N authcookie %1$s)" },
     { "NSMSG_HOSTMASK_INVALID", "Your hostmask is not valid for account $b%s$b." },
     { "NSMSG_USER_IS_SERVICE", "$b%s$b is a network service; you can only use that command on real users." },
     { "NSMSG_USER_PREV_AUTH", "$b%s$b is already authenticated." },
@@ -248,6 +251,7 @@ static const struct message_entry msgtab[] = {
     { "NSMSG_HANDLEINFO_COOKIE_EMAIL", "Cookie: There is currently an email change cookie issued for this account" },
     { "NSMSG_HANDLEINFO_COOKIE_ALLOWAUTH", "Cookie: There is currently an allowauth cookie issued for this account" },
     { "NSMSG_HANDLEINFO_COOKIE_UNKNOWN", "Cookie: There is currently an unknown cookie issued for this account" },
+    { "NSMSG_HANDLEINFO_COOKIE_EMAIL_DATA", "Cookie: New email address: %s" },
     { "NSMSG_HANDLEINFO_INFOLINE", "Infoline: %s" },
     { "NSMSG_HANDLEINFO_FLAGS", "Flags: %s" },
     { "NSMSG_HANDLEINFO_EPITHET", "Epithet: %s" },
@@ -266,7 +270,12 @@ static const struct message_entry msgtab[] = {
     { "NSMSG_HANDLEINFO_DNR", "Do-not-register (by %s): %s" },
     { "NSMSG_USERINFO_AUTHED_AS", "$b%s$b is authenticated to account $b%s$b." },
     { "NSMSG_USERINFO_NOT_AUTHED", "$b%s$b is not authenticated to any account." },
-    { "NSMSG_NICKINFO_OWNER", "Nick $b%s$b is owned by account $b%s$b." },
+    { "NSMSG_NICKINFO_ON", "$bNick Information for %s$b" },
+    { "NSMSG_NICKINFO_END", "----------End of Nick Info-----------" },
+    { "NSMSG_NICKINFO_REGGED", "Registered on: %s" },
+    { "NSMSG_NICKINFO_LASTSEEN", "Last seen: %s" },
+    { "NSMSG_NICKINFO_LASTSEEN_NOW", "Last seen: Right now!" },
+    { "NSMSG_NICKINFO_OWNER", "Account: %s." },
     { "NSMSG_PASSWORD_INVALID", "Incorrect password; please try again." },
     { "NSMSG_PLEASE_SET_EMAIL", "We now require email addresses for users.  Please use the $bset email$b command to set your email address!" },
     { "NSMSG_WEAK_PASSWORD", "WARNING: You are using a password that is considered weak (easy to guess).  It is STRONGLY recommended you change it (now, if not sooner) by typing \"/msg $S@$s PASS oldpass newpass\" (with your current password and a new password)." },
@@ -356,13 +365,13 @@ static const struct message_entry msgtab[] = {
     { "NSMSG_SET_FLAGS", "$bFLAGS:        $b%s" },
     { "NSMSG_SET_EMAIL", "$bEMAIL:        $b%s" },
     { "NSMSG_SET_MAXLOGINS", "$bMAXLOGINS:    $b%d" },
-    { "NSMSG_SET_ADVANCED", "$bADVANCED:      $b%s" },
+    { "NSMSG_SET_ADVANCED", "$bADVANCED:     $b%s" },
     { "NSMSG_SET_LANGUAGE", "$bLANGUAGE:     $b%s" },
     { "NSMSG_SET_LEVEL", "$bLEVEL:        $b%d" },
     { "NSMSG_SET_EPITHET", "$bEPITHET:      $b%s" },
     { "NSMSG_SET_NOTE", "$bNOTE:         $b%s"},
     { "NSMSG_SET_TITLE", "$bTITLE:        $b%s" },
-    { "NSMSG_SET_FAKEHOST", "$bFAKEHOST:    $b%s" },
+    { "NSMSG_SET_FAKEHOST", "$bFAKEHOST:     $b%s" },
 
     { "NSMSG_AUTO_OPER", "You have been auto-opered" },
     { "NSMSG_AUTO_OPER_ADMIN", "You have been auto-admined" },
@@ -479,6 +488,8 @@ register_nick(const char *nick, struct handle_info *owner)
     struct nick_info *ni;
     ni = malloc(sizeof(struct nick_info));
     safestrncpy(ni->nick, nick, sizeof(ni->nick));
+    ni->registered = now;
+    ni->lastseen = now;
     ni->owner = owner;
     ni->next = owner->nicks;
     owner->nicks = ni;
@@ -958,7 +969,7 @@ generate_fakehost(struct handle_info *handle)
         if (data)
             style = atoi(data);
 
-        if (style == 1)
+        if ((style == 1) || (style == 3))
             snprintf(buffer, sizeof(buffer), "%s.%s", handle->handle, hidden_host_suffix);
         else if (style == 2) {
             /* Due to the way fakehost is coded theres no way i can
@@ -967,7 +978,10 @@ generate_fakehost(struct handle_info *handle)
             for (target = handle->users; target; target = target->next_authed)
                break;
 
-            snprintf(buffer, sizeof(buffer), "%s", target->crypthost);
+            if (target)
+               snprintf(buffer, sizeof(buffer), "%s", target->crypthost);
+            else
+               strncpy(buffer, "none", sizeof(buffer));
         }
         return buffer;
     } else if (handle->fakehost[0] == '.') {
@@ -1016,6 +1030,7 @@ set_user_handle_info(struct userNode *user, struct handle_info *hi, int stamp)
 
     if (user->handle_info) {
        struct userNode *other;
+        struct nick_info* ni;
 
        if (IsHelper(user))
             userList_remove(&curr_helpers, user);
@@ -1037,6 +1052,8 @@ set_user_handle_info(struct userNode *user, struct handle_info *hi, int stamp)
             HANDLE_CLEAR_FLAG(user->handle_info, HELPING);
         /* record them as being last seen at this time */
        user->handle_info->lastseen = now;
+        if ((ni = get_nick_info(user->nick)))
+            ni->lastseen = now;
         /* and record their hostmask */
         snprintf(user->handle_info->last_quit_host, sizeof(user->handle_info->last_quit_host), "%s@%s", user->ident, user->hostname);
     }
@@ -1095,8 +1112,10 @@ set_user_handle_info(struct userNode *user, struct handle_info *hi, int stamp)
         }
 
         /* Stop trying to kick this user off their nick */
-        if ((ni = get_nick_info(user->nick)) && (ni->owner == hi))
+        if ((ni = get_nick_info(user->nick)) && (ni->owner == hi)) {
             timeq_del(0, nickserv_reclaim_p, user, TIMEQ_IGNORE_WHEN);
+            ni->lastseen = now;
+        }
     } else {
         /* We cannot clear the user's account ID, unfortunately. */
        user->next_authed = NULL;
@@ -1117,7 +1136,7 @@ nickserv_register(struct userNode *user, struct userNode *settee, const char *ha
 {
     struct handle_info *hi;
     struct nick_info *ni;
-    char crypted[MD5_CRYPT_LENGTH];
+    char crypted[MD5_CRYPT_LENGTH] = "";
 
     if ((hi = dict_find(nickserv_handle_dict, handle, NULL))) {
         if(user)
@@ -1132,14 +1151,17 @@ nickserv_register(struct userNode *user, struct userNode *settee, const char *ha
         return 0;
     }
 
-    if (!is_secure_password(handle, passwd, user))
-        return 0;
+    if (passwd)
+    {
+        if (!is_secure_password(handle, passwd, user))
+            return 0;
 
-    cryptpass(passwd, crypted);
+        cryptpass(passwd, crypted);
+    }
 #ifdef WITH_LDAP
     if(nickserv_conf.ldap_enable && nickserv_conf.ldap_admin_dn) {
         int rc;
-        rc = ldap_do_add(handle, (no_auth ? NULL : crypted), NULL);
+        rc = ldap_do_add(handle, (no_auth || !passwd ? NULL : crypted), NULL);
         if(LDAP_SUCCESS != rc && LDAP_ALREADY_EXISTS != rc ) {
            if(user)
              send_message(user, nickserv, "NSMSG_LDAP_FAIL", ldap_err2string(rc));
@@ -1526,7 +1548,7 @@ static NICKSERV_FUNC(cmd_oregister)
     char* mask = NULL;
     char* nick = NULL;
 
-    NICKSERV_MIN_PARMS(2);
+    NICKSERV_MIN_PARMS(3);
    
     account = argv[1];
     pass = argv[2];
@@ -1611,6 +1633,8 @@ static NICKSERV_FUNC(cmd_oregister)
             string_list_append(hi->masks, mask_canonicalized);
     }
 
+    argv[2] = "****";
+
     if (nickserv_conf.sync_log)
         SyncLog("REGISTER %s %s %s %s", hi->handle, hi->passwd, email ? email : "@", user->info); /* Send just @ for email if none */
     return 1;
@@ -1754,6 +1778,8 @@ static NICKSERV_FUNC(cmd_handleinfo)
         default: type = "NSMSG_HANDLEINFO_COOKIE_UNKNOWN"; break;
         }
         reply(type);
+        if (IsOper(user) && (hi->cookie->type == EMAIL_CHANGE))
+            reply("NSMSG_HANDLEINFO_COOKIE_EMAIL_DATA", hi->cookie->data);
     }
 
     if (hi->flags) {
@@ -1945,13 +1971,29 @@ static NICKSERV_FUNC(cmd_userinfo)
 static NICKSERV_FUNC(cmd_nickinfo)
 {
     struct nick_info *ni;
+    char buff[400];
 
     NICKSERV_MIN_PARMS(2);
     if (!(ni = get_nick_info(argv[1]))) {
        reply("MSG_NICK_UNKNOWN", argv[1]);
        return 0;
     }
-    reply("NSMSG_NICKINFO_OWNER", ni->nick, ni->owner->handle);
+
+    reply("NSMSG_NICKINFO_ON", ni->nick);
+    reply("MSG_BAR");
+    reply("NSMSG_NICKINFO_REGGED", ctime(&ni->registered));
+
+    if (!GetUserH(ni->nick)) {
+        intervalString(buff, now - ni->lastseen, user->handle_info);
+        reply("NSMSG_NICKINFO_LASTSEEN", buff);
+    } else {
+        reply("NSMSG_NICKINFO_LASTSEEN_NOW");
+    }
+
+    reply("NSMSG_NICKINFO_OWNER", ni->owner->handle);
+
+    reply("NSMSG_NICKINFO_END");
+
     return 1;
 }
 
@@ -2033,6 +2075,27 @@ reg_failpw_func(failpw_func_t func, void *extra)
     failpw_func_list_extra[failpw_func_used++] = extra;
 }
 
+/*
+ * Return hi for the first handle that has a matching SSL fingerprint.
+ */
+struct handle_info *find_handleinfo_by_sslfp(char *sslfp)
+{
+    dict_iterator_t it;
+    struct handle_info *hi;
+    unsigned int ii = 0;;
+
+    for (it = dict_first(nickserv_handle_dict); it; it = iter_next(it)) {
+        hi = iter_data(it);
+        for (ii=0; ii<hi->sslfps->used; ii++) {
+            if (!irccasecmp(sslfp, hi->sslfps->list[ii])) {
+                return hi;
+            }
+        }
+    }
+
+    return NULL;
+}
+
 /*
  * Return hi if the handle/pass pair matches, NULL if it doesnt.
  *
@@ -2044,17 +2107,23 @@ struct handle_info *loc_auth(char *sslfp, char *handle, char *password, char *us
     int wildmask = 0, auth = 0;
     int used, maxlogins;
     unsigned int ii;
-    struct handle_info *hi;
+    struct handle_info *hi = NULL;
     struct userNode *other;
 #ifdef WITH_LDAP
     int ldap_result = LDAP_SUCCESS;
     char *email = NULL;
 #endif
     
-    hi = dict_find(nickserv_handle_dict, handle, NULL);
+    if (handle != NULL)
+        hi = dict_find(nickserv_handle_dict, handle, NULL);
+    if (!hi && (sslfp != NULL)) {
+        hi = find_handleinfo_by_sslfp(sslfp);
+        if (!handle && (hi != NULL))
+            handle = hi->handle;
+    }
     
 #ifdef WITH_LDAP
-    if (nickserv_conf.ldap_enable) {
+    if (nickserv_conf.ldap_enable && (password != NULL)) {
         ldap_result = ldap_check_auth(handle, password);
         if (!hi && (ldap_result != LDAP_SUCCESS))
             return NULL;
@@ -2136,16 +2205,37 @@ struct handle_info *loc_auth(char *sslfp, char *handle, char *password, char *us
      */
     if(userhost) {
         char *buf;
-        char *ident;
-        char *realhost;
-        char *ip;
+        char *ident = NULL;
+        char *realhost = NULL;
+        char *ip = NULL;
         char *uh;
         char *ui;
+        char *c;
+        int bracket = 0;
 
         buf = strdup(userhost);
-        ident = mysep(&buf, "@");
-        realhost = mysep(&buf, ":");
-        ip = mysep(&buf, ":");
+
+        ident = buf;
+        for (c = buf; *c; c++) {
+            if ((realhost == NULL) && (*c == '@')) {
+                *c++ = '\0';
+                if (*c == '[') {
+                    bracket = 1;
+                    *c++ = '\0';
+                }
+                realhost = c;
+            } else if (bracket && (ip == NULL) && (*c == ']')) {
+                bracket = 0;
+                *c = '\0';
+            } else if (!bracket && (ip == NULL) && (*c == ':')) {
+                *c++ = '\0';
+                ip = c;
+                break;
+            }
+        }
+
+        log_module(NS_LOG, LOG_DEBUG, "LOC: ident=%s host=%s ip=%s", ident, realhost, ip);
+
         if(!ip || !realhost || !ident) {
             free(buf);
             return NULL; /* Invalid AC request, just quit */
@@ -2251,7 +2341,7 @@ static NICKSERV_FUNC(cmd_auth)
     }
     
 #ifdef WITH_LDAP
-    if(strchr(argv[1], '<') || strchr(handle, '>')) {
+    if(strchr(handle, '<') || strchr(handle, '>')) {
         reply("NSMSG_NO_ANGLEBRACKETS");
         return 0;
     }
@@ -2287,7 +2377,7 @@ static NICKSERV_FUNC(cmd_auth)
             * create the account.
             */
              char *mask;
-             if(!(hi = nickserv_register(user, user, argv[1], argv[2], 0))) {
+             if(!(hi = nickserv_register(user, user, handle, passwd, 0))) {
                 reply("NSMSG_UNABLE_TO_ADD");
                 return 0; /* couldn't add the user for some reason */
              }
@@ -4040,14 +4130,16 @@ nickserv_saxdb_write(struct saxdb_context *ctx) {
         if (hi->maxlogins)
             saxdb_write_int(ctx, KEY_MAXLOGINS, hi->maxlogins);
         if (hi->nicks) {
-            struct string_list *slist;
             struct nick_info *ni;
 
-            slist = alloc_string_list(nickserv_conf.nicks_per_handle);
-            for (ni = hi->nicks; ni; ni = ni->next) string_list_append(slist, ni->nick);
-            saxdb_write_string_list(ctx, KEY_NICKS, slist);
-            free(slist->list);
-            free(slist);
+            saxdb_start_record(ctx, KEY_NICKS_EX, 0);
+            for (ni = hi->nicks; ni; ni = ni->next) {
+                saxdb_start_record(ctx, ni->nick, 0);
+                saxdb_write_int(ctx, KEY_REGISTER_ON, ni->registered);
+                saxdb_write_int(ctx, KEY_LAST_SEEN, ni->lastseen);
+                saxdb_end_record(ctx);
+            }
+            saxdb_end_record(ctx);
         }
         if (hi->opserv_level)
             saxdb_write_int(ctx, KEY_OPSERV_LEVEL, hi->opserv_level);
@@ -4706,6 +4798,8 @@ nickserv_db_read_handle(char *handle, dict_t obj)
     struct handle_info *hi;
     struct userNode *authed_users;
     struct userData *channel_list;
+    struct dict *obj2;
+    dict_iterator_t it;
     unsigned long int id;
     unsigned int ii;
     dict_t subdb;
@@ -4763,10 +4857,39 @@ nickserv_db_read_handle(char *handle, dict_t obj)
     hi->karma = str ? strtoul(str, NULL, 0) : 0;
     /* We want to read the nicks even if disable_nicks is set.  This is so
      * that we don't lose the nick data entirely. */
-    slist = database_get_data(obj, KEY_NICKS, RECDB_STRING_LIST);
-    if (slist) {
-        for (ii=0; ii<slist->used; ii++)
-            register_nick(slist->list[ii], hi);
+    obj2 = database_get_data(obj, KEY_NICKS_EX, RECDB_OBJECT);
+    for(it = dict_first(obj2); it; it = iter_next(it))
+    {
+        struct record_data *rd = iter_data(it);
+        struct nick_info* ni;
+
+        register_nick(iter_key(it), hi);
+        ni = get_nick_info(iter_key(it));
+
+        if (!(ni))
+            continue;
+
+        str = database_get_data(rd->d.object, KEY_REGISTER_ON, RECDB_QSTRING);
+        ni->registered = str ? (time_t)strtoul(str, NULL, 0) : now;
+        str = database_get_data(rd->d.object, KEY_LAST_SEEN, RECDB_QSTRING);
+        ni->lastseen = str ? (time_t)strtoul(str, NULL, 0) : ni->registered;
+    }
+    if (!obj2) {
+        slist = database_get_data(obj, KEY_NICKS, RECDB_STRING_LIST);
+        if (slist) {
+            for (ii=0; ii<slist->used; ii++) {
+                struct nick_info* ni;
+
+                register_nick(slist->list[ii], hi);
+                ni = get_nick_info(slist->list[ii]);
+
+                if (!(ni))
+                    continue;
+
+                ni->registered = hi->registered;
+                ni->lastseen = ni->registered;
+            }
+        }
     }
     str = database_get_data(obj, KEY_FLAGS, RECDB_QSTRING);
     if (str) {
@@ -4916,6 +5039,36 @@ expire_handles(UNUSED_ARG(void *data))
         timeq_add(now + nickserv_conf.handle_expire_frequency, expire_handles, NULL);
 }
 
+static void
+expire_nicks(UNUSED_ARG(void *data))
+{
+    dict_iterator_t it, next;
+    time_t expiry = nickserv_conf.nick_expire_delay;
+    struct nick_info *ni;
+    struct userNode *ui;
+
+    if (!(nickserv_conf.expire_nicks))
+        return;
+
+    for (it=dict_first(nickserv_nick_dict); it; it=next) {
+        next = iter_next(it);
+        ni = iter_data(it);
+        if ((ni->owner->opserv_level > 0)
+            || ((ui = GetUserH(ni->nick)) && (ui->handle_info) && (ui->handle_info == ni->owner))
+            || HANDLE_FLAGGED(ni->owner, FROZEN)
+            || HANDLE_FLAGGED(ni->owner, NODELETE)) {
+            continue;
+        }
+        if ((now - ni->lastseen) > expiry) {
+            log_module(NS_LOG, LOG_INFO, "Expiring nick %s for inactivity.", ni->nick);
+            delete_nick(ni);
+        }
+    }
+
+    if (nickserv_conf.nick_expire_frequency && nickserv_conf.expire_nicks)
+        timeq_add(now + nickserv_conf.nick_expire_frequency, expire_nicks, NULL);
+}
+
 static void
 nickserv_load_dict(const char *fname)
 {
@@ -5037,6 +5190,7 @@ nickserv_conf_read(void)
     str = database_get_data(conf_node, "default_maxlogins", RECDB_QSTRING);
     nickserv_conf.default_maxlogins = str ? strtoul(str, NULL, 0) : 2;
     str = database_get_data(conf_node, "hard_maxlogins", RECDB_QSTRING);
+    nickserv_conf.hard_maxlogins = str ? strtoul(str, NULL, 0) : 10;
     str = database_get_data(conf_node, KEY_OUNREGISTER_INACTIVE, RECDB_QSTRING);
     nickserv_conf.ounregister_inactive = str ? ParseInterval(str) : 86400*28;
     str = database_get_data(conf_node, KEY_OUNREGISTER_FLAGS, RECDB_QSTRING);
@@ -5049,7 +5203,6 @@ nickserv_conf_read(void)
         if(pos)
             nickserv_conf.ounregister_flags |= 1 << (pos - 1);
     }
-    nickserv_conf.hard_maxlogins = str ? strtoul(str, NULL, 0) : 10;
     if (!nickserv_conf.disable_nicks) {
         str = database_get_data(conf_node, "reclaim_action", RECDB_QSTRING);
         nickserv_conf.reclaim_action = str ? reclaim_action_from_string(str) : RECLAIM_NONE;
@@ -5059,6 +5212,12 @@ nickserv_conf_read(void)
         nickserv_conf.auto_reclaim_action = str ? reclaim_action_from_string(str) : RECLAIM_NONE;
         str = database_get_data(conf_node, "auto_reclaim_delay", RECDB_QSTRING);
         nickserv_conf.auto_reclaim_delay = str ? ParseInterval(str) : 0;
+        str = database_get_data(conf_node, KEY_NICK_EXPIRE_FREQ, RECDB_QSTRING);
+        nickserv_conf.nick_expire_frequency = str ? ParseInterval(str) : 86400;
+        str = database_get_data(conf_node, KEY_NICK_EXPIRE_DELAY, RECDB_QSTRING);
+        nickserv_conf.nick_expire_delay = str ? ParseInterval(str) : 86400*30;
+        str = database_get_data(conf_node, "expire_nicks", RECDB_QSTRING);
+        nickserv_conf.expire_nicks = str ? enabled_string(str) : 0;
     }
     child = database_get_data(conf_node, KEY_FLAG_LEVELS, RECDB_OBJECT);
     for (it=dict_first(child); it; it=iter_next(it)) {
@@ -5230,6 +5389,10 @@ nickserv_reclaim(struct userNode *user, struct nick_info *ni, enum reclaim_actio
 
     assert(user);
     assert(ni);
+
+    if (IsLocal(user))
+        return;
+
     switch (action) {
     case RECLAIM_NONE:
         /* do nothing */
@@ -5310,6 +5473,39 @@ ctime(&hi->registered));
     log_module(MAIN_LOG, LOG_WARNING, "Using non-P10 code in accounts, not tested at all!");
 #endif
 
+#ifdef WITH_LDAP
+    if(!hi && nickserv_conf.ldap_enable && nickserv_conf.ldap_autocreate &&
+       (ldap_user_exists(stamp) == LDAP_SUCCESS)) {
+        int rc = 0;
+        int cont = 1;
+        char *email = NULL;
+        char *mask;
+
+        /* First attempt to get the email address from LDAP */
+        if((rc = ldap_get_user_info(stamp, &email) != LDAP_SUCCESS))
+            if(nickserv_conf.email_required)
+                cont = 0;
+
+        /* Now try to register the handle */
+        if (cont && (hi = nickserv_register(user, user, stamp, NULL, 1))) {
+            if(nickserv_conf.default_hostmask)
+                mask = "*@*";
+            else
+                mask = generate_hostmask(user, GENMASK_OMITNICK|GENMASK_NO_HIDING|GENMASK_ANY_IDENT);
+
+            if(mask) {
+                char* mask_canonicalized = canonicalize_hostmask(strdup(mask));
+                string_list_append(hi->masks, mask_canonicalized);
+            }
+
+            if(email) {
+                nickserv_set_email_addr(hi, email);
+                free(email);
+            }
+        }
+    }
+#endif
+
     if (hi) {
         if (HANDLE_FLAGGED(hi, SUSPENDED)) {
             return;
@@ -5367,10 +5563,325 @@ nickserv_define_func(const char *name, modcmd_func_t func, int min_level, int mu
     }
 }
 
+#define SDFLAG_STALE 0x01  /**< SASL session data is stale, delete on next pass. */
+
+struct SASLSession
+{
+    struct SASLSession *next;
+    struct SASLSession *prev;
+    struct server* source;
+    char *buf, *p;
+    int buflen;
+    char uid[128];
+    char mech[10];
+    char *sslclifp;
+    char *hostmask;
+    int flags;
+};
+
+struct SASLSession *saslsessions = NULL;
+
+void
+sasl_delete_session(struct SASLSession *session)
+{
+    if (!session)
+        return;
+
+    if (session->buf)
+        free(session->buf);
+    session->buf = NULL;
+
+    if (session->sslclifp)
+        free(session->sslclifp);
+    session->sslclifp = NULL;
+
+    if (session->hostmask)
+        free(session->hostmask);
+    session->hostmask = NULL;
+
+    if (session->next)
+        session->next->prev = session->prev;
+    if (session->prev)
+        session->prev->next = session->next;
+    else
+        saslsessions = session->next;
+
+    free(session);
+}
+
+void
+sasl_delete_stale(UNUSED_ARG(void *data))
+{
+    int delcount = 0;
+    int remcount = 0;
+    struct SASLSession *sess = NULL;
+    struct SASLSession *nextsess = NULL;
+
+    log_module(NS_LOG, LOG_DEBUG, "SASL: Checking for stale sessions");
+
+    for (sess = saslsessions; sess; sess = nextsess)
+    {
+        nextsess = sess->next;
+
+        if (sess->flags & SDFLAG_STALE)
+        {
+            delcount++;
+            sasl_delete_session(sess);
+        }
+        else
+        {
+            remcount++;
+            sess->flags |= SDFLAG_STALE;
+        }
+    }
+
+    if (delcount)
+        log_module(NS_LOG, LOG_DEBUG, "SASL: Deleted %d stale sessions, %d remaining", delcount, remcount);
+    if (remcount)
+        timeq_add(now + 30, sasl_delete_stale, NULL);
+}
+
+struct SASLSession*
+sasl_get_session(const char *uid)
+{
+    struct SASLSession *sess;
+
+    for (sess = saslsessions; sess; sess = sess->next)
+    {
+        if (!strncmp(sess->uid, uid, 128))
+        {
+            log_module(NS_LOG, LOG_DEBUG, "SASL: Found session for %s", sess->uid);
+            return sess;
+        }
+    }
+
+    sess = malloc(sizeof(struct SASLSession));
+    memset(sess, 0, sizeof(struct SASLSession));
+
+    strncpy(sess->uid, uid, 128);
+
+    if (!saslsessions)
+        timeq_add(now + 30, sasl_delete_stale, NULL);
+
+    if (saslsessions)
+        saslsessions->prev = sess;
+    sess->next = saslsessions;
+    saslsessions = sess;
+
+    log_module(NS_LOG, LOG_DEBUG, "SASL: Created session for %s", sess->uid);
+    return sess;
+}
+
+void
+sasl_packet(struct SASLSession *session)
+{
+    log_module(NS_LOG, LOG_DEBUG, "SASL: Got packet containing: %s", session->buf);
+
+    if (!session->mech[0])
+    {
+        log_module(NS_LOG, LOG_DEBUG, "SASL: No mechanism stored yet, using %s", session->buf);
+        if (strcmp(session->buf, "PLAIN") && (strcmp(session->buf, "EXTERNAL") || !session->sslclifp)) {
+            if (!session->sslclifp)
+                irc_sasl(session->source, session->uid, "M", "PLAIN");
+            else
+                irc_sasl(session->source, session->uid, "M", "PLAIN,EXTERNAL");
+            irc_sasl(session->source, session->uid, "D", "F");
+            sasl_delete_session(session);
+            return;
+        }
+
+        strncpy(session->mech, session->buf, 10);
+        irc_sasl(session->source, session->uid, "C", "+");
+    }
+    else if (!strcmp(session->mech, "EXTERNAL"))
+    {
+        char *raw = NULL;
+        size_t rawlen = 0;
+        char *authzid = NULL;
+        struct handle_info *hi = NULL;
+        static char buffer[256];
+
+        base64_decode_alloc(session->buf, session->buflen, &raw, &rawlen);
+
+        if (rawlen != 0)
+            authzid = raw;
+
+        log_module(NS_LOG, LOG_DEBUG, "SASL: Checking supplied credentials");
+
+        if (!session->sslclifp) {
+            log_module(NS_LOG, LOG_DEBUG, "SASL: Incomplete credentials supplied");
+            irc_sasl(session->source, session->uid, "D", "F");
+        } else {
+            if (!(hi = loc_auth(session->sslclifp, authzid, NULL, session->hostmask)))
+            {
+                log_module(NS_LOG, LOG_DEBUG, "SASL: Invalid credentials supplied");
+                irc_sasl(session->source, session->uid, "D", "F");
+            }
+            else
+            {
+                snprintf(buffer, sizeof(buffer), "%s "FMT_TIME_T, hi->handle, hi->registered);
+                log_module(NS_LOG, LOG_DEBUG, "SASL: Valid credentials supplied");
+                irc_sasl(session->source, session->uid, "L", buffer);
+                irc_sasl(session->source, session->uid, "D", "S");
+            }
+        }
+
+        sasl_delete_session(session);
+
+        free(raw);
+        return;
+    }
+    else
+    {
+        char *raw = NULL;
+        size_t rawlen = 0;
+        char *authzid = NULL;
+        char *authcid = NULL;
+        char *passwd = NULL;
+        char *r = NULL;
+        unsigned int i = 0, c = 0;
+        struct handle_info *hi = NULL;
+        struct handle_info *hii = NULL;
+        static char buffer[256];
+
+        base64_decode_alloc(session->buf, session->buflen, &raw, &rawlen);
+
+        raw = (char *)realloc(raw, rawlen+1);
+       raw[rawlen] = '\0';
+
+        authzid = raw;
+        r = raw;
+        for (i=0; i<rawlen; i++)
+        {
+            if (!*r++)
+            {
+                if (c++)
+                    passwd = r;
+                else
+                    authcid = r;
+            }
+        }
+
+        log_module(NS_LOG, LOG_DEBUG, "SASL: Checking supplied credentials");
+
+        if (c != 2)
+        {
+            log_module(NS_LOG, LOG_DEBUG, "SASL: Incomplete credentials supplied");
+            irc_sasl(session->source, session->uid, "D", "F");
+        }
+        else
+        {
+            if (!(hi = loc_auth(session->sslclifp, authcid, passwd, session->hostmask)))
+            {
+                log_module(NS_LOG, LOG_DEBUG, "SASL: Invalid credentials supplied");
+                irc_sasl(session->source, session->uid, "D", "F");
+            }
+            else
+            {
+                if (*authzid && irccasecmp(authzid, authcid) && HANDLE_FLAGGED(hi, IMPERSONATE))
+                {
+                    hii = hi;
+                    hi = get_handle_info(authzid);
+                }
+                if (hi)
+                {
+                    if (hii)
+                    {
+                        log_module(NS_LOG, LOG_DEBUG, "SASL: %s is ipersonating %s", hii->handle, hi->handle);
+                        snprintf(buffer, sizeof(buffer), "%s "FMT_TIME_T, hii->handle, hii->registered);
+                        irc_sasl(session->source, session->uid, "I", buffer);
+                    }
+                    log_module(NS_LOG, LOG_DEBUG, "SASL: Valid credentials supplied");
+                    snprintf(buffer, sizeof(buffer), "%s "FMT_TIME_T, hi->handle, hi->registered);
+                    irc_sasl(session->source, session->uid, "L", buffer);
+                    irc_sasl(session->source, session->uid, "D", "S");
+                }
+                else
+                {
+                    log_module(NS_LOG, LOG_DEBUG, "SASL: Invalid credentials supplied");
+                    irc_sasl(session->source, session->uid, "D", "F");
+                }
+            }
+        }
+
+        sasl_delete_session(session);
+
+        free(raw);
+        return;
+    }
+
+    /* clear stale state */
+    session->flags &= ~SDFLAG_STALE;
+}
+
+void
+handle_sasl_input(struct server* source ,const char *uid, const char *subcmd, const char *data, const char *ext, UNUSED_ARG(void *extra))
+{
+    struct SASLSession* sess = sasl_get_session(uid);
+    int len = strlen(data);
+
+    sess->source = source;
+
+    if (!strcmp(subcmd, "D"))
+    {
+        sasl_delete_session(sess);
+        return;
+    }
+
+    if (!strcmp(subcmd, "H")) {
+       log_module(NS_LOG, LOG_DEBUG, "SASL: Storing host mask %s", data);
+       sess->hostmask = strdup(data);
+       return ;
+    }
+
+    if (strcmp(subcmd, "S") && strcmp(subcmd, "C"))
+        return;
+
+    if (len == 0)
+        return;
+
+    if (sess->p == NULL)
+    {
+        sess->buf = (char *)malloc(len + 1);
+        sess->p = sess->buf;
+        sess->buflen = len;
+    }
+    else
+    {
+        if (sess->buflen + len + 1 > 8192) /* This is a little much... */
+        {
+            irc_sasl(source, uid, "D", "F");
+            sasl_delete_session(sess);
+            return;
+        }
+
+        sess->buf = (char *)realloc(sess->buf, sess->buflen + len + 1);
+        sess->p = sess->buf + sess->buflen;
+        sess->buflen += len;
+    }
+
+    memcpy(sess->p, data, len);
+    sess->buf[len] = '\0';
+
+    if (ext != NULL)
+        sess->sslclifp = strdup(ext);
+
+    /* Messages not exactly 400 bytes are the end of a packet. */
+    if(len < 400)
+    {
+        sasl_packet(sess);
+        sess->buflen = 0;
+        if (sess->buf != NULL)
+          free(sess->buf);
+        sess->buf = sess->p = NULL;
+    }
+}
+
 static void
 nickserv_db_cleanup(UNUSED_ARG(void* extra))
 {
     unreg_del_user_func(nickserv_remove_user, NULL);
+    unreg_sasl_input_func(handle_sasl_input, NULL);
     userList_clean(&curr_helpers);
     policer_params_delete(nickserv_conf.auth_policer_params);
     dict_delete(nickserv_handle_dict);
@@ -5445,12 +5956,16 @@ init_nickserv(const char *nick)
     reg_del_user_func(nickserv_remove_user, NULL);
     reg_account_func(handle_account);
     reg_auth_func(handle_loc_auth_oper, NULL);
+    reg_sasl_input_func(handle_sasl_input, NULL);
 
     /* set up handle_inverse_flags */
     memset(handle_inverse_flags, 0, sizeof(handle_inverse_flags));
     for (i=0; handle_flags[i]; i++) {
         handle_inverse_flags[(unsigned char)handle_flags[i]] = i + 1;
         flag_access_levels[i] = 0;
+        /* ensure flag I requires a minimum of 999 if not set in the config */
+        if ((unsigned char)handle_flags[i] == 'I')
+            flag_access_levels[i] = 999;
     }
 
     conf_register_reload(nickserv_conf_read);
@@ -5565,6 +6080,8 @@ init_nickserv(const char *nick)
     reg_exit_func(nickserv_db_cleanup, NULL);
     if(nickserv_conf.handle_expire_frequency)
         timeq_add(now + nickserv_conf.handle_expire_frequency, expire_handles, NULL);
+    if(nickserv_conf.nick_expire_frequency && nickserv_conf.expire_nicks)
+        timeq_add(now + nickserv_conf.nick_expire_frequency, expire_nicks, NULL);
 
     if(autojoin_channels && nickserv) {
         for (i = 0; i < autojoin_channels->used; i++) {
@@ -5572,6 +6089,7 @@ init_nickserv(const char *nick)
             AddChannelUser(nickserv, chan)->modes |= MODE_CHANOP;
         }
     }
+
 #ifdef WITH_LDAP
     ldap_do_init(nickserv_conf);
 #endif