From 1bac31d6bdcde7988dab684f053cc8fe5fafed41 Mon Sep 17 00:00:00 2001
From: "Kevin P. Fleming" <kpfleming@digium.com>
Date: Mon, 6 Jun 2005 02:29:18 +0000
Subject: [PATCH] more efficient (and understandable) ast_channel_walk_locked,
 and vastly more efficient ast_channel_by_name_locked (bug #4265)

git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@5853 65c4cc65-6c06-0410-ace0-fbb531ad65f3
---
 app.c                      |  38 +++---
 apps/app_groupcount.c      |   4 +-
 apps/app_setcdruserfield.c |   8 +-
 apps/app_softhangup.c      |   1 +
 apps/app_zapscan.c         |  10 +-
 channel.c                  | 131 +++++++++++----------
 cli.c                      | 230 +++++++++++++++++--------------------
 include/asterisk/channel.h |   4 +-
 manager.c                  |  55 ++-------
 pbx.c                      |  17 +--
 res/res_agi.c              |  38 +++---
 res/res_features.c         |   6 +-
 res/res_monitor.c          |  27 +----
 res/res_musiconhold.c      |   8 +-
 14 files changed, 231 insertions(+), 346 deletions(-)

diff --git a/app.c b/app.c
index b61ff55ae9..9f4267f344 100755
--- a/app.c
+++ b/app.c
@@ -1013,22 +1013,20 @@ int ast_app_group_get_count(char *group, char *category)
 	int count = 0;
 	char *test;
 	char cat[80] = "";
+	char *s;
 
-	if (category && !ast_strlen_zero(category)) {
-		ast_copy_string(cat, category, sizeof(cat));
-	} else {
-		ast_copy_string(cat, GROUP_CATEGORY_PREFIX, sizeof(cat));
-	}
+	if (group == NULL || ast_strlen_zero(group))
+		return 0;
 
-	if (group && !ast_strlen_zero(group)) {
-		chan = ast_channel_walk_locked(NULL);
-		while(chan) {
-			test = pbx_builtin_getvar_helper(chan, cat);
-			if (test && !strcasecmp(test, group))
-				count++;
-			ast_mutex_unlock(&chan->lock);
-			chan = ast_channel_walk_locked(chan);
-		}
+ 	s = (category && !ast_strlen_zero(category)) ? category : GROUP_CATEGORY_PREFIX;
+	ast_copy_string(cat, s, sizeof(cat));
+
+	chan = NULL;
+	while ((chan = ast_channel_walk_locked(chan)) != NULL) {
+ 		test = pbx_builtin_getvar_helper(chan, cat);
+		if (test && !strcasecmp(test, group))
+ 			count++;
+		ast_mutex_unlock(&chan->lock);
 	}
 
 	return count;
@@ -1041,6 +1039,7 @@ int ast_app_group_match_get_count(char *groupmatch, char *category)
 	int count = 0;
 	char *test;
 	char cat[80] = "";
+	char *s;
 
 	if (!groupmatch || ast_strlen_zero(groupmatch))
 		return 0;
@@ -1049,14 +1048,11 @@ int ast_app_group_match_get_count(char *groupmatch, char *category)
 	if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
 		return 0;
 
-	if (category && !ast_strlen_zero(category)) {
-		ast_copy_string(cat, category, sizeof(cat));
-	} else {
-		ast_copy_string(cat, GROUP_CATEGORY_PREFIX, sizeof(cat));
-	}
+	s = (category && !ast_strlen_zero(category)) ? category : GROUP_CATEGORY_PREFIX;
+	ast_copy_string(cat, s, sizeof(cat));
 
-	chan = ast_channel_walk_locked(NULL);
-	while(chan) {
+	chan = NULL;
+	while ((chan = ast_channel_walk_locked(chan)) != NULL) {
 		test = pbx_builtin_getvar_helper(chan, cat);
 		if (test && !regexec(&regexbuf, test, 0, NULL, 0))
 			count++;
diff --git a/apps/app_groupcount.c b/apps/app_groupcount.c
index f7ac15763d..d17521001d 100755
--- a/apps/app_groupcount.c
+++ b/apps/app_groupcount.c
@@ -174,9 +174,8 @@ static int group_show_channels(int fd, int argc, char *argv[])
 		havepattern = 1;
 	}
 
-	c = ast_channel_walk_locked(NULL);
 	ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
-	while(c) {
+	while ( (c = ast_channel_walk_locked(c)) != NULL) {
 		headp=&c->varshead;
 		AST_LIST_TRAVERSE(headp,current,entries) {
 			if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
@@ -194,7 +193,6 @@ static int group_show_channels(int fd, int argc, char *argv[])
 		}
 		numchans++;
 		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
 	}
 
 	if (havepattern)
diff --git a/apps/app_setcdruserfield.c b/apps/app_setcdruserfield.c
index 4684fdd8b6..7e820db12f 100755
--- a/apps/app_setcdruserfield.c
+++ b/apps/app_setcdruserfield.c
@@ -76,13 +76,7 @@ static int action_setcdruserfield(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No UserField specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while (c) {
-		if (!strcasecmp(c->name, channel))
-			break;
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(channel);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
diff --git a/apps/app_softhangup.c b/apps/app_softhangup.c
index 6631b0ad72..124f270c6c 100755
--- a/apps/app_softhangup.c
+++ b/apps/app_softhangup.c
@@ -60,6 +60,7 @@ static int softhangup_exec(struct ast_channel *chan, void *data)
 	while (c) {
 		strncpy(name, c->name, sizeof(name)-1);
 		ast_mutex_unlock(&c->lock);
+		/* XXX watch out, i think it is wrong to access c-> after unlocking! */
 		if (all) {
 			/* CAPI is set up like CAPI[foo/bar]/clcnt */ 
 			if (!strcmp(c->type,"CAPI")) 
diff --git a/apps/app_zapscan.c b/apps/app_zapscan.c
index 195fc657c7..9b153ed26d 100755
--- a/apps/app_zapscan.c
+++ b/apps/app_zapscan.c
@@ -64,15 +64,7 @@ static struct ast_channel *get_zap_channel_locked(int num) {
 	char name[80];
 	
 	snprintf(name,sizeof(name),"Zap/%d-1",num);
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
-	return c;
+	return ast_get_channel_by_name_locked(name);
 }
 
 static int careful_write(int fd, unsigned char *data, int len)
diff --git a/channel.c b/channel.c
index d321759398..9797f0ab15 100755
--- a/channel.c
+++ b/channel.c
@@ -61,7 +61,11 @@
 #define MONITOR_DELAY	150 * 8		/* 150 ms of MONITORING DELAY */
 #endif
 
+/*
+ * Prevent new channel allocation if shutting down.
+ */
 static int shutting_down = 0;
+
 static int uniqueint = 0;
 
 unsigned long global_fin = 0, global_fout = 0;
@@ -71,12 +75,17 @@ unsigned long global_fin = 0, global_fout = 0;
 struct chanlist {
 	const struct ast_channel_tech *tech;
 	struct chanlist *next;
-} *backends = NULL;
-struct ast_channel *channels = NULL;
+};
 
-/* Protect the channel list (highly unlikely that two things would change
-   it at the same time, but still! */
-   
+static struct chanlist *backends = NULL;
+
+/*
+ * the list of channels we have
+ */
+static struct ast_channel *channels = NULL;
+
+/* Protect the channel list, both backends and channels.
+ */
 AST_MUTEX_DEFINE_STATIC(chlock);
 
 static int show_channeltypes(int fd, int argc, char *argv[])
@@ -514,72 +523,70 @@ void ast_channel_undefer_dtmf(struct ast_channel *chan)
 		ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
 }
 
-/*--- ast_channel_walk_locked: Browse channels in use */
-struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
+/*
+ * Helper function to return the channel after prev, or the one matching name,
+ * with the channel's lock held. If getting the individual lock fails,
+ * unlock and retry quickly up to 10 times, then give up.
+ * 
+ * XXX Note that this code has cost O(N) because of the need to verify
+ * that the object is still on the global list.
+ *
+ * XXX also note that accessing fields (e.g. c->name in ast_log())
+ * can only be done with the lock held or someone could delete the
+ * object while we work on it. This causes some ugliness in the code.
+ * Note that removing the first ast_log() may be harmful, as it would
+ * shorten the retry period and possibly cause failures.
+ * We should definitely go for a better scheme that is deadlock-free.
+ */
+static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
+					       const char *name)
 {
-	/* Returns next channel (locked) */
-	struct ast_channel *l, *ret;
-	int retries = 0;	
-retry:
-	ret=NULL;
-	ast_mutex_lock(&chlock);
-	l = channels;
-	if (!prev) {
-		if (l) {
-			if (ast_mutex_trylock(&l->lock)) {
-				if (retries < 10)
-					ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
-				else
-					ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
-				ast_mutex_unlock(&chlock);
-				if (retries < 10) {
-					usleep(1);
-					retries++;
-					goto retry;
-				} else
-					return NULL;
+	const char *msg = prev ? "initial deadlock" : "deadlock";
+	int retries, done;
+	struct ast_channel *c;
+
+	for (retries = 0; retries < 10; retries++) {
+		ast_mutex_lock(&chlock);
+		for (c = channels; c; c = c->next) {
+			if (prev == NULL) {
+				/* want either head of list or match by name */
+				if (name == NULL || !strcasecmp(name, c->name))
+					break;
+			} else if (c == prev) { /* found, return c->next */
+				c = c->next;
+				break;
 			}
 		}
+		/* exit if chan not found or mutex acquired successfully */
+		done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
+		/* this is slightly unsafe, as we _should_ hold the lock to access c->name */
+		if (!done && c)
+			ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
 		ast_mutex_unlock(&chlock);
-		return l;
-	}
-	while(l) {
-		if (l == prev)
-			ret = l->next;
-		l = l->next;
-	}
-	if (ret) {
-		if (ast_mutex_trylock(&ret->lock)) {
-			if (retries < 10)
-				ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
-			else
-				ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
-			ast_mutex_unlock(&chlock);
-			if (retries < 10) {
-				usleep(1);
-				retries++;
-				goto retry;
-			} else
-				return NULL;
-		}
+		if (done)
+			return c;
+		usleep(1);
 	}
-	ast_mutex_unlock(&chlock);
-	return ret;
-	
+	/*
+ 	 * c is surely not null, but we don't have the lock so cannot
+	 * access c->name
+	 */
+	ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
+		msg, c, retries);
+
+	return NULL;
+}
+
+/*--- ast_channel_walk_locked: Browse channels in use */
+struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
+{
+	return channel_find_locked(prev, NULL);
 }
 
 /*--- ast_get_channel_by_name_locked: Get channel by name and lock it */
-struct ast_channel *ast_get_channel_by_name_locked(char *channame)
+struct ast_channel *ast_get_channel_by_name_locked(const char *name)
 {
-	struct ast_channel *chan;
-	chan = ast_channel_walk_locked(NULL);
-	while(chan) {
-		if (!strcasecmp(chan->name, channame))
-			return chan;
-		ast_mutex_unlock(&chan->lock);
-		chan = ast_channel_walk_locked(chan);
-	}
-	return NULL;
+	return channel_find_locked(NULL, name);
 }
 
 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
diff --git a/cli.c b/cli.c
index b61b5898c4..8e13573657 100755
--- a/cli.c
+++ b/cli.c
@@ -412,10 +412,9 @@ static int handle_chanlist(int fd, int argc, char *argv[])
 		return RESULT_SHOWUSAGE;
 	
 	concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
-	c = ast_channel_walk_locked(NULL);
 	if(!concise)
 		ast_cli(fd, FORMAT_STRING2, "Channel", "Context", "Extension", "Pri", "State", "Appl.", "Data");
-	while(c) {
+	while ( (c = ast_channel_walk_locked(c)) != NULL) {
 		if(concise)
 			ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
 					c->appl ? c->appl : "(None)", c->data ? ( !ast_strlen_zero(c->data) ? c->data : "" ): "",
@@ -427,7 +426,6 @@ static int handle_chanlist(int fd, int argc, char *argv[])
 
 		numchans++;
 		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
 	}
 	if(!concise) {
 		ast_cli(fd, "%d active channel(s)\n", numchans);
@@ -476,18 +474,12 @@ static int handle_softhangup(int fd, int argc, char *argv[])
 	struct ast_channel *c=NULL;
 	if (argc != 3)
 		return RESULT_SHOWUSAGE;
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, argv[2])) {
-			ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
-			ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
-			ast_mutex_unlock(&c->lock);
-			break;
-		}
+	c = ast_get_channel_by_name_locked(argv[2]);
+	if (c) {
+		ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
+		ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
 		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
-	if (!c) 
+	} else
 		ast_cli(fd, "%s is not a known channel\n", argv[2]);
 	return RESULT_SUCCESS;
 }
@@ -601,6 +593,8 @@ static int handle_debuglevel(int fd, int argc, char *argv[])
 	return RESULT_SUCCESS;
 }
 
+#define	DEBUGCHAN_FLAG	0x80000000
+/* XXX todo: merge next two functions!!! */
 static int handle_debugchan(int fd, int argc, char *argv[])
 {
 	struct ast_channel *c=NULL;
@@ -610,31 +604,26 @@ static int handle_debugchan(int fd, int argc, char *argv[])
 
 	is_all = !strcasecmp("all", argv[2]);
 	if (is_all) {
-		global_fin |= 0x80000000;
-		global_fout |= 0x80000000;
+		global_fin |= DEBUGCHAN_FLAG;
+		global_fout |= DEBUGCHAN_FLAG;
+		c = ast_channel_walk_locked(NULL);
+	} else {
+		c = ast_get_channel_by_name_locked(argv[2]);
+		if (c == NULL)
+			ast_cli(fd, "No such channel %s\n", argv[2]);
 	}
-	c = ast_channel_walk_locked(NULL);
 	while(c) {
-		if (is_all || !strcasecmp(c->name, argv[2])) {
-			if (!(c->fin & 0x80000000) || !(c->fout & 0x80000000)) {
-				c->fin |= 0x80000000;
-				c->fout |= 0x80000000;
-				ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
-			}
-			if (!is_all)
-				break;
+		if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
+			c->fin |= DEBUGCHAN_FLAG;
+			c->fout |= DEBUGCHAN_FLAG;
+			ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
 		}
 		ast_mutex_unlock(&c->lock);
+		if (!is_all)
+			break;
 		c = ast_channel_walk_locked(c);
 	}
-	if (!is_all) {
-		if (c)
-			ast_mutex_unlock(&c->lock);
-		else
-			ast_cli(fd, "No such channel %s\n", argv[2]);
-	}
-	else
-		ast_cli(fd, "Debugging on new channels is enabled\n");
+	ast_cli(fd, "Debugging on new channels is enabled\n");
 	return RESULT_SUCCESS;
 }
 
@@ -646,31 +635,26 @@ static int handle_nodebugchan(int fd, int argc, char *argv[])
 		return RESULT_SHOWUSAGE;
 	is_all = !strcasecmp("all", argv[3]);
 	if (is_all) {
-		global_fin &= ~0x80000000;
-		global_fout &= ~0x80000000;
-	}
-	c = ast_channel_walk_locked(NULL);
+		global_fin &= ~DEBUGCHAN_FLAG;
+		global_fout &= ~DEBUGCHAN_FLAG;
+		c = ast_channel_walk_locked(NULL);
+	} else {
+		c = ast_get_channel_by_name_locked(argv[3]);
+		if (c == NULL)
+			ast_cli(fd, "No such channel %s\n", argv[3]);
+    }
 	while(c) {
-		if (is_all || !strcasecmp(c->name, argv[3])) {
-			if ((c->fin & 0x80000000) || (c->fout & 0x80000000)) {
-				c->fin &= 0x7fffffff;
-				c->fout &= 0x7fffffff;
-				ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
-			}
-			if (!is_all)
-				break;
+		if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
+			c->fin &= ~DEBUGCHAN_FLAG;
+			c->fout &= ~DEBUGCHAN_FLAG;
+			ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
 		}
 		ast_mutex_unlock(&c->lock);
+		if (!is_all)
+			break;
 		c = ast_channel_walk_locked(c);
 	}
-	if (!is_all) {
-		if (c)
-			ast_mutex_unlock(&c->lock);
-		else
-			ast_cli(fd, "No such channel %s\n", argv[3]);
-	}
-	else
-		ast_cli(fd, "Debugging on new channels is disabled\n");
+	ast_cli(fd, "Debugging on new channels is disabled\n");
 	return RESULT_SUCCESS;
 }
 		
@@ -688,94 +672,86 @@ static int handle_showchan(int fd, int argc, char *argv[])
 	if (argc != 3)
 		return RESULT_SHOWUSAGE;
 	gettimeofday(&now, NULL);
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, argv[2])) {
-			if(c->cdr) {
-				elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
-				hour = elapsed_seconds / 3600;
-				min = (elapsed_seconds % 3600) / 60;
-				sec = elapsed_seconds % 60;
-				snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
-			} else
-				strncpy(cdrtime, "N/A", sizeof(cdrtime) -1);
-			ast_cli(fd, 
-				" -- General --\n"
-				"           Name: %s\n"
-				"           Type: %s\n"
-				"       UniqueID: %s\n"
-				"      Caller ID: %s\n"
-				" Caller ID Name: %s\n"
-				"    DNID Digits: %s\n"
-				"          State: %s (%d)\n"
-				"          Rings: %d\n"
-				"   NativeFormat: %d\n"
-				"    WriteFormat: %d\n"
-				"     ReadFormat: %d\n"
-				"1st File Descriptor: %d\n"
-				"      Frames in: %d%s\n"
-				"     Frames out: %d%s\n"
-				" Time to Hangup: %ld\n"
-				"   Elapsed Time: %s\n"
-				"  Direct Bridge: %s\n"
-				"Indirect Bridge: %s\n"
-				" --   PBX   --\n"
-				"        Context: %s\n"
-				"      Extension: %s\n"
-				"       Priority: %d\n"
-				"     Call Group: %d\n"
-				"   Pickup Group: %d\n"
-				"    Application: %s\n"
-				"           Data: %s\n"
-				"    Blocking in: %s\n",
-				c->name, c->type, c->uniqueid,
-				(c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
-				(c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
-				(c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
-				c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
-				c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
-				cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
-				c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
-				( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
-				(ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
-			
-				if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
-					ast_cli(fd,"      Variables:\n%s\n",buf);
-				if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
-					ast_cli(fd,"  CDR Variables:\n%s\n",buf);
-
-			ast_mutex_unlock(&c->lock);
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
-	if (!c) 
+	c = ast_get_channel_by_name_locked(argv[2]);
+	if (!c) {
 		ast_cli(fd, "%s is not a known channel\n", argv[2]);
+		return RESULT_SUCCESS;
+	}
+	if(c->cdr) {
+		elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
+		hour = elapsed_seconds / 3600;
+		min = (elapsed_seconds % 3600) / 60;
+		sec = elapsed_seconds % 60;
+		snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
+	} else
+		strncpy(cdrtime, "N/A", sizeof(cdrtime) -1);
+	ast_cli(fd, 
+		" -- General --\n"
+		"           Name: %s\n"
+		"           Type: %s\n"
+		"       UniqueID: %s\n"
+		"      Caller ID: %s\n"
+		" Caller ID Name: %s\n"
+		"    DNID Digits: %s\n"
+		"          State: %s (%d)\n"
+		"          Rings: %d\n"
+		"   NativeFormat: %d\n"
+		"    WriteFormat: %d\n"
+		"     ReadFormat: %d\n"
+		"1st File Descriptor: %d\n"
+		"      Frames in: %d%s\n"
+		"     Frames out: %d%s\n"
+		" Time to Hangup: %ld\n"
+		"   Elapsed Time: %s\n"
+		"  Direct Bridge: %s\n"
+		"Indirect Bridge: %s\n"
+		" --   PBX   --\n"
+		"        Context: %s\n"
+		"      Extension: %s\n"
+		"       Priority: %d\n"
+		"     Call Group: %d\n"
+		"   Pickup Group: %d\n"
+		"    Application: %s\n"
+		"           Data: %s\n"
+		"    Blocking in: %s\n",
+		c->name, c->type, c->uniqueid,
+		(c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
+		(c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
+		(c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
+		c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
+		c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
+		cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
+		c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
+		( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
+		(ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
+	
+	if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
+		ast_cli(fd,"      Variables:\n%s\n",buf);
+	if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
+		ast_cli(fd,"  CDR Variables:\n%s\n",buf);
+	
+	ast_mutex_unlock(&c->lock);
 	return RESULT_SUCCESS;
 }
 
 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
 {
-	struct ast_channel *c;
+	struct ast_channel *c = NULL;
 	int which=0;
-	char *ret;
+	char *ret = NULL;
+
 	if (pos != rpos)
 		return NULL;
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
+	while ( (c = ast_channel_walk_locked(c)) != NULL) {
 		if (!strncasecmp(word, c->name, strlen(word))) {
-			if (++which > state)
+			if (++which > state) {
+				ret = strdup(c->name);
+				ast_mutex_unlock(&c->lock);
 				break;
+			}
 		}
 		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
 	}
-	if (c) {
-		ret = strdup(c->name);
-		ast_mutex_unlock(&c->lock);
-	} else
-		ret = NULL;
 	return ret;
 }
 
diff --git a/include/asterisk/channel.h b/include/asterisk/channel.h
index 893e34add5..a98442f768 100755
--- a/include/asterisk/channel.h
+++ b/include/asterisk/channel.h
@@ -744,10 +744,10 @@ int ast_recvchar(struct ast_channel *chan, int timeout);
  * Returns the next channel in the list, NULL on end.
  * If it returns a channel, that channel *has been locked*!
  */
-struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev);
+struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev);
 
 /*! Get channel by name (locks channel) */
-struct ast_channel *ast_get_channel_by_name_locked(char *channame);
+struct ast_channel *ast_get_channel_by_name_locked(const char *chan);
 
 /*! Waits for a digit */
 /*! 
diff --git a/manager.c b/manager.c
index 11c671c48a..5a6af77cff 100755
--- a/manager.c
+++ b/manager.c
@@ -574,14 +574,7 @@ static int action_hangup(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No channel specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
@@ -615,14 +608,7 @@ static int action_setvar(struct mansession *s, struct message *m)
 		return 0;
 	}
 
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
@@ -660,14 +646,7 @@ static int action_getvar(struct mansession *s, struct message *m)
 		return 0;
 	}
 
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
@@ -702,25 +681,22 @@ static int action_status(struct mansession *s, struct message *m)
 	char bridge[256];
 	struct timeval now;
 	long elapsed_seconds=0;
+	int all = !name || ast_strlen_zero(name); /* set if we want all channels */
 
 	gettimeofday(&now, NULL);
 	astman_send_ack(s, m, "Channel status will follow");
-	c = ast_channel_walk_locked(NULL);
         if (id && !ast_strlen_zero(id))
                 snprintf(idText,256,"ActionID: %s\r\n",id);
-	if (name && !ast_strlen_zero(name)) {
-		while (c) {
-			if (!strcasecmp(c->name, name)) {
-				break;
-			}
-			ast_mutex_unlock(&c->lock);
-			c = ast_channel_walk_locked(c);
-		}
+	if (all)
+		c = ast_channel_walk_locked(NULL);
+	else {
+		c = ast_get_channel_by_name_locked(name);
 		if (!c) {
 			astman_send_error(s, m, "No such channel");
 			return 0;
 		}
 	}
+	/* if we look by name, we break after the first iteration */
 	while(c) {
 		if (c->_bridge)
 			snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->_bridge->name);
@@ -773,10 +749,8 @@ static int action_status(struct mansession *s, struct message *m)
 			ast_state2str(c->_state), bridge, c->uniqueid, idText);
 		}
 		ast_mutex_unlock(&s->lock);
-		ast_mutex_unlock(&c->lock);
-		if (name && !ast_strlen_zero(name)) {
+		if (!all)
 			break;
-		}
 		c = ast_channel_walk_locked(c);
 	}
 	ast_mutex_lock(&s->lock);
@@ -1175,14 +1149,7 @@ static int action_timeout(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No timeout specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
diff --git a/pbx.c b/pbx.c
index 23b000edc4..1307f6768a 100755
--- a/pbx.c
+++ b/pbx.c
@@ -4453,14 +4453,7 @@ int ast_async_goto_by_name(const char *channame, const char *context, const char
 	struct ast_channel *chan;
 	int res = -1;
 
-	chan = ast_channel_walk_locked(NULL);
-	while(chan) {
-		if (!strcasecmp(channame, chan->name))
-			break;
-		ast_mutex_unlock(&chan->lock);
-		chan = ast_channel_walk_locked(chan);
-	}
-	
+	chan = ast_get_channel_by_name_locked(channame);
 	if (chan) {
 		res = ast_async_goto(chan, context, exten, priority);
 		ast_mutex_unlock(&chan->lock);
@@ -5803,7 +5796,7 @@ int pbx_builtin_importvar(struct ast_channel *chan, void *data)
 	char *value;
 	char *stringp=NULL;
 	char *channel;
-	struct ast_channel *chan2=NULL;
+	struct ast_channel *chan2;
 	char tmp[4096]="";
 	char *s;
 
@@ -5817,11 +5810,7 @@ int pbx_builtin_importvar(struct ast_channel *chan, void *data)
 	channel = strsep(&stringp,"|"); 
 	value = strsep(&stringp,"\0");
 	if (channel && value && name) {
-		while((chan2 = ast_channel_walk_locked(chan2))) {
-			if (!strcmp(chan2->name, channel))
-				break;
-			ast_mutex_unlock(&chan2->lock);
-		}
+		chan2 = ast_get_channel_by_name_locked(channel);
 		if (chan2) {
 			s = alloca(strlen(value) + 4);
 			if (s) {
diff --git a/res/res_agi.c b/res/res_agi.c
index da28898161..f1837b5f01 100755
--- a/res/res_agi.c
+++ b/res/res_agi.c
@@ -960,19 +960,15 @@ static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **ar
 		ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
 		fdprintf(agi->fd, "200 result=1\n");
 		return RESULT_SUCCESS;
-        } else if (argc == 2) {
+	} else if (argc == 2) {
 		/* one argument: look for info on the specified channel */
-		c = ast_channel_walk_locked(NULL);
-		while (c) {
-			if (strcasecmp(argv[1], c->name) == 0) {
-				/* we have a matching channel */
-				ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
-				fdprintf(agi->fd, "200 result=1\n");
-				ast_mutex_unlock(&c->lock);
-       				return RESULT_SUCCESS;
-			}
+		c = ast_get_channel_by_name_locked(argv[1]);
+		if (c) {
+			/* we have a matching channel */
+			ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
+			fdprintf(agi->fd, "200 result=1\n");
 			ast_mutex_unlock(&c->lock);
-			c = ast_channel_walk_locked(c);
+			return RESULT_SUCCESS;
 		}
 		/* if we get this far no channel name matched the argument given */
 		fdprintf(agi->fd, "200 result=-1\n");
@@ -1036,15 +1032,11 @@ static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, ch
 		return RESULT_SUCCESS;
 	} else if (argc == 3) {
 		/* one argument: look for info on the specified channel */
-		c = ast_channel_walk_locked(NULL);
-		while (c) {
-			if (strcasecmp(argv[2],c->name)==0) {
-				fdprintf(agi->fd, "200 result=%d\n", c->_state);
-				ast_mutex_unlock(&c->lock);
-				return RESULT_SUCCESS;
-			}
+		c = ast_get_channel_by_name_locked(argv[2]);
+		if (c) {
+			fdprintf(agi->fd, "200 result=%d\n", c->_state);
 			ast_mutex_unlock(&c->lock);
-			c = ast_channel_walk_locked(c);
+			return RESULT_SUCCESS;
 		}
 		/* if we get this far no channel name matched the argument given */
 		fdprintf(agi->fd, "200 result=-1\n");
@@ -1087,15 +1079,11 @@ static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc,
 	if ((argc != 4) && (argc != 5))
 		return RESULT_SHOWUSAGE;
 	if (argc == 5) {
-		while((chan2 = ast_channel_walk_locked(chan2))) {
-			if (!strcmp(chan2->name, argv[4]))
-				break;
-			ast_mutex_unlock(&chan2->lock);
-		}
+		chan2 = ast_get_channel_by_name_locked(argv[4]);
 	} else {
 		chan2 = chan;
 	}
-	if (chan) {
+	if (chan) { /* XXX isn't this chan2 ? */
 		pbx_substitute_variables_helper(chan2, argv[3], tmp, sizeof(tmp) - 1);
 		fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
 	} else {
diff --git a/res/res_features.c b/res/res_features.c
index d6363e112b..15546c0406 100755
--- a/res/res_features.c
+++ b/res/res_features.c
@@ -1661,10 +1661,9 @@ int load_module(void)
 
 int ast_pickup_call(struct ast_channel *chan)
 {
-	struct ast_channel *cur;
+	struct ast_channel *cur = NULL;
 	int res = -1;
-	cur = ast_channel_walk_locked(NULL);
-	while(cur) {
+	while ( (cur = ast_channel_walk_locked(cur)) != NULL) {
 		if (!cur->pbx && 
 			(cur != chan) &&
 			(chan->pickupgroup & cur->callgroup) &&
@@ -1673,7 +1672,6 @@ int ast_pickup_call(struct ast_channel *chan)
 			 	break;
 		}
 		ast_mutex_unlock(&cur->lock);
-		cur = ast_channel_walk_locked(cur);
 	}
 	if (cur) {
 		if (option_debug)
diff --git a/res/res_monitor.c b/res/res_monitor.c
index cff024dc95..62d35dd1de 100755
--- a/res/res_monitor.c
+++ b/res/res_monitor.c
@@ -413,14 +413,7 @@ static int start_monitor_action(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No channel specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while (c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
@@ -471,14 +464,7 @@ static int stop_monitor_action(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No channel specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
@@ -514,14 +500,7 @@ static int change_monitor_action(struct mansession *s, struct message *m)
 		astman_send_error(s, m, "No filename specified");
 		return 0;
 	}
-	c = ast_channel_walk_locked(NULL);
-	while(c) {
-		if (!strcasecmp(c->name, name)) {
-			break;
-		}
-		ast_mutex_unlock(&c->lock);
-		c = ast_channel_walk_locked(c);
-	}
+	c = ast_get_channel_by_name_locked(name);
 	if (!c) {
 		astman_send_error(s, m, "No such channel");
 		return 0;
diff --git a/res/res_musiconhold.c b/res/res_musiconhold.c
index df018b4296..3b8c5b0988 100755
--- a/res/res_musiconhold.c
+++ b/res/res_musiconhold.c
@@ -962,10 +962,11 @@ static void ast_moh_destroy(void)
 	ast_mutex_unlock(&moh_lock);
 }
 
-static void moh_on_off(int on) {
-	struct ast_channel *chan = ast_channel_walk_locked(NULL);
+static void moh_on_off(int on)
+{
+	struct ast_channel *chan = NULL;
 
-	while (chan) {
+	while ( (chan = ast_channel_walk_locked(chan)) != NULL) {
 		if (ast_test_flag(chan, AST_FLAG_MOH)) {
 			if (on)
 				local_ast_moh_start(chan, NULL);
@@ -973,7 +974,6 @@ static void moh_on_off(int on) {
 				ast_deactivate_generator(chan);
 		}
 		ast_mutex_unlock(&chan->lock);
-		chan = ast_channel_walk_locked(chan);
 	}
 }
 
-- 
GitLab