--- main/manager.c	2007-07-20 23:54:10.000000000 +0400
+++ main/manager.c	2007-09-05 11:12:01.000000000 +0400
@@ -23,13 +23,13 @@
  * \author Mark Spencer <markster@digium.com>
  *
  * Channel Management and more
- * 
+ *
  * \ref amiconf
  */
 
-/*! \addtogroup Group_AMI AMI functions 
+/*! \addtogroup Group_AMI AMI functions
 */
-/*! @{ 
+/*! @{
  Doxygen group */
 
 #include "asterisk.h"
@@ -215,7 +215,7 @@
 
 	if (ast_strlen_zero(res))
 		ast_copy_string(res, "<none>", reslen);
-	
+
 	return res;
 }
 
@@ -265,7 +265,7 @@
 			strcpy(*dst, "&amp;");
 			(*dst) += 5;
 			*maxlen -= 5;
-			break;		
+			break;
 		default:
 			*(*dst)++ = lower ? tolower(*src) : *src;
 			(*maxlen)--;
@@ -287,11 +287,11 @@
 	int escaped = 0;
 	int inobj = 0;
 	int x;
-	
+
 	for (v = vars; v; v = v->next) {
 		if (!dest && !strcasecmp(v->name, "ajaxdest"))
 			dest = v->value;
-		else if (!objtype && !strcasecmp(v->name, "ajaxobjtype")) 
+		else if (!objtype && !strcasecmp(v->name, "ajaxobjtype"))
 			objtype = v->value;
 	}
 	if (!dest)
@@ -336,7 +336,7 @@
 					ast_build_string(&tmp, &len, "<response type='object' id='%s'><%s", dest, objtype);
 					inobj = 1;
 				}
-				ast_build_string(&tmp, &len, " ");				
+				ast_build_string(&tmp, &len, " ");
 				xml_copy_escape(&tmp, &len, var, 1);
 				ast_build_string(&tmp, &len, "='");
 				xml_copy_escape(&tmp, &len, val, 0);
@@ -423,7 +423,7 @@
 	va_start(ap, fmt);
 	ast_dynamic_str_thread_set_va(&buf, 0, &astman_append_buf, fmt, ap);
 	va_end(ap);
-	
+
 	if (s->fd > -1)
 		ast_carefulwrite(s->fd, buf->str, strlen(buf->str), s->writetimeout);
 	else {
@@ -432,7 +432,7 @@
 			return;
 		}
 
-		ast_dynamic_str_append(&s->outputstr, 0, "%s", buf->str);	
+		ast_dynamic_str_append(&s->outputstr, 0, "%s", buf->str);
 	}
 
 	ast_mutex_unlock(&s->__lock);
@@ -531,7 +531,7 @@
 }
 
 
-/*! \brief  CLI command 
+/*! \brief  CLI command
 	Should change to "manager show commands" */
 static int handle_showmancmds(int fd, int argc, char *argv[])
 {
@@ -541,12 +541,12 @@
 
 	ast_cli(fd, format, "Action", "Privilege", "Synopsis");
 	ast_cli(fd, format, "------", "---------", "--------");
-	
+
 	ast_rwlock_rdlock(&actionlock);
 	for (cur = first_action; cur; cur = cur->next) /* Walk the list of actions */
 		ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
 	ast_rwlock_unlock(&actionlock);
-	
+
 	return RESULT_SUCCESS;
 }
 
@@ -558,7 +558,7 @@
 	char *format = "  %-15.15s  %-15.15s\n";
 
 	ast_cli(fd, format, "Username", "IP Address");
-	
+
 	AST_LIST_LOCK(&sessions);
 	AST_LIST_TRAVERSE(&sessions, s, list)
 		ast_cli(fd, format,s->username, ast_inet_ntoa(s->sin.sin_addr));
@@ -567,8 +567,8 @@
 	return RESULT_SUCCESS;
 }
 
-/*! \brief CLI command show manager connected */
-/* Should change to "manager show connected" */
+/*! \brief CLI command show manager eventq */
+/* Should change to "manager show eventq" */
 static int handle_showmaneventq(int fd, int argc, char *argv[])
 {
 	struct eventqent *s;
@@ -584,20 +584,20 @@
 	return RESULT_SUCCESS;
 }
 
-static char showmancmd_help[] = 
+static char showmancmd_help[] =
 "Usage: manager show command <actionname>\n"
 "	Shows the detailed description for a specific Asterisk manager interface command.\n";
 
-static char showmancmds_help[] = 
+static char showmancmds_help[] =
 "Usage: manager show commands\n"
 "	Prints a listing of all the available Asterisk manager interface commands.\n";
 
-static char showmanconn_help[] = 
+static char showmanconn_help[] =
 "Usage: manager show connected\n"
 "	Prints a listing of the users that are currently connected to the\n"
 "Asterisk manager interface.\n";
 
-static char showmaneventq_help[] = 
+static char showmaneventq_help[] =
 "Usage: manager show eventq\n"
 "	Prints a listing of all events pending in the Asterisk manger\n"
 "event queue.\n";
@@ -682,10 +682,19 @@
 static void destroy_session(struct mansession *s)
 {
 	AST_LIST_LOCK(&sessions);
+
+	struct eventqent *eqe;
+	while ((s->eventq)&&(s->eventq->next)) {
+		eqe = s->eventq->next;
+		unuse_eventqent(s->eventq);
+		s->eventq = eqe;
+	};
+
 	AST_LIST_REMOVE(&sessions, s, list);
 	AST_LIST_UNLOCK(&sessions);
 
 	ast_atomic_fetchadd_int(&num_sessions, -1);
+
 	free_session(s);
 }
 
@@ -710,12 +719,12 @@
 	struct ast_variable *head = NULL, *cur;
 	char *var, *val;
 
-	char *parse;    
+	char *parse;
 	AST_DECLARE_APP_ARGS(args,
 		AST_APP_ARG(vars)[32];
 	);
 
-	varlen = strlen("Variable: ");	
+	varlen = strlen("Variable: ");
 
 	for (x = 0; x < m->hdrcount; x++) {
 		if (strncasecmp("Variable: ", m->headers[x], varlen))
@@ -786,7 +795,7 @@
    ast_instring("this|that|more","this",',') == 1;
 
    feel free to move this to app.c -anthm */
-static int ast_instring(const char *bigstr, const char *smallstr, char delim) 
+static int ast_instring(const char *bigstr, const char *smallstr, char delim)
 {
 	const char *val = bigstr, *next;
 
@@ -815,11 +824,11 @@
 		if (ast_instring(instr, perms[x].label, ','))
 			ret |= perms[x].num;
 	}
-	
+
 	return ret;
 }
 
-static int ast_is_number(const char *string) 
+static int ast_is_number(const char *string)
 {
 	int ret = 1, x = 0;
 
@@ -832,14 +841,14 @@
 			break;
 		}
 	}
-	
+
 	return ret ? atoi(string) : 0;
 }
 
-static int strings_to_mask(const char *string) 
+static int strings_to_mask(const char *string)
 {
 	int x, ret = -1;
-	
+
 	x = ast_is_number(string);
 
 	if (x)
@@ -851,12 +860,12 @@
 	else if (ast_true(string)) {
 		ret = 0;
 		for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
-			ret |= perms[x].num;		
+			ret |= perms[x].num;
 	} else {
 		ret = 0;
 		for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
-			if (ast_instring(string, perms[x].label, ',')) 
-				ret |= perms[x].num;		
+			if (ast_instring(string, perms[x].label, ','))
+				ret |= perms[x].num;
 		}
 	}
 
@@ -864,7 +873,7 @@
 }
 
 /*! \brief
-   Rather than braindead on,off this now can also accept a specific int mask value 
+   Rather than braindead on,off this now can also accept a specific int mask value
    or a ',' delim list of mask strings (the same as manager.conf) -anthm
 */
 static int set_eventmask(struct mansession *s, const char *eventmask)
@@ -872,10 +881,10 @@
 	int maskint = strings_to_mask(eventmask);
 
 	ast_mutex_lock(&s->__lock);
-	if (maskint >= 0)	
+	if (maskint >= 0)
 		s->send_events = maskint;
 	ast_mutex_unlock(&s->__lock);
-	
+
 	return maskint;
 }
 
@@ -888,7 +897,7 @@
 	const char *authtype = astman_get_header(m, "AuthType");
 	const char *key = astman_get_header(m, "Key");
 	const char *events = astman_get_header(m, "Events");
-	
+
 	cfg = ast_config_load("manager.conf");
 	if (!cfg)
 		return -1;
@@ -923,7 +932,7 @@
 						else
 							s->writetimeout = val;
 					}
-				    		
+
 				}
 				if (ha && !ast_apply_ha(ha, &(s->sin))) {
 					ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
@@ -933,7 +942,7 @@
 				} else if (ha)
 					ast_free_ha(ha);
 				if (!strcasecmp(authtype, "MD5")) {
-					if (!ast_strlen_zero(key) && 
+					if (!ast_strlen_zero(key) &&
 					    !ast_strlen_zero(s->challenge) && !ast_strlen_zero(password)) {
 						int x;
 						int len = 0;
@@ -953,7 +962,7 @@
 							return -1;
 						}
 					} else {
-						ast_log(LOG_DEBUG, "MD5 authentication is not possible.  challenge: '%s'\n", 
+						ast_log(LOG_DEBUG, "MD5 authentication is not possible.  challenge: '%s'\n",
 							S_OR(s->challenge, ""));
 						ast_config_destroy(cfg);
 						return -1;
@@ -964,7 +973,7 @@
 					ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
 					ast_config_destroy(cfg);
 					return -1;
-				}	
+				}
 			}
 		}
 		cat = ast_category_browse(cfg, cat);
@@ -1018,7 +1027,7 @@
 }
 
 /*! \brief Manager PING */
-static char mandescr_ping[] = 
+static char mandescr_ping[] =
 "Description: A 'Ping' action will ellicit a 'Pong' response.  Used to keep the\n"
 "  manager connection open.\n"
 "Variables: NONE\n";
@@ -1079,7 +1088,7 @@
 	const char *action, *cat, *var, *value, *match;
 	struct ast_category *category;
 	struct ast_variable *v;
-	
+
 	for (x=0;x<100000;x++) {
 		unsigned int object = 0;
 
@@ -1109,7 +1118,7 @@
 		} else if (!strcasecmp(action, "renamecat")) {
 			if (!ast_strlen_zero(cat) && !ast_strlen_zero(value)) {
 				category = ast_category_get(cfg, cat);
-				if (category) 
+				if (category)
 					ast_category_rename(category, value);
 			}
 		} else if (!strcasecmp(action, "delcat")) {
@@ -1122,8 +1131,8 @@
 			if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) && (category = ast_category_get(cfg, cat)))
 				ast_variable_delete(category, (char *) var, (char *) match);
 		} else if (!strcasecmp(action, "append")) {
-			if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) && 
-				(category = ast_category_get(cfg, cat)) && 
+			if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) &&
+				(category = ast_category_get(cfg, cat)) &&
 				(v = ast_variable_new(var, value))){
 				if (object || (match && !strcasecmp(match, "object")))
 					v->object = 1;
@@ -1178,13 +1187,13 @@
 	if (!ast_strlen_zero(rld)) {
 		if (ast_true(rld))
 			rld = NULL;
-		ast_module_reload(rld); 
+		ast_module_reload(rld);
 	}
 	return 0;
 }
 
 /*! \brief Manager WAITEVENT */
-static char mandescr_waitevent[] = 
+static char mandescr_waitevent[] =
 "Description: A 'WaitEvent' action will ellicit a 'Success' response.  Whenever\n"
 "a manager event is queued.  Once WaitEvent has been called on an HTTP manager\n"
 "session, events will be generated and queued.\n"
@@ -1208,7 +1217,7 @@
 	if (!ast_strlen_zero(timeouts)) {
 		sscanf(timeouts, "%i", &timeout);
 	}
-	
+
 	ast_mutex_lock(&s->__lock);
 	if (s->waiting_thread != AST_PTHREADT_NULL) {
 		pthread_kill(s->waiting_thread, SIGURG);
@@ -1273,7 +1282,7 @@
 	return 0;
 }
 
-static char mandescr_listcommands[] = 
+static char mandescr_listcommands[] =
 "Description: Returns the action name and synopsis for every\n"
 "  action that is available to the user\n"
 "Variables: NONE\n";
@@ -1298,7 +1307,7 @@
 	return 0;
 }
 
-static char mandescr_events[] = 
+static char mandescr_events[] =
 "Description: Enable/Disable sending of events to this manager\n"
 "  client.\n"
 "Variables:\n"
@@ -1320,7 +1329,7 @@
 	return 0;
 }
 
-static char mandescr_logoff[] = 
+static char mandescr_logoff[] =
 "Description: Logoff this manager session\n"
 "Variables: NONE\n";
 
@@ -1330,7 +1339,7 @@
 	return -1;
 }
 
-static char mandescr_hangup[] = 
+static char mandescr_hangup[] =
 "Description: Hangup a channel\n"
 "Variables: \n"
 "	Channel: The channel name to be hungup\n";
@@ -1354,7 +1363,7 @@
 	return 0;
 }
 
-static char mandescr_setvar[] = 
+static char mandescr_setvar[] =
 "Description: Set a global or local channel variable.\n"
 "Variables: (Names marked with * are required)\n"
 "	Channel: Channel to set variable for\n"
@@ -1367,12 +1376,12 @@
 	const char *name = astman_get_header(m, "Channel");
 	const char *varname = astman_get_header(m, "Variable");
 	const char *varval = astman_get_header(m, "Value");
-	
+
 	if (ast_strlen_zero(varname)) {
 		astman_send_error(s, m, "No variable specified");
 		return 0;
 	}
-	
+
 	if (!ast_strlen_zero(name)) {
 		c = ast_get_channel_by_name_locked(name);
 		if (!c) {
@@ -1380,18 +1389,18 @@
 			return 0;
 		}
 	}
-	
+
 	pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
-	  
+
 	if (c)
 		ast_channel_unlock(c);
 
-	astman_send_ack(s, m, "Variable Set");	
+	astman_send_ack(s, m, "Variable Set");
 
 	return 0;
 }
 
-static char mandescr_getvar[] = 
+static char mandescr_getvar[] =
 "Description: Get the value of a global or local channel variable.\n"
 "Variables: (Names marked with * are required)\n"
 "	Channel: Channel to read variable from\n"
@@ -1493,10 +1502,10 @@
 			"Uniqueid: %s\r\n"
 			"%s"
 			"\r\n",
-			c->name, 
-			S_OR(c->cid.cid_num, "<unknown>"), 
-			S_OR(c->cid.cid_num, "<unknown>"), 
-			S_OR(c->cid.cid_name, "<unknown>"), 
+			c->name,
+			S_OR(c->cid.cid_num, "<unknown>"),
+			S_OR(c->cid.cid_num, "<unknown>"),
+			S_OR(c->cid.cid_name, "<unknown>"),
 			c->accountcode,
 			ast_state2str(c->_state), c->context,
 			c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
@@ -1514,10 +1523,10 @@
 			"Uniqueid: %s\r\n"
 			"%s"
 			"\r\n",
-			c->name, 
-			S_OR(c->cid.cid_num, "<unknown>"), 
-			S_OR(c->cid.cid_num, "<unknown>"), 
-			S_OR(c->cid.cid_name, "<unknown>"), 
+			c->name,
+			S_OR(c->cid.cid_num, "<unknown>"),
+			S_OR(c->cid.cid_num, "<unknown>"),
+			S_OR(c->cid.cid_name, "<unknown>"),
 			c->accountcode,
 			ast_state2str(c->_state), bridge, c->uniqueid, idText);
 		}
@@ -1533,7 +1542,7 @@
 	return 0;
 }
 
-static char mandescr_redirect[] = 
+static char mandescr_redirect[] =
 "Description: Redirect (transfer) a call.\n"
 "Variables: (Names marked with * are required)\n"
 "	*Channel: Channel to redirect\n"
@@ -1608,7 +1617,7 @@
 	return 0;
 }
 
-static char mandescr_command[] = 
+static char mandescr_command[] =
 "Description: Run a CLI command.\n"
 "Variables: (Names marked with * are required)\n"
 "	*Command: Asterisk CLI command to run\n"
@@ -1669,19 +1678,19 @@
 	char requested_channel[AST_CHANNEL_NAME];
 
 	if (!ast_strlen_zero(in->app)) {
-		res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, 
-			S_OR(in->cid_num, NULL), 
+		res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1,
+			S_OR(in->cid_num, NULL),
 			S_OR(in->cid_name, NULL),
 			in->vars, in->account, &chan);
 	} else {
-		res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, 
-			S_OR(in->cid_num, NULL), 
+		res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
+			S_OR(in->cid_num, NULL),
 			S_OR(in->cid_name, NULL),
 			in->vars, in->account, &chan);
 	}
 
 	if (!chan)
-		snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);	
+		snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
 	/* Tell the manager what happened with the channel */
 	manager_event(EVENT_FLAG_CALL, "OriginateResponse",
 		"%s"
@@ -1694,7 +1703,7 @@
 		"CallerID: %s\r\n"		/* This parameter is deprecated and will be removed post-1.4 */
 		"CallerIDNum: %s\r\n"
 		"CallerIDName: %s\r\n",
-		in->idtext, res ? "Failure" : "Success", chan ? chan->name : requested_channel, in->context, in->exten, reason, 
+		in->idtext, res ? "Failure" : "Success", chan ? chan->name : requested_channel, in->context, in->exten, reason,
 		chan ? chan->uniqueid : "<null>",
 		S_OR(in->cid_num, "<unknown>"),
 		S_OR(in->cid_num, "<unknown>"),
@@ -1708,7 +1717,7 @@
 	return NULL;
 }
 
-static char mandescr_originate[] = 
+static char mandescr_originate[] =
 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
 "  Application/Data\n"
 "Variables: (Names marked with * are required)\n"
@@ -1746,7 +1755,7 @@
 	int reason = 0;
 	char tmp[256];
 	char tmp2[256];
-	
+
 	pthread_t th;
 	pthread_attr_t attr;
 	if (!name) {
@@ -1797,7 +1806,7 @@
 				ast_copy_string(fast->cid_num, l, sizeof(fast->cid_num));
 			if (n)
 				ast_copy_string(fast->cid_name, n, sizeof(fast->cid_name));
-			fast->vars = vars;	
+			fast->vars = vars;
 			ast_copy_string(fast->context, context, sizeof(fast->context));
 			ast_copy_string(fast->exten, exten, sizeof(fast->exten));
 			ast_copy_string(fast->account, account, sizeof(fast->account));
@@ -1821,7 +1830,7 @@
 			astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
 			return 0;
 		}
-	}   
+	}
 	if (!res)
 		astman_send_ack(s, m, "Originate successfully queued");
 	else
@@ -1831,7 +1840,7 @@
 
 /*! \brief Help text for manager command mailboxstatus
  */
-static char mandescr_mailboxstatus[] = 
+static char mandescr_mailboxstatus[] =
 "Description: Checks a voicemail account for status.\n"
 "Variables: (Names marked with * are required)\n"
 "	*Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
@@ -1863,7 +1872,7 @@
 	return 0;
 }
 
-static char mandescr_mailboxcount[] = 
+static char mandescr_mailboxcount[] =
 "Description: Checks a voicemail account for new messages.\n"
 "Variables: (Names marked with * are required)\n"
 "	*Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
@@ -1893,13 +1902,13 @@
 				   "Message: Mailbox Message Count\r\n"
 				   "Mailbox: %s\r\n"
 		 		   "NewMessages: %d\r\n"
-				   "OldMessages: %d\r\n" 
+				   "OldMessages: %d\r\n"
 				   "\r\n",
 				    idText,mailbox, newmsgs, oldmsgs);
 	return 0;
 }
 
-static char mandescr_extensionstate[] = 
+static char mandescr_extensionstate[] =
 "Description: Report the extension state for given extension.\n"
 "  If the extension has a hint, will use devicestate to check\n"
 "  the status of the device connected to the extension.\n"
@@ -1940,7 +1949,7 @@
 	return 0;
 }
 
-static char mandescr_timeout[] = 
+static char mandescr_timeout[] =
 "Description: Hangup a channel after a certain time.\n"
 "Variables: (Names marked with * are required)\n"
 "	*Channel: Channel name to hangup\n"
@@ -2063,11 +2072,11 @@
 				s->authenticated = 1;
 				if (option_verbose > 1) {
 					if (displayconnects) {
-						ast_verbose(VERBOSE_PREFIX_2 "%sManager '%s' logged on from %s\n", 
+						ast_verbose(VERBOSE_PREFIX_2 "%sManager '%s' logged on from %s\n",
 							(s->sessiontimeout ? "HTTP " : ""), s->username, ast_inet_ntoa(s->sin.sin_addr));
 					}
 				}
-				ast_log(LOG_EVENT, "%sManager '%s' logged on from %s\n", 
+				ast_log(LOG_EVENT, "%sManager '%s' logged on from %s\n",
 					(s->sessiontimeout ? "HTTP " : ""), s->username, ast_inet_ntoa(s->sin.sin_addr));
 				astman_send_ack(s, m, "Authentication accepted");
 			}
@@ -2081,7 +2090,7 @@
 			astman_send_ack(s, m, "Already logged in");
 		else {
 			ast_rwlock_rdlock(&actionlock);
-			for (tmp = first_action; tmp; tmp = tmp->next) { 		
+			for (tmp = first_action; tmp; tmp = tmp->next) {
 				if (strcasecmp(action, tmp->action))
 					continue;
 				if ((s->writeperm & tmp->authority) == tmp->authority) {
@@ -2118,7 +2127,7 @@
 			s->inlen -= (x + 1);
 			return 1;
 		}
-	} 
+	}
 	if (s->inlen >= sizeof(s->inbuf) - 1) {
 		ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(s->sin.sin_addr), s->inbuf);
 		s->inlen = 0;
@@ -2189,7 +2198,7 @@
 {
 	struct mansession *s = data;
 	int res;
-	
+
 	astman_append(s, "Asterisk Call Manager/1.0\r\n");
 	for (;;) {
 		if ((res = do_message(s)) < 0)
@@ -2197,7 +2206,7 @@
 	}
 	if (s->authenticated) {
 		if (option_verbose > 1) {
-			if (displayconnects) 
+			if (displayconnects)
 				ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
 		}
 		ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
@@ -2240,7 +2249,7 @@
 						s->username, ast_inet_ntoa(s->sin.sin_addr));
 				}
 				free_session(s);
-				break;	
+				break;
 			}
 		}
 		AST_LIST_TRAVERSE_SAFE_END
@@ -2263,6 +2272,7 @@
 		   we can ditch any old manager sessions */
 		if (poll(pfds, 1, 5000) < 1)
 			continue;
+
 		as = accept(asock, (struct sockaddr *)&sin, &sinlen);
 		if (as < 0) {
 			ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
@@ -2277,8 +2287,6 @@
 		if (!(s = ast_calloc(1, sizeof(*s))))
 			continue;
 
-		ast_atomic_fetchadd_int(&num_sessions, 1);
-		
 		memcpy(&s->sin, &sin, sizeof(sin));
 		s->writetimeout = 100;
 		s->waiting_thread = AST_PTHREADT_NULL;
@@ -2299,10 +2307,14 @@
 		/* Find the last place in the master event queue and hook ourselves
 		   in there */
 		s->eventq = master_eventq;
-		while(s->eventq->next)
+		while (s->eventq->next)
 			s->eventq = s->eventq->next;
 		AST_LIST_UNLOCK(&sessions);
+
+		ast_atomic_fetchadd_int(&num_sessions, 1);
+
 		ast_atomic_fetchadd_int(&s->eventq->usecount, 1);
+
 		if (ast_pthread_create_background(&s->t, &attr, session_do, s))
 			destroy_session(s);
 	}
@@ -2321,18 +2333,18 @@
 	tmp->next = NULL;
 	tmp->category = category;
 	strcpy(tmp->eventdata, str);
-	
+
 	if (master_eventq) {
 		prev = master_eventq;
-		while (prev->next) 
+		while (prev->next)
 			prev = prev->next;
 		prev->next = tmp;
 	} else {
 		master_eventq = tmp;
 	}
-	
+
 	tmp->usecount = num_sessions;
-	
+
 	return 0;
 }
 
@@ -2366,9 +2378,9 @@
 	va_start(ap, fmt);
 	ast_dynamic_str_thread_append_va(&buf, 0, &manager_event_buf, fmt, ap);
 	va_end(ap);
-	
-	ast_dynamic_str_thread_append(&buf, 0, &manager_event_buf, "\r\n");	
-	
+
+	ast_dynamic_str_thread_append(&buf, 0, &manager_event_buf, "\r\n");
+
 	/* Append event to master list and wake up any sleeping sessions */
 	AST_LIST_LOCK(&sessions);
 	append_event(buf->str, category);
@@ -2383,7 +2395,7 @@
 	return 0;
 }
 
-int ast_manager_unregister(char *action) 
+int ast_manager_unregister(char *action)
 {
 	struct manager_action *cur, *prev;
 
@@ -2393,7 +2405,7 @@
 		if (!strcasecmp(action, cur->action)) {
 			prev->next = cur->next;
 			free(cur);
-			if (option_verbose > 1) 
+			if (option_verbose > 1)
 				ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
 			ast_rwlock_unlock(&actionlock);
 			return 0;
@@ -2436,10 +2448,10 @@
 			}
 			break;
 		}
-		prev = cur; 
+		prev = cur;
 		cur = cur->next;
 	}
-	
+
 	if (!cur) {
 		if (prev)
 			prev->next = act;
@@ -2448,13 +2460,13 @@
 		act->next = NULL;
 	}
 
-	if (option_verbose > 1) 
+	if (option_verbose > 1)
 		ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
 	ast_rwlock_unlock(&actionlock);
 	return 0;
 }
 
-/*! \brief register a new command with manager, including online help. This is 
+/*! \brief register a new command with manager, including online help. This is
 	the preferred way to register a manager command */
 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
 {
@@ -2463,7 +2475,7 @@
 	cur = ast_malloc(sizeof(*cur));
 	if (!cur)
 		return -1;
-	
+
 	cur->action = action;
 	cur->authority = auth;
 	cur->func = func;
@@ -2559,7 +2571,7 @@
 			break;
 		}
 	}
-	
+
 	if (!(s = find_session(ident))) {
 		/* Create new session */
 		if (!(s = ast_calloc(1, sizeof(*s)))) {
@@ -2592,7 +2604,7 @@
 	else
 		s->sessiontimeout += httptimeout;
 	ast_mutex_unlock(&s->__lock);
-	
+
 	if (s) {
 		struct message m = { 0 };
 		char tmp[80];
@@ -2609,8 +2621,8 @@
 		if (process_message(s, &m)) {
 			if (s->authenticated) {
 				if (option_verbose > 1) {
-					if (displayconnects) 
-						ast_verbose(VERBOSE_PREFIX_2 "HTTP Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));    
+					if (displayconnects)
+						ast_verbose(VERBOSE_PREFIX_2 "HTTP Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
 				}
 				ast_log(LOG_EVENT, "HTTP Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
 			} else {
@@ -2681,12 +2693,12 @@
 	} else
 		s->inuse--;
 	ast_mutex_unlock(&s->__lock);
-	
+
 	if (blastaway)
 		destroy_session(s);
 generic_callback_out:
 	if (*status != 200)
-		return ast_http_error(500, "Server Error", NULL, "Internal Server Error (out of memory)\n"); 
+		return ast_http_error(500, "Server Error", NULL, "Internal Server Error (out of memory)\n");
 	return retval;
 }
 
@@ -2810,12 +2822,12 @@
 	ba.sin_port = htons(portno);
 
 	if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
-		if (!inet_aton(val, &ba.sin_addr)) { 
+		if (!inet_aton(val, &ba.sin_addr)) {
 			ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
 			memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
 		}
 	}
-	
+
 
 	if ((asock > -1) && ((portno != oldportno) || !enabled)) {
 #if 0
@@ -2904,7 +2916,7 @@
 	AST_LIST_UNLOCK(&users);
 
 	ast_config_destroy(cfg);
-	
+
 	if (webenabled && enabled) {
 		if (!webregged) {
 			ast_http_uri_link(&rawmanuri);
