features: call pickup stasis refactoring
[asterisk/asterisk.git] / res / res_parking.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Jonathan Rose <jrose@digium.com>
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 Call Parking Resource
22  *
23  * \author Jonathan Rose <jrose@digium.com>
24  */
25
26 /*** MODULEINFO
27         <depend>bridge_holding</depend>
28         <support_level>core</support_level>
29  ***/
30
31 /*** DOCUMENTATION
32         <configInfo name="res_parking" language="en_US">
33                 <configFile name="res_parking.conf">
34                         <configObject name="globals">
35                                 <synopsis>Options that apply to every parking lot</synopsis>
36                         </configObject>
37                         <configObject name="parking_lot">
38                                 <synopsis>Defined parking lots for res_parking to use to park calls on</synopsis>
39                                 <configOption name="context" default="parkedcalls">
40                                         <synopsis>The name of the context where calls are parked and picked up from.</synopsis>
41                                         <description><para>This option is only used if parkext is set.</para></description>
42                                 </configOption>
43                                 <configOption name="parkext">
44                                         <synopsis>Extension to park calls to this parking lot.</synopsis>
45                                         <description><para>If this option is used, this extension will automatically be created to place calls into
46                         parking lots. In addition, if parkext_exclusive is set for this parking lot, the name of the parking lot
47                         will be included in the application's arguments so that it only parks to this parking lot. The extension
48                         will be created in <literal>context</literal>. Using this option also creates extensions for retrieving
49                         parked calls from the parking spaces in the same context.</para></description>
50                                 </configOption>
51                                 <configOption name="parkext_exclusive" default="no">
52                                         <synopsis>If yes, the extension registered as parkext will park exclusively to this parking lot.</synopsis>
53                                 </configOption>
54                                 <configOption name="parkpos" default="701-750">
55                                         <synopsis>Numerical range of parking spaces which can be used to retrieve parked calls.</synopsis>
56                                         <description><para>If parkext is set, these extensions will automatically be mapped in <literal>context</literal>
57                                                 in order to pick up calls parked to these parking spaces.</para></description>
58                                 </configOption>
59                                 <configOption name="parkinghints" default="no">
60                                         <synopsis>If yes, this parking lot will add hints automatically for parking spaces.</synopsis>
61                                 </configOption>
62                                 <configOption name="parkingtime" default="45">
63                                         <synopsis>Amount of time a call will remain parked before giving up (in seconds).</synopsis>
64                                 </configOption>
65                                 <configOption name="parkedmusicclass">
66                                         <synopsis>Which music class to use for parked calls. They will use the default if unspecified.</synopsis>
67                                 </configOption>
68                                 <configOption name="comebacktoorigin" default="yes">
69                                         <synopsis>Determines what should be done with the parked channel if no one picks it up before it times out.</synopsis>
70                                         <description><para>Valid Options:</para>
71                                                 <enumlist>
72                                                         <enum name="yes">
73                                                                 <para>Automatically have the parked channel dial the device that parked the call with dial
74                                                                         timeout set by the <literal>parkingtime</literal> option. When the call times out an extension
75                                                                         to dial the PARKER will automatically be created in the <literal>park-dial</literal> context with
76                                                                         an extension of the flattened parker device name. If the call is not answered, the parked channel
77                                                                         that is timing out will continue in the dial plan at that point if there are more priorities in
78                                                                         the extension (which won't be the case unless the dialplan deliberately includes such priorities
79                                                                         in the <literal>park-dial</literal> context through pattern matching or deliberately written
80                                                                         flattened peer extensions).</para>
81                                                         </enum>
82                                                         <enum name="no">
83                                                                 <para>Place the call into the PBX at <literal>comebackcontext</literal> instead. The extension will
84                                                                         still be set as the flattened peer name. If an extension the flattened peer name isn't available
85                                                                         then it will fall back to the <literal>s</literal> extension. If that also is unavailable it will
86                                                                         attempt to fall back to <literal>s@default</literal>. The normal dial extension will still be
87                                                                         created in the <literal>park-dial</literal> context with the extension also being the flattened
88                                                                         peer name.</para>
89                                                         </enum>
90                                                 </enumlist>
91                                                 <note><para>Flattened Peer Names - Extensions can not include slash characters since those are used for pattern
92                                                         matching. When a peer name is flattened, slashes become underscores. For example if the parker of a call
93                                                         is called <literal>SIP/0004F2040001</literal> then flattened peer name and therefor the extensions created
94                                                         and used on timeouts will be <literal>SIP_0004F204001</literal>.</para></note>
95                                                 <note><para>When parking times out and the channel returns to the dial plan, the following variables are set:
96                                                 </para></note>
97                                                 <variablelist>
98                                                         <variable name="PARKINGSLOT">
99                                                                 <para>extension that the call was parked in prior to timing out.</para>
100                                                         </variable>
101                                                         <variable name="PARKEDLOT">
102                                                                 <para>name of the lot that the call was parked in prior to timing out.</para>
103                                                         </variable>
104                                                         <variable name="PARKER">
105                                                                 <para>The device that parked the call</para>
106                                                         </variable>
107                                                 </variablelist>
108                                         </description>
109                                 </configOption>
110                                 <configOption name="comebackdialtime" default="30">
111                                         <synopsis>Timeout for the Dial extension created to call back the parker when a parked call times out.</synopsis>
112                                 </configOption>
113                                 <configOption name="comebackcontext" default="parkedcallstimeout">
114                                         <synopsis>Context where parked calls will enter the PBX on timeout when comebacktoorigin=no</synopsis>
115                                         <description><para>The extension the call enters will prioritize the flattened peer name in this context.
116                                                 If the flattened peer name extension is unavailable, then the 's' extension in this context will be
117                                                 used. If that also is unavailable, the 's' extension in the 'default' context will be used.</para>
118                                         </description>
119                                 </configOption>
120                                 <configOption name="courtesytone">
121                                         <synopsis>If the name of a sound file is provided, use this as the courtesy tone</synopsis>
122                                         <description><para>By default, this tone is only played to the caller of a parked call. Who receives the tone
123                                                 can be changed using the <literal>parkedplay</literal> option.</para>
124                                         </description>
125                                 </configOption>
126                                 <configOption name="parkedplay" default="caller">
127                                         <synopsis>Who we should play the courtesytone to on the pickup of a parked call from this lot</synopsis>
128                                         <description>
129                                                 <enumlist>
130                                                         <enum name="no"><para>Apply to neither side.</para></enum>
131                                                         <enum name="caller"><para>Apply to only to the caller picking up the parked call.</para></enum>
132                                                         <enum name="callee"><para>Apply to only to the parked call being picked up.</para></enum>
133                                                         <enum name="both"><para>Apply to both the caller and the callee.</para></enum>
134                                                 </enumlist>
135                                                 <note><para>If courtesy tone is not specified then this option will be ignored.</para></note>
136                                         </description>
137                                 </configOption>
138                                 <configOption name="parkedcalltransfers" default="no">
139                                         <synopsis>Apply the DTMF transfer features to the caller and/or callee when parked calls are picked up.</synopsis>
140                                         <description>
141                                                 <xi:include xpointer="xpointer(/docs/configInfo[@name='res_parking']/configFile[@name='res_parking.conf']/configObject[@name='parking_lot']/configOption[@name='parkedplay']/description/enumlist)" />
142                                         </description>
143                                 </configOption>
144                                 <configOption name="parkedcallreparking" default="no">
145                                         <synopsis>Apply the DTMF parking feature to the caller and/or callee when parked calls are picked up.</synopsis>
146                                         <description>
147                                                 <xi:include xpointer="xpointer(/docs/configInfo[@name='res_parking']/configFile[@name='res_parking.conf']/configObject[@name='parking_lot']/configOption[@name='parkedplay']/description/enumlist)" />
148                                         </description>
149                                 </configOption>
150                                 <configOption name="parkedcallhangup" default="no">
151                                         <synopsis>Apply the DTMF Hangup feature to the caller and/or callee when parked calls are picked up.</synopsis>
152                                         <description>
153                                                 <xi:include xpointer="xpointer(/docs/configInfo[@name='res_parking']/configFile[@name='res_parking.conf']/configObject[@name='parking_lot']/configOption[@name='parkedplay']/description/enumlist)" />
154                                         </description>
155                                 </configOption>
156                                 <configOption name="parkedcallrecording" default="no">
157                                         <synopsis>Apply the DTMF recording features to the caller and/or callee when parked calls are picked up</synopsis>
158                                         <description>
159                                                 <xi:include xpointer="xpointer(/docs/configInfo[@name='res_parking']/configFile[@name='res_parking.conf']/configObject[@name='parking_lot']/configOption[@name='parkedplay']/description/enumlist)" />
160                                         </description>
161                                 </configOption>
162                                 <configOption name="findslot" default="first">
163                                         <synopsis>Rule to use when trying to figure out which parking space a call should be parked with.</synopsis>
164                                         <description>
165                                                 <enumlist>
166                                                         <enum name="first"><para>Always try to place in the lowest available space in the parking lot</para></enum>
167                                                         <enum name="next"><para>Track the last parking space used and always attempt to use the one immediately after.
168                                                         </para></enum>
169                                                 </enumlist>
170                                         </description>
171                                 </configOption>
172                                 <configOption name="courtesytone">
173                                         <synopsis>If set, the sound set will be played to whomever is set by parkedplay</synopsis>
174                                 </configOption>
175                         </configObject>
176                 </configFile>
177         </configInfo>
178  ***/
179
180 #include "asterisk.h"
181
182 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
183
184 #include "parking/res_parking.h"
185 #include "asterisk/config.h"
186 #include "asterisk/config_options.h"
187 #include "asterisk/event.h"
188 #include "asterisk/utils.h"
189 #include "asterisk/module.h"
190 #include "asterisk/cli.h"
191 #include "asterisk/astobj2.h"
192 #include "asterisk/features.h"
193 #include "asterisk/manager.h"
194 #include "asterisk/pbx.h"
195
196 #define PARKED_CALL_APPLICATION "ParkedCall"
197 #define PARK_AND_ANNOUNCE_APPLICATION "ParkAndAnnounce"
198
199 /* TODO Add unit tests for parking */
200
201 static int parking_lot_sort_fn(const void *obj_left, const void *obj_right, int flags)
202 {
203         const struct parking_lot *left = obj_left;
204         const struct parking_lot *right = obj_right;
205         const char *right_key = obj_right;
206         int cmp;
207
208         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
209         default:
210         case OBJ_POINTER:
211                 right_key = right->name;
212                 /* Fall through */
213         case OBJ_KEY:
214                 cmp = strcmp(left->name, right_key);
215                 break;
216         case OBJ_PARTIAL_KEY:
217                 cmp = strncmp(left->name, right_key, strlen(right_key));
218         }
219         return cmp;
220 }
221
222 /*! All parking lots that are currently alive in some fashion can be obtained from here */
223 static struct ao2_container *parking_lot_container;
224
225 static void *parking_config_alloc(void);
226
227 static void *parking_lot_cfg_alloc(const char *cat);
228 static void *named_item_find(struct ao2_container *container, const char *name); /* XXX This is really just a generic string find. Move to astobj2.c? */
229
230 static int config_parking_preapply(void);
231 static void link_configured_disable_marked_lots(void);
232
233 struct parking_global_config {
234         /* TODO Implement dynamic parking lots. Entirely. */
235         int parkeddynamic;
236 };
237
238 struct parking_config {
239         struct parking_global_config *global;
240         struct ao2_container *parking_lots;
241 };
242
243 static struct aco_type global_option = {
244         .type = ACO_GLOBAL,
245         .name = "globals",
246         .item_offset = offsetof(struct parking_config, global),
247         .category_match = ACO_WHITELIST,
248         .category = "^general$",
249 };
250
251 struct aco_type *global_options[] = ACO_TYPES(&global_option);
252
253 static struct aco_type parking_lot_type = {
254         .type = ACO_ITEM,
255         .name = "parking_lot",
256         .category_match = ACO_BLACKLIST,
257         .category = "^(general)$",
258         .item_alloc = parking_lot_cfg_alloc,
259         .item_find = named_item_find,
260         .item_offset = offsetof(struct parking_config, parking_lots),
261 };
262
263 struct aco_type *parking_lot_types[] = ACO_TYPES(&parking_lot_type);
264
265 struct aco_file parking_lot_conf = {
266         .filename = "res_parking.conf",
267         .types = ACO_TYPES(&global_option, &parking_lot_type),
268 };
269
270 static AO2_GLOBAL_OBJ_STATIC(globals);
271
272 CONFIG_INFO_STANDARD(cfg_info, globals, parking_config_alloc,
273         .files = ACO_FILES(&parking_lot_conf),
274         .pre_apply_config = config_parking_preapply,
275         .post_apply_config = link_configured_disable_marked_lots,
276 );
277
278 static int parking_lot_cfg_hash_fn(const void *obj, const int flags)
279 {
280         const struct parking_lot_cfg *entry;
281         const char *key;
282
283         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
284         case OBJ_KEY:
285                 key = obj;
286                 return ast_str_hash(key);
287         case OBJ_PARTIAL_KEY:
288                 ast_assert(0);
289                 return 0;
290         default:
291                 entry = obj;
292                 return ast_str_hash(entry->name);
293         }
294 }
295
296 static int parking_lot_cfg_cmp_fn(void *obj, void *arg, const int flags)
297 {
298         struct parking_lot_cfg *entry1 = obj;
299
300         char *key;
301         size_t key_size;
302         struct parking_lot_cfg *entry2;
303
304         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
305         case OBJ_KEY:
306                 key = arg;
307                 return (!strcmp(entry1->name, key)) ? CMP_MATCH : 0;
308         case OBJ_PARTIAL_KEY:
309                 key = arg;
310                 key_size = strlen(key);
311                 return (!strncmp(entry1->name, key, key_size)) ? CMP_MATCH : 0;
312         case OBJ_POINTER:
313                 entry2 = arg;
314                 return (!strcmp(entry1->name, entry2->name)) ? CMP_MATCH : 0;
315         default:
316                 return CMP_STOP;
317         }
318 }
319
320 /*! \brief destructor for parking_config */
321 static void parking_config_destructor(void *obj)
322 {
323         struct parking_config *cfg = obj;
324         ao2_cleanup(cfg->parking_lots);
325         ao2_cleanup(cfg->global);
326 }
327
328 /*! \brief destructor for parking_global_config */
329 static void parking_global_config_destructor(void *obj)
330 {
331         /* For now, do nothing. */
332 }
333
334 /*! \brief allocator callback for parking_config. Notice it returns void * since it is only used by the backend config code */
335 static void *parking_config_alloc(void)
336 {
337         RAII_VAR(struct parking_config *, cfg, NULL, ao2_cleanup);
338
339         if (!(cfg = ao2_alloc(sizeof(*cfg), parking_config_destructor))) {
340                 return NULL;
341         }
342
343         if (!(cfg->parking_lots = ao2_container_alloc(37, parking_lot_cfg_hash_fn, parking_lot_cfg_cmp_fn))) {
344                 return NULL;
345         }
346
347         if (!(cfg->global = ao2_alloc(sizeof(*cfg->global), parking_global_config_destructor))) {
348                 return NULL;
349         }
350
351         /* Bump the ref count since RAII_VAR is going to eat one */
352         ao2_ref(cfg, +1);
353         return cfg;
354 }
355
356 void parking_lot_remove_if_unused(struct parking_lot *lot)
357 {
358
359         if (lot->mode != PARKINGLOT_DISABLED) {
360                 return;
361         }
362
363
364         if (!ao2_container_count(lot->parked_users)) {
365                 ao2_unlink(parking_lot_container, lot);
366         }
367 }
368
369 static void parking_lot_disable(struct parking_lot *lot)
370 {
371         lot->mode = PARKINGLOT_DISABLED;
372         parking_lot_remove_if_unused(lot);
373 }
374
375 /*! \brief Destroy a parking lot cfg object */
376 static void parking_lot_cfg_destructor(void *obj)
377 {
378         struct parking_lot_cfg *lot_cfg = obj;
379         parking_lot_cfg_remove_extensions(lot_cfg);
380         ast_string_field_free_memory(lot_cfg);
381 }
382
383 /* The arg just needs to have the parking space with it */
384 static int parked_user_cmp_fn(void *obj, void *arg, int flags)
385 {
386         int *search_space = arg;
387         struct parked_user *user = obj;
388         int object_space = user->parking_space;
389
390         if (*search_space == object_space) {
391                 return CMP_MATCH;
392         }
393         return 0;
394 }
395
396 static int parked_user_sort_fn(const void *obj_left, const void *obj_right, int flags)
397 {
398         const struct parked_user *left = obj_left;
399         const struct parked_user *right = obj_right;
400
401         return left->parking_space - right->parking_space;
402 }
403
404 /*!
405  * \brief create a parking lot structure
406  * \param cat name given to the parking lot
407  * \retval NULL failure
408  * \retval non-NULL successfully allocated parking lot
409  */
410 static void *parking_lot_cfg_alloc(const char *cat)
411 {
412         struct parking_lot_cfg *lot_cfg;
413
414         lot_cfg = ao2_alloc(sizeof(*lot_cfg), parking_lot_cfg_destructor);
415         if (!lot_cfg) {
416                 return NULL;
417         }
418
419         if (ast_string_field_init(lot_cfg, 32)) {
420                 ao2_cleanup(lot_cfg);
421                 return NULL;
422         }
423
424         ast_string_field_set(lot_cfg, name, cat);
425
426         return lot_cfg;
427 }
428
429 /*!
430  * XXX This is actually incredibly generic and might be better placed in something like astobj2 if there isn't already an equivalent
431  * \brief find an item in a container by its name
432  *
433  * \param container ao2container where we want the item from
434  * \param key name of the item wanted to be found
435  *
436  * \retval pointer to the parking lot if available. NULL if not found.
437  */
438 static void *named_item_find(struct ao2_container *container, const char *name)
439 {
440         return ao2_find(container, name, OBJ_KEY);
441 }
442
443 /*!
444  * \brief Custom field handler for parking positions
445  */
446 static int option_handler_parkpos(const struct aco_option *opt, struct ast_variable *var, void *obj)
447 {
448         struct parking_lot_cfg *lot_cfg = obj;
449         int low;
450         int high;
451
452         if (sscanf(var->value, "%30d-%30d", &low, &high) != 2) {
453                 ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers\n");
454         } else if (high < low || low <= 0 || high <= 0) {
455                 ast_log(LOG_WARNING, "Format for parking positions is a-b, where a <= b\n");
456         } else {
457                 lot_cfg->parking_start = low;
458                 lot_cfg->parking_stop = high;
459                 return 0;
460         }
461         return -1;
462 }
463
464 /*!
465  * \brief Custom field handler for the findslot option
466  */
467 static int option_handler_findslot(const struct aco_option *opt, struct ast_variable *var, void *obj)
468 {
469         struct parking_lot_cfg *lot_cfg = obj;
470
471         if (!strcmp(var->value, "first")) {
472                 lot_cfg->parkfindnext = 0;
473         } else if (!strcmp(var->value, "next")) {
474                 lot_cfg->parkfindnext = 1;
475         } else {
476                 ast_log(LOG_WARNING, "value '%s' is not valid for findslot option.\n", var->value);
477                 return -1;
478         }
479
480         return 0;
481 }
482
483 /*!
484  * \brief Maps string values for option_handler_parkedfeature to their ENUM values
485  */
486 static int parking_feature_flag_cfg(int *param, const char *var)
487 {
488         if (ast_false(var)) {
489                 *param = 0;
490         } else if (!strcasecmp(var, "both")) {
491                 *param = AST_FEATURE_FLAG_BYBOTH;
492         } else if (!strcasecmp(var, "caller")) {
493                 *param = AST_FEATURE_FLAG_BYCALLER;
494         } else if (!strcasecmp(var, "callee")) {
495                 *param = AST_FEATURE_FLAG_BYCALLEE;
496         } else {
497                 return -1;
498         }
499
500         return 0;
501 }
502
503 /*!
504  * \brief Custom field handler for feature mapping on parked call pickup options
505  */
506 static int option_handler_parkedfeature(const struct aco_option *opt, struct ast_variable *var, void *obj)
507 {
508         struct parking_lot_cfg *cfg = obj;
509         enum parked_call_feature_options option = aco_option_get_flags(opt);
510         int *parameter = NULL;
511
512         switch (option) {
513         case OPT_PARKEDPLAY:
514                 parameter = &cfg->parkedplay;
515                 break;
516         case OPT_PARKEDTRANSFERS:
517                 parameter = &cfg->parkedcalltransfers;
518                 break;
519         case OPT_PARKEDREPARKING:
520                 parameter = &cfg->parkedcallreparking;
521                 break;
522         case OPT_PARKEDHANGUP:
523                 parameter = &cfg->parkedcallhangup;
524                 break;
525         case OPT_PARKEDRECORDING:
526                 parameter = &cfg->parkedcallrecording;
527                 break;
528         }
529
530         ast_assert(parameter != NULL);
531         if (!parameter || parking_feature_flag_cfg(parameter, var->value)) {
532                 return -1;
533         }
534
535         return 0;
536 }
537
538 struct ao2_container *get_parking_lot_container(void)
539 {
540         return parking_lot_container;
541 }
542
543 struct parking_lot *parking_lot_find_by_name(const char *lot_name)
544 {
545         struct parking_lot *lot = named_item_find(parking_lot_container, lot_name);
546         return lot;
547 }
548
549 const char *find_channel_parking_lot_name(struct ast_channel *chan)
550 {
551         const char *name;
552
553         /* The channel variable overrides everything */
554         name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
555         if (ast_strlen_zero(name) && !ast_strlen_zero(ast_channel_parkinglot(chan))) {
556                 /* Use the channel's parking lot. */
557                 name = ast_channel_parkinglot(chan);
558         }
559
560         /* If the name couldn't be pulled from that either, use the default parking lot name. */
561         if (ast_strlen_zero(name)) {
562                 name = DEFAULT_PARKING_LOT;
563         }
564
565         return name;
566 }
567
568 static void parking_lot_destructor(void *obj)
569 {
570         struct parking_lot *lot = obj;
571
572         if (lot->parking_bridge) {
573                 ast_bridge_destroy(lot->parking_bridge);
574         }
575         ao2_cleanup(lot->parked_users);
576         ao2_cleanup(lot->cfg);
577         ast_string_field_free_memory(lot);
578 }
579
580 static struct parking_lot *alloc_new_parking_lot(struct parking_lot_cfg *lot_cfg)
581 {
582         struct parking_lot *lot;
583         if (!(lot = ao2_alloc(sizeof(*lot), parking_lot_destructor))) {
584                 return NULL;
585         }
586
587         if (ast_string_field_init(lot, 32)) {
588                 return NULL;
589         }
590
591         /* Create parked user ordered list */
592         lot->parked_users = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_RWLOCK,
593                 AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT,
594                 parked_user_sort_fn,
595                 parked_user_cmp_fn);
596
597         if (!lot->parked_users) {
598                 ao2_cleanup(lot);
599                 return NULL;
600         }
601
602         ast_string_field_set(lot, name, lot_cfg->name);
603         return lot;
604 }
605
606 void parking_lot_cfg_remove_extensions(struct parking_lot_cfg *lot_cfg)
607 {
608         if (!ast_strlen_zero(lot_cfg->registrar)) {
609                 /* Although the function is called ast_context_destroy, the use of this funtion is
610                  * intended only to remove extensions, hints, etc registered by the parking lot's registrar.
611                  * It won't actually destroy the context unless that context is empty afterwards and it is
612                  * unreferenced.
613                  */
614                 ast_context_destroy(NULL, lot_cfg->registrar);
615         }
616 }
617
618 static void remove_all_configured_parking_lot_extensions(void)
619 {
620         RAII_VAR(struct parking_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
621         struct parking_lot_cfg *lot_cfg;
622         struct ao2_iterator iter;
623
624         if (!cfg) {
625                 return;
626         }
627
628         for (iter = ao2_iterator_init(cfg->parking_lots, 0); (lot_cfg = ao2_iterator_next(&iter)); ao2_ref(lot_cfg, -1)) {
629                 parking_lot_cfg_remove_extensions(lot_cfg);
630         }
631
632         ast_context_destroy(NULL, BASE_REGISTRAR);
633
634         ao2_iterator_destroy(&iter);
635 }
636
637 /*!
638  * \internal
639  * \since 12
640  * \brief Create an extension using ast_add_extension2_nolock. This function automatically allocates a duplicate
641  *        of the data string so that whatever calls it doesn't have to deal with freeing it if the ast_add_extension2_nolock
642  *        fails.
643  *
644  * \param context a write locked ast_context. Make certain it is write locked prior to calling this function
645  * \param replace whether the extension should replace existing extensions
646  * \param extension name of the extension desired
647  * \param priority priority of the extension we are registering
648  * \param application name of the application being used for the extension
649  * \param data application arguments
650  * \param registrar name of the registrar you should use for the extension.
651  *        Make sure this string doesn't go anywhere while there are still extensions using it.
652  */
653 static int parking_add_extension(struct ast_context *context, int replace, const char *extension,
654         int priority, const char *application, const char *data, const char *registrar)
655 {
656         char *data_duplicate = ast_strdup(data);
657
658         if (!data_duplicate) {
659                 return -1;
660         }
661
662         if (ast_add_extension2_nolock(context, replace, extension, priority, NULL, NULL,
663                         application, data_duplicate, ast_free_ptr, registrar)) {
664                 ast_free(data_duplicate);
665                 return -1;
666         }
667
668         return 0;
669 }
670
671 static int extension_is_compatible(struct parking_lot_cfg *lot_cfg, const char *app_type, struct ast_exten *extension)
672 {
673         RAII_VAR(struct parking_lot_cfg *, owner, NULL, ao2_cleanup);
674         const char *extension_registrar = ast_get_extension_registrar(extension);
675         const char *extension_context = ast_get_context_name(ast_get_extension_context(extension));
676         const char *extension_name = ast_get_extension_name(extension);
677         const char *extension_application = ast_get_extension_app(extension);
678
679         ast_assert(extension_registrar && extension_context && extension_name && extension_application);
680
681         if (strcmp(extension_registrar, BASE_REGISTRAR)) {
682                 ast_log(LOG_ERROR, "Parking lot '%s' -- Needs an extension '%s@%s', but that extension is already owned by %s.\n",
683                         lot_cfg->name, extension_name, extension_context, extension_registrar);
684                 return 0;
685         }
686
687         if (strcmp(extension_application, app_type)) {
688                 ast_log(LOG_ERROR, "Parking lot '%s' -- Needs an extension '%s@%s' with a non-exclusive %s application, "
689                         "but a/an %s application is already registered to that extension by %s.\n",
690                         lot_cfg->name, extension_name, extension_context, app_type,
691                         extension_application, BASE_REGISTRAR);
692                 return 0;
693         }
694
695         ast_debug(3, "Parking lot '%s' -- extension '%s@%s' with application %s is compatible.\n",
696                   lot_cfg->name, extension_name, extension_context, app_type);
697         return 1;
698 }
699
700 int parking_lot_cfg_create_extensions(struct parking_lot_cfg *lot_cfg)
701 {
702         int parkingspace;
703         struct ast_exten *existing_exten;
704         struct ast_context *lot_context;
705         struct pbx_find_info find_info = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
706         const char *registrar_pointer;
707
708         if (ast_strlen_zero(lot_cfg->parkext)) {
709                 return 0;
710         }
711
712         if (lot_cfg->parkext_exclusive) {
713                 ast_string_field_build(lot_cfg, registrar, "%s/%s", BASE_REGISTRAR, lot_cfg->name);
714                 registrar_pointer = lot_cfg->registrar;
715         } else {
716                 registrar_pointer = BASE_REGISTRAR;
717         }
718
719         /* We need the contexts list locked to safely be able to both read and lock the specific context within */
720         if (ast_wrlock_contexts()) {
721                 ast_log(LOG_ERROR, "Failed to lock the contexts list.\n");
722                 return -1;
723         }
724
725         if (!(lot_context = ast_context_find_or_create(NULL, NULL, lot_cfg->parking_con, registrar_pointer))) {
726                 ast_log(LOG_ERROR, "Parking lot '%s' -- Needs a context '%s' which does not exist and Asterisk was unable to create\n",
727                         lot_cfg->name, lot_cfg->parking_con);
728                 if (ast_unlock_contexts()) {
729                         ast_assert(0);
730                 }
731                 return -1;
732         }
733
734         /* Once we know what context we will be modifying, we need to write lock it because we will be reading extensions
735          * and we don't want something else to destroy them while we are looking at them.
736          */
737         if (ast_wrlock_context(lot_context)) {
738                 ast_log(LOG_ERROR, "failed to obtain write lock on context\n");
739                 return -1;
740         }
741
742         if (ast_unlock_contexts()) {
743                 ast_assert(0);
744         }
745
746         /* Handle generation/confirmation for the Park extension */
747         if ((existing_exten = pbx_find_extension(NULL, NULL, &find_info, lot_cfg->parking_con, lot_cfg->parkext, 1, NULL, NULL, E_MATCH))) {
748                 if (lot_cfg->parkext_exclusive || !extension_is_compatible(lot_cfg, PARK_APPLICATION, existing_exten)) {
749                         ast_unlock_context(lot_context);
750                         return -1;
751                 }
752         } else if (parking_add_extension(lot_context, 0, lot_cfg->parkext, 1, PARK_APPLICATION,
753                    lot_cfg->parkext_exclusive ? lot_cfg->name : "", registrar_pointer)) {
754                 ast_log(LOG_ERROR, "Parking lot '%s' -- Failed to add %s extension '%s@%s' to the PBX.\n",
755                         lot_cfg->name, PARK_APPLICATION, lot_cfg->parkext, lot_cfg->parking_con);
756                 ast_unlock_context(lot_context);
757                 return -1;
758         }
759
760         /* Handle generation/confirmation for the ParkedCall extensions and hints */
761         for (parkingspace = lot_cfg->parking_start; parkingspace <= lot_cfg->parking_stop; parkingspace++) {
762                 char space[AST_MAX_EXTENSION];
763                 RAII_VAR(struct ast_str *, arguments_string, NULL, ast_free);
764                 find_info.stacklen = 0; /* reset for pbx_find_exten */
765
766                 snprintf(space, sizeof(space), "%d", parkingspace);
767
768                 /* Unlike the Park extensions, ParkedCall extensions and their hints may never be shared for any reason. */
769                 if ((existing_exten = pbx_find_extension(NULL, NULL, &find_info, lot_cfg->parking_con, space, 1, NULL, NULL, E_MATCH))) {
770                         ast_unlock_context(lot_context);
771                         return -1;
772                 }
773
774                 arguments_string = ast_str_create(32);
775                 if (!arguments_string) {
776                         ast_unlock_context(lot_context);
777                         return -1;
778                 }
779
780                 ast_str_set(&arguments_string, 0, "%s,%s", lot_cfg->name, space);
781                 if (parking_add_extension(lot_context, 0, space, 1, PARKED_CALL_APPLICATION,
782                     ast_str_buffer(arguments_string), registrar_pointer)) {
783                         ast_log(LOG_ERROR, "Parking lot '%s' -- Failed to add %s extension '%s@%s' to the PBX.\n",
784                                 lot_cfg->name, PARKED_CALL_APPLICATION, space, lot_cfg->parking_con);
785                         ast_unlock_context(lot_context);
786                         return -1;
787                 }
788
789                 find_info.stacklen = 0; /* reset for pbx_find_exten */
790
791                 if (lot_cfg->parkaddhints) {
792                         char hint_device[AST_MAX_EXTENSION];
793
794                         snprintf(hint_device, sizeof(hint_device), "park:%s@%s", space, lot_cfg->parking_con);
795
796                         if ((existing_exten = pbx_find_extension(NULL, NULL, &find_info, lot_cfg->parking_con, space, PRIORITY_HINT, NULL, NULL, E_MATCH))) {
797                                 ast_log(LOG_ERROR, "Parking lot '%s' -- Needs to add a hint '%s' at '%s@%s' but one already exists owned by %s\n",
798                                 lot_cfg->name, hint_device, space, lot_cfg->parking_con, ast_get_extension_registrar(existing_exten));
799                                         ast_unlock_context(lot_context);
800                                         return -1;
801                         }
802
803                         if (parking_add_extension(lot_context, 0, space, PRIORITY_HINT, hint_device, "", registrar_pointer)) {
804                                 ast_log(LOG_ERROR, "Parking lot '%s' -- Failed to add hint '%s@%s' to the PBX.\n",
805                                         lot_cfg->name, space, lot_cfg->parking_con);
806                                 ast_unlock_context(lot_context);
807                                 return -1;
808                         }
809                 }
810         }
811
812         if (ast_unlock_context(lot_context)) {
813                 ast_assert(0);
814         }
815
816         return 0;
817 }
818
819 struct parking_lot *parking_lot_build_or_update(struct parking_lot_cfg *lot_cfg)
820 {
821         struct parking_lot *lot;
822         struct parking_lot_cfg *replaced_cfg = NULL;
823         int found = 0;
824
825         /* Start by trying to find it. If that works we can skip the rest. */
826         lot = named_item_find(parking_lot_container, lot_cfg->name);
827         if (!lot) {
828                 lot = alloc_new_parking_lot(lot_cfg);
829
830                 /* If we still don't have a lot, we failed to alloc one. */
831                 if (!lot) {
832                         return NULL;
833                 }
834         } else {
835                 found = 1;
836         }
837
838         /* Set the configuration reference. Unref the one currently in the lot if it's there. */
839         if (lot->cfg) {
840                 replaced_cfg = lot->cfg;
841         }
842
843         ao2_ref(lot_cfg, +1);
844         lot->cfg = lot_cfg;
845
846         ao2_cleanup(replaced_cfg);
847
848         /* Set the operating mode to normal since the parking lot has a configuration. */
849         lot->disable_mark = 0;
850         lot->mode = PARKINGLOT_NORMAL;
851
852         if (!found) {
853                 /* Link after configuration is set since a lot without configuration will cause all kinds of trouble. */
854                 ao2_link(parking_lot_container, lot);
855         };
856
857         return lot;
858 }
859
860 static void generate_or_link_lots_to_configs(void)
861 {
862         RAII_VAR(struct parking_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
863         struct parking_lot_cfg *lot_cfg;
864         struct ao2_iterator iter;
865
866         for (iter = ao2_iterator_init(cfg->parking_lots, 0); (lot_cfg = ao2_iterator_next(&iter)); ao2_ref(lot_cfg, -1)) {
867                 RAII_VAR(struct parking_lot *, lot, NULL, ao2_cleanup);
868                 lot = parking_lot_build_or_update(lot_cfg);
869         }
870
871         ao2_iterator_destroy(&iter);
872 }
873
874 /* Preapply */
875
876 static int verify_default_parking_lot(void)
877 {
878         struct parking_config *cfg = aco_pending_config(&cfg_info);
879         RAII_VAR(struct parking_lot_cfg *, lot_cfg, NULL, ao2_cleanup);
880
881         if (!cfg) {
882                 return 0;
883         }
884
885         lot_cfg = ao2_find(cfg->parking_lots, DEFAULT_PARKING_LOT, OBJ_KEY);
886         if (!lot_cfg) {
887                 lot_cfg = parking_lot_cfg_alloc(DEFAULT_PARKING_LOT);
888                 if (!lot_cfg) {
889                         return -1;
890                 }
891                 ast_log(AST_LOG_NOTICE, "Adding %s profile to res_parking\n", DEFAULT_PARKING_LOT);
892                 aco_set_defaults(&parking_lot_type, DEFAULT_PARKING_LOT, lot_cfg);
893                 ast_string_field_set(lot_cfg, parkext, DEFAULT_PARKING_EXTEN);
894                 ao2_link(cfg->parking_lots, lot_cfg);
895         }
896
897         return 0;
898 }
899
900 static void remove_pending_parking_lot_extensions(struct parking_config *cfg_pending)
901 {
902         struct parking_lot_cfg *lot_cfg;
903         struct ao2_iterator iter;
904
905         for (iter = ao2_iterator_init(cfg_pending->parking_lots, 0); (lot_cfg = ao2_iterator_next(&iter)); ao2_ref(lot_cfg, -1)) {
906                 parking_lot_cfg_remove_extensions(lot_cfg);
907         }
908
909         ao2_iterator_destroy(&iter);
910
911         ast_context_destroy(NULL, BASE_REGISTRAR);
912
913 }
914
915 static int configure_parking_extensions(void)
916 {
917         struct parking_config *cfg = aco_pending_config(&cfg_info);
918         struct ao2_iterator iter;
919         RAII_VAR(struct parking_lot_cfg *, lot_cfg, NULL, ao2_cleanup);
920         int res = 0;
921
922         if (!cfg) {
923                 return 0;
924         }
925
926         /* Clear existing extensions */
927         remove_all_configured_parking_lot_extensions();
928
929         /* Attempt to build new extensions for each lot */
930         for (iter = ao2_iterator_init(cfg->parking_lots, 0); (lot_cfg = ao2_iterator_next(&iter)); ao2_ref(lot_cfg, -1)) {
931                 if (parking_lot_cfg_create_extensions(lot_cfg)) {
932                         ao2_cleanup(lot_cfg);
933                         lot_cfg = NULL;
934                         res = -1;
935                         break;
936                 }
937         }
938         ao2_iterator_destroy(&iter);
939
940         if (res) {
941                 remove_pending_parking_lot_extensions(cfg);
942                 ast_log(LOG_ERROR, "Extension registration failed. Previously configured lot extensions were removed and can not be safely restored.\n");
943         }
944
945         return res;
946 }
947
948 static void mark_lots_as_disabled(void)
949 {
950         struct ao2_iterator iter;
951         struct parking_lot *lot;
952
953         for (iter = ao2_iterator_init(parking_lot_container, 0); (lot = ao2_iterator_next(&iter)); ao2_ref(lot, -1)) {
954                 /* We aren't concerned with dynamic lots */
955                 if (lot->mode == PARKINGLOT_DYNAMIC) {
956                         continue;
957                 }
958
959                 lot->disable_mark = 1;
960         }
961
962         ao2_iterator_destroy(&iter);
963 }
964
965 static int config_parking_preapply(void)
966 {
967         mark_lots_as_disabled();
968
969         if (verify_default_parking_lot()) {
970                 return -1;
971         }
972
973         if (configure_parking_extensions()) {
974                 return -1;
975         }
976
977         return 0;
978 }
979
980 static void disable_marked_lots(void)
981 {
982         struct ao2_iterator iter;
983         struct parking_lot *lot;
984
985         for (iter = ao2_iterator_init(parking_lot_container, 0); (lot = ao2_iterator_next(&iter)); ao2_ref(lot, -1)) {
986                 if (lot->disable_mark) {
987                         parking_lot_disable(lot);
988                 }
989         }
990
991         ao2_iterator_destroy(&iter);
992 }
993
994 static void link_configured_disable_marked_lots(void)
995 {
996         generate_or_link_lots_to_configs();
997         disable_marked_lots();
998 }
999
1000 static int load_module(void)
1001 {
1002         if (aco_info_init(&cfg_info)) {
1003                 goto error;
1004         }
1005
1006         parking_lot_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_RWLOCK,
1007                 AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT,
1008                 parking_lot_sort_fn,
1009                 NULL);
1010
1011         if (!parking_lot_container) {
1012                 goto error;
1013         }
1014
1015         /* Global options */
1016
1017         /* Register the per parking lot options. */
1018         aco_option_register(&cfg_info, "parkext", ACO_EXACT, parking_lot_types, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct parking_lot_cfg, parkext));
1019         aco_option_register(&cfg_info, "context", ACO_EXACT, parking_lot_types, "parkedcalls", OPT_STRINGFIELD_T, 0, STRFLDSET(struct parking_lot_cfg, parking_con));
1020         aco_option_register(&cfg_info, "parkingtime", ACO_EXACT, parking_lot_types, "45", OPT_UINT_T, 0, FLDSET(struct parking_lot_cfg, parkingtime));
1021         aco_option_register(&cfg_info, "comebacktoorigin", ACO_EXACT, parking_lot_types, "yes", OPT_BOOL_T, 1, FLDSET(struct parking_lot_cfg, comebacktoorigin));
1022         aco_option_register(&cfg_info, "comebackcontext", ACO_EXACT, parking_lot_types, "parkedcallstimeout", OPT_STRINGFIELD_T, 0, STRFLDSET(struct parking_lot_cfg, comebackcontext));
1023         aco_option_register(&cfg_info, "comebackdialtime", ACO_EXACT, parking_lot_types, "30", OPT_UINT_T, 0, FLDSET(struct parking_lot_cfg, comebackdialtime));
1024         aco_option_register(&cfg_info, "parkedmusicclass", ACO_EXACT, parking_lot_types, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct parking_lot_cfg, mohclass));
1025         aco_option_register(&cfg_info, "parkext_exclusive", ACO_EXACT, parking_lot_types, "no", OPT_BOOL_T, 1, FLDSET(struct parking_lot_cfg, parkext_exclusive));
1026         aco_option_register(&cfg_info, "parkinghints", ACO_EXACT, parking_lot_types, "no", OPT_BOOL_T, 1, FLDSET(struct parking_lot_cfg, parkaddhints));
1027         aco_option_register(&cfg_info, "courtesytone", ACO_EXACT, parking_lot_types, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct parking_lot_cfg, courtesytone));
1028
1029         /* More complicated parking lot options that require special handling */
1030         aco_option_register_custom(&cfg_info, "parkpos", ACO_EXACT, parking_lot_types, "701-750", option_handler_parkpos, 0);
1031         aco_option_register_custom(&cfg_info, "findslot", ACO_EXACT, parking_lot_types, "first", option_handler_findslot, 0);
1032         aco_option_register_custom(&cfg_info, "parkedplay", ACO_EXACT, parking_lot_types, "caller", option_handler_parkedfeature, OPT_PARKEDPLAY);
1033         aco_option_register_custom(&cfg_info, "parkedcalltransfers", ACO_EXACT, parking_lot_types, "no", option_handler_parkedfeature, OPT_PARKEDTRANSFERS);
1034         aco_option_register_custom(&cfg_info, "parkedcallreparking", ACO_EXACT, parking_lot_types, "no", option_handler_parkedfeature, OPT_PARKEDREPARKING);
1035         aco_option_register_custom(&cfg_info, "parkedcallhangup", ACO_EXACT, parking_lot_types, "no", option_handler_parkedfeature, OPT_PARKEDHANGUP);
1036         aco_option_register_custom(&cfg_info, "parkedcallrecording", ACO_EXACT, parking_lot_types, "no", option_handler_parkedfeature, OPT_PARKEDRECORDING);
1037
1038         if (aco_process_config(&cfg_info, 0) == ACO_PROCESS_ERROR) {
1039                 goto error;
1040         }
1041
1042         if (ast_register_application_xml(PARK_APPLICATION, park_app_exec)) {
1043                 goto error;
1044         }
1045
1046         if (ast_register_application_xml(PARKED_CALL_APPLICATION, parked_call_app_exec)) {
1047                 goto error;
1048         }
1049
1050         if (ast_register_application_xml(PARK_AND_ANNOUNCE_APPLICATION, park_and_announce_app_exec)) {
1051                 goto error;
1052         }
1053
1054         if (load_parking_ui()) {
1055                 goto error;
1056         }
1057
1058         if (load_parking_manager()) {
1059                 goto error;
1060         }
1061
1062         if (load_parking_bridge_features()) {
1063                 goto error;
1064         }
1065
1066         if (load_parking_devstate()) {
1067                 goto error;
1068         }
1069
1070         return AST_MODULE_LOAD_SUCCESS;
1071
1072 error:
1073         ao2_cleanup(parking_lot_container);
1074         aco_info_destroy(&cfg_info);
1075         return AST_MODULE_LOAD_DECLINE;
1076 }
1077
1078 static int reload_module(void)
1079 {
1080         if (aco_process_config(&cfg_info, 1) == ACO_PROCESS_ERROR) {
1081                 return AST_MODULE_LOAD_DECLINE;
1082         }
1083
1084         return 0;
1085 }
1086
1087 static int unload_module(void)
1088 {
1089         /* XXX Parking is currently not unloadable due to the fact that it loads features which could cause
1090          *     significant problems if they disappeared while a channel still had access to them.
1091          */
1092         return -1;
1093
1094         /* TODO Things we will need to do here:
1095          *
1096          *  destroy existing parking lots
1097          *  uninstall parking related bridge features
1098          *  remove extensions owned by the parking registrar
1099          */
1100 }
1101
1102 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Call Parking Resource",
1103         .load = load_module,
1104         .unload = unload_module,
1105         .reload = reload_module,
1106 );