From e96a35b179db4063e0a53de0bf8351767a5d6918 Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Mon, 23 Feb 2026 16:00:40 -0500 Subject: [PATCH 1/7] func_groupcount.c: Adding Group Variables + additional Group functions DumpGroups ------------------- * New application. This will dump all channel group membership and associated variables Groups and Group Variables ------------------ * Group variables can be set on a group once the group is created When a group is destroyed, all variables on that group are also destroyed A group variable is somewhat like a global variable, but it's on a per-group basis. GroupSet - Adds functionality to the manager to be able to set a GROUP() on a channel. GroupsShowChannels - Show each channel and it's associated groups (a channel will be repeated for each group@category it's a member of) GroupsShowVariables - Show variables in each group@category, one event per group, all variables are contained in each group@category event GroupVarSet - Set a group variable (the group must already exist) GroupVarGet - Get a group variable * New Manager events: ------------------ GroupCreate - Event is fired any time a group is made, ie: Set(GROUP=x) or Set(GROUP()=x@y). This event is only sent on when a channel is added to a group that did not exist previously. GroupChannelAdd - Event is fired any time a channel is added to a group GroupChannelRemove - Event is fired any time a channel is removed from a group GroupDestroy - Event is fired when there are no longer any channels assigned to the group GroupVarSet - Event is fired when any group variable is changed * New CLI Command --------------- group show variables * New Application --------------- DumpGroups() - Show groups and group assigments (similar to DumpChan) Resolves: #291 --- funcs/func_groupcount.c | 1323 ++++++++++++++++++++++++++++++++++- include/asterisk/app.h | 48 ++ include/asterisk/channel.h | 46 ++ include/asterisk/chanvars.h | 116 +++ main/app.c | 574 ++++++++++++++- main/cli.c | 63 +- 6 files changed, 2111 insertions(+), 59 deletions(-) diff --git a/funcs/func_groupcount.c b/funcs/func_groupcount.c index d1e89d9567..74012ee1ee 100644 --- a/funcs/func_groupcount.c +++ b/funcs/func_groupcount.c @@ -27,11 +27,16 @@ #include "asterisk.h" +#include + #include "asterisk/module.h" #include "asterisk/channel.h" #include "asterisk/pbx.h" #include "asterisk/utils.h" #include "asterisk/app.h" +#include "asterisk/manager.h" +#include "asterisk/strings.h" +#include "asterisk/cli.h" /*** DOCUMENTATION @@ -54,6 +59,233 @@ channel's current group if not specified (and non-empty). + + Find groups by regular expression + + + + + + Search for groups matching group@category. This search will look at all known groups and filter by the regex(s) provided. + If only the group_regex is specified, then return group@category results that only match the group name against the group_regex + If only the category_regex is specified, then return group@category results that only match the category name against the category_regex. + If the search regex parameters are entirely empty, all group@category will be returned. + Uses standard regular expression matching (see regex(7)). + + On Channel 1: + Set(GROUP()=groupName) + On Channel 2: + Set(GROUP()=foobarbaz) + On Channel 3: + Set(GROUP()=foobarbill) + On Channel 4: + Set(GROUP()=somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(groups_found=${GROUP_LIST(.*foo.*)}) + Given the above: + This will find the groups 'foobarbaz' and 'foobarbill' since they both match .*foo.* regex against the group name + Variable groups_found will be set to: foobarbaz,foobarbill + + + On Channel 1: + Set(GROUP()=groupName@categoryName) + On Channel 2: + Set(GROUP()=foo@barbaz) + On Channel 3: + Set(GROUP()=foo@barbill) + On Channel 4: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(groups_found=${GROUP_LIST(@.*bar.*)}) + + Given the above: + This will find the groups 'foo@barbaz' and 'foo@barbill' since they both match .*bar.* regex against the category name + Variable groups_found will be set to: foo@barbaz,foo@barbill + + + On Channel 1: + Set(GROUP()=groupName@categoryName) + On Channel 2: + Set(GROUP()=foo@barbaz) + On Channel 3: + Set(GROUP()=foo@barbill) + On Channel 4: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(groups_found=${GROUP_LIST(.*foo.*@.*bar.*)}) + + Given the above: + This will find the groups 'foo@barbaz' and 'foo@barbill' since they both match .*foo*. against the group name and .*bar.* regex against the category name + Variable groups_found will be set to: foo@barbaz,foo@barbill + + + + GROUP + GROUP_CHANNEL_LIST + + + + + Find channels that are members of groups/categories by exact match + + + + + + + Search for groups matching group@category and return the channels that are members of those groups, the group/category must match exactly + If only the group is specified, then return group@category results that only match against the group name + If only the category is specified, then return group@category results that only match the against the category name + If the search parameters are entirely empty, all channels having any kind of group membership will be returned. + After GROUP_CHANNEL_LIST is complete. Channel variables may be set with information related to the function call. + + + + The full result is not complete and was truncated + + + + + Find channels that are members of the group 'foobarbaz': + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName) + On Channel PJSIP/1234-0000003: + Set(GROUP()=foobarbaz) + On Channel PJSIP/1234-0000004: + Set(GROUP()=foobarbill) + On Channel PJSIP/1234-0000005: + Set(GROUP()=somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_CHANNEL_LIST(foobarbaz)} + Given the above: + This will find the channels that are in the group 'foobarbaz' + Variable channels_found will be set to: PJSIP/1234-0000003 + + + Find channels that have the category name of 'barbaz' + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName@categoryName) + On Channel PJSIP/1234-0000002: + Set(GROUP()=foo@barbaz) + On Channel PJSIP/1234-0000003: + Set(GROUP()=oof@barbaz) + On Channel PJSIP/1234-0000004: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_CHANNEL_LIST(@barbaz)}) + + Given the above: + This will find the channels that are in group 'foo@foobarbaz' and 'oof@barbaz' since they both have the category barbaz + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + + + Find groups containing 'foo' and category name of 'bar' + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName@categoryName) + On Channel PJSIP/1234-0000002: + Set(GROUP()=foo@bar) + On Channel PJSIP/1234-0000003: + Set(GROUP()=foo@bar) + On Channel PJSIP/1234-0000004: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*@.*bar.*)}) + + Given the above: + This will find the channels that are in the group@category assignment of foo@bar + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + + + + GROUP + GROUP_MATCH_CHANNEL_LIST + + + + + Find channels that are members of groups by regular expression + + + + + + + Search for groups matching group@category and return the channels that are members of those groups, filtering known groups by the regex(s) provided. + If only the group_regex is specified, then return group@category results that only match the group name against the group_regex + If only the category_regex is specified, then return group@category results that only match the category name against the category_regex. + If the search regex parameters are entirely empty, all channels having any kind of group membership will be returned. + Uses standard regular expression matching (see regex(7)). + + Find channels containing the string 'foo' + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName) + On Channel PJSIP/1234-0000003: + Set(GROUP()=foobarbaz) + On Channel PJSIP/1234-0000004: + Set(GROUP()=foobarbill) + On Channel PJSIP/1234-0000005: + Set(GROUP()=somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*)}) + Given the above: + This will find the channels that are in groups 'foobarbaz' and 'foobarbill' since they both match .*foo.* regex against the group name + Variable channels_found will be set to: PJSIP/1234-0000003,PJSIP/1234-0000004 + + + Find channels in groups containing category name of 'bar' + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName@categoryName) + On Channel PJSIP/1234-0000002: + Set(GROUP()=foo@barbaz) + On Channel PJSIP/1234-0000003: + Set(GROUP()=foo@barbill) + On Channel PJSIP/1234-0000004: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(@.*bar.*)}) + + Given the above: + This will find the channels that are in groups 'foo@barbaz' and 'foo@barbill' since they both match .*bar.* regex against the category name + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + + + Find channels in groups where they contain 'foo' and have the matching category contain the name of 'bar' + + On Channel PJSIP/1234-0000001: + Set(GROUP()=groupName@categoryName) + On Channel PJSIP/1234-0000002: + Set(GROUP()=foo@bar) + On Channel PJSIP/1234-0000003: + Set(GROUP()=foo@barbill) + On Channel PJSIP/1234-0000004: + Set(GROUP()=anything@somethingelse) + On any Channel: + Assuming that channels still exist that have the above associated GROUP() assignents + Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*@.*bar.*)} + + Given the above: + This will find the channels that are in groups 'foo@barbaz' and 'foo@barbill' since they both match .*foo*. against the group name and .*bar.* regex against the category name + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + + + + GROUP + GROUP_CHANNEL_LIST + + 1.2.0 @@ -62,17 +294,17 @@ Counts the number of channels in the groups matching the specified pattern. - + A standard regular expression used to match a group name. - + A standard regular expression used to match a category name. Calculates the group count for all groups that match the specified pattern. Note: category matching is applied after matching based on group. - Uses standard regular expression matching on both (see regex(7)). + Uses standard regular expression matching on both parameters (see regex(7)). @@ -82,15 +314,61 @@ Gets or sets the channel group. - + + + Group name. + Category name. category can be employed for more fine grained group management. Each channel - can only be member of exactly one group per category. + can only be member of exactly one group per category. Once a group is assigned to + a channel, per-group variables can then be assigned via GROUP_VAR() + + + GROUP_VAR + + + + + Gets or sets a variable on a channel group. + + + + Category name. + + + + + Once a GROUP() is assinged to a channel, variables can then be attached to that group. As long as the + group exists, these variables will exist. When the group no longer exists, the variables will be cleaned up + automatically. + + + These variables can be considered 'globals for a group of channels'. These variables are + like a SHARED() variable but for a collection of channels. + + + On Channel 1 + Set(GROUP()=foo) + Set(GROUP_VAR(foo,savethis)=123) + + On Channel 2 -- Assuming Channel1 is still up and Channel1 is still a member of GROUP(foo) + We can now join the same Group and read a Group Variable + Set(GROUP()=foo) + NoOp(${GROUP_VAR(foo,savethis) <-- This prints '123' + + On Channel 3 -- Assuming Channel1 is still up and Channel1 is still a member of GROUP(foo) + We do not need to join the group in order to read a Group Variable + NoOp(${GROUP_VAR(foo,savethis) <-- This prints '123' + + + GROUP + SHARED + @@ -104,15 +382,179 @@ Gets a list of the groups set on a channel. + + + Add channel group assignments + + + + + Channel to operate on. + + + Group name to set. + + + Category name to set. + + + + For more information, see the dialplan function GROUP() + + + + + Remove channel group assignments + + + + + Channel to operate on. + + + Group name to remove. + + + Category name to remove. + + + + For more information, see the dialplan function GROUP() + + + + + Dump all group information to the console + + + When executed, this will show all group assignments and group variables + in the console + + + + + Get channel group variables. + + + + + + + + + + At a minimum, either group or category must be provided. + For more information, see the dialplan function GROUP_VAR(). + + + + + + Set channel group variables. + + + + + + + + + + + At a minimum, either group or category must be provided. + For more information, see the dialplan function GROUP_VAR(). + + + + + + Show channel groups. With optional filtering + + + + + The exact group name to find, or to use a regular expression: set this parameter to: /regex/ + + + The exact category to find, or to use a regular expression: set this parameter to: /regex/ + + + + + This will return a list of channel groups that are in use. + For more information, see the dialplan function GROUP(). + + + + + + Show group channel assignments. With optional filtering + + + + + The exact group name to find, or to use a regular expression: set this parameter to: /regex/ + + + The exact category to find, or to use a regular expression: set this parameter to: /regex/ + + + + + This will return a list the channels that are within each group. + For more information, see the dialplan function GROUP(). + + + + + + Show group channel variable assignments. + + + + + + + This will return a list of groups and the variables assigned in each group. + For more information, see the dialplan function GROUP_VAR(). + + + + + + + Raised in response to a a GroupVarGet command + + + + ActionID (if any) that was passed into the GroupVarGet request + + + Name of the group that the variable is a part of + + + Name of the category that the variable is a part of + + + The variable that was requested + + + The value of the variable + + + + ***/ +static const char *dumpgroups_app = "DumpGroups"; + static int group_count_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) { int ret = -1; int count = -1; - char group[80] = "", category[80] = ""; + char group[MAX_GROUP_LEN] = "", category[MAX_CATEGORY_LEN] = ""; if (!chan) { ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd); @@ -128,15 +570,18 @@ static int group_count_function_read(struct ast_channel *chan, const char *cmd, ast_app_group_list_rdlock(); for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { - if (gi->chan != chan) + if (gi->chan != chan) { continue; - if (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))) + } + if (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))) { break; + } } if (gi) { ast_copy_string(group, gi->group, sizeof(group)); - if (!ast_strlen_zero(gi->category)) + if (!ast_strlen_zero(gi->category)) { ast_copy_string(category, gi->category, sizeof(category)); + } } ast_app_group_list_unlock(); } @@ -161,8 +606,8 @@ static int group_match_count_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) { - char group[80] = ""; - char category[80] = ""; + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category)); @@ -198,12 +643,15 @@ static int group_function_read(struct ast_channel *chan, const char *cmd, ast_app_group_list_rdlock(); for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { - if (gi->chan != chan) + if (gi->chan != chan) { continue; - if (ast_strlen_zero(data)) + } + if (ast_strlen_zero(data)) { break; - if (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, data)) + } + if (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, data)) { break; + } } if (gi) { @@ -249,6 +697,553 @@ static struct ast_custom_function group_function = { .write = group_function_write, }; + +/* GROUP_VAR and related */ + +static int group_var_function_read(struct ast_channel *chan, const char *cmd, + char *data, char *buf, size_t len) +{ + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; + char *variable_value; + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(groupcategory); + AST_APP_ARG(varname); + ); + AST_STANDARD_APP_ARGS(args, data); + + buf[0] = '\0'; + + if (ast_strlen_zero(args.groupcategory) || ast_strlen_zero(args.varname)) { + ast_log(LOG_WARNING, "Syntax GROUP_VAR(group[@category],)\n"); + return -1; + } + + if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { + return -1; + } + + variable_value = ast_app_group_get_var(group, category, args.varname); + + if (variable_value) { + ast_copy_string(buf, variable_value, len); + ast_free(variable_value); + } + + return 0; +} + +static int group_var_function_write(struct ast_channel *chan, const char *cmd, + char *data, const char *value) +{ + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; + int result; + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(groupcategory); + AST_APP_ARG(varname); + ); + AST_STANDARD_APP_ARGS(args, data); + + if (!value) { + value = ""; + } + + if (ast_strlen_zero(args.groupcategory) || ast_strlen_zero(args.varname)) { + ast_log(LOG_WARNING, "Syntax GROUP_VAR(group[@category],)=)\n"); + return -1; + } + + ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category)); + result = ast_app_group_set_var(chan, group, category, args.varname, value); + + if (result != 0) { + /* We know we're not passing any NULL values, so our error has to be 'non-exist' */ + ast_log(LOG_WARNING, "GROUP_VAR() Variable set failed (group doesn't exist)"); + return -1; + } + + return 0; +} + +static int manager_group_set(struct mansession *s, const struct message *m) +{ + const char *channel = astman_get_header(m, "Channel"); + const char *group = astman_get_header(m, "Group"); + const char *category = astman_get_header(m, "Category"); + + struct ast_channel *chan = NULL; + struct ast_str *group_category = ast_str_create(MAX_GROUP_LEN); + + if (!group_category) { + astman_send_error(s, m, "Unable to allocate new variable. Cannot proceed with GroupSet\n"); + return AMI_SUCCESS; + } + + if (ast_strlen_zero(channel)) { + astman_send_error(s, m, "Channel not specified."); + return AMI_SUCCESS; + } + + chan = ast_channel_get_by_name(channel); + if (!chan) { + astman_send_error(s, m, "Channel not found."); + return AMI_SUCCESS; + } + + if (!group) { + group = ""; + } + + if (!category) { + category = ""; + } + + if (ast_str_set(&group_category, 0, "%s@%s", group, category) == AST_DYNSTR_BUILD_FAILED) { + astman_send_error(s, m, "Unable to allocate new variable. Cannot proceed with GroupSet\n"); + goto done; + } + + if (ast_app_group_set_channel(chan, ast_str_buffer(group_category)) == 0) { + astman_send_ack(s, m, "Group Set"); + ast_channel_unref(chan); + return AMI_SUCCESS; + } + + astman_send_error(s, m, "Group set failed."); + + done: + ast_channel_unref(chan); + ast_free(group_category); + + return AMI_SUCCESS; +} + +static int manager_group_remove(struct mansession *s, const struct message *m) +{ + const char *group = astman_get_header(m, "Group"); + const char *category = astman_get_header(m, "Category"); + + if (ast_app_group_remove_all_channels(group, category) == 0) { + astman_send_ack(s, m, "Group Removed"); + return AMI_SUCCESS; + } + + astman_send_error(s, m, "Group remove failed."); + + return AMI_SUCCESS; +} + +static int manager_group_var_get(struct mansession *s, const struct message *m) +{ + const char *id = astman_get_header(m, "ActionID"); + const char *group = astman_get_header(m, "Group"); + const char *category = astman_get_header(m, "Category"); + const char *variable = astman_get_header(m, "Variable"); + char *variable_value; + char idText[256] = ""; + + if (ast_strlen_zero(group)) { + astman_send_error(s, m, "No group specified."); + return 0; + } + + if (ast_strlen_zero(variable)) { + astman_send_error(s, m, "No variable specified."); + return 0; + } + + if (!ast_strlen_zero(id)) { + snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id); + } + + if (!category) { + category = ""; + } + + variable_value = ast_app_group_get_var(group, category, variable); + + if (!variable_value) { + astman_send_error(s, m, "Group variable not found"); + return 0; + } + + astman_send_ack(s, m, "Result will follow"); + astman_append(s, "Event: GroupVarGetResponse\r\n" + "Group: %s\r\n" + "Category: %s\r\n" + "Variable: %s\r\n" + "Value: %s\r\n" + "%s" + "\r\n", + group, category, variable, variable_value, idText); + + ast_free(variable_value); + + return AMI_SUCCESS; +} + +static int manager_group_var_set(struct mansession *s, const struct message *m) +{ + const char *group = astman_get_header(m, "Group"); + const char *category = astman_get_header(m, "Category"); + const char *variable = astman_get_header(m, "Variable"); + const char *value = astman_get_header(m, "Value"); + int result = 0; + + if (ast_strlen_zero(group)) { + astman_send_error(s, m, "No group specified."); + return AMI_SUCCESS; + } + + if (ast_strlen_zero(variable)) { + astman_send_error(s, m, "No variable specified."); + return AMI_SUCCESS; + } + + if (!category) { + category = ""; + } + + if (!value) { + value = ""; + } + + result = ast_app_group_set_var(NULL, group, category, variable, value); + + if (result != 0) { + /* We know we're not passing any NULL values, so our error has to be 'non-exist' */ + astman_send_error(s, m, "Variable set failed (group doesn't exist)"); + return 0; + } + + astman_send_ack(s, m, "Variable Set"); + + return 0; +} + +static int manager_groups_show(struct mansession *s, const struct message *m) +{ + const char *id = astman_get_header(m, "ActionID"); + const char *group_or_regex = astman_get_header(m, "Group"); /* could be a regex, if starting with '/' */ + const char *category_or_regex = astman_get_header(m, "Category"); /* could be a regex, if starting with '/' */ + + const char *group_match = NULL; + const char *category_match = NULL; + + struct ast_str *group_regex_string = NULL; + struct ast_str *category_regex_string = NULL; + + regex_t regexbuf_group; + regex_t regexbuf_category; + + struct ast_group_meta *gmi = NULL; + char idText[256] = ""; + int groups = 0; + + if (!ast_strlen_zero(group_or_regex)) { + if (group_or_regex[0] == '/') { + group_regex_string = ast_str_create(strlen(group_or_regex)); + if (!group_regex_string) { + astman_send_error(s, m, "Memory Allocation Failure"); + return 0; /* Nothing to clean up */ + } + + /* Make "/regex/" into "regex" */ + if (ast_regex_string_to_regex_pattern(group_or_regex, &group_regex_string) != 0) { + astman_send_error(s, m, "Regex format invalid, Group param should be /regex/"); + ast_free(group_regex_string); + return AMI_SUCCESS; /* Nothing else to clean up */ + } + + /* if regex compilation fails, whole command fails */ + if (regcomp(®exbuf_group, ast_str_buffer(group_regex_string), REG_EXTENDED | REG_NOSUB)) { + astman_send_error_va(s, m, "Regex compile failed on: %s", group_or_regex); + ast_free(group_regex_string); + return AMI_SUCCESS; /* Nothing else to clean up */ + } + } else { + group_match = group_or_regex; + } + } + + if (!ast_strlen_zero(category_or_regex)) { + if (category_or_regex[0] == '/') { + category_regex_string = ast_str_create(strlen(category_or_regex)); + if (!category_regex_string) { + astman_send_error(s, m, "Memory Allocation Failure"); + goto done; + } + + /* Make "/regex/" into "regex" */ + if (ast_regex_string_to_regex_pattern(category_or_regex, &category_regex_string) != 0) { + astman_send_error(s, m, "Regex format invalid, Category param should be /regex/"); + ast_free(category_regex_string); + category_regex_string = NULL; + goto done; + } + + /* if regex compilation fails, whole command fails */ + if (regcomp(®exbuf_category, ast_str_buffer(category_regex_string), REG_EXTENDED | REG_NOSUB)) { + astman_send_error_va(s, m, "Regex compile failed on: %s", category_or_regex); + ast_free(category_regex_string); + category_regex_string = NULL; + goto done; + } + } else { + category_match = category_or_regex; + } + } + + if (!ast_strlen_zero(id)) { + snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id); + } + + astman_send_listack(s, m, "Groups will follow", "start"); + + ast_app_group_meta_rdlock(); + for (gmi = ast_app_group_meta_head(); gmi; gmi = AST_LIST_NEXT(gmi, group_meta_list)) { + if (group_regex_string && regexec(®exbuf_group, gmi->group, 0, NULL, 0)) { + continue; + } + + if (category_regex_string && regexec(®exbuf_category, gmi->category, 0, NULL, 0)) { + continue; + } + + if (group_match && strcmp(group_match, gmi->group)) { + continue; + } + + if (category_match && strcmp(category_match, gmi->category)) { + continue; + } + + astman_append(s, + "Event: GroupsShow\r\n" + "Group: %s\r\n" + "Category: %s\r\n" + "%s" + "\r\n", gmi->group, gmi->category, idText); + + groups++; + } + ast_app_group_meta_unlock(); + + astman_append(s, + "Event: GroupsShowComplete\r\n" + "EventList: Complete\r\n" + "ListItems: %d\r\n" + "%s" + "\r\n", groups, idText); + +done: + if (group_regex_string) { + regfree(®exbuf_group); + ast_free(group_regex_string); + } + + if (category_regex_string) { + regfree(®exbuf_category); + ast_free(category_regex_string); + } + + return AMI_SUCCESS; +} + +static int manager_groups_show_channels(struct mansession *s, const struct message *m) +{ + const char *id = astman_get_header(m, "ActionID"); + const char *group_or_regex = astman_get_header(m, "Group"); /* could be a regex, if starting with '/' */ + const char *category_or_regex = astman_get_header(m, "Category"); /* could be a regex, if starting with '/' */ + + const char *group_match = NULL; + const char *category_match = NULL; + + struct ast_str *group_regex_string = NULL; + struct ast_str *category_regex_string = NULL; + + regex_t regexbuf_group; + regex_t regexbuf_category; + + struct ast_group_info *gi = NULL; + char idText[256] = ""; + int channels = 0; + + if (!ast_strlen_zero(group_or_regex)) { + if (group_or_regex[0] == '/') { + group_regex_string = ast_str_create(strlen(group_or_regex)); + if (!group_regex_string) { + astman_send_error(s, m, "Memory Allocation Failure"); + return 0; /* Nothing to clean up */ + } + + /* Make "/regex/" into "regex" */ + if (ast_regex_string_to_regex_pattern(group_or_regex, &group_regex_string) != 0) { + astman_send_error(s, m, "Regex format invalid, Group param should be /regex/"); + ast_free(group_regex_string); + return AMI_SUCCESS; /* Nothing else to clean up */ + } + + /* if regex compilation fails, whole command fails */ + if (regcomp(®exbuf_group, ast_str_buffer(group_regex_string), REG_EXTENDED | REG_NOSUB)) { + astman_send_error_va(s, m, "Regex compile failed on: %s", group_or_regex); + ast_free(group_regex_string); + return AMI_SUCCESS; /* Nothing else to clean up */ + } + } else { + group_match = group_or_regex; + } + } + + if (!ast_strlen_zero(category_or_regex)) { + if (category_or_regex[0] == '/') { + category_regex_string = ast_str_create(strlen(category_or_regex)); + if (!category_regex_string) { + astman_send_error(s, m, "Memory Allocation Failure"); + goto done; + } + + /* Make "/regex/" into "regex" */ + if (ast_regex_string_to_regex_pattern(category_or_regex, &category_regex_string) != 0) { + astman_send_error(s, m, "Regex format invalid, Category param should be /regex/"); + ast_free(category_regex_string); + category_regex_string = NULL; + goto done; + } + + /* if regex compilation fails, whole command fails */ + if (regcomp(®exbuf_category, ast_str_buffer(category_regex_string), REG_EXTENDED | REG_NOSUB)) { + astman_send_error_va(s, m, "Regex compile failed on: %s", category_or_regex); + ast_free(category_regex_string); + category_regex_string = NULL; + goto done; + } + } else { + category_match = category_or_regex; + } + } + + if (!ast_strlen_zero(id)) { + snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id); + } + + astman_send_listack(s, m, "Group channels will follow", "start"); + + ast_app_group_list_rdlock(); + for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { + if (group_regex_string && regexec(®exbuf_group, gi->group, 0, NULL, 0)) { + continue; + } + + if (category_regex_string && regexec(®exbuf_category, gi->category, 0, NULL, 0)) { + continue; + } + + if (group_match && strcmp(group_match, gi->group)) { + continue; + } + + if (category_match && strcmp(category_match, gi->category)) { + continue; + } + + astman_append(s, + "Event: GroupsShowChannels\r\n" + "Group: %s\r\n" + "Category: %s\r\n" + "Channel: %s\r\n" + "%s" + "\r\n", gi->group, gi->category, ast_channel_name(gi->chan), idText); + + channels++; + } + ast_app_group_list_unlock(); + + astman_append(s, + "Event: GroupsShowChannelsComplete\r\n" + "EventList: Complete\r\n" + "ListItems: %d\r\n" + "%s" + "\r\n", channels, idText); + +done: + if (group_regex_string) { + regfree(®exbuf_group); + ast_free(group_regex_string); + } + + if (category_regex_string) { + regfree(®exbuf_category); + ast_free(category_regex_string); + } + + return AMI_SUCCESS; +} + +static int manager_groups_show_variables(struct mansession *s, const struct message *m) +{ + const char *id = astman_get_header(m, "ActionID"); + struct ast_group_meta *gmi = NULL; + char action_id[256] = ""; + int groups = 0; + + struct varshead *headp; + struct ast_var_t *vardata; + struct ast_str *variables = ast_str_create(100); + + if (!variables) { + ast_log(LOG_ERROR, "Unable to allocate new variable. Cannot proceed with GroupsShowVariables().\n"); + return AMI_SUCCESS; + } + + if (!ast_strlen_zero(id)) { + snprintf(action_id, sizeof(action_id), "ActionID: %s\r\n", id); + } + + astman_send_listack(s, m, "Group variables will follow", "start"); + + ast_app_group_meta_rdlock(); + for (gmi = ast_app_group_meta_head(); gmi; gmi = AST_LIST_NEXT(gmi, group_meta_list)) { + headp = &gmi->varshead; + ast_str_reset(variables); + + AST_LIST_TRAVERSE(headp, vardata, entries) { + ast_str_append(&variables, 0, "Variable(%s): %s\r\n", ast_var_name(vardata), ast_var_value(vardata)); + } + + astman_append(s, + "Event: GroupsShowVariables\r\n" + "Group: %s\r\n" + "Category: %s\r\n" + "%s" + "%s" + "\r\n", gmi->group, gmi->category, action_id, ast_str_buffer((variables))); + + groups++; + } + ast_app_group_meta_unlock(); + + astman_append(s, + "Event: GroupsShowVariablesComplete\r\n" + "EventList: Complete\r\n" + "ListItems: %d\r\n" + "%s" + "\r\n", groups, action_id); + + ast_free(variables); + + return AMI_SUCCESS; +} + +static struct ast_custom_function group_var_function = { + .name = "GROUP_VAR", + .syntax = "GROUP_VAR(groupname[@category],var)", + .synopsis = "Gets or sets a channel group variable.", + .read = group_var_function_read, + .write = group_var_function_write, +}; + static int group_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) { @@ -262,19 +1257,23 @@ static int group_list_function_read(struct ast_channel *chan, const char *cmd, ast_app_group_list_rdlock(); for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { - if (gi->chan != chan) + if (gi->chan != chan) { continue; + } + if (!ast_strlen_zero(tmp1)) { ast_copy_string(tmp2, tmp1, sizeof(tmp2)); - if (!ast_strlen_zero(gi->category)) + if (!ast_strlen_zero(gi->category)) { snprintf(tmp1, sizeof(tmp1), "%s %s@%s", tmp2, gi->group, gi->category); - else + } else { snprintf(tmp1, sizeof(tmp1), "%s %s", tmp2, gi->group); + } } else { - if (!ast_strlen_zero(gi->category)) + if (!ast_strlen_zero(gi->category)) { snprintf(tmp1, sizeof(tmp1), "%s@%s", gi->group, gi->category); - else + } else { snprintf(tmp1, sizeof(tmp1), "%s", gi->group); + } } } @@ -285,21 +1284,293 @@ static int group_list_function_read(struct ast_channel *chan, const char *cmd, return 0; } +static int group_match_list_function_read(struct ast_channel *chan, const char *cmd, + char *data, char *buf, size_t len) +{ + struct ast_group_meta *gmi = NULL; + struct ast_str *foundgroup_str = ast_str_create(MAX_GROUP_LEN + MAX_CATEGORY_LEN); + + char groupmatch[MAX_GROUP_LEN] = ""; + char categorymatch[MAX_CATEGORY_LEN] = ""; + int groups_found = 0; + regex_t regexbuf_group; + regex_t regexbuf_category; + + buf[0] = '\0'; + + if (!foundgroup_str) { + ast_log(LOG_ERROR, "Unable to allocate new variable. Cannot proceed with GROUP_MATCH_LIST()\n"); + return -1; + } + + ast_app_group_split_group(data, groupmatch, sizeof(groupmatch), categorymatch, sizeof(categorymatch)); + + /* if regex compilation fails, return zero matches */ + if (regcomp(®exbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) { + ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch); + return -1; + } + + if (regcomp(®exbuf_category, categorymatch, REG_EXTENDED | REG_NOSUB)) { + ast_log(LOG_ERROR, "Regex compile failed on: %s\n", categorymatch); + regfree(®exbuf_group); + return -1; + } + + /* Traverse all groups, and keep track of what we find */ + ast_app_group_meta_rdlock(); + for (gmi = ast_app_group_meta_head(); gmi; gmi = AST_LIST_NEXT(gmi, group_meta_list)) { + if (!regexec(®exbuf_group, gmi->group, 0, NULL, 0) && (ast_strlen_zero(categorymatch) || (!ast_strlen_zero(gmi->category) && !regexec(®exbuf_category, gmi->category, 0, NULL, 0)))) { + if (groups_found > 1) { + ast_str_append(&foundgroup_str, 0, ","); + } + + ast_str_append(&foundgroup_str, 0, "%s@%s", gmi->group, gmi->category); + + groups_found++; + } + } + ast_app_group_meta_unlock(); + + snprintf(buf, len, "%s", ast_str_buffer(foundgroup_str)); + + regfree(®exbuf_group); + regfree(®exbuf_category); + + return 0; +} + +static int dumpgroups_exec(struct ast_channel *chan, const char *data) +{ +#define FORMAT_STRING_CHANNELS "%-25s %-20s %-20s\n" +#define FORMAT_STRING_GROUPS "%-20s %-20s\n" +#define FORMAT_STRING_VAR " %s=%s\n" + + static char *line = "================================================================================"; + static char *thinline = "-----------------------------------"; + + struct ast_group_info *gi = NULL; + struct ast_group_meta *gmi = NULL; + struct varshead *headp; + struct ast_var_t *variable = NULL; + int numgroups = 0; + int numchans = 0; + struct ast_str *out = ast_str_create(4096); + + if (!out) { + ast_log(LOG_ERROR, "Unable to allocate new variable. Cannot proceed with DumpGroups().\n"); + return -1; + } + + ast_verbose("%s\n", line); + ast_verbose(FORMAT_STRING_CHANNELS, "Channel", "Group", "Category\n"); + + ast_app_group_list_rdlock(); + gi = ast_app_group_list_head(); + while (gi) { + ast_str_append(&out, 0, FORMAT_STRING_CHANNELS, ast_channel_name(gi->chan), gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category)); + numchans++; + gi = AST_LIST_NEXT(gi, group_list); + } + + ast_app_group_list_unlock(); + + ast_str_append(&out, 0, "%d active group assignment%s\n", numchans, ESS(numchans)); + + ast_str_append(&out, 0, "%s\n", thinline); + /****************** Group Variables ******************/ + + ast_str_append(&out, 0, "Group Variables Category\n"); + + /* Print group variables */ + ast_app_group_meta_rdlock(); + gmi = ast_app_group_meta_head(); + while (gmi) { + ast_str_append(&out, 0, FORMAT_STRING_GROUPS, gmi->group, (strcmp(gmi->category, "") ? gmi->category : "(Default)")); + numgroups++; + headp = &gmi->varshead; + + AST_LIST_TRAVERSE(headp, variable, entries) { + ast_str_append(&out, 0, FORMAT_STRING_VAR, ast_var_name(variable), ast_var_value(variable)); + } + + gmi = AST_LIST_NEXT(gmi, group_meta_list); + } + ast_app_group_meta_unlock(); + + ast_str_append(&out, 0, "%s\n", line); + + ast_verbose("%s\n", ast_str_buffer(out)); + + ast_free(out); + + return 0; + +#undef FORMAT_STRING_CHANNELS +#undef FORMAT_STRING_GROUPS +#undef FORMAT_STRING_VAR +} + +static struct ast_custom_function group_match_list_function = { + .name = "GROUP_MATCH_LIST", + .read = group_match_list_function_read, + .write = NULL, +}; + static struct ast_custom_function group_list_function = { .name = "GROUP_LIST", .read = group_list_function_read, .write = NULL, }; +static int group_channel_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; + struct ast_group_info *gi = NULL; + int out_len = 0; + int remaining_buf = len; + char *buf_pos = buf; + + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(groupcategory); + ); + AST_STANDARD_APP_ARGS(args, data); + + pbx_builtin_setvar_helper(chan, "GROUP_CHANNEL_LIST_ERROR", NULL); + + buf[0] = '\0'; + + if (ast_strlen_zero(args.groupcategory)) { + ast_log(LOG_WARNING, "Syntax GROUP_CHANNEL_LIST(group[@category])\n"); + return -1; + } + + if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { + return -1; + } + + ast_app_group_list_rdlock(); + gi = ast_app_group_list_head(); + while (gi) { + if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { + int write_len; + + /* In the odd event we go over the buffer length, don't include a partial channel name */ + int channel_name_len = strlen(ast_channel_name(gi->chan)); + + if ((out_len + channel_name_len + 1) > len) { /* +1 for null */ + ast_log(LOG_WARNING, "GROUP_CHANNEL_LIST(%s) Channel membership list too large for buffer, truncating.\n", args.groupcategory); + pbx_builtin_setvar_helper(chan, "GROUP_CHANNEL_LIST_ERROR", "TRUNCATED"); + break; + } + + write_len = snprintf(buf_pos, remaining_buf, "%s,", ast_channel_name(gi->chan)); + /* Note we already prevent buffer overrun above, write_len will always be characters written */ + out_len += write_len; + buf_pos += write_len; + remaining_buf -= write_len; + } + + gi = AST_LIST_NEXT(gi, group_list); + } + ast_app_group_list_unlock(); + + /* delete the last comma. We'll always have a final comma, because we already do overlength check above, so we'll never have a partial write */ + if (out_len) { + buf_pos--; + *buf_pos = '\0'; + } + + return 0; +} + +static struct ast_custom_function group_channel_list_function = { + .name = "GROUP_CHANNEL_LIST", + .read = group_channel_list_function_read, +}; + +static int group_match_channel_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; + struct ast_group_info *gi = NULL; + struct ast_str *out = ast_str_create(1024); + int out_len = 0; + + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(groupcategory); + ); + AST_STANDARD_APP_ARGS(args, data); + + if (!out) { + ast_log(LOG_ERROR, "Unable to allocate new variable. Cannot proceed with GROUP_MATCH_CHANNEL_LIST().\n"); + return -1; + } + + buf[0] = 0; + + if (ast_strlen_zero(args.groupcategory)) { + ast_log(LOG_WARNING, "Syntax GROUP_MATCH_CHANNEL_LIST(group[@category])\n"); + return -1; + } + + if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { + return -1; + } + + ast_app_group_list_rdlock(); + gi = ast_app_group_list_head(); + while (gi) { + if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { + ast_str_append(&out, 0, "%s,", ast_channel_name(gi->chan)); + } + + gi = AST_LIST_NEXT(gi, group_list); + } + ast_app_group_list_unlock(); + + out_len = strlen(ast_str_buffer(out)); + + if (out_len) { + if (out_len <= len) { + len -= 1; /* rid , only if we didn't go over the buffer limit */ + } + + ast_copy_string(buf, ast_str_buffer(out), len); + } + + ast_free(out); + + return 0; +} + +static struct ast_custom_function group_match_channel_list_function = { + .name = "GROUP_MATCH_CHANNEL_LIST", + .read = group_match_channel_list_function_read, +}; + static int unload_module(void) { int res = 0; res |= ast_custom_function_unregister(&group_count_function); res |= ast_custom_function_unregister(&group_match_count_function); + res |= ast_custom_function_unregister(&group_match_list_function); + res |= ast_custom_function_unregister(&group_match_channel_list_function); res |= ast_custom_function_unregister(&group_list_function); + res |= ast_custom_function_unregister(&group_channel_list_function); + res |= ast_custom_function_unregister(&group_var_function); res |= ast_custom_function_unregister(&group_function); + res |= ast_unregister_application(dumpgroups_app); + + res |= ast_manager_unregister("GroupVarGet"); + res |= ast_manager_unregister("GroupVarSet"); + res |= ast_manager_unregister("GroupsShow"); + res |= ast_manager_unregister("GroupsShowChannels"); + res |= ast_manager_unregister("GroupsShowVariables"); + return res; } @@ -309,9 +1580,23 @@ static int load_module(void) res |= ast_custom_function_register(&group_count_function); res |= ast_custom_function_register(&group_match_count_function); + res |= ast_custom_function_register(&group_match_list_function); + res |= ast_custom_function_register(&group_match_channel_list_function); res |= ast_custom_function_register(&group_list_function); + res |= ast_custom_function_register(&group_channel_list_function); + res |= ast_custom_function_register(&group_var_function); res |= ast_custom_function_register(&group_function); + res |= ast_register_application_xml(dumpgroups_app, dumpgroups_exec); + + res |= ast_manager_register_xml("GroupSet", EVENT_FLAG_CALL, manager_group_set); + res |= ast_manager_register_xml("GroupRemove", EVENT_FLAG_CALL, manager_group_remove); + res |= ast_manager_register_xml("GroupVarGet", EVENT_FLAG_CALL, manager_group_var_get); + res |= ast_manager_register_xml("GroupVarSet", EVENT_FLAG_CALL, manager_group_var_set); + res |= ast_manager_register_xml("GroupsShow", EVENT_FLAG_REPORTING, manager_groups_show); + res |= ast_manager_register_xml("GroupsShowChannels", EVENT_FLAG_REPORTING, manager_groups_show_channels); + res |= ast_manager_register_xml("GroupsShowVariables", EVENT_FLAG_REPORTING, manager_groups_show_variables); + return res; } diff --git a/include/asterisk/app.h b/include/asterisk/app.h index 587b6b04f9..c6fd2a421c 100644 --- a/include/asterisk/app.h +++ b/include/asterisk/app.h @@ -1196,9 +1196,48 @@ struct ast_group_info; /*! \brief Split a group string into group and category, returning a default category if none is provided. */ int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max); +/*! \brief Remove channel assignments for the specified group */ +int ast_app_group_remove_all_channels(const char *group, const char *category); + +/*! \brief Rename a group@category while retaining all the channel memberships + * \return Number of rename operations performed + * \retval -1 on Error + * \retval 0 group@category was not found + */ +int ast_app_group_rename(const char *old_group, const char *old_category, const char *new_group, const char *new_category); + /*! \brief Set the group for a channel, splitting the provided data into group and category, if specified. */ int ast_app_group_set_channel(struct ast_channel *chan, const char *data); +/*! + * \brief Set a group variable for a group@category + * + * \param chan channel (if any) that is setting the group variable (can be NULL) + * \param group group to set the variable on (cannot be null) + * \param category category to set the variable on (cannot be null) + * \param name name of the variable to set (cannot be null) + * \param value value of the variable to set (cannot be null) + * + * \retval 0 On success + * \retval -1 On failure (group@category not found) + * \retval -2 On failure (input validation error) + */ +int ast_app_group_set_var(struct ast_channel *chan, const char *group, const char *category, const char *name, const char *value); + +/*! + * \brief Get a group variable for a group@category + * + * \param group group to get the variable from + * \param category category to get the variable from + * \param name name of the variable to get + * + * \return Allocated string containing variable contents + * \retval NULL On failure (variable in group@category not found) + * + * \post caller must ast_free() the returned value + */ +char *ast_app_group_get_var(const char *group, const char *category, const char *name); + /*! \brief Get the current channel count of the specified group and category. */ int ast_app_group_get_count(const char *group, const char *category); @@ -1223,6 +1262,15 @@ struct ast_group_info *ast_app_group_list_head(void); /*! \brief Unlock the group count list */ int ast_app_group_list_unlock(void); +/*! \brief Read Lock the group meta list */ +int ast_app_group_meta_rdlock(void); + +/*! \brief Get the head of the group meta list */ +struct ast_group_meta *ast_app_group_meta_head(void); + +/*! \brief Unlock the group meta list */ +int ast_app_group_meta_unlock(void); + /*! \brief Define an application argument \param name The name of the argument diff --git a/include/asterisk/channel.h b/include/asterisk/channel.h index 1d3dc99a9f..2e0a4bfae7 100644 --- a/include/asterisk/channel.h +++ b/include/asterisk/channel.h @@ -122,6 +122,8 @@ References: #ifndef _ASTERISK_CHANNEL_H #define _ASTERISK_CHANNEL_H +#include + #include "asterisk/alertpipe.h" #include "asterisk/abstract_jb.h" #include "asterisk/astobj2.h" @@ -175,6 +177,9 @@ extern "C" { #define MAX_MUSICCLASS 80 /*!< Max length of the music class setting */ #define AST_MAX_USER_FIELD 256 /*!< Max length of the channel user field */ +#define MAX_GROUP_LEN 80 /*!< Max length of a channel group */ +#define MAX_CATEGORY_LEN 80 /*!< Max length of a channel group category */ + #include "asterisk/frame.h" #include "asterisk/chanvars.h" #include "asterisk/config.h" @@ -2980,6 +2985,18 @@ struct ast_group_info { AST_LIST_ENTRY(ast_group_info) group_list; }; +/*! \brief list of groups currently in use, with a pointer to a list of channels within the groups */ +struct ast_group_meta { + int num_channels; /*!< number of channels in this group */ + struct varshead varshead; /*!< A linked list for group variables. See \ref AstGroupVar */ + + AST_LIST_ENTRY(ast_group_info) channels_list; /*!< List of channels in this group */ + AST_LIST_ENTRY(ast_group_meta) group_meta_list; /*!< Next group */ + + char category[MAX_CATEGORY_LEN]; + char group[MAX_GROUP_LEN]; +}; + #define ast_channel_lock(chan) ao2_lock(chan) #define ast_channel_unlock(chan) ao2_unlock(chan) #define ast_channel_trylock(chan) ao2_trylock(chan) @@ -3211,6 +3228,7 @@ struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context); /*! + * \brief Find a channel by a uniqueid * * \param uniqueid The uniqueid to search for @@ -3220,6 +3238,34 @@ struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *cont */ struct ast_channel *ast_channel_get_by_uniqueid(const char *uniqueid); +/* + * \brief Find a channel by a regex string + * + * \arg regex_string the regex pattern to search for + * + * Return a channel that where the regex pattern matches the channel name + * + * \retval a channel that matches the regex pattern + * \retval NULL if no channel was found or pattern is bad + * + * \since 23 + */ +struct ast_channel *ast_channel_get_by_regex(const char *regex_string); + +/*! + * \brief Find a channel by a regex pattern + * + * \arg regex the compiled regex pattern to search for + * + * Return a channel that where the regex pattern matches the channel name + * + * \retval a channel that matches the regex pattern + * \retval NULL if no channel was found + * + * \since 23 + */ +struct ast_channel *ast_channel_get_by_regex_compiled(regex_t *regex); + /*! @} End channel search functions. */ /*! diff --git a/include/asterisk/chanvars.h b/include/asterisk/chanvars.h index 1a303c5f73..c867baef9e 100644 --- a/include/asterisk/chanvars.h +++ b/include/asterisk/chanvars.h @@ -33,27 +33,143 @@ struct ast_var_t { AST_LIST_HEAD_NOLOCK(varshead, ast_var_t); + +/*! + * \brief Create a new variables list and initalize to empty + * + * \retval NULL on error + * \retval returns the pointer to the newly created list on success + */ struct varshead *ast_var_list_create(void); + +/*! + * \brief Remove all variables from the list, free them and also free the list + * + * \param head pointer to the list + * + */ void ast_var_list_destroy(struct varshead *head); struct ast_var_t *_ast_var_assign(const char *name, const char *value, const char *file, int lineno, const char *function); + +/*! + * \brief Insert a new variable into the variables list and store the value + * + * \param name name of the variable to set + * \param value value of the variable to set + * + * \retval NULL on error + * \retval returns a populated struct ast_var_t + */ #define ast_var_assign(name, value) _ast_var_assign(name, value, __FILE__, __LINE__, __PRETTY_FUNCTION__) +/*! + * \brief Free a variable. This does not remove the variable from the list that it might be a part of + * \see linkedlists.h + * + * \see ast_var_find + * \see ast_var_assign + * + * \param var must be a struct ast_var_t* that's been set up with ast_var_assign + * + */ void ast_var_delete(struct ast_var_t *var); + +/*! + * \brief Return the name component of an existing struct ast_var_t, stripping any _ or __ inheritance modifiers + * + * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) + * + * \retval NULL on error + * \retval variable name on success + */ const char *ast_var_name(const struct ast_var_t *var); + +/*! + * \brief Return the full name component of an existing struct ast_var_t, including any _ or __ inheritance modifiers + * + * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) + * + * \retval NULL on error + * \retval variable name on success + */ const char *ast_var_full_name(const struct ast_var_t *var); + +/*! + * \brief Return the value component of an existing struct ast_var_t + * + * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) + * + * \retval NULL on error + * \retval variable value on success + */ const char *ast_var_value(const struct ast_var_t *var); + +/*! + * \brief Find a variable by full name + * + * \note If the original variable was set with a _ or __ prefix, the name param for this search will have to match exactly + * + * \see ast_var_full_name + * + * \param varshead pointer to an existing and fully set up variables list + * \param name name of the variable to find + * + * \retval variable value on success + * \retval NULL on not found + */ char *ast_var_find(const struct varshead *head, const char *name); + +/*! + * \brief Create a brand new variables list with the same variables as the source list + * + * \param head an existing varshead + * + * \retval NULL on error + * \retval pointer to new list on success + */ struct varshead *ast_var_list_clone(struct varshead *head); +/*! + * \brief Traverse the variable list in the same style as AST_LIST_TRAVERSE + * + * * \param head This is a pointer to the list head structure + * \param var This is the name of the variable that will hold a pointer to the + * current list entry on each iteration. It must be declared before calling + * this macro. + * \param field This is the name of the field (declared using AST_LIST_ENTRY()) + * used to link entries of this list together. + * + * + * \see AST_LIST_TRAVERSE + */ #define AST_VAR_LIST_TRAVERSE(head, var) AST_LIST_TRAVERSE(head, var, entries) +/*! + * \brief Insert into the end of the variables list in the same style as AST_LIST_INSERT_TAIL + * + * \see AST_LIST_INSERT_TAIL + * + * \param head list to insert into + * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) + * + */ static inline void AST_VAR_LIST_INSERT_TAIL(struct varshead *head, struct ast_var_t *var) { if (var) { AST_LIST_INSERT_TAIL(head, var, entries); } } + +/*! + * \brief Insert into the beginning of the variables list in the same style as AST_LIST_INSERT_HEAD + * + * \see AST_LIST_INSERT_HEAD + * + * \param head list to insert into + * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) + * + */ static inline void AST_VAR_LIST_INSERT_HEAD(struct varshead *head, struct ast_var_t *var) { if (var) { AST_LIST_INSERT_HEAD(head, var, entries); diff --git a/main/app.c b/main/app.c index 480b1ce2c4..f3dd2ccad4 100644 --- a/main/app.c +++ b/main/app.c @@ -61,6 +61,7 @@ #include "asterisk/indications.h" #include "asterisk/linkedlists.h" #include "asterisk/threadstorage.h" +#include "asterisk/manager.h" #include "asterisk/test.h" #include "asterisk/module.h" #include "asterisk/astobj2.h" @@ -69,6 +70,95 @@ #include "asterisk/json.h" #include "asterisk/format_cache.h" +/*** DOCUMENTATION + + + Raised when a group has been created. Note: GroupChannelAdd events will show which channels have been assigned this group@category + + + The category portion of the group@category that has been created + + + The group portion of the group@category that has been created + + + + + + + Raised when a channel is now a part of a group@category GROUP() assignment + + + Channel that is now part of this group@category + + + Uniqueid of the channel that is now part of this group@category + + + The category portion of the group@category of the GROUP() that the channel is now a part of + + + The group portion of the group@category of the GROUP() that the channel is now a part of + + + + + + + Raised in response to when a Group Variable is set using GROUP_VAR() on a group@category GROUP() + + + Name of the group that the variable was set on + + + Name of the category that the variable was set on + + + Channel (if any) that caused the variable to be set + + + The variable that was set + + + The value of the variable + + + + + + + Raised when a channel is no longer part of a group@category GROUP() assignment + + + Channel that no longer is part of this group@category + + + Uniqueid of the channel that is no longer is part of this group + + + The category portion of the group@category of the GROUP() that the channel was a part of + + + The group portion of the group@category of the GROUP() that the channel was a part of + + + + + + + Raised when a group has been completely removed. Note: GroupChannelRemove events will show which channels no longer are assigned to this group@category + + + The category portion of the group@category that is no longer present + + + The group portion of the group@category that is no longer present + + + + + ***/ + AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf); static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL; @@ -118,10 +208,36 @@ static void *shaun_of_the_dead(void *data) return NULL; } +struct group_data_store; + +/* \brief a single group assignment entry */ +struct group_list_entry { + struct ast_str *group; /*!< A group assignment is group@category, this is the group part */ + struct ast_str *category; /*!< This is the category part */ + + struct group_data_store *group_store; /*!< The group_data_store we live on */ + + AST_LIST_ENTRY(group_list_entry) entries; /*!< Next group */ +}; + +AST_LIST_HEAD_NOLOCK(group_list, group_list_entry); /*!< All GROUP assignments */ + +/* Datastore for GROUP() entry storage */ +struct group_data_store { + void *datastore; /*!< Pointer to the datastore that was allocated in */ + struct ast_channel *chan; /*!< Channel this datastore is on */ + + struct group_list group_list_head; /*!< All the GROUPs that this channel is in */ + + AST_LIST_ENTRY(group_data_store) entries; /*!< Next GROUP datastore */ +}; + +AST_RWLIST_HEAD_STATIC(group_stores_list, group_data_store); #define AST_MAX_FORMATS 10 -static AST_RWLIST_HEAD_STATIC(groups, ast_group_info); +static AST_RWLIST_HEAD_STATIC(groups, ast_group_info); /*!< List of channels that are in groups */ +static AST_RWLIST_HEAD_STATIC(groups_meta, ast_group_meta); /*!< List of groups and their metadata */ /*! * \brief This function presents a dialtone and reads an extension into 'collect' @@ -2191,51 +2307,273 @@ int ast_app_group_split_group(const char *data, char *group, int group_max, char return res; } -int ast_app_group_set_channel(struct ast_channel *chan, const char *data) +static int ast_app_group_add_meta_ifneeded(const char *group, const char *category) { - int res = 0; - char group[80] = "", category[80] = ""; - struct ast_group_info *gi = NULL; - size_t len = 0; + struct ast_group_meta *gmi = NULL; /*!< Group metadatas */ - if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) { - return -1; + AST_RWLIST_WRLOCK(&groups_meta); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups_meta, gmi, group_meta_list) { + if (!strcasecmp(gmi->group, group) && !strcasecmp(gmi->category, category)) { + break; /* We only have one list item per group@category */ + } } + AST_RWLIST_TRAVERSE_SAFE_END; - /* Calculate memory we will need if this is new */ - len = sizeof(*gi) + strlen(group) + 1; - if (!ast_strlen_zero(category)) { - len += strlen(category) + 1; + if (!gmi) { + if (!(gmi = ast_calloc(1, sizeof(struct ast_group_meta)))) { + AST_RWLIST_UNLOCK(&groups_meta); + return -1; + } + + ast_copy_string(gmi->group, group, MAX_GROUP_LEN); + + if (!ast_strlen_zero(category)) { + ast_copy_string(gmi->category, category, MAX_CATEGORY_LEN); + } + + AST_RWLIST_INSERT_TAIL(&groups_meta, gmi, group_meta_list); + + manager_event(EVENT_FLAG_DIALPLAN, "GroupCreate", + "Category: %s\r\n" + "Group: %s\r\n", + category, group); } - AST_RWLIST_WRLOCK(&groups); - AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { - if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { - AST_RWLIST_REMOVE_CURRENT(group_list); - ast_free(gi); - break; + gmi->num_channels++; + + AST_RWLIST_UNLOCK(&groups_meta); + + return 1; +} + +/* NOTE: Ideally we would also be able to use direct pointers to the group meta, so we don't have to search */ +static int ast_app_group_remove_meta_ifneeded(const char *group, const char *category) +{ + struct ast_group_meta *gmi = NULL; /*!< Group metadatas */ + + struct varshead *headp; + struct ast_var_t *vardata; + + if (!category) { + category = ""; + } + + AST_RWLIST_WRLOCK(&groups_meta); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups_meta, gmi, group_meta_list) { + if (!strcasecmp(gmi->group, group) && !strcasecmp(gmi->category, category) && (--gmi->num_channels <= 0)) { + /* Remove all group variables */ + headp = &gmi->varshead; + + while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) { + ast_var_delete(vardata); + } + + AST_RWLIST_REMOVE_CURRENT(group_meta_list); + ast_free(gmi); + + break; /* We only have one list item per group@category */ } } AST_RWLIST_TRAVERSE_SAFE_END; + AST_RWLIST_UNLOCK(&groups_meta); - if (ast_strlen_zero(group)) { - /* Enable unsetting the group */ - } else if ((gi = ast_calloc(1, len))) { - gi->chan = chan; - gi->group = (char *) gi + sizeof(*gi); - strcpy(gi->group, group); - if (!ast_strlen_zero(category)) { - gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1; - strcpy(gi->category, category); + if (gmi) { + manager_event(EVENT_FLAG_DIALPLAN, "GroupDestroy", + "Category: %s\r\n" + "Group: %s\r\n", + category, group); + } + + return (gmi != NULL); +} + +int ast_app_group_set_channel(struct ast_channel *chan, const char *data) +{ + int res = 0; + char group[MAX_GROUP_LEN] = "", category[MAX_CATEGORY_LEN] = ""; + struct ast_group_info *gi = NULL; + size_t len = 0; + + if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) { + return -1; + } + + /* Calculate memory we will need if this is new */ + len = sizeof(*gi) + strlen(group) + 1; + if (!ast_strlen_zero(category)) { + len += strlen(category) + 1; + } + + /* Remove previous group assignment within this category if there is one */ + AST_RWLIST_WRLOCK(&groups); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { + if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { + /* Find our group meta data, remove the entire group metadata if we're the last channel */ + ast_app_group_remove_meta_ifneeded(gi->group, gi->category); + + manager_event(EVENT_FLAG_DIALPLAN, "GroupChannelRemove", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Uniqueid: %s\r\n", + ast_channel_name(chan), + gi->category, gi->group, + ast_channel_uniqueid(chan)); + + AST_RWLIST_REMOVE_CURRENT(group_list); + ast_free(gi); + break; + } + } + AST_RWLIST_TRAVERSE_SAFE_END; + + if (ast_strlen_zero(group)) { + /* Enable unsetting the group */ + } else if ((gi = ast_calloc(1, len))) { + gi->chan = chan; + gi->group = (char *) gi + sizeof(*gi); + strcpy(gi->group, group); + if (!ast_strlen_zero(category)) { + gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1; + strcpy(gi->category, category); + } + AST_RWLIST_INSERT_TAIL(&groups, gi, group_list); + + ast_app_group_add_meta_ifneeded(group, category); + + manager_event(EVENT_FLAG_DIALPLAN, "GroupChannelAdd", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Uniqueid: %s\r\n", + ast_channel_name(chan), + category, group, + ast_channel_uniqueid(chan)); + + } else { + res = -1; + } + + AST_RWLIST_UNLOCK(&groups); + + return res; +} + +int ast_app_group_set_var(struct ast_channel *chan, const char *group, const char *category, const char *name, const char *value) +{ + struct ast_group_meta *gmi = NULL; + + struct varshead *headp; + struct ast_var_t *variable = NULL; + + if (!group || !name) { + ast_log(LOG_WARNING, "<%s> GROUP variable assignment failed for %s@%s, group/name cannot be NULL, group variable '%s' not set\n", ast_channel_name(chan), group, category, name); + return -2; + } + + if (!category) { + category = ""; + } + + if (!value) { + value = ""; + } + + /* Find our group meta data */ + AST_RWLIST_WRLOCK(&groups_meta); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups_meta, gmi, group_meta_list) { + if ((strcasecmp(gmi->group, group) != 0) || (strcasecmp(gmi->category, category) != 0)) { + continue; } - AST_RWLIST_INSERT_TAIL(&groups, gi, group_list); - } else { - res = -1; + + headp = &gmi->varshead; + + AST_LIST_TRAVERSE(headp, variable, entries) { + if (strcasecmp(ast_var_name(variable), name) == 0) { + /* there is already such a variable, nuke it so we can replace it */ + ast_var_delete(variable); + break; + } + } + + variable = ast_var_assign(name, value); + + AST_LIST_INSERT_HEAD(headp, variable, entries); + manager_event(EVENT_FLAG_DIALPLAN, "GroupVarSet", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Variable: %s\r\n" + "Value: %s\r\n" + "Uniqueid: %s\r\n", + chan ? ast_channel_name(chan) : "none", + category, group, name, value, + chan ? ast_channel_uniqueid(chan) : "none"); + + break; /* We only have one list item per group@category */ } + AST_RWLIST_TRAVERSE_SAFE_END; + AST_RWLIST_UNLOCK(&groups_meta); - AST_RWLIST_UNLOCK(&groups); + if (!variable) { + ast_log(LOG_WARNING, "<%s> GROUP assignment %s@%s doesn't exist, group variable '%s' not set\n", ast_channel_name(chan), group, category, name); + return -1; + } - return res; + return 0; +} + +char *ast_app_group_get_var(const char *group, const char *category, const char *name) +{ + struct ast_group_meta *gmi = NULL; + struct varshead *headp; + const char *variable; + char *return_value; + struct ast_var_t *ast_var; + int len; + + if (!group || !name) { + return NULL; + } + + if (!category) { + category = ""; + } + + /* Find our group meta data */ + AST_RWLIST_RDLOCK(&groups_meta); + AST_RWLIST_TRAVERSE(&groups_meta, gmi, group_meta_list) { + if ((strcasecmp(gmi->group, group) != 0) || (strcasecmp(gmi->category, category) != 0)) { + continue; + } + + headp = &gmi->varshead; + + AST_LIST_TRAVERSE(headp, ast_var, entries) { + variable = ast_var_name(ast_var); + + if (!strcasecmp(variable, name)) { + /* found it */ + variable = ast_var_value(ast_var); /* Already found it, we can safely re-use */ + len = strlen(variable); + + return_value = ast_malloc(len + 1); + if (!return_value) { + ast_log(LOG_ERROR, "Group Variable Get Failed to allocate memory for return value\n"); + AST_RWLIST_UNLOCK(&groups_meta); + return NULL; + } + + ast_copy_string(return_value, variable, len); + AST_RWLIST_UNLOCK(&groups_meta); + + return return_value; + } + } + } + AST_RWLIST_UNLOCK(&groups_meta); + + return NULL; } int ast_app_group_get_count(const char *group, const char *category) @@ -2276,6 +2614,7 @@ int ast_app_group_match_get_count(const char *groupmatch, const char *category) return 0; } + /* if regex compilation fails, return zero matches */ if (!ast_strlen_zero(category) && regcomp(®exbuf_category, category, REG_EXTENDED | REG_NOSUB)) { ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category); regfree(®exbuf_group); @@ -2301,14 +2640,21 @@ int ast_app_group_match_get_count(const char *groupmatch, const char *category) int ast_app_group_update(struct ast_channel *old, struct ast_channel *new) { struct ast_group_info *gi = NULL; + struct ast_group_info *gi_new = NULL; AST_RWLIST_WRLOCK(&groups); AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { + /* keep channel groups on transfer */ if (gi->chan == old) { + /* only move group if it doesn't already exist on new */ + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi_new, group_list) { + if (gi_new->chan == old && !strcasecmp(gi_new->group, gi->group) && !strcasecmp(gi_new->category, gi->category)) { + break; + } + } + AST_RWLIST_TRAVERSE_SAFE_END; + gi->chan = new; - } else if (gi->chan == new) { - AST_RWLIST_REMOVE_CURRENT(group_list); - ast_free(gi); } } AST_RWLIST_TRAVERSE_SAFE_END; @@ -2317,16 +2663,153 @@ int ast_app_group_update(struct ast_channel *old, struct ast_channel *new) return 0; } +/* Remove all channels from the given group */ +int ast_app_group_remove_all_channels(const char *group, const char *category) +{ + struct ast_group_info *gi = NULL; + int group_meta_found = 0; + + if (!group) { + ast_log(LOG_WARNING, "Group Remove: At the minimum, group must be non-NULL\n"); + return 0; + } + + if (!category) { + category = ""; + } + + /* Traverse group@category channel assignments */ + AST_RWLIST_WRLOCK(&groups); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { + if (strcasecmp(gi->group, group) || strcasecmp(gi->category, category)) { + /* Need to match group@category exactly */ + continue; + } + + manager_event(EVENT_FLAG_DIALPLAN, "GroupChannelRemove", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Uniqueid: %s\r\n", + ast_channel_name(gi->chan), + gi->category, gi->group, + ast_channel_uniqueid(gi->chan)); + + ast_app_group_remove_meta_ifneeded(gi->group, gi->category); + + AST_RWLIST_REMOVE_CURRENT(group_list); + ast_free(gi); + + group_meta_found++; + } + AST_RWLIST_TRAVERSE_SAFE_END; + AST_RWLIST_UNLOCK(&groups); + + return group_meta_found; +} + +int ast_app_group_rename(const char *old_group, const char *old_category, const char *new_group, const char *new_category) +{ + struct ast_group_info *gi = NULL; + struct ast_group_meta *gmi = NULL; /*!< Group metadatas */ + + int groups_found = 0; + + if (!old_group) { + ast_log(LOG_WARNING, "Old Group name is required for group rename\n"); + return -1; + } + + if (!new_group) { + ast_log(LOG_WARNING, "New Group name is required for group rename\n"); + return -1; + } + + if (!old_category) { + old_category = ""; + } + + if (!new_category) { + new_category = ""; + } + + /* Traverse group@category channel assignments */ + AST_RWLIST_WRLOCK(&groups); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { + if (strcasecmp(gi->group, old_group) || strcasecmp(gi->category, old_category)) { + /* Need to match group@category exactly */ + continue; + } + + ast_copy_string(gi->group, new_group, MAX_GROUP_LEN); + ast_copy_string(gi->category, new_category, MAX_CATEGORY_LEN); + groups_found++; + } + AST_RWLIST_TRAVERSE_SAFE_END; + AST_RWLIST_UNLOCK(&groups); + + /* Group Variables */ + AST_RWLIST_WRLOCK(&groups_meta); + AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups_meta, gmi, group_meta_list) { + if (strcasecmp(gmi->group, old_group) || strcasecmp(gmi->category, old_category)) { + /* Need to match group@category exactly */ + continue; + } + + strncpy(gmi->group, new_group, MAX_GROUP_LEN - 1); + strncpy(gmi->category, new_category, MAX_CATEGORY_LEN - 1); + + /* + No groups_found++ here, since we already found it earlier. + If everyone plays by the rules, we'll never have a groups_meta + entry for a group@category without first already having + a group@category itself + */ + } + AST_RWLIST_TRAVERSE_SAFE_END; + AST_RWLIST_UNLOCK(&groups_meta); + + if (groups_found) { + manager_event(EVENT_FLAG_DIALPLAN, "GroupRename", + "OldGroup: %s\r\n" + "OldCategory: %s\r\n" + "NewGroup: %s\r\n" + "NewCategory: %s\r\n", + old_group, + old_category, + new_group, + new_category); + } + + return groups_found; +} + int ast_app_group_discard(struct ast_channel *chan) { struct ast_group_info *gi = NULL; + /* Find and remove all groups associated to this channel */ AST_RWLIST_WRLOCK(&groups); AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { - if (gi->chan == chan) { - AST_RWLIST_REMOVE_CURRENT(group_list); - ast_free(gi); + if (gi->chan != chan) { + continue; } + + manager_event(EVENT_FLAG_DIALPLAN, "GroupChannelRemove", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Uniqueid: %s\r\n", + ast_channel_name(gi->chan), + gi->category, gi->group, + ast_channel_uniqueid(chan)); + + /* Find our group meta data, remove the entire group metadata if we're the last channel */ + ast_app_group_remove_meta_ifneeded(gi->group, gi->category); + + /* Remove this group assignment for this channel */ + AST_RWLIST_REMOVE_CURRENT(group_list); + ast_free(gi); } AST_RWLIST_TRAVERSE_SAFE_END; AST_RWLIST_UNLOCK(&groups); @@ -2354,6 +2837,21 @@ int ast_app_group_list_unlock(void) return AST_RWLIST_UNLOCK(&groups); } +int ast_app_group_meta_rdlock(void) +{ + return AST_RWLIST_RDLOCK(&groups_meta); +} + +struct ast_group_meta *ast_app_group_meta_head(void) +{ + return AST_RWLIST_FIRST(&groups_meta); +} + +int ast_app_group_meta_unlock(void) +{ + return AST_RWLIST_UNLOCK(&groups_meta); +} + unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen) { int argc; diff --git a/main/cli.c b/main/cli.c index 5c324f6a60..6bbf981e48 100644 --- a/main/cli.c +++ b/main/cli.c @@ -2008,8 +2008,9 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl return NULL; } - if (a->argc < 3 || a->argc > 4) + if (a->argc < 3 || a->argc > 4) { return CLI_SHOWUSAGE; + } if (a->argc == 4) { if (regcomp(®exbuf, a->argv[3], REG_EXTENDED | REG_NOSUB)) @@ -2040,6 +2041,64 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl #undef FORMAT_STRING } +static char *group_show_variables(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) +{ +#define FORMAT_STRING "%-20s %-20s\n" +#define FORMAT_STRING_VAR " %s=%s\n" + + struct ast_group_meta *gmi = NULL; + struct varshead *headp; + struct ast_var_t *variable = NULL; + int numgroups = 0; + char group[80]; + char category[80]; + + switch (cmd) { + case CLI_INIT: + e->command = "group show variables"; + e->usage = + "Usage: group show variables [group@[category]]\n" + " Lists all currently active groups and their variables.\n" + " Optional group, or group@category can be used to only show a specific group\n"; + return NULL; + case CLI_GENERATE: + return NULL; + } + + if (a->argc < 3 || a->argc > 4) { + return CLI_SHOWUSAGE; + } + + if (a->argc == 4) { + if (ast_app_group_split_group(a->argv[3], group, sizeof(group), category, sizeof(category))) { + return NULL; + } + } + + ast_cli(a->fd, "Group\n Category\nVariables\n"); + ast_cli(a->fd, "------------------------------\n"); + + /* Print group variables */ + ast_app_group_meta_rdlock(); + gmi = ast_app_group_meta_head(); + while (gmi) { + ast_cli(a->fd, FORMAT_STRING, gmi->group, (strcmp(gmi->category, "") ? gmi->category : "(Default)")); + numgroups++; + headp = &gmi->varshead; + + AST_LIST_TRAVERSE(headp, variable, entries) { + ast_cli(a->fd, FORMAT_STRING_VAR, ast_var_name(variable), ast_var_value(variable)); + } + + gmi = AST_LIST_NEXT(gmi, group_meta_list); + } + ast_app_group_meta_unlock(); + + ast_cli(a->fd, "%d active group%s\n", numgroups, ESS(numgroups)); + return CLI_SUCCESS; +#undef FORMAT_STRING +} + static char *handle_cli_wait_fullybooted(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { switch (cmd) { @@ -2113,7 +2172,6 @@ static struct ast_cli_entry cli_cli[] = { AST_CLI_DEFINE(handle_debug, "Set level of debug chattiness"), AST_CLI_DEFINE(handle_trace, "Set level of trace chattiness"), AST_CLI_DEFINE(handle_verbose, "Set level of verbose chattiness"), - AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"), AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"), @@ -2143,6 +2201,7 @@ static struct ast_cli_entry cli_channels_cli[] = { AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"), AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel"), AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"), + AST_CLI_DEFINE(group_show_variables, "Display active channels with group(s), along with group variables"), AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"), }; From 880b8bb1acb7e6d48494473bd419c9f511ddeecd Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Wed, 2 Sep 2026 14:52:51 -0400 Subject: [PATCH 2/7] app.c: Fix use-after-free in ast_app_group_set_var() When replacing an existing group variable, ast_var_delete() was called without first unlinking the node from the group's varshead list via AST_LIST_REMOVE(). The freed node remained reachable in the list, so a subsequent traversal (GroupVarGet, GROUP() read, or another GroupVarSet) would walk into freed memory, crashing in ast_var_name() with a poisoned 0xdeaddead pointer. --- main/app.c | 1 + 1 file changed, 1 insertion(+) diff --git a/main/app.c b/main/app.c index f3dd2ccad4..9de8655043 100644 --- a/main/app.c +++ b/main/app.c @@ -2491,6 +2491,7 @@ int ast_app_group_set_var(struct ast_channel *chan, const char *group, const cha AST_LIST_TRAVERSE(headp, variable, entries) { if (strcasecmp(ast_var_name(variable), name) == 0) { /* there is already such a variable, nuke it so we can replace it */ + AST_LIST_REMOVE(headp, variable, entries); ast_var_delete(variable); break; } From f32025c72a2b1ec44ac32aa1c6fec8c0b82bb19e Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Wed, 2 Sep 2026 16:07:58 -0400 Subject: [PATCH 3/7] tests/test_app.c: Add unit tests for group variables; fix two more bugs found Added app_group_var to tests/test_app.c, covering set/get, overwrite, per-name case-insensitivity, per-category isolation, and cleanup on group destruction for the Group Variables feature. Writing the test surfaced two more defects in main/app.c, fixed here: - ast_app_group_set_var() called ast_channel_name(chan) unconditionally in two error-logging paths, even though chan is documented as nullable. The AMI GroupVarSet action (manager_group_var_set in func_groupcount.c) always passes a NULL chan, so setting a variable on a group@category that doesn't exist yet crashed on a NULL dereference. Guarded both call sites the same way the existing manager_event() call in the same function already does. - ast_app_group_get_var() allocated len+1 bytes for the returned value but called ast_copy_string(return_value, variable, len) instead of len + 1. Since ast_copy_string()'s size parameter is the destination buffer size, passing the source string's length exactly triggers its null-termination guard, which backs up one character and overwrites it with '\0' -- silently truncating the last character of every group variable value returned by GroupVarGet / GROUP_VAR(). Verified by building with TEST_FRAMEWORK enabled and running all three /main/app/ tests against a live instance: 3 Test(s) Executed, 3 Passed, 0 Failed. --- main/app.c | 6 +- tests/test_app.c | 161 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 164 insertions(+), 3 deletions(-) diff --git a/main/app.c b/main/app.c index 9de8655043..3e74c8212a 100644 --- a/main/app.c +++ b/main/app.c @@ -2467,7 +2467,7 @@ int ast_app_group_set_var(struct ast_channel *chan, const char *group, const cha struct ast_var_t *variable = NULL; if (!group || !name) { - ast_log(LOG_WARNING, "<%s> GROUP variable assignment failed for %s@%s, group/name cannot be NULL, group variable '%s' not set\n", ast_channel_name(chan), group, category, name); + ast_log(LOG_WARNING, "<%s> GROUP variable assignment failed for %s@%s, group/name cannot be NULL, group variable '%s' not set\n", chan ? ast_channel_name(chan) : "none", group, category, name); return -2; } @@ -2517,7 +2517,7 @@ int ast_app_group_set_var(struct ast_channel *chan, const char *group, const cha AST_RWLIST_UNLOCK(&groups_meta); if (!variable) { - ast_log(LOG_WARNING, "<%s> GROUP assignment %s@%s doesn't exist, group variable '%s' not set\n", ast_channel_name(chan), group, category, name); + ast_log(LOG_WARNING, "<%s> GROUP assignment %s@%s doesn't exist, group variable '%s' not set\n", chan ? ast_channel_name(chan) : "none", group, category, name); return -1; } @@ -2565,7 +2565,7 @@ char *ast_app_group_get_var(const char *group, const char *category, const char return NULL; } - ast_copy_string(return_value, variable, len); + ast_copy_string(return_value, variable, len + 1); AST_RWLIST_UNLOCK(&groups_meta); return return_value; diff --git a/tests/test_app.c b/tests/test_app.c index f3dd135b14..c8be348e95 100644 --- a/tests/test_app.c +++ b/tests/test_app.c @@ -221,8 +221,168 @@ exit_group_test: return res; } +AST_TEST_DEFINE(app_group_var) +{ + struct ast_channel *test_channel1 = NULL; + enum ast_test_result_state res = AST_TEST_PASS; + static const char group[] = "vartestgroup"; + static const char category[] = "vartestcategory"; + char *value = NULL; + struct ast_group_meta *gmi; + struct ast_var_t *var; + int count; + + switch (cmd) { + case TEST_INIT: + info->name = "app_group_var"; + info->category = "/main/app/"; + info->summary = "App group variable unit test"; + info->description = + "This tests setting, getting, overwriting, and cleaning up group\n" + "variables. It includes a regression test for a use-after-free that\n" + "occurred when overwriting an existing group variable (the old variable\n" + "was freed without being unlinked from the group's variable list), and\n" + "a regression test for a NULL channel crash when setting a variable on\n" + "a group@category that doesn't exist (the path exercised by the AMI\n" + "GroupVarSet action, which always passes a NULL channel)."; + return AST_TEST_NOT_RUN; + case TEST_EXECUTE: + break; + } + + if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, "TestChannel1"))) { + return AST_TEST_FAIL; + } + ast_channel_unlock(test_channel1); + + /* A group must already exist (have a member channel) before a variable can be + * set on it. This is also a regression test: with a NULL chan (as the AMI + * GroupVarSet action always passes), this used to crash inside the "doesn't + * exist" error log via an unconditional ast_channel_name(NULL). */ + if (ast_app_group_set_var(NULL, group, "", "foo", "bar") != -1) { + ast_test_status_update(test, "Expected failure setting a variable on a nonexistent group\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + + ast_app_group_set_channel(test_channel1, group); + + /* Basic set/get */ + if (ast_app_group_set_var(test_channel1, group, "", "myvar", "value1")) { + ast_test_status_update(test, "Failed to set group variable 'myvar'\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + if (!(value = ast_app_group_get_var(group, "", "myvar")) || strcmp(value, "value1")) { + ast_test_status_update(test, "Expected 'value1', got '%s'\n", value ? value : "(null)"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + ast_free(value); + value = NULL; + + /* Overwrite: regression test for a use-after-free when replacing an existing + * group variable. The old ast_var_t node used to be freed without first being + * unlinked from the group's variable list, leaving a dangling node for the + * next traversal (this get, or another set) to walk into. */ + if (ast_app_group_set_var(test_channel1, group, "", "myvar", "value2")) { + ast_test_status_update(test, "Failed to overwrite group variable 'myvar'\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + if (ast_app_group_set_var(test_channel1, group, "", "myvar", "value3")) { + ast_test_status_update(test, "Failed to overwrite group variable 'myvar' a second time\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + if (!(value = ast_app_group_get_var(group, "", "myvar")) || strcmp(value, "value3")) { + ast_test_status_update(test, "Expected 'value3' after overwriting twice, got '%s'\n", value ? value : "(null)"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + ast_free(value); + value = NULL; + + /* Confirm the overwrites left exactly one 'myvar' entry in the list (no + * dangling freed node left behind by an unlinked-then-freed variable) */ + ast_app_group_meta_rdlock(); + count = 0; + for (gmi = ast_app_group_meta_head(); gmi; gmi = AST_LIST_NEXT(gmi, group_meta_list)) { + if (strcasecmp(gmi->group, group) || strcasecmp(gmi->category, "")) { + continue; + } + AST_LIST_TRAVERSE(&gmi->varshead, var, entries) { + if (!strcasecmp(ast_var_name(var), "myvar")) { + count++; + } + } + } + ast_app_group_meta_unlock(); + if (count != 1) { + ast_test_status_update(test, "Expected exactly 1 'myvar' entry after overwriting, found %d " + "(indicates a stale/dangling list node)\n", count); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + + /* Independent variables coexist, and lookups are case-insensitive by name */ + if (ast_app_group_set_var(test_channel1, group, "", "othervar", "otherval")) { + ast_test_status_update(test, "Failed to set group variable 'othervar'\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + if (!(value = ast_app_group_get_var(group, "", "MYVAR")) || strcmp(value, "value3")) { + ast_test_status_update(test, "Case-insensitive lookup of 'MYVAR' failed, got '%s'\n", value ? value : "(null)"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + ast_free(value); + value = NULL; + if (!(value = ast_app_group_get_var(group, "", "othervar")) || strcmp(value, "otherval")) { + ast_test_status_update(test, "Setting 'othervar' should not disturb 'myvar', got '%s' for 'othervar'\n", value ? value : "(null)"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + ast_free(value); + value = NULL; + + /* Variables are isolated per category */ + if (ast_app_group_get_var(group, category, "myvar") != NULL) { + ast_test_status_update(test, "Variable 'myvar' set on the default category should not be visible under a different category\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + + /* Nonexistent variable/group lookups return NULL */ + if (ast_app_group_get_var(group, "", "novar") != NULL) { + ast_test_status_update(test, "Expected NULL for a variable that was never set\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + if (ast_app_group_get_var("nosuchgroup", "", "myvar") != NULL) { + ast_test_status_update(test, "Expected NULL for a variable on a group that doesn't exist\n"); + res = AST_TEST_FAIL; + goto exit_group_var_test; + } + +exit_group_var_test: + ast_free(value); + ast_hangup(test_channel1); + + /* Once the last channel leaves the group, the group (and its variables) + * should be destroyed */ + if (res == AST_TEST_PASS && ast_app_group_get_var(group, "", "myvar") != NULL) { + ast_test_status_update(test, "Group variable 'myvar' should have been freed when the group was destroyed\n"); + res = AST_TEST_FAIL; + } + + return res; +} + static int unload_module(void) { + AST_TEST_UNREGISTER(app_group_var); AST_TEST_UNREGISTER(app_group); AST_TEST_UNREGISTER(options_parsing); return 0; @@ -230,6 +390,7 @@ static int unload_module(void) static int load_module(void) { + AST_TEST_REGISTER(app_group_var); AST_TEST_REGISTER(app_group); AST_TEST_REGISTER(options_parsing); return AST_MODULE_LOAD_SUCCESS; From 33a257b503632941d4daa0a08806c1e1d42b33de Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Mon, 5 Oct 2026 22:22:55 -0400 Subject: [PATCH 4/7] Address review: drop unused numgroups, move chanvars.h docs out Remove the numgroups variable from dumpgroups_exec to avoid an unused-but-set-variable compiler warning. Revert the documentation changes to chanvars.h; they are moving to a separate PR. --- funcs/func_groupcount.c | 2 - include/asterisk/chanvars.h | 116 ------------------------------------ 2 files changed, 118 deletions(-) diff --git a/funcs/func_groupcount.c b/funcs/func_groupcount.c index 74012ee1ee..db826008ee 100644 --- a/funcs/func_groupcount.c +++ b/funcs/func_groupcount.c @@ -1353,7 +1353,6 @@ static int dumpgroups_exec(struct ast_channel *chan, const char *data) struct ast_group_meta *gmi = NULL; struct varshead *headp; struct ast_var_t *variable = NULL; - int numgroups = 0; int numchans = 0; struct ast_str *out = ast_str_create(4096); @@ -1387,7 +1386,6 @@ static int dumpgroups_exec(struct ast_channel *chan, const char *data) gmi = ast_app_group_meta_head(); while (gmi) { ast_str_append(&out, 0, FORMAT_STRING_GROUPS, gmi->group, (strcmp(gmi->category, "") ? gmi->category : "(Default)")); - numgroups++; headp = &gmi->varshead; AST_LIST_TRAVERSE(headp, variable, entries) { diff --git a/include/asterisk/chanvars.h b/include/asterisk/chanvars.h index c867baef9e..1a303c5f73 100644 --- a/include/asterisk/chanvars.h +++ b/include/asterisk/chanvars.h @@ -33,143 +33,27 @@ struct ast_var_t { AST_LIST_HEAD_NOLOCK(varshead, ast_var_t); - -/*! - * \brief Create a new variables list and initalize to empty - * - * \retval NULL on error - * \retval returns the pointer to the newly created list on success - */ struct varshead *ast_var_list_create(void); - -/*! - * \brief Remove all variables from the list, free them and also free the list - * - * \param head pointer to the list - * - */ void ast_var_list_destroy(struct varshead *head); struct ast_var_t *_ast_var_assign(const char *name, const char *value, const char *file, int lineno, const char *function); - -/*! - * \brief Insert a new variable into the variables list and store the value - * - * \param name name of the variable to set - * \param value value of the variable to set - * - * \retval NULL on error - * \retval returns a populated struct ast_var_t - */ #define ast_var_assign(name, value) _ast_var_assign(name, value, __FILE__, __LINE__, __PRETTY_FUNCTION__) -/*! - * \brief Free a variable. This does not remove the variable from the list that it might be a part of - * \see linkedlists.h - * - * \see ast_var_find - * \see ast_var_assign - * - * \param var must be a struct ast_var_t* that's been set up with ast_var_assign - * - */ void ast_var_delete(struct ast_var_t *var); - -/*! - * \brief Return the name component of an existing struct ast_var_t, stripping any _ or __ inheritance modifiers - * - * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) - * - * \retval NULL on error - * \retval variable name on success - */ const char *ast_var_name(const struct ast_var_t *var); - -/*! - * \brief Return the full name component of an existing struct ast_var_t, including any _ or __ inheritance modifiers - * - * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) - * - * \retval NULL on error - * \retval variable name on success - */ const char *ast_var_full_name(const struct ast_var_t *var); - -/*! - * \brief Return the value component of an existing struct ast_var_t - * - * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) - * - * \retval NULL on error - * \retval variable value on success - */ const char *ast_var_value(const struct ast_var_t *var); - -/*! - * \brief Find a variable by full name - * - * \note If the original variable was set with a _ or __ prefix, the name param for this search will have to match exactly - * - * \see ast_var_full_name - * - * \param varshead pointer to an existing and fully set up variables list - * \param name name of the variable to find - * - * \retval variable value on success - * \retval NULL on not found - */ char *ast_var_find(const struct varshead *head, const char *name); - -/*! - * \brief Create a brand new variables list with the same variables as the source list - * - * \param head an existing varshead - * - * \retval NULL on error - * \retval pointer to new list on success - */ struct varshead *ast_var_list_clone(struct varshead *head); -/*! - * \brief Traverse the variable list in the same style as AST_LIST_TRAVERSE - * - * * \param head This is a pointer to the list head structure - * \param var This is the name of the variable that will hold a pointer to the - * current list entry on each iteration. It must be declared before calling - * this macro. - * \param field This is the name of the field (declared using AST_LIST_ENTRY()) - * used to link entries of this list together. - * - * - * \see AST_LIST_TRAVERSE - */ #define AST_VAR_LIST_TRAVERSE(head, var) AST_LIST_TRAVERSE(head, var, entries) -/*! - * \brief Insert into the end of the variables list in the same style as AST_LIST_INSERT_TAIL - * - * \see AST_LIST_INSERT_TAIL - * - * \param head list to insert into - * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) - * - */ static inline void AST_VAR_LIST_INSERT_TAIL(struct varshead *head, struct ast_var_t *var) { if (var) { AST_LIST_INSERT_TAIL(head, var, entries); } } - -/*! - * \brief Insert into the beginning of the variables list in the same style as AST_LIST_INSERT_HEAD - * - * \see AST_LIST_INSERT_HEAD - * - * \param head list to insert into - * \param var must be a struct ast_var_t * (Allowed to be empty/uninitalized) - * - */ static inline void AST_VAR_LIST_INSERT_HEAD(struct varshead *head, struct ast_var_t *var) { if (var) { AST_LIST_INSERT_HEAD(head, var, entries); From 21291ff0c25351478646be0dc24831740911b0d3 Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Wed, 7 Oct 2026 10:30:06 -0400 Subject: [PATCH 5/7] tests/test_app.c: Drop redundant value = NULL before reassignment Per review: 'value' is assigned again by the very next statement, so clearing it after ast_free() is unnecessary. --- tests/test_app.c | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_app.c b/tests/test_app.c index c8be348e95..fead2e1c62 100644 --- a/tests/test_app.c +++ b/tests/test_app.c @@ -338,7 +338,6 @@ AST_TEST_DEFINE(app_group_var) goto exit_group_var_test; } ast_free(value); - value = NULL; if (!(value = ast_app_group_get_var(group, "", "othervar")) || strcmp(value, "otherval")) { ast_test_status_update(test, "Setting 'othervar' should not disturb 'myvar', got '%s' for 'othervar'\n", value ? value : "(null)"); res = AST_TEST_FAIL; From 4eb7dcda6da7f9e134dfc87b1762f25e13031b61 Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Wed, 7 Oct 2026 10:35:56 -0400 Subject: [PATCH 6/7] func_groupcount.c: Fix GROUP_MATCH_LIST output formatting Don't emit a trailing '@' for groups that have no category, matching the documentation and the GROUP_LIST() output. Separate results with a comma starting at the second match. The separator was only added from the third match onward, so the first two results ran together (e.g. "g@c1g@c2"). --- funcs/func_groupcount.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/funcs/func_groupcount.c b/funcs/func_groupcount.c index db826008ee..2f874bc92a 100644 --- a/funcs/func_groupcount.c +++ b/funcs/func_groupcount.c @@ -1321,11 +1321,15 @@ static int group_match_list_function_read(struct ast_channel *chan, const char * ast_app_group_meta_rdlock(); for (gmi = ast_app_group_meta_head(); gmi; gmi = AST_LIST_NEXT(gmi, group_meta_list)) { if (!regexec(®exbuf_group, gmi->group, 0, NULL, 0) && (ast_strlen_zero(categorymatch) || (!ast_strlen_zero(gmi->category) && !regexec(®exbuf_category, gmi->category, 0, NULL, 0)))) { - if (groups_found > 1) { + if (groups_found > 0) { ast_str_append(&foundgroup_str, 0, ","); } - ast_str_append(&foundgroup_str, 0, "%s@%s", gmi->group, gmi->category); + if (ast_strlen_zero(gmi->category)) { + ast_str_append(&foundgroup_str, 0, "%s", gmi->group); + } else { + ast_str_append(&foundgroup_str, 0, "%s@%s", gmi->group, gmi->category); + } groups_found++; } From 8f51462cdb4cd4df3832eafa8228c652afc9a592 Mon Sep 17 00:00:00 2001 From: Mark Murawski Date: Wed, 25 Nov 2026 21:36:41 -0500 Subject: [PATCH 7/7] Address review: fix group update, implement regex channel list, docs main/app.c: - ast_app_group_update(): Restore the original behavior funcs/func_groupcount.c: - GROUP_MATCH_CHANNEL_LIST - actually match by regular expression - New matching GROUP_MATCH_CHANNEL_LIST_ERROR error for GROUP_MATCH_CHANNEL_LIST - Only set GROUP_CHANNEL_LIST_ERROR / GROUP_MATCH_CHANNEL_LIST_ERROR when there is a channel (don't set global) - Check ast_app_group_split_group() returns - GROUP_MATCH_LIST leak fix - unload_module unregister GroupSet and GroupRemove. - Fix the doc examples - Tabs tests: - Add app_group_update and group_channel_lists unit tests. --- funcs/func_groupcount.c | 519 ++++++++++++++++++++++++++++++---------- main/app.c | 28 ++- tests/test_app.c | 142 +++++++++++ 3 files changed, 546 insertions(+), 143 deletions(-) diff --git a/funcs/func_groupcount.c b/funcs/func_groupcount.c index 2f874bc92a..d05d186ab1 100644 --- a/funcs/func_groupcount.c +++ b/funcs/func_groupcount.c @@ -37,6 +37,7 @@ #include "asterisk/manager.h" #include "asterisk/strings.h" #include "asterisk/cli.h" +#include "asterisk/test.h" /*** DOCUMENTATION @@ -82,10 +83,10 @@ Set(GROUP()=somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(groups_found=${GROUP_LIST(.*foo.*)}) + Set(groups_found=${GROUP_MATCH_LIST(.*foo.*)}) Given the above: This will find the groups 'foobarbaz' and 'foobarbill' since they both match .*foo.* regex against the group name - Variable groups_found will be set to: foobarbaz,foobarbill + Variable groups_found will be set to: foobarbaz,foobarbill On Channel 1: @@ -98,11 +99,11 @@ Set(GROUP()=anything@somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(groups_found=${GROUP_LIST(@.*bar.*)}) + Set(groups_found=${GROUP_MATCH_LIST(@.*bar.*)}) Given the above: This will find the groups 'foo@barbaz' and 'foo@barbill' since they both match .*bar.* regex against the category name - Variable groups_found will be set to: foo@barbaz,foo@barbill + Variable groups_found will be set to: foo@barbaz,foo@barbill On Channel 1: @@ -115,11 +116,11 @@ Set(GROUP()=anything@somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(groups_found=${GROUP_LIST(.*foo.*@.*bar.*)}) + Set(groups_found=${GROUP_MATCH_LIST(.*foo.*@.*bar.*)}) Given the above: - This will find the groups 'foo@barbaz' and 'foo@barbill' since they both match .*foo*. against the group name and .*bar.* regex against the category name - Variable groups_found will be set to: foo@barbaz,foo@barbill + This will find the groups 'foo@barbaz' and 'foo@barbill' since they both match .*foo.* regex against the group name and .*bar.* regex against the category name + Variable groups_found will be set to: foo@barbaz,foo@barbill @@ -138,9 +139,10 @@ Search for groups matching group@category and return the channels that are members of those groups, the group/category must match exactly If only the group is specified, then return group@category results that only match against the group name - If only the category is specified, then return group@category results that only match the against the category name + If only the category is specified, then return group@category results that only match against the category name If the search parameters are entirely empty, all channels having any kind of group membership will be returned. - After GROUP_CHANNEL_LIST is complete. Channel variables may be set with information related to the function call. + A channel is only listed once, even if it is a member of more than one matching group. + After GROUP_CHANNEL_LIST is complete. Channel variables may be set with information related to the function call. No variables are set when the function is used without a channel. @@ -148,9 +150,7 @@ - - Find channels that are members of the group 'foobarbaz': - + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName) On Channel PJSIP/1234-0000003: @@ -161,48 +161,46 @@ Set(GROUP()=somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(channels_found=${GROUP_CHANNEL_LIST(foobarbaz)} + Set(channels_found=${GROUP_CHANNEL_LIST(foobarbaz)}) + Given the above: This will find the channels that are in the group 'foobarbaz' - Variable channels_found will be set to: PJSIP/1234-0000003 + Variable channels_found will be set to: PJSIP/1234-0000003 - - Find channels that have the category name of 'barbaz' - + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName@categoryName) On Channel PJSIP/1234-0000002: Set(GROUP()=foo@barbaz) - On Channel PJSIP/1234-0000003: + On Channel PJSIP/1234-0000003: Set(GROUP()=oof@barbaz) - On Channel PJSIP/1234-0000004: + On Channel PJSIP/1234-0000004: Set(GROUP()=anything@somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents Set(channels_found=${GROUP_CHANNEL_LIST(@barbaz)}) Given the above: - This will find the channels that are in group 'foo@foobarbaz' and 'oof@barbaz' since they both have the category barbaz - Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + This will find the channels that are in the groups 'foo@barbaz' and 'oof@barbaz' since they both have the category 'barbaz' + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 - - Find groups containing 'foo' and category name of 'bar' - - On Channel PJSIP/1234-0000001: + + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName@categoryName) - On Channel PJSIP/1234-0000002: + On Channel PJSIP/1234-0000002: Set(GROUP()=foo@bar) - On Channel PJSIP/1234-0000003: + On Channel PJSIP/1234-0000003: Set(GROUP()=foo@bar) - On Channel PJSIP/1234-0000004: - Set(GROUP()=anything@somethingelse) + On Channel PJSIP/1234-0000004: + Set(GROUP()=foo@barbill) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*@.*bar.*)}) + Set(channels_found=${GROUP_CHANNEL_LIST(foo@bar)}) Given the above: This will find the channels that are in the group@category assignment of foo@bar - Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + The category must match exactly, so the channel in 'foo@barbill' is not included + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 @@ -224,9 +222,16 @@ If only the category_regex is specified, then return group@category results that only match the category name against the category_regex. If the search regex parameters are entirely empty, all channels having any kind of group membership will be returned. Uses standard regular expression matching (see regex(7)). - - Find channels containing the string 'foo' - + A channel is only listed once, even if it is a member of more than one matching group. + After GROUP_MATCH_CHANNEL_LIST is complete. Channel variables may be set with information related to the function call. No variables are set when the function is used without a channel. + + + + The full result is not complete and was truncated + + + + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName) On Channel PJSIP/1234-0000003: @@ -238,47 +243,44 @@ On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*)}) + Given the above: - This will find the channels that are in groups 'foobarbaz' and 'foobarbill' since they both match .*foo.* regex against the group name - Variable channels_found will be set to: PJSIP/1234-0000003,PJSIP/1234-0000004 + This will find the channels that are in the groups 'foobarbaz' and 'foobarbill' since they both match .*foo.* regex against the group name + Variable channels_found will be set to: PJSIP/1234-0000003,PJSIP/1234-0000004 - - Find channels in groups containing category name of 'bar' - + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName@categoryName) On Channel PJSIP/1234-0000002: Set(GROUP()=foo@barbaz) - On Channel PJSIP/1234-0000003: + On Channel PJSIP/1234-0000003: Set(GROUP()=foo@barbill) - On Channel PJSIP/1234-0000004: + On Channel PJSIP/1234-0000004: Set(GROUP()=anything@somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(@.*bar.*)}) Given the above: - This will find the channels that are in groups 'foo@barbaz' and 'foo@barbill' since they both match .*bar.* regex against the category name - Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + This will find the channels that are in the groups 'foo@barbaz' and 'foo@barbill' since they both match .*bar.* regex against the category name + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 - - Find channels in groups where they contain 'foo' and have the matching category contain the name of 'bar' - - On Channel PJSIP/1234-0000001: + + On Channel PJSIP/1234-0000001: Set(GROUP()=groupName@categoryName) - On Channel PJSIP/1234-0000002: + On Channel PJSIP/1234-0000002: Set(GROUP()=foo@bar) - On Channel PJSIP/1234-0000003: + On Channel PJSIP/1234-0000003: Set(GROUP()=foo@barbill) - On Channel PJSIP/1234-0000004: + On Channel PJSIP/1234-0000004: Set(GROUP()=anything@somethingelse) On any Channel: Assuming that channels still exist that have the above associated GROUP() assignents - Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*@.*bar.*)} + Set(channels_found=${GROUP_MATCH_CHANNEL_LIST(.*foo.*@.*bar.*)}) Given the above: - This will find the channels that are in groups 'foo@barbaz' and 'foo@barbill' since they both match .*foo*. against the group name and .*bar.* regex against the category name - Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 + This will find the channels that are in the groups 'foo@bar' and 'foo@barbill' since they both match .*foo.* regex against the group name and .*bar.* regex against the category name + Variable channels_found will be set to: PJSIP/1234-0000002,PJSIP/1234-0000003 @@ -754,12 +756,16 @@ static int group_var_function_write(struct ast_channel *chan, const char *cmd, return -1; } - ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category)); + if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { + ast_log(LOG_WARNING, "GROUP_VAR() Unable to parse group@category '%s'\n", args.groupcategory); + return -1; + } + result = ast_app_group_set_var(chan, group, category, args.varname, value); if (result != 0) { /* We know we're not passing any NULL values, so our error has to be 'non-exist' */ - ast_log(LOG_WARNING, "GROUP_VAR() Variable set failed (group doesn't exist)"); + ast_log(LOG_WARNING, "GROUP_VAR() Variable set failed (group doesn't exist)\n"); return -1; } @@ -1303,17 +1309,22 @@ static int group_match_list_function_read(struct ast_channel *chan, const char * return -1; } - ast_app_group_split_group(data, groupmatch, sizeof(groupmatch), categorymatch, sizeof(categorymatch)); + if (ast_app_group_split_group(data, groupmatch, sizeof(groupmatch), categorymatch, sizeof(categorymatch))) { + ast_log(LOG_WARNING, "GROUP_MATCH_LIST() Unable to parse group@category '%s'\n", S_OR(data, "")); + ast_free(foundgroup_str); + return -1; + } - /* if regex compilation fails, return zero matches */ if (regcomp(®exbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) { ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch); + ast_free(foundgroup_str); return -1; } if (regcomp(®exbuf_category, categorymatch, REG_EXTENDED | REG_NOSUB)) { ast_log(LOG_ERROR, "Regex compile failed on: %s\n", categorymatch); regfree(®exbuf_group); + ast_free(foundgroup_str); return -1; } @@ -1338,6 +1349,7 @@ static int group_match_list_function_read(struct ast_channel *chan, const char * snprintf(buf, len, "%s", ast_str_buffer(foundgroup_str)); + ast_free(foundgroup_str); regfree(®exbuf_group); regfree(®exbuf_category); @@ -1425,65 +1437,137 @@ static struct ast_custom_function group_list_function = { .write = NULL, }; -static int group_channel_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +/*! + * \internal + * \brief Check whether a channel name is already present in a comma separated list + */ +static int channel_list_contains(const char *list, size_t list_len, const char *name, size_t name_len) { - char group[MAX_GROUP_LEN] = ""; - char category[MAX_CATEGORY_LEN] = ""; - struct ast_group_info *gi = NULL; - int out_len = 0; - int remaining_buf = len; - char *buf_pos = buf; + const char *pos = list; + const char *end = list + list_len; - AST_DECLARE_APP_ARGS(args, - AST_APP_ARG(groupcategory); - ); - AST_STANDARD_APP_ARGS(args, data); + while (pos < end) { + const char *comma = memchr(pos, ',', end - pos); + size_t token_len = comma ? (size_t) (comma - pos) : (size_t) (end - pos); - pbx_builtin_setvar_helper(chan, "GROUP_CHANNEL_LIST_ERROR", NULL); + if (token_len == name_len && !strncmp(pos, name, name_len)) { + return 1; + } + if (!comma) { + break; + } + pos = comma + 1; + } - buf[0] = '\0'; + return 0; +} - if (ast_strlen_zero(args.groupcategory)) { - ast_log(LOG_WARNING, "Syntax GROUP_CHANNEL_LIST(group[@category])\n"); - return -1; - } +/*! + * \internal + * \brief Build a comma separated list of the channels that are members of matching groups + * + * An empty group or category matches anything. When group_regex is NULL the group + * and category are compared exactly (case insensitive), otherwise group_regex and + * category_regex (which must both be valid) are used. + * + * A channel is only listed once, even if it is a member of several matching groups. + * The list never contains a partial channel name. + * + * \retval 0 The complete list was written to buf + * \retval 1 The list did not fit in buf and was truncated + */ +static int group_channel_list_build(char *buf, size_t len, const char *group, const char *category, + const regex_t *group_regex, const regex_t *category_regex) +{ + struct ast_group_info *gi; + size_t out_len = 0; + int truncated = 0; - if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { - return -1; - } + buf[0] = '\0'; ast_app_group_list_rdlock(); - gi = ast_app_group_list_head(); - while (gi) { - if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { - int write_len; - - /* In the odd event we go over the buffer length, don't include a partial channel name */ - int channel_name_len = strlen(ast_channel_name(gi->chan)); + for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { + const char *name; + size_t name_len; + size_t needed; - if ((out_len + channel_name_len + 1) > len) { /* +1 for null */ - ast_log(LOG_WARNING, "GROUP_CHANNEL_LIST(%s) Channel membership list too large for buffer, truncating.\n", args.groupcategory); - pbx_builtin_setvar_helper(chan, "GROUP_CHANNEL_LIST_ERROR", "TRUNCATED"); - break; + if (group_regex) { + if (regexec(group_regex, gi->group, 0, NULL, 0)) { + continue; + } + if (!ast_strlen_zero(category) && (ast_strlen_zero(gi->category) || regexec(category_regex, gi->category, 0, NULL, 0))) { + continue; + } + } else { + if (!ast_strlen_zero(group) && strcasecmp(gi->group, group)) { + continue; + } + if (!ast_strlen_zero(category) && (ast_strlen_zero(gi->category) || strcasecmp(gi->category, category))) { + continue; } + } + + name = ast_channel_name(gi->chan); + name_len = strlen(name); - write_len = snprintf(buf_pos, remaining_buf, "%s,", ast_channel_name(gi->chan)); - /* Note we already prevent buffer overrun above, write_len will always be characters written */ - out_len += write_len; - buf_pos += write_len; - remaining_buf -= write_len; + if (channel_list_contains(buf, out_len, name, name_len)) { + continue; } - gi = AST_LIST_NEXT(gi, group_list); + /* Optional separator, the name and the terminating NULL */ + needed = (out_len ? 1 : 0) + name_len + 1; + if (out_len + needed > len) { + truncated = 1; + break; + } + + if (out_len) { + buf[out_len++] = ','; + } + memcpy(buf + out_len, name, name_len); + out_len += name_len; + buf[out_len] = '\0'; } ast_app_group_list_unlock(); - /* delete the last comma. We'll always have a final comma, because we already do overlength check above, so we'll never have a partial write */ - if (out_len) { - buf_pos--; - *buf_pos = '\0'; + return truncated; +} + +/*! + * \internal + * \brief Set, or clear, the variable that reports a truncated channel list + * + * Only a channel has variables to set. With no channel pbx_builtin_setvar_helper() + * would modify a global variable instead, so do nothing. + */ +static void channel_list_set_error(struct ast_channel *chan, const char *variable, int truncated) +{ + if (chan) { + pbx_builtin_setvar_helper(chan, variable, truncated ? "TRUNCATED" : NULL); + } +} + +static int group_channel_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + char group[MAX_GROUP_LEN] = ""; + char category[MAX_CATEGORY_LEN] = ""; + int truncated; + + buf[0] = '\0'; + + if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) { + ast_log(LOG_WARNING, "GROUP_CHANNEL_LIST() Unable to parse group@category '%s'\n", S_OR(data, "")); + return -1; + } + + truncated = group_channel_list_build(buf, len, group, category, NULL, NULL); + if (truncated) { + ast_log(LOG_WARNING, "GROUP_CHANNEL_LIST(%s) Channel membership list too large for buffer, truncating.\n", S_OR(data, "")); } + /* Done after the group list lock is released, setting a variable locks the channel */ + channel_list_set_error(chan, "GROUP_CHANNEL_LIST_ERROR", truncated); + return 0; } @@ -1494,55 +1578,39 @@ static struct ast_custom_function group_channel_list_function = { static int group_match_channel_list_function_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) { - char group[MAX_GROUP_LEN] = ""; - char category[MAX_CATEGORY_LEN] = ""; - struct ast_group_info *gi = NULL; - struct ast_str *out = ast_str_create(1024); - int out_len = 0; + char groupmatch[MAX_GROUP_LEN] = ""; + char categorymatch[MAX_CATEGORY_LEN] = ""; + regex_t regexbuf_group; + regex_t regexbuf_category; + int truncated; - AST_DECLARE_APP_ARGS(args, - AST_APP_ARG(groupcategory); - ); - AST_STANDARD_APP_ARGS(args, data); + buf[0] = '\0'; - if (!out) { - ast_log(LOG_ERROR, "Unable to allocate new variable. Cannot proceed with GROUP_MATCH_CHANNEL_LIST().\n"); + if (ast_app_group_split_group(data, groupmatch, sizeof(groupmatch), categorymatch, sizeof(categorymatch))) { + ast_log(LOG_WARNING, "GROUP_MATCH_CHANNEL_LIST() Unable to parse group@category '%s'\n", S_OR(data, "")); return -1; } - buf[0] = 0; - - if (ast_strlen_zero(args.groupcategory)) { - ast_log(LOG_WARNING, "Syntax GROUP_MATCH_CHANNEL_LIST(group[@category])\n"); + if (regcomp(®exbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) { + ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch); return -1; } - if (ast_app_group_split_group(args.groupcategory, group, sizeof(group), category, sizeof(category))) { + if (regcomp(®exbuf_category, categorymatch, REG_EXTENDED | REG_NOSUB)) { + ast_log(LOG_ERROR, "Regex compile failed on: %s\n", categorymatch); + regfree(®exbuf_group); return -1; } - ast_app_group_list_rdlock(); - gi = ast_app_group_list_head(); - while (gi) { - if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) { - ast_str_append(&out, 0, "%s,", ast_channel_name(gi->chan)); - } - - gi = AST_LIST_NEXT(gi, group_list); + truncated = group_channel_list_build(buf, len, groupmatch, categorymatch, ®exbuf_group, ®exbuf_category); + if (truncated) { + ast_log(LOG_WARNING, "GROUP_MATCH_CHANNEL_LIST(%s) Channel membership list too large for buffer, truncating.\n", S_OR(data, "")); } - ast_app_group_list_unlock(); - - out_len = strlen(ast_str_buffer(out)); - if (out_len) { - if (out_len <= len) { - len -= 1; /* rid , only if we didn't go over the buffer limit */ - } - - ast_copy_string(buf, ast_str_buffer(out), len); - } + regfree(®exbuf_group); + regfree(®exbuf_category); - ast_free(out); + channel_list_set_error(chan, "GROUP_MATCH_CHANNEL_LIST_ERROR", truncated); return 0; } @@ -1552,6 +1620,185 @@ static struct ast_custom_function group_match_channel_list_function = { .read = group_match_channel_list_function_read, }; +#ifdef TEST_FRAMEWORK + +/*! + * \internal + * \brief Run GROUP_CHANNEL_LIST or GROUP_MATCH_CHANNEL_LIST and compare the result + * + * \retval 1 The result matched the expected value + */ +static int check_channel_list(struct ast_test *test, int match, const char *data, const char *expected_fmt, ...) + __attribute__((format(printf, 4, 5))); + +static int check_channel_list(struct ast_test *test, int match, const char *data, const char *expected_fmt, ...) +{ + char expected[512]; + char buf[512]; + char *args = ast_strdupa(data); + va_list ap; + int res; + + va_start(ap, expected_fmt); + vsnprintf(expected, sizeof(expected), expected_fmt, ap); + va_end(ap); + + if (match) { + res = group_match_channel_list_function_read(NULL, "GROUP_MATCH_CHANNEL_LIST", args, buf, sizeof(buf)); + } else { + res = group_channel_list_function_read(NULL, "GROUP_CHANNEL_LIST", args, buf, sizeof(buf)); + } + + if (res || strcmp(buf, expected)) { + ast_test_status_update(test, "%s(%s): expected '%s', got '%s' (result %d)\n", + match ? "GROUP_MATCH_CHANNEL_LIST" : "GROUP_CHANNEL_LIST", data, expected, buf, res); + return 0; + } + + return 1; +} + +AST_TEST_DEFINE(test_group_channel_lists) +{ + struct ast_channel *chans[4] = { NULL, }; + const char *names[4] = { NULL, }; + enum ast_test_result_state res = AST_TEST_PASS; + char buf[512]; + char data[128]; + const char *var; + size_t i; + + switch (cmd) { + case TEST_INIT: + info->name = "group_channel_lists"; + info->category = "/funcs/func_groupcount/"; + info->summary = "GROUP_CHANNEL_LIST, GROUP_MATCH_CHANNEL_LIST and GROUP_MATCH_LIST"; + info->description = + "Tests exact and regular expression matching of the group channel list\n" + "functions, that channels are only listed once, that truncation never\n" + "returns a partial channel name, and that the error variables are only\n" + "touched when there is a channel to set them on."; + return AST_TEST_NOT_RUN; + case TEST_EXECUTE: + break; + } + + for (i = 0; i < ARRAY_LEN(chans); i++) { + chans[i] = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, "TestGroupChannel%d", (int) i); + if (!chans[i]) { + res = AST_TEST_FAIL; + goto cleanup; + } + ast_channel_unlock(chans[i]); + names[i] = ast_channel_name(chans[i]); + } + + /* chans[1] is in two groups, with different categories, so that matching + * more than one of them must not list it twice */ + ast_app_group_set_channel(chans[0], "gclgroupname@gclcategoryname"); + ast_app_group_set_channel(chans[1], "gclfoo@gclbar"); + ast_app_group_set_channel(chans[2], "gclfoo@gclbarbill"); + ast_app_group_set_channel(chans[3], "gclanything@gclsomethingelse"); + ast_app_group_set_channel(chans[1], "gclfoo2@gclbar2"); + + /* Exact matching */ + if (!check_channel_list(test, 0, "gclfoo@gclbar", "%s", names[1]) + || !check_channel_list(test, 0, "GCLFOO@GCLBAR", "%s", names[1]) + || !check_channel_list(test, 0, "gclfoo", "%s,%s", names[1], names[2]) + || !check_channel_list(test, 0, "@gclbar", "%s", names[1]) + || !check_channel_list(test, 0, "gclfoo@nosuchcategory", "%s", "") + || !check_channel_list(test, 0, "nosuchgroup", "%s", "") + || !check_channel_list(test, 0, "", "%s,%s,%s,%s", names[0], names[1], names[2], names[3])) { + res = AST_TEST_FAIL; + } + + /* Regular expression matching. A match on the group name or category + * alone is not exact, 'gclfoo' also matches 'gclfoo2' */ + if (!check_channel_list(test, 1, "gclfoo.*", "%s,%s", names[1], names[2]) + || !check_channel_list(test, 1, "@.*gclbar.*", "%s,%s", names[1], names[2]) + || !check_channel_list(test, 1, "gclfoo.*@.*gclbar.*", "%s,%s", names[1], names[2]) + || !check_channel_list(test, 1, "^gclfoo$@^gclbar$", "%s", names[1]) + || !check_channel_list(test, 1, "gclfoo.*@^gclbarbill$", "%s", names[2]) + || !check_channel_list(test, 1, "nomatchxyz", "%s", "") + || !check_channel_list(test, 1, "", "%s,%s,%s,%s", names[0], names[1], names[2], names[3])) { + res = AST_TEST_FAIL; + } + + /* An invalid regular expression is an error, not an empty result */ + snprintf(data, sizeof(data), "[["); + if (group_match_channel_list_function_read(NULL, "GROUP_MATCH_CHANNEL_LIST", data, buf, sizeof(buf)) != -1) { + ast_test_status_update(test, "GROUP_MATCH_CHANNEL_LIST with an invalid regex should fail\n"); + res = AST_TEST_FAIL; + } + + /* GROUP_MATCH_LIST lists group@category, in the order the groups were created */ + snprintf(data, sizeof(data), "gclfoo.*"); + if (group_match_list_function_read(NULL, "GROUP_MATCH_LIST", data, buf, sizeof(buf)) + || strcmp(buf, "gclfoo@gclbar,gclfoo@gclbarbill,gclfoo2@gclbar2")) { + ast_test_status_update(test, "GROUP_MATCH_LIST(%s): unexpected result '%s'\n", data, buf); + res = AST_TEST_FAIL; + } + + /* Truncation: room for the first channel name only. The partial name of + * the second channel must not be written, and the caller is told. */ + snprintf(data, sizeof(data), "gclfoo.*"); + if (group_match_channel_list_function_read(chans[0], "GROUP_MATCH_CHANNEL_LIST", data, buf, strlen(names[1]) + 1) + || strcmp(buf, names[1])) { + ast_test_status_update(test, "GROUP_MATCH_CHANNEL_LIST truncation: expected '%s', got '%s'\n", names[1], buf); + res = AST_TEST_FAIL; + } + var = pbx_builtin_getvar_helper(chans[0], "GROUP_MATCH_CHANNEL_LIST_ERROR"); + if (ast_strlen_zero(var) || strcmp(var, "TRUNCATED")) { + ast_test_status_update(test, "GROUP_MATCH_CHANNEL_LIST_ERROR should be TRUNCATED, got '%s'\n", S_OR(var, "")); + res = AST_TEST_FAIL; + } + + /* A complete result clears the error again */ + if (group_match_channel_list_function_read(chans[0], "GROUP_MATCH_CHANNEL_LIST", data, buf, sizeof(buf)) + || pbx_builtin_getvar_helper(chans[0], "GROUP_MATCH_CHANNEL_LIST_ERROR")) { + ast_test_status_update(test, "GROUP_MATCH_CHANNEL_LIST_ERROR should be cleared by a complete result\n"); + res = AST_TEST_FAIL; + } + + snprintf(data, sizeof(data), "gclfoo"); + if (group_channel_list_function_read(chans[0], "GROUP_CHANNEL_LIST", data, buf, strlen(names[1]) + 1) + || strcmp(buf, names[1])) { + ast_test_status_update(test, "GROUP_CHANNEL_LIST truncation: expected '%s', got '%s'\n", names[1], buf); + res = AST_TEST_FAIL; + } + var = pbx_builtin_getvar_helper(chans[0], "GROUP_CHANNEL_LIST_ERROR"); + if (ast_strlen_zero(var) || strcmp(var, "TRUNCATED")) { + ast_test_status_update(test, "GROUP_CHANNEL_LIST_ERROR should be TRUNCATED, got '%s'\n", S_OR(var, "")); + res = AST_TEST_FAIL; + } + + /* Without a channel there is nowhere to set the error variable. It must + * not be set as a global variable instead. */ + snprintf(data, sizeof(data), "gclfoo"); + group_channel_list_function_read(NULL, "GROUP_CHANNEL_LIST", data, buf, strlen(names[1]) + 1); + snprintf(data, sizeof(data), "gclfoo.*"); + group_match_channel_list_function_read(NULL, "GROUP_MATCH_CHANNEL_LIST", data, buf, strlen(names[1]) + 1); + if (pbx_builtin_getvar_helper(NULL, "GROUP_CHANNEL_LIST_ERROR") + || pbx_builtin_getvar_helper(NULL, "GROUP_MATCH_CHANNEL_LIST_ERROR")) { + ast_test_status_update(test, "An error variable was set as a global variable when there was no channel\n"); + pbx_builtin_setvar_helper(NULL, "GROUP_CHANNEL_LIST_ERROR", NULL); + pbx_builtin_setvar_helper(NULL, "GROUP_MATCH_CHANNEL_LIST_ERROR", NULL); + res = AST_TEST_FAIL; + } + +cleanup: + for (i = 0; i < ARRAY_LEN(chans); i++) { + if (chans[i]) { + ast_hangup(chans[i]); + } + } + + return res; +} + +#endif /* TEST_FRAMEWORK */ + static int unload_module(void) { int res = 0; @@ -1565,8 +1812,12 @@ static int unload_module(void) res |= ast_custom_function_unregister(&group_var_function); res |= ast_custom_function_unregister(&group_function); + AST_TEST_UNREGISTER(test_group_channel_lists); + res |= ast_unregister_application(dumpgroups_app); + res |= ast_manager_unregister("GroupSet"); + res |= ast_manager_unregister("GroupRemove"); res |= ast_manager_unregister("GroupVarGet"); res |= ast_manager_unregister("GroupVarSet"); res |= ast_manager_unregister("GroupsShow"); @@ -1589,6 +1840,8 @@ static int load_module(void) res |= ast_custom_function_register(&group_var_function); res |= ast_custom_function_register(&group_function); + AST_TEST_REGISTER(test_group_channel_lists); + res |= ast_register_application_xml(dumpgroups_app, dumpgroups_exec); res |= ast_manager_register_xml("GroupSet", EVENT_FLAG_CALL, manager_group_set); diff --git a/main/app.c b/main/app.c index 3e74c8212a..f06ba7ab81 100644 --- a/main/app.c +++ b/main/app.c @@ -2641,21 +2641,29 @@ int ast_app_group_match_get_count(const char *groupmatch, const char *category) int ast_app_group_update(struct ast_channel *old, struct ast_channel *new) { struct ast_group_info *gi = NULL; - struct ast_group_info *gi_new = NULL; AST_RWLIST_WRLOCK(&groups); AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) { - /* keep channel groups on transfer */ if (gi->chan == old) { - /* only move group if it doesn't already exist on new */ - AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi_new, group_list) { - if (gi_new->chan == old && !strcasecmp(gi_new->group, gi->group) && !strcasecmp(gi_new->category, gi->category)) { - break; - } - } - AST_RWLIST_TRAVERSE_SAFE_END; - + /* keep channel groups on transfer */ gi->chan = new; + } else if (gi->chan == new) { + /* The group assignments of old replace those of new, so drop + * any that new already had. Group membership counts are tracked + * per group@category, so release this channel's reference too. */ + manager_event(EVENT_FLAG_DIALPLAN, "GroupChannelRemove", + "Channel: %s\r\n" + "Category: %s\r\n" + "Group: %s\r\n" + "Uniqueid: %s\r\n", + ast_channel_name(gi->chan), + S_OR(gi->category, ""), gi->group, + ast_channel_uniqueid(gi->chan)); + + ast_app_group_remove_meta_ifneeded(gi->group, gi->category); + + AST_RWLIST_REMOVE_CURRENT(group_list); + ast_free(gi); } } AST_RWLIST_TRAVERSE_SAFE_END; diff --git a/tests/test_app.c b/tests/test_app.c index fead2e1c62..63a138fa22 100644 --- a/tests/test_app.c +++ b/tests/test_app.c @@ -379,8 +379,149 @@ exit_group_var_test: return res; } +/*! \brief Check a group variable has the expected value, NULL meaning it must not exist */ +static int group_var_matches(struct ast_test *test, const char *group, const char *category, + const char *name, const char *expected) +{ + char *value = ast_app_group_get_var(group, category, name); + int ok = (!value && !expected) || (value && expected && !strcmp(value, expected)); + + if (!ok) { + ast_test_status_update(test, "Group variable '%s' on %s@%s: expected '%s', got '%s'\n", + name, group, category, expected ? expected : "(none)", value ? value : "(none)"); + } + ast_free(value); + + return ok; +} + +AST_TEST_DEFINE(app_group_update) +{ + struct ast_channel *old_chan = NULL; + struct ast_channel *new_chan = NULL; + struct ast_group_info *gi; + enum ast_test_result_state res = AST_TEST_PASS; + int old_count = 0; + int new_count = 0; + + switch (cmd) { + case TEST_INIT: + info->name = "app_group_update"; + info->category = "/main/app/"; + info->summary = "App group update (masquerade) unit test"; + info->description = + "This tests that ast_app_group_update() moves the group assignments of the\n" + "old channel to the new channel, replaces any group assignments the new\n" + "channel already had, and keeps group membership counts and group\n" + "variables consistent while doing so."; + return AST_TEST_NOT_RUN; + case TEST_EXECUTE: + break; + } + + if (!(old_chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, "TestChannelOld"))) { + return AST_TEST_FAIL; + } + ast_channel_unlock(old_chan); + if (!(new_chan = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, 0, "TestChannelNew"))) { + ast_hangup(old_chan); + return AST_TEST_FAIL; + } + ast_channel_unlock(new_chan); + + /* A channel is in at most one group per category. Both channels are in + * 'updshared' (default category), old is also in updonlyold@cat and new is + * also in updonlynew@cat2. */ + ast_app_group_set_channel(old_chan, "updshared"); + ast_app_group_set_channel(old_chan, "updonlyold@cat"); + ast_app_group_set_channel(new_chan, "updshared"); + ast_app_group_set_channel(new_chan, "updonlynew@cat2"); + + if (ast_app_group_set_var(old_chan, "updshared", "", "v", "shared") + || ast_app_group_set_var(old_chan, "updonlyold", "cat", "v", "old") + || ast_app_group_set_var(new_chan, "updonlynew", "cat2", "v", "new")) { + ast_test_status_update(test, "Failed to set group variables\n"); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + + if (ast_app_group_get_count("updshared", "") != 2) { + ast_test_status_update(test, "Expected 2 channels in 'updshared' before the update, found %d\n", + ast_app_group_get_count("updshared", "")); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + + ast_app_group_update(old_chan, new_chan); + + /* A channel that was in both must not be counted twice, and the assignment + * that only the new channel had is gone */ + if (ast_app_group_get_count("updshared", "") != 1) { + ast_test_status_update(test, "Expected 1 channel in 'updshared' after the update, found %d\n", + ast_app_group_get_count("updshared", "")); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + if (ast_app_group_get_count("updonlyold", "cat") != 1) { + ast_test_status_update(test, "Expected 1 channel in 'updonlyold@cat' after the update, found %d\n", + ast_app_group_get_count("updonlyold", "cat")); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + if (ast_app_group_get_count("updonlynew", "cat2") != 0) { + ast_test_status_update(test, "Expected 0 channels in 'updonlynew@cat2' after the update, found %d\n", + ast_app_group_get_count("updonlynew", "cat2")); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + + /* Everything the old channel was in now belongs to the new channel */ + ast_app_group_list_rdlock(); + for (gi = ast_app_group_list_head(); gi; gi = AST_LIST_NEXT(gi, group_list)) { + if (gi->chan == old_chan) { + old_count++; + } else if (gi->chan == new_chan) { + new_count++; + } + } + ast_app_group_list_unlock(); + if (old_count != 0 || new_count != 2) { + ast_test_status_update(test, "Expected 0 assignments on the old channel and 2 on the new one, found %d and %d\n", + old_count, new_count); + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + + /* Groups that still have a member keep their variables, a group that lost + * its last member (updonlynew) loses them */ + if (!group_var_matches(test, "updshared", "", "v", "shared") + || !group_var_matches(test, "updonlyold", "cat", "v", "old") + || !group_var_matches(test, "updonlynew", "cat2", "v", NULL)) { + res = AST_TEST_FAIL; + goto exit_group_update_test; + } + +exit_group_update_test: + ast_hangup(old_chan); + ast_hangup(new_chan); + + /* The remaining assignments went with the new channel, nothing may be left */ + if (res == AST_TEST_PASS + && (ast_app_group_get_count("updshared", "") || ast_app_group_get_count("updonlyold", "cat") + || !group_var_matches(test, "updshared", "", "v", NULL) + || !group_var_matches(test, "updonlyold", "cat", "v", NULL))) { + ast_test_status_update(test, "Group assignments or variables were left behind after hanging up\n"); + res = AST_TEST_FAIL; + } + + return res; +} + static int unload_module(void) { + AST_TEST_UNREGISTER(app_group_update); AST_TEST_UNREGISTER(app_group_var); AST_TEST_UNREGISTER(app_group); AST_TEST_UNREGISTER(options_parsing); @@ -389,6 +530,7 @@ static int unload_module(void) static int load_module(void) { + AST_TEST_REGISTER(app_group_update); AST_TEST_REGISTER(app_group_var); AST_TEST_REGISTER(app_group); AST_TEST_REGISTER(options_parsing);