Asterisk - The Open Source Telephony Project GIT-master-754dea3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
app_signal.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2022, Naveen Albert
5 *
6 * Naveen Albert <asterisk@phreaknet.org>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19/*! \file
20 *
21 * \brief Channel signaling applications
22 *
23 * \author Naveen Albert <asterisk@phreaknet.org>
24 *
25 * \ingroup applications
26 */
27
28/*** MODULEINFO
29 <support_level>extended</support_level>
30 ***/
31
32#include "asterisk.h"
33
34#include "asterisk/file.h"
35#include "asterisk/channel.h"
36#include "asterisk/pbx.h"
37#include "asterisk/module.h"
38#include "asterisk/app.h"
39#include "asterisk/module.h"
40
41/*** DOCUMENTATION
42 <application name="Signal" language="en_US">
43 <since>
44 <version>18.17.0</version>
45 <version>20.2.0</version>
46 </since>
47 <synopsis>
48 Sends a signal to any waiting channels.
49 </synopsis>
50 <syntax>
51 <parameter name="signalname" required="true">
52 <para>Name of signal to send.</para>
53 </parameter>
54 <parameter name="payload" required="false">
55 <para>Payload data to deliver.</para>
56 </parameter>
57 </syntax>
58 <description>
59 <para>Sends a named signal to any channels that may be
60 waiting for one. Acts as a producer in a simple
61 message queue.</para>
62 <variablelist>
63 <variable name="SIGNALSTATUS">
64 <value name="SUCCESS">
65 Signal was successfully sent to at least
66 one listener for processing.
67 </value>
68 <value name="FAILURE">
69 Signal could not be sent or nobody
70 was listening for this signal.
71 </value>
72 </variable>
73 </variablelist>
74 <example title="Send a signal named workdone">
75 same => n,Signal(workdone,Work has completed)
76 </example>
77 </description>
78 <see-also>
79 <ref type="application">WaitForSignal</ref>
80 </see-also>
81 </application>
82 <application name="WaitForSignal" language="en_US">
83 <since>
84 <version>18.17.0</version>
85 <version>20.2.0</version>
86 </since>
87 <synopsis>
88 Waits for a named signal on a channel.
89 </synopsis>
90 <syntax>
91 <parameter name="signalname" required="true">
92 <para>Name of signal to send.</para>
93 </parameter>
94 <parameter name="signaltimeout" required="false">
95 <para>Maximum time, in seconds, to wait for signal.</para>
96 </parameter>
97 </syntax>
98 <description>
99 <para>Waits for <replaceable>signaltimeout</replaceable> seconds on the current
100 channel to receive a signal with name <replaceable>signalname</replaceable>.
101 Acts as a consumer in a simple message queue.</para>
102 <para>Result of signal wait will be stored in the following variables:</para>
103 <variablelist>
104 <variable name="WAITFORSIGNALSTATUS">
105 <value name="SIGNALED">
106 Signal was received.
107 </value>
108 <value name="TIMEOUT">
109 Timed out waiting for signal.
110 </value>
111 <value name="HANGUP">
112 Channel hung up before signal was received.
113 </value>
114 </variable>
115 <variable name="WAITFORSIGNALPAYLOAD">
116 <para>Data payload attached to signal, if it exists</para>
117 </variable>
118 </variablelist>
119 <example title="Wait for the workdone signal, indefinitely, and print out payload">
120 same => n,WaitForSignal(workdone)
121 same => n,NoOp(Received: ${WAITFORSIGNALPAYLOAD})
122 </example>
123 </description>
124 <see-also>
125 <ref type="application">Signal</ref>
126 </see-also>
127 </application>
128 ***/
129
130static const char * const app = "Signal";
131static const char * const app2 = "WaitForSignal";
132
138 unsigned int signaled:1;
139 char *payload;
140 AST_LIST_ENTRY(signalitem) entry; /*!< Next Signal item */
141};
142
144
145static struct signalitem *alloc_signal(const char *sname)
146{
147 struct signalitem *s;
148
149 if (!(s = ast_calloc(1, sizeof(*s)))) {
150 return NULL;
151 }
152
153 ast_mutex_init(&s->lock);
154 ast_copy_string(s->name, sname, sizeof(s->name));
155
156 s->sig_alert_pipe[0] = -1;
157 s->sig_alert_pipe[1] = -1;
158 s->watchers = 0;
159 s->payload = NULL;
161
162 return s;
163}
164
165static int dealloc_signal(struct signalitem *s)
166{
167 if (s->watchers) { /* somebody is still using us... refuse to go away */
168 ast_debug(1, "Signal '%s' is still being used by %d listener(s)\n", s->name, s->watchers);
169 return -1;
170 }
173 if (s->payload) {
174 ast_free(s->payload);
175 s->payload = NULL;
176 }
177 ast_free(s);
178 s = NULL;
179 return 0;
180}
181
182static int remove_signal(char *sname)
183{
184 int res = -1;
185 struct signalitem *s;
186
188 if (!strcmp(s->name, sname)) {
190 res = dealloc_signal(s);
191 ast_debug(1, "Removed signal '%s'\n", sname);
192 }
193 }
195
196 return res;
197}
198
199static struct signalitem *get_signal(char *sname, int addnew)
200{
201 struct signalitem *s = NULL;
204 if (!strcasecmp(s->name, sname)) {
205 ast_debug(1, "Using existing signal item '%s'\n", sname);
206 break;
207 }
208 }
209 if (!s) {
210 if (addnew) { /* signal doesn't exist, so create it */
211 s = alloc_signal(sname);
212 /* Totally fail if we fail to find/create an entry */
213 if (s) {
214 ast_debug(1, "Created new signal item '%s'\n", sname);
216 } else {
217 ast_log(LOG_WARNING, "Failed to create signal item for '%s'\n", sname);
218 }
219 } else {
220 ast_debug(1, "Signal '%s' doesn't exist, and not creating it\n", sname);
221 }
222 }
224 return s;
225}
226
227static int wait_for_signal_or_hangup(struct ast_channel *chan, char *signame, int timeout)
228{
229 struct signalitem *s = NULL;
230 int ms, remaining_time, res = 1, goaway = 0;
231 struct timeval start;
232 struct ast_frame *frame = NULL;
233
234 remaining_time = timeout;
235 start = ast_tvnow();
236
237 s = get_signal(signame, 1);
238
239 ast_mutex_lock(&s->lock);
240 s->watchers = s->watchers + 1; /* we unlock, because a) other people need to use this and */
241 ast_mutex_unlock(&s->lock); /* b) the signal will be available to us as long as watchers > 0 */
242
243 while (timeout == 0 || remaining_time > 0) {
244 int ofd, exception;
245
246 ms = 1000;
247 errno = 0;
248 if (ast_waitfor_nandfds(&chan, 1, &s->sig_alert_pipe[0], 1, &exception, &ofd, &ms)) { /* channel won */
249 if (!(frame = ast_read(chan))) { /* channel hung up */
250 ast_debug(1, "Channel '%s' did not return a frame; probably hung up.\n", ast_channel_name(chan));
251 res = -1;
252 break;
253 } else {
254 ast_frfree(frame); /* handle frames */
255 }
256 } else if (ofd == s->sig_alert_pipe[0]) { /* fd won */
258 ast_debug(1, "Alert pipe has data for us\n");
259 res = 0;
260 break;
261 } else {
262 ast_debug(1, "Alert pipe does not have data for us\n");
263 }
264 } else { /* nobody won */
265 if (ms && (ofd < 0)) {
266 if (!((errno == 0) || (errno == EINTR))) {
267 ast_log(LOG_WARNING, "Something bad happened while channel '%s' was polling.\n", ast_channel_name(chan));
268 break;
269 }
270 } /* else, nothing happened */
271 }
272 if (timeout) {
273 remaining_time = ast_remaining_ms(start, timeout);
274 }
275 }
276
277 /* WRLOCK the list so that if we're going to destroy the signal now, nobody else can grab it before that happens. */
279 ast_mutex_lock(&s->lock);
280 if (s->payload) {
281 pbx_builtin_setvar_helper(chan, "WAITFORSIGNALPAYLOAD", s->payload);
282 }
283 s->watchers = s->watchers - 1;
284 if (s->watchers) { /* folks are still waiting for this, pass it on... */
285 int save_errno = errno;
287 ast_log(LOG_WARNING, "%s: write() failed: %s\n", __FUNCTION__, strerror(errno));
288 }
289 errno = save_errno;
290 } else { /* nobody else is waiting for this */
291 goaway = 1; /* we were the last guy using this, so mark signal item for destruction */
292 }
294
295 if (goaway) {
296 /* remove_signal calls ast_mutex_destroy, so don't call it with the mutex itself locked. */
297 remove_signal(signame);
298 }
300
301 return res;
302}
303
304static int send_signal(char *signame, char *payload)
305{
306 struct signalitem *s;
307 int save_errno = errno;
308 int res = 0;
309
310 s = get_signal(signame, 0); /* if signal doesn't exist already, no point in creating it, because nobody could be waiting for it! */
311
312 if (!s) {
313 return -1; /* this signal didn't exist, so we can't send a signal for it */
314 }
315
316 /* at this point, we know someone is listening, since signals are destroyed when watchers gets down to 0 */
317 ast_mutex_lock(&s->lock);
318 s->signaled = 1;
319 if (payload && *payload) {
320 int len = strlen(payload);
321 if (s->payload) {
322 ast_free(s->payload); /* if there was already a payload, replace it */
323 s->payload = NULL;
324 }
325 s->payload = ast_malloc(len + 1);
326 if (!s->payload) {
327 ast_log(LOG_WARNING, "Failed to allocate signal payload '%s'\n", payload);
328 } else {
330 }
331 }
333 ast_log(LOG_WARNING, "%s: write() failed: %s\n", __FUNCTION__, strerror(errno));
334 s->signaled = 0; /* okay, so we didn't send a signal after all... */
335 res = -1;
336 }
337 errno = save_errno;
338 ast_debug(1, "Sent '%s' signal to %d listeners\n", signame, s->watchers);
340
341 return res;
342}
343
344static int waitsignal_exec(struct ast_channel *chan, const char *data)
345{
346 char *argcopy;
347 int r = 0, timeoutms = 0;
348 double timeout = 0;
349
351 AST_APP_ARG(signame);
352 AST_APP_ARG(sigtimeout);
353 );
354
355 if (ast_strlen_zero(data)) {
356 ast_log(LOG_WARNING, "Signal() requires arguments\n");
357 return -1;
358 }
359
360 argcopy = ast_strdupa(data);
361 AST_STANDARD_APP_ARGS(args, argcopy);
362
363 if (ast_strlen_zero(args.signame)) {
364 ast_log(LOG_WARNING, "Missing signal name\n");
365 return -1;
366 }
367 if (strlen(args.signame) >= AST_MAX_CONTEXT) {
368 ast_log(LOG_WARNING, "Signal name '%s' is too long\n", args.signame);
369 return -1;
370 }
371 if (!ast_strlen_zero(args.sigtimeout)) {
372 if (sscanf(args.sigtimeout, "%30lg", &timeout) != 1 || timeout < 0) {
373 ast_log(LOG_WARNING, "Invalid timeout provided: %s. Defaulting to no timeout.\n", args.sigtimeout);
374 } else {
375 timeoutms = timeout * 1000; /* sec to msec */
376 }
377 }
378
379 if (timeout > 0) {
380 ast_debug(1, "Waiting for signal '%s' for %d ms\n", args.signame, timeoutms);
381 } else {
382 ast_debug(1, "Waiting for signal '%s', indefinitely\n", args.signame);
383 }
384
385 r = wait_for_signal_or_hangup(chan, args.signame, timeoutms);
386
387 if (r == 1) {
388 ast_verb(3, "Channel '%s' timed out, waiting for signal '%s'\n", ast_channel_name(chan), args.signame);
389 pbx_builtin_setvar_helper(chan, "WAITFORSIGNALSTATUS", "TIMEOUT");
390 } else if (!r) {
391 ast_verb(3, "Received signal '%s' on channel '%s'\n", args.signame, ast_channel_name(chan));
392 pbx_builtin_setvar_helper(chan, "WAITFORSIGNALSTATUS", "SIGNALED");
393 } else {
394 pbx_builtin_setvar_helper(chan, "WAITFORSIGNALSTATUS", "HANGUP");
395 ast_verb(3, "Channel '%s' hung up\n", ast_channel_name(chan));
396 return -1;
397 }
398
399 return 0;
400}
401
402static int signal_exec(struct ast_channel *chan, const char *data)
403{
404 char *argcopy;
406 AST_APP_ARG(signame);
408 );
409
410 if (ast_strlen_zero(data)) {
411 ast_log(LOG_WARNING, "Signal() requires arguments\n");
412 return -1;
413 }
414
415 argcopy = ast_strdupa(data);
416 AST_STANDARD_APP_ARGS(args, argcopy);
417
418 if (ast_strlen_zero(args.signame)) {
419 ast_log(LOG_WARNING, "Missing signal name\n");
420 return -1;
421 }
422 if (strlen(args.signame) >= AST_MAX_CONTEXT) {
423 ast_log(LOG_WARNING, "Signal name '%s' is too long\n", args.signame);
424 return -1;
425 }
426
427 if (send_signal(args.signame, args.payload)) {
428 pbx_builtin_setvar_helper(chan, "SIGNALSTATUS", "FAILURE");
429 } else {
430 pbx_builtin_setvar_helper(chan, "SIGNALSTATUS", "SUCCESS");
431 }
432
433 return 0;
434}
435
436static int unload_module(void)
437{
438 struct signalitem *s;
439 int res = 0;
440
441 /* To avoid a locking nightmare, and for logistical reasons, this module
442 * will refuse to unload if watchers > 0. That way we know a signal's
443 * pipe won't disappear while it's being used. */
444
446 /* Don't just use AST_RWLIST_REMOVE_HEAD, because if dealloc_signal fails, it should stay in the list. */
448 int mres = dealloc_signal(s);
449 res |= mres;
450 if (!mres) {
452 }
453 }
456
457 /* One or more signals still has watchers. */
458 if (res) {
459 ast_log(LOG_WARNING, "One or more signals is currently in use. Unload failed.\n");
460 return res;
461 }
462
465
466 return res;
467}
468
469static int load_module(void)
470{
471 int res;
472
475
476 return res;
477}
478
479AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Channel Signaling Applications");
void ast_alertpipe_close(int alert_pipe[2])
Close an alert pipe.
Definition: alertpipe.c:79
ssize_t ast_alertpipe_write(int alert_pipe[2])
Write an event to an alert pipe.
Definition: alertpipe.c:120
int ast_alertpipe_init(int alert_pipe[2])
Initialize an alert pipe.
Definition: alertpipe.c:38
@ AST_ALERT_READ_SUCCESS
Definition: alertpipe.h:25
ast_alert_status_t ast_alertpipe_read(int alert_pipe[2])
Read an event from an alert pipe.
Definition: alertpipe.c:102
static int wait_for_signal_or_hangup(struct ast_channel *chan, char *signame, int timeout)
Definition: app_signal.c:227
static int signal_exec(struct ast_channel *chan, const char *data)
Definition: app_signal.c:402
static int waitsignal_exec(struct ast_channel *chan, const char *data)
Definition: app_signal.c:344
static struct signalitem * alloc_signal(const char *sname)
Definition: app_signal.c:145
static const char *const app
Definition: app_signal.c:130
static const char *const app2
Definition: app_signal.c:131
static int dealloc_signal(struct signalitem *s)
Definition: app_signal.c:165
static int send_signal(char *signame, char *payload)
Definition: app_signal.c:304
static struct signalitem * get_signal(char *sname, int addnew)
Definition: app_signal.c:199
static int remove_signal(char *sname)
Definition: app_signal.c:182
static int load_module(void)
Definition: app_signal.c:469
static int unload_module(void)
Definition: app_signal.c:436
AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Channel Signaling Applications")
Asterisk main include file. File version handling, generic pbx functions.
#define ast_free(a)
Definition: astmm.h:180
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:298
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
#define ast_malloc(len)
A wrapper for malloc()
Definition: astmm.h:191
#define ast_log
Definition: astobj2.c:42
General Asterisk PBX channel definitions.
const char * ast_channel_name(const struct ast_channel *chan)
struct ast_channel * ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, int *exception, int *outfd, int *ms)
Waits for activity on a group of channels.
Definition: channel.c:3016
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4274
#define AST_MAX_CONTEXT
Definition: channel.h:135
Generic File Format Support. Should be included by clients of the file handling routines....
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
Application convenience functions, designed to give consistent look and feel to Asterisk apps.
#define AST_APP_ARG(name)
Define an application argument.
#define AST_DECLARE_APP_ARGS(name, arglist)
Declare a structure to hold an application's arguments.
#define AST_STANDARD_APP_ARGS(args, parse)
Performs the 'standard' argument separation process for an application.
#define ast_frfree(fr)
#define ast_debug(level,...)
Log a DEBUG message.
#define ast_verb(level,...)
#define LOG_WARNING
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:52
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:151
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:491
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized.
Definition: linkedlists.h:333
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:410
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
Definition: linkedlists.h:615
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
Definition: linkedlists.h:529
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:557
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:718
#define ast_mutex_init(pmutex)
Definition: lock.h:190
#define ast_mutex_unlock(a)
Definition: lock.h:194
#define ast_mutex_destroy(a)
Definition: lock.h:192
#define ast_mutex_lock(a)
Definition: lock.h:193
int errno
Asterisk module definitions.
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx_app.c:392
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:640
Core PBX routines and definitions.
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name.
#define NULL
Definition: resample.c:96
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:65
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
Main Channel structure associated with a channel.
Data structure associated with a single frame of data.
Structure for mutex and tracking information.
Definition: lock.h:139
unsigned int signaled
Definition: app_signal.c:138
char * payload
Definition: app_signal.c:139
struct signalitem::@62 entry
int sig_alert_pipe[2]
Definition: app_signal.c:136
int watchers
Definition: app_signal.c:137
char name[AST_MAX_CONTEXT]
Definition: app_signal.c:135
ast_mutex_t lock
Definition: app_signal.c:134
const char * args
int ast_remaining_ms(struct timeval start, int max_ms)
Calculate remaining milliseconds given a starting timestamp and upper bound.
Definition: utils.c:2281
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159