4ae08efc2ab89bc9a3996ca008314120fd19d29a
[asterisk/asterisk.git] / funcs / func_channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2006, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*! \file
18  *
19  * \brief Channel info dialplan functions
20  *
21  * \author Kevin P. Fleming <kpfleming@digium.com>
22  * \author Ben Winslow
23  * 
24  * \ingroup functions
25  */
26
27 #include "asterisk.h"
28
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30
31 #include <regex.h>
32 #include <ctype.h>
33
34 #include "asterisk/module.h"
35 #include "asterisk/channel.h"
36 #include "asterisk/pbx.h"
37 #include "asterisk/utils.h"
38 #include "asterisk/app.h"
39 #include "asterisk/indications.h"
40 #include "asterisk/stringfields.h"
41 #include "asterisk/global_datastores.h"
42
43 /*** DOCUMENTATION
44         <function name="CHANNELS" language="en_US">
45                 <synopsis>
46                         Gets the list of channels, optionally filtering by a regular expression.
47                 </synopsis>
48                 <syntax>
49                         <parameter name="regular_expression" />
50                 </syntax>
51                 <description>
52                         <para>Gets the list of channels, optionally filtering by a <replaceable>regular_expression</replaceable>. If
53                         no argument is provided, all known channels are returned. The
54                         <replaceable>regular_expression</replaceable> must correspond to
55                         the POSIX.2 specification, as shown in <emphasis>regex(7)</emphasis>. The list returned
56                         will be space-delimited.</para>
57                 </description>
58         </function>
59         <function name="MASTER_CHANNEL" language="en_US">
60                 <synopsis>
61                         Gets or sets variables on the master channel
62                 </synopsis>
63                 <description>
64                         <para>Allows access to the channel which created the current channel, if any.  If the channel is already
65                         a master channel, then accesses local channel variables.</para>
66                 </description>
67         </function>
68         <function name="CHANNEL" language="en_US">
69                 <synopsis>
70                         Gets/sets various pieces of information about the channel.
71                 </synopsis>
72                 <syntax>
73                         <parameter name="item" required="true">
74                                 <para>Standard items (provided by all channel technologies) are:</para>
75                                 <enumlist>
76                                         <enum name="audioreadformat">
77                                                 <para>R/O format currently being read.</para>
78                                         </enum>
79                                         <enum name="audionativeformat">
80                                                 <para>R/O format used natively for audio.</para>
81                                         </enum>
82                                         <enum name="audiowriteformat">
83                                                 <para>R/O format currently being written.</para>
84                                         </enum>
85                                         <enum name="callgroup">
86                                                 <para>R/W call groups for call pickup.</para>
87                                         </enum>
88                                         <enum name="channeltype">
89                                                 <para>R/O technology used for channel.</para>
90                                         </enum>
91                                         <enum name="checkhangup">
92                                                 <para>R/O Whether the channel is hanging up (1/0)</para>
93                                         </enum>
94                                         <enum name="language">
95                                                 <para>R/W language for sounds played.</para>
96                                         </enum>
97                                         <enum name="musicclass">
98                                                 <para>R/W class (from musiconhold.conf) for hold music.</para>
99                                         </enum>
100                                         <enum name="name">
101                                                 <para>The name of the channel</para>
102                                         </enum>
103                                         <enum name="parkinglot">
104                                                 <para>R/W parkinglot for parking.</para>
105                                         </enum>
106                                         <enum name="rxgain">
107                                                 <para>R/W set rxgain level on channel drivers that support it.</para>
108                                         </enum>
109                                         <enum name="secure_bridge_signaling">
110                                                 <para>Whether or not channels bridged to this channel require secure signaling</para>
111                                         </enum>
112                                         <enum name="secure_bridge_media">
113                                                 <para>Whether or not channels bridged to this channel require secure media</para>
114                                         </enum>
115                                         <enum name="state">
116                                                 <para>R/O state for channel</para>
117                                         </enum>
118                                         <enum name="tonezone">
119                                                 <para>R/W zone for indications played</para>
120                                         </enum>
121                                         <enum name="transfercapability">
122                                                 <para>R/W ISDN Transfer Capability, one of:</para>
123                                                 <enumlist>
124                                                         <enum name="SPEECH" />
125                                                         <enum name="DIGITAL" />
126                                                         <enum name="RESTRICTED_DIGITAL" />
127                                                         <enum name="3K1AUDIO" />
128                                                         <enum name="DIGITAL_W_TONES" />
129                                                         <enum name="VIDEO" />
130                                                 </enumlist>
131                                         </enum>
132                                         <enum name="txgain">
133                                                 <para>R/W set txgain level on channel drivers that support it.</para>
134                                         </enum>
135                                         <enum name="videonativeformat">
136                                                 <para>R/O format used natively for video</para>
137                                         </enum>
138                                         <enum name="trace">
139                                                 <para>R/W whether or not context tracing is enabled, only available
140                                                 <emphasis>if CHANNEL_TRACE is defined</emphasis>.</para>
141                                         </enum>
142                                 </enumlist>
143                                 <para><emphasis>chan_sip</emphasis> provides the following additional options:</para>
144                                 <enumlist>
145                                         <enum name="peerip">
146                                                 <para>R/O Get the IP address of the peer.</para>
147                                         </enum>
148                                         <enum name="recvip">
149                                                 <para>R/O Get the source IP address of the peer.</para>
150                                         </enum>
151                                         <enum name="from">
152                                                 <para>R/O Get the URI from the From: header.</para>
153                                         </enum>
154                                         <enum name="uri">
155                                                 <para>R/O Get the URI from the Contact: header.</para>
156                                         </enum>
157                                         <enum name="useragent">
158                                                 <para>R/O Get the useragent.</para>
159                                         </enum>
160                                         <enum name="peername">
161                                                 <para>R/O Get the name of the peer.</para>
162                                         </enum>
163                                         <enum name="t38passthrough">
164                                                 <para>R/O <literal>1</literal> if T38 is offered or enabled in this channel,
165                                                 otherwise <literal>0</literal></para>
166                                         </enum>
167                                         <enum name="rtpqos">
168                                                 <para>R/O Get QOS information about the RTP stream</para>
169                                                 <para>    This option takes two additional arguments:</para>
170                                                 <para>    Argument 1:</para>
171                                                 <para>     <literal>audio</literal>             Get data about the audio stream</para>
172                                                 <para>     <literal>video</literal>             Get data about the video stream</para>
173                                                 <para>     <literal>text</literal>              Get data about the text stream</para>
174                                                 <para>    Argument 2:</para>
175                                                 <para>     <literal>local_ssrc</literal>        Local SSRC (stream ID)</para>
176                                                 <para>     <literal>local_lostpackets</literal> Local lost packets</para>
177                                                 <para>     <literal>local_jitter</literal>      Local calculated jitter</para>
178                                                 <para>     <literal>local_maxjitter</literal>   Local calculated jitter (maximum)</para>
179                                                 <para>     <literal>local_minjitter</literal>   Local calculated jitter (minimum)</para>
180                                                 <para>     <literal>local_normdevjitter</literal>Local calculated jitter (normal deviation)</para>
181                                                 <para>     <literal>local_stdevjitter</literal> Local calculated jitter (standard deviation)</para>
182                                                 <para>     <literal>local_count</literal>       Number of received packets</para>
183                                                 <para>     <literal>remote_ssrc</literal>       Remote SSRC (stream ID)</para>
184                                                 <para>     <literal>remote_lostpackets</literal>Remote lost packets</para>
185                                                 <para>     <literal>remote_jitter</literal>     Remote reported jitter</para>
186                                                 <para>     <literal>remote_maxjitter</literal>  Remote calculated jitter (maximum)</para>
187                                                 <para>     <literal>remote_minjitter</literal>  Remote calculated jitter (minimum)</para>
188                                                 <para>     <literal>remote_normdevjitter</literal>Remote calculated jitter (normal deviation)</para>
189                                                 <para>     <literal>remote_stdevjitter</literal>Remote calculated jitter (standard deviation)</para>
190                                                 <para>     <literal>remote_count</literal>      Number of transmitted packets</para>
191                                                 <para>     <literal>remote_ssrc</literal>       Remote SSRC (stream ID)</para>
192                                                 <para>     <literal>remote_lostpackets</literal>Remote lost packets</para>
193                                                 <para>     <literal>remote_jitter</literal>     Remote reported jitter</para>
194                                                 <para>     <literal>remote_maxjitter</literal>  Remote calculated jitter (maximum)</para>
195                                                 <para>     <literal>remote_minjitter</literal>  Remote calculated jitter (minimum)</para>
196                                                 <para>     <literal>remote_normdevjitter</literal>Remote calculated jitter (normal deviation)</para>
197                                                 <para>     <literal>remote_stdevjitter</literal>Remote calculated jitter (standard deviation)</para>
198                                                 <para>     <literal>remote_count</literal>      Number of transmitted packets</para>
199                                                 <para>     <literal>rtt</literal>               Round trip time</para>
200                                                 <para>     <literal>maxrtt</literal>            Round trip time (maximum)</para>
201                                                 <para>     <literal>minrtt</literal>            Round trip time (minimum)</para>
202                                                 <para>     <literal>normdevrtt</literal>        Round trip time (normal deviation)</para>
203                                                 <para>     <literal>stdevrtt</literal>          Round trip time (standard deviation)</para>
204                                                 <para>     <literal>all</literal>               All statistics (in a form suited to logging,
205                                                 but not for parsing)</para>
206                                         </enum>
207                                         <enum name="rtpdest">
208                                                 <para>R/O Get remote RTP destination information.</para>
209                                                 <para>   This option takes one additional argument:</para>
210                                                 <para>    Argument 1:</para>
211                                                 <para>     <literal>audio</literal>             Get audio destination</para>
212                                                 <para>     <literal>video</literal>             Get video destination</para>
213                                                 <para>     <literal>text</literal>              Get text destination</para>
214                                         </enum>
215                                 </enumlist>
216                                 <para><emphasis>chan_iax2</emphasis> provides the following additional options:</para>
217                                 <enumlist>
218                                         <enum name="peerip">
219                                                 <para>R/O Get the peer's ip address.</para>
220                                         </enum>
221                                         <enum name="peername">
222                                                 <para>R/O Get the peer's username.</para>
223                                         </enum>
224                                 </enumlist>
225                                 <para><emphasis>chan_dahdi</emphasis> provides the following additional options:</para>
226                                 <enumlist>
227                                         <enum name="keypad_digits">
228                                                 <para>R/O PRI Keypad digits that came in with the SETUP message.</para>
229                                         </enum>
230                                         <enum name="reversecharge">
231                                                 <para>R/O PRI Reverse Charging Indication, one of:</para>
232                                                 <enumlist>
233                                                         <enum name="-1"> <para>None</para></enum>
234                                                         <enum name=" 1"> <para>Reverse Charging Requested</para></enum>
235                                                 </enumlist>
236                                         </enum>
237                                         <enum name="no_media_path">
238                                                 <para>R/O PRI Nonzero if the channel has no B channel.
239                                                 The channel is either on hold or a call waiting call.</para>
240                                         </enum>
241                                 </enumlist>
242                         </parameter>
243                 </syntax>
244                 <description>
245                         <para>Gets/sets various pieces of information about the channel, additional <replaceable>item</replaceable> may
246                         be available from the channel driver; see its documentation for details. Any <replaceable>item</replaceable>
247                         requested that is not available on the current channel will return an empty string.</para>
248                 </description>
249         </function>
250  ***/
251
252 #define locked_copy_string(chan, dest, source, len) \
253         do { \
254                 ast_channel_lock(chan); \
255                 ast_copy_string(dest, source, len); \
256                 ast_channel_unlock(chan); \
257         } while (0)
258 #define locked_string_field_set(chan, field, source) \
259         do { \
260                 ast_channel_lock(chan); \
261                 ast_string_field_set(chan, field, source); \
262                 ast_channel_unlock(chan); \
263         } while (0)
264
265 static const char * const transfercapability_table[0x20] = {
266         "SPEECH", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK",
267         "DIGITAL", "RESTRICTED_DIGITAL", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK",
268         "3K1AUDIO", "DIGITAL_W_TONES", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK",
269         "VIDEO", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK", "UNK", };
270
271 static int func_channel_read(struct ast_channel *chan, const char *function,
272                              char *data, char *buf, size_t len)
273 {
274         int ret = 0;
275         char tmp[512];
276         struct ast_format_cap *tmpcap;
277
278         if (!strcasecmp(data, "audionativeformat")) {
279                 if ((tmpcap = ast_format_cap_get_type(chan->nativeformats, AST_FORMAT_TYPE_AUDIO))) {
280                         ast_copy_string(buf, ast_getformatname_multiple(tmp, sizeof(tmp), tmpcap), len);
281                         tmpcap = ast_format_cap_destroy(tmpcap);
282                 }
283         } else if (!strcasecmp(data, "videonativeformat")) {
284                 if ((tmpcap = ast_format_cap_get_type(chan->nativeformats, AST_FORMAT_TYPE_VIDEO))) {
285                         ast_copy_string(buf, ast_getformatname_multiple(tmp, sizeof(tmp), tmpcap), len);
286                         tmpcap = ast_format_cap_destroy(tmpcap);
287                 }
288         } else if (!strcasecmp(data, "audioreadformat")) {
289                 ast_copy_string(buf, ast_getformatname(&chan->readformat), len);
290         } else if (!strcasecmp(data, "audiowriteformat")) {
291                 ast_copy_string(buf, ast_getformatname(&chan->writeformat), len);
292 #ifdef CHANNEL_TRACE
293         } else if (!strcasecmp(data, "trace")) {
294                 ast_channel_lock(chan);
295                 ast_copy_string(buf, ast_channel_trace_is_enabled(chan) ? "1" : "0", len);
296                 ast_channel_unlock(chan);
297 #endif
298         } else if (!strcasecmp(data, "tonezone") && chan->zone)
299                 locked_copy_string(chan, buf, chan->zone->country, len);
300         else if (!strcasecmp(data, "language"))
301                 locked_copy_string(chan, buf, chan->language, len);
302         else if (!strcasecmp(data, "musicclass"))
303                 locked_copy_string(chan, buf, chan->musicclass, len);
304         else if (!strcasecmp(data, "name")) {
305                 locked_copy_string(chan, buf, chan->name, len);
306         } else if (!strcasecmp(data, "parkinglot"))
307                 locked_copy_string(chan, buf, chan->parkinglot, len);
308         else if (!strcasecmp(data, "state"))
309                 locked_copy_string(chan, buf, ast_state2str(chan->_state), len);
310         else if (!strcasecmp(data, "channeltype"))
311                 locked_copy_string(chan, buf, chan->tech->type, len);
312         else if (!strcasecmp(data, "accountcode"))
313                 locked_copy_string(chan, buf, chan->accountcode, len);
314         else if (!strcasecmp(data, "checkhangup")) {
315                 ast_channel_lock(chan);
316                 ast_copy_string(buf, ast_check_hangup(chan) ? "1" : "0", len);
317                 ast_channel_unlock(chan);
318         } else if (!strcasecmp(data, "peeraccount"))
319                 locked_copy_string(chan, buf, chan->peeraccount, len);
320         else if (!strcasecmp(data, "hangupsource"))
321                 locked_copy_string(chan, buf, chan->hangupsource, len);
322         else if (!strcasecmp(data, "appname") && chan->appl)
323                 locked_copy_string(chan, buf, chan->appl, len);
324         else if (!strcasecmp(data, "appdata") && chan->data)
325                 locked_copy_string(chan, buf, chan->data, len);
326         else if (!strcasecmp(data, "exten") && chan->data)
327                 locked_copy_string(chan, buf, chan->exten, len);
328         else if (!strcasecmp(data, "context") && chan->data)
329                 locked_copy_string(chan, buf, chan->context, len);
330         else if (!strcasecmp(data, "userfield") && chan->data)
331                 locked_copy_string(chan, buf, chan->userfield, len);
332         else if (!strcasecmp(data, "channame") && chan->data)
333                 locked_copy_string(chan, buf, chan->name, len);
334         else if (!strcasecmp(data, "linkedid")) {
335                 ast_channel_lock(chan);
336                 if (ast_strlen_zero(chan->linkedid)) {
337                         /* fall back on the channel's uniqueid if linkedid is unset */
338                         ast_copy_string(buf, chan->uniqueid, len);
339                 }
340                 else {
341                         ast_copy_string(buf, chan->linkedid, len);
342                 }
343                 ast_channel_unlock(chan);
344         } else if (!strcasecmp(data, "peer")) {
345                 struct ast_channel *p;
346                 ast_channel_lock(chan);
347                 p = ast_bridged_channel(chan);
348                 if (p || chan->tech || chan->cdr) /* dummy channel? if so, we hid the peer name in the language */
349                         ast_copy_string(buf, (p ? p->name : ""), len);
350                 else {
351                         /* a dummy channel can still pass along bridged peer info via
352                            the BRIDGEPEER variable */
353                         const char *pname = pbx_builtin_getvar_helper(chan, "BRIDGEPEER");
354                         if (!ast_strlen_zero(pname))
355                                 ast_copy_string(buf, pname, len); /* a horrible kludge, but... how else? */
356                         else
357                                 buf[0] = 0;
358                 }
359                 ast_channel_unlock(chan);
360         } else if (!strcasecmp(data, "uniqueid")) {
361                 locked_copy_string(chan, buf, chan->uniqueid, len);
362         } else if (!strcasecmp(data, "transfercapability")) {
363                 locked_copy_string(chan, buf, transfercapability_table[chan->transfercapability & 0x1f], len);
364         } else if (!strcasecmp(data, "callgroup")) {
365                 char groupbuf[256];
366                 locked_copy_string(chan, buf,  ast_print_group(groupbuf, sizeof(groupbuf), chan->callgroup), len);
367         } else if (!strcasecmp(data, "amaflags")) {
368                 char amabuf[256];
369                 snprintf(amabuf,sizeof(amabuf), "%d", chan->amaflags);
370                 locked_copy_string(chan, buf, amabuf, len);
371         } else if (!strncasecmp(data, "secure_bridge_", 14)) {
372                 struct ast_datastore *ds;
373                 ast_channel_lock(chan);
374                 if ((ds = ast_channel_datastore_find(chan, &secure_call_info, NULL))) {
375                         struct ast_secure_call_store *encrypt = ds->data;
376                         if (!strcasecmp(data, "secure_bridge_signaling")) {
377                                 snprintf(buf, len, "%s", encrypt->signaling ? "1" : "");
378                         } else if (!strcasecmp(data, "secure_bridge_media")) {
379                                 snprintf(buf, len, "%s", encrypt->media ? "1" : "");
380                         }
381                 }
382                 ast_channel_unlock(chan);
383         } else if (!chan->tech || !chan->tech->func_channel_read || chan->tech->func_channel_read(chan, function, data, buf, len)) {
384                 ast_log(LOG_WARNING, "Unknown or unavailable item requested: '%s'\n", data);
385                 ret = -1;
386         }
387
388         return ret;
389 }
390
391 static int func_channel_write_real(struct ast_channel *chan, const char *function,
392                               char *data, const char *value)
393 {
394         int ret = 0;
395         signed char gainset;
396
397         if (!strcasecmp(data, "language"))
398                 locked_string_field_set(chan, language, value);
399         else if (!strcasecmp(data, "parkinglot"))
400                 locked_string_field_set(chan, parkinglot, value);
401         else if (!strcasecmp(data, "musicclass"))
402                 locked_string_field_set(chan, musicclass, value);
403         else if (!strcasecmp(data, "accountcode"))
404                 locked_string_field_set(chan, accountcode, value);
405         else if (!strcasecmp(data, "userfield"))
406                 locked_string_field_set(chan, userfield, value);
407         else if (!strcasecmp(data, "amaflags")) {
408                 ast_channel_lock(chan);
409                 if(isdigit(*value)) {
410                         sscanf(value, "%30d", &chan->amaflags);
411                 } else if (!strcasecmp(value,"OMIT")){
412                         chan->amaflags = 1;
413                 } else if (!strcasecmp(value,"BILLING")){
414                         chan->amaflags = 2;
415                 } else if (!strcasecmp(value,"DOCUMENTATION")){
416                         chan->amaflags = 3;
417                 }
418                 ast_channel_unlock(chan);
419         } else if (!strcasecmp(data, "peeraccount"))
420                 locked_string_field_set(chan, peeraccount, value);
421         else if (!strcasecmp(data, "hangupsource"))
422                 /* XXX - should we be forcing this here? */
423                 ast_set_hangupsource(chan, value, 0);
424 #ifdef CHANNEL_TRACE
425         else if (!strcasecmp(data, "trace")) {
426                 ast_channel_lock(chan);
427                 if (ast_true(value)) 
428                         ret = ast_channel_trace_enable(chan);
429                 else if (ast_false(value))
430                         ret = ast_channel_trace_disable(chan);
431                 else {
432                         ret = -1;
433                         ast_log(LOG_WARNING, "Invalid value for CHANNEL(trace).");
434                 }
435                 ast_channel_unlock(chan);
436         }
437 #endif
438         else if (!strcasecmp(data, "tonezone")) {
439                 struct ast_tone_zone *new_zone;
440                 if (!(new_zone = ast_get_indication_zone(value))) {
441                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", value);
442                         ret = -1;       
443                 } else {
444                         ast_channel_lock(chan);
445                         if (chan->zone) {
446                                 chan->zone = ast_tone_zone_unref(chan->zone);
447                         }
448                         chan->zone = ast_tone_zone_ref(new_zone);
449                         ast_channel_unlock(chan);
450                         new_zone = ast_tone_zone_unref(new_zone);
451                 }
452         } else if (!strcasecmp(data, "callgroup"))
453                 chan->callgroup = ast_get_group(value);
454         else if (!strcasecmp(data, "txgain")) {
455                 sscanf(value, "%4hhd", &gainset);
456                 ast_channel_setoption(chan, AST_OPTION_TXGAIN, &gainset, sizeof(gainset), 0);
457         } else if (!strcasecmp(data, "rxgain")) {
458                 sscanf(value, "%4hhd", &gainset);
459                 ast_channel_setoption(chan, AST_OPTION_RXGAIN, &gainset, sizeof(gainset), 0);
460         } else if (!strcasecmp(data, "transfercapability")) {
461                 unsigned short i;
462                 for (i = 0; i < 0x20; i++) {
463                         if (!strcasecmp(transfercapability_table[i], value) && strcmp(value, "UNK")) {
464                                 chan->transfercapability = i;
465                                 break;
466                         }
467                 }
468         } else if (!strncasecmp(data, "secure_bridge_", 14)) {
469                 struct ast_datastore *ds;
470                 struct ast_secure_call_store *store;
471
472                 if (!chan || !value) {
473                         return -1;
474                 }
475
476                 ast_channel_lock(chan);
477                 if (!(ds = ast_channel_datastore_find(chan, &secure_call_info, NULL))) {
478                         if (!(ds = ast_datastore_alloc(&secure_call_info, NULL))) {
479                                 ast_channel_unlock(chan);
480                                 return -1;
481                         }
482                         if (!(store = ast_calloc(1, sizeof(*store)))) {
483                                 ast_channel_unlock(chan);
484                                 ast_free(ds);
485                                 return -1;
486                         }
487                         ds->data = store;
488                         ast_channel_datastore_add(chan, ds);
489                 } else {
490                         store = ds->data;
491                 }
492                 ast_channel_unlock(chan);
493
494                 if (!strcasecmp(data, "secure_bridge_signaling")) {
495                         store->signaling = ast_true(value) ? 1 : 0;
496                 } else if (!strcasecmp(data, "secure_bridge_media")) {
497                         store->media = ast_true(value) ? 1 : 0;
498                 }
499         } else if (!chan->tech->func_channel_write
500                  || chan->tech->func_channel_write(chan, function, data, value)) {
501                 ast_log(LOG_WARNING, "Unknown or unavailable item requested: '%s'\n",
502                                 data);
503                 ret = -1;
504         }
505
506         return ret;
507 }
508
509 static int func_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value)
510 {
511         int res;
512         ast_chan_write_info_t write_info = {
513                 .version = AST_CHAN_WRITE_INFO_T_VERSION,
514                 .write_fn = func_channel_write_real,
515                 .chan = chan,
516                 .function = function,
517                 .data = data,
518                 .value = value,
519         };
520
521         res = func_channel_write_real(chan, function, data, value);
522         ast_channel_setoption(chan, AST_OPTION_CHANNEL_WRITE, &write_info, sizeof(write_info), 0);
523
524         return res;
525 }
526
527 static struct ast_custom_function channel_function = {
528         .name = "CHANNEL",
529         .read = func_channel_read,
530         .write = func_channel_write,
531 };
532
533 static int func_channels_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t maxlen)
534 {
535         struct ast_channel *c = NULL;
536         regex_t re;
537         int res;
538         size_t buflen = 0;
539         struct ast_channel_iterator *iter;
540
541         buf[0] = '\0';
542
543         if (!ast_strlen_zero(data)) {
544                 if ((res = regcomp(&re, data, REG_EXTENDED | REG_ICASE | REG_NOSUB))) {
545                         regerror(res, &re, buf, maxlen);
546                         ast_log(LOG_WARNING, "Error compiling regular expression for %s(%s): %s\n", function, data, buf);
547                         return -1;
548                 }
549         }
550
551         if (!(iter = ast_channel_iterator_all_new())) {
552                 if (!ast_strlen_zero(data)) {
553                         regfree(&re);
554                 }
555                 return -1;
556         }
557
558         while ((c = ast_channel_iterator_next(iter))) {
559                 ast_channel_lock(c);
560                 if (ast_strlen_zero(data) || regexec(&re, c->name, 0, NULL, 0) == 0) {
561                         size_t namelen = strlen(c->name);
562                         if (buflen + namelen + (ast_strlen_zero(buf) ? 0 : 1) + 1 < maxlen) {
563                                 if (!ast_strlen_zero(buf)) {
564                                         strcat(buf, " ");
565                                         buflen++;
566                                 }
567                                 strcat(buf, c->name);
568                                 buflen += namelen;
569                         } else {
570                                 ast_log(LOG_WARNING, "Number of channels exceeds the available buffer space.  Output will be truncated!\n");
571                         }
572                 }
573                 ast_channel_unlock(c);
574                 c = ast_channel_unref(c);
575         }
576
577         ast_channel_iterator_destroy(iter);
578
579         if (!ast_strlen_zero(data)) {
580                 regfree(&re);
581         }
582
583         return 0;
584 }
585
586 static struct ast_custom_function channels_function = {
587         .name = "CHANNELS",
588         .read = func_channels_read,
589 };
590
591 static int func_mchan_read(struct ast_channel *chan, const char *function,
592                              char *data, struct ast_str **buf, ssize_t len)
593 {
594         struct ast_channel *mchan = ast_channel_get_by_name(chan->linkedid);
595         char *template = alloca(4 + strlen(data));
596         sprintf(template, "${%s}", data); /* SAFE */
597         ast_str_substitute_variables(buf, len, mchan ? mchan : chan, template);
598         if (mchan) {
599                 ast_channel_unref(mchan);
600         }
601         return 0;
602 }
603
604 static int func_mchan_write(struct ast_channel *chan, const char *function,
605                               char *data, const char *value)
606 {
607         struct ast_channel *mchan = ast_channel_get_by_name(chan->linkedid);
608         pbx_builtin_setvar_helper(mchan ? mchan : chan, data, value);
609         if (mchan) {
610                 ast_channel_unref(mchan);
611         }
612         return 0;
613 }
614
615 static struct ast_custom_function mchan_function = {
616         .name = "MASTER_CHANNEL",
617         .read2 = func_mchan_read,
618         .write = func_mchan_write,
619 };
620
621 static int unload_module(void)
622 {
623         int res = 0;
624
625         res |= ast_custom_function_unregister(&channel_function);
626         res |= ast_custom_function_unregister(&channels_function);
627         res |= ast_custom_function_unregister(&mchan_function);
628
629         return res;
630 }
631
632 static int load_module(void)
633 {
634         int res = 0;
635
636         res |= ast_custom_function_register(&channel_function);
637         res |= ast_custom_function_register(&channels_function);
638         res |= ast_custom_function_register(&mchan_function);
639
640         return res;
641 }
642
643 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Channel information dialplan functions");