Asterisk - The Open Source Telephony Project  18.5.0
func_cut.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2003-2006 Tilghman Lesher. All rights reserved.
5  *
6  * Tilghman Lesher <[email protected]>
7  *
8  * This code is released by the author with no restrictions on usage.
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  */
17 
18 /*! \file
19  *
20  * \brief CUT function
21  *
22  * \author Tilghman Lesher <[email protected]>
23  *
24  * \ingroup functions
25  */
26 
27 /*** MODULEINFO
28  <support_level>core</support_level>
29  ***/
30 
31 #include "asterisk.h"
32 
33 #include "asterisk/file.h"
34 #include "asterisk/channel.h"
35 #include "asterisk/pbx.h"
36 #include "asterisk/module.h"
37 #include "asterisk/app.h"
38 
39 /*** DOCUMENTATION
40  <function name="SORT" language="en_US">
41  <synopsis>
42  Sorts a list of key/vals into a list of keys, based upon the vals.
43  </synopsis>
44  <syntax>
45  <parameter name="keyval" required="true" argsep=":">
46  <argument name="key1" required="true" />
47  <argument name="val1" required="true" />
48  </parameter>
49  <parameter name="keyvaln" multiple="true" argsep=":">
50  <argument name="key2" required="true" />
51  <argument name="val2" required="true" />
52  </parameter>
53  </syntax>
54  <description>
55  <para>Takes a comma-separated list of keys and values, each separated by a colon, and returns a
56  comma-separated list of the keys, sorted by their values. Values will be evaluated as
57  floating-point numbers.</para>
58  </description>
59  </function>
60  <function name="CUT" language="en_US">
61  <synopsis>
62  Slices and dices strings, based upon a named delimiter.
63  </synopsis>
64  <syntax>
65  <parameter name="varname" required="true">
66  <para>Variable you want cut</para>
67  </parameter>
68  <parameter name="char-delim" required="true">
69  <para>Delimiter, defaults to <literal>-</literal></para>
70  </parameter>
71  <parameter name="range-spec" required="true">
72  <para>Number of the field you want (1-based offset), may also be specified as a range (with <literal>-</literal>)
73  or group of ranges and fields (with <literal>&amp;</literal>)</para>
74  </parameter>
75  </syntax>
76  <description>
77  <para>Cut out information from a string (<replaceable>varname</replaceable>), based upon a named delimiter.</para>
78  </description>
79  </function>
80  ***/
81 
82 struct sortable_keys {
83  char *key;
84  float value;
85 };
86 
87 static int sort_subroutine(const void *arg1, const void *arg2)
88 {
89  const struct sortable_keys *one=arg1, *two=arg2;
90  if (one->value < two->value)
91  return -1;
92  else if (one->value == two->value)
93  return 0;
94  else
95  return 1;
96 }
97 
98 #define ERROR_NOARG (-1)
99 #define ERROR_NOMEM (-2)
100 #define ERROR_USAGE (-3)
101 
102 static int sort_internal(struct ast_channel *chan, char *data, char *buffer, size_t buflen)
103 {
104  char *strings, *ptrkey, *ptrvalue;
105  int count=1, count2, element_count=0;
107 
108  *buffer = '\0';
109 
110  if (!data)
111  return ERROR_NOARG;
112 
113  strings = ast_strdupa(data);
114 
115  for (ptrkey = strings; *ptrkey; ptrkey++) {
116  if (*ptrkey == ',')
117  count++;
118  }
119 
120  sortable_keys = ast_alloca(count * sizeof(struct sortable_keys));
121 
122  memset(sortable_keys, 0, count * sizeof(struct sortable_keys));
123 
124  /* Parse each into a struct */
125  count2 = 0;
126  while ((ptrkey = strsep(&strings, ","))) {
127  ptrvalue = strchr(ptrkey, ':');
128  if (!ptrvalue) {
129  count--;
130  continue;
131  }
132  *ptrvalue++ = '\0';
133  sortable_keys[count2].key = ptrkey;
134  sscanf(ptrvalue, "%30f", &sortable_keys[count2].value);
135  count2++;
136  }
137 
138  /* Sort the structs */
139  qsort(sortable_keys, count, sizeof(struct sortable_keys), sort_subroutine);
140 
141  for (count2 = 0; count2 < count; count2++) {
142  int blen = strlen(buffer);
143  if (element_count++) {
144  strncat(buffer + blen, ",", buflen - blen - 1);
145  blen++;
146  }
147  strncat(buffer + blen, sortable_keys[count2].key, buflen - blen - 1);
148  }
149 
150  return 0;
151 }
152 
153 static int cut_internal(struct ast_channel *chan, char *data, struct ast_str **buf, ssize_t buflen)
154 {
155  char *parse, ds[2], *var_expr;
156  size_t delim_consumed;
157  struct ast_str *var_value;
159  AST_APP_ARG(varname);
160  AST_APP_ARG(delimiter);
161  AST_APP_ARG(field);
162  );
163 
164  parse = ast_strdupa(data);
165 
166  AST_STANDARD_APP_ARGS(args, parse);
167 
168  /* Check arguments */
169  if (args.argc < 3) {
170  return ERROR_NOARG;
171  }
172  var_expr = ast_alloca(strlen(args.varname) + 4);
173 
174  /* Get the value of the variable named in the 1st argument */
175  snprintf(var_expr, strlen(args.varname) + 4, "${%s}", args.varname);
176  var_value = ast_str_create(16);
177  ast_str_substitute_variables(&var_value, 0, chan, var_expr);
178 
179  /* Copy delimiter from 2nd argument to ds[] possibly decoding backslash escapes */
180  if (ast_get_encoded_char(args.delimiter, ds, &delim_consumed)) {
181  ast_copy_string(ds, "-", sizeof(ds));
182  }
183  ds[1] = '\0';
184 
185  if (ast_str_strlen(var_value)) {
186  int curfieldnum = 1;
187  char *curfieldptr = ast_str_buffer(var_value);
188  int out_field_count = 0;
189 
190  while (curfieldptr != NULL && args.field != NULL) {
191  char *next_range = strsep(&(args.field), "&");
192  int start_field, stop_field;
193  char trashchar;
194 
195  if (sscanf(next_range, "%30d-%30d", &start_field, &stop_field) == 2) {
196  /* range with both start and end */
197  } else if (sscanf(next_range, "-%30d", &stop_field) == 1) {
198  /* range with end only */
199  start_field = 1;
200  } else if ((sscanf(next_range, "%30d%1c", &start_field, &trashchar) == 2) && (trashchar == '-')) {
201  /* range with start only */
202  stop_field = INT_MAX;
203  } else if (sscanf(next_range, "%30d", &start_field) == 1) {
204  /* single number */
205  stop_field = start_field;
206  } else {
207  /* invalid field spec */
208  ast_free(var_value);
209  return ERROR_USAGE;
210  }
211 
212  /* Get to start, if not there already */
213  while (curfieldptr != NULL && curfieldnum < start_field) {
214  strsep(&curfieldptr, ds);
215  curfieldnum++;
216  }
217 
218  /* Most frequent problem is the expectation of reordering fields */
219  if (curfieldnum > start_field) {
220  ast_log(LOG_WARNING, "We're already past the field you wanted?\n");
221  }
222 
223  /* Output fields until we either run out of fields or stop_field is reached */
224  while (curfieldptr != NULL && curfieldnum <= stop_field) {
225  char *field_value = strsep(&curfieldptr, ds);
226  ast_str_append(buf, buflen, "%s%s", out_field_count++ ? ds : "", field_value);
227  curfieldnum++;
228  }
229  }
230  }
231  ast_free(var_value);
232  return 0;
233 }
234 
235 static int acf_sort_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
236 {
237  int ret = -1;
238 
239  switch (sort_internal(chan, data, buf, len)) {
240  case ERROR_NOARG:
241  ast_log(LOG_ERROR, "SORT() requires an argument\n");
242  break;
243  case ERROR_NOMEM:
244  ast_log(LOG_ERROR, "Out of memory\n");
245  break;
246  case 0:
247  ret = 0;
248  break;
249  default:
250  ast_log(LOG_ERROR, "Unknown internal error\n");
251  }
252 
253  return ret;
254 }
255 
256 static int acf_cut_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
257 {
258  int ret = -1;
259  struct ast_str *str = ast_str_create(16);
260 
261  switch (cut_internal(chan, data, &str, len)) {
262  case ERROR_NOARG:
263  ast_log(LOG_ERROR, "Syntax: CUT(<varname>,<char-delim>,<range-spec>) - missing argument!\n");
264  break;
265  case ERROR_NOMEM:
266  ast_log(LOG_ERROR, "Out of memory\n");
267  break;
268  case ERROR_USAGE:
269  ast_log(LOG_ERROR, "Usage: CUT(<varname>,<char-delim>,<range-spec>)\n");
270  break;
271  case 0:
272  ret = 0;
273  ast_copy_string(buf, ast_str_buffer(str), len);
274  break;
275  default:
276  ast_log(LOG_ERROR, "Unknown internal error\n");
277  }
278  ast_free(str);
279  return ret;
280 }
281 
282 static int acf_cut_exec2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
283 {
284  int ret = -1;
285 
286  switch (cut_internal(chan, data, buf, len)) {
287  case ERROR_NOARG:
288  ast_log(LOG_ERROR, "Syntax: CUT(<varname>,<char-delim>,<range-spec>) - missing argument!\n");
289  break;
290  case ERROR_NOMEM:
291  ast_log(LOG_ERROR, "Out of memory\n");
292  break;
293  case ERROR_USAGE:
294  ast_log(LOG_ERROR, "Usage: CUT(<varname>,<char-delim>,<range-spec>)\n");
295  break;
296  case 0:
297  ret = 0;
298  break;
299  default:
300  ast_log(LOG_ERROR, "Unknown internal error\n");
301  }
302 
303  return ret;
304 }
305 
306 static struct ast_custom_function acf_sort = {
307  .name = "SORT",
308  .read = acf_sort_exec,
309 };
310 
311 static struct ast_custom_function acf_cut = {
312  .name = "CUT",
313  .read = acf_cut_exec,
314  .read2 = acf_cut_exec2,
315 };
316 
317 static int unload_module(void)
318 {
319  int res = 0;
320 
321  res |= ast_custom_function_unregister(&acf_cut);
322  res |= ast_custom_function_unregister(&acf_sort);
323 
324  return res;
325 }
326 
327 static int load_module(void)
328 {
329  int res = 0;
330 
331  res |= ast_custom_function_register(&acf_cut);
332  res |= ast_custom_function_register(&acf_sort);
333 
334  return res;
335 }
336 
337 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Cut out information from a string");
const char * name
Definition: pbx.h:119
Main Channel structure associated with a channel.
#define AST_MODULE_INFO_STANDARD(keystr, desc)
Definition: module.h:567
Asterisk main include file. File version handling, generic pbx functions.
static int acf_cut_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_cut.c:256
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
#define AST_STANDARD_APP_ARGS(args, parse)
Performs the &#39;standard&#39; argument separation process for an application.
#define LOG_WARNING
Definition: logger.h:274
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:714
void ast_str_substitute_variables(struct ast_str **buf, ssize_t maxlen, struct ast_channel *chan, const char *templ)
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1091
static struct ast_custom_function acf_sort
Definition: func_cut.c:306
const char * str
Definition: app_jack.c:147
Generic File Format Support. Should be included by clients of the file handling routines. File service providers should instead include mod_format.h.
const char * args
#define NULL
Definition: resample.c:96
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
#define ERROR_NOARG
Definition: func_cut.c:98
#define ast_log
Definition: astobj2.c:42
#define ERROR_NOMEM
Definition: func_cut.c:99
General Asterisk PBX channel definitions.
Data structure associated with a custom dialplan function.
Definition: pbx.h:118
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
Decode an encoded control or extended ASCII character.
Definition: main/app.c:2927
Core PBX routines and definitions.
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:290
static int cut_internal(struct ast_channel *chan, char *data, struct ast_str **buf, ssize_t buflen)
Definition: func_cut.c:153
#define LOG_ERROR
Definition: logger.h:285
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:584
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
float value
Definition: func_cut.c:84
static int load_module(void)
Definition: func_cut.c:327
static void parse(struct mgcp_request *req)
Definition: chan_mgcp.c:1872
#define ast_free(a)
Definition: astmm.h:182
static int acf_sort_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_cut.c:235
#define ERROR_USAGE
Definition: func_cut.c:100
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:688
char * strsep(char **str, const char *delims)
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
char * key
Definition: func_cut.c:83
static struct ast_custom_function acf_cut
Definition: func_cut.c:311
static int unload_module(void)
Definition: func_cut.c:317
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
Asterisk module definitions.
static int sort_internal(struct ast_channel *chan, char *data, char *buffer, size_t buflen)
Definition: func_cut.c:102
static int acf_cut_exec2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
Definition: func_cut.c:282
#define AST_DECLARE_APP_ARGS(name, arglist)
Declare a structure to hold an application&#39;s arguments.
Application convenience functions, designed to give consistent look and feel to Asterisk apps...
static int sort_subroutine(const void *arg1, const void *arg2)
Definition: func_cut.c:87
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1508
#define ast_str_create(init_len)
Create a malloc&#39;ed dynamic length string.
Definition: strings.h:620
#define AST_APP_ARG(name)
Define an application argument.