app_dial: Allow macro/gosub pre-bridge execution to occur on priorities
[asterisk/asterisk.git] / main / pickup.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2013, Digium, Inc.
5  * Copyright (C) 2012, Russell Bryant
6  *
7  * Matt Jordan <mjordan@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Routines implementing call pickup
23  *
24  * \author Matt Jordan <mjordan@digium.com>
25  */
26
27 /*!
28  * \li Call pickup uses the configuration file \ref features.conf
29  * \addtogroup configuration_file Configuration Files
30  */
31
32 /*** MODULEINFO
33         <support_level>core</support_level>
34  ***/
35
36 /*** DOCUMENTATION
37         <managerEvent language="en_US" name="Pickup">
38                 <managerEventInstance class="EVENT_FLAG_CALL">
39                         <synopsis>Raised when a call pickup occurs.</synopsis>
40                         <syntax>
41                                 <channel_snapshot/>
42                                 <channel_snapshot prefix="Target"/>
43                         </syntax>
44                 </managerEventInstance>
45         </managerEvent>
46  ***/
47
48 #include "asterisk.h"
49
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51
52 #include "asterisk/pickup.h"
53 #include "asterisk/channel.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/app.h"
56 #include "asterisk/callerid.h"
57 #include "asterisk/causes.h"
58 #include "asterisk/stasis.h"
59 #include "asterisk/stasis_channels.h"
60 #include "asterisk/features_config.h"
61
62 static struct ast_manager_event_blob *call_pickup_to_ami(struct stasis_message *message);
63
64 STASIS_MESSAGE_TYPE_DEFN(
65         ast_call_pickup_type,
66         .to_ami = call_pickup_to_ami);
67
68
69 /*!
70  * The presence of this datastore on the channel indicates that
71  * someone is attemting to pickup or has picked up the channel.
72  * The purpose is to prevent a race between two channels
73  * attempting to pickup the same channel.
74  */
75 static const struct ast_datastore_info pickup_active = {
76         .type = "pickup-active",
77 };
78
79 int ast_can_pickup(struct ast_channel *chan)
80 {
81         if (!ast_channel_pbx(chan) && !ast_channel_masq(chan) && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
82                 && (ast_channel_state(chan) == AST_STATE_RINGING
83                         || ast_channel_state(chan) == AST_STATE_RING
84                         /*
85                          * Check the down state as well because some SIP devices do not
86                          * give 180 ringing when they can just give 183 session progress
87                          * instead.  Issue 14005.  (Some ISDN switches as well for that
88                          * matter.)
89                          */
90                         || ast_channel_state(chan) == AST_STATE_DOWN)
91                 && !ast_channel_datastore_find(chan, &pickup_active, NULL)) {
92                 return 1;
93         }
94         return 0;
95 }
96
97 static int find_channel_by_group(void *obj, void *arg, void *data, int flags)
98 {
99         struct ast_channel *target = obj; /*!< Potential pickup target */
100         struct ast_channel *chan = arg;   /*!< Channel wanting to pickup call */
101
102         if (chan == target) {
103                 return 0;
104         }
105
106         ast_channel_lock(target);
107         if (ast_can_pickup(target)) {
108                 /* Lock both channels. */
109                 while (ast_channel_trylock(chan)) {
110                         ast_channel_unlock(target);
111                         sched_yield();
112                         ast_channel_lock(target);
113                 }
114
115                 /*
116                  * Both callgroup and namedcallgroup pickup variants are
117                  * matched independently.  Checking for named group match is
118                  * done last since it's a more expensive operation.
119                  */
120                 if ((ast_channel_pickupgroup(chan) & ast_channel_callgroup(target))
121                         || (ast_namedgroups_intersect(ast_channel_named_pickupgroups(chan),
122                                 ast_channel_named_callgroups(target)))) {
123                         struct ao2_container *candidates = data;/*!< Candidate channels found. */
124
125                         /* This is a candidate to pickup */
126                         ao2_link(candidates, target);
127                 }
128                 ast_channel_unlock(chan);
129         }
130         ast_channel_unlock(target);
131
132         return 0;
133 }
134
135 struct ast_channel *ast_pickup_find_by_group(struct ast_channel *chan)
136 {
137         struct ao2_container *candidates;/*!< Candidate channels found to pickup. */
138         struct ast_channel *target;/*!< Potential pickup target */
139
140         candidates = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL);
141         if (!candidates) {
142                 return NULL;
143         }
144
145         /* Find all candidate targets by group. */
146         ast_channel_callback(find_channel_by_group, chan, candidates, 0);
147
148         /* Find the oldest pickup target candidate */
149         target = NULL;
150         for (;;) {
151                 struct ast_channel *candidate;/*!< Potential new older target */
152                 struct ao2_iterator iter;
153
154                 iter = ao2_iterator_init(candidates, 0);
155                 while ((candidate = ao2_iterator_next(&iter))) {
156                         if (!target) {
157                                 /* First target. */
158                                 target = candidate;
159                                 continue;
160                         }
161                         if (ast_tvcmp(ast_channel_creationtime(candidate), ast_channel_creationtime(target)) < 0) {
162                                 /* We have a new target. */
163                                 ast_channel_unref(target);
164                                 target = candidate;
165                                 continue;
166                         }
167                         ast_channel_unref(candidate);
168                 }
169                 ao2_iterator_destroy(&iter);
170                 if (!target) {
171                         /* No candidates found. */
172                         break;
173                 }
174
175                 /* The found channel must be locked and ref'd. */
176                 ast_channel_lock(target);
177
178                 /* Recheck pickup ability */
179                 if (ast_can_pickup(target)) {
180                         /* This is the channel to pickup. */
181                         break;
182                 }
183
184                 /* Someone else picked it up or the call went away. */
185                 ast_channel_unlock(target);
186                 ao2_unlink(candidates, target);
187                 target = ast_channel_unref(target);
188         }
189         ao2_ref(candidates, -1);
190
191         return target;
192 }
193
194 /*!
195  * \brief Pickup a call
196  * \param chan channel that initiated pickup.
197  *
198  * Walk list of channels, checking it is not itself, channel is pbx one,
199  * check that the callgroup for both channels are the same and the channel is ringing.
200  * Answer calling channel, flag channel as answered on queue, masq channels together.
201  */
202 int ast_pickup_call(struct ast_channel *chan)
203 {
204         struct ast_channel *target;/*!< Potential pickup target */
205         int res = -1;
206         RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
207         const char *pickup_sound;
208         const char *fail_sound;
209
210         ast_debug(1, "Pickup attempt by %s\n", ast_channel_name(chan));
211         ast_channel_lock(chan);
212         pickup_cfg = ast_get_chan_features_pickup_config(chan);
213         if (!pickup_cfg) {
214                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration. Unable to play pickup sounds\n");
215         }
216         pickup_sound = ast_strdupa(pickup_cfg ? pickup_cfg->pickupsound : "");
217         fail_sound = ast_strdupa(pickup_cfg ? pickup_cfg->pickupfailsound : "");
218         ast_channel_unlock(chan);
219
220         /* The found channel is already locked. */
221         target = ast_pickup_find_by_group(chan);
222         if (target) {
223                 ast_log(LOG_NOTICE, "Pickup %s attempt by %s\n", ast_channel_name(target), ast_channel_name(chan));
224
225                 res = ast_do_pickup(chan, target);
226                 ast_channel_unlock(target);
227                 if (!res) {
228                         if (!ast_strlen_zero(pickup_sound)) {
229                                 pbx_builtin_setvar_helper(target, "BRIDGE_PLAY_SOUND", pickup_sound);
230                         }
231                 } else {
232                         ast_log(LOG_WARNING, "Pickup %s failed by %s\n", ast_channel_name(target), ast_channel_name(chan));
233                 }
234                 target = ast_channel_unref(target);
235         }
236
237         if (res < 0) {
238                 ast_debug(1, "No call pickup possible... for %s\n", ast_channel_name(chan));
239                 if (!ast_strlen_zero(fail_sound)) {
240                         ast_answer(chan);
241                         ast_stream_and_wait(chan, fail_sound, "");
242                 }
243         }
244
245         return res;
246 }
247
248 static struct ast_manager_event_blob *call_pickup_to_ami(struct stasis_message *message)
249 {
250         struct ast_multi_channel_blob *contents = stasis_message_data(message);
251         struct ast_channel_snapshot *chan;
252         struct ast_channel_snapshot *target;
253         struct ast_manager_event_blob *res;
254
255         RAII_VAR(struct ast_str *, channel_str, NULL, ast_free);
256         RAII_VAR(struct ast_str *, target_str, NULL, ast_free);
257
258         chan = ast_multi_channel_blob_get_channel(contents, "channel");
259         target = ast_multi_channel_blob_get_channel(contents, "target");
260
261         ast_assert(chan != NULL && target != NULL);
262
263         if (!(channel_str = ast_manager_build_channel_state_string(chan))) {
264                 return NULL;
265         }
266
267         if (!(target_str = ast_manager_build_channel_state_string_prefix(target, "Target"))) {
268                 return NULL;
269         }
270
271         res = ast_manager_event_blob_create(EVENT_FLAG_CALL, "Pickup",
272                 "%s"
273                 "%s",
274                 ast_str_buffer(channel_str),
275                 ast_str_buffer(target_str));
276
277         return res;
278 }
279
280 static int send_call_pickup_stasis_message(struct ast_channel *picking_up, struct ast_channel_snapshot *chan, struct ast_channel_snapshot *target)
281 {
282         RAII_VAR(struct ast_multi_channel_blob *, pickup_payload, NULL, ao2_cleanup);
283         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
284
285         if (!(pickup_payload = ast_multi_channel_blob_create(ast_json_null()))) {
286                 return -1;
287         }
288
289         ast_multi_channel_blob_add_channel(pickup_payload, "channel", chan);
290         ast_multi_channel_blob_add_channel(pickup_payload, "target", target);
291
292         if (!(msg = stasis_message_create(ast_call_pickup_type(), pickup_payload))) {
293                 return -1;
294         }
295
296         stasis_publish(ast_channel_topic(picking_up), msg);
297         return 0;
298 }
299
300 int ast_do_pickup(struct ast_channel *chan, struct ast_channel *target)
301 {
302         struct ast_party_connected_line connected_caller;
303         struct ast_datastore *ds_pickup;
304         const char *chan_name;/*!< A masquerade changes channel names. */
305         const char *target_name;/*!< A masquerade changes channel names. */
306         int res = -1;
307
308         RAII_VAR(struct ast_channel_snapshot *, chan_snapshot, NULL, ao2_cleanup);
309         RAII_VAR(struct ast_channel_snapshot *, target_snapshot, NULL, ao2_cleanup);
310
311         target_name = ast_strdupa(ast_channel_name(target));
312         ast_debug(1, "Call pickup on '%s' by '%s'\n", target_name, ast_channel_name(chan));
313
314         /* Mark the target to block any call pickup race. */
315         ds_pickup = ast_datastore_alloc(&pickup_active, NULL);
316         if (!ds_pickup) {
317                 ast_log(LOG_WARNING,
318                         "Unable to create channel datastore on '%s' for call pickup\n", target_name);
319                 return -1;
320         }
321         ast_channel_datastore_add(target, ds_pickup);
322
323         ast_party_connected_line_init(&connected_caller);
324         ast_party_connected_line_copy(&connected_caller, ast_channel_connected(target));
325         ast_channel_unlock(target);/* The pickup race is avoided so we do not need the lock anymore. */
326         /* Reset any earlier private connected id representation */
327         ast_party_id_reset(&connected_caller.priv);
328
329         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
330         if (ast_channel_connected_line_sub(NULL, chan, &connected_caller, 0) &&
331                 ast_channel_connected_line_macro(NULL, chan, &connected_caller, 0, 0)) {
332                 ast_channel_update_connected_line(chan, &connected_caller, NULL);
333         }
334         ast_party_connected_line_free(&connected_caller);
335
336         ast_channel_lock(chan);
337         chan_name = ast_strdupa(ast_channel_name(chan));
338         ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(chan));
339         ast_channel_unlock(chan);
340         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
341
342         if (ast_answer(chan)) {
343                 ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name);
344                 goto pickup_failed;
345         }
346
347         if (ast_queue_control(chan, AST_CONTROL_ANSWER)) {
348                 ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name);
349                 goto pickup_failed;
350         }
351
352         ast_channel_queue_connected_line_update(chan, &connected_caller, NULL);
353
354         /* setting the HANGUPCAUSE so the ringing channel knows this call was not a missed call */
355         ast_channel_hangupcause_set(chan, AST_CAUSE_ANSWERED_ELSEWHERE);
356
357         ast_channel_lock(chan);
358         chan_snapshot = ast_channel_snapshot_create(chan);
359         ast_channel_unlock(chan);
360         if (!chan_snapshot) {
361                 goto pickup_failed;
362         }
363
364         ast_channel_lock(target);
365         target_snapshot = ast_channel_snapshot_create(target);
366         ast_channel_unlock(target);
367         if (!target_snapshot) {
368                 goto pickup_failed;
369         }
370
371         if (ast_channel_move(target, chan)) {
372                 ast_log(LOG_WARNING, "Unable to complete call pickup of '%s' with '%s'\n",
373                         chan_name, target_name);
374                 goto pickup_failed;
375         }
376
377         /* target points to the channel that did the pickup at this point, so use that channel's topic instead of chan */
378         send_call_pickup_stasis_message(target, chan_snapshot, target_snapshot);
379
380         res = 0;
381
382 pickup_failed:
383         ast_channel_lock(target);
384         if (!ast_channel_datastore_remove(target, ds_pickup)) {
385                 ast_datastore_free(ds_pickup);
386         }
387         ast_party_connected_line_free(&connected_caller);
388
389         return res;
390 }
391
392 /*!
393  * \internal
394  * \brief Clean up resources on Asterisk shutdown
395  */
396 static void pickup_shutdown(void)
397 {
398         STASIS_MESSAGE_TYPE_CLEANUP(ast_call_pickup_type);
399 }
400
401 int ast_pickup_init(void)
402 {
403         STASIS_MESSAGE_TYPE_INIT(ast_call_pickup_type);
404         ast_register_atexit(pickup_shutdown);
405
406         return 0;
407 }