Asterisk - The Open Source Telephony Project  GIT-master-a24979a
ccss.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@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  * \brief Call Completion Supplementary Services implementation
21  * \author Mark Michelson <mmichelson@digium.com>
22  */
23 
24 /*! \li \ref ccss.c uses the configuration file \ref ccss.conf
25  * \addtogroup configuration_file Configuration Files
26  */
27 
28 /*!
29  * \page ccss.conf ccss.conf
30  * \verbinclude ccss.conf.sample
31  */
32 
33 /*** MODULEINFO
34  <support_level>core</support_level>
35  ***/
36 
37 #include "asterisk.h"
38 
39 #include "asterisk/astobj2.h"
40 #include "asterisk/strings.h"
41 #include "asterisk/ccss.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/utils.h"
45 #include "asterisk/taskprocessor.h"
46 #include "asterisk/devicestate.h"
47 #include "asterisk/module.h"
48 #include "asterisk/app.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/manager.h"
51 #include "asterisk/causes.h"
52 #include "asterisk/stasis_system.h"
53 #include "asterisk/format_cache.h"
54 
55 /*** DOCUMENTATION
56  <application name="CallCompletionRequest" language="en_US">
57  <synopsis>
58  Request call completion service for previous call
59  </synopsis>
60  <syntax />
61  <description>
62  <para>Request call completion service for a previously failed
63  call attempt.</para>
64  <para>This application sets the following channel variables:</para>
65  <variablelist>
66  <variable name="CC_REQUEST_RESULT">
67  <para>This is the returned status of the request.</para>
68  <value name="SUCCESS" />
69  <value name="FAIL" />
70  </variable>
71  <variable name="CC_REQUEST_REASON">
72  <para>This is the reason the request failed.</para>
73  <value name="NO_CORE_INSTANCE" />
74  <value name="NOT_GENERIC" />
75  <value name="TOO_MANY_REQUESTS" />
76  <value name="UNSPECIFIED" />
77  </variable>
78  </variablelist>
79  </description>
80  </application>
81  <application name="CallCompletionCancel" language="en_US">
82  <synopsis>
83  Cancel call completion service
84  </synopsis>
85  <syntax />
86  <description>
87  <para>Cancel a Call Completion Request.</para>
88  <para>This application sets the following channel variables:</para>
89  <variablelist>
90  <variable name="CC_CANCEL_RESULT">
91  <para>This is the returned status of the cancel.</para>
92  <value name="SUCCESS" />
93  <value name="FAIL" />
94  </variable>
95  <variable name="CC_CANCEL_REASON">
96  <para>This is the reason the cancel failed.</para>
97  <value name="NO_CORE_INSTANCE" />
98  <value name="NOT_GENERIC" />
99  <value name="UNSPECIFIED" />
100  </variable>
101  </variablelist>
102  </description>
103  </application>
104  ***/
105 
106 /* These are some file-scoped variables. It would be
107  * nice to define them closer to their first usage, but since
108  * they are used in many places throughout the file, defining
109  * them here at the top is easiest.
110  */
111 
112 /*!
113  * The ast_sched_context used for all generic CC timeouts
114  */
116 /*!
117  * Counter used to create core IDs for CC calls. Each new
118  * core ID is created by atomically adding 1 to the core_id_counter
119  */
120 static int core_id_counter;
121 /*!
122  * Taskprocessor from which all CC agent and monitor callbacks
123  * are called.
124  */
126 /*!
127  * Name printed on all CC log messages.
128  */
129 static const char *CC_LOGGER_LEVEL_NAME = "CC";
130 /*!
131  * Logger level registered by the CC core.
132  */
133 static int cc_logger_level;
134 /*!
135  * Parsed configuration value for cc_max_requests
136  */
137 static unsigned int global_cc_max_requests;
138 /*!
139  * The current number of CC requests in the system
140  */
141 static int cc_request_count;
142 
143 static inline void *cc_ref(void *obj, const char *debug)
144 {
145  ao2_t_ref(obj, +1, debug);
146  return obj;
147 }
148 
149 static inline void *cc_unref(void *obj, const char *debug)
150 {
151  ao2_t_ref(obj, -1, debug);
152  return NULL;
153 }
154 
155 /*!
156  * \since 1.8
157  * \internal
158  * \brief A structure for holding the configuration parameters
159  * relating to CCSS
160  */
164  unsigned int cc_offer_timer;
165  unsigned int ccnr_available_timer;
166  unsigned int ccbs_available_timer;
167  unsigned int cc_recall_timer;
168  unsigned int cc_max_agents;
169  unsigned int cc_max_monitors;
173 };
174 
175 /*!
176  * \since 1.8
177  * \brief The states used in the CCSS core state machine
178  *
179  * For more information, see doc/CCSS_architecture.pdf
180  */
181 enum cc_state {
182  /*! Entered when it is determined that CCSS may be used for the call */
184  /*! Entered when a CCSS agent has offered CCSS to a caller */
186  /*! Entered when a CCSS agent confirms that a caller has
187  * requested CCSS */
189  /*! Entered when a CCSS monitor confirms acknowledgment of an
190  * outbound CCSS request */
192  /*! Entered when a CCSS monitor alerts the core that the called party
193  * has become available */
195  /*! Entered when a CCSS agent alerts the core that the calling party
196  * may not be recalled because he is unavailable
197  */
199  /*! Entered when a CCSS agent alerts the core that the calling party
200  * is attempting to recall the called party
201  */
203  /*! Entered when an application alerts the core that the calling party's
204  * recall attempt has had a call progress response indicated
205  */
207  /*! Entered any time that something goes wrong during the process, thus
208  * resulting in the failure of the attempted CCSS transaction. Note also
209  * that cancellations of CC are treated as failures.
210  */
212 };
213 
214 /*!
215  * \brief The payload for an AST_CONTROL_CC frame
216  *
217  * \details
218  * This contains all the necessary data regarding
219  * a called device so that the CC core will be able
220  * to allocate the proper monitoring resources.
221  */
223  /*!
224  * \brief The type of monitor to allocate.
225  *
226  * \details
227  * The type of monitor to allocate. This is a string which corresponds
228  * to a set of monitor callbacks registered. Examples include "generic"
229  * and "SIP"
230  *
231  * \note This really should be an array of characters in case this payload
232  * is sent across an IAX2 link. However, this would not make too much sense
233  * given this type may not be recognized by the other end.
234  * Protection may be necessary to prevent it from being transmitted.
235  *
236  * In addition the following other problems are also possible:
237  * 1) Endian issues with the integers/enums stored in the config_params.
238  * 2) Alignment padding issues for the element types.
239  */
240  const char *monitor_type;
241  /*!
242  * \brief Private data allocated by the callee
243  *
244  * \details
245  * All channel drivers that monitor endpoints will need to allocate
246  * data that is not usable by the CC core. In most cases, some or all
247  * of this data is allocated at the time that the channel driver offers
248  * CC to the caller. There are many opportunities for failures to occur
249  * between when a channel driver offers CC and when a monitor is actually
250  * allocated to watch the endpoint. For this reason, the channel driver
251  * must give the core a pointer to the private data that was allocated so
252  * that the core can call back into the channel driver to destroy it if
253  * a failure occurs. If no private data has been allocated at the time that
254  * CC is offered, then it is perfectly acceptable to pass NULL for this
255  * field.
256  */
258  /*!
259  * \brief Service offered by the endpoint
260  *
261  * \details
262  * This indicates the type of call completion service offered by the
263  * endpoint. This data is not crucial to the machinations of the CC core,
264  * but it is helpful for debugging purposes.
265  */
267  /*!
268  * \brief Configuration parameters used by this endpoint
269  *
270  * \details
271  * Each time an endpoint offers call completion, it must provide its call
272  * completion configuration parameters. This is because settings may be different
273  * depending on the circumstances.
274  */
276  /*!
277  * \brief ID of parent extension
278  *
279  * \details
280  * This is the only datum that the CC core derives on its own and is not
281  * provided by the offerer of CC. This provides the core with information on
282  * which extension monitor is the most immediate parent of this device.
283  */
285  /*!
286  * \brief Name of device to be monitored
287  *
288  * \details
289  * The device name by which this monitored endpoint will be referred in the
290  * CC core. It is highly recommended that this device name is derived by using
291  * the function ast_channel_get_device_name.
292  */
294  /*!
295  * \brief Recall dialstring
296  *
297  * \details
298  * Certain channel drivers (DAHDI in particular) will require that a special
299  * dialstring be used to indicate that the outgoing call is to interpreted as
300  * a CC recall. If the channel driver has such a requirement, then this is
301  * where that special recall dialstring is placed. If no special dialstring
302  * is to be used, then the channel driver must provide the original dialstring
303  * used to call this endpoint.
304  */
306 };
307 
308 /*!
309  * \brief The "tree" of interfaces that is dialed.
310  *
311  * \details
312  * Though this is a linked list, it is logically treated
313  * as a tree of monitors. Each monitor has an id and a parent_id
314  * associated with it. The id is a unique ID for that monitor, and
315  * the parent_id is the unique ID of the monitor's parent in the
316  * tree. The tree is structured such that all of a parent's children
317  * will appear after the parent in the tree. However, it cannot be
318  * guaranteed exactly where after the parent the children are.
319  *
320  * The tree is reference counted since several threads may need
321  * to use it, and it may last beyond the lifetime of a single
322  * thread.
323  */
325 
326 static const int CC_CORE_INSTANCES_BUCKETS = 17;
328 
330  /*!
331  * Unique identifier for this instance of the CC core.
332  */
333  int core_id;
334  /*!
335  * The current state for this instance of the CC core.
336  */
337  enum cc_state current_state;
338  /*!
339  * The CC agent in use for this call
340  */
342  /*!
343  * Reference to the monitor tree formed during the initial call
344  */
346 };
347 
348 /*!
349  * \internal
350  * \brief Request that the core change states
351  * \param state The state to which we wish to change
352  * \param core_id The unique identifier for this instance of the CCSS core state machine
353  * \param debug Optional message explaining the reason for the state change
354  * \param ap varargs list
355  * \retval 0 State change successfully queued
356  * \retval -1 Unable to queue state change request
357  */
358 static int __attribute__((format(printf, 3, 0))) cc_request_state_change(enum cc_state state, const int core_id, const char *debug, va_list ap);
359 
360 /*!
361  * \internal
362  * \brief create a new instance of the CC core and an agent for the calling channel
363  *
364  * This function will check to make sure that the incoming channel
365  * is allowed to request CC by making sure that the incoming channel
366  * has not exceeded its maximum number of allowed agents.
367  *
368  * Should that check pass, the core instance is created, and then the
369  * agent for the channel.
370  *
371  * \param caller_chan The incoming channel for this particular call
372  * \param called_tree A reference to the tree of called devices. The agent
373  * will gain a reference to this tree as well
374  * \param core_id The core_id that this core_instance will assume
375  * \param cc_data
376  * \retval NULL Failed to create the core instance either due to memory allocation
377  * errors or due to the agent count for the caller being too high
378  * \retval non-NULL A reference to the newly created cc_core_instance
379  */
380 static struct cc_core_instance *cc_core_init_instance(struct ast_channel *caller_chan,
381  struct cc_monitor_tree *called_tree, const int core_id, struct cc_control_payload *cc_data);
382 
383 static const struct {
385  const char *service_string;
387  {AST_CC_NONE, "NONE"},
388  {AST_CC_CCBS, "CCBS"},
389  {AST_CC_CCNR, "CCNR"},
390  {AST_CC_CCNL, "CCNL"},
391 };
392 
393 static const struct {
394  enum cc_state state;
395  const char *state_string;
397  {CC_AVAILABLE, "CC is available"},
398  {CC_CALLER_OFFERED, "CC offered to caller"},
399  {CC_CALLER_REQUESTED, "CC requested by caller"},
400  {CC_ACTIVE, "CC accepted by callee"},
401  {CC_CALLEE_READY, "Callee has become available"},
402  {CC_CALLER_BUSY, "Callee was ready, but caller is now unavailable"},
403  {CC_RECALLING, "Caller is attempting to recall"},
404  {CC_COMPLETE, "Recall complete"},
405  {CC_FAILED, "CC has failed"},
406 };
407 
408 static const char *cc_state_to_string(enum cc_state state)
409 {
410  return cc_state_to_string_map[state].state_string;
411 }
412 
414 {
415  return cc_service_to_string_map[service].service_string;
416 }
417 
418 static int cc_core_instance_hash_fn(const void *obj, const int flags)
419 {
420  const struct cc_core_instance *core_instance = obj;
421  return core_instance->core_id;
422 }
423 
424 static int cc_core_instance_cmp_fn(void *obj, void *arg, int flags)
425 {
426  struct cc_core_instance *core_instance1 = obj;
427  struct cc_core_instance *core_instance2 = arg;
428 
429  return core_instance1->core_id == core_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
430 }
431 
433 {
434  struct cc_core_instance finder = {.core_id = core_id,};
435 
436  return ao2_t_find(cc_core_instances, &finder, OBJ_POINTER, "Finding a core_instance");
437 }
438 
440  ao2_callback_fn *function;
441  void *args;
442  const char *type;
443 };
444 
445 static int cc_agent_callback_helper(void *obj, void *args, int flags)
446 {
447  struct cc_core_instance *core_instance = obj;
448  struct cc_callback_helper *helper = args;
449 
450  if (strcmp(core_instance->agent->callbacks->type, helper->type)) {
451  return 0;
452  }
453 
454  return helper->function(core_instance->agent, helper->args, flags);
455 }
456 
457 struct ast_cc_agent *ast_cc_agent_callback(int flags, ao2_callback_fn *function, void *args, const char * const type)
458 {
459  struct cc_callback_helper helper = {.function = function, .args = args, .type = type};
460  struct cc_core_instance *core_instance;
461  if ((core_instance = ao2_t_callback(cc_core_instances, flags, cc_agent_callback_helper, &helper,
462  "Calling provided agent callback function"))) {
463  struct ast_cc_agent *agent = cc_ref(core_instance->agent, "An outside entity needs the agent");
464  cc_unref(core_instance, "agent callback done with the core_instance");
465  return agent;
466  }
467  return NULL;
468 }
469 
471  /* Only match agents that have not yet
472  * made a CC request
473  */
474  MATCH_NO_REQUEST = (1 << 0),
475  /* Only match agents that have made
476  * a CC request
477  */
478  MATCH_REQUEST = (1 << 1),
479 };
480 
481 /* ao2_callbacks for cc_core_instances */
482 
483 /*!
484  * \internal
485  * \brief find a core instance based on its agent
486  *
487  * The match flags tell whether we wish to find core instances
488  * that have a monitor or core instances that do not. Core instances
489  * with no monitor are core instances for which a caller has not yet
490  * requested CC. Core instances with a monitor are ones for which the
491  * caller has requested CC.
492  */
493 static int match_agent(void *obj, void *arg, void *data, int flags)
494 {
495  struct cc_core_instance *core_instance = obj;
496  const char *name = arg;
497  unsigned long match_flags = *(unsigned long *)data;
498  int possible_match = 0;
499 
500  if ((match_flags & MATCH_NO_REQUEST) && core_instance->current_state < CC_CALLER_REQUESTED) {
501  possible_match = 1;
502  }
503 
504  if ((match_flags & MATCH_REQUEST) && core_instance->current_state >= CC_CALLER_REQUESTED) {
505  possible_match = 1;
506  }
507 
508  if (!possible_match) {
509  return 0;
510  }
511 
512  if (!strcmp(core_instance->agent->device_name, name)) {
513  return CMP_MATCH | CMP_STOP;
514  }
515  return 0;
516 }
517 
519  int count;
521 };
522 
523 /*!
524  * \internal
525  * \brief Count the number of agents a specific interface is using
526  *
527  * We're only concerned with the number of agents that have requested
528  * CC, so we restrict our search to core instances which have a non-NULL
529  * monitor pointer
530  */
531 static int count_agents_cb(void *obj, void *arg, void *data, int flags)
532 {
533  struct cc_core_instance *core_instance = obj;
534  const char *name = arg;
535  struct count_agents_cb_data *cb_data = data;
536 
537  if (cb_data->core_id_exception == core_instance->core_id) {
538  ast_log_dynamic_level(cc_logger_level, "Found agent with core_id %d but not counting it toward total\n", core_instance->core_id);
539  return 0;
540  }
541 
542  if (core_instance->current_state >= CC_CALLER_REQUESTED && !strcmp(core_instance->agent->device_name, name)) {
543  cb_data->count++;
544  }
545  return 0;
546 }
547 
548 /* default values mapping from cc_state to ast_dev_state */
549 
550 #define CC_AVAILABLE_DEVSTATE_DEFAULT AST_DEVICE_NOT_INUSE
551 #define CC_CALLER_OFFERED_DEVSTATE_DEFAULT AST_DEVICE_NOT_INUSE
552 #define CC_CALLER_REQUESTED_DEVSTATE_DEFAULT AST_DEVICE_NOT_INUSE
553 #define CC_ACTIVE_DEVSTATE_DEFAULT AST_DEVICE_INUSE
554 #define CC_CALLEE_READY_DEVSTATE_DEFAULT AST_DEVICE_RINGING
555 #define CC_CALLER_BUSY_DEVSTATE_DEFAULT AST_DEVICE_ONHOLD
556 #define CC_RECALLING_DEVSTATE_DEFAULT AST_DEVICE_RINGING
557 #define CC_COMPLETE_DEVSTATE_DEFAULT AST_DEVICE_NOT_INUSE
558 #define CC_FAILED_DEVSTATE_DEFAULT AST_DEVICE_NOT_INUSE
559 
560 /*!
561  * \internal
562  * \brief initialization of defaults for CC_STATE to DEVICE_STATE map
563  */
574 };
575 
576 /*!
577  * \internal
578  * \brief lookup the ast_device_state mapped to cc_state
579  *
580  * \param state
581  *
582  * \return the correponding DEVICE STATE from the cc_state_to_devstate_map
583  * when passed an internal state.
584  */
586 {
588 }
589 
590 /*!
591  * \internal
592  * \brief Callback for devicestate providers
593  *
594  * \details
595  * Initialize with ast_devstate_prov_add() and returns the corresponding
596  * DEVICE STATE based on the current CC_STATE state machine if the requested
597  * device is found and is a generic device. Returns the equivalent of
598  * CC_FAILED, which defaults to NOT_INUSE, if no device is found. NOT_INUSE would
599  * indicate that there is no presence of any pending call back.
600  */
601 static enum ast_device_state ccss_device_state(const char *device_name)
602 {
603  struct cc_core_instance *core_instance;
604  unsigned long match_flags;
605  enum ast_device_state cc_current_state;
606 
609  (char *) device_name, &match_flags,
610  "Find Core Instance for ccss_device_state reqeust.");
611  if (!core_instance) {
613  "Couldn't find a core instance for caller %s\n", device_name);
615  }
616 
618  "Core %d: Found core_instance for caller %s in state %s\n",
619  core_instance->core_id, device_name, cc_state_to_string(core_instance->current_state));
620 
621  if (strcmp(core_instance->agent->callbacks->type, "generic")) {
623  "Core %d: Device State is only for generic agent types.\n",
624  core_instance->core_id);
625  cc_unref(core_instance, "Unref core_instance since ccss_device_state was called with native agent");
627  }
628  cc_current_state = cc_state_to_devstate(core_instance->current_state);
629  cc_unref(core_instance, "Unref core_instance done with ccss_device_state");
630  return cc_current_state;
631 }
632 
633 /*!
634  * \internal
635  * \brief Notify Device State Changes from CC STATE MACHINE
636  *
637  * \details
638  * Any time a state is changed, we call this function to notify the DEVICE STATE
639  * subsystem of the change so that subscribed phones to any corresponding hints that
640  * are using that state are updated.
641  */
642 static void ccss_notify_device_state_change(const char *device, enum cc_state state)
643 {
644  enum ast_device_state devstate;
645 
646  devstate = cc_state_to_devstate(state);
647 
649  "Notification of CCSS state change to '%s', device state '%s' for device '%s'\n",
650  cc_state_to_string(state), ast_devstate2str(devstate), device);
651 
652  ast_devstate_changed(devstate, AST_DEVSTATE_CACHABLE, "ccss:%s", device);
653 }
654 
655 #define CC_OFFER_TIMER_DEFAULT 20 /* Seconds */
656 #define CCNR_AVAILABLE_TIMER_DEFAULT 7200 /* Seconds */
657 #define CCBS_AVAILABLE_TIMER_DEFAULT 4800 /* Seconds */
658 #define CC_RECALL_TIMER_DEFAULT 20 /* Seconds */
659 #define CC_MAX_AGENTS_DEFAULT 5
660 #define CC_MAX_MONITORS_DEFAULT 5
661 #define GLOBAL_CC_MAX_REQUESTS_DEFAULT 20
662 
663 static const struct ast_cc_config_params cc_default_params = {
665  .cc_monitor_policy = AST_CC_MONITOR_NEVER,
666  .cc_offer_timer = CC_OFFER_TIMER_DEFAULT,
667  .ccnr_available_timer = CCNR_AVAILABLE_TIMER_DEFAULT,
668  .ccbs_available_timer = CCBS_AVAILABLE_TIMER_DEFAULT,
669  .cc_recall_timer = CC_RECALL_TIMER_DEFAULT,
670  .cc_max_agents = CC_MAX_AGENTS_DEFAULT,
671  .cc_max_monitors = CC_MAX_MONITORS_DEFAULT,
672  .cc_callback_macro = "",
673  .cc_callback_sub = "",
674  .cc_agent_dialstring = "",
675 };
676 
678 {
679  *params = cc_default_params;
680 }
681 
682 struct ast_cc_config_params *__ast_cc_config_params_init(const char *file, int line, const char *function)
683 {
684  struct ast_cc_config_params *params = __ast_malloc(sizeof(*params), file, line, function);
685 
686  if (!params) {
687  return NULL;
688  }
689 
691  return params;
692 }
693 
695 {
696  ast_free(params);
697 }
698 
699 static enum ast_cc_agent_policies str_to_agent_policy(const char * const value)
700 {
701  if (!strcasecmp(value, "never")) {
702  return AST_CC_AGENT_NEVER;
703  } else if (!strcasecmp(value, "native")) {
704  return AST_CC_AGENT_NATIVE;
705  } else if (!strcasecmp(value, "generic")) {
706  return AST_CC_AGENT_GENERIC;
707  } else {
708  ast_log(LOG_WARNING, "%s is an invalid value for cc_agent_policy. Switching to 'never'\n", value);
709  return AST_CC_AGENT_NEVER;
710  }
711 }
712 
713 static enum ast_cc_monitor_policies str_to_monitor_policy(const char * const value)
714 {
715  if (!strcasecmp(value, "never")) {
716  return AST_CC_MONITOR_NEVER;
717  } else if (!strcasecmp(value, "native")) {
718  return AST_CC_MONITOR_NATIVE;
719  } else if (!strcasecmp(value, "generic")) {
720  return AST_CC_MONITOR_GENERIC;
721  } else if (!strcasecmp(value, "always")) {
722  return AST_CC_MONITOR_ALWAYS;
723  } else {
724  ast_log(LOG_WARNING, "%s is an invalid value for cc_monitor_policy. Switching to 'never'\n", value);
725  return AST_CC_MONITOR_NEVER;
726  }
727 }
728 
729 static const char *agent_policy_to_str(enum ast_cc_agent_policies policy)
730 {
731  switch (policy) {
732  case AST_CC_AGENT_NEVER:
733  return "never";
734  case AST_CC_AGENT_NATIVE:
735  return "native";
737  return "generic";
738  default:
739  /* This should never happen... */
740  return "";
741  }
742 }
743 
744 static const char *monitor_policy_to_str(enum ast_cc_monitor_policies policy)
745 {
746  switch (policy) {
748  return "never";
750  return "native";
752  return "generic";
754  return "always";
755  default:
756  /* This should never happen... */
757  return "";
758  }
759 }
760 int ast_cc_get_param(struct ast_cc_config_params *params, const char * const name,
761  char *buf, size_t buf_len)
762 {
763  const char *value = NULL;
764 
765  if (!strcasecmp(name, "cc_callback_macro")) {
767  } else if (!strcasecmp(name, "cc_callback_sub")) {
768  value = ast_get_cc_callback_sub(params);
769  } else if (!strcasecmp(name, "cc_agent_policy")) {
771  } else if (!strcasecmp(name, "cc_monitor_policy")) {
773  } else if (!strcasecmp(name, "cc_agent_dialstring")) {
775  }
776  if (value) {
777  ast_copy_string(buf, value, buf_len);
778  return 0;
779  }
780 
781  /* The rest of these are all ints of some sort and require some
782  * snprintf-itude
783  */
784 
785  if (!strcasecmp(name, "cc_offer_timer")) {
786  snprintf(buf, buf_len, "%u", ast_get_cc_offer_timer(params));
787  } else if (!strcasecmp(name, "ccnr_available_timer")) {
788  snprintf(buf, buf_len, "%u", ast_get_ccnr_available_timer(params));
789  } else if (!strcasecmp(name, "ccbs_available_timer")) {
790  snprintf(buf, buf_len, "%u", ast_get_ccbs_available_timer(params));
791  } else if (!strcasecmp(name, "cc_max_agents")) {
792  snprintf(buf, buf_len, "%u", ast_get_cc_max_agents(params));
793  } else if (!strcasecmp(name, "cc_max_monitors")) {
794  snprintf(buf, buf_len, "%u", ast_get_cc_max_monitors(params));
795  } else if (!strcasecmp(name, "cc_recall_timer")) {
796  snprintf(buf, buf_len, "%u", ast_get_cc_recall_timer(params));
797  } else {
798  ast_log(LOG_WARNING, "%s is not a valid CC parameter. Ignoring.\n", name);
799  return -1;
800  }
801 
802  return 0;
803 }
804 
805 int ast_cc_set_param(struct ast_cc_config_params *params, const char * const name,
806  const char * const value)
807 {
808  unsigned int value_as_uint;
809  if (!strcasecmp(name, "cc_agent_policy")) {
811  } else if (!strcasecmp(name, "cc_monitor_policy")) {
813  } else if (!strcasecmp(name, "cc_agent_dialstring")) {
815  } else if (!strcasecmp(name, "cc_callback_macro")) {
817  return 0;
818  } else if (!strcasecmp(name, "cc_callback_sub")) {
820  return 0;
821  }
822 
823  if (sscanf(value, "%30u", &value_as_uint) != 1) {
824  return -1;
825  }
826 
827  if (!strcasecmp(name, "cc_offer_timer")) {
828  ast_set_cc_offer_timer(params, value_as_uint);
829  } else if (!strcasecmp(name, "ccnr_available_timer")) {
830  ast_set_ccnr_available_timer(params, value_as_uint);
831  } else if (!strcasecmp(name, "ccbs_available_timer")) {
832  ast_set_ccbs_available_timer(params, value_as_uint);
833  } else if (!strcasecmp(name, "cc_max_agents")) {
834  ast_set_cc_max_agents(params, value_as_uint);
835  } else if (!strcasecmp(name, "cc_max_monitors")) {
836  ast_set_cc_max_monitors(params, value_as_uint);
837  } else if (!strcasecmp(name, "cc_recall_timer")) {
838  ast_set_cc_recall_timer(params, value_as_uint);
839  } else {
840  ast_log(LOG_WARNING, "%s is not a valid CC parameter. Ignoring.\n", name);
841  return -1;
842  }
843 
844  return 0;
845 }
846 
847 int ast_cc_is_config_param(const char * const name)
848 {
849  return (!strcasecmp(name, "cc_agent_policy") ||
850  !strcasecmp(name, "cc_monitor_policy") ||
851  !strcasecmp(name, "cc_offer_timer") ||
852  !strcasecmp(name, "ccnr_available_timer") ||
853  !strcasecmp(name, "ccbs_available_timer") ||
854  !strcasecmp(name, "cc_max_agents") ||
855  !strcasecmp(name, "cc_max_monitors") ||
856  !strcasecmp(name, "cc_callback_macro") ||
857  !strcasecmp(name, "cc_callback_sub") ||
858  !strcasecmp(name, "cc_agent_dialstring") ||
859  !strcasecmp(name, "cc_recall_timer"));
860 }
861 
863 {
864  *dest = *src;
865 }
866 
868 {
869  return config->cc_agent_policy;
870 }
871 
873 {
874  /* Screw C and its weak type checking for making me have to do this
875  * validation at runtime.
876  */
877  if (value < AST_CC_AGENT_NEVER || value > AST_CC_AGENT_GENERIC) {
878  return -1;
879  }
880  config->cc_agent_policy = value;
881  return 0;
882 }
883 
885 {
886  return config->cc_monitor_policy;
887 }
888 
890 {
891  /* Screw C and its weak type checking for making me have to do this
892  * validation at runtime.
893  */
894  if (value < AST_CC_MONITOR_NEVER || value > AST_CC_MONITOR_ALWAYS) {
895  return -1;
896  }
897  config->cc_monitor_policy = value;
898  return 0;
899 }
900 
902 {
903  return config->cc_offer_timer;
904 }
905 
907 {
908  /* 0 is an unreasonable value for any timer. Stick with the default */
909  if (value == 0) {
910  ast_log(LOG_WARNING, "0 is an invalid value for cc_offer_timer. Retaining value as %u\n", config->cc_offer_timer);
911  return;
912  }
913  config->cc_offer_timer = value;
914 }
915 
917 {
918  return config->ccnr_available_timer;
919 }
920 
922 {
923  /* 0 is an unreasonable value for any timer. Stick with the default */
924  if (value == 0) {
925  ast_log(LOG_WARNING, "0 is an invalid value for ccnr_available_timer. Retaining value as %u\n", config->ccnr_available_timer);
926  return;
927  }
928  config->ccnr_available_timer = value;
929 }
930 
932 {
933  return config->cc_recall_timer;
934 }
935 
937 {
938  /* 0 is an unreasonable value for any timer. Stick with the default */
939  if (value == 0) {
940  ast_log(LOG_WARNING, "0 is an invalid value for ccnr_available_timer. Retaining value as %u\n", config->cc_recall_timer);
941  return;
942  }
943  config->cc_recall_timer = value;
944 }
945 
947 {
948  return config->ccbs_available_timer;
949 }
950 
952 {
953  /* 0 is an unreasonable value for any timer. Stick with the default */
954  if (value == 0) {
955  ast_log(LOG_WARNING, "0 is an invalid value for ccbs_available_timer. Retaining value as %u\n", config->ccbs_available_timer);
956  return;
957  }
958  config->ccbs_available_timer = value;
959 }
960 
962 {
963  return config->cc_agent_dialstring;
964 }
965 
967 {
968  if (ast_strlen_zero(value)) {
969  config->cc_agent_dialstring[0] = '\0';
970  } else {
971  ast_copy_string(config->cc_agent_dialstring, value, sizeof(config->cc_agent_dialstring));
972  }
973 }
974 
976 {
977  return config->cc_max_agents;
978 }
979 
981 {
982  config->cc_max_agents = value;
983 }
984 
986 {
987  return config->cc_max_monitors;
988 }
989 
991 {
992  config->cc_max_monitors = value;
993 }
994 
996 {
997  return config->cc_callback_macro;
998 }
999 
1001 {
1002  return config->cc_callback_sub;
1003 }
1004 
1006 {
1007  ast_log(LOG_WARNING, "Usage of cc_callback_macro is deprecated. Please use cc_callback_sub instead.\n");
1008  if (ast_strlen_zero(value)) {
1009  config->cc_callback_macro[0] = '\0';
1010  } else {
1011  ast_copy_string(config->cc_callback_macro, value, sizeof(config->cc_callback_macro));
1012  }
1013 }
1014 
1016 {
1017  if (ast_strlen_zero(value)) {
1018  config->cc_callback_sub[0] = '\0';
1019  } else {
1020  ast_copy_string(config->cc_callback_sub, value, sizeof(config->cc_callback_sub));
1021  }
1022 }
1023 
1024 static int cc_publish(struct stasis_message_type *message_type, int core_id, struct ast_json *extras)
1025 {
1026  struct ast_json *blob;
1027  struct ast_json_payload *payload;
1028  struct stasis_message *message;
1029 
1030  if (!message_type) {
1031  return -1;
1032  }
1033 
1034  blob = ast_json_pack("{s: i}",
1035  "core_id", core_id);
1036  if (!blob) {
1037  return -1;
1038  }
1039 
1040  if (extras) {
1041  ast_json_object_update(blob, extras);
1042  }
1043 
1044  payload = ast_json_payload_create(blob);
1045  ast_json_unref(blob);
1046 
1047  if (!payload) {
1048  return -1;
1049  }
1050 
1051  message = stasis_message_create(message_type, payload);
1052  ao2_ref(payload, -1);
1053 
1054  if (!message) {
1055  return -1;
1056  }
1057 
1059  ao2_ref(message, -1);
1060 
1061  return 0;
1062 }
1063 
1064 static void cc_publish_available(int core_id, const char *callee, const char *service)
1065 {
1066  struct ast_json *extras;
1067 
1068  extras = ast_json_pack("{s: s, s: s}",
1069  "callee", callee,
1070  "service", service);
1071 
1072  cc_publish(ast_cc_available_type(), core_id, extras);
1073  ast_json_unref(extras);
1074 }
1075 
1076 static void cc_publish_offertimerstart(int core_id, const char *caller, unsigned int expires)
1077 {
1078  struct ast_json *extras;
1079 
1080  extras = ast_json_pack("{s: s, s: I}",
1081  "caller", caller,
1082  "expires", (ast_json_int_t)expires);
1083 
1084  cc_publish(ast_cc_offertimerstart_type(), core_id, extras);
1085  ast_json_unref(extras);
1086 }
1087 
1088 static void cc_publish_requested(int core_id, const char *caller, const char *callee)
1089 {
1090  struct ast_json *extras;
1091 
1092  extras = ast_json_pack("{s: s, s: s}",
1093  "caller", caller,
1094  "callee", callee);
1095 
1096  cc_publish(ast_cc_requested_type(), core_id, extras);
1097  ast_json_unref(extras);
1098 }
1099 
1100 static void cc_publish_requestacknowledged(int core_id, const char *caller)
1101 {
1102  struct ast_json *extras;
1103 
1104  extras = ast_json_pack("{s: s}",
1105  "caller", caller);
1106 
1107  cc_publish(ast_cc_requestacknowledged_type(), core_id, extras);
1108  ast_json_unref(extras);
1109 }
1110 
1111 static void cc_publish_callerstopmonitoring(int core_id, const char *caller)
1112 {
1113  struct ast_json *extras;
1114 
1115  extras = ast_json_pack("{s: s}",
1116  "caller", caller);
1117 
1118  cc_publish(ast_cc_callerstopmonitoring_type(), core_id, extras);
1119  ast_json_unref(extras);
1120 }
1121 
1122 static void cc_publish_callerstartmonitoring(int core_id, const char *caller)
1123 {
1124  struct ast_json *extras;
1125 
1126  extras = ast_json_pack("{s: s}",
1127  "caller", caller);
1128 
1129  cc_publish(ast_cc_callerstartmonitoring_type(), core_id, extras);
1130  ast_json_unref(extras);
1131 }
1132 
1133 static void cc_publish_callerrecalling(int core_id, const char *caller)
1134 {
1135  struct ast_json *extras;
1136 
1137  extras = ast_json_pack("{s: s}",
1138  "caller", caller);
1139 
1140  cc_publish(ast_cc_callerrecalling_type(), core_id, extras);
1141  ast_json_unref(extras);
1142 }
1143 
1144 static void cc_publish_recallcomplete(int core_id, const char *caller)
1145 {
1146  struct ast_json *extras;
1147 
1148  extras = ast_json_pack("{s: s}",
1149  "caller", caller);
1150 
1151  cc_publish(ast_cc_recallcomplete_type(), core_id, extras);
1152  ast_json_unref(extras);
1153 }
1154 
1155 static void cc_publish_failure(int core_id, const char *caller, const char *reason)
1156 {
1157  struct ast_json *extras;
1158 
1159  extras = ast_json_pack("{s: s, s: s}",
1160  "caller", caller,
1161  "reason", reason);
1162 
1163  cc_publish(ast_cc_failure_type(), core_id, extras);
1164  ast_json_unref(extras);
1165 }
1166 
1167 static void cc_publish_monitorfailed(int core_id, const char *callee)
1168 {
1169  struct ast_json *extras;
1170 
1171  extras = ast_json_pack("{s: s}",
1172  "callee", callee);
1173 
1174  cc_publish(ast_cc_monitorfailed_type(), core_id, extras);
1175  ast_json_unref(extras);
1176 }
1177 
1181 };
1182 
1184 
1186 {
1187  struct cc_monitor_backend *backend = ast_calloc(1, sizeof(*backend));
1188 
1189  if (!backend) {
1190  return -1;
1191  }
1192 
1193  backend->callbacks = callbacks;
1194 
1198  return 0;
1199 }
1200 
1201 static const struct ast_cc_monitor_callbacks *find_monitor_callbacks(const char * const type)
1202 {
1203  struct cc_monitor_backend *backend;
1204  const struct ast_cc_monitor_callbacks *callbacks = NULL;
1205 
1207  AST_RWLIST_TRAVERSE(&cc_monitor_backends, backend, next) {
1208  if (!strcmp(backend->callbacks->type, type)) {
1209  ast_log_dynamic_level(cc_logger_level, "Returning monitor backend %s\n", backend->callbacks->type);
1210  callbacks = backend->callbacks;
1211  break;
1212  }
1213  }
1215  return callbacks;
1216 }
1217 
1219 {
1220  struct cc_monitor_backend *backend;
1223  if (backend->callbacks == callbacks) {
1225  ast_free(backend);
1226  break;
1227  }
1228  }
1231 }
1232 
1236 };
1237 
1239 
1241 {
1242  struct cc_agent_backend *backend = ast_calloc(1, sizeof(*backend));
1243 
1244  if (!backend) {
1245  return -1;
1246  }
1247 
1248  backend->callbacks = callbacks;
1252  return 0;
1253 }
1254 
1256 {
1257  struct cc_agent_backend *backend;
1260  if (backend->callbacks == callbacks) {
1262  ast_free(backend);
1263  break;
1264  }
1265  }
1268 }
1269 
1270 static const struct ast_cc_agent_callbacks *find_agent_callbacks(struct ast_channel *chan)
1271 {
1272  struct cc_agent_backend *backend;
1273  const struct ast_cc_agent_callbacks *callbacks = NULL;
1274  struct ast_cc_config_params *cc_params;
1275  char type[32];
1276 
1277  cc_params = ast_channel_get_cc_config_params(chan);
1278  if (!cc_params) {
1279  return NULL;
1280  }
1281  switch (ast_get_cc_agent_policy(cc_params)) {
1282  case AST_CC_AGENT_GENERIC:
1283  ast_copy_string(type, "generic", sizeof(type));
1284  break;
1285  case AST_CC_AGENT_NATIVE:
1286  ast_channel_get_cc_agent_type(chan, type, sizeof(type));
1287  break;
1288  default:
1289  ast_log_dynamic_level(cc_logger_level, "Not returning agent callbacks since this channel is configured not to have a CC agent\n");
1290  return NULL;
1291  }
1292 
1294  AST_RWLIST_TRAVERSE(&cc_agent_backends, backend, next) {
1295  if (!strcmp(backend->callbacks->type, type)) {
1296  ast_log_dynamic_level(cc_logger_level, "Returning agent backend %s\n", backend->callbacks->type);
1297  callbacks = backend->callbacks;
1298  break;
1299  }
1300  }
1302  return callbacks;
1303 }
1304 
1305 /*!
1306  * \internal
1307  * \brief Determine if the given device state is considered available by generic CCSS.
1308  * \since 1.8
1309  *
1310  * \param state Device state to test.
1311  *
1312  * \retval TRUE if the given device state is considered available by generic CCSS.
1313  */
1315 {
1317 }
1318 
1319 static int cc_generic_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1320 static int cc_generic_monitor_suspend(struct ast_cc_monitor *monitor);
1321 static int cc_generic_monitor_unsuspend(struct ast_cc_monitor *monitor);
1322 static int cc_generic_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1323 static void cc_generic_monitor_destructor(void *private_data);
1324 
1326  .type = "generic",
1327  .request_cc = cc_generic_monitor_request_cc,
1328  .suspend = cc_generic_monitor_suspend,
1329  .unsuspend = cc_generic_monitor_unsuspend,
1330  .cancel_available_timer = cc_generic_monitor_cancel_available_timer,
1331  .destructor = cc_generic_monitor_destructor,
1332 };
1333 
1335 
1337  int core_id;
1341 };
1342 
1344  const char *device_name;
1346  /* If there are multiple instances monitoring the
1347  * same device and one should fail, we need to know
1348  * whether to signal that the device can be recalled.
1349  * The problem is that the device state is not enough
1350  * to check. If a caller has requested CCNR, then the
1351  * fact that the device is available does not indicate
1352  * that the device is ready to be recalled. Instead, as
1353  * soon as one instance of the monitor becomes available
1354  * for a recall, we mark the entire list as being fit
1355  * for recall. If a CCNR request comes in, then we will
1356  * have to mark the list as unfit for recall since this
1357  * is a clear indicator that the person at the monitored
1358  * device has gone away and is actually not fit to be
1359  * recalled
1360  */
1364 };
1365 
1366 /*!
1367  * \brief private data for generic device monitor
1368  */
1370  /*!
1371  * We need the device name during destruction so we
1372  * can find the appropriate item to destroy.
1373  */
1374  const char *device_name;
1375  /*!
1376  * We need the core ID for similar reasons. Once we
1377  * find the appropriate item in our ao2_container, we
1378  * need to remove the appropriate cc_monitor from the
1379  * list of monitors.
1380  */
1381  int core_id;
1382 };
1383 
1386 
1387 static struct generic_monitor_instance_list *find_generic_monitor_instance_list(const char * const device_name)
1388 {
1389  struct generic_monitor_instance_list finder = {0};
1390  char *uppertech = ast_strdupa(device_name);
1391  ast_tech_to_upper(uppertech);
1392  finder.device_name = uppertech;
1393 
1394  return ao2_t_find(generic_monitors, &finder, OBJ_POINTER, "Finding generic monitor instance list");
1395 }
1396 
1398 {
1399  struct generic_monitor_instance_list *generic_list = obj;
1400  struct generic_monitor_instance *generic_instance;
1401 
1402  generic_list->sub = stasis_unsubscribe(generic_list->sub);
1403  while ((generic_instance = AST_LIST_REMOVE_HEAD(&generic_list->list, next))) {
1404  ast_free(generic_instance);
1405  }
1406  ast_free((char *)generic_list->device_name);
1407 }
1408 
1409 static void generic_monitor_devstate_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg);
1411 {
1412  struct generic_monitor_instance_list *generic_list = ao2_t_alloc(sizeof(*generic_list),
1413  generic_monitor_instance_list_destructor, "allocate generic monitor instance list");
1414  char * device_name;
1415  struct stasis_topic *device_specific_topic;
1416 
1417  if (!generic_list) {
1418  return NULL;
1419  }
1420 
1421  if (!(device_name = ast_strdup(monitor->interface->device_name))) {
1422  cc_unref(generic_list, "Failed to strdup the monitor's device name");
1423  return NULL;
1424  }
1425  ast_tech_to_upper(device_name);
1426  generic_list->device_name = device_name;
1427 
1428  device_specific_topic = ast_device_state_topic(device_name);
1429  if (!device_specific_topic) {
1430  return NULL;
1431  }
1432 
1433  if (!(generic_list->sub = stasis_subscribe(device_specific_topic, generic_monitor_devstate_cb, NULL))) {
1434  cc_unref(generic_list, "Failed to subscribe to device state");
1435  return NULL;
1436  }
1439  generic_list->current_state = ast_device_state(monitor->interface->device_name);
1440  ao2_t_link(generic_monitors, generic_list, "linking new generic monitor instance list");
1441  return generic_list;
1442 }
1443 
1444 static int generic_monitor_devstate_tp_cb(void *data)
1445 {
1446  RAII_VAR(struct ast_device_state_message *, dev_state, data, ao2_cleanup);
1447  enum ast_device_state new_state = dev_state->state;
1448  enum ast_device_state previous_state;
1449  struct generic_monitor_instance_list *generic_list;
1450  struct generic_monitor_instance *generic_instance;
1451 
1452  if (!(generic_list = find_generic_monitor_instance_list(dev_state->device))) {
1453  /* The most likely cause for this is that we destroyed the monitor in the
1454  * time between subscribing to its device state and the time this executes.
1455  * Not really a big deal.
1456  */
1457  return 0;
1458  }
1459 
1460  if (generic_list->current_state == new_state) {
1461  /* The device state hasn't actually changed, so we don't really care */
1462  cc_unref(generic_list, "Kill reference of generic list in devstate taskprocessor callback");
1463  return 0;
1464  }
1465 
1466  previous_state = generic_list->current_state;
1467  generic_list->current_state = new_state;
1468 
1469  if (cc_generic_is_device_available(new_state) &&
1470  (previous_state == AST_DEVICE_INUSE || previous_state == AST_DEVICE_UNAVAILABLE ||
1471  previous_state == AST_DEVICE_BUSY)) {
1472  AST_LIST_TRAVERSE(&generic_list->list, generic_instance, next) {
1473  if (!generic_instance->is_suspended && generic_instance->monitoring) {
1474  generic_instance->monitoring = 0;
1475  generic_list->fit_for_recall = 1;
1476  ast_cc_monitor_callee_available(generic_instance->core_id, "Generic monitored party has become available");
1477  break;
1478  }
1479  }
1480  }
1481  cc_unref(generic_list, "Kill reference of generic list in devstate taskprocessor callback");
1482  return 0;
1483 }
1484 
1485 static void generic_monitor_devstate_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
1486 {
1487  /* Wow, it's cool that we've picked up on a state change, but we really want
1488  * the actual work to be done in the core's taskprocessor execution thread
1489  * so that all monitor operations can be serialized. Locks?! We don't need
1490  * no steenkin' locks!
1491  */
1492  struct ast_device_state_message *dev_state;
1494  return;
1495  }
1496 
1497  dev_state = stasis_message_data(msg);
1498  if (dev_state->eid) {
1499  /* ignore non-aggregate states */
1500  return;
1501  }
1502 
1503  ao2_t_ref(dev_state, +1, "Bumping dev_state ref for cc_core_taskprocessor");
1505  ao2_cleanup(dev_state);
1506  return;
1507  }
1508 }
1509 
1510 int ast_cc_available_timer_expire(const void *data)
1511 {
1512  struct ast_cc_monitor *monitor = (struct ast_cc_monitor *) data;
1513  int res;
1514  monitor->available_timer_id = -1;
1515  res = ast_cc_monitor_failed(monitor->core_id, monitor->interface->device_name, "Available timer expired for monitor");
1516  cc_unref(monitor, "Unref reference from scheduler\n");
1517  return res;
1518 }
1519 
1521 {
1522  struct generic_monitor_instance_list *generic_list;
1523  struct generic_monitor_instance *generic_instance;
1524  struct generic_monitor_pvt *gen_mon_pvt;
1526  int when;
1527 
1528  /* First things first. Native channel drivers will have their private data allocated
1529  * at the time that they tell the core that they can offer CC. Generic is quite a bit
1530  * different, and we wait until this point to allocate our private data.
1531  */
1532  if (!(gen_mon_pvt = ast_calloc(1, sizeof(*gen_mon_pvt)))) {
1533  return -1;
1534  }
1535 
1536  if (!(gen_mon_pvt->device_name = ast_strdup(monitor->interface->device_name))) {
1537  ast_free(gen_mon_pvt);
1538  return -1;
1539  }
1540 
1541  gen_mon_pvt->core_id = monitor->core_id;
1542 
1543  monitor->private_data = gen_mon_pvt;
1544 
1545  if (!(generic_list = find_generic_monitor_instance_list(monitor->interface->device_name))) {
1546  if (!(generic_list = create_new_generic_list(monitor))) {
1547  return -1;
1548  }
1549  }
1550 
1551  if (!(generic_instance = ast_calloc(1, sizeof(*generic_instance)))) {
1552  /* The generic monitor destructor will take care of the appropriate
1553  * deallocations
1554  */
1555  cc_unref(generic_list, "Generic monitor instance failed to allocate");
1556  return -1;
1557  }
1558  generic_instance->core_id = monitor->core_id;
1559  generic_instance->monitoring = 1;
1560  AST_LIST_INSERT_TAIL(&generic_list->list, generic_instance, next);
1563 
1564  *available_timer_id = ast_sched_add(cc_sched_context, when * 1000,
1565  ast_cc_available_timer_expire, cc_ref(monitor, "Give the scheduler a monitor reference"));
1566  if (*available_timer_id == -1) {
1567  cc_unref(monitor, "Failed to schedule available timer. (monitor)");
1568  cc_unref(generic_list, "Failed to schedule available timer. (generic_list)");
1569  return -1;
1570  }
1571  /* If the new instance was created as CCNR, then that means this device is not currently
1572  * fit for recall even if it previously was.
1573  */
1574  if (service == AST_CC_CCNR || service == AST_CC_CCNL) {
1575  generic_list->fit_for_recall = 0;
1576  }
1577  ast_cc_monitor_request_acked(monitor->core_id, "Generic monitor for %s subscribed to device state.",
1578  monitor->interface->device_name);
1579  cc_unref(generic_list, "Finished with monitor instance reference in request cc callback");
1580  return 0;
1581 }
1582 
1583 static int cc_generic_monitor_suspend(struct ast_cc_monitor *monitor)
1584 {
1585  struct generic_monitor_instance_list *generic_list;
1586  struct generic_monitor_instance *generic_instance;
1588 
1589  if (!(generic_list = find_generic_monitor_instance_list(monitor->interface->device_name))) {
1590  return -1;
1591  }
1592 
1593  /* First we need to mark this particular monitor as being suspended. */
1594  AST_LIST_TRAVERSE(&generic_list->list, generic_instance, next) {
1595  if (generic_instance->core_id == monitor->core_id) {
1596  generic_instance->is_suspended = 1;
1597  break;
1598  }
1599  }
1600 
1601  /* If the device being suspended is currently in use, then we don't need to
1602  * take any further actions
1603  */
1605  cc_unref(generic_list, "Device is in use. Nothing to do. Unref generic list.");
1606  return 0;
1607  }
1608 
1609  /* If the device is not in use, though, then it may be possible to report the
1610  * device's availability using a different monitor which is monitoring the
1611  * same device
1612  */
1613 
1614  AST_LIST_TRAVERSE(&generic_list->list, generic_instance, next) {
1615  if (!generic_instance->is_suspended) {
1616  ast_cc_monitor_callee_available(generic_instance->core_id, "Generic monitored party has become available");
1617  break;
1618  }
1619  }
1620  cc_unref(generic_list, "Done with generic list in suspend callback");
1621  return 0;
1622 }
1623 
1625 {
1626  struct generic_monitor_instance *generic_instance;
1629 
1630  if (!generic_list) {
1631  return -1;
1632  }
1633  /* If the device is currently available, we can immediately announce
1634  * its availability
1635  */
1637  ast_cc_monitor_callee_available(monitor->core_id, "Generic monitored party has become available");
1638  }
1639 
1640  /* In addition, we need to mark this generic_monitor_instance as not being suspended anymore */
1641  AST_LIST_TRAVERSE(&generic_list->list, generic_instance, next) {
1642  if (generic_instance->core_id == monitor->core_id) {
1643  generic_instance->is_suspended = 0;
1644  generic_instance->monitoring = 1;
1645  break;
1646  }
1647  }
1648  cc_unref(generic_list, "Done with generic list in cc_generic_monitor_unsuspend");
1649  return 0;
1650 }
1651 
1653 {
1654  ast_assert(sched_id != NULL);
1655 
1656  if (*sched_id == -1) {
1657  return 0;
1658  }
1659 
1660  ast_log_dynamic_level(cc_logger_level, "Core %d: Canceling generic monitor available timer for monitor %s\n",
1661  monitor->core_id, monitor->interface->device_name);
1663  cc_unref(monitor, "Remove scheduler's reference to the monitor");
1664  }
1665  *sched_id = -1;
1666  return 0;
1667 }
1668 
1669 static void cc_generic_monitor_destructor(void *private_data)
1670 {
1671  struct generic_monitor_pvt *gen_mon_pvt = private_data;
1672  struct generic_monitor_instance_list *generic_list;
1673  struct generic_monitor_instance *generic_instance;
1674 
1675  if (!private_data) {
1676  /* If the private data is NULL, that means that the monitor hasn't even
1677  * been created yet, but that the destructor was called. While this sort
1678  * of behavior is useful for native monitors, with a generic one, there is
1679  * nothing in particular to do.
1680  */
1681  return;
1682  }
1683 
1684  ast_log_dynamic_level(cc_logger_level, "Core %d: Destroying generic monitor %s\n",
1685  gen_mon_pvt->core_id, gen_mon_pvt->device_name);
1686 
1687  if (!(generic_list = find_generic_monitor_instance_list(gen_mon_pvt->device_name))) {
1688  /* If there's no generic list, that means that the monitor is being destroyed
1689  * before we actually got to request CC. Not a biggie. Same in the situation
1690  * below if the list traversal should complete without finding an entry.
1691  */
1692  ast_free((char *)gen_mon_pvt->device_name);
1693  ast_free(gen_mon_pvt);
1694  return;
1695  }
1696 
1697  AST_LIST_TRAVERSE_SAFE_BEGIN(&generic_list->list, generic_instance, next) {
1698  if (generic_instance->core_id == gen_mon_pvt->core_id) {
1700  ast_free(generic_instance);
1701  break;
1702  }
1703  }
1705 
1706  if (AST_LIST_EMPTY(&generic_list->list)) {
1707  /* No more monitors with this device name exist. Time to unlink this
1708  * list from the container
1709  */
1710  ao2_t_unlink(generic_monitors, generic_list, "Generic list is empty. Unlink it from the container");
1711  } else {
1712  /* There are still instances for this particular device. The situation
1713  * may be that we were attempting a CC recall and a failure occurred, perhaps
1714  * on the agent side. If a failure happens here and the device being monitored
1715  * is available, then we need to signal on the first unsuspended instance that
1716  * the device is available for recall.
1717  */
1718 
1719  /* First things first. We don't even want to consider this action if
1720  * the device in question isn't available right now.
1721  */
1722  if (generic_list->fit_for_recall
1723  && cc_generic_is_device_available(generic_list->current_state)) {
1724  AST_LIST_TRAVERSE(&generic_list->list, generic_instance, next) {
1725  if (!generic_instance->is_suspended && generic_instance->monitoring) {
1726  ast_cc_monitor_callee_available(generic_instance->core_id, "Signaling generic monitor "
1727  "availability due to other instance's failure.");
1728  break;
1729  }
1730  }
1731  }
1732  }
1733  cc_unref(generic_list, "Done with generic list in generic monitor destructor");
1734  ast_free((char *)gen_mon_pvt->device_name);
1735  ast_free(gen_mon_pvt);
1736 }
1737 
1738 static void cc_interface_destroy(void *data)
1739 {
1740  struct ast_cc_interface *interface = data;
1741  ast_log_dynamic_level(cc_logger_level, "Destroying cc interface %s\n", interface->device_name);
1742  ast_cc_config_params_destroy(interface->config_params);
1743 }
1744 
1745 /*!
1746  * \brief Data regarding an extension monitor's child's dialstrings
1747  *
1748  * \details
1749  * In developing CCSS, we had most aspects of its operation finished,
1750  * but there was one looming problem that we had failed to get right.
1751  * In our design document, we stated that when a CC recall occurs, all
1752  * endpoints that had been dialed originally would be called back.
1753  * Unfortunately, our implementation only allowed for devices which had
1754  * active monitors to inhabit the CC_INTERFACES channel variable, thus
1755  * making the automated recall only call monitored devices.
1756  *
1757  * Devices that were not CC-capable, or devices which failed CC at some
1758  * point during the process would not make it into the CC_INTERFACES
1759  * channel variable. This struct is meant as a remedy for the problem.
1760  */
1762  /*!
1763  * \brief the original dialstring used to call a particular device
1764  *
1765  * \details
1766  * When someone dials a particular endpoint, the dialstring used in
1767  * the dialplan is copied into this buffer. What's important here is
1768  * that this is the ORIGINAL dialstring, not the dialstring saved on
1769  * a device monitor. The dialstring on a device monitor is what should
1770  * be used when recalling that device. The two dialstrings may not be
1771  * the same.
1772  *
1773  * By keeping a copy of the original dialstring used, we can fall back
1774  * to using it if the device either does not ever offer CC or if the
1775  * device at some point fails for some reason, such as a timer expiration.
1776  */
1778  /*!
1779  * \brief The name of the device being dialed
1780  *
1781  * \details
1782  * This serves mainly as a key when searching for a particular dialstring.
1783  * For instance, let's say that we have called device SIP/400\@somepeer. This
1784  * device offers call completion, but then due to some unforeseen circumstance,
1785  * this device backs out and makes CC unavailable. When that happens, we need
1786  * to find the dialstring that corresponds to that device, and we use the
1787  * stored device name as a way to find it.
1788  *
1789  * \note There is one particular case where the device name stored here
1790  * will be empty. This is the case where we fail to request a channel, but we
1791  * still can make use of generic call completion. In such a case, since we never
1792  * were able to request the channel, we can't find what its device name is. In
1793  * this case, however, it is not important because the dialstring is guaranteed
1794  * to be the same both here and in the device monitor.
1795  */
1797  /*!
1798  * \brief Is this structure valid for use in CC_INTERFACES?
1799  *
1800  * \details
1801  * When this structure is first created, all information stored here is planned
1802  * to be used, so we set the is_valid flag. However, if a device offers call
1803  * completion, it will potentially have its own dialstring to use for the recall,
1804  * so we find this structure and clear the is_valid flag. By clearing the is_valid
1805  * flag, we won't try to populate the CC_INTERFACES variable with the dialstring
1806  * stored in this struct. Now, if later, the device which had offered CC should fail,
1807  * perhaps due to a timer expiration, then we need to re-set the is_valid flag. This
1808  * way, we still will end up placing a call to the device again, and the dialstring
1809  * used will be the same as was originally used.
1810  */
1813 };
1814 
1815 /*!
1816  * \brief Private data for an extension monitor
1817  */
1820 };
1821 
1822 static void cc_extension_monitor_destructor(void *private_data)
1823 {
1824  struct extension_monitor_pvt *extension_pvt = private_data;
1825  struct extension_child_dialstring *child_dialstring;
1826 
1827  /* This shouldn't be possible, but I'm paranoid */
1828  if (!extension_pvt) {
1829  return;
1830  }
1831 
1832  while ((child_dialstring = AST_LIST_REMOVE_HEAD(&extension_pvt->child_dialstrings, next))) {
1833  ast_free(child_dialstring);
1834  }
1835  ast_free(extension_pvt);
1836 }
1837 
1838 static void cc_monitor_destroy(void *data)
1839 {
1840  struct ast_cc_monitor *monitor = data;
1841  /* During the monitor creation process, it is possible for this
1842  * function to be called prior to when callbacks are assigned
1843  * to the monitor. Also, extension monitors do not have callbacks
1844  * assigned to them, so we wouldn't want to segfault when we try
1845  * to destroy one of them.
1846  */
1847  ast_log_dynamic_level(cc_logger_level, "Core %d: Calling destructor for monitor %s\n",
1848  monitor->core_id, monitor->interface->device_name);
1851  }
1852  if (monitor->callbacks) {
1853  monitor->callbacks->destructor(monitor->private_data);
1854  }
1855  cc_unref(monitor->interface, "Unreffing tree's reference to interface");
1856  ast_free(monitor->dialstring);
1857 }
1858 
1859 static void cc_interface_tree_destroy(void *data)
1860 {
1861  struct cc_monitor_tree *cc_interface_tree = data;
1862  struct ast_cc_monitor *monitor;
1863  while ((monitor = AST_LIST_REMOVE_HEAD(cc_interface_tree, next))) {
1864  if (monitor->callbacks) {
1865  monitor->callbacks->cancel_available_timer(monitor, &monitor->available_timer_id);
1866  }
1867  cc_unref(monitor, "Destroying all monitors");
1868  }
1869  AST_LIST_HEAD_DESTROY(cc_interface_tree);
1870 }
1871 
1872 /*!
1873  * This counter is used for assigning unique ids
1874  * to CC-enabled dialed interfaces.
1875  */
1877 
1878 /*!
1879  * \internal
1880  * \brief data stored in CC datastore
1881  *
1882  * The datastore creates a list of interfaces that were
1883  * dialed, including both extensions and devices. In addition
1884  * to the intrinsic data of the tree, some extra information
1885  * is needed for use by app_dial.
1886  */
1888  /*!
1889  * This value serves a dual-purpose. When dial starts, if the
1890  * dialed_cc_interfaces datastore currently exists on the calling
1891  * channel, then the dial_parent_id will serve as a means of
1892  * letting the new extension cc_monitor we create know
1893  * who his parent is. This value will be the extension
1894  * cc_monitor that dialed the local channel that resulted
1895  * in the new Dial app being called.
1896  *
1897  * In addition, once an extension cc_monitor is created,
1898  * the dial_parent_id will be changed to the id of that newly
1899  * created interface. This way, device interfaces created from
1900  * receiving AST_CONTROL_CC frames can use this field to determine
1901  * who their parent extension interface should be.
1902  */
1903  unsigned int dial_parent_id;
1904  /*!
1905  * Identifier for the potential CC request that may be made
1906  * based on this call. Even though an instance of the core may
1907  * not be made (since the caller may not request CC), we allocate
1908  * a new core_id at the beginning of the call so that recipient
1909  * channel drivers can have the information handy just in case
1910  * the caller does end up requesting CC.
1911  */
1912  int core_id;
1913  /*!
1914  * When a new Dial application is started, and the datastore
1915  * already exists on the channel, we can determine if we
1916  * should be adding any new interface information to tree.
1917  */
1918  char ignore;
1919  /*!
1920  * When it comes time to offer CC to the caller, we only want to offer
1921  * it to the original incoming channel. For nested Dials and outbound
1922  * channels, it is incorrect to attempt such a thing. This flag indicates
1923  * if the channel to which this datastore is attached may be legally
1924  * offered CC when the call is finished.
1925  */
1927  /*!
1928  * Reference-counted "tree" of interfaces.
1929  */
1931 };
1932 
1933 /*!
1934  * \internal
1935  * \brief Destructor function for cc_interfaces datastore
1936  *
1937  * This function will free the actual datastore and drop
1938  * the refcount for the monitor tree by one. In cases
1939  * where CC can actually be used, this unref will not
1940  * result in the destruction of the monitor tree, because
1941  * the CC core will still have a reference.
1942  *
1943  * \param data The dialed_cc_interfaces struct to destroy
1944  */
1945 static void dialed_cc_interfaces_destroy(void *data)
1946 {
1947  struct dialed_cc_interfaces *cc_interfaces = data;
1948  cc_unref(cc_interfaces->interface_tree, "Unref dial's ref to monitor tree");
1949  ast_free(cc_interfaces);
1950 }
1951 
1952 /*!
1953  * \internal
1954  * \brief Duplicate callback for cc_interfaces datastore
1955  *
1956  * Integers are copied by value, but the monitor tree
1957  * is done via a shallow copy and a bump of the refcount.
1958  * This way, sub-Dials will be appending interfaces onto
1959  * the same list as this call to Dial.
1960  *
1961  * \param data The old dialed_cc_interfaces we want to copy
1962  * \retval NULL Could not allocate memory for new dialed_cc_interfaces
1963  * \retval non-NULL The new copy of the dialed_cc_interfaces
1964  */
1965 static void *dialed_cc_interfaces_duplicate(void *data)
1966 {
1967  struct dialed_cc_interfaces *old_cc_interfaces = data;
1968  struct dialed_cc_interfaces *new_cc_interfaces = ast_calloc(1, sizeof(*new_cc_interfaces));
1969  if (!new_cc_interfaces) {
1970  return NULL;
1971  }
1972  new_cc_interfaces->ignore = old_cc_interfaces->ignore;
1973  new_cc_interfaces->dial_parent_id = old_cc_interfaces->dial_parent_id;
1974  new_cc_interfaces->is_original_caller = 0;
1975  cc_ref(old_cc_interfaces->interface_tree, "New ref due to duplication of monitor tree");
1976  new_cc_interfaces->core_id = old_cc_interfaces->core_id;
1977  new_cc_interfaces->interface_tree = old_cc_interfaces->interface_tree;
1978  return new_cc_interfaces;
1979 }
1980 
1981 /*!
1982  * \internal
1983  * \brief information regarding the dialed_cc_interfaces datastore
1984  *
1985  * The dialed_cc_interfaces datastore is responsible for keeping track
1986  * of what CC-enabled interfaces have been dialed by the caller. For
1987  * more information regarding the actual structure of the tree, see
1988  * the documentation provided in include/asterisk/ccss.h
1989  */
1990 static const struct ast_datastore_info dialed_cc_interfaces_info = {
1991  .type = "Dial CC Interfaces",
1992  .duplicate = dialed_cc_interfaces_duplicate,
1993  .destroy = dialed_cc_interfaces_destroy,
1994 };
1995 
1997 {
1998  struct extension_monitor_pvt *ext_pvt = ast_calloc(1, sizeof(*ext_pvt));
1999  if (!ext_pvt) {
2000  return NULL;
2001  }
2003  return ext_pvt;
2004 }
2005 
2006 void ast_cc_extension_monitor_add_dialstring(struct ast_channel *incoming, const char * const dialstring, const char * const device_name)
2007 {
2008  struct ast_datastore *cc_datastore;
2009  struct dialed_cc_interfaces *cc_interfaces;
2010  struct ast_cc_monitor *monitor;
2011  struct extension_monitor_pvt *extension_pvt;
2012  struct extension_child_dialstring *child_dialstring;
2013  struct cc_monitor_tree *interface_tree;
2014  int id;
2015 
2016  ast_channel_lock(incoming);
2017  if (!(cc_datastore = ast_channel_datastore_find(incoming, &dialed_cc_interfaces_info, NULL))) {
2018  ast_channel_unlock(incoming);
2019  return;
2020  }
2021 
2022  cc_interfaces = cc_datastore->data;
2023  interface_tree = cc_interfaces->interface_tree;
2024  id = cc_interfaces->dial_parent_id;
2025  ast_channel_unlock(incoming);
2026 
2027  AST_LIST_LOCK(interface_tree);
2028  AST_LIST_TRAVERSE(interface_tree, monitor, next) {
2029  if (monitor->id == id) {
2030  break;
2031  }
2032  }
2033 
2034  if (!monitor) {
2035  AST_LIST_UNLOCK(interface_tree);
2036  return;
2037  }
2038 
2039  extension_pvt = monitor->private_data;
2040  if (!(child_dialstring = ast_calloc(1, sizeof(*child_dialstring)))) {
2041  AST_LIST_UNLOCK(interface_tree);
2042  return;
2043  }
2044  ast_copy_string(child_dialstring->original_dialstring, dialstring, sizeof(child_dialstring->original_dialstring));
2045  ast_copy_string(child_dialstring->device_name, device_name, sizeof(child_dialstring->device_name));
2046  child_dialstring->is_valid = 1;
2047  AST_LIST_INSERT_TAIL(&extension_pvt->child_dialstrings, child_dialstring, next);
2048  AST_LIST_UNLOCK(interface_tree);
2049 }
2050 
2051 static void cc_extension_monitor_change_is_valid(struct cc_core_instance *core_instance, unsigned int parent_id, const char * const device_name, int is_valid)
2052 {
2053  struct ast_cc_monitor *monitor_iter;
2054  struct extension_monitor_pvt *extension_pvt;
2055  struct extension_child_dialstring *child_dialstring;
2056 
2057  AST_LIST_TRAVERSE(core_instance->monitors, monitor_iter, next) {
2058  if (monitor_iter->id == parent_id) {
2059  break;
2060  }
2061  }
2062 
2063  if (!monitor_iter) {
2064  return;
2065  }
2066  extension_pvt = monitor_iter->private_data;
2067 
2068  AST_LIST_TRAVERSE(&extension_pvt->child_dialstrings, child_dialstring, next) {
2069  if (!strcmp(child_dialstring->device_name, device_name)) {
2070  child_dialstring->is_valid = is_valid;
2071  break;
2072  }
2073  }
2074 }
2075 
2076 /*!
2077  * \internal
2078  * \brief Allocate and initialize an "extension" interface for CC purposes
2079  *
2080  * When app_dial starts, this function is called in order to set up the
2081  * information about the extension in which this Dial is occurring. Any
2082  * devices dialed will have this particular cc_monitor as a parent.
2083  *
2084  * \param exten Extension from which Dial is occurring
2085  * \param context Context to which exten belongs
2086  * \param parent_id What should we set the parent_id of this interface to?
2087  * \retval NULL Memory allocation failure
2088  * \retval non-NULL The newly-created cc_monitor for the extension
2089  */
2090 static struct ast_cc_monitor *cc_extension_monitor_init(const char * const exten, const char * const context, const unsigned int parent_id)
2091 {
2093  struct ast_cc_interface *cc_interface;
2094  struct ast_cc_monitor *monitor;
2095 
2096  ast_str_set(&str, 0, "%s@%s", exten, context);
2097 
2098  if (!(cc_interface = ao2_t_alloc(sizeof(*cc_interface) + ast_str_strlen(str), cc_interface_destroy,
2099  "Allocating new ast_cc_interface"))) {
2100  return NULL;
2101  }
2102 
2103  if (!(monitor = ao2_t_alloc(sizeof(*monitor), cc_monitor_destroy, "Allocating new ast_cc_monitor"))) {
2104  cc_unref(cc_interface, "failed to allocate the monitor, so unref the interface");
2105  return NULL;
2106  }
2107 
2108  if (!(monitor->private_data = extension_monitor_pvt_init())) {
2109  cc_unref(monitor, "Failed to initialize extension monitor private data. uref monitor");
2110  cc_unref(cc_interface, "Failed to initialize extension monitor private data. unref cc_interface");
2111  }
2112 
2114  monitor->parent_id = parent_id;
2115  cc_interface->monitor_type = "extension";
2116  cc_interface->monitor_class = AST_CC_EXTENSION_MONITOR;
2117  strcpy(cc_interface->device_name, ast_str_buffer(str));
2118  monitor->interface = cc_interface;
2119  ast_log_dynamic_level(cc_logger_level, "Created an extension cc interface for '%s' with id %u and parent %u\n", cc_interface->device_name, monitor->id, monitor->parent_id);
2120  return monitor;
2121 }
2122 
2123 /*!
2124  * \internal
2125  * \brief allocate dialed_cc_interfaces datastore and initialize fields
2126  *
2127  * This function is called when Situation 1 occurs in ast_cc_call_init.
2128  * See that function for more information on what Situation 1 is.
2129  *
2130  * In this particular case, we have to do a lot of memory allocation in order
2131  * to create the datastore, the data for the datastore, the tree of interfaces
2132  * that we'll be adding to, and the initial extension interface for this Dial
2133  * attempt.
2134  *
2135  * \param chan The channel onto which the datastore should be added.
2136  * \retval -1 An error occurred
2137  * \retval 0 Success
2138  */
2139 static int cc_interfaces_datastore_init(struct ast_channel *chan) {
2141  struct ast_cc_monitor *monitor;
2142  struct ast_datastore *dial_cc_datastore;
2143 
2144  /*XXX This may be a bit controversial. In an attempt to not allocate
2145  * extra resources, I make sure that a future request will be within
2146  * limits. The problem here is that it is reasonable to think that
2147  * even if we're not within the limits at this point, we may be by
2148  * the time the requestor will have made his request. This may be
2149  * deleted at some point.
2150  */
2152  return 0;
2153  }
2154 
2155  if (!(interfaces = ast_calloc(1, sizeof(*interfaces)))) {
2156  return -1;
2157  }
2158 
2161  return -1;
2162  }
2163 
2164  if (!(dial_cc_datastore = ast_datastore_alloc(&dialed_cc_interfaces_info, NULL))) {
2165  cc_unref(monitor, "Could not allocate the dialed interfaces datastore. Unreffing monitor");
2167  return -1;
2168  }
2169 
2170  if (!(interfaces->interface_tree = ao2_t_alloc(sizeof(*interfaces->interface_tree), cc_interface_tree_destroy,
2171  "Allocate monitor tree"))) {
2172  ast_datastore_free(dial_cc_datastore);
2173  cc_unref(monitor, "Could not allocate monitor tree on dialed interfaces datastore. Unreffing monitor");
2175  return -1;
2176  }
2177 
2178  /* Finally, all that allocation is done... */
2179  AST_LIST_HEAD_INIT(interfaces->interface_tree);
2180  AST_LIST_INSERT_TAIL(interfaces->interface_tree, monitor, next);
2181  cc_ref(monitor, "List's reference to extension monitor");
2182  dial_cc_datastore->data = interfaces;
2183  dial_cc_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
2184  interfaces->dial_parent_id = monitor->id;
2185  interfaces->core_id = monitor->core_id = ast_atomic_fetchadd_int(&core_id_counter, +1);
2186  interfaces->is_original_caller = 1;
2187  ast_channel_lock(chan);
2188  ast_channel_datastore_add(chan, dial_cc_datastore);
2189  ast_channel_unlock(chan);
2190  cc_unref(monitor, "Unreffing allocation's reference");
2191  return 0;
2192 }
2193 
2194 /*!
2195  * \internal
2196  * \brief Call a monitor's destructor before the monitor has been allocated
2197  * \since 1.8
2198  *
2199  * \param monitor_type The type of monitor callbacks to use when calling the destructor
2200  * \param private_data Data allocated by a channel driver that must be freed
2201  *
2202  * \details
2203  * I'll admit, this is a bit evil.
2204  *
2205  * When a channel driver determines that it can offer a call completion service to
2206  * a caller, it is very likely that the channel driver will need to allocate some
2207  * data so that when the time comes to request CC, the channel driver will have the
2208  * necessary data at hand.
2209  *
2210  * The problem is that there are many places where failures may occur before the monitor
2211  * has been properly allocated and had its callbacks assigned to it. If one of these
2212  * failures should occur, then we still need to let the channel driver know that it
2213  * must destroy the data that it allocated.
2214  */
2215 static void call_destructor_with_no_monitor(const char * const monitor_type, void *private_data)
2216 {
2217  const struct ast_cc_monitor_callbacks *monitor_callbacks = find_monitor_callbacks(monitor_type);
2218 
2219  if (!monitor_callbacks) {
2220  return;
2221  }
2222 
2223  monitor_callbacks->destructor(private_data);
2224 }
2225 
2226 /*!
2227  * \internal
2228  * \brief Allocate and intitialize a device cc_monitor
2229  *
2230  * For all intents and purposes, this is the same as
2231  * cc_extension_monitor_init, except that there is only
2232  * a single parameter used for naming the interface.
2233  *
2234  * This function is called when handling AST_CONTROL_CC frames.
2235  * The device has reported that CC is possible, so we add it
2236  * to the interface_tree.
2237  *
2238  * Note that it is not necessarily erroneous to add the same
2239  * device to the tree twice. If the same device is called by
2240  * two different extension during the same call, then
2241  * that is a legitimate situation.
2242  *
2243  * \param device_name The name of the device being added to the tree
2244  * \param dialstring The dialstring used to dial the device being added
2245  * \param core_id
2246  * \param cc_data
2247  * \retval NULL Memory allocation failure
2248  * \retval non-NULL The new ast_cc_interface created.
2249  */
2250 static struct ast_cc_monitor *cc_device_monitor_init(const char * const device_name, const char * const dialstring, const struct cc_control_payload *cc_data, int core_id)
2251 {
2252  struct ast_cc_interface *cc_interface;
2253  struct ast_cc_monitor *monitor;
2254  size_t device_name_len = strlen(device_name);
2255  int parent_id = cc_data->parent_interface_id;
2256 
2257  if (!(cc_interface = ao2_t_alloc(sizeof(*cc_interface) + device_name_len, cc_interface_destroy,
2258  "Allocating new ast_cc_interface"))) {
2259  return NULL;
2260  }
2261 
2262  if (!(cc_interface->config_params = ast_cc_config_params_init())) {
2263  cc_unref(cc_interface, "Failed to allocate config params, unref interface");
2264  return NULL;
2265  }
2266 
2267  if (!(monitor = ao2_t_alloc(sizeof(*monitor), cc_monitor_destroy, "Allocating new ast_cc_monitor"))) {
2268  cc_unref(cc_interface, "Failed to allocate monitor, unref interface");
2269  return NULL;
2270  }
2271 
2272  if (!(monitor->dialstring = ast_strdup(dialstring))) {
2273  cc_unref(monitor, "Failed to copy dialable name. Unref monitor");
2274  cc_unref(cc_interface, "Failed to copy dialable name");
2275  return NULL;
2276  }
2277 
2278  if (!(monitor->callbacks = find_monitor_callbacks(cc_data->monitor_type))) {
2279  cc_unref(monitor, "Failed to find monitor callbacks. Unref monitor");
2280  cc_unref(cc_interface, "Failed to find monitor callbacks");
2281  return NULL;
2282  }
2283 
2284  strcpy(cc_interface->device_name, device_name);
2286  monitor->parent_id = parent_id;
2287  monitor->core_id = core_id;
2288  monitor->service_offered = cc_data->service;
2289  monitor->private_data = cc_data->private_data;
2290  cc_interface->monitor_type = cc_data->monitor_type;
2291  cc_interface->monitor_class = AST_CC_DEVICE_MONITOR;
2292  monitor->interface = cc_interface;
2293  monitor->available_timer_id = -1;
2294  ast_cc_copy_config_params(cc_interface->config_params, &cc_data->config_params);
2295  ast_log_dynamic_level(cc_logger_level, "Core %d: Created a device cc interface for '%s' with id %u and parent %u\n",
2296  monitor->core_id, cc_interface->device_name, monitor->id, monitor->parent_id);
2297  return monitor;
2298 }
2299 
2300 /*!
2301  * \details
2302  * Unless we are ignoring CC for some reason, we will always
2303  * call this function when we read an AST_CONTROL_CC frame
2304  * from an outbound channel.
2305  *
2306  * This function will call cc_device_monitor_init to
2307  * create the new cc_monitor for the device from which
2308  * we read the frame. In addition, the new device will be added
2309  * to the monitor tree on the dialed_cc_interfaces datastore
2310  * on the inbound channel.
2311  *
2312  * If this is the first AST_CONTROL_CC frame that we have handled
2313  * for this call, then we will also initialize the CC core for
2314  * this call.
2315  */
2316 void ast_handle_cc_control_frame(struct ast_channel *inbound, struct ast_channel *outbound, void *frame_data)
2317 {
2318  char *device_name;
2319  char *dialstring;
2320  struct ast_cc_monitor *monitor;
2321  struct ast_datastore *cc_datastore;
2322  struct dialed_cc_interfaces *cc_interfaces;
2323  struct cc_control_payload *cc_data = frame_data;
2324  struct cc_core_instance *core_instance;
2325 
2326  device_name = cc_data->device_name;
2327  dialstring = cc_data->dialstring;
2328 
2329  ast_channel_lock(inbound);
2330  if (!(cc_datastore = ast_channel_datastore_find(inbound, &dialed_cc_interfaces_info, NULL))) {
2331  ast_log(LOG_WARNING, "Unable to retrieve CC datastore while processing CC frame from '%s'. CC services will be unavailable.\n", device_name);
2332  ast_channel_unlock(inbound);
2334  return;
2335  }
2336 
2337  cc_interfaces = cc_datastore->data;
2338 
2339  if (cc_interfaces->ignore) {
2340  ast_channel_unlock(inbound);
2342  return;
2343  }
2344 
2345  if (!cc_interfaces->is_original_caller) {
2346  /* If the is_original_caller is not set on the *inbound* channel, then
2347  * it must be a local channel. As such, we do not want to create a core instance
2348  * or an agent for the local channel. Instead, we want to pass this along to the
2349  * other side of the local channel so that the original caller can benefit.
2350  */
2351  ast_channel_unlock(inbound);
2352  ast_indicate_data(inbound, AST_CONTROL_CC, cc_data, sizeof(*cc_data));
2353  return;
2354  }
2355 
2356  core_instance = find_cc_core_instance(cc_interfaces->core_id);
2357  if (!core_instance) {
2358  core_instance = cc_core_init_instance(inbound, cc_interfaces->interface_tree,
2359  cc_interfaces->core_id, cc_data);
2360  if (!core_instance) {
2361  cc_interfaces->ignore = 1;
2362  ast_channel_unlock(inbound);
2364  return;
2365  }
2366  }
2367 
2368  ast_channel_unlock(inbound);
2369 
2370  /* Yeah this kind of sucks, but luckily most people
2371  * aren't dialing thousands of interfaces on every call
2372  *
2373  * This traversal helps us to not create duplicate monitors in
2374  * case a device queues multiple CC control frames.
2375  */
2376  AST_LIST_LOCK(cc_interfaces->interface_tree);
2377  AST_LIST_TRAVERSE(cc_interfaces->interface_tree, monitor, next) {
2378  if (!strcmp(monitor->interface->device_name, device_name)) {
2379  ast_log_dynamic_level(cc_logger_level, "Core %d: Device %s sent us multiple CC control frames. Ignoring those beyond the first.\n",
2380  core_instance->core_id, device_name);
2381  AST_LIST_UNLOCK(cc_interfaces->interface_tree);
2382  cc_unref(core_instance, "Returning early from ast_handle_cc_control_frame. Unref core_instance");
2384  return;
2385  }
2386  }
2387  AST_LIST_UNLOCK(cc_interfaces->interface_tree);
2388 
2389  if (!(monitor = cc_device_monitor_init(device_name, dialstring, cc_data, core_instance->core_id))) {
2390  ast_log(LOG_WARNING, "Unable to create CC device interface for '%s'. CC services will be unavailable on this interface.\n", device_name);
2391  cc_unref(core_instance, "Returning early from ast_handle_cc_control_frame. Unref core_instance");
2393  return;
2394  }
2395 
2396  AST_LIST_LOCK(cc_interfaces->interface_tree);
2397  cc_ref(monitor, "monitor tree's reference to the monitor");
2398  AST_LIST_INSERT_TAIL(cc_interfaces->interface_tree, monitor, next);
2399  AST_LIST_UNLOCK(cc_interfaces->interface_tree);
2400 
2401  cc_extension_monitor_change_is_valid(core_instance, monitor->parent_id, monitor->interface->device_name, 0);
2402 
2403  cc_publish_available(cc_interfaces->core_id, device_name, cc_service_to_string(cc_data->service));
2404 
2405  cc_unref(core_instance, "Done with core_instance after handling CC control frame");
2406  cc_unref(monitor, "Unref reference from allocating monitor");
2407 }
2408 
2409 int ast_cc_call_init(struct ast_channel *chan, int *ignore_cc)
2410 {
2411  /* There are three situations to deal with here:
2412  *
2413  * 1. The channel does not have a dialed_cc_interfaces datastore on
2414  * it. This means that this is the first time that Dial has
2415  * been called. We need to create/initialize the datastore.
2416  *
2417  * 2. The channel does have a cc_interface datastore on it and
2418  * the "ignore" indicator is 0. This means that a Local channel
2419  * was called by a "parent" dial. We can check the datastore's
2420  * parent field to see who the root of this particular dial tree
2421  * is.
2422  *
2423  * 3. The channel does have a cc_interface datastore on it and
2424  * the "ignore" indicator is 1. This means that a second Dial call
2425  * is being made from an extension. In this case, we do not
2426  * want to make any additions/modifications to the datastore. We
2427  * will instead set a flag to indicate that CCSS is completely
2428  * disabled for this Dial attempt.
2429  */
2430 
2431  struct ast_datastore *cc_interfaces_datastore;
2433  struct ast_cc_monitor *monitor;
2434  struct ast_cc_config_params *cc_params;
2435 
2436  ast_channel_lock(chan);
2437 
2438  cc_params = ast_channel_get_cc_config_params(chan);
2439  if (!cc_params) {
2440  ast_channel_unlock(chan);
2441  return -1;
2442  }
2443  if (ast_get_cc_agent_policy(cc_params) == AST_CC_AGENT_NEVER) {
2444  /* We can't offer CC to this caller anyway, so don't bother with CC on this call
2445  */
2446  *ignore_cc = 1;
2447  ast_channel_unlock(chan);
2448  ast_log_dynamic_level(cc_logger_level, "Agent policy for %s is 'never'. CC not possible\n", ast_channel_name(chan));
2449  return 0;
2450  }
2451 
2452  if (!(cc_interfaces_datastore = ast_channel_datastore_find(chan, &dialed_cc_interfaces_info, NULL))) {
2453  /* Situation 1 has occurred */
2454  ast_channel_unlock(chan);
2455  return cc_interfaces_datastore_init(chan);
2456  }
2457  interfaces = cc_interfaces_datastore->data;
2458  ast_channel_unlock(chan);
2459 
2460  if (interfaces->ignore) {
2461  /* Situation 3 has occurred */
2462  *ignore_cc = 1;
2463  ast_log_dynamic_level(cc_logger_level, "Datastore is present with ignore flag set. Ignoring CC offers on this call\n");
2464  return 0;
2465  }
2466 
2467  /* Situation 2 has occurred */
2469  S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan)), interfaces->dial_parent_id))) {
2470  return -1;
2471  }
2472  monitor->core_id = interfaces->core_id;
2473  AST_LIST_LOCK(interfaces->interface_tree);
2474  cc_ref(monitor, "monitor tree's reference to the monitor");
2475  AST_LIST_INSERT_TAIL(interfaces->interface_tree, monitor, next);
2476  AST_LIST_UNLOCK(interfaces->interface_tree);
2477  interfaces->dial_parent_id = monitor->id;
2478  cc_unref(monitor, "Unref monitor's allocation reference");
2479  return 0;
2480 }
2481 
2483 {
2485 }
2486 
2488 {
2489  struct ast_datastore *datastore;
2490  struct dialed_cc_interfaces *cc_interfaces;
2491  int core_id_return;
2492 
2493  ast_channel_lock(chan);
2494  if (!(datastore = ast_channel_datastore_find(chan, &dialed_cc_interfaces_info, NULL))) {
2495  ast_channel_unlock(chan);
2496  return -1;
2497  }
2498 
2499  cc_interfaces = datastore->data;
2500  core_id_return = cc_interfaces->ignore ? -1 : cc_interfaces->core_id;
2501  ast_channel_unlock(chan);
2502  return core_id_return;
2503 
2504 }
2505 
2506 static long count_agents(const char * const caller, const int core_id_exception)
2507 {
2509 
2510  ao2_t_callback_data(cc_core_instances, OBJ_NODATA, count_agents_cb, (char *)caller, &data, "Counting agents");
2511  ast_log_dynamic_level(cc_logger_level, "Counted %d agents\n", data.count);
2512  return data.count;
2513 }
2514 
2515 static void kill_duplicate_offers(char *caller)
2516 {
2517  unsigned long match_flags = MATCH_NO_REQUEST;
2518  struct ao2_iterator *dups_iter;
2519 
2520  /*
2521  * Must remove the ref that was in cc_core_instances outside of
2522  * the container lock to prevent deadlock.
2523  */
2525  match_agent, caller, &match_flags, "Killing duplicate offers");
2526  if (dups_iter) {
2527  /* Now actually unref any duplicate offers by simply destroying the iterator. */
2528  ao2_iterator_destroy(dups_iter);
2529  }
2530 }
2531 
2533 {
2534  ast_assert(callbacks->init != NULL);
2535  ast_assert(callbacks->start_offer_timer != NULL);
2536  ast_assert(callbacks->stop_offer_timer != NULL);
2537  ast_assert(callbacks->respond != NULL);
2538  ast_assert(callbacks->status_request != NULL);
2539  ast_assert(callbacks->start_monitoring != NULL);
2540  ast_assert(callbacks->callee_available != NULL);
2541  ast_assert(callbacks->destructor != NULL);
2542 }
2543 
2544 static void agent_destroy(void *data)
2545 {
2546  struct ast_cc_agent *agent = data;
2547 
2548  if (agent->callbacks) {
2549  agent->callbacks->destructor(agent);
2550  }
2552 }
2553 
2554 static struct ast_cc_agent *cc_agent_init(struct ast_channel *caller_chan,
2555  const char * const caller_name, const int core_id,
2556  struct cc_monitor_tree *interface_tree)
2557 {
2558  struct ast_cc_agent *agent;
2559  struct ast_cc_config_params *cc_params;
2560 
2561  if (!(agent = ao2_t_alloc(sizeof(*agent) + strlen(caller_name), agent_destroy,
2562  "Allocating new ast_cc_agent"))) {
2563  return NULL;
2564  }
2565 
2566  agent->core_id = core_id;
2567  strcpy(agent->device_name, caller_name);
2568 
2569  cc_params = ast_channel_get_cc_config_params(caller_chan);
2570  if (!cc_params) {
2571  cc_unref(agent, "Could not get channel config params.");
2572  return NULL;
2573  }
2574  if (!(agent->cc_params = ast_cc_config_params_init())) {
2575  cc_unref(agent, "Could not init agent config params.");
2576  return NULL;
2577  }
2578  ast_cc_copy_config_params(agent->cc_params, cc_params);
2579 
2580  if (!(agent->callbacks = find_agent_callbacks(caller_chan))) {
2581  cc_unref(agent, "Could not find agent callbacks.");
2582  return NULL;
2583  }
2585 
2586  if (agent->callbacks->init(agent, caller_chan)) {
2587  cc_unref(agent, "Agent init callback failed.");
2588  return NULL;
2589  }
2590  ast_log_dynamic_level(cc_logger_level, "Core %u: Created an agent for caller %s\n",
2591  agent->core_id, agent->device_name);
2592  return agent;
2593 }
2594 
2595 /* Generic agent callbacks */
2596 static int cc_generic_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
2597 static int cc_generic_agent_start_offer_timer(struct ast_cc_agent *agent);
2598 static int cc_generic_agent_stop_offer_timer(struct ast_cc_agent *agent);
2599 static void cc_generic_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
2600 static int cc_generic_agent_status_request(struct ast_cc_agent *agent);
2601 static int cc_generic_agent_stop_ringing(struct ast_cc_agent *agent);
2602 static int cc_generic_agent_start_monitoring(struct ast_cc_agent *agent);
2603 static int cc_generic_agent_recall(struct ast_cc_agent *agent);
2604 static void cc_generic_agent_destructor(struct ast_cc_agent *agent);
2605 
2607  .type = "generic",
2608  .init = cc_generic_agent_init,
2609  .start_offer_timer = cc_generic_agent_start_offer_timer,
2610  .stop_offer_timer = cc_generic_agent_stop_offer_timer,
2611  .respond = cc_generic_agent_respond,
2612  .status_request = cc_generic_agent_status_request,
2613  .stop_ringing = cc_generic_agent_stop_ringing,
2614  .start_monitoring = cc_generic_agent_start_monitoring,
2615  .callee_available = cc_generic_agent_recall,
2616  .destructor = cc_generic_agent_destructor,
2617 };
2618 
2620  /*!
2621  * Subscription to device state
2622  *
2623  * Used in the CC_CALLER_BUSY state. The
2624  * generic agent will subscribe to the
2625  * device state of the caller in order to
2626  * determine when we may move on
2627  */
2629  /*!
2630  * Scheduler id of offer timer.
2631  */
2633  /*!
2634  * Caller ID number
2635  *
2636  * When we re-call the caller, we need
2637  * to provide this information to
2638  * ast_request_and_dial so that the
2639  * information will be present in the
2640  * call to the callee
2641  */
2643  /*!
2644  * Caller ID name
2645  *
2646  * See the description of cid_num.
2647  * The same applies here, except this
2648  * is the caller's name.
2649  */
2651  /*!
2652  * Extension dialed
2653  *
2654  * The original extension dialed. This is used
2655  * so that when performing a recall, we can
2656  * call the proper extension.
2657  */
2659  /*!
2660  * Context dialed
2661  *
2662  * The original context dialed. This is used
2663  * so that when performing a recall, we can
2664  * call into the proper context
2665  */
2667 };
2668 
2669 static int cc_generic_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
2670 {
2671  struct cc_generic_agent_pvt *generic_pvt = ast_calloc(1, sizeof(*generic_pvt));
2672 
2673  if (!generic_pvt) {
2674  return -1;
2675  }
2676 
2677  generic_pvt->offer_timer_id = -1;
2678  if (ast_channel_caller(chan)->id.number.valid && ast_channel_caller(chan)->id.number.str) {
2679  ast_copy_string(generic_pvt->cid_num, ast_channel_caller(chan)->id.number.str, sizeof(generic_pvt->cid_num));
2680  }
2681  if (ast_channel_caller(chan)->id.name.valid && ast_channel_caller(chan)->id.name.str) {
2682  ast_copy_string(generic_pvt->cid_name, ast_channel_caller(chan)->id.name.str, sizeof(generic_pvt->cid_name));
2683  }
2684  ast_copy_string(generic_pvt->exten, S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan)), sizeof(generic_pvt->exten));
2685  ast_copy_string(generic_pvt->context, S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan)), sizeof(generic_pvt->context));
2686  agent->private_data = generic_pvt;
2688  return 0;
2689 }
2690 
2691 static int offer_timer_expire(const void *data)
2692 {
2693  struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
2694  struct cc_generic_agent_pvt *agent_pvt = agent->private_data;
2695  ast_log_dynamic_level(cc_logger_level, "Core %u: Queuing change request because offer timer has expired.\n",
2696  agent->core_id);
2697  agent_pvt->offer_timer_id = -1;
2698  ast_cc_failed(agent->core_id, "Generic agent %s offer timer expired", agent->device_name);
2699  cc_unref(agent, "Remove scheduler's reference to the agent");
2700  return 0;
2701 }
2702 
2704 {
2705  int when;
2706  int sched_id;
2707  struct cc_generic_agent_pvt *generic_pvt = agent->private_data;
2708 
2710  ast_assert(agent->cc_params != NULL);
2711 
2712  when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
2713  ast_log_dynamic_level(cc_logger_level, "Core %u: About to schedule offer timer expiration for %d ms\n",
2714  agent->core_id, when);
2715  if ((sched_id = ast_sched_add(cc_sched_context, when, offer_timer_expire, cc_ref(agent, "Give scheduler an agent ref"))) == -1) {
2716  return -1;
2717  }
2718  generic_pvt->offer_timer_id = sched_id;
2719  return 0;
2720 }
2721 
2723 {
2724  struct cc_generic_agent_pvt *generic_pvt = agent->private_data;
2725 
2726  if (generic_pvt->offer_timer_id != -1) {
2727  if (!ast_sched_del(cc_sched_context, generic_pvt->offer_timer_id)) {
2728  cc_unref(agent, "Remove scheduler's reference to the agent");
2729  }
2730  generic_pvt->offer_timer_id = -1;
2731  }
2732  return 0;
2733 }
2734 
2736 {
2737  /* The generic agent doesn't have to do anything special to
2738  * acknowledge a CC request. Just return.
2739  */
2740  return;
2741 }
2742 
2744 {
2746  return 0;
2747 }
2748 
2750 {
2751  struct ast_channel *recall_chan = ast_channel_get_by_name_prefix(agent->device_name, strlen(agent->device_name));
2752 
2753  if (!recall_chan) {
2754  return 0;
2755  }
2756 
2758  return 0;
2759 }
2760 
2761 static void generic_agent_devstate_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
2762 {
2763  struct ast_cc_agent *agent = userdata;
2764  enum ast_device_state new_state;
2765  struct ast_device_state_message *dev_state;
2766  struct cc_generic_agent_pvt *generic_pvt = agent->private_data;
2767 
2769  cc_unref(agent, "Done holding ref for subscription");
2770  return;
2771  } else if (ast_device_state_message_type() != stasis_message_type(msg)) {
2772  return;
2773  }
2774 
2775  dev_state = stasis_message_data(msg);
2776  if (dev_state->eid) {
2777  /* ignore non-aggregate states */
2778  return;
2779  }
2780 
2781  new_state = dev_state->state;
2782  if (!cc_generic_is_device_available(new_state)) {
2783  /* Not interested in this new state of the device. It is still busy. */
2784  return;
2785  }
2786 
2787  generic_pvt->sub = stasis_unsubscribe(sub);
2788  ast_cc_agent_caller_available(agent->core_id, "%s is no longer busy", agent->device_name);
2789 }
2790 
2792 {
2793  struct cc_generic_agent_pvt *generic_pvt = agent->private_data;
2794  struct ast_str *str = ast_str_alloca(128);
2795  struct stasis_topic *device_specific_topic;
2796 
2797  ast_assert(generic_pvt->sub == NULL);
2798  ast_str_set(&str, 0, "Agent monitoring %s device state since it is busy\n",
2799  agent->device_name);
2800 
2801  device_specific_topic = ast_device_state_topic(agent->device_name);
2802  if (!device_specific_topic) {
2803  return -1;
2804  }
2805 
2806  if (!(generic_pvt->sub = stasis_subscribe(device_specific_topic, generic_agent_devstate_cb, agent))) {
2807  return -1;
2808  }
2812  cc_ref(agent, "Ref agent for subscription");
2813  return 0;
2814 }
2815 
2816 static void *generic_recall(void *data)
2817 {
2818  struct ast_cc_agent *agent = data;
2819  struct cc_generic_agent_pvt *generic_pvt = agent->private_data;
2820  const char *interface = S_OR(ast_get_cc_agent_dialstring(agent->cc_params), ast_strdupa(agent->device_name));
2821  const char *tech;
2822  char *target;
2823  int reason;
2824  struct ast_channel *chan;
2825  const char *callback_macro = ast_get_cc_callback_macro(agent->cc_params);
2826  const char *callback_sub = ast_get_cc_callback_sub(agent->cc_params);
2827  unsigned int recall_timer = ast_get_cc_recall_timer(agent->cc_params) * 1000;
2829 
2830  if (!tmp_cap) {
2831  return NULL;
2832  }
2833 
2834  tech = interface;
2835  if ((target = strchr(interface, '/'))) {
2836  *target++ = '\0';
2837  }
2838 
2840  if (!(chan = ast_request_and_dial(tech, tmp_cap, NULL, NULL, target, recall_timer, &reason, generic_pvt->cid_num, generic_pvt->cid_name))) {
2841  /* Hmm, no channel. Sucks for you, bud.
2842  */
2843  ast_log_dynamic_level(cc_logger_level, "Core %u: Failed to call back %s for reason %d\n",
2844  agent->core_id, agent->device_name, reason);
2845  ast_cc_failed(agent->core_id, "Failed to call back device %s/%s", tech, target);
2846  ao2_ref(tmp_cap, -1);
2847  return NULL;
2848  }
2849  ao2_ref(tmp_cap, -1);
2850 
2851  /* We have a channel. It's time now to set up the datastore of recalled CC interfaces.
2852  * This will be a common task for all recall functions. If it were possible, I'd have
2853  * the core do it automatically, but alas I cannot. Instead, I will provide a public
2854  * function to do so.
2855  */
2856  ast_setup_cc_recall_datastore(chan, agent->core_id);
2858 
2859  ast_channel_exten_set(chan, generic_pvt->exten);
2860  ast_channel_context_set(chan, generic_pvt->context);
2861  ast_channel_priority_set(chan, 1);
2862 
2863  pbx_builtin_setvar_helper(chan, "CC_EXTEN", generic_pvt->exten);
2864  pbx_builtin_setvar_helper(chan, "CC_CONTEXT", generic_pvt->context);
2865 
2866  if (!ast_strlen_zero(callback_macro)) {
2867  ast_log_dynamic_level(cc_logger_level, "Core %u: There's a callback macro configured for agent %s\n",
2868  agent->core_id, agent->device_name);
2869  if (ast_app_exec_macro(NULL, chan, callback_macro)) {
2870  ast_cc_failed(agent->core_id, "Callback macro to %s failed. Maybe a hangup?", agent->device_name);
2871  ast_hangup(chan);
2872  return NULL;
2873  }
2874  }
2875 
2876  if (!ast_strlen_zero(callback_sub)) {
2877  ast_log_dynamic_level(cc_logger_level, "Core %u: There's a callback subroutine configured for agent %s\n",
2878  agent->core_id, agent->device_name);
2879  if (ast_app_exec_sub(NULL, chan, callback_sub, 0)) {
2880  ast_cc_failed(agent->core_id, "Callback subroutine to %s failed. Maybe a hangup?", agent->device_name);
2881  ast_hangup(chan);
2882  return NULL;
2883  }
2884  }
2885  if (ast_pbx_start(chan)) {
2886  ast_cc_failed(agent->core_id, "PBX failed to start for %s.", agent->device_name);
2887  ast_hangup(chan);
2888  return NULL;
2889  }
2890  ast_cc_agent_recalling(agent->core_id, "Generic agent %s is recalling",
2891  agent->device_name);
2892  return NULL;
2893 }
2894 
2895 static int cc_generic_agent_recall(struct ast_cc_agent *agent)
2896 {
2897  pthread_t clotho;
2898  enum ast_device_state current_state = ast_device_state(agent->device_name);
2899 
2900  if (!cc_generic_is_device_available(current_state)) {
2901  /* We can't try to contact the device right now because he's not available
2902  * Let the core know he's busy.
2903  */
2904  ast_cc_agent_caller_busy(agent->core_id, "Generic agent caller %s is busy", agent->device_name);
2905  return 0;
2906  }
2908  return 0;
2909 }
2910 
2911 static void cc_generic_agent_destructor(struct ast_cc_agent *agent)
2912 {
2913  struct cc_generic_agent_pvt *agent_pvt = agent->private_data;
2914 
2915  if (!agent_pvt) {
2916  /* The agent constructor probably failed. */
2917  return;
2918  }
2919 
2921  if (agent_pvt->sub) {
2922  agent_pvt->sub = stasis_unsubscribe(agent_pvt->sub);
2923  }
2924 
2926 }
2927 
2928 static void cc_core_instance_destructor(void *data)
2929 {
2930  struct cc_core_instance *core_instance = data;
2931  ast_log_dynamic_level(cc_logger_level, "Core %d: Destroying core instance\n", core_instance->core_id);
2932  if (core_instance->agent) {
2933  cc_unref(core_instance->agent, "Core instance is done with the agent now");
2934  }
2935  if (core_instance->monitors) {
2936  core_instance->monitors = cc_unref(core_instance->monitors, "Core instance is done with interface list");
2937  }
2938 }
2939 
2940 static struct cc_core_instance *cc_core_init_instance(struct ast_channel *caller_chan,
2941  struct cc_monitor_tree *called_tree, const int core_id, struct cc_control_payload *cc_data)
2942 {
2943  char caller[AST_CHANNEL_NAME];
2944  struct cc_core_instance *core_instance;
2945  struct ast_cc_config_params *cc_params;
2946  long agent_count;
2947  int recall_core_id;
2948 
2949  ast_channel_get_device_name(caller_chan, caller, sizeof(caller));
2950  cc_params = ast_channel_get_cc_config_params(caller_chan);
2951  if (!cc_params) {
2952  ast_log_dynamic_level(cc_logger_level, "Could not get CC parameters for %s\n",
2953  caller);
2954  return NULL;
2955  }
2956  /* First, we need to kill off other pending CC offers from caller. If the caller is going
2957  * to request a CC service, it may only be for the latest call he made.
2958  */
2959  if (ast_get_cc_agent_policy(cc_params) == AST_CC_AGENT_GENERIC) {
2960  kill_duplicate_offers(caller);
2961  }
2962 
2963  ast_cc_is_recall(caller_chan, &recall_core_id, NULL);
2964  agent_count = count_agents(caller, recall_core_id);
2965  if (agent_count >= ast_get_cc_max_agents(cc_params)) {
2966  ast_log_dynamic_level(cc_logger_level, "Caller %s already has the maximum number of agents configured\n", caller);
2967  return NULL;
2968  }
2969 
2970  /* Generic agents can only have a single outstanding CC request per caller. */
2971  if (agent_count > 0 && ast_get_cc_agent_policy(cc_params) == AST_CC_AGENT_GENERIC) {
2972  ast_log_dynamic_level(cc_logger_level, "Generic agents can only have a single outstanding request\n");
2973  return NULL;
2974  }
2975 
2976  /* Next, we need to create the core instance for this call */
2977  if (!(core_instance = ao2_t_alloc(sizeof(*core_instance), cc_core_instance_destructor, "Creating core instance for CC"))) {
2978  return NULL;
2979  }
2980 
2981  core_instance->core_id = core_id;
2982  if (!(core_instance->agent = cc_agent_init(caller_chan, caller, core_instance->core_id, called_tree))) {
2983  cc_unref(core_instance, "Couldn't allocate agent, unref core_instance");
2984  return NULL;
2985  }
2986 
2987  core_instance->monitors = cc_ref(called_tree, "Core instance getting ref to monitor tree");
2988 
2989  ao2_t_link(cc_core_instances, core_instance, "Link core instance into container");
2990 
2991  return core_instance;
2992 }
2993 
2995  struct cc_core_instance *core_instance;/*!< Holds reference to core instance. */
2996  enum cc_state state;
2997  int core_id;
2998  char debug[1];
2999 };
3000 
3001 static int is_state_change_valid(enum cc_state current_state, const enum cc_state new_state, struct ast_cc_agent *agent)
3002 {
3003  int is_valid = 0;
3004  switch (new_state) {
3005  case CC_AVAILABLE:
3006  ast_log_dynamic_level(cc_logger_level, "Core %u: Asked to change to state %u? That should never happen.\n",
3007  agent->core_id, new_state);
3008  break;
3009  case CC_CALLER_OFFERED:
3010  if (current_state == CC_AVAILABLE) {
3011  is_valid = 1;
3012  }
3013  break;
3014  case CC_CALLER_REQUESTED:
3017  is_valid = 1;
3018  }
3019  break;
3020  case CC_ACTIVE:
3022  is_valid = 1;
3023  }
3024  break;
3025  case CC_CALLEE_READY:
3026  if (current_state == CC_ACTIVE) {
3027  is_valid = 1;
3028  }
3029  break;
3030  case CC_CALLER_BUSY:
3031  if (current_state == CC_CALLEE_READY) {
3032  is_valid = 1;
3033  }
3034  break;
3035  case CC_RECALLING:
3036  if (current_state == CC_CALLEE_READY) {
3037  is_valid = 1;
3038  }
3039  break;
3040  case CC_COMPLETE:
3041  if (current_state == CC_RECALLING) {
3042  is_valid = 1;
3043  }
3044  break;
3045  case CC_FAILED:
3046  is_valid = 1;
3047  break;
3048  default:
3049  ast_log_dynamic_level(cc_logger_level, "Core %u: Asked to change to unknown state %u\n",
3050  agent->core_id, new_state);
3051  break;
3052  }
3053 
3054  return is_valid;
3055 }
3056 
3057 static int cc_available(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3058 {
3059  /* This should never happen... */
3060  ast_log(LOG_WARNING, "Someone requested to change to CC_AVAILABLE? Ignoring.\n");
3061  return -1;
3062 }
3063 
3064 static int cc_caller_offered(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3065 {
3066  if (core_instance->agent->callbacks->start_offer_timer(core_instance->agent)) {
3067  ast_cc_failed(core_instance->core_id, "Failed to start the offer timer for %s\n",
3068  core_instance->agent->device_name);
3069  return -1;
3070  }
3071  cc_publish_offertimerstart(core_instance->core_id, core_instance->agent->device_name, core_instance->agent->cc_params->cc_offer_timer);
3072  ast_log_dynamic_level(cc_logger_level, "Core %d: Started the offer timer for the agent %s!\n",
3073  core_instance->core_id, core_instance->agent->device_name);
3074  return 0;
3075 }
3076 
3077 /*!
3078  * \brief check if the core instance has any device monitors
3079  *
3080  * In any case where we end up removing a device monitor from the
3081  * list of device monitors, it is important to see what the state
3082  * of the list is afterwards. If we find that we only have extension
3083  * monitors left, then no devices are actually being monitored.
3084  * In such a case, we need to declare that CC has failed for this
3085  * call. This function helps those cases to determine if they should
3086  * declare failure.
3087  *
3088  * \param core_instance The core instance we are checking for the existence
3089  * of device monitors
3090  * \retval 0 No device monitors exist on this core_instance
3091  * \retval 1 There is still at least 1 device monitor remaining
3092  */
3093 static int has_device_monitors(struct cc_core_instance *core_instance)
3094 {
3095  struct ast_cc_monitor *iter;
3096  int res = 0;
3097 
3098  AST_LIST_TRAVERSE(core_instance->monitors, iter, next) {
3100  res = 1;
3101  break;
3102  }
3103  }
3104 
3105  return res;
3106 }
3107 
3108 static void request_cc(struct cc_core_instance *core_instance)
3109 {
3110  struct ast_cc_monitor *monitor_iter;
3111  AST_LIST_LOCK(core_instance->monitors);
3112  AST_LIST_TRAVERSE_SAFE_BEGIN(core_instance->monitors, monitor_iter, next) {
3113  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
3114  if (monitor_iter->callbacks->request_cc(monitor_iter, &monitor_iter->available_timer_id)) {
3116  cc_extension_monitor_change_is_valid(core_instance, monitor_iter->parent_id,
3117  monitor_iter->interface->device_name, 1);
3118  cc_unref(monitor_iter, "request_cc failed. Unref list's reference to monitor");
3119  } else {
3120  cc_publish_requested(core_instance->core_id, core_instance->agent->device_name, monitor_iter->interface->device_name);
3121  }
3122  }
3123  }
3125 
3126  if (!has_device_monitors(core_instance)) {
3127  ast_cc_failed(core_instance->core_id, "All device monitors failed to request CC");
3128  }
3129  AST_LIST_UNLOCK(core_instance->monitors);
3130 }
3131 
3132 static int cc_caller_requested(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3133 {
3135  ast_log(LOG_WARNING, "Cannot request CC since there is no more room for requests\n");
3136  core_instance->agent->callbacks->respond(core_instance->agent,
3138  ast_cc_failed(core_instance->core_id, "Too many requests in the system");
3139  return -1;
3140  }
3141  core_instance->agent->callbacks->stop_offer_timer(core_instance->agent);
3142  request_cc(core_instance);
3143  return 0;
3144 }
3145 
3146 static void unsuspend(struct cc_core_instance *core_instance)
3147 {
3148  struct ast_cc_monitor *monitor_iter;
3149  AST_LIST_LOCK(core_instance->monitors);
3150  AST_LIST_TRAVERSE_SAFE_BEGIN(core_instance->monitors, monitor_iter, next) {
3151  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
3152  if (monitor_iter->callbacks->unsuspend(monitor_iter)) {
3154  cc_extension_monitor_change_is_valid(core_instance, monitor_iter->parent_id,
3155  monitor_iter->interface->device_name, 1);
3156  cc_unref(monitor_iter, "unsuspend failed. Unref list's reference to monitor");
3157  }
3158  }
3159  }
3161 
3162  if (!has_device_monitors(core_instance)) {
3163  ast_cc_failed(core_instance->core_id, "All device monitors failed to unsuspend CC");
3164  }
3165  AST_LIST_UNLOCK(core_instance->monitors);
3166 }
3167 
3168 static int cc_active(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3169 {
3170  /* Either
3171  * 1. Callee accepted CC request, call agent's ack callback.
3172  * 2. Caller became available, call agent's stop_monitoring callback and
3173  * call monitor's unsuspend callback.
3174  */
3175  if (previous_state == CC_CALLER_REQUESTED) {
3176  core_instance->agent->callbacks->respond(core_instance->agent,
3178  cc_publish_requestacknowledged(core_instance->core_id, core_instance->agent->device_name);
3179  } else if (previous_state == CC_CALLER_BUSY) {
3180  cc_publish_callerstopmonitoring(core_instance->core_id, core_instance->agent->device_name);
3181  unsuspend(core_instance);
3182  }
3183  /* Not possible for previous_state to be anything else due to the is_state_change_valid check at the beginning */
3184  return 0;
3185 }
3186 
3187 static int cc_callee_ready(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3188 {
3189  core_instance->agent->callbacks->callee_available(core_instance->agent);
3190  return 0;
3191 }
3192 
3193 static void suspend(struct cc_core_instance *core_instance)
3194 {
3195  struct ast_cc_monitor *monitor_iter;
3196  AST_LIST_LOCK(core_instance->monitors);
3197  AST_LIST_TRAVERSE_SAFE_BEGIN(core_instance->monitors, monitor_iter, next) {
3198  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
3199  if (monitor_iter->callbacks->suspend(monitor_iter)) {
3201  cc_extension_monitor_change_is_valid(core_instance, monitor_iter->parent_id,
3202  monitor_iter->interface->device_name, 1);
3203  cc_unref(monitor_iter, "suspend failed. Unref list's reference to monitor");
3204  }
3205  }
3206  }
3208 
3209  if (!has_device_monitors(core_instance)) {
3210  ast_cc_failed(core_instance->core_id, "All device monitors failed to suspend CC");
3211  }
3212  AST_LIST_UNLOCK(core_instance->monitors);
3213 }
3214 
3215 static int cc_caller_busy(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3216 {
3217  /* Callee was available, but caller was busy, call agent's begin_monitoring callback
3218  * and call monitor's suspend callback.
3219  */
3220  suspend(core_instance);
3221  core_instance->agent->callbacks->start_monitoring(core_instance->agent);
3222  cc_publish_callerstartmonitoring(core_instance->core_id, core_instance->agent->device_name);
3223  return 0;
3224 }
3225 
3226 static void cancel_available_timer(struct cc_core_instance *core_instance)
3227 {
3228  struct ast_cc_monitor *monitor_iter;
3229  AST_LIST_LOCK(core_instance->monitors);
3230  AST_LIST_TRAVERSE_SAFE_BEGIN(core_instance->monitors, monitor_iter, next) {
3231  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
3232  if (monitor_iter->callbacks->cancel_available_timer(monitor_iter, &monitor_iter->available_timer_id)) {
3234  cc_extension_monitor_change_is_valid(core_instance, monitor_iter->parent_id,
3235  monitor_iter->interface->device_name, 1);
3236  cc_unref(monitor_iter, "cancel_available_timer failed. Unref list's reference to monitor");
3237  }
3238  }
3239  }
3241 
3242  if (!has_device_monitors(core_instance)) {
3243  ast_cc_failed(core_instance->core_id, "All device monitors failed to cancel their available timers");
3244  }
3245  AST_LIST_UNLOCK(core_instance->monitors);
3246 }
3247 
3248 static int cc_recalling(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3249 {
3250  /* Both caller and callee are available, call agent's recall callback
3251  */
3252  cancel_available_timer(core_instance);
3253  cc_publish_callerrecalling(core_instance->core_id, core_instance->agent->device_name);
3254  return 0;
3255 }
3256 
3257 static int cc_complete(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3258 {
3259  /* Recall has made progress, call agent and monitor destructor functions
3260  */
3261  cc_publish_recallcomplete(core_instance->core_id, core_instance->agent->device_name);
3262  ao2_t_unlink(cc_core_instances, core_instance, "Unlink core instance since CC recall has completed");
3263  return 0;
3264 }
3265 
3266 static int cc_failed(struct cc_core_instance *core_instance, struct cc_state_change_args *args, enum cc_state previous_state)
3267 {
3268  cc_publish_failure(core_instance->core_id, core_instance->agent->device_name, args->debug);
3269  ao2_t_unlink(cc_core_instances, core_instance, "Unlink core instance since CC failed");
3270  return 0;
3271 }
3272 
3273 static int (* const state_change_funcs [])(struct cc_core_instance *, struct cc_state_change_args *, enum cc_state previous_state) = {
3277  [CC_ACTIVE] = cc_active,
3282  [CC_FAILED] = cc_failed,
3283 };
3284 
3285 static int cc_do_state_change(void *datap)
3286 {
3287  struct cc_state_change_args *args = datap;
3288  struct cc_core_instance *core_instance;
3289  enum cc_state previous_state;
3290  int res;
3291 
3292  ast_log_dynamic_level(cc_logger_level, "Core %d: State change to %u requested. Reason: %s\n",
3293  args->core_id, args->state, args->debug);
3294 
3295  core_instance = args->core_instance;
3296 
3297  if (!is_state_change_valid(core_instance->current_state, args->state, core_instance->agent)) {
3298  ast_log_dynamic_level(cc_logger_level, "Core %d: Invalid state change requested. Cannot go from %s to %s\n",
3299  args->core_id, cc_state_to_string(core_instance->current_state), cc_state_to_string(args->state));
3300  if (args->state == CC_CALLER_REQUESTED) {
3301  /*
3302  * For out-of-order requests, we need to let the requester know that
3303  * we can't handle the request now.
3304  */
3305  core_instance->agent->callbacks->respond(core_instance->agent,
3307  }
3308  ast_free(args);
3309  cc_unref(core_instance, "Unref core instance from when it was found earlier");
3310  return -1;
3311  }
3312 
3313  /* We can change to the new state now. */
3314  previous_state = core_instance->current_state;
3315  core_instance->current_state = args->state;
3316  res = state_change_funcs[core_instance->current_state](core_instance, args, previous_state);
3317 
3318  /* If state change successful then notify any device state watchers of the change */
3319  if (!res && !strcmp(core_instance->agent->callbacks->type, "generic")) {
3320  ccss_notify_device_state_change(core_instance->agent->device_name, core_instance->current_state);
3321  }
3322 
3323  ast_free(args);
3324  cc_unref(core_instance, "Unref since state change has completed"); /* From ao2_find */
3325  return res;
3326 }
3327 
3328 static int cc_request_state_change(enum cc_state state, const int core_id, const char *debug, va_list ap)
3329 {
3330  int res;
3331  int debuglen;
3332  char dummy[1];
3333  va_list aq;
3334  struct cc_core_instance *core_instance;
3335  struct cc_state_change_args *args;
3336  /* This initial call to vsnprintf is simply to find what the
3337  * size of the string needs to be
3338  */
3339  va_copy(aq, ap);
3340  /* We add 1 to the result since vsnprintf's return does not
3341  * include the terminating null byte
3342  */
3343  debuglen = vsnprintf(dummy, sizeof(dummy), debug, aq) + 1;
3344  va_end(aq);
3345 
3346  if (!(args = ast_calloc(1, sizeof(*args) + debuglen))) {
3347  return -1;
3348  }
3349 
3351  if (!core_instance) {
3352  ast_log_dynamic_level(cc_logger_level, "Core %d: Unable to find core instance.\n",
3353  core_id);
3354  ast_free(args);
3355  return -1;
3356  }
3357 
3358  args->core_instance = core_instance;
3359  args->state = state;
3360  args->core_id = core_id;
3361  vsnprintf(args->debug, debuglen, debug, ap);
3362 
3364  if (res) {
3365  cc_unref(core_instance, "Unref core instance. ast_taskprocessor_push failed");
3366  ast_free(args);
3367  }
3368  return res;
3369 }
3370 
3372  int core_id;
3373  char ignore;
3374  char nested;
3376 };
3377 
3378 static void *cc_recall_ds_duplicate(void *data)
3379 {
3380  struct cc_recall_ds_data *old_data = data;
3381  struct cc_recall_ds_data *new_data = ast_calloc(1, sizeof(*new_data));
3382 
3383  if (!new_data) {
3384  return NULL;
3385  }
3386  new_data->interface_tree = cc_ref(old_data->interface_tree, "Bump refcount of monitor tree for recall datastore duplicate");
3387  new_data->core_id = old_data->core_id;
3388  new_data->nested = 1;
3389  return new_data;
3390 }
3391 
3392 static void cc_recall_ds_destroy(void *data)
3393 {
3394  struct cc_recall_ds_data *recall_data = data;
3395  recall_data->interface_tree = cc_unref(recall_data->interface_tree, "Unref recall monitor tree");
3396  ast_free(recall_data);
3397 }
3398 
3399 static const struct ast_datastore_info recall_ds_info = {
3400  .type = "cc_recall",
3401  .duplicate = cc_recall_ds_duplicate,
3402  .destroy = cc_recall_ds_destroy,
3403 };
3404 
3405 int ast_setup_cc_recall_datastore(struct ast_channel *chan, const int core_id)
3406 {
3407  struct ast_datastore *recall_datastore = ast_datastore_alloc(&recall_ds_info, NULL);
3408  struct cc_recall_ds_data *recall_data;
3409  struct cc_core_instance *core_instance;
3410 
3411  if (!recall_datastore) {
3412  return -1;
3413  }
3414 
3415  if (!(recall_data = ast_calloc(1, sizeof(*recall_data)))) {
3416  ast_datastore_free(recall_datastore);
3417  return -1;
3418  }
3419 
3420  if (!(core_instance = find_cc_core_instance(core_id))) {
3421  ast_free(recall_data);
3422  ast_datastore_free(recall_datastore);
3423  return -1;
3424  }
3425 
3426  recall_data->interface_tree = cc_ref(core_instance->monitors,
3427  "Bump refcount for monitor tree for recall datastore");
3428  recall_data->core_id = core_id;
3429  recall_datastore->data = recall_data;
3430  recall_datastore->inheritance = DATASTORE_INHERIT_FOREVER;
3431  ast_channel_lock(chan);
3432  ast_channel_datastore_add(chan, recall_datastore);
3433  ast_channel_unlock(chan);
3434  cc_unref(core_instance, "Recall datastore set up. No need for core_instance ref");
3435  return 0;
3436 }
3437 
3438 int ast_cc_is_recall(struct ast_channel *chan, int *core_id, const char * const monitor_type)
3439 {
3440  struct ast_datastore *recall_datastore;
3441  struct cc_recall_ds_data *recall_data;
3442  struct cc_monitor_tree *interface_tree;
3443  char device_name[AST_CHANNEL_NAME];
3444  struct ast_cc_monitor *device_monitor;
3445  int core_id_candidate;
3446 
3447  ast_assert(core_id != NULL);
3448 
3449  *core_id = -1;
3450 
3451  ast_channel_lock(chan);
3452  if (!(recall_datastore = ast_channel_datastore_find(chan, &recall_ds_info, NULL))) {
3453  /* Obviously not a recall if the datastore isn't present */
3454  ast_channel_unlock(chan);
3455  return 0;
3456  }
3457 
3458  recall_data = recall_datastore->data;
3459 
3460  if (recall_data->ignore) {
3461  /* Though this is a recall, the call to this particular interface is not part of the
3462  * recall either because this is a call forward or because this is not the first
3463  * invocation of Dial during this call
3464  */
3465  ast_channel_unlock(chan);
3466  return 0;
3467  }
3468 
3469  if (!recall_data->nested) {
3470  /* If the nested flag is not set, then this means that
3471  * the channel passed to this function is the caller making
3472  * the recall. This means that we shouldn't look through
3473  * the monitor tree for the channel because it shouldn't be
3474  * there. However, this is a recall though, so return true.
3475  */
3476  *core_id = recall_data->core_id;
3477  ast_channel_unlock(chan);
3478  return 1;
3479  }
3480 
3481  if (ast_strlen_zero(monitor_type)) {
3482  /* If someone passed a NULL or empty monitor type, then it is clear
3483  * the channel they passed in was an incoming channel, and so searching
3484  * the list of dialed interfaces is not going to be helpful. Just return
3485  * false immediately.
3486  */
3487  ast_channel_unlock(chan);
3488  return 0;
3489  }
3490 
3491  interface_tree = recall_data->interface_tree;
3492  ast_channel_get_device_name(chan, device_name, sizeof(device_name));
3493  /* We grab the value of the recall_data->core_id so that we
3494  * can unlock the channel before we start looking through the
3495  * interface list. That way we don't have to worry about a possible
3496  * clash between the channel lock and the monitor tree lock.
3497  */
3498  core_id_candidate = recall_data->core_id;
3499  ast_channel_unlock(chan);
3500 
3501  /*
3502  * Now we need to find out if the channel device name
3503  * is in the list of interfaces in the called tree.
3504  */
3505  AST_LIST_LOCK(interface_tree);
3506  AST_LIST_TRAVERSE(interface_tree, device_monitor, next) {
3507  if (!strcmp(device_monitor->interface->device_name, device_name) &&
3508  !strcmp(device_monitor->interface->monitor_type, monitor_type)) {
3509  /* BOOM! Device is in the tree! We have a winner! */
3510  *core_id = core_id_candidate;
3511  AST_LIST_UNLOCK(interface_tree);
3512  return 1;
3513  }
3514  }
3515  AST_LIST_UNLOCK(interface_tree);
3516  return 0;
3517 }
3518 
3519 struct ast_cc_monitor *ast_cc_get_monitor_by_recall_core_id(const int core_id, const char * const device_name)
3520 {
3521  struct cc_core_instance *core_instance = find_cc_core_instance(core_id);
3522  struct ast_cc_monitor *monitor_iter;
3523 
3524  if (!core_instance) {
3525  return NULL;
3526  }
3527 
3528  AST_LIST_LOCK(core_instance->monitors);
3529  AST_LIST_TRAVERSE(core_instance->monitors, monitor_iter, next) {
3530  if (!strcmp(monitor_iter->interface->device_name, device_name)) {
3531  /* Found a monitor. */
3532  cc_ref(monitor_iter, "Hand the requester of the monitor a reference");
3533  break;
3534  }
3535  }
3536  AST_LIST_UNLOCK(core_instance->monitors);
3537  cc_unref(core_instance, "Done with core instance ref in ast_cc_get_monitor_by_recall_core_id");
3538  return monitor_iter;
3539 }
3540 
3541 /*!
3542  * \internal
3543  * \brief uniquely append a dialstring to our CC_INTERFACES chanvar string.
3544  *
3545  * We will only append a string if it has not already appeared in our channel
3546  * variable earlier. We ensure that we don't erroneously match substrings by
3547  * adding an ampersand to the end of our potential dialstring and searching for
3548  * it plus the ampersand in our variable.
3549  *
3550  * It's important to note that once we have built the full CC_INTERFACES string,
3551  * there will be an extra ampersand at the end which must be stripped off by
3552  * the caller of this function.
3553  *
3554  * \param str An ast_str holding what we will add to CC_INTERFACES
3555  * \param dialstring A new dialstring to add
3556  */
3557 static void cc_unique_append(struct ast_str **str, const char *dialstring)
3558 {
3559  char dialstring_search[AST_CHANNEL_NAME + 1];
3560 
3561  if (ast_strlen_zero(dialstring)) {
3562  /* No dialstring to append. */
3563  return;
3564  }
3565  snprintf(dialstring_search, sizeof(dialstring_search), "%s%c", dialstring, '&');
3566  if (strstr(ast_str_buffer(*str), dialstring_search)) {
3567  return;
3568  }
3569  ast_str_append(str, 0, "%s", dialstring_search);
3570 }
3571 
3572 /*!
3573  * \internal
3574  * \brief Build the CC_INTERFACES channel variable
3575  *
3576  * The method used is to traverse the child dialstrings in the
3577  * passed-in extension monitor, adding any that have the is_valid
3578  * flag set. Then, traverse the monitors, finding all children
3579  * of the starting extension monitor and adding their dialstrings
3580  * as well.
3581  *
3582  * \param starting_point The extension monitor that is the parent to all
3583  * monitors whose dialstrings should be added to CC_INTERFACES
3584  * \param str Where we will store CC_INTERFACES
3585  */
3586 static void build_cc_interfaces_chanvar(struct ast_cc_monitor *starting_point, struct ast_str **str)
3587 {
3588  struct extension_monitor_pvt *extension_pvt;
3589  struct extension_child_dialstring *child_dialstring;
3590  struct ast_cc_monitor *monitor_iter = starting_point;
3591  int top_level_id = starting_point->id;
3592  size_t length;
3593 
3594  /* Init to an empty string. */
3595  ast_str_truncate(*str, 0);
3596 
3597  /* First we need to take all of the is_valid child_dialstrings from
3598  * the extension monitor we found and add them to the CC_INTERFACES
3599  * chanvar
3600  */
3601  extension_pvt = starting_point->private_data;
3602  AST_LIST_TRAVERSE(&extension_pvt->child_dialstrings, child_dialstring, next) {
3603  if (child_dialstring->is_valid) {
3604  cc_unique_append(str, child_dialstring->original_dialstring);
3605  }
3606  }
3607 
3608  /* And now we get the dialstrings from each of the device monitors */
3609  while ((monitor_iter = AST_LIST_NEXT(monitor_iter, next))) {
3610  if (monitor_iter->parent_id == top_level_id) {
3611  cc_unique_append(str, monitor_iter->dialstring);
3612  }
3613  }
3614 
3615  /* str will have an extra '&' tacked onto the end of it, so we need
3616  * to get rid of that.
3617  */
3618  length = ast_str_strlen(*str);
3619  if (length) {
3620  ast_str_truncate(*str, length - 1);
3621  }
3622  if (length <= 1) {
3623  /* Nothing to recall? This should not happen. */
3624  ast_log(LOG_ERROR, "CC_INTERFACES is empty. starting device_name:'%s'\n",
3625  starting_point->interface->device_name);
3626  }
3627 }
3628 
3630 {
3631  struct ast_datastore *recall_datastore;
3632  struct cc_monitor_tree *interface_tree;
3633  struct ast_cc_monitor *monitor;
3634  struct cc_recall_ds_data *recall_data;
3635  struct ast_str *str = ast_str_create(64);
3636  int core_id;
3637 
3638  if (!str) {
3639  return -1;
3640  }
3641 
3642  ast_channel_lock(chan);
3643  if (!(recall_datastore = ast_channel_datastore_find(chan, &recall_ds_info, NULL))) {
3644  ast_channel_unlock(chan);
3645  ast_free(str);
3646  return -1;
3647  }
3648  recall_data = recall_datastore->data;
3649  interface_tree = recall_data->interface_tree;
3650  core_id = recall_data->core_id;
3651  ast_channel_unlock(chan);
3652 
3653  AST_LIST_LOCK(interface_tree);
3654  monitor = AST_LIST_FIRST(interface_tree);
3655  build_cc_interfaces_chanvar(monitor, &str);
3656  AST_LIST_UNLOCK(interface_tree);
3657 
3658  pbx_builtin_setvar_helper(chan, "CC_INTERFACES", ast_str_buffer(str));
3659  ast_log_dynamic_level(cc_logger_level, "Core %d: CC_INTERFACES set to %s\n",
3660  core_id, ast_str_buffer(str));
3661 
3662  ast_free(str);
3663  return 0;
3664 }
3665 
3666 int ast_set_cc_interfaces_chanvar(struct ast_channel *chan, const char * const extension)
3667 {
3668  struct ast_datastore *recall_datastore;
3669  struct cc_monitor_tree *interface_tree;
3670  struct ast_cc_monitor *monitor_iter;
3671  struct cc_recall_ds_data *recall_data;
3672  struct ast_str *str = ast_str_create(64);
3673  int core_id;
3674 
3675  if (!str) {
3676  return -1;
3677  }
3678 
3679  ast_channel_lock(chan);
3680  if (!(recall_datastore = ast_channel_datastore_find(chan, &recall_ds_info, NULL))) {
3681  ast_channel_unlock(chan);
3682  ast_free(str);
3683  return -1;
3684  }
3685  recall_data = recall_datastore->data;
3686  interface_tree = recall_data->interface_tree;
3687  core_id = recall_data->core_id;
3688  ast_channel_unlock(chan);
3689 
3690  AST_LIST_LOCK(interface_tree);
3691  AST_LIST_TRAVERSE(interface_tree, monitor_iter, next) {
3692  if (!strcmp(monitor_iter->interface->device_name, extension)) {
3693  break;
3694  }
3695  }
3696 
3697  if (!monitor_iter) {
3698  /* We couldn't find this extension. This may be because
3699  * we have been directed into an unexpected extension because
3700  * the admin has changed a CC_INTERFACES variable at some point.
3701  */
3702  AST_LIST_UNLOCK(interface_tree);
3703  ast_free(str);
3704  return -1;
3705  }
3706 
3707  build_cc_interfaces_chanvar(monitor_iter, &str);
3708  AST_LIST_UNLOCK(interface_tree);
3709 
3710  pbx_builtin_setvar_helper(chan, "CC_INTERFACES", ast_str_buffer(str));
3711  ast_log_dynamic_level(cc_logger_level, "Core %d: CC_INTERFACES set to %s\n",
3712  core_id, ast_str_buffer(str));
3713 
3714  ast_free(str);
3715  return 0;
3716 }
3717 
3718 void ast_ignore_cc(struct ast_channel *chan)
3719 {
3720  struct ast_datastore *cc_datastore;
3721  struct ast_datastore *cc_recall_datastore;
3722  struct dialed_cc_interfaces *cc_interfaces;
3723  struct cc_recall_ds_data *recall_cc_data;
3724 
3725  ast_channel_lock(chan);
3726  if ((cc_datastore = ast_channel_datastore_find(chan, &dialed_cc_interfaces_info, NULL))) {
3727  cc_interfaces = cc_datastore->data;
3728  cc_interfaces->ignore = 1;
3729  }
3730 
3731  if ((cc_recall_datastore = ast_channel_datastore_find(chan, &recall_ds_info, NULL))) {
3732  recall_cc_data = cc_recall_datastore->data;
3733  recall_cc_data->ignore = 1;
3734  }
3735  ast_channel_unlock(chan);
3736 }
3737 
3738 static __attribute__((format(printf, 2, 3))) int cc_offer(const int core_id, const char * const debug, ...)
3739 {
3740  va_list ap;
3741  int res;
3742 
3743  va_start(ap, debug);
3745  va_end(ap);
3746  return res;
3747 }
3748 
3749 int ast_cc_offer(struct ast_channel *caller_chan)
3750 {
3751  int core_id;
3752  int res = -1;
3753  struct ast_datastore *datastore;
3754  struct dialed_cc_interfaces *cc_interfaces;
3755  char cc_is_offerable;
3756 
3757  ast_channel_lock(caller_chan);
3758  if (!(datastore = ast_channel_datastore_find(caller_chan, &dialed_cc_interfaces_info, NULL))) {
3759  ast_channel_unlock(caller_chan);
3760  return res;
3761  }
3762 
3763  cc_interfaces = datastore->data;
3764  cc_is_offerable = cc_interfaces->is_original_caller;
3765  core_id = cc_interfaces->core_id;
3766  ast_channel_unlock(caller_chan);
3767 
3768  if (cc_is_offerable) {
3769  res = cc_offer(core_id, "CC offered to caller %s", ast_channel_name(caller_chan));
3770  }
3771  return res;
3772 }
3773 
3774 int ast_cc_agent_accept_request(int core_id, const char * const debug, ...)
3775 {
3776  va_list ap;
3777  int res;
3778 
3779  va_start(ap, debug);
3781  va_end(ap);
3782  return res;
3783 }
3784 
3785 int ast_cc_monitor_request_acked(int core_id, const char * const debug, ...)
3786 {
3787  va_list ap;
3788  int res;
3789 
3790  va_start(ap, debug);
3792  va_end(ap);
3793  return res;
3794 }
3795 
3796 int ast_cc_monitor_callee_available(const int core_id, const char * const debug, ...)
3797 {
3798  va_list ap;
3799  int res;
3800 
3801  va_start(ap, debug);
3803  va_end(ap);
3804  return res;
3805 }
3806 
3807 int ast_cc_agent_caller_busy(int core_id, const char * debug, ...)
3808 {
3809  va_list ap;
3810  int res;
3811 
3812  va_start(ap, debug);
3814  va_end(ap);
3815  return res;
3816 }
3817 
3818 int ast_cc_agent_caller_available(int core_id, const char * const debug, ...)
3819 {
3820  va_list ap;
3821  int res;
3822 
3823  va_start(ap, debug);
3825  va_end(ap);
3826  return res;
3827 }
3828 
3829 int ast_cc_agent_recalling(int core_id, const char * const debug, ...)
3830 {
3831  va_list ap;
3832  int res;
3833 
3834  va_start(ap, debug);
3836  va_end(ap);
3837  return res;
3838 }
3839 
3840 int ast_cc_completed(struct ast_channel *chan, const char * const debug, ...)
3841 {
3842  struct ast_datastore *recall_datastore;
3843  struct cc_recall_ds_data *recall_data;
3844  int core_id;
3845  va_list ap;
3846  int res;
3847 
3848  ast_channel_lock(chan);
3849  if (!(recall_datastore = ast_channel_datastore_find(chan, &recall_ds_info, NULL))) {
3850  /* Silly! Why did you call this function if there's no recall DS? */
3851  ast_channel_unlock(chan);
3852  return -1;
3853  }
3854  recall_data = recall_datastore->data;
3855  if (recall_data->nested || recall_data->ignore) {
3856  /* If this is being called from a nested Dial, it is too
3857  * early to determine if the recall has actually completed.
3858  * The outermost dial is the only one with the authority to
3859  * declare the recall to be complete.
3860  *
3861  * Similarly, if this function has been called when the
3862  * recall has progressed beyond the first dial, this is not
3863  * a legitimate time to declare the recall to be done. In fact,
3864  * that should have been done already.
3865  */
3866  ast_channel_unlock(chan);
3867  return -1;
3868  }
3869  core_id = recall_data->core_id;
3870  ast_channel_unlock(chan);
3871  va_start(ap, debug);
3873  va_end(ap);
3874  return res;
3875 }
3876 
3877 int ast_cc_failed(int core_id, const char * const debug, ...)
3878 {
3879  va_list ap;
3880  int res;
3881 
3882  va_start(ap, debug);
3884  va_end(ap);
3885  return res;
3886 }
3887 
3889  const char *device_name;
3890  char *debug;
3891  int core_id;
3892 };
3893 
3894 static int cc_monitor_failed(void *data)
3895 {
3896  struct ast_cc_monitor_failure_data *failure_data = data;
3897  struct cc_core_instance *core_instance;
3898  struct ast_cc_monitor *monitor_iter;
3899 
3900  core_instance = find_cc_core_instance(failure_data->core_id);
3901  if (!core_instance) {
3902  /* Core instance no longer exists or invalid core_id. */
3904  "Core %d: Could not find core instance for device %s '%s'\n",
3905  failure_data->core_id, failure_data->device_name, failure_data->debug);
3906  ast_free((char *) failure_data->device_name);
3907  ast_free((char *) failure_data->debug);
3908  ast_free(failure_data);
3909  return -1;
3910  }
3911 
3912  AST_LIST_LOCK(core_instance->monitors);
3913  AST_LIST_TRAVERSE_SAFE_BEGIN(core_instance->monitors, monitor_iter, next) {
3914  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
3915  if (!strcmp(monitor_iter->interface->device_name, failure_data->device_name)) {
3917  cc_extension_monitor_change_is_valid(core_instance, monitor_iter->parent_id,
3918  monitor_iter->interface->device_name, 1);
3919  monitor_iter->callbacks->cancel_available_timer(monitor_iter, &monitor_iter->available_timer_id);
3920  cc_publish_monitorfailed(monitor_iter->core_id, monitor_iter->interface->device_name);
3921  cc_unref(monitor_iter, "Monitor reported failure. Unref list's reference.");
3922  }
3923  }
3924  }
3926 
3927  if (!has_device_monitors(core_instance)) {
3928  ast_cc_failed(core_instance->core_id, "All monitors have failed\n");
3929  }
3930  AST_LIST_UNLOCK(core_instance->monitors);
3931  cc_unref(core_instance, "Finished with core_instance in cc_monitor_failed\n");
3932 
3933  ast_free((char *) failure_data->device_name);
3934  ast_free((char *) failure_data->debug);
3935  ast_free(failure_data);
3936  return 0;
3937 }
3938 
3939 int ast_cc_monitor_failed(int core_id, const char *const monitor_name, const char * const debug, ...)
3940 {
3941  struct ast_cc_monitor_failure_data *failure_data;
3942  int res;
3943  va_list ap;
3944 
3945  if (!(failure_data = ast_calloc(1, sizeof(*failure_data)))) {
3946  return -1;
3947  }
3948 
3949  if (!(failure_data->device_name = ast_strdup(monitor_name))) {
3950  ast_free(failure_data);
3951  return -1;
3952  }
3953 
3954  va_start(ap, debug);
3955  if (ast_vasprintf(&failure_data->debug, debug, ap) == -1) {
3956  va_end(ap);
3957  ast_free((char *)failure_data->device_name);
3958  ast_free(failure_data);
3959  return -1;
3960  }
3961  va_end(ap);
3962 
3963  failure_data->core_id = core_id;
3964 
3966  if (res) {
3967  ast_free((char *)failure_data->device_name);
3968  ast_free((char *)failure_data->debug);
3969  ast_free(failure_data);
3970  }
3971  return res;
3972 }
3973 
3974 static int cc_status_request(void *data)
3975 {
3976  struct cc_core_instance *core_instance= data;
3977  int res;
3978 
3979  res = core_instance->agent->callbacks->status_request(core_instance->agent);
3980  cc_unref(core_instance, "Status request finished. Unref core instance");
3981  return res;
3982 }
3983 
3985 {
3986  int res;
3987  struct cc_core_instance *core_instance = find_cc_core_instance(core_id);
3988 
3989  if (!core_instance) {
3990  return -1;
3991  }
3992 
3994  if (res) {
3995  cc_unref(core_instance, "Unref core instance. ast_taskprocessor_push failed");
3996  }
3997  return res;
3998 }
3999 
4000 static int cc_stop_ringing(void *data)
4001 {
4002  struct cc_core_instance *core_instance = data;
4003  int res = 0;
4004 
4005  if (core_instance->agent->callbacks->stop_ringing) {
4006  res = core_instance->agent->callbacks->stop_ringing(core_instance->agent);
4007  }
4008  /* If an agent is being asked to stop ringing, then he needs to be prepared if for
4009  * whatever reason he needs to be called back again. The proper state to be in to
4010  * detect such a circumstance is the CC_ACTIVE state.
4011  *
4012  * We get to this state using the slightly unintuitive method of calling
4013  * ast_cc_monitor_request_acked because it gets us to the proper state.
4014  */
4015  ast_cc_monitor_request_acked(core_instance->core_id, "Agent %s asked to stop ringing. Be prepared to be recalled again.",
4016  core_instance->agent->device_name);
4017  cc_unref(core_instance, "Stop ringing finished. Unref core_instance");
4018  return res;
4019 }
4020 
4022 {
4023  int res;
4024  struct cc_core_instance *core_instance = find_cc_core_instance(core_id);
4025 
4026  if (!core_instance) {
4027  return -1;
4028  }
4029 
4031  if (res) {
4032  cc_unref(core_instance, "Unref core instance. ast_taskprocessor_push failed");
4033  }
4034  return res;
4035 }
4036 
4037 static int cc_party_b_free(void *data)
4038 {
4039  struct cc_core_instance *core_instance = data;
4040  int res = 0;
4041 
4042  if (core_instance->agent->callbacks->party_b_free) {
4043  res = core_instance->agent->callbacks->party_b_free(core_instance->agent);
4044  }
4045  cc_unref(core_instance, "Party B free finished. Unref core_instance");
4046  return res;
4047 }
4048 
4050 {
4051  int res;
4052  struct cc_core_instance *core_instance = find_cc_core_instance(core_id);
4053 
4054  if (!core_instance) {
4055  return -1;
4056  }
4057 
4059  if (res) {
4060  cc_unref(core_instance, "Unref core instance. ast_taskprocessor_push failed");
4061  }
4062  return res;
4063 }
4064 
4068 };
4069 
4070 static int cc_status_response(void *data)
4071 {
4072  struct cc_status_response_args *args = data;
4073  struct cc_core_instance *core_instance = args->core_instance;
4074  struct ast_cc_monitor *monitor_iter;
4075  enum ast_device_state devstate = args->devstate;
4076 
4077  ast_free(args);
4078 
4079  AST_LIST_LOCK(core_instance->monitors);
4080  AST_LIST_TRAVERSE(core_instance->monitors, monitor_iter, next) {
4081  if (monitor_iter->interface->monitor_class == AST_CC_DEVICE_MONITOR &&
4082  monitor_iter->callbacks->status_response) {
4083  monitor_iter->callbacks->status_response(monitor_iter, devstate);
4084  }
4085  }
4086  AST_LIST_UNLOCK(core_instance->monitors);
4087  cc_unref(core_instance, "Status response finished. Unref core instance");
4088  return 0;
4089 }
4090 
4092 {
4093  struct cc_status_response_args *args;
4094  struct cc_core_instance *core_instance;
4095  int res;
4096 
4097  args = ast_calloc(1, sizeof(*args));
4098  if (!args) {
4099  return -1;
4100  }
4101 
4102  core_instance = find_cc_core_instance(core_id);
4103  if (!core_instance) {
4104  ast_free(args);
4105  return -1;
4106  }
4107 
4108  args->core_instance = core_instance;
4109  args->devstate = devstate;
4110 
4112  if (res) {
4113  cc_unref(core_instance, "Unref core instance. ast_taskprocessor_push failed");
4114  ast_free(args);
4115  }
4116  return res;
4117 }
4118 
4119 static int cc_build_payload(struct ast_channel *chan, struct ast_cc_config_params *cc_params,
4120  const char *monitor_type, const char * const device_name, const char * dialstring,
4121  enum ast_cc_service_type service, void *private_data, struct cc_control_payload *payload)
4122 {
4123  struct ast_datastore *datastore;
4124  struct dialed_cc_interfaces *cc_interfaces;
4125  int dial_parent_id;
4126 
4127  ast_channel_lock(chan);
4129  if (!datastore) {
4130  ast_channel_unlock(chan);
4131  return -1;
4132  }
4133  cc_interfaces = datastore->data;
4134  dial_parent_id = cc_interfaces->dial_parent_id;
4135  ast_channel_unlock(chan);
4136 
4137  payload->monitor_type = monitor_type;
4138  payload->private_data = private_data;
4139  payload->service = service;
4140  ast_cc_copy_config_params(&payload->config_params, cc_params);
4142  ast_copy_string(payload->device_name, device_name, sizeof(payload->device_name));
4143  ast_copy_string(payload->dialstring, dialstring, sizeof(payload->dialstring));
4144  return 0;
4145 }
4146 
4147 int ast_queue_cc_frame(struct ast_channel *chan, const char *monitor_type,
4148  const char * const dialstring, enum ast_cc_service_type service, void *private_data)
4149 {
4150  struct ast_frame frame = {0,};
4151  char device_name[AST_CHANNEL_NAME];
4152  int retval;
4153  struct ast_cc_config_params *cc_params;
4154 
4155  cc_params = ast_channel_get_cc_config_params(chan);
4156  if (!cc_params) {
4157  return -1;
4158  }
4159  ast_channel_get_device_name(chan, device_name, sizeof(device_name));
4160  if (ast_cc_monitor_count(device_name, monitor_type) >= ast_get_cc_max_monitors(cc_params)) {
4161  ast_log(LOG_NOTICE, "Not queuing a CC frame for device %s since it already has its maximum monitors allocated\n", device_name);
4162  return -1;
4163  }
4164 
4165  if (ast_cc_build_frame(chan, cc_params, monitor_type, device_name, dialstring, service, private_data, &frame)) {
4166  /* Frame building failed. We can't use this. */
4167  return -1;
4168  }
4169  retval = ast_queue_frame(chan, &frame);
4170  ast_frfree(&frame);
4171  return retval;
4172 }
4173 
4174 int ast_cc_build_frame(struct ast_channel *chan, struct ast_cc_config_params *cc_params,
4175  const char *monitor_type, const char * const device_name,
4176  const char * const dialstring, enum ast_cc_service_type service, void *private_data,
4177  struct ast_frame *frame)
4178 {
4179  struct cc_control_payload *payload = ast_calloc(1, sizeof(*payload));
4180 
4181  if (!payload) {
4182  return -1;
4183  }
4184  if (cc_build_payload(chan, cc_params, monitor_type, device_name, dialstring, service, private_data, payload)) {
4185  /* Something screwed up, we can't make a frame with this */
4186  ast_free(payload);
4187  return -1;
4188  }
4189  frame->frametype = AST_FRAME_CONTROL;
4190  frame->subclass.integer = AST_CONTROL_CC;
4191  frame->data.ptr = payload;
4192  frame->datalen = sizeof(*payload);
4193  frame->mallocd = AST_MALLOCD_DATA;
4194  return 0;
4195 }
4196 
4197 void ast_cc_call_failed(struct ast_channel *incoming, struct ast_channel *outgoing, const char * const dialstring)
4198 {
4200  struct cc_control_payload payload;
4201  struct ast_cc_config_params *cc_params;
4202 
4204  /* It doesn't make sense to try to offer CCBS to the caller if the reason for ast_call
4205  * failing is something other than busy or congestion
4206  */
4207  return;
4208  }
4209 
4211  if (!cc_params) {
4212  return;
4213  }
4215  /* This sort of CCBS only works if using generic CC. For native, we would end up sending
4216  * a CC request for a non-existent call. The far end will reject this every time
4217  */
4218  return;
4219  }
4220 
4221  ast_channel_get_device_name(outgoing, device_name, sizeof(device_name));
4222  if (cc_build_payload(outgoing, cc_params, AST_CC_GENERIC_MONITOR_TYPE, device_name,
4223  dialstring, AST_CC_CCBS, NULL, &payload)) {
4224  /* Something screwed up, we can't make a frame with this */
4225  return;
4226  }
4227  ast_handle_cc_control_frame(incoming, outgoing, &payload);
4228 }
4229 
4230 void ast_cc_busy_interface(struct ast_channel *inbound, struct ast_cc_config_params *cc_params,
4231  const char *monitor_type, const char * const device_name, const char * const dialstring, void *private_data)
4232 {
4233  struct cc_control_payload payload;
4234  if (cc_build_payload(inbound, cc_params, monitor_type, device_name, dialstring, AST_CC_CCBS, private_data, &payload)) {
4235  /* Something screwed up. Don't try to handle this payload */
4237  return;
4238  }
4239  ast_handle_cc_control_frame(inbound, NULL, &payload);
4240 }
4241 
4242 int ast_cc_callback(struct ast_channel *inbound, const char * const tech, const char * const dest, ast_cc_callback_fn callback)
4243 {
4244  const struct ast_channel_tech *chantech = ast_get_channel_tech(tech);
4245 
4246  if (chantech && chantech->cc_callback) {
4247  chantech->cc_callback(inbound, dest, callback);
4248  }
4249 
4250  return 0;
4251 }
4252 
4253 static const char *ccreq_app = "CallCompletionRequest";
4254 
4255 static int ccreq_exec(struct ast_channel *chan, const char *data)
4256 {
4257  struct cc_core_instance *core_instance;
4258  char device_name[AST_CHANNEL_NAME];
4259  unsigned long match_flags;
4260  int res;
4261 
4262  ast_channel_get_device_name(chan, device_name, sizeof(device_name));
4263 
4265  if (!(core_instance = ao2_t_callback_data(cc_core_instances, 0, match_agent, device_name, &match_flags, "Find core instance for CallCompletionRequest"))) {
4266  ast_log_dynamic_level(cc_logger_level, "Couldn't find a core instance for caller %s\n", device_name);
4267  pbx_builtin_setvar_helper(chan, "CC_REQUEST_RESULT", "FAIL");
4268  pbx_builtin_setvar_helper(chan, "CC_REQUEST_REASON", "NO_CORE_INSTANCE");
4269  return 0;
4270  }
4271 
4272  ast_log_dynamic_level(cc_logger_level, "Core %d: Found core_instance for caller %s\n",
4273  core_instance->core_id, device_name);
4274 
4275  if (strcmp(core_instance->agent->callbacks->type, "generic")) {
4276  ast_log_dynamic_level(cc_logger_level, "Core %d: CallCompletionRequest is only for generic agent types.\n",
4277  core_instance->core_id);
4278  pbx_builtin_setvar_helper(chan, "CC_REQUEST_RESULT", "FAIL");
4279  pbx_builtin_setvar_helper(chan, "CC_REQUEST_REASON", "NOT_GENERIC");
4280  cc_unref(core_instance, "Unref core_instance since CallCompletionRequest was called with native agent");
4281  return 0;
4282  }
4283 
4285  ast_log_dynamic_level(cc_logger_level, "Core %d: CallCompletionRequest failed. Too many requests in the system\n",
4286  core_instance->core_id);
4287  ast_cc_failed(core_instance->core_id, "Too many CC requests\n");
4288  pbx_builtin_setvar_helper(chan, "CC_REQUEST_RESULT", "FAIL");
4289  pbx_builtin_setvar_helper(chan, "CC_REQUEST_REASON", "TOO_MANY_REQUESTS");
4290  cc_unref(core_instance, "Unref core_instance since too many CC requests");
4291  return 0;
4292  }
4293 
4294  res = ast_cc_agent_accept_request(core_instance->core_id, "CallCompletionRequest called by caller %s for core_id %d", device_name, core_instance->core_id);
4295  pbx_builtin_setvar_helper(chan, "CC_REQUEST_RESULT", res ? "FAIL" : "SUCCESS");
4296  if (res) {
4297  pbx_builtin_setvar_helper(chan, "CC_REQUEST_REASON", "UNSPECIFIED");
4298  }
4299 
4300  cc_unref(core_instance, "Done with CallCompletionRequest");
4301  return 0;
4302 }
4303 
4304 static const char *cccancel_app = "CallCompletionCancel";
4305 
4306 static int cccancel_exec(struct ast_channel *chan, const char *data)
4307 {
4308  struct cc_core_instance *core_instance;
4309  char device_name[AST_CHANNEL_NAME];
4310  unsigned long match_flags;
4311  int res;
4312 
4313  ast_channel_get_device_name(chan, device_name, sizeof(device_name));
4314 
4316  if (!(core_instance = ao2_t_callback_data(cc_core_instances, 0, match_agent, device_name, &match_flags, "Find core instance for CallCompletionCancel"))) {
4317  ast_log_dynamic_level(cc_logger_level, "Cannot find CC transaction to cancel for caller %s\n", device_name);
4318  pbx_builtin_setvar_helper(chan, "CC_CANCEL_RESULT", "FAIL");
4319  pbx_builtin_setvar_helper(chan, "CC_CANCEL_REASON", "NO_CORE_INSTANCE");
4320  return 0;
4321  }
4322 
4323  if (strcmp(core_instance->agent->callbacks->type, "generic")) {
4324  ast_log(LOG_WARNING, "CallCompletionCancel may only be used for calles with a generic agent\n");
4325  cc_unref(core_instance, "Unref core instance found during CallCompletionCancel");
4326  pbx_builtin_setvar_helper(chan, "CC_CANCEL_RESULT", "FAIL");
4327  pbx_builtin_setvar_helper(chan, "CC_CANCEL_REASON", "NOT_GENERIC");
4328  return 0;
4329  }
4330  res = ast_cc_failed(core_instance->core_id, "Call completion request Cancelled for core ID %d by caller %s",
4331  core_instance->core_id, device_name);
4332  cc_unref(core_instance, "Unref core instance found during CallCompletionCancel");
4333  pbx_builtin_setvar_helper(chan, "CC_CANCEL_RESULT", res ? "FAIL" : "SUCCESS");
4334  if (res) {
4335  pbx_builtin_setvar_helper(chan, "CC_CANCEL_REASON", "UNSPECIFIED");
4336  }
4337  return 0;
4338 }
4339 
4341  const char *device_name;
4342  const char *monitor_type;
4343  int count;
4344 };
4345 
4346 static int count_monitors_cb(void *obj, void *arg, int flags)
4347 {
4348  struct cc_core_instance *core_instance = obj;
4349  struct count_monitors_cb_data *cb_data = arg;
4350  const char *device_name = cb_data->device_name;
4351  const char *monitor_type = cb_data->monitor_type;
4352  struct ast_cc_monitor *monitor_iter;
4353 
4354  AST_LIST_LOCK(core_instance->monitors);
4355  AST_LIST_TRAVERSE(core_instance->monitors, monitor_iter, next) {
4356  if (!strcmp(monitor_iter->interface->device_name, device_name) &&
4357  !strcmp(monitor_iter->interface->monitor_type, monitor_type)) {
4358  cb_data->count++;
4359  break;
4360  }
4361  }
4362  AST_LIST_UNLOCK(core_instance->monitors);
4363  return 0;
4364 }
4365 
4366 int ast_cc_monitor_count(const char * const name, const char * const type)
4367 {
4368  struct count_monitors_cb_data data = {.device_name = name, .monitor_type = type,};
4369 
4370  ao2_t_callback(cc_core_instances, OBJ_NODATA, count_monitors_cb, &data, "Counting agents");
4371  ast_log_dynamic_level(cc_logger_level, "Counted %d monitors\n", data.count);
4372  return data.count;
4373 }
4374 
4376 {
4377  struct ast_config *cc_config;
4378  const char *cc_max_requests_str;
4379  struct ast_flags config_flags = {0,};
4380  char *endptr;
4381 
4382  cc_config = ast_config_load2("ccss.conf", "ccss", config_flags);
4383  if (!cc_config || cc_config == CONFIG_STATUS_FILEINVALID) {
4384  ast_log(LOG_WARNING, "Could not find valid ccss.conf file. Using cc_max_requests default\n");
4386  return;
4387  }
4388 
4389  if (!(cc_max_requests_str = ast_variable_retrieve(cc_config, "general", "cc_max_requests"))) {
4390  ast_config_destroy(cc_config);
4392  return;
4393  }
4394 
4395  global_cc_max_requests = strtol(cc_max_requests_str, &endptr, 10);
4396 
4397  if (!ast_strlen_zero(endptr)) {
4398  ast_log(LOG_WARNING, "Invalid input given for cc_max_requests. Using default\n");
4400  }
4401 
4402  ast_config_destroy(cc_config);
4403  return;
4404 }
4405 
4406 /*!
4407  * \internal
4408  * \brief helper function to parse and configure each devstate map
4409  */
4410 static void initialize_cc_devstate_map_helper(struct ast_config *cc_config, enum cc_state state, const char *cc_setting)
4411 {
4412  const char *cc_devstate_str;
4413  enum ast_device_state this_devstate;
4414 
4415  if ((cc_devstate_str = ast_variable_retrieve(cc_config, "general", cc_setting))) {
4416  this_devstate = ast_devstate_val(cc_devstate_str);
4417  if (this_devstate != AST_DEVICE_UNKNOWN) {
4418  cc_state_to_devstate_map[state] = this_devstate;
4419  }
4420  }
4421 }
4422 
4423 /*!
4424  * \internal
4425  * \brief initializes cc_state_to_devstate_map from ccss.conf
4426  *
4427  * \details
4428  * The cc_state_to_devstate_map[] is already initialized with all the
4429  * default values. This will update that structure with any changes
4430  * from the ccss.conf file. The configuration parameters in ccss.conf
4431  * should use any valid device state form that is recognized by
4432  * ast_devstate_val() function.
4433  */
4435 {
4436  struct ast_config *cc_config;
4437  struct ast_flags config_flags = { 0, };
4438 
4439  cc_config = ast_config_load2("ccss.conf", "ccss", config_flags);
4440  if (!cc_config || cc_config == CONFIG_STATUS_FILEINVALID) {
4442  "Could not find valid ccss.conf file. Using cc_[state]_devstate defaults\n");
4443  return;
4444  }
4445 
4446  initialize_cc_devstate_map_helper(cc_config, CC_AVAILABLE, "cc_available_devstate");
4447  initialize_cc_devstate_map_helper(cc_config, CC_CALLER_OFFERED, "cc_caller_offered_devstate");
4448  initialize_cc_devstate_map_helper(cc_config, CC_CALLER_REQUESTED, "cc_caller_requested_devstate");
4449  initialize_cc_devstate_map_helper(cc_config, CC_ACTIVE, "cc_active_devstate");
4450  initialize_cc_devstate_map_helper(cc_config, CC_CALLEE_READY, "cc_callee_ready_devstate");
4451  initialize_cc_devstate_map_helper(cc_config, CC_CALLER_BUSY, "cc_caller_busy_devstate");
4452  initialize_cc_devstate_map_helper(cc_config, CC_RECALLING, "cc_recalling_devstate");
4453  initialize_cc_devstate_map_helper(cc_config, CC_COMPLETE, "cc_complete_devstate");
4454  initialize_cc_devstate_map_helper(cc_config, CC_FAILED, "cc_failed_devstate");
4455 
4456  ast_config_destroy(cc_config);
4457 }
4458 
4459 static void cc_cli_print_monitor_stats(struct ast_cc_monitor *monitor, int fd, int parent_id)
4460 {
4461  struct ast_cc_monitor *child_monitor_iter = monitor;
4462  if (!monitor) {
4463  return;
4464  }
4465 
4466  ast_cli(fd, "\t\t|-->%s", monitor->interface->device_name);
4467  if (monitor->interface->monitor_class == AST_CC_DEVICE_MONITOR) {
4468  ast_cli(fd, "(%s)", cc_service_to_string(monitor->service_offered));
4469  }
4470  ast_cli(fd, "\n");
4471 
4472  while ((child_monitor_iter = AST_LIST_NEXT(child_monitor_iter, next))) {
4473  if (child_monitor_iter->parent_id == monitor->id) {
4474  cc_cli_print_monitor_stats(child_monitor_iter, fd, child_monitor_iter->id);
4475  }
4476  }
4477 }
4478 
4479 static int print_stats_cb(void *obj, void *arg, int flags)
4480 {
4481  int *cli_fd = arg;
4482  struct cc_core_instance *core_instance = obj;
4483 
4484  ast_cli(*cli_fd, "%d\t\t%s\t\t%s\n", core_instance->core_id, core_instance->agent->device_name,
4485  cc_state_to_string(core_instance->current_state));
4486  AST_LIST_LOCK(core_instance->monitors);
4487  cc_cli_print_monitor_stats(AST_LIST_FIRST(core_instance->monitors), *cli_fd, 0);
4488  AST_LIST_UNLOCK(core_instance->monitors);
4489  return 0;
4490 }
4491 
4492 static int cc_cli_output_status(void *data)
4493 {
4494  int *cli_fd = data;
4496 
4497  if (!count) {
4498  ast_cli(*cli_fd, "There are currently no active call completion transactions\n");
4499  } else {
4500  ast_cli(*cli_fd, "%d Call completion transactions\n", count);
4501  ast_cli(*cli_fd, "Core ID\t\tCaller\t\t\t\tStatus\n");
4502  ast_cli(*cli_fd, "----------------------------------------------------------------------------\n");
4503  ao2_t_callback(cc_core_instances, OBJ_NODATA, print_stats_cb, cli_fd, "Printing stats to CLI");
4504  }
4505  ast_free(cli_fd);
4506  return 0;
4507 }
4508 
4509 static char *handle_cc_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4510 {
4511  int *cli_fd;
4512 
4513  switch (cmd) {
4514  case CLI_INIT:
4515  e->command = "cc report status";
4516  e->usage =
4517  "Usage: cc report status\n"
4518  " Report the current status of any ongoing CC transactions\n";
4519  return NULL;
4520  case CLI_GENERATE:
4521  return NULL;
4522  }
4523 
4524  if (a->argc != 3) {
4525  return CLI_SHOWUSAGE;
4526  }
4527 
4528  cli_fd = ast_malloc(sizeof(*cli_fd));
4529  if (!cli_fd) {
4530  return CLI_FAILURE;
4531  }
4532 
4533  *cli_fd = a->fd;
4534 
4536  ast_free(cli_fd);
4537  return CLI_FAILURE;
4538  }
4539  return CLI_SUCCESS;
4540 }
4541 
4542 static int kill_cores(void *obj, void *arg, int flags)
4543 {
4544  int *core_id = arg;
4545  struct cc_core_instance *core_instance = obj;
4546 
4547  if (!core_id || (core_instance->core_id == *core_id)) {
4548  ast_cc_failed(core_instance->core_id, "CC transaction canceled administratively\n");
4549  }
4550  return 0;
4551 }
4552 
4553 static char *complete_core_id(const char *word)
4554 {
4555  int wordlen = strlen(word);
4556  struct ao2_iterator core_iter = ao2_iterator_init(cc_core_instances, 0);
4557  struct cc_core_instance *core_instance;
4558 
4559  for (; (core_instance = ao2_t_iterator_next(&core_iter, "Next core instance"));
4560  cc_unref(core_instance, "CLI tab completion iteration")) {
4561  char core_id_str[20];
4562  snprintf(core_id_str, sizeof(core_id_str), "%d", core_instance->core_id);
4563  if (!strncmp(word, core_id_str, wordlen)) {
4564  if (ast_cli_completion_add(ast_strdup(core_id_str))) {
4565  cc_unref(core_instance, "Found a matching core ID for CLI tab-completion");
4566  break;
4567  }
4568  }
4569  }
4570  ao2_iterator_destroy(&core_iter);
4571 
4572  return NULL;
4573 }
4574 
4575 static char *handle_cc_kill(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4576 {
4577  switch (cmd) {
4578  case CLI_INIT:
4579  e->command = "cc cancel [core|all]";
4580  e->usage =
4581  "Usage: cc cancel can be used in two ways.\n"
4582  " 1. 'cc cancel core [core ID]' will cancel the CC transaction with\n"
4583  " core ID equal to the specified core ID.\n"
4584  " 2. 'cc cancel all' will cancel all active CC transactions.\n";
4585  return NULL;
4586  case CLI_GENERATE:
4587  if (a->pos == 3 && !strcasecmp(a->argv[2], "core")) {
4588  return complete_core_id(a->word);
4589  }
4590  return NULL;
4591  }
4592 
4593  if (a->argc == 4) {
4594  int core_id;
4595  char *endptr;
4596  if (strcasecmp(a->argv[2], "core")) {
4597  return CLI_SHOWUSAGE;
4598  }
4599  core_id = strtol(a->argv[3], &endptr, 10);
4600  if ((errno != 0 && core_id == 0) || (endptr == a->argv[3])) {
4601  return CLI_SHOWUSAGE;
4602  }
4603  ao2_t_callback(cc_core_instances, OBJ_NODATA, kill_cores, &core_id, "CLI Killing Core Id");
4604  } else if (a->argc == 3) {
4605  if (strcasecmp(a->argv[2], "all")) {
4606  return CLI_SHOWUSAGE;
4607  }
4608  ao2_t_callback(cc_core_instances, OBJ_NODATA, kill_cores, NULL, "CLI Killing all CC cores");
4609  } else {
4610  return CLI_SHOWUSAGE;
4611  }
4612 
4613  return CLI_SUCCESS;
4614 }
4615 
4616 static struct ast_cli_entry cc_cli[] = {
4617  AST_CLI_DEFINE(handle_cc_status, "Reports CC stats"),
4618  AST_CLI_DEFINE(handle_cc_kill, "Kill a CC transaction"),
4619 };
4620 
4621 static int unload_module(void)
4622 {
4623  ast_devstate_prov_del("ccss");
4630 
4631  if (cc_sched_context) {
4634  }
4635  if (cc_core_taskprocessor) {
4637  }
4638  /* Note that core instances must be destroyed prior to the generic_monitors */
4639  if (cc_core_instances) {
4640  ao2_t_ref(cc_core_instances, -1, "Unref cc_core_instances container in cc_shutdown");
4642  }
4643  if (generic_monitors) {
4644  ao2_t_ref(generic_monitors, -1, "Unref generic_monitor container in cc_shutdown");
4646  }
4647 
4648  return 0;
4649 }
4650 
4651 static int load_module(void)
4652 {
4653  int res;
4654 
4658  "Create core instance container");
4659  if (!cc_core_instances) {
4660  return AST_MODULE_LOAD_FAILURE;
4661  }
4662 
4665  generic_monitor_instance_list_hash_fn, NULL, generic_monitor_instance_list_cmp_fn,
4666  "Create generic monitor container");
4667  if (!generic_monitors) {
4668  return AST_MODULE_LOAD_FAILURE;
4669  }
4671  return AST_MODULE_LOAD_FAILURE;
4672  }
4674  return AST_MODULE_LOAD_FAILURE;
4675  }
4677  return AST_MODULE_LOAD_FAILURE;
4678  }
4683 
4688 
4689  /* Read the map and register the device state callback for generic agents */
4691  res |= ast_devstate_prov_add("ccss", ccss_device_state);
4692 
4694 }
4695