Asterisk - The Open Source Telephony Project  GIT-master-a24979a
cdr.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*! \file
20  *
21  * \brief Call Detail Record API
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \note Includes code and algorithms from the Zapata library.
26  *
27  * \note We do a lot of checking here in the CDR code to try to be sure we don't ever let a CDR slip
28  * through our fingers somehow. If someone allocates a CDR, it must be completely handled normally
29  * or a WARNING shall be logged, so that we can best keep track of any escape condition where the CDR
30  * isn't properly generated and posted.
31  */
32 
33 /*! \li \ref cdr.c uses the configuration file \ref cdr.conf
34  * \addtogroup configuration_file Configuration Files
35  */
36 
37 /*!
38  * \page cdr.conf cdr.conf
39  * \verbinclude cdr.conf.sample
40  */
41 
42 /*** MODULEINFO
43  <support_level>core</support_level>
44  ***/
45 
46 #include "asterisk.h"
47 
48 #include <signal.h>
49 #include <inttypes.h>
50 
51 #include "asterisk/lock.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/cdr.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/manager.h"
56 #include "asterisk/module.h"
57 #include "asterisk/causes.h"
58 #include "asterisk/linkedlists.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/sched.h"
61 #include "asterisk/config.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/stringfields.h"
65 #include "asterisk/json.h"
66 #include "asterisk/parking.h"
67 #include "asterisk/stasis.h"
71 #include "asterisk/astobj2.h"
72 #include "asterisk/taskprocessor.h"
73 
74 /*** DOCUMENTATION
75  <configInfo name="cdr" language="en_US">
76  <synopsis>Call Detail Record configuration</synopsis>
77  <description>
78  <para>CDR is Call Detail Record, which provides logging services via a variety of
79  pluggable backend modules. Detailed call information can be recorded to
80  databases, files, etc. Useful for billing, fraud prevention, compliance with
81  Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
82  </description>
83  <configFile name="cdr.conf">
84  <configObject name="general">
85  <synopsis>Global settings applied to the CDR engine.</synopsis>
86  <configOption name="debug">
87  <synopsis>Enable/disable verbose CDR debugging.</synopsis>
88  <description><para>When set to <literal>True</literal>, verbose updates
89  of changes in CDR information will be logged. Note that this is only
90  of use when debugging CDR behavior.</para>
91  </description>
92  </configOption>
93  <configOption name="enable" default="yes">
94  <synopsis>Enable/disable CDR logging.</synopsis>
95  <description><para>Define whether or not to use CDR logging. Setting this to "no" will override
96  any loading of backend CDR modules.</para>
97  </description>
98  </configOption>
99  <configOption name="channeldefaultenabled" default="yes">
100  <synopsis>Whether CDR is enabled on a channel by default</synopsis>
101  <description><para>Define whether or not CDR should be enabled on a channel by default.
102  Setting this to "yes" will enable CDR on every channel unless it is explicitly disabled.
103  Setting this to "no" will disable CDR on every channel unless it is explicitly enabled.
104  </para>
105  <para>Note that CDR must still be globally enabled (<literal>enable = yes</literal>) for this
106  option to have any effect. This only applies to whether CDR is enabled or disabled on
107  newly created channels, which can be changed in the dialplan during a call.</para>
108  <para>If this is set to "yes", you should use <literal>Set(CDR_PROP(disable)=1)</literal>
109  to disable CDR for a call.</para>
110  <para>If this is set to "no", you should use <literal>Set(CDR_PROP(disable)=0)</literal>
111  to undisable (enable) CDR for a call.</para>
112  </description>
113  </configOption>
114  <configOption name="unanswered">
115  <synopsis>Log calls that are never answered and don't set an outgoing party.</synopsis>
116  <description><para>
117  Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
118  this to "yes" will make calls to extensions that don't answer and don't set a side B channel
119  (such as by using the Dial application) receive CDR log entries. If this option is set to
120  "no", then those log entries will not be created. Unanswered calls which get offered to an
121  outgoing line will always receive log entries regardless of this option, and that is the
122  intended behavior.
123  </para>
124  </description>
125  </configOption>
126  <configOption name="congestion">
127  <synopsis>Log congested calls.</synopsis>
128  <description><para>Define whether or not to log congested calls. Setting this to "yes" will
129  report each call that fails to complete due to congestion conditions.</para>
130  </description>
131  </configOption>
132  <configOption name="endbeforehexten">
133  <synopsis>Don't produce CDRs while executing hangup logic</synopsis>
134  <description>
135  <para>As each CDR for a channel is finished, its end time is updated
136  and the CDR is finalized. When a channel is hung up and hangup
137  logic is present (in the form of a hangup handler or the
138  <literal>h</literal> extension), a new CDR is generated for the
139  channel. Any statistics are gathered from this new CDR. By enabling
140  this option, no new CDR is created for the dialplan logic that is
141  executed in <literal>h</literal> extensions or attached hangup handler
142  subroutines. The default value is <literal>yes</literal>, indicating
143  that a CDR will be generated during hangup logic.</para>
144  </description>
145  </configOption>
146  <configOption name="initiatedseconds">
147  <synopsis>Count microseconds for billsec purposes</synopsis>
148  <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
149  is simply the end time (hangup time) minus the answer time in seconds. Internally,
150  asterisk stores the time in terms of microseconds and seconds. By setting
151  initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
152  that were initiated (a sort of round up method). Technically, this is
153  when the microsecond part of the end time is greater than the microsecond
154  part of the answer time, then the billsec time is incremented one second.</para>
155  </description>
156  </configOption>
157  <configOption name="batch">
158  <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
159  <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
160  every call, the data will be stored in a buffer to help alleviate load on the
161  asterisk server.</para>
162  <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
163  i.e., software crash, power failure, kill -9, etc.</para>
164  </warning>
165  </description>
166  </configOption>
167  <configOption name="size">
168  <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
169  <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
170  them to the backend engines. batch must be set to <literal>yes</literal>.</para>
171  </description>
172  </configOption>
173  <configOption name="time">
174  <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
175  <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
176  backend engines. If this time limit is reached, then it will post the records, regardless of the value
177  defined for size. batch must be set to <literal>yes</literal>.</para>
178  <note><para>Time is expressed in seconds.</para></note>
179  </description>
180  </configOption>
181  <configOption name="scheduleronly">
182  <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
183  <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
184  records. Posting can either occur inside the scheduler thread, or a new
185  thread can be spawned for the submission of every batch. For small batches,
186  it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
187  For large batches, say anything over size=10, a new thread is recommended, so
188  set this to <literal>no</literal>.</para>
189  </description>
190  </configOption>
191  <configOption name="safeshutdown">
192  <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
193  <description><para>When shutting down asterisk, you can block until the CDRs are submitted. If
194  you don't, then data will likely be lost. You can always check the size of
195  the CDR batch buffer with the CLI <astcli>cdr status</astcli> command. To enable blocking on
196  submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
197  </description>
198  </configOption>
199  </configObject>
200  </configFile>
201  </configInfo>
202  ***/
203 
204 #define DEFAULT_ENABLED "1"
205 #define DEFAULT_BATCHMODE "0"
206 #define DEFAULT_UNANSWERED "0"
207 #define DEFAULT_CONGESTION "0"
208 #define DEFAULT_END_BEFORE_H_EXTEN "1"
209 #define DEFAULT_INITIATED_SECONDS "0"
210 #define DEFAULT_CHANNEL_ENABLED "1"
211 
212 #define DEFAULT_BATCH_SIZE "100"
213 #define MAX_BATCH_SIZE 1000
214 #define DEFAULT_BATCH_TIME "300"
215 #define MAX_BATCH_TIME 86400
216 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
217 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
218 
219 #define cdr_set_debug_mode(mod_cfg) \
220  do { \
221  cdr_debug_enabled = ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG); \
222  } while (0)
223 
224 static int cdr_debug_enabled;
225 
226 #define CDR_DEBUG(fmt, ...) \
227  do { \
228  if (cdr_debug_enabled) { \
229  ast_verbose((fmt), ##__VA_ARGS__); \
230  } \
231  } while (0)
232 
233 static void cdr_detach(struct ast_cdr *cdr);
234 static void cdr_submit_batch(int shutdown);
235 static int cdr_toggle_runtime_options(void);
236 
237 /*! \brief The configuration settings for this module */
239  struct ast_cdr_config *general; /*!< CDR global settings */
240 };
241 
242 /*! \brief The container for the module configuration */
243 static AO2_GLOBAL_OBJ_STATIC(module_configs);
244 
245 /*! \brief The type definition for general options */
246 static struct aco_type general_option = {
247  .type = ACO_GLOBAL,
248  .name = "general",
249  .item_offset = offsetof(struct module_config, general),
250  .category = "general",
251  .category_match = ACO_WHITELIST_EXACT,
252 };
253 
254 /*! Config sections used by existing modules. Do not add to this list. */
255 static const char *ignore_categories[] = {
256  "csv",
257  "custom",
258  "manager",
259  "odbc",
260  "pgsql",
261  "radius",
262  "sqlite",
263  "tds",
264  "mysql",
265  NULL,
266 };
267 
268 static struct aco_type ignore_option = {
269  .type = ACO_IGNORE,
270  .name = "modules",
271  .category = (const char*)ignore_categories,
273 };
274 
275 static void *module_config_alloc(void);
276 static void module_config_destructor(void *obj);
277 static void module_config_post_apply(void);
278 
279 /*! \brief The file definition */
280 static struct aco_file module_file_conf = {
281  .filename = "cdr.conf",
283 };
284 
285 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
286  .files = ACO_FILES(&module_file_conf),
287  .post_apply_config = module_config_post_apply,
288 );
289 
291 
292 static void module_config_post_apply(void)
293 {
294  struct module_config *mod_cfg;
295 
296  mod_cfg = ao2_global_obj_ref(module_configs);
297  if (!mod_cfg) {
298  return;
299  }
300  cdr_set_debug_mode(mod_cfg);
301  ao2_cleanup(mod_cfg);
302 }
303 
304 /*! \brief Dispose of a module config object */
305 static void module_config_destructor(void *obj)
306 {
307  struct module_config *cfg = obj;
308 
309  if (!cfg) {
310  return;
311  }
312  ao2_ref(cfg->general, -1);
313 }
314 
315 /*! \brief Create a new module config object */
316 static void *module_config_alloc(void)
317 {
318  struct module_config *mod_cfg;
319  struct ast_cdr_config *cdr_config;
320 
321  mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
322  if (!mod_cfg) {
323  return NULL;
324  }
325 
326  cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
327  if (!cdr_config) {
328  ao2_ref(cdr_config, -1);
329  return NULL;
330  }
331  mod_cfg->general = cdr_config;
332 
333  return mod_cfg;
334 }
335 
336 /*! \brief Registration object for CDR backends */
337 struct cdr_beitem {
338  char name[20];
339  char desc[80];
342  int suspended:1;
343 };
344 
345 /*! \brief List of registered backends */
347 
348 /*! \brief List of registered modifiers */
350 
351 /*! \brief Queued CDR waiting to be batched */
353  struct ast_cdr *cdr;
355 };
356 
357 /*! \brief The actual batch queue */
358 static struct cdr_batch {
359  int size;
362 } *batch = NULL;
363 
364 /*! \brief The global sequence counter used for CDRs */
365 static int global_cdr_sequence = 0;
366 
367 /*! \brief Scheduler items */
368 static struct ast_sched_context *sched;
369 static int cdr_sched = -1;
371 static pthread_t cdr_thread = AST_PTHREADT_NULL;
372 
373 /*! \brief Lock protecting modifications to the batch queue */
375 
376 /*! \brief These are used to wake up the CDR thread when there's work to do */
379 
380 /*! \brief A container of the active master CDRs indexed by Party A channel uniqueid */
382 
383 /*! \brief A container of all active CDRs with a Party B indexed by Party B channel name */
385 
386 /*! \brief Message router for stasis messages regarding channel state */
388 
389 /*! \brief Our subscription for bridges */
391 
392 /*! \brief Our subscription for channels */
394 
395 /*! \brief Our subscription for parking */
397 
398 /*! \brief The parent topic for all topics we want to aggregate for CDRs */
399 static struct stasis_topic *cdr_topic;
400 
401 /*! \brief A message type used to synchronize with the CDR topic */
402 STASIS_MESSAGE_TYPE_DEFN_LOCAL(cdr_sync_message_type);
403 
404 struct cdr_object;
405 
406 /*! \brief Return types for \p process_bridge_enter functions */
408  /*!
409  * The CDR was the only party in the bridge.
410  */
412  /*!
413  * The CDR was able to obtain a Party B from some other party already in the bridge
414  */
416  /*!
417  * The CDR was not able to obtain a Party B
418  */
420  /*!
421  * This CDR can't handle a bridge enter message and a new CDR needs to be created
422  */
424 };
425 
426 /*!
427  * \brief A virtual table used for \ref cdr_object.
428  *
429  * Note that all functions are optional - if a subclass does not need an
430  * implementation, it is safe to leave it NULL.
431  */
433  /*! \brief Name of the subclass */
434  const char *name;
435 
436  /*!
437  * \brief An initialization function. This will be called automatically
438  * when a \ref cdr_object is switched to this type in
439  * \ref cdr_object_transition_state
440  *
441  * \param cdr The \ref cdr_object that was just transitioned
442  */
443  void (* const init_function)(struct cdr_object *cdr);
444 
445  /*!
446  * \brief Process a Party A update for the \ref cdr_object
447  *
448  * \param cdr The \ref cdr_object to process the update
449  * \param snapshot The snapshot for the CDR's Party A
450  * \retval 0 the CDR handled the update or ignored it
451  * \retval 1 the CDR is finalized and a new one should be made to handle it
452  */
453  int (* const process_party_a)(struct cdr_object *cdr,
454  struct ast_channel_snapshot *snapshot);
455 
456  /*!
457  * \brief Process a Party B update for the \ref cdr_object
458  *
459  * \param cdr The \ref cdr_object to process the update
460  * \param snapshot The snapshot for the CDR's Party B
461  */
462  void (* const process_party_b)(struct cdr_object *cdr,
463  struct ast_channel_snapshot *snapshot);
464 
465  /*!
466  * \brief Process the beginning of a dial. A dial message implies one of two
467  * things:
468  * The \ref cdr_object's Party A has been originated
469  * The \ref cdr_object's Party A is dialing its Party B
470  *
471  * \param cdr The \ref cdr_object
472  * \param caller The originator of the dial attempt
473  * \param peer The destination of the dial attempt
474  *
475  * \retval 0 if the parties in the dial were handled by this CDR
476  * \retval 1 if the parties could not be handled by this CDR
477  */
478  int (* const process_dial_begin)(struct cdr_object *cdr,
480  struct ast_channel_snapshot *peer);
481 
482  /*!
483  * \brief Process the end of a dial. At the end of a dial, a CDR can be
484  * transitioned into one of two states - DialedPending
485  * (\ref dialed_pending_state_fn_table) or Finalized
486  * (\ref finalized_state_fn_table).
487  *
488  * \param cdr The \ref cdr_object
489  * \param caller The originator of the dial attempt
490  * \param peer the Destination of the dial attempt
491  * \param dial_status What happened
492  *
493  * \retval 0 if the parties in the dial were handled by this CDR
494  * \retval 1 if the parties could not be handled by this CDR
495  */
496  int (* const process_dial_end)(struct cdr_object *cdr,
498  struct ast_channel_snapshot *peer,
499  const char *dial_status);
500 
501  /*!
502  * \brief Process the entering of a bridge by this CDR. The purpose of this
503  * callback is to have the CDR prepare itself for the bridge and attempt to
504  * find a valid Party B. The act of creating new CDRs based on the entering
505  * of this channel into the bridge is handled by the higher level message
506  * handler.
507  *
508  * Note that this handler is for when a channel enters into a "normal"
509  * bridge, where people actually talk to each other. Parking is its own
510  * thing.
511  *
512  * \param cdr The \ref cdr_object
513  * \param bridge The bridge that the Party A just entered into
514  * \param channel The \ref ast_channel_snapshot for this CDR's Party A
515  *
516  * \return process_bridge_enter_results Defines whether or not this CDR was able
517  * to fully handle the bridge enter message.
518  */
520  struct cdr_object *cdr,
521  struct ast_bridge_snapshot *bridge,
522  struct ast_channel_snapshot *channel);
523 
524  /*!
525  * \brief Process entering into a parking bridge.
526  *
527  * \param cdr The \ref cdr_object
528  * \param bridge The parking bridge that Party A just entered into
529  * \param channel The \ref ast_channel_snapshot for this CDR's Party A
530  *
531  * \retval 0 This CDR successfully transitioned itself into the parked state
532  * \retval 1 This CDR couldn't handle the parking transition and we need a
533  * new CDR.
534  */
535  int (* const process_parking_bridge_enter)(struct cdr_object *cdr,
536  struct ast_bridge_snapshot *bridge,
537  struct ast_channel_snapshot *channel);
538 
539  /*!
540  * \brief Process the leaving of a bridge by this CDR.
541  *
542  * \param cdr The \ref cdr_object
543  * \param bridge The bridge that the Party A just left
544  * \param channel The \ref ast_channel_snapshot for this CDR's Party A
545  *
546  * \retval 0 This CDR left successfully
547  * \retval 1 Error
548  */
549  int (* const process_bridge_leave)(struct cdr_object *cdr,
550  struct ast_bridge_snapshot *bridge,
551  struct ast_channel_snapshot *channel);
552 
553  /*!
554  * \brief Process an update informing us that the channel got itself parked
555  *
556  * \param cdr The \ref cdr_object
557  * \param channel The parking information for this CDR's party A
558  *
559  * \retval 0 This CDR successfully parked itself
560  * \retval 1 This CDR couldn't handle the park
561  */
562  int (* const process_parked_channel)(struct cdr_object *cdr,
563  struct ast_parked_call_payload *parking_info);
564 };
565 
566 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
567 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
568 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
569 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
570 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info);
571 
572 static void single_state_init_function(struct cdr_object *cdr);
573 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
574 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
576 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
577 
578 /*!
579  * \brief The virtual table for the Single state.
580  *
581  * A \ref cdr_object starts off in this state. This represents a channel that
582  * has no Party B information itself.
583  *
584  * A \ref cdr_object from this state can go into any of the following states:
585  * * \ref dial_state_fn_table
586  * * \ref bridge_state_fn_table
587  * * \ref finalized_state_fn_table
588  */
590  .name = "Single",
591  .init_function = single_state_init_function,
592  .process_party_a = base_process_party_a,
593  .process_party_b = single_state_process_party_b,
594  .process_dial_begin = single_state_process_dial_begin,
595  .process_dial_end = base_process_dial_end,
596  .process_bridge_enter = single_state_process_bridge_enter,
597  .process_parking_bridge_enter = single_state_process_parking_bridge_enter,
598  .process_bridge_leave = base_process_bridge_leave,
599  .process_parked_channel = base_process_parked_channel,
600 };
601 
602 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
603 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
604 static int dial_state_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
606 
607 /*!
608  * \brief The virtual table for the Dial state.
609  *
610  * A \ref cdr_object that has begun a dial operation. This state is entered when
611  * the Party A for a CDR is determined to be dialing out to a Party B or when
612  * a CDR is for an originated channel (in which case the Party A information is
613  * the originated channel, and there is no Party B).
614  *
615  * A \ref cdr_object from this state can go in any of the following states:
616  * * \ref dialed_pending_state_fn_table
617  * * \ref bridge_state_fn_table
618  * * \ref finalized_state_fn_table
619  */
621  .name = "Dial",
622  .process_party_a = base_process_party_a,
623  .process_party_b = dial_state_process_party_b,
624  .process_dial_begin = dial_state_process_dial_begin,
625  .process_dial_end = dial_state_process_dial_end,
626  .process_bridge_enter = dial_state_process_bridge_enter,
627  .process_bridge_leave = base_process_bridge_leave,
628 };
629 
630 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
631 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
634 
635 /*!
636  * \brief The virtual table for the Dialed Pending state.
637  *
638  * A \ref cdr_object that has successfully finished a dial operation, but we
639  * don't know what they're going to do yet. It's theoretically possible to dial
640  * a party and then have that party not be bridged with the caller; likewise,
641  * an origination can complete and the channel go off and execute dialplan. The
642  * pending state acts as a bridge between either:
643  * * Entering a bridge
644  * * Getting a new CDR for new dialplan execution
645  * * Switching from being originated to executing dialplan
646  *
647  * A \ref cdr_object from this state can go in any of the following states:
648  * * \ref single_state_fn_table
649  * * \ref dialed_pending_state_fn_table
650  * * \ref bridge_state_fn_table
651  * * \ref finalized_state_fn_table
652  */
654  .name = "DialedPending",
655  .process_party_a = dialed_pending_state_process_party_a,
656  .process_dial_begin = dialed_pending_state_process_dial_begin,
657  .process_bridge_enter = dialed_pending_state_process_bridge_enter,
658  .process_parking_bridge_enter = dialed_pending_state_process_parking_bridge_enter,
659  .process_bridge_leave = base_process_bridge_leave,
660  .process_parked_channel = base_process_parked_channel,
661 };
662 
663 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
664 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
665 
666 /*!
667  * \brief The virtual table for the Bridged state
668  *
669  * A \ref cdr_object enters this state when it receives notification that the
670  * channel has entered a bridge.
671  *
672  * A \ref cdr_object from this state can go to:
673  * * \ref finalized_state_fn_table
674  */
676  .name = "Bridged",
677  .process_party_a = base_process_party_a,
678  .process_party_b = bridge_state_process_party_b,
679  .process_bridge_leave = bridge_state_process_bridge_leave,
680  .process_parked_channel = base_process_parked_channel,
681 };
682 
683 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
684 
685 /*!
686  * \brief The virtual table for the Parked state
687  *
688  * Parking is weird. Unlike typical bridges, it has to be treated somewhat
689  * uniquely - a channel in a parking bridge (which is a subclass of a holding
690  * bridge) has to be handled as if the channel went into an application.
691  * However, when the channel comes out, we need a new CDR - unlike the Single
692  * state.
693  */
695  .name = "Parked",
696  .process_party_a = base_process_party_a,
697  .process_bridge_leave = parked_state_process_bridge_leave,
698  .process_parked_channel = base_process_parked_channel,
699 };
700 
701 static void finalized_state_init_function(struct cdr_object *cdr);
702 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
703 
704 /*!
705  * \brief The virtual table for the finalized state.
706  *
707  * Once in the finalized state, the CDR is done. No modifications can be made
708  * to the CDR.
709  */
711  .name = "Finalized",
712  .init_function = finalized_state_init_function,
713  .process_party_a = finalized_state_process_party_a,
714  .process_bridge_enter = base_process_bridge_enter,
715 };
716 
717 /*! \brief A wrapper object around a snapshot.
718  * Fields that are mutable by the CDR engine are replicated here.
719  */
721  struct ast_channel_snapshot *snapshot; /*!< The channel snapshot */
722  char userfield[AST_MAX_USER_FIELD]; /*!< Userfield for the channel */
723  unsigned int flags; /*!< Specific flags for this party */
724  struct varshead variables; /*!< CDR variables for the channel */
725 };
726 
727 /*! \brief An in-memory representation of an active CDR */
728 struct cdr_object {
729  struct cdr_object_snapshot party_a; /*!< The Party A information */
730  struct cdr_object_snapshot party_b; /*!< The Party B information */
731  struct cdr_object_fn_table *fn_table; /*!< The current virtual table */
732 
733  enum ast_cdr_disposition disposition; /*!< The disposition of the CDR */
734  struct timeval start; /*!< When this CDR was created */
735  struct timeval answer; /*!< Either when the channel was answered, or when the path between channels was established */
736  struct timeval end; /*!< When this CDR was finalized */
737  struct timeval lastevent; /*!< The time at which the last event was created regarding this CDR */
738  unsigned int sequence; /*!< A monotonically increasing number for each CDR */
739  struct ast_flags flags; /*!< Flags on the CDR */
741  AST_STRING_FIELD(linkedid); /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
742  AST_STRING_FIELD(uniqueid); /*!< Unique id of party A. Cached here as it is the master CDR container key */
743  AST_STRING_FIELD(name); /*!< Channel name of party A. Cached here as the party A address may change */
744  AST_STRING_FIELD(bridge); /*!< The bridge the party A happens to be in. */
745  AST_STRING_FIELD(appl); /*!< The last accepted application party A was in */
746  AST_STRING_FIELD(data); /*!< The data for the last accepted application party A was in */
747  AST_STRING_FIELD(context); /*!< The accepted context for Party A */
748  AST_STRING_FIELD(exten); /*!< The accepted extension for Party A */
749  AST_STRING_FIELD(party_b_name); /*!< Party B channel name. Cached here as it is the all CDRs container key */
750  );
751  struct cdr_object *next; /*!< The next CDR object in the chain */
752  struct cdr_object *last; /*!< The last CDR object in the chain */
753  int is_root; /*!< True if this is the first CDR in the chain */
754 };
755 
756 /*!
757  * \brief Copy variables from one list to another
758  * \param to_list destination
759  * \param from_list source
760  * \return The number of copied variables
761  */
762 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
763 {
764  struct ast_var_t *variables;
765  struct ast_var_t *newvariable;
766  const char *var;
767  const char *val;
768  int x = 0;
769 
770  AST_LIST_TRAVERSE(from_list, variables, entries) {
771  var = ast_var_name(variables);
772  if (ast_strlen_zero(var)) {
773  continue;
774  }
775  val = ast_var_value(variables);
776  if (ast_strlen_zero(val)) {
777  continue;
778  }
779  newvariable = ast_var_assign(var, val);
780  if (newvariable) {
781  AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
782  ++x;
783  }
784  }
785 
786  return x;
787 }
788 
789 /*!
790  * \brief Delete all variables from a variable list
791  * \param headp The head pointer to the variable list to delete
792  */
793 static void free_variables(struct varshead *headp)
794 {
795  struct ast_var_t *vardata;
796 
797  while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
798  ast_var_delete(vardata);
799  }
800 }
801 
802 /*!
803  * \brief Copy a snapshot and its details
804  * \param dst The destination
805  * \param src The source
806  */
808 {
809  ao2_t_replace(dst->snapshot, src->snapshot, "CDR snapshot copy");
810  strcpy(dst->userfield, src->userfield);
811  dst->flags = src->flags;
812  copy_variables(&dst->variables, &src->variables);
813 }
814 
815 /*!
816  * \brief Transition a \ref cdr_object to a new state with initiation flag
817  * \param cdr The \ref cdr_object to transition
818  * \param fn_table The \ref cdr_object_fn_table state to go to
819  * \param do_init
820  */
821 static void cdr_object_transition_state_init(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table, int do_init)
822 {
823  CDR_DEBUG("%p - Transitioning CDR for %s from state %s to %s\n",
824  cdr, cdr->party_a.snapshot->base->name,
825  cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
826  cdr->fn_table = fn_table;
827 
828  if (cdr->fn_table->init_function && do_init) {
829  cdr->fn_table->init_function(cdr);
830  }
831 }
832 
833 /*!
834  * \brief Transition a \ref cdr_object to a new state
835  * \param cdr The \ref cdr_object to transition
836  * \param fn_table The \ref cdr_object_fn_table state to go to
837  */
838 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
839 {
840  cdr_object_transition_state_init(cdr, fn_table, 1);
841 }
842 
843 /*!
844  * \internal
845  * \brief Hash function for master CDR container indexed by Party A uniqueid.
846  */
847 static int cdr_master_hash_fn(const void *obj, const int flags)
848 {
849  const struct cdr_object *cdr;
850  const char *key;
851 
852  switch (flags & OBJ_SEARCH_MASK) {
853  case OBJ_SEARCH_KEY:
854  key = obj;
855  break;
856  case OBJ_SEARCH_OBJECT:
857  cdr = obj;
858  key = cdr->uniqueid;
859  break;
860  default:
861  ast_assert(0);
862  return 0;
863  }
864  return ast_str_case_hash(key);
865 }
866 
867 /*!
868  * \internal
869  * \brief Comparison function for master CDR container indexed by Party A uniqueid.
870  */
871 static int cdr_master_cmp_fn(void *obj, void *arg, int flags)
872 {
873  struct cdr_object *left = obj;
874  struct cdr_object *right = arg;
875  const char *right_key = arg;
876  int cmp;
877 
878  switch (flags & OBJ_SEARCH_MASK) {
879  case OBJ_SEARCH_OBJECT:
880  right_key = right->uniqueid;
881  /* Fall through */
882  case OBJ_SEARCH_KEY:
883  cmp = strcmp(left->uniqueid, right_key);
884  break;
886  /*
887  * We could also use a partial key struct containing a length
888  * so strlen() does not get called for every comparison instead.
889  */
890  cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
891  break;
892  default:
893  /* Sort can only work on something with a full or partial key. */
894  ast_assert(0);
895  cmp = 0;
896  break;
897  }
898  return cmp ? 0 : CMP_MATCH;
899 }
900 
901 /*!
902  * \internal
903  * \brief Hash function for all CDR container indexed by Party B channel name.
904  */
905 static int cdr_all_hash_fn(const void *obj, const int flags)
906 {
907  const struct cdr_object *cdr;
908  const char *key;
909 
910  switch (flags & OBJ_SEARCH_MASK) {
911  case OBJ_SEARCH_KEY:
912  key = obj;
913  break;
914  case OBJ_SEARCH_OBJECT:
915  cdr = obj;
916  key = cdr->party_b_name;
917  break;
918  default:
919  ast_assert(0);
920  return 0;
921  }
922  return ast_str_case_hash(key);
923 }
924 
925 /*!
926  * \internal
927  * \brief Comparison function for all CDR container indexed by Party B channel name.
928  */
929 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
930 {
931  struct cdr_object *left = obj;
932  struct cdr_object *right = arg;
933  const char *right_key = arg;
934  int cmp;
935 
936  switch (flags & OBJ_SEARCH_MASK) {
937  case OBJ_SEARCH_OBJECT:
938  right_key = right->party_b_name;
939  /* Fall through */
940  case OBJ_SEARCH_KEY:
941  cmp = strcasecmp(left->party_b_name, right_key);
942  break;
944  /*
945  * We could also use a partial key struct containing a length
946  * so strlen() does not get called for every comparison instead.
947  */
948  cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
949  break;
950  default:
951  /* Sort can only work on something with a full or partial key. */
952  ast_assert(0);
953  cmp = 0;
954  break;
955  }
956  return cmp ? 0 : CMP_MATCH;
957 }
958 
959 /*!
960  * \internal
961  * \brief Relink the CDR because Party B's snapshot changed.
962  * \since 13.19.0
963  */
964 static void cdr_all_relink(struct cdr_object *cdr)
965 {
967  if (cdr->party_b.snapshot) {
968  if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->base->name)) {
972  }
973  } else {
976  }
978 }
979 
980 /*!
981  * \internal
982  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
983  * \since 13.19.0
984  */
985 static void cdr_all_unlink(struct cdr_object *cdr)
986 {
987  struct cdr_object *cur;
988  struct cdr_object *next;
989 
990  ast_assert(cdr->is_root);
991 
992  /* Hold a ref to the root CDR to ensure the list members don't go away on us. */
993  ao2_ref(cdr, +1);
995  for (cur = cdr; cur; cur = next) {
996  next = cur->next;
998  /*
999  * It is safe to still use cur after unlinking because the
1000  * root CDR holds a ref to all the CDRs in the list and we
1001  * have a ref to the root CDR.
1002  */
1004  }
1006  ao2_ref(cdr, -1);
1007 }
1008 
1009 /*!
1010  * \brief \ref cdr_object Destructor
1011  */
1012 static void cdr_object_dtor(void *obj)
1013 {
1014  struct cdr_object *cdr = obj;
1015  struct ast_var_t *it_var;
1016 
1019  while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
1020  ast_var_delete(it_var);
1021  }
1022  while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
1023  ast_var_delete(it_var);
1024  }
1026 
1027  /* CDR destruction used to work by calling ao2_cleanup(next) and
1028  * allowing the chain to destroy itself neatly. Unfortunately, for
1029  * really long chains, this can result in a stack overflow. So now
1030  * when the root CDR is destroyed, it is responsible for unreffing
1031  * all CDRs in the chain
1032  */
1033  if (cdr->is_root) {
1034  struct cdr_object *curr = cdr->next;
1035  struct cdr_object *next;
1036 
1037  while (curr) {
1038  next = curr->next;
1039  ao2_cleanup(curr);
1040  curr = next;
1041  }
1042  }
1043 }
1044 
1045 /*!
1046  * \brief \ref cdr_object constructor
1047  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1048  * \param event_time
1049  *
1050  * This implicitly sets the state of the newly created CDR to the Single state
1051  * (\ref single_state_fn_table)
1052  */
1053 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan, const struct timeval *event_time)
1054 {
1055  struct cdr_object *cdr;
1056 
1057  ast_assert(chan != NULL);
1058 
1059  cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1060  if (!cdr) {
1061  return NULL;
1062  }
1063  cdr->last = cdr;
1064  if (ast_string_field_init(cdr, 64)) {
1065  ao2_cleanup(cdr);
1066  return NULL;
1067  }
1069  ast_string_field_set(cdr, name, chan->base->name);
1071  cdr->disposition = AST_CDR_NULL;
1073  cdr->lastevent = *event_time;
1074 
1075  cdr->party_a.snapshot = chan;
1076  ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1077 
1078  CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->base->name);
1079 
1081 
1082  return cdr;
1083 }
1084 
1085 /*!
1086  * \brief Create a new \ref cdr_object and append it to an existing chain
1087  * \param cdr The \ref cdr_object to append to
1088  * \param event_time
1089  */
1090 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr, const struct timeval *event_time)
1091 {
1092  struct cdr_object *new_cdr;
1093  struct cdr_object *it_cdr;
1094  struct cdr_object *cdr_last;
1095 
1096  cdr_last = cdr->last;
1097  new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot, event_time);
1098  if (!new_cdr) {
1099  return NULL;
1100  }
1101  new_cdr->disposition = AST_CDR_NULL;
1102 
1103  /* Copy over the linkedid, as it may have changed */
1104  ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1105  ast_string_field_set(new_cdr, appl, cdr_last->appl);
1106  ast_string_field_set(new_cdr, data, cdr_last->data);
1107  ast_string_field_set(new_cdr, context, cdr_last->context);
1108  ast_string_field_set(new_cdr, exten, cdr_last->exten);
1109 
1110  /*
1111  * If the current CDR says to disable all future ones,
1112  * keep the disable chain going
1113  */
1114  if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1116  }
1117 
1118  /* Copy over other Party A information */
1119  cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1120 
1121  /* Append the CDR to the end of the list */
1122  for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1123  it_cdr->last = new_cdr;
1124  }
1125  it_cdr->last = new_cdr;
1126  it_cdr->next = new_cdr;
1127 
1128  return new_cdr;
1129 }
1130 
1131 /*!
1132  * \internal
1133  * \brief Determine if CDR flag is configured.
1134  *
1135  * \param cdr_flag The configured CDR flag to check.
1136  *
1137  * \retval 0 if the CDR flag is not configured.
1138  * \retval non-zero if the CDR flag is configured.
1139  */
1140 static int is_cdr_flag_set(unsigned int cdr_flag)
1141 {
1142  struct module_config *mod_cfg;
1143  int flag_set;
1144 
1145  mod_cfg = ao2_global_obj_ref(module_configs);
1146  flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1147  ao2_cleanup(mod_cfg);
1148  return flag_set;
1149 }
1150 
1151 /*!
1152  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1153  * to endbeforehexten logic
1154  *
1155  * \param old_snapshot The previous state
1156  * \param new_snapshot The new state
1157  *
1158  * \retval 0 if the state has not changed
1159  * \retval 1 if the state changed
1160  */
1161 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1162  struct ast_channel_snapshot *new_snapshot)
1163 {
1164  /* If we ignore hangup logic, don't indicate that we're executing anything new */
1167  return 0;
1168  }
1169 
1170  /* When Party A is originated to an application and the application exits, the stack
1171  * will attempt to clear the application and restore the dummy originate application
1172  * of "AppDialX". Ignore application changes to AppDialX as a result.
1173  */
1174  if (strcmp(new_snapshot->dialplan->appl, old_snapshot->dialplan->appl)
1175  && strncasecmp(new_snapshot->dialplan->appl, "appdial", 7)
1176  && (strcmp(new_snapshot->dialplan->context, old_snapshot->dialplan->context)
1177  || strcmp(new_snapshot->dialplan->exten, old_snapshot->dialplan->exten)
1178  || new_snapshot->dialplan->priority != old_snapshot->dialplan->priority)) {
1179  return 1;
1180  }
1181 
1182  return 0;
1183 }
1184 
1185 /*!
1186  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1187  * that was created as the result of a dial operation
1188  *
1189  * \retval 0 the channel was not created as the result of a dial
1190  * \retval 1 the channel was created as the result of a dial
1191  */
1192 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1193 {
1194  return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1195  && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1196 }
1197 
1198 /*!
1199  * \brief Given two CDR snapshots, figure out who should be Party A for the
1200  * resulting CDR
1201  * \param left One of the snapshots
1202  * \param right The other snapshot
1203  * \return The snapshot that won
1204  */
1206 {
1207  /* Check whether or not the party is dialed. A dialed party is never the
1208  * Party A with a party that was not dialed.
1209  */
1210  if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1211  return left;
1212  } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1213  return right;
1214  }
1215 
1216  /* Try the Party A flag */
1218  return left;
1219  } else if (!ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1220  return right;
1221  }
1222 
1223  /* Neither party is dialed and neither has the Party A flag - defer to
1224  * creation time */
1225  if (left->snapshot->base->creationtime.tv_sec < right->snapshot->base->creationtime.tv_sec) {
1226  return left;
1227  } else if (left->snapshot->base->creationtime.tv_sec > right->snapshot->base->creationtime.tv_sec) {
1228  return right;
1229  } else if (left->snapshot->base->creationtime.tv_usec > right->snapshot->base->creationtime.tv_usec) {
1230  return right;
1231  } else {
1232  /* Okay, fine, take the left one */
1233  return left;
1234  }
1235 }
1236 
1237 /*!
1238  * Compute the duration for a \ref cdr_object
1239  */
1240 static long cdr_object_get_duration(struct cdr_object *cdr)
1241 {
1242  return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1243 }
1244 
1245 /*!
1246  * \brief Compute the billsec for a \ref cdr_object
1247  */
1248 static long cdr_object_get_billsec(struct cdr_object *cdr)
1249 {
1250  long int ms;
1251 
1252  if (ast_tvzero(cdr->answer)) {
1253  return 0;
1254  }
1255 
1256  ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1257  if (ms % 1000 >= 500
1259  ms = (ms / 1000) + 1;
1260  } else {
1261  ms = ms / 1000;
1262  }
1263 
1264  return ms;
1265 }
1266 
1267 /*!
1268  * \internal
1269  * \brief Set a variable on a CDR object
1270  *
1271  * \param headp The header pointer to the variable to set
1272  * \param name The name of the variable
1273  * \param value The value of the variable
1274  */
1275 static void set_variable(struct varshead *headp, const char *name, const char *value)
1276 {
1277  struct ast_var_t *newvariable;
1278 
1279  AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1280  if (!strcasecmp(ast_var_name(newvariable), name)) {
1282  ast_var_delete(newvariable);
1283  break;
1284  }
1285  }
1287 
1288  if (value && (newvariable = ast_var_assign(name, value))) {
1289  AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1290  }
1291 }
1292 
1293 /*!
1294  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1295  * suitable for consumption by the registered CDR backends
1296  * \param cdr The \ref cdr_object to convert to a public record
1297  * \return A chain of \ref ast_cdr objects on success
1298  * \retval NULL on failure
1299  */
1301 {
1302  struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1303  struct cdr_object *it_cdr;
1304  struct ast_var_t *it_var, *it_copy_var;
1305  struct ast_channel_snapshot *party_a;
1306  struct ast_channel_snapshot *party_b;
1307 
1308  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1309  struct ast_cdr *cdr_copy;
1310 
1311  /* Don't create records for CDRs where the party A was a dialed channel */
1312  if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1313  ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1314  it_cdr->party_a.snapshot->base->name);
1315  continue;
1316  }
1317 
1318  cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1319  if (!cdr_copy) {
1320  ast_free(pub_cdr);
1321  return NULL;
1322  }
1323 
1324  party_a = it_cdr->party_a.snapshot;
1325  party_b = it_cdr->party_b.snapshot;
1326 
1327  /* Party A */
1328  ast_assert(party_a != NULL);
1329  ast_copy_string(cdr_copy->accountcode, party_a->base->accountcode, sizeof(cdr_copy->accountcode));
1330  cdr_copy->amaflags = party_a->amaflags;
1331  ast_copy_string(cdr_copy->channel, party_a->base->name, sizeof(cdr_copy->channel));
1332  ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller->name, party_a->caller->number, "");
1333  ast_copy_string(cdr_copy->src, party_a->caller->number, sizeof(cdr_copy->src));
1334  ast_copy_string(cdr_copy->uniqueid, party_a->base->uniqueid, sizeof(cdr_copy->uniqueid));
1335  ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1336  ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1337  ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1338  ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1339 
1340  /* Party B */
1341  if (party_b) {
1342  ast_copy_string(cdr_copy->dstchannel, party_b->base->name, sizeof(cdr_copy->dstchannel));
1343  ast_copy_string(cdr_copy->peeraccount, party_b->base->accountcode, sizeof(cdr_copy->peeraccount));
1344  if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1345  snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1346  }
1347  }
1348  if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1349  ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1350  }
1351 
1352  /* Timestamps/durations */
1353  cdr_copy->start = it_cdr->start;
1354  cdr_copy->answer = it_cdr->answer;
1355  cdr_copy->end = it_cdr->end;
1356  cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1357  cdr_copy->duration = cdr_object_get_duration(it_cdr);
1358 
1359  /* Flags and IDs */
1360  ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1361  ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1362  cdr_copy->disposition = it_cdr->disposition;
1363  cdr_copy->sequence = it_cdr->sequence;
1364 
1365  /* Variables */
1366  copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1367  AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1368  int found = 0;
1369  struct ast_var_t *newvariable;
1370  AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1371  if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1372  found = 1;
1373  break;
1374  }
1375  }
1376  if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1377  AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1378  }
1379  }
1380 
1381  if (!pub_cdr) {
1382  pub_cdr = cdr_copy;
1383  cdr_prev = pub_cdr;
1384  } else {
1385  cdr_prev->next = cdr_copy;
1386  cdr_prev = cdr_copy;
1387  }
1388  }
1389 
1390  return pub_cdr;
1391 }
1392 
1393 /*!
1394  * \brief Dispatch a CDR.
1395  * \param cdr The \ref cdr_object to dispatch
1396  *
1397  * This will create a \ref ast_cdr object and publish it to the various backends
1398  */
1399 static void cdr_object_dispatch(struct cdr_object *cdr)
1400 {
1401  struct ast_cdr *pub_cdr;
1402 
1403  CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1404  cdr->party_a.snapshot->base->name,
1405  cdr->party_b.snapshot ? cdr->party_b.snapshot->base->name : "<none>");
1406  pub_cdr = cdr_object_create_public_records(cdr);
1407  cdr_detach(pub_cdr);
1408 }
1409 
1410 /*!
1411  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1412  * \param cdr The \ref cdr_object
1413  * \param hangupcause The Asterisk hangup cause code
1414  */
1415 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1416 {
1417  /* Change the disposition based on the hang up cause */
1418  switch (hangupcause) {
1419  case AST_CAUSE_BUSY:
1420  cdr->disposition = AST_CDR_BUSY;
1421  break;
1422  case AST_CAUSE_CONGESTION:
1424  cdr->disposition = AST_CDR_FAILED;
1425  } else {
1427  }
1428  break;
1431  cdr->disposition = AST_CDR_FAILED;
1432  break;
1434  case AST_CAUSE_NO_ANSWER:
1436  break;
1437  default:
1438  break;
1439  }
1440 }
1441 
1442 /*!
1443  * \brief Finalize a CDR.
1444  *
1445  * This function is safe to call multiple times. Note that you can call this
1446  * explicitly before going to the finalized state if there's a chance the CDR
1447  * will be re-activated, in which case the \p cdr's end time should be
1448  * cleared. This function is implicitly called when a CDR transitions to the
1449  * finalized state and right before it is dispatched
1450  *
1451  * \param cdr The CDR to finalize
1452  */
1453 static void cdr_object_finalize(struct cdr_object *cdr)
1454 {
1455  if (!ast_tvzero(cdr->end)) {
1456  return;
1457  }
1458  cdr->end = cdr->lastevent;
1459 
1460  if (cdr->disposition == AST_CDR_NULL) {
1461  if (!ast_tvzero(cdr->answer)) {
1463  } else if (cdr->party_a.snapshot->hangup->cause) {
1465  } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangup->cause) {
1467  } else {
1468  cdr->disposition = AST_CDR_FAILED;
1469  }
1470  }
1471 
1472  /* tv_usec is suseconds_t, which could be int or long */
1473  ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dur %.3f bill %.3f dispo %s\n",
1474  cdr->party_a.snapshot->base->name,
1475  (long)cdr->start.tv_sec,
1476  (long)cdr->start.tv_usec,
1477  (long)cdr->answer.tv_sec,
1478  (long)cdr->answer.tv_usec,
1479  (long)cdr->end.tv_sec,
1480  (long)cdr->end.tv_usec,
1481  (double)ast_tvdiff_ms(cdr->end, cdr->start) / 1000.0,
1482  (double)ast_tvdiff_ms(cdr->end, cdr->answer) / 1000.0,
1484 }
1485 
1486 /*!
1487  * \brief Check to see if a CDR needs to move to the finalized state because
1488  * its Party A hungup.
1489  */
1491 {
1494  cdr_object_finalize(cdr);
1495  }
1496 
1498  && cdr->fn_table != &finalized_state_fn_table) {
1500  }
1501 }
1502 
1503 /*!
1504  * \brief Check to see if a CDR needs to be answered based on its Party A.
1505  * Note that this is safe to call as much as you want - we won't answer twice
1506  */
1508 {
1509  if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1510  cdr->answer = cdr->lastevent;
1511  /* tv_usec is suseconds_t, which could be int or long */
1512  CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1513  (long)cdr->answer.tv_sec,
1514  (long)cdr->answer.tv_usec);
1515  }
1516 }
1517 
1518 /*! \brief Set Caller ID information on a CDR */
1519 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1520 {
1521  if (!old_snapshot->snapshot) {
1522  set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1523  set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1524  set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1525  return;
1526  }
1527  if (strcmp(old_snapshot->snapshot->caller->dnid, new_snapshot->caller->dnid)) {
1528  set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1529  }
1530  if (strcmp(old_snapshot->snapshot->caller->subaddr, new_snapshot->caller->subaddr)) {
1531  set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1532  }
1533  if (strcmp(old_snapshot->snapshot->caller->dialed_subaddr, new_snapshot->caller->dialed_subaddr)) {
1534  set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1535  }
1536 }
1537 
1538 /*!
1539  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1540  * a new \ref ast_channel_snapshot
1541  * \param old_snapshot The old \ref cdr_object_snapshot
1542  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1543  */
1544 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1545  struct ast_channel_snapshot *new_snapshot)
1546 {
1547  cdr_object_update_cid(old_snapshot, new_snapshot);
1548  ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1549 }
1550 
1551 /* BASE METHOD IMPLEMENTATIONS */
1552 
1553 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1554 {
1555  ast_assert(strcasecmp(snapshot->base->name, cdr->party_a.snapshot->base->name) == 0);
1556 
1557  /* Finalize the CDR if we're in hangup logic and we're set to do so */
1560  cdr_object_finalize(cdr);
1561  return 0;
1562  }
1563 
1564  /*
1565  * Only record the context and extension if we aren't in a subroutine, or if
1566  * we are executing hangup logic.
1567  */
1568  if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1570  if (strcmp(cdr->context, snapshot->dialplan->context)) {
1571  ast_string_field_set(cdr, context, snapshot->dialplan->context);
1572  }
1573  if (strcmp(cdr->exten, snapshot->dialplan->exten)) {
1574  ast_string_field_set(cdr, exten, snapshot->dialplan->exten);
1575  }
1576  }
1577 
1578  cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1579 
1580  /* When Party A is originated to an application and the application exits, the stack
1581  * will attempt to clear the application and restore the dummy originate application
1582  * of "AppDialX". Prevent that, and any other application changes we might not want
1583  * here.
1584  */
1585  if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1586  && !ast_strlen_zero(snapshot->dialplan->appl)
1587  && (strncasecmp(snapshot->dialplan->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1588  if (strcmp(cdr->appl, snapshot->dialplan->appl)) {
1589  ast_string_field_set(cdr, appl, snapshot->dialplan->appl);
1590  }
1591  if (strcmp(cdr->data, snapshot->dialplan->data)) {
1592  ast_string_field_set(cdr, data, snapshot->dialplan->data);
1593  }
1594 
1595  /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1596  * execute before the dial begins, will alter the application/data to
1597  * something people typically don't want to see, if we see a channel enter
1598  * into Dial here, we set the appl/data accordingly and lock it.
1599  */
1600  if (!strcmp(snapshot->dialplan->appl, "Dial")) {
1602  }
1603  }
1604 
1605  if (strcmp(cdr->linkedid, snapshot->peer->linkedid)) {
1606  ast_string_field_set(cdr, linkedid, snapshot->peer->linkedid);
1607  }
1610 
1611  return 0;
1612 }
1613 
1615 {
1616  return 0;
1617 }
1618 
1619 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1620 {
1621  return 0;
1622 }
1623 
1625 {
1626  /* Base process bridge enter simply indicates that we can't handle it */
1627  return BRIDGE_ENTER_NEED_CDR;
1628 }
1629 
1630 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1631 {
1632  char park_info[128];
1633 
1634  ast_assert(!strcasecmp(parking_info->parkee->base->name, cdr->party_a.snapshot->base->name));
1635 
1636  /* Update Party A information regardless */
1637  cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1638 
1639  /* Fake out where we're parked */
1640  ast_string_field_set(cdr, appl, "Park");
1641  snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1642  ast_string_field_set(cdr, data, park_info);
1643 
1644  /* Prevent any further changes to the App/Data fields for this record */
1646 
1647  return 0;
1648 }
1649 
1650 /* SINGLE STATE */
1651 
1652 static void single_state_init_function(struct cdr_object *cdr)
1653 {
1654  cdr->start = cdr->lastevent;
1656 }
1657 
1658 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1659 {
1660  /* This should never happen! */
1661  ast_assert(cdr->party_b.snapshot == NULL);
1662  ast_assert(0);
1663  return;
1664 }
1665 
1666 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1667 {
1668  if (caller && !strcasecmp(cdr->party_a.snapshot->base->name, caller->base->name)) {
1669  base_process_party_a(cdr, caller);
1670  CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1671  cdr->party_a.snapshot->base->name);
1672  cdr_object_swap_snapshot(&cdr->party_b, peer);
1673  cdr_all_relink(cdr);
1674  CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1675  cdr->party_b.snapshot->base->name);
1676 
1677  /* If we have two parties, lock the application that caused the
1678  * two parties to be associated. This prevents mid-call event
1679  * macros/gosubs from perturbing the CDR application/data
1680  */
1682  } else if (!strcasecmp(cdr->party_a.snapshot->base->name, peer->base->name)) {
1683  /* We're the entity being dialed, i.e., outbound origination */
1684  base_process_party_a(cdr, peer);
1685  CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1686  cdr->party_a.snapshot->base->name);
1687  }
1688 
1690  return 0;
1691 }
1692 
1693 /*!
1694  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1695  * already in the bridge while in the Single state. The goal of this is to find
1696  * a Party B for our CDR.
1697  *
1698  * \param cdr Our \ref cdr_object in the Single state
1699  * \param cand_cdr The \ref cdr_object already in the Bridge state
1700  *
1701  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1702  * Party B
1703  * \retval 1 No party in the cand_cdr could be used as our Party B
1704  */
1706  struct cdr_object *cand_cdr)
1707 {
1708  struct cdr_object_snapshot *party_a;
1709 
1710  /* Don't match on ourselves */
1711  if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1712  return 1;
1713  }
1714 
1715  /* Try the candidate CDR's Party A first */
1716  party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1717  if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1718  CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1719  cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name);
1720  cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1721  cdr_all_relink(cdr);
1722  if (!cand_cdr->party_b.snapshot) {
1723  /* We just stole them - finalize their CDR. Note that this won't
1724  * transition their state, it just sets the end time and the
1725  * disposition - if we need to re-activate them later, we can.
1726  */
1727  cdr_object_finalize(cand_cdr);
1728  }
1729  return 0;
1730  }
1731 
1732  /* Try their Party B, unless it's us */
1733  if (!cand_cdr->party_b.snapshot
1734  || !strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name)) {
1735  return 1;
1736  }
1737  party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1738  if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1739  CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1740  cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name);
1741  cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1742  cdr_all_relink(cdr);
1743  return 0;
1744  }
1745 
1746  return 1;
1747 }
1748 
1750 {
1751  struct ao2_iterator it_cdrs;
1752  char *channel_id;
1753  int success = 0;
1754 
1755  ast_string_field_set(cdr, bridge, bridge->uniqueid);
1756 
1757  if (ao2_container_count(bridge->channels) == 1) {
1758  /* No one in the bridge yet but us! */
1760  return BRIDGE_ENTER_ONLY_PARTY;
1761  }
1762 
1763  for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1764  !success && (channel_id = ao2_iterator_next(&it_cdrs));
1765  ao2_ref(channel_id, -1)) {
1766  struct cdr_object *cand_cdr_master;
1767  struct cdr_object *cand_cdr;
1768 
1769  cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1770  if (!cand_cdr_master) {
1771  continue;
1772  }
1773 
1774  ao2_lock(cand_cdr_master);
1775  for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1776  /* Skip any records that are not in a bridge or in this bridge.
1777  * I'm not sure how that would happen, but it pays to be careful. */
1778  if (cand_cdr->fn_table != &bridge_state_fn_table ||
1779  strcmp(cdr->bridge, cand_cdr->bridge)) {
1780  continue;
1781  }
1782 
1783  if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1784  continue;
1785  }
1786  /* We successfully got a party B - break out */
1787  success = 1;
1788  break;
1789  }
1790  ao2_unlock(cand_cdr_master);
1791  ao2_cleanup(cand_cdr_master);
1792  }
1793  ao2_iterator_destroy(&it_cdrs);
1794 
1795  /* We always transition state, even if we didn't get a peer */
1797 
1798  /* Success implies that we have a Party B */
1799  if (success) {
1801  }
1802 
1803  return BRIDGE_ENTER_NO_PARTY_B;
1804 }
1805 
1807 {
1809  return 0;
1810 }
1811 
1812 
1813 /* DIAL STATE */
1814 
1815 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1816 {
1817  ast_assert(snapshot != NULL);
1819  && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
1820 
1821  cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1822 
1823  /* If party B hangs up, finalize this CDR */
1826  }
1827 }
1828 
1829 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1830 {
1831  /* Don't process a begin dial here. A party A already in the dial state will
1832  * who receives a dial begin for something else will be handled by the
1833  * message router callback and will add a new CDR for the party A */
1834  return 1;
1835 }
1836 
1837 /*!
1838  * \internal
1839  * \brief Convert a dial status to a CDR disposition
1840  */
1841 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1842 {
1843  if (!strcmp(dial_status, "ANSWER")) {
1844  return AST_CDR_ANSWERED;
1845  } else if (!strcmp(dial_status, "BUSY")) {
1846  return AST_CDR_BUSY;
1847  } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1848  return AST_CDR_NOANSWER;
1849  } else if (!strcmp(dial_status, "CONGESTION")) {
1851  return AST_CDR_FAILED;
1852  } else {
1853  return AST_CDR_CONGESTION;
1854  }
1855  } else if (!strcmp(dial_status, "FAILED")) {
1856  return AST_CDR_FAILED;
1857  }
1858  return AST_CDR_FAILED;
1859 }
1860 
1861 static int dial_state_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1862 {
1863  struct ast_channel_snapshot *party_a;
1864 
1865  if (caller) {
1866  party_a = caller;
1867  } else {
1868  party_a = peer;
1869  }
1870  ast_assert(!strcasecmp(cdr->party_a.snapshot->base->name, party_a->base->name));
1871  cdr_object_swap_snapshot(&cdr->party_a, party_a);
1872 
1873  if (cdr->party_b.snapshot) {
1874  if (strcasecmp(cdr->party_b.snapshot->base->name, peer->base->name)) {
1875  /* Not the status for this CDR - defer back to the message router */
1876  return 1;
1877  }
1879  }
1880 
1881  /* Set the disposition based on the dial string. */
1882  cdr->disposition = dial_status_to_disposition(dial_status);
1883  if (cdr->disposition == AST_CDR_ANSWERED) {
1884  /* Switch to dial pending to wait and see what the caller does */
1886  } else {
1888  }
1889 
1890  return 0;
1891 }
1892 
1894 {
1895  int success = 0;
1896 
1897  ast_string_field_set(cdr, bridge, bridge->uniqueid);
1898 
1899  /* Get parties in the bridge */
1900  if (ao2_container_count(bridge->channels) == 1) {
1901  /* No one in the bridge yet but us! */
1903  return BRIDGE_ENTER_ONLY_PARTY;
1904  }
1905 
1906  /* If we don't have a Party B (originated channel), skip it */
1907  if (cdr->party_b.snapshot) {
1908  struct ao2_iterator it_cdrs;
1909  char *channel_id;
1910 
1911  for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1912  !success && (channel_id = ao2_iterator_next(&it_cdrs));
1913  ao2_ref(channel_id, -1)) {
1914  struct cdr_object *cand_cdr_master;
1915  struct cdr_object *cand_cdr;
1916 
1917  cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1918  if (!cand_cdr_master) {
1919  continue;
1920  }
1921 
1922  ao2_lock(cand_cdr_master);
1923  for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1924  /* Skip any records that are not in a bridge or in this bridge.
1925  * I'm not sure how that would happen, but it pays to be careful. */
1926  if (cand_cdr->fn_table != &bridge_state_fn_table
1927  || strcmp(cdr->bridge, cand_cdr->bridge)) {
1928  continue;
1929  }
1930 
1931  /* Skip any records that aren't our Party B */
1932  if (strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1933  continue;
1934  }
1935  cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1936  /* If they have a Party B, they joined up with someone else as their
1937  * Party A. Don't finalize them as they're active. Otherwise, we
1938  * have stolen them so they need to be finalized.
1939  */
1940  if (!cand_cdr->party_b.snapshot) {
1941  cdr_object_finalize(cand_cdr);
1942  }
1943  success = 1;
1944  break;
1945  }
1946  ao2_unlock(cand_cdr_master);
1947  ao2_cleanup(cand_cdr_master);
1948  }
1949  ao2_iterator_destroy(&it_cdrs);
1950  }
1951 
1952  /* We always transition state, even if we didn't get a peer */
1954 
1955  /* Success implies that we have a Party B */
1956  if (success) {
1958  }
1959  return BRIDGE_ENTER_NO_PARTY_B;
1960 }
1961 
1962 /* DIALED PENDING STATE */
1963 
1965 {
1966  /* If we get a CEP change, we're executing dialplan. If we have a Party B
1967  * that means we need a new CDR; otherwise, switch us over to single.
1968  */
1969  if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1970  if (cdr->party_b.snapshot) {
1972  cdr->fn_table->process_party_a(cdr, snapshot);
1973  return 1;
1974  } else {
1975  /* The CDR does not need to be reinitialized when transitioning
1976  * to its single state as this would overwrite the start time,
1977  * causing potentially both the answer and the start time to be
1978  * the same which is incorrect.
1979  */
1981  cdr->fn_table->process_party_a(cdr, snapshot);
1982  return 0;
1983  }
1984  }
1985  base_process_party_a(cdr, snapshot);
1986  return 0;
1987 }
1988 
1990 {
1992  return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1993 }
1994 
1996 {
1997  if (cdr->party_b.snapshot) {
1998  /* We can't handle this as we have a Party B - ask for a new one */
1999  return 1;
2000  }
2002  return 0;
2003 }
2004 
2006 {
2008 
2009  /* Ask for a new CDR */
2010  return 1;
2011 }
2012 
2013 /* BRIDGE STATE */
2014 
2015 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2016 {
2018  && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
2019 
2020  cdr_object_swap_snapshot(&cdr->party_b, snapshot);
2021 
2022  /* If party B hangs up, finalize this CDR */
2025  }
2026 }
2027 
2029 {
2030  if (strcmp(cdr->bridge, bridge->uniqueid)) {
2031  return 1;
2032  }
2033  if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)
2034  && cdr->party_b.snapshot
2035  && strcasecmp(cdr->party_b.snapshot->base->name, channel->base->name)) {
2036  return 1;
2037  }
2039 
2040  return 0;
2041 }
2042 
2043 /* PARKED STATE */
2044 
2046 {
2047  if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)) {
2048  return 1;
2049  }
2051 
2052  return 0;
2053 }
2054 
2055 /* FINALIZED STATE */
2056 
2058 {
2059  cdr_object_finalize(cdr);
2060 }
2061 
2062 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2063 {
2066  return 0;
2067  }
2068 
2069  /* Indicate that, if possible, we should get a new CDR */
2070  return 1;
2071 }
2072 
2073 /*!
2074  * \internal
2075  * \brief Filter channel snapshots by technology
2076  */
2077 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2078 {
2079  return snapshot->base->tech_properties & AST_CHAN_TP_INTERNAL;
2080 }
2081 
2082 /*!
2083  * \internal
2084  * \brief Filter a channel snapshot update
2085  */
2087  struct ast_channel_snapshot *new_snapshot)
2088 {
2089  int ret = 0;
2090 
2091  /* Drop cache updates from certain channel technologies */
2092  if (old_snapshot) {
2093  ret |= filter_channel_snapshot(old_snapshot);
2094  }
2095  if (new_snapshot) {
2096  ret |= filter_channel_snapshot(new_snapshot);
2097  }
2098 
2099  return ret;
2100 }
2101 
2102 static int dial_status_end(const char *dialstatus)
2103 {
2104  return (strcmp(dialstatus, "RINGING") &&
2105  strcmp(dialstatus, "PROCEEDING") &&
2106  strcmp(dialstatus, "PROGRESS"));
2107 }
2108 
2109 /* TOPIC ROUTER CALLBACKS */
2110 
2111 /*!
2112  * \brief Handler for Stasis-Core dial messages
2113  * \param data Passed on
2114  * \param sub The stasis subscription for this message callback
2115  * \param message The message
2116  */
2118 {
2119  struct cdr_object *cdr;
2121  struct ast_channel_snapshot *caller;
2122  struct ast_channel_snapshot *peer;
2123  struct cdr_object *it_cdr;
2124  struct ast_json *dial_status_blob;
2125  const char *dial_status = NULL;
2126  int res = 1;
2127 
2128  caller = ast_multi_channel_blob_get_channel(payload, "caller");
2129  peer = ast_multi_channel_blob_get_channel(payload, "peer");
2130  if (!peer && !caller) {
2131  return;
2132  }
2133 
2134  if (peer && filter_channel_snapshot(peer)) {
2135  return;
2136  }
2137 
2138  if (caller && filter_channel_snapshot(caller)) {
2139  return;
2140  }
2141 
2142  dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2143  if (dial_status_blob) {
2144  dial_status = ast_json_string_get(dial_status_blob);
2145  }
2146 
2147  CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2148  ast_strlen_zero(dial_status) ? "Begin" : "End",
2149  caller ? caller->base->name : "(none)",
2150  peer ? peer->base->name : "(none)",
2151  (unsigned int)stasis_message_timestamp(message)->tv_sec,
2152  (unsigned int)stasis_message_timestamp(message)->tv_usec);
2153 
2154  /* Figure out who is running this show */
2155  if (caller) {
2157  } else {
2159  }
2160  if (!cdr) {
2161  ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->base->name : peer->base->name);
2162  ast_assert(0);
2163  return;
2164  }
2165 
2166  ao2_lock(cdr);
2167  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2169  if (ast_strlen_zero(dial_status)) {
2170  if (!it_cdr->fn_table->process_dial_begin) {
2171  continue;
2172  }
2173  CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2174  it_cdr,
2175  caller ? caller->base->name : "(none)",
2176  peer ? peer->base->name : "(none)");
2177  res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2178  caller,
2179  peer);
2180  } else if (dial_status_end(dial_status)) {
2181  if (!it_cdr->fn_table->process_dial_end) {
2182  continue;
2183  }
2184  CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2185  it_cdr,
2186  caller ? caller->base->name : "(none)",
2187  peer ? peer->base->name : "(none)");
2188  it_cdr->fn_table->process_dial_end(it_cdr,
2189  caller,
2190  peer,
2191  dial_status);
2192  }
2193  }
2194 
2195  /* If no CDR handled a dial begin message, make a new one */
2196  if (res && ast_strlen_zero(dial_status)) {
2197  struct cdr_object *new_cdr;
2198 
2200  if (new_cdr) {
2201  new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2202  }
2203  }
2204  ao2_unlock(cdr);
2205  ao2_cleanup(cdr);
2206 }
2207 
2208 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2209 {
2210  struct cdr_object *cdr = obj;
2211 
2212  if (!strcasecmp(cdr->party_b_name, arg)) {
2213 #ifdef AST_DEVMODE
2214  struct ast_channel_snapshot *party_b = data;
2215 
2216  /*
2217  * For sanity's sake we also assert the party_b snapshot
2218  * is consistent with the key.
2219  */
2221  && !strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name));
2222 #endif
2223 
2224  /* Don't transition to the finalized state - let the Party A do
2225  * that when its ready
2226  */
2227  cdr_object_finalize(cdr);
2228  }
2229  return 0;
2230 }
2231 
2232 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2233 {
2234  struct cdr_object *cdr = obj;
2235 
2236  if (cdr->fn_table->process_party_b
2237  && !strcasecmp(cdr->party_b_name, arg)) {
2238  struct ast_channel_snapshot *party_b = data;
2239 
2240  /*
2241  * For sanity's sake we also check the party_b snapshot
2242  * for consistency with the key. The callback needs and
2243  * asserts the snapshot to be this way.
2244  */
2245  if (!cdr->party_b.snapshot
2246  || strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name)) {
2248  "CDR for Party A %s(%s) has inconsistent Party B %s name. Message can be ignored but this shouldn't happen.\n",
2249  cdr->linkedid,
2250  cdr->party_a.snapshot->base->name,
2251  cdr->party_b_name);
2252  return 0;
2253  }
2254 
2255  cdr->fn_table->process_party_b(cdr, party_b);
2256  }
2257  return 0;
2258 }
2259 
2260 /*! \brief Determine if we need to add a new CDR based on snapshots */
2261 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2262  struct ast_channel_snapshot *new_snapshot)
2263 {
2264  /* If we're dead, we don't need a new CDR */
2265  if (!new_snapshot
2268  return 0;
2269  }
2270 
2271  /* Auto-fall through will increment the priority but have no application */
2272  if (ast_strlen_zero(new_snapshot->dialplan->appl)) {
2273  return 0;
2274  }
2275 
2276  if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2277  return 0;
2278  }
2279 
2280  return 1;
2281 }
2282 
2283 /*!
2284  * \brief Handler for channel snapshot update messages
2285  * \param data Passed on
2286  * \param sub The stasis subscription for this message callback
2287  * \param message The message
2288  */
2290 {
2291  struct cdr_object *cdr;
2293  struct cdr_object *it_cdr;
2294 
2295  if (filter_channel_snapshot_message(update->old_snapshot, update->new_snapshot)) {
2296  return;
2297  }
2298 
2299  if (update->new_snapshot && !update->old_snapshot) {
2300  struct module_config *mod_cfg = NULL;
2301 
2303  if (!cdr) {
2304  return;
2305  }
2306  mod_cfg = ao2_global_obj_ref(module_configs);
2307  cdr->is_root = 1;
2309 
2310  /* If CDR should be disabled unless enabled on a per-channel basis, then disable
2311  CDR, right from the get go */
2312  if (mod_cfg) {
2314  ast_debug(3, "Disable CDR by default\n");
2316  }
2317  ao2_cleanup(mod_cfg);
2318  }
2319  } else {
2320  cdr = ao2_find(active_cdrs_master, update->new_snapshot->base->uniqueid, OBJ_SEARCH_KEY);
2321  }
2322 
2323  /* Handle Party A */
2324  if (!cdr) {
2325  ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", update->new_snapshot->base->name);
2326  ast_assert(0);
2327  } else {
2328  int all_reject = 1;
2329 
2330  ao2_lock(cdr);
2331  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2333  if (!it_cdr->fn_table->process_party_a) {
2334  continue;
2335  }
2336  all_reject &= it_cdr->fn_table->process_party_a(it_cdr, update->new_snapshot);
2337  }
2338  if (all_reject && check_new_cdr_needed(update->old_snapshot, update->new_snapshot)) {
2339  /* We're not hung up and we have a new snapshot - we need a new CDR */
2340  struct cdr_object *new_cdr;
2341 
2343  if (new_cdr) {
2344  new_cdr->fn_table->process_party_a(new_cdr, update->new_snapshot);
2345  }
2346  }
2347  ao2_unlock(cdr);
2348  }
2349 
2350  if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2351  ao2_lock(cdr);
2352  CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, update->old_snapshot->base->name);
2353  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2355  cdr_object_finalize(it_cdr);
2356  }
2357  cdr_object_dispatch(cdr);
2358  ao2_unlock(cdr);
2359 
2360  cdr_all_unlink(cdr);
2362  }
2363 
2364  /* Handle Party B */
2365  if (update->new_snapshot) {
2367  cdr_object_update_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2368  }
2369 
2370  if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2372  cdr_object_finalize_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2373  }
2374 
2375  ao2_cleanup(cdr);
2376 }
2377 
2381  const struct timeval *lastevent;
2382 };
2383 
2384 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2385 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2386 {
2387  struct cdr_object *cdr = obj;
2388  struct bridge_leave_data *leave_data = data;
2389 
2390  if (cdr->fn_table == &bridge_state_fn_table
2391  && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2392  && !strcasecmp(cdr->party_b_name, arg)) {
2393  /*
2394  * For sanity's sake we also assert the party_b snapshot
2395  * is consistent with the key.
2396  */
2398  && !strcasecmp(cdr->party_b.snapshot->base->name, leave_data->channel->base->name));
2399 
2400  /* It is our Party B, in our bridge. Set the last event and let the handler
2401  * transition our CDR appropriately when we leave the bridge.
2402  */
2403  cdr->lastevent = *leave_data->lastevent;
2404  cdr_object_finalize(cdr);
2405  }
2406  return 0;
2407 }
2408 
2409 /*! \brief Filter bridge messages based on bridge technology */
2411 {
2412  /* Ignore holding bridge technology messages. We treat this simply as an application
2413  * that a channel enters into.
2414  */
2415  if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2416  return 1;
2417  }
2418  return 0;
2419 }
2420 
2421 /*!
2422  * \brief Handler for when a channel leaves a bridge
2423  * \param data Passed on
2424  * \param sub The stasis subscription for this message callback
2425  * \param message The message - hopefully a bridge one!
2426  */
2427 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2428  struct stasis_message *message)
2429 {
2431  struct ast_bridge_snapshot *bridge = update->bridge;
2432  struct ast_channel_snapshot *channel = update->channel;
2433  struct cdr_object *cdr;
2434  struct cdr_object *it_cdr;
2435  struct bridge_leave_data leave_data = {
2436  .bridge = bridge,
2437  .channel = channel,
2438  .lastevent = stasis_message_timestamp(message)
2439  };
2440  int left_bridge = 0;
2441 
2443  return;
2444  }
2445 
2447  return;
2448  }
2449 
2450  CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2451  channel->base->name,
2452  (unsigned int)leave_data.lastevent->tv_sec,
2453  (unsigned int)leave_data.lastevent->tv_usec);
2454 
2456  if (!cdr) {
2457  ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2458  ast_assert(0);
2459  return;
2460  }
2461 
2462  /* Party A */
2463  ao2_lock(cdr);
2464  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2465  it_cdr->lastevent = *leave_data.lastevent;
2466  if (!it_cdr->fn_table->process_bridge_leave) {
2467  continue;
2468  }
2469  CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2470  it_cdr, channel->base->name);
2471  if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2472  ast_string_field_set(it_cdr, bridge, "");
2473  left_bridge = 1;
2474  }
2475  }
2476  ao2_unlock(cdr);
2477 
2478  /* Party B */
2479  if (left_bridge
2480  && strcmp(bridge->subclass, "parking")) {
2482  cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->base->name,
2483  &leave_data);
2484  }
2485 
2486  ao2_cleanup(cdr);
2487 }
2488 
2489 /*!
2490  * \internal
2491  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2492  *
2493  * \note The new CDR will be automatically transitioned to the bridge state
2494  */
2495 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2496  struct cdr_object_snapshot *party_b)
2497 {
2498  struct cdr_object *new_cdr;
2499 
2500  new_cdr = cdr_object_create_and_append(cdr, &cdr->lastevent);
2501  if (!new_cdr) {
2502  return;
2503  }
2505  cdr_all_relink(new_cdr);
2507  ast_string_field_set(new_cdr, bridge, cdr->bridge);
2509  CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2510  new_cdr, new_cdr->party_a.snapshot->base->name,
2511  party_b->snapshot->base->name);
2512 }
2513 
2514 /*!
2515  * \brief Process a single \c bridge_candidate
2516  *
2517  * When a CDR enters a bridge, it needs to make pairings with everyone else
2518  * that it is not currently paired with. This function determines, for the
2519  * CDR for the channel that entered the bridge and the CDR for every other
2520  * channel currently in the bridge, who is Party A and makes new CDRs.
2521  *
2522  * \param cdr The \ref cdr_object being processed
2523  * \param base_cand_cdr The \ref cdr_object that is a candidate
2524  *
2525  */
2526 static void bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2527 {
2528  struct cdr_object_snapshot *party_a;
2529  struct cdr_object *cand_cdr;
2530 
2531  ao2_lock(base_cand_cdr);
2532 
2533  for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2534  /* Skip any records that are not in this bridge */
2535  if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2536  continue;
2537  }
2538 
2539  /* If the candidate is us or someone we've taken on, pass on by */
2540  if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)
2541  || (cdr->party_b.snapshot
2542  && !strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name))) {
2543  break;
2544  }
2545 
2546  party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2547  /* We're party A - make a new CDR, append it to us, and set the candidate as
2548  * Party B */
2549  if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2550  bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2551  break;
2552  }
2553 
2554  /* We're Party B. Check if we can add ourselves immediately or if we need
2555  * a new CDR for them (they already have a Party B) */
2556  if (cand_cdr->party_b.snapshot
2557  && strcasecmp(cand_cdr->party_b.snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2558  bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2559  } else {
2560  CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2561  cand_cdr, cand_cdr->party_a.snapshot->base->name,
2562  cdr->party_a.snapshot->base->name);
2563  cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2564  cdr_all_relink(cand_cdr);
2565  /* It's possible that this joined at one point and was never chosen
2566  * as party A. Clear their end time, as it would be set in such a
2567  * case.
2568  */
2569  memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2570  }
2571 
2572  break;
2573  }
2574 
2575  ao2_unlock(base_cand_cdr);
2576 }
2577 
2578 /*!
2579  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2580  * entered a bridge
2581  * \param cdr The \ref cdr_object that just entered the bridge
2582  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2583  */
2585 {
2586  struct ao2_iterator it_channels;
2587  char *channel_id;
2588 
2589  it_channels = ao2_iterator_init(bridge->channels, 0);
2590  while ((channel_id = ao2_iterator_next(&it_channels))) {
2591  struct cdr_object *cand_cdr;
2592 
2593  cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2594  if (cand_cdr) {
2595  bridge_candidate_process(cdr, cand_cdr);
2596  ao2_ref(cand_cdr, -1);
2597  }
2598 
2599  ao2_ref(channel_id, -1);
2600  }
2601  ao2_iterator_destroy(&it_channels);
2602 }
2603 
2604 /*! \brief Handle entering into a parking bridge
2605  * \param cdr The CDR to operate on
2606  * \param bridge The bridge the channel just entered
2607  * \param channel The channel snapshot
2608  * \param event_time
2609  */
2611  struct ast_bridge_snapshot *bridge,
2612  struct ast_channel_snapshot *channel,
2613  const struct timeval *event_time)
2614 {
2615  int res = 1;
2616  struct cdr_object *it_cdr;
2617  struct cdr_object *new_cdr;
2618 
2619  ao2_lock(cdr);
2620 
2621  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2622  it_cdr->lastevent = *event_time;
2623 
2624  if (it_cdr->fn_table->process_parking_bridge_enter) {
2625  res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2626  }
2627  if (it_cdr->fn_table->process_party_a) {
2628  CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2629  channel->base->name);
2630  it_cdr->fn_table->process_party_a(it_cdr, channel);
2631  }
2632  }
2633 
2634  if (res) {
2635  /* No one handled it - we need a new one! */
2636  new_cdr = cdr_object_create_and_append(cdr, event_time);
2637  if (new_cdr) {
2638  /* Let the single state transition us to Parked */
2640  new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2641  }
2642  }
2643  ao2_unlock(cdr);
2644 }
2645 
2646 /*! \brief Handle a bridge enter message for a 'normal' bridge
2647  * \param cdr The CDR to operate on
2648  * \param bridge The bridge the channel just entered
2649  * \param channel The channel snapshot
2650  * \param event_time
2651  */
2653  struct ast_bridge_snapshot *bridge,
2654  struct ast_channel_snapshot *channel,
2655  const struct timeval *event_time)
2656 {
2658  struct cdr_object *it_cdr;
2659  struct cdr_object *new_cdr;
2660  struct cdr_object *handled_cdr = NULL;
2661 
2662  ao2_lock(cdr);
2663 
2664 try_again:
2665  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2666  it_cdr->lastevent = *event_time;
2667 
2668  if (it_cdr->fn_table->process_party_a) {
2669  CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2670  channel->base->name);
2671  it_cdr->fn_table->process_party_a(it_cdr, channel);
2672  }
2673 
2674  /* Notify all states that they have entered a bridge */
2675  if (it_cdr->fn_table->process_bridge_enter) {
2676  CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2677  channel->base->name);
2678  result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2679  switch (result) {
2681  /* Fall through */
2683  if (!handled_cdr) {
2684  handled_cdr = it_cdr;
2685  }
2686  break;
2687  case BRIDGE_ENTER_NEED_CDR:
2688  /* Pass */
2689  break;
2691  /* We didn't win on any - end this CDR. If someone else comes in later
2692  * that is Party B to this CDR, it can re-activate this CDR.
2693  */
2694  if (!handled_cdr) {
2695  handled_cdr = it_cdr;
2696  }
2697  cdr_object_finalize(cdr);
2698  break;
2699  }
2700  }
2701  }
2702 
2703  /* Create the new matchings, but only for either:
2704  * * The first CDR in the chain that handled it. This avoids issues with
2705  * forked CDRs.
2706  * * If no one handled it, the last CDR in the chain. This would occur if
2707  * a CDR joined a bridge and it wasn't Party A for anyone. We still need
2708  * to make pairings with everyone in the bridge.
2709  */
2710  if (handled_cdr) {
2711  handle_bridge_pairings(handled_cdr, bridge);
2712  } else {
2713  /* Nothing handled it - we need a new one! */
2714  new_cdr = cdr_object_create_and_append(cdr, event_time);
2715  if (new_cdr) {
2716  /* This is guaranteed to succeed: the new CDR is created in the single state
2717  * and will be able to handle the bridge enter message
2718  */
2719  goto try_again;
2720  }
2721  }
2722  ao2_unlock(cdr);
2723 }
2724 
2725 /*!
2726  * \internal
2727  * \brief Handler for Stasis-Core bridge enter messages
2728  * \param data Passed on
2729  * \param sub The stasis subscription for this message callback
2730  * \param message The message - hopefully a bridge one!
2731  */
2733  struct stasis_message *message)
2734 {
2736  struct ast_bridge_snapshot *bridge = update->bridge;
2737  struct ast_channel_snapshot *channel = update->channel;
2738  struct cdr_object *cdr;
2739 
2741  return;
2742  }
2743 
2744  if (filter_channel_snapshot(channel)) {
2745  return;
2746  }
2747 
2748  CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2749  channel->base->name,
2750  (unsigned int)stasis_message_timestamp(message)->tv_sec,
2751  (unsigned int)stasis_message_timestamp(message)->tv_usec);
2752 
2754  if (!cdr) {
2755  ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2756  ast_assert(0);
2757  return;
2758  }
2759 
2760  if (!strcmp(bridge->subclass, "parking")) {
2762  } else {
2764  }
2765  ao2_cleanup(cdr);
2766 }
2767 
2768 /*!
2769  * \brief Handler for when a channel is parked
2770  * \param data Passed on
2771  * \param sub The stasis subscription for this message callback
2772  * \param message The message about who got parked
2773  * */
2775  struct stasis_message *message)
2776 {
2778  struct ast_channel_snapshot *channel = payload->parkee;
2779  struct cdr_object *cdr;
2780  int unhandled = 1;
2781  struct cdr_object *it_cdr;
2782 
2783  /* Anything other than getting parked will be handled by other updates */
2784  if (payload->event_type != PARKED_CALL) {
2785  return;
2786  }
2787 
2788  /* No one got parked? */
2789  if (!channel) {
2790  return;
2791  }
2792 
2793  if (filter_channel_snapshot(channel)) {
2794  return;
2795  }
2796 
2797  CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2798  channel->base->name,
2799  (unsigned int)stasis_message_timestamp(message)->tv_sec,
2800  (unsigned int)stasis_message_timestamp(message)->tv_usec);
2801 
2803  if (!cdr) {
2804  ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2805  ast_assert(0);
2806  return;
2807  }
2808 
2809  ao2_lock(cdr);
2810 
2811  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2813  if (it_cdr->fn_table->process_parked_channel) {
2814  unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2815  }
2816  }
2817 
2818  if (unhandled) {
2819  /* Nothing handled the messgae - we need a new one! */
2820  struct cdr_object *new_cdr;
2821 
2823  if (new_cdr) {
2824  /* As the new CDR is created in the single state, it is guaranteed
2825  * to have a function for the parked call message and will handle
2826  * the message */
2827  new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2828  }
2829  }
2830 
2831  ao2_unlock(cdr);
2832 
2833  ao2_cleanup(cdr);
2834 }
2835 
2836 /*!
2837  * \brief Handler for a synchronization message
2838  * \param data Passed on
2839  * \param sub The stasis subscription for this message callback
2840  * \param message A blank ao2 object
2841  * */
2843  struct stasis_message *message)
2844 {
2845  return;
2846 }
2847 
2849 {
2850  struct ast_cdr_config *general;
2851  struct module_config *mod_cfg;
2852 
2853  mod_cfg = ao2_global_obj_ref(module_configs);
2854  if (!mod_cfg) {
2855  return NULL;
2856  }
2857  general = ao2_bump(mod_cfg->general);
2858  ao2_cleanup(mod_cfg);
2859  return general;
2860 }
2861 
2863 {
2864  struct module_config *mod_cfg;
2865 
2866  if (!config) {
2867  return;
2868  }
2869 
2870  mod_cfg = ao2_global_obj_ref(module_configs);
2871  if (!mod_cfg) {
2872  return;
2873  }
2874 
2875  ao2_replace(mod_cfg->general, config);
2876 
2877  cdr_set_debug_mode(mod_cfg);
2879 
2880  ao2_cleanup(mod_cfg);
2881 }
2882 
2884 {
2885  return is_cdr_flag_set(CDR_ENABLED);
2886 }
2887 
2889 {
2890  int success = -1;
2891  struct cdr_beitem *i = NULL;
2892 
2894  AST_RWLIST_TRAVERSE(&be_list, i, list) {
2895  if (!strcasecmp(name, i->name)) {
2896  ast_debug(3, "Suspending CDR backend %s\n", i->name);
2897  i->suspended = 1;
2898  success = 0;
2899  }
2900  }
2902 
2903  return success;
2904 }
2905 
2907 {
2908  int success = -1;
2909  struct cdr_beitem *i = NULL;
2910 
2912  AST_RWLIST_TRAVERSE(&be_list, i, list) {
2913  if (!strcasecmp(name, i->name)) {
2914  ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2915  i->suspended = 0;
2916  success = 0;
2917  }
2918  }
2920 
2921  return success;
2922 }
2923 
2924 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2925 {
2926  struct cdr_beitem *i;
2927  struct cdr_beitem *cur;
2928 
2929  if (!name) {
2930  return -1;
2931  }
2932 
2933  if (!be) {
2934  ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2935 
2936  return -1;
2937  }
2938 
2939  i = ast_calloc(1, sizeof(*i));
2940  if (!i) {
2941  return -1;
2942  }
2943 
2944  i->be = be;
2945  ast_copy_string(i->name, name, sizeof(i->name));
2946  ast_copy_string(i->desc, desc, sizeof(i->desc));
2947 
2948  AST_RWLIST_WRLOCK(generic_list);
2949  AST_RWLIST_TRAVERSE(generic_list, cur, list) {
2950  if (!strcasecmp(name, cur->name)) {
2951  ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2952  AST_RWLIST_UNLOCK(generic_list);
2953  ast_free(i);
2954 
2955  return -1;
2956  }
2957  }
2958 
2959  AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2960  AST_RWLIST_UNLOCK(generic_list);
2961 
2962  return 0;
2963 }
2964 
2965 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2966 {
2967  return cdr_generic_register(&be_list, name, desc, be);
2968 }
2969 
2970 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2971 {
2972  return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2973 }
2974 
2975 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2976 {
2977  struct cdr_beitem *match = NULL;
2978  int active_count;
2979 
2980  AST_RWLIST_WRLOCK(generic_list);
2981  AST_RWLIST_TRAVERSE(generic_list, match, list) {
2982  if (!strcasecmp(name, match->name)) {
2983  break;
2984  }
2985  }
2986 
2987  if (!match) {
2988  AST_RWLIST_UNLOCK(generic_list);
2989  return 0;
2990  }
2991 
2992  active_count = ao2_container_count(active_cdrs_master);
2993 
2994  if (!match->suspended && active_count != 0) {
2995  AST_RWLIST_UNLOCK(generic_list);
2996  ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2997  name, active_count);
2998  return -1;
2999  }
3000 
3001  AST_RWLIST_REMOVE(generic_list, match, list);
3002  AST_RWLIST_UNLOCK(generic_list);
3003 
3004  ast_verb(2, "Unregistered '%s' CDR backend\n", name);
3005  ast_free(match);
3006 
3007  return 0;
3008 }
3009 
3010 int ast_cdr_unregister(const char *name)
3011 {
3013 }
3014 
3016 {
3017  return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
3018 }
3019 
3020 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
3021 {
3022  struct ast_cdr *newcdr;
3023 
3024  if (!cdr) {
3025  return NULL;
3026  }
3027  newcdr = ast_cdr_alloc();
3028  if (!newcdr) {
3029  return NULL;
3030  }
3031 
3032  *newcdr = *cdr;
3034  copy_variables(&newcdr->varshead, &cdr->varshead);
3035  newcdr->next = NULL;
3036 
3037  return newcdr;
3038 }
3039 
3040 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
3041 {
3042  struct ast_var_t *variables;
3043 
3044  if (ast_strlen_zero(name)) {
3045  return NULL;
3046  }
3047 
3048  AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
3049  if (!strcasecmp(name, ast_var_name(variables))) {
3050  return ast_var_value(variables);
3051  }
3052  }
3053 
3054  return NULL;
3055 }
3056 
3057 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
3058 {
3059  if (fmt == NULL) { /* raw mode */
3060  snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
3061  } else {
3062  buf[0] = '\0';/* Ensure the buffer is initialized. */
3063  if (when.tv_sec) {
3064  struct ast_tm tm;
3065 
3066  ast_localtime(&when, &tm, NULL);
3067  ast_strftime(buf, bufsize, fmt, &tm);
3068  }
3069  }
3070 }
3071 
3072 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
3073 {
3074  const char *fmt = "%Y-%m-%d %T";
3075  const char *varbuf;
3076 
3077  if (!cdr) {
3078  return;
3079  }
3080 
3081  *ret = NULL;
3082 
3083  if (!strcasecmp(name, "clid")) {
3084  ast_copy_string(workspace, cdr->clid, workspacelen);
3085  } else if (!strcasecmp(name, "src")) {
3086  ast_copy_string(workspace, cdr->src, workspacelen);
3087  } else if (!strcasecmp(name, "dst")) {
3088  ast_copy_string(workspace, cdr->dst, workspacelen);
3089  } else if (!strcasecmp(name, "dcontext")) {
3090  ast_copy_string(workspace, cdr->dcontext, workspacelen);
3091  } else if (!strcasecmp(name, "channel")) {
3092  ast_copy_string(workspace, cdr->channel, workspacelen);
3093  } else if (!strcasecmp(name, "dstchannel")) {
3094  ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3095  } else if (!strcasecmp(name, "lastapp")) {
3096  ast_copy_string(workspace, cdr->lastapp, workspacelen);
3097  } else if (!strcasecmp(name, "lastdata")) {
3098  ast_copy_string(workspace, cdr->lastdata, workspacelen);
3099  } else if (!strcasecmp(name, "start")) {
3100  cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3101  } else if (!strcasecmp(name, "answer")) {
3102  cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3103  } else if (!strcasecmp(name, "end")) {
3104  cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3105  } else if (!strcasecmp(name, "duration")) {
3106  snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3107  } else if (!strcasecmp(name, "billsec")) {
3108  snprintf(workspace, workspacelen, "%ld", (cdr->billsec || !ast_tvzero(cdr->end) || ast_tvzero(cdr->answer)) ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
3109  } else if (!strcasecmp(name, "disposition")) {
3110  if (raw) {
3111  snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3112  } else {
3113  ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3114  }
3115  } else if (!strcasecmp(name, "amaflags")) {
3116  if (raw) {
3117  snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3118  } else {
3119  ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3120  }
3121  } else if (!strcasecmp(name, "accountcode")) {
3122  ast_copy_string(workspace, cdr->accountcode, workspacelen);
3123  } else if (!strcasecmp(name, "peeraccount")) {
3124  ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3125  } else if (!strcasecmp(name, "uniqueid")) {
3126  ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3127  } else if (!strcasecmp(name, "linkedid")) {
3128  ast_copy_string(workspace, cdr->linkedid, workspacelen);
3129  } else if (!strcasecmp(name, "userfield")) {
3130  ast_copy_string(workspace, cdr->userfield, workspacelen);
3131  } else if (!strcasecmp(name, "sequence")) {
3132  snprintf(workspace, workspacelen, "%d", cdr->sequence);
3133  } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3134  ast_copy_string(workspace, varbuf, workspacelen);
3135  } else {
3136  workspace[0] = '\0';
3137  }
3138 
3139  if (!ast_strlen_zero(workspace)) {
3140  *ret = workspace;
3141  }
3142 }
3143 
3144 /*!
3145  * \internal
3146  * \brief Callback that finds all CDRs that reference a particular channel by name
3147  */
3148 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3149 {
3150  struct cdr_object *cdr = obj;
3151  const char *name = arg;
3152 
3153  if (!strcasecmp(cdr->party_a.snapshot->base->name, name) ||
3154  (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->base->name, name))) {
3155  return CMP_MATCH;
3156  }
3157  return 0;
3158 }
3159 
3160 /*!
3161  * \internal
3162  * \brief Callback that finds a CDR by channel name
3163  */
3164 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3165 {
3166  struct cdr_object *cdr = obj;
3167  const char *name = arg;
3168 
3169  if (!strcasecmp(cdr->party_a.snapshot->base->name, name)) {
3170  return CMP_MATCH;
3171  }
3172  return 0;
3173 }
3174 
3175 /* Read Only CDR variables */
3176 static const char * const cdr_readonly_vars[] = {
3177  "clid",
3178  "src",
3179  "dst",
3180  "dcontext",
3181  "channel",
3182  "dstchannel",
3183  "lastapp",
3184  "lastdata",
3185  "start",
3186  "answer",
3187  "end",
3188  "duration",
3189  "billsec",
3190  "disposition",
3191  "amaflags",
3192  "accountcode",
3193  "uniqueid",
3194  "linkedid",
3195  "userfield",
3196  "sequence",
3197  NULL
3198 };
3199 
3200 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3201 {
3202  struct cdr_object *cdr;
3203  struct cdr_object *it_cdr;
3204  struct ao2_iterator *it_cdrs;
3205  char *arg = ast_strdupa(channel_name);
3206  int x;
3207 
3208  for (x = 0; cdr_readonly_vars[x]; x++) {
3209  if (!strcasecmp(name, cdr_readonly_vars[x])) {
3210  ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3211  return -1;
3212  }
3213  }
3214 
3216  if (!it_cdrs) {
3217  ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3218  return -1;
3219  }
3220 
3221  for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3222  ao2_lock(cdr);
3223  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3224  struct varshead *headp = NULL;
3225 
3226  if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3227  continue;
3228  }
3229  if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->base->name)) {
3230  headp = &it_cdr->party_a.variables;
3231  } else if (it_cdr->party_b.snapshot
3232  && !strcasecmp(channel_name, it_cdr->party_b.snapshot->base->name)) {
3233  headp = &it_cdr->party_b.variables;
3234  }
3235  if (headp) {
3236  set_variable(headp, name, value);
3237  }
3238  }
3239  }
3240  ao2_iterator_destroy(it_cdrs);
3241 
3242  return 0;
3243 }
3244 
3245 /*!
3246  * \brief Format a variable on a \ref cdr_object
3247  */
3248 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3249 {
3250  struct ast_var_t *variable;
3251 
3252  AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3253  if (!strcasecmp(name, ast_var_name(variable))) {
3254  ast_copy_string(value, ast_var_value(variable), length);
3255  return;
3256  }
3257  }
3258 
3259  *value = '\0';
3260 }
3261 
3262 /*!
3263  * \brief Format one of the standard properties on a \ref cdr_object
3264  */
3265 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3266 {
3267  struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3268  struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3269 
3270  if (!strcasecmp(name, "clid")) {
3271  ast_callerid_merge(value, length, party_a->caller->name, party_a->caller->number, "");
3272  } else if (!strcasecmp(name, "src")) {
3273  ast_copy_string(value, party_a->caller->number, length);
3274  } else if (!strcasecmp(name, "dst")) {
3275  ast_copy_string(value, party_a->dialplan->exten, length);
3276  } else if (!strcasecmp(name, "dcontext")) {
3277  ast_copy_string(value, party_a->dialplan->context, length);
3278  } else if (!strcasecmp(name, "channel")) {
3279  ast_copy_string(value, party_a->base->name, length);
3280  } else if (!strcasecmp(name, "dstchannel")) {
3281  if (party_b) {
3282  ast_copy_string(value, party_b->base->name, length);
3283  } else {
3284  ast_copy_string(value, "", length);
3285  }
3286  } else if (!strcasecmp(name, "lastapp")) {
3287  ast_copy_string(value, party_a->dialplan->appl, length);
3288  } else if (!strcasecmp(name, "lastdata")) {
3289  ast_copy_string(value, party_a->dialplan->data, length);
3290  } else if (!strcasecmp(name, "start")) {
3291  cdr_get_tv(cdr_obj->start, NULL, value, length);
3292  } else if (!strcasecmp(name, "answer")) {
3293  cdr_get_tv(cdr_obj->answer, NULL, value, length);
3294  } else if (!strcasecmp(name, "end")) {
3295  cdr_get_tv(cdr_obj->end, NULL, value, length);
3296  } else if (!strcasecmp(name, "duration")) {
3297  snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3298  } else if (!strcasecmp(name, "billsec")) {
3299  snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3300  } else if (!strcasecmp(name, "disposition")) {
3301  snprintf(value, length, "%u", cdr_obj->disposition);
3302  } else if (!strcasecmp(name, "amaflags")) {
3303  snprintf(value, length, "%d", party_a->amaflags);
3304  } else if (!strcasecmp(name, "accountcode")) {
3305  ast_copy_string(value, party_a->base->accountcode, length);
3306  } else if (!strcasecmp(name, "peeraccount")) {
3307  if (party_b) {
3308  ast_copy_string(value, party_b->base->accountcode, length);
3309  } else {
3310  ast_copy_string(value, "", length);
3311  }
3312  } else if (!strcasecmp(name, "uniqueid")) {
3313  ast_copy_string(value, party_a->base->uniqueid, length);
3314  } else if (!strcasecmp(name, "linkedid")) {
3315  ast_copy_string(value, cdr_obj->linkedid, length);
3316  } else if (!strcasecmp(name, "userfield")) {
3317  ast_copy_string(value, cdr_obj->party_a.userfield, length);
3318  } else if (!strcasecmp(name, "sequence")) {
3319  snprintf(value, length, "%u", cdr_obj->sequence);
3320  } else {
3321  return 1;
3322  }
3323 
3324  return 0;
3325 }
3326 
3327 /*! \internal
3328  * \brief Look up and retrieve a CDR object by channel name
3329  * \param name The name of the channel
3330  * \retval NULL on error
3331  * \return The \ref cdr_object for the channel on success, with the reference
3332  * count bumped by one.
3333  */
3334 static struct cdr_object *cdr_object_get_by_name(const char *name)
3335 {
3336  char *param;
3337 
3338  if (ast_strlen_zero(name)) {
3339  return NULL;
3340  }
3341 
3342  param = ast_strdupa(name);
3344 }
3345 
3346 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3347 {
3348  struct cdr_object *cdr;
3349  struct cdr_object *cdr_obj;
3350 
3351  if (ast_strlen_zero(name)) {
3352  return 1;
3353  }
3354 
3355  cdr = cdr_object_get_by_name(channel_name);
3356  if (!cdr) {
3357  ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3358  return 1;
3359  }
3360 
3361  ao2_lock(cdr);
3362 
3363  cdr_obj = cdr->last;
3364  if (cdr_object_format_property(cdr_obj, name, value, length)) {
3365  /* Property failed; attempt variable */
3366  cdr_object_format_var_internal(cdr_obj, name, value, length);
3367  }
3368 
3369  ao2_unlock(cdr);
3370 
3371  ao2_cleanup(cdr);
3372  return 0;
3373 }
3374 
3375 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3376 {
3377  struct cdr_object *cdr;
3378  struct cdr_object *it_cdr;
3379  struct ast_var_t *variable;
3380  const char *var;
3381  char workspace[256];
3382  int total = 0, x = 0, i;
3383 
3384  cdr = cdr_object_get_by_name(channel_name);
3385  if (!cdr) {
3387  ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3388  }
3389  return 0;
3390  }
3391 
3392  ast_str_reset(*buf);
3393 
3394  ao2_lock(cdr);
3395  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3396  if (++x > 1) {
3397  ast_str_append(buf, 0, "\n");
3398  }
3399 
3400  AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3401  if (!(var = ast_var_name(variable))) {
3402  continue;
3403  }
3404 
3405  if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
3406  ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3407  break;
3408  }
3409 
3410  total++;
3411  }
3412 
3413  for (i = 0; cdr_readonly_vars[i]; i++) {
3414  if (cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace))) {
3415  /* Unhandled read-only CDR variable. */
3416  ast_assert(0);
3417  continue;
3418  }
3419 
3420  if (!ast_strlen_zero(workspace)
3421  && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
3422  ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3423  break;
3424  }
3425  total++;
3426  }
3427  }
3428  ao2_unlock(cdr);
3429  ao2_cleanup(cdr);
3430  return total;
3431 }
3432 
3433 void ast_cdr_free(struct ast_cdr *cdr)
3434 {
3435  while (cdr) {
3436  struct ast_cdr *next = cdr->next;
3437 
3438  free_variables(&cdr->varshead);
3439  ast_free(cdr);
3440  cdr = next;
3441  }
3442 }
3443 
3444 struct ast_cdr *ast_cdr_alloc(void)
3445 {
3446  struct ast_cdr *x;
3447 
3448  x = ast_calloc(1, sizeof(*x));
3449  return x;
3450 }
3451 
3453 {
3454  switch (disposition) {
3455  case AST_CDR_NULL:
3456  return "NO ANSWER"; /* by default, for backward compatibility */
3457  case AST_CDR_NOANSWER:
3458  return "NO ANSWER";
3459  case AST_CDR_FAILED:
3460  return "FAILED";
3461  case AST_CDR_BUSY:
3462  return "BUSY";
3463  case AST_CDR_ANSWERED:
3464  return "ANSWERED";
3465  case AST_CDR_CONGESTION:
3466  return "CONGESTION";
3467  }
3468  return "UNKNOWN";
3469 }
3470 
3472  const char *channel_name;
3473  const char *userfield;
3474 };
3475 
3476 /*! \brief Callback used to update the userfield on Party B on all CDRs */
3477 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, void *data, int flags)
3478 {
3479  struct cdr_object *cdr = obj;
3480 
3481  if ((cdr->fn_table != &finalized_state_fn_table || !cdr->next)
3482  && !strcasecmp(cdr->party_b_name, arg)) {
3483  struct party_b_userfield_update *info = data;
3484 
3485  /*
3486  * For sanity's sake we also assert the party_b snapshot
3487  * is consistent with the key.
3488  */
3490  && !strcasecmp(cdr->party_b.snapshot->base->name, info->channel_name));
3491 
3492  ast_copy_string(cdr->party_b.userfield, info->userfield,
3493  sizeof(cdr->party_b.userfield));
3494  }
3495 
3496  return 0;
3497 }
3498 
3499 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
3500 {
3501  struct cdr_object *cdr;
3502  struct party_b_userfield_update party_b_info = {
3504  .userfield = userfield,
3505  };
3506  struct cdr_object *it_cdr;
3507 
3508  /* Handle Party A */
3509  cdr = cdr_object_get_by_name(channel_name);
3510  if (cdr) {
3511  ao2_lock(cdr);
3512  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3513  if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3514  continue;
3515  }
3516  ast_copy_string(it_cdr->party_a.userfield, userfield,
3517  sizeof(it_cdr->party_a.userfield));
3518  }
3519  ao2_unlock(cdr);
3520  }
3521 
3522  /* Handle Party B */
3525  &party_b_info);
3526 
3527  ao2_cleanup(cdr);
3528 }
3529 
3530 static void post_cdr(struct ast_cdr *cdr)
3531 {
3532  struct module_config *mod_cfg;
3533  struct cdr_beitem *i;
3534 
3535  mod_cfg = ao2_global_obj_ref(module_configs);
3536  if (!mod_cfg) {
3537  return;
3538  }
3539 
3540  for (; cdr ; cdr = cdr->next) {
3541  /* For people, who don't want to see unanswered single-channel events */
3542  if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
3543  cdr->disposition < AST_CDR_ANSWERED &&
3545  ast_debug(1, "Skipping CDR for %s since we weren't answered\n", cdr->channel);
3546  continue;
3547  }
3548 
3549  /* Modify CDR's */
3551  AST_RWLIST_TRAVERSE(&mo_list, i, list) {
3552  i->be(cdr);
3553  }
3555 
3556  if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
3557  continue;
3558  }
3560  AST_RWLIST_TRAVERSE(&be_list, i, list) {
3561  if (!i->suspended) {
3562  i->be(cdr);
3563  }
3564  }
3566  }
3567  ao2_cleanup(mod_cfg);
3568 }
3569 
3570 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
3571 {
3572  struct cdr_object *cdr;
3573  struct cdr_object *it_cdr;
3574 
3575  cdr = cdr_object_get_by_name(channel_name);
3576  if (!cdr) {
3577  return -1;
3578  }
3579 
3580  ao2_lock(cdr);
3581  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3582  if (it_cdr->fn_table == &finalized_state_fn_table) {
3583  continue;
3584  }
3585  /* Note: in general, set the flags on both the CDR record as well as the
3586  * Party A. Sometimes all we have is the Party A to look at.
3587  */
3588  ast_set_flag(&it_cdr->flags, option);
3589  ast_set_flag(&it_cdr->party_a, option);
3590  }
3591  ao2_unlock(cdr);
3592 
3593  ao2_cleanup(cdr);
3594  return 0;
3595 }
3596 
3597 int ast_cdr_clear_property(const char *channel_name, enum ast_cdr_options option)
3598 {
3599  struct cdr_object *cdr;
3600  struct cdr_object *it_cdr;
3601 
3602  cdr = cdr_object_get_by_name(channel_name);
3603  if (!cdr) {
3604  return -1;
3605  }
3606 
3607  ao2_lock(cdr);
3608  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3609  if (it_cdr->fn_table == &finalized_state_fn_table) {
3610  continue;
3611  }
3612  ast_clear_flag(&it_cdr->flags, option);
3613  }
3614  ao2_unlock(cdr);
3615 
3616  ao2_cleanup(cdr);
3617  return 0;
3618 }
3619 
3620 int ast_cdr_reset(const char *channel_name, int keep_variables)
3621 {
3622  struct cdr_object *cdr;
3623  struct ast_var_t *vardata;
3624  struct cdr_object *it_cdr;
3625 
3626  cdr = cdr_object_get_by_name(channel_name);
3627  if (!cdr) {
3628  return -1;
3629  }
3630 
3631  ao2_lock(cdr);
3632  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3633  /* clear variables */
3634  if (!keep_variables) {
3635  while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_a.variables, entries))) {
3636  ast_var_delete(vardata);
3637  }
3638  if (cdr->party_b.snapshot) {
3639  while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_b.variables, entries))) {
3640  ast_var_delete(vardata);
3641  }
3642  }
3643  }
3644 
3645  /* Reset to initial state */
3646  memset(&it_cdr->start, 0, sizeof(it_cdr->start));
3647  memset(&it_cdr->end, 0, sizeof(it_cdr->end));
3648  memset(&it_cdr->answer, 0, sizeof(it_cdr->answer));
3649  it_cdr->start = ast_tvnow();
3650  it_cdr->lastevent = it_cdr->start;
3652  }
3653  ao2_unlock(cdr);
3654 
3655  ao2_cleanup(cdr);
3656  return 0;
3657 }
3658 
3659 int ast_cdr_fork(const char *channel_name, struct ast_flags *options)
3660 {
3661  RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3662  struct cdr_object *new_cdr;
3663  struct cdr_object *it_cdr;
3664  struct cdr_object *cdr_obj;
3665 
3666  if (!cdr) {
3667  return -1;
3668  }
3669 
3670  {
3671  SCOPED_AO2LOCK(lock, cdr);
3672  struct timeval now = ast_tvnow();
3673 
3674  cdr_obj = cdr->last;
3675  if (cdr_obj->fn_table == &finalized_state_fn_table) {
3676  /* If the last CDR in the chain is finalized, don't allow a fork -
3677  * things are already dying at this point
3678  */
3679  return -1;
3680  }
3681 
3682  /* Copy over the basic CDR information. The Party A information is
3683  * copied over automatically as part of the append
3684  */
3685  ast_debug(1, "Forking CDR for channel %s\n", cdr->party_a.snapshot->base->name);
3686  new_cdr = cdr_object_create_and_append(cdr, &now);
3687  if (!new_cdr) {
3688  return -1;
3689  }
3690  new_cdr->fn_table = cdr_obj->fn_table;
3691  ast_string_field_set(new_cdr, bridge, cdr->bridge);
3692  ast_string_field_set(new_cdr, appl, cdr->appl);
3693  ast_string_field_set(new_cdr, data, cdr->data);
3694  ast_string_field_set(new_cdr, context, cdr->context);
3695  ast_string_field_set(new_cdr, exten, cdr->exten);
3696  new_cdr->flags = cdr->flags;
3697  /* Explicitly clear the AST_CDR_LOCK_APP flag - we want
3698  * the application to be changed on the new CDR if the
3699  * dialplan demands it
3700  */
3702 
3703  /* If there's a Party B, copy it over as well */
3704  if (cdr_obj->party_b.snapshot) {
3705  new_cdr->party_b.snapshot = cdr_obj->party_b.snapshot;
3706  ao2_ref(new_cdr->party_b.snapshot, +1);
3707  cdr_all_relink(new_cdr);
3708  strcpy(new_cdr->party_b.userfield, cdr_obj->party_b.userfield);
3709  new_cdr->party_b.flags = cdr_obj->party_b.flags;
3711  copy_variables(&new_cdr->party_b.variables, &cdr_obj->party_b.variables);
3712  }
3713  }
3714  new_cdr->start = cdr_obj->start;
3715  new_cdr->answer = cdr_obj->answer;
3716  new_cdr->lastevent = ast_tvnow();
3717 
3718  /* Modify the times based on the flags passed in */
3720  && new_cdr->party_a.snapshot->state == AST_STATE_UP) {
3721  new_cdr->answer = ast_tvnow();
3722  }
3724  new_cdr->answer = ast_tvnow();
3725  new_cdr->start = ast_tvnow();
3726  }
3727 
3728  /* Create and append, by default, copies over the variables */
3730  free_variables(&new_cdr->party_a.variables);
3731  }
3732 
3733  /* Finalize any current CDRs */
3735  for (it_cdr = cdr; it_cdr != new_cdr; it_cdr = it_cdr->next) {
3736  if (it_cdr->fn_table == &finalized_state_fn_table) {
3737  continue;
3738  }
3739  /* Force finalization on the CDR. This will bypass any checks for
3740  * end before 'h' extension.
3741  */
3742  cdr_object_finalize(it_cdr);
3744  }
3745  }
3746  }
3747 
3748  return 0;
3749 }
3750 
3751 /*! \note Don't call without cdr_batch_lock */
3752 static void reset_batch(void)
3753 {
3754  batch->size = 0;
3755  batch->head = NULL;
3756  batch->tail = NULL;
3757 }
3758 
3759 /*! \note Don't call without cdr_batch_lock */
3760 static int init_batch(void)
3761 {
3762  /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
3763  if (!(batch = ast_malloc(sizeof(*batch))))
3764  return -1;
3765 
3766  reset_batch();
3767 
3768  return 0;
3769 }
3770 
3771 static void *do_batch_backend_process(void *data)
3772 {
3773  struct cdr_batch_item *processeditem;
3774  struct cdr_batch_item *batchitem = data;
3775 
3776  /* Push each CDR into storage mechanism(s) and free all the memory */
3777  while (batchitem) {
3778  post_cdr(batchitem->cdr);
3779  ast_cdr_free(batchitem->cdr);
3780  processeditem = batchitem;
3781  batchitem = batchitem->next;
3782  ast_free(processeditem);
3783  }
3784 
3785  return NULL;
3786 }
3787 
3788 static void cdr_submit_batch(int do_shutdown)
3789 {
3790  struct module_config *mod_cfg;
3791  struct cdr_batch_item *oldbatchitems = NULL;
3792  pthread_t batch_post_thread = AST_PTHREADT_NULL;
3793 
3794  /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
3795  if (!batch || !batch->head) {
3796  return;
3797  }
3798 
3799  /* move the old CDRs aside, and prepare a new CDR batch */
3801  oldbatchitems = batch->head;
3802  reset_batch();
3804 
3805  mod_cfg = ao2_global_obj_ref(module_configs);
3806 
3807  /* if configured, spawn a new thread to post these CDRs,
3808  also try to save as much as possible if we are shutting down safely */
3809  if (!mod_cfg
3811  || do_shutdown) {
3812  ast_debug(1, "CDR single-threaded batch processing begins now\n");
3813  do_batch_backend_process(oldbatchitems);
3814  } else {
3815  if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
3816  ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
3817  do_batch_backend_process(oldbatchitems);
3818  } else {
3819  ast_debug(1, "CDR multi-threaded batch processing begins now\n");
3820  }
3821  }
3822 
3823  ao2_cleanup(mod_cfg);
3824 }
3825 
3826 static int submit_scheduled_batch(const void *data)
3827 {
3828  struct module_config *mod_cfg;
3829  int nextms;
3830 
3831  cdr_submit_batch(0);
3832 
3833  mod_cfg = ao2_global_obj_ref(module_configs);
3834  if (!mod_cfg) {
3835  return 0;
3836  }
3837 
3838  /* Calculate the next scheduled interval */
3839  nextms = mod_cfg->general->batch_settings.time * 1000;
3840 
3841  ao2_cleanup(mod_cfg);
3842 
3843  return nextms;
3844 }
3845 
3846 /*! Do not hold the batch lock while calling this function */
3847 static void start_batch_mode(void)
3848 {
3849  /* Prevent two deletes from happening at the same time */
3851  /* this is okay since we are not being called from within the scheduler */
3853  /* schedule the submission to occur ASAP (1 ms) */
3856 
3857  /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
3861 }
3862 
3863 static void cdr_detach(struct ast_cdr *cdr)
3864 {
3865  struct cdr_batch_item *newtail;
3866  int curr;
3867  RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3868  int submit_batch = 0;
3869 
3870  if (!cdr) {
3871  return;
3872  }
3873 
3874  /* maybe they disabled CDR stuff completely, so just drop it */
3875  if (!mod_cfg || !ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3876  ast_debug(1, "Dropping CDR !\n");
3877  ast_cdr_free(cdr);
3878  return;
3879  }
3880 
3881  /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
3882  if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3883  post_cdr(cdr);
3884  ast_cdr_free(cdr);
3885  return;
3886  }
3887 
3888  /* otherwise, each CDR gets put into a batch list (at the end) */
3889  ast_debug(1, "CDR detaching from this thread\n");
3890 
3891  /* we'll need a new tail for every CDR */
3892  if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
3893  post_cdr(cdr);
3894  ast_cdr_free(cdr);
3895  return;
3896  }
3897 
3898  /* don't traverse a whole list (just keep track of the tail) */
3900  if (!batch)
3901  init_batch();
3902  if (!batch->head) {
3903  /* new batch is empty, so point the head at the new tail */
3904  batch->head = newtail;
3905  } else {
3906  /* already got a batch with something in it, so just append a new tail */
3907  batch->tail->next = newtail;
3908  }
3909  newtail->cdr = cdr;
3910  batch->tail = newtail;
3911  curr = batch->size++;
3912 
3913  /* if we have enough stuff to post, then do it */
3914  if (curr >= (mod_cfg->general->batch_settings.size - 1)) {
3915  submit_batch = 1;
3916  }
3918 
3919  /* Don't submit a batch with cdr_batch_lock held */
3920  if (submit_batch) {
3921  start_batch_mode();
3922  }
3923 }
3924 
3925 static void *do_cdr(void *data)
3926 {
3927  struct timespec timeout;
3928  int schedms;
3929  int numevents = 0;
3930 
3931  for (;;) {
3932  struct timeval now;
3933  schedms = ast_sched_wait(sched);
3934  /* this shouldn't happen, but provide a 1 second default just in case */
3935  if (schedms < 0)
3936  schedms = 1000;
3937  now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
3938  timeout.tv_sec = now.tv_sec;
3939  timeout.tv_nsec = now.tv_usec * 1000;
3940  /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
3943  numevents = ast_sched_runq(sched);
3945  ast_debug(2, "Processed %d CDR batches from the run queue\n", numevents);
3946  }
3947 
3948  return NULL;
3949 }
3950 
3951 static char *handle_cli_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3952 {
3953  struct module_config *mod_cfg;
3954 
3955  switch (cmd) {
3956  case CLI_INIT:
3957  e->command = "cdr set debug [on|off]";
3958  e->usage = "Enable or disable extra debugging in the CDR Engine. Note\n"
3959  "that this will dump debug information to the VERBOSE setting\n"
3960  "and should only be used when debugging information from the\n"
3961  "CDR engine is needed.\n";
3962  return NULL;
3963  case CLI_GENERATE:
3964  return NULL;
3965  }
3966 
3967  if (a->argc != 4) {
3968  return CLI_SHOWUSAGE;
3969  }
3970 
3971  mod_cfg = ao2_global_obj_ref(module_configs);
3972  if (!mod_cfg) {
3973  ast_cli(a->fd, "Could not set CDR debugging mode\n");
3974  return CLI_SUCCESS;
3975  }
3976  if (!strcasecmp(a->argv[3], "on")
3977  && !ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3978  ast_set_flag(&mod_cfg->general->settings, CDR_DEBUG);
3979  ast_cli(a->fd, "CDR debugging enabled\n");
3980  } else if (!strcasecmp(a->argv[3], "off")
3981  && ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3983  ast_cli(a->fd, "CDR debugging disabled\n");
3984  }
3985  cdr_set_debug_mode(mod_cfg);
3986  ao2_cleanup(mod_cfg);
3987 
3988  return CLI_SUCCESS;
3989 }
3990 
3991 /*! \brief Complete user input for 'cdr show' */
3992 static char *cli_complete_show(struct ast_cli_args *a)
3993 {
3994  int wordlen = strlen(a->word);
3995  struct ao2_iterator it_cdrs;
3996  struct cdr_object *cdr;
3997 
3998  it_cdrs = ao2_iterator_init(active_cdrs_master, 0);
3999  while ((cdr = ao2_iterator_next(&it_cdrs))) {
4000  if (!strncasecmp(a->word, cdr->party_a.snapshot->base->name, wordlen)) {
4002  ao2_ref(cdr, -1);
4003  break;
4004  }
4005  }
4006  ao2_ref(cdr, -1);
4007  }
4008  ao2_iterator_destroy(&it_cdrs);
4009 
4010  return NULL;
4011 }
4012 
4013 static void cli_show_channels(struct ast_cli_args *a)
4014 {
4015  struct ao2_iterator it_cdrs;
4016  struct cdr_object *cdr;
4017  char start_time_buffer[64];
4018  char answer_time_buffer[64];
4019  char end_time_buffer[64];
4020 
4021 #define TITLE_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8s %-8.8s\n"
4022 #define FORMAT_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8ld %-8.8ld\n"
4023 
4024  ast_cli(a->fd, "\n");
4025  ast_cli(a->fd, "Channels with Call Detail Record (CDR) Information\n");
4026  ast_cli(a->fd, "--------------------------------------------------\n");
4027  ast_cli(a->fd, TITLE_STRING, "Channel", "Dst. Channel", "LastApp", "Start", "Answer", "End", "Billsec", "Duration");
4028 
4029  it_cdrs = ao2_iterator_init(active_cdrs_master, 0);
4030  for (; (cdr = ao2_iterator_next(&it_cdrs)); ao2_cleanup(cdr)) {
4031  struct cdr_object *it_cdr;
4032  struct timeval start_time = { 0, };
4033  struct timeval answer_time = { 0, };
4034  struct timeval end_time = { 0, };
4035 
4036  SCOPED_AO2LOCK(lock, cdr);
4037 
4038  /* Calculate the start, end, answer, billsec, and duration over the
4039  * life of all of the CDR entries
4040  */
4041  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4042  if (snapshot_is_dialed(it_cdr->party_a.snapshot)) {
4043  continue;
4044  }
4045  if (ast_tvzero(start_time)) {
4046  start_time = it_cdr->start;
4047  }
4048  if (!ast_tvzero(it_cdr->answer) && ast_tvzero(answer_time)) {
4049  answer_time = it_cdr->answer;
4050  }
4051  }
4052 
4053  /* If there was no start time, then all CDRs were for a dialed channel; skip */
4054  if (ast_tvzero(start_time)) {
4055  continue;
4056  }
4057  it_cdr = cdr->last;
4058 
4059  end_time = ast_tvzero(it_cdr->end) ? ast_tvnow() : it_cdr->end;
4060  cdr_get_tv(start_time, "%T", start_time_buffer, sizeof(start_time_buffer));
4061  cdr_get_tv(answer_time, "%T", answer_time_buffer, sizeof(answer_time_buffer));
4062  cdr_get_tv(end_time, "%T", end_time_buffer, sizeof(end_time_buffer));
4063  ast_cli(a->fd, FORMAT_STRING, it_cdr->party_a.snapshot->base->name,
4064  it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->base->name : "<none>",
4065  it_cdr->appl,
4066  start_time_buffer,
4067  answer_time_buffer,
4068  end_time_buffer,
4069  ast_tvzero(answer_time) ? 0 : (long)ast_tvdiff_ms(end_time, answer_time) / 1000,
4070  (long)ast_tvdiff_ms(end_time, start_time) / 1000);
4071  }
4072  ao2_iterator_destroy(&it_cdrs);
4073 #undef FORMAT_STRING
4074 #undef TITLE_STRING
4075 }
4076 
4077 static void cli_show_channel(struct ast_cli_args *a)
4078 {
4079  struct cdr_object *it_cdr;
4080  char clid[64];
4081  char start_time_buffer[64];
4082  char answer_time_buffer[64];
4083  char end_time_buffer[64];
4084  const char *channel_name = a->argv[3];
4085  struct cdr_object *cdr;
4086 
4087 #define TITLE_STRING "%-10.10s %-20.20s %-25.25s %-15.15s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8s %-8.8s\n"
4088 #define FORMAT_STRING "%-10.10s %-20.20s %-25.25s %-15.15s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8ld %-8.8ld\n"
4089 
4090  cdr = cdr_object_get_by_name(channel_name);
4091  if (!cdr) {
4092  ast_cli(a->fd, "Unknown channel: %s\n", channel_name);
4093  return;
4094  }
4095 
4096  ast_cli(a->fd, "\n");
4097  ast_cli(a->fd, "Call Detail Record (CDR) Information for %s\n", channel_name);
4098  ast_cli(a->fd, "--------------------------------------------------\n");
4099  ast_cli(a->fd, TITLE_STRING, "AccountCode", "CallerID", "Dst. Channel", "LastApp", "Data", "Start", "Answer", "End", "Billsec", "Duration");
4100 
4101  ao2_lock(cdr);
4102  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4103  struct timeval end;
4104 
4105  if (snapshot_is_dialed(it_cdr->party_a.snapshot)) {
4106  continue;
4107  }
4108  ast_callerid_merge(clid, sizeof(clid), it_cdr->party_a.snapshot->caller->name, it_cdr->party_a.snapshot->caller->number, "");
4109  if (ast_tvzero(it_cdr->end)) {
4110  end = ast_tvnow();
4111  } else {
4112  end = it_cdr->end;
4113  }
4114  cdr_get_tv(it_cdr->start, "%T", start_time_buffer, sizeof(start_time_buffer));
4115  cdr_get_tv(it_cdr->answer, "%T", answer_time_buffer, sizeof(answer_time_buffer));
4116  cdr_get_tv(end, "%T", end_time_buffer, sizeof(end_time_buffer));
4117  ast_cli(a->fd, FORMAT_STRING,
4118  it_cdr->party_a.snapshot->base->accountcode,
4119  clid,
4120  it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->base->name : "<none>",
4121  it_cdr->appl,
4122  it_cdr->data,
4123  start_time_buffer,
4124  answer_time_buffer,
4125  end_time_buffer,
4126  (long)ast_tvdiff_ms(end, it_cdr->answer) / 1000,
4127  (long)ast_tvdiff_ms(end, it_cdr->start) / 1000);
4128  }
4129  ao2_unlock(cdr);
4130 
4131  ao2_cleanup(cdr);
4132 
4133 #undef FORMAT_STRING
4134 #undef TITLE_STRING
4135 }
4136 
4137 static char *handle_cli_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4138 {
4139  switch (cmd) {
4140  case CLI_INIT:
4141  e->command = "cdr show active";
4142  e->usage =
4143  "Usage: cdr show active [channel]\n"
4144  " Displays a summary of all Call Detail Records when [channel]\n"
4145  " is omitted; displays all of the Call Detail Records\n"
4146  " currently in flight for a given [channel] when [channel] is\n"
4147  " specified.\n\n"
4148  " Note that this will not display Call Detail Records that\n"
4149  " have already been dispatched to a backend storage, nor for\n"
4150  " channels that are no longer active.\n";
4151  return NULL;
4152  case CLI_GENERATE:
4153  return cli_complete_show(a);
4154  }
4155 
4156  if (a->argc > 4) {
4157  return CLI_SHOWUSAGE;
4158  } else if (a->argc < 4) {
4160  } else {
4162  }
4163 
4164  return CLI_SUCCESS;
4165 }
4166 
4167 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4168 {
4169  struct cdr_beitem *beitem = NULL;
4170  struct module_config *mod_cfg;
4171  int cnt = 0;
4172  long nextbatchtime = 0;
4173 
4174  switch (cmd) {
4175  case CLI_INIT:
4176  e->command = "cdr show status";
4177  e->usage =
4178  "Usage: cdr show status\n"
4179  " Displays the Call Detail Record engine system status.\n";
4180  return NULL;
4181  case CLI_GENERATE:
4182  return NULL;
4183  }
4184 
4185  if (a->argc > 3) {
4186  return CLI_SHOWUSAGE;
4187  }
4188 
4189  mod_cfg = ao2_global_obj_ref(module_configs);
4190  if (!mod_cfg) {
4191  return CLI_FAILURE;
4192  }
4193 
4194  ast_cli(a->fd, "\n");
4195  ast_cli(a->fd, "Call Detail Record (CDR) settings\n");
4196  ast_cli(a->fd, "----------------------------------\n");
4197  ast_cli(a->fd, " Logging: %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED) ? "Enabled" : "Disabled");
4198  ast_cli(a->fd, " Mode: %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE) ? "Batch" : "Simple");
4199  if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
4200  ast_cli(a->fd, " Log calls by default: %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_CHANNEL_DEFAULT_ENABLED) ? "Yes" : "No");
4201  ast_cli(a->fd, " Log unanswered calls: %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) ? "Yes" : "No");
4202  ast_cli(a->fd, " Log congestion: %s\n\n", ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION) ? "Yes" : "No");
4203  if (ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
4204  ast_cli(a->fd, "* Batch Mode Settings\n");
4205  ast_cli(a->fd, " -------------------\n");
4206  if (batch)
4207  cnt = batch->size;
4208  if (cdr_sched > -1)
4209  nextbatchtime = ast_sched_when(sched, cdr_sched);
4210  ast_cli(a->fd, " Safe shutdown: %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SAFE_SHUTDOWN) ? "Enabled" : "Disabled");
4211  ast_cli(a->fd, " Threading model: %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY) ? "Scheduler only" : "Scheduler plus separate threads");
4212  ast_cli(a->fd, " Current batch size: %d record%s\n", cnt, ESS(cnt));
4213  ast_cli(a->fd, " Maximum batch size: %u record%s\n", mod_cfg->general->batch_settings.size, ESS(mod_cfg->general->batch_settings.size));
4214  ast_cli(a->fd, " Maximum batch time: %u second%s\n", mod_cfg->general->batch_settings.time, ESS(mod_cfg->general->batch_settings.time));
4215  ast_cli(a->fd, " Next batch processing time: %ld second%s\n\n", nextbatchtime, ESS(nextbatchtime));
4216  }
4217  ast_cli(a->fd, "* Registered Backends\n");
4218  ast_cli(a->fd, " -------------------\n");
4220  if (AST_RWLIST_EMPTY(&be_list)) {
4221  ast_cli(a->fd, " (none)\n");
4222  } else {
4223  AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
4224  ast_cli(a->fd, " %s%s\n", beitem->name, beitem->suspended ? " (suspended) " : "");
4225  }
4226  }
4228  ast_cli(a->fd, "\n");
4229  }
4230 
4231  ao2_cleanup(mod_cfg);
4232  return CLI_SUCCESS;
4233 }
4234 
4235 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4236 {
4237  struct module_config *mod_cfg;
4238 
4239  switch (cmd) {
4240  case CLI_INIT:
4241  e->command = "cdr submit";
4242  e->usage =
4243  "Usage: cdr submit\n"
4244  "Posts all pending batched CDR data to the configured CDR\n"
4245  "backend engine modules.\n";
4246  return NULL;
4247  case CLI_GENERATE:
4248  return NULL;
4249  }
4250  if (a->argc > 2) {
4251  return CLI_SHOWUSAGE;
4252  }
4253 
4254  mod_cfg = ao2_global_obj_ref(module_configs);
4255  if (!mod_cfg) {
4256  return CLI_FAILURE;
4257  }
4258 
4259  if (!ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
4260  ast_cli(a->fd, "Cannot submit CDR batch: CDR engine disabled.\n");
4261  } else if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
4262  ast_cli(a->fd, "Cannot submit CDR batch: batch mode not enabled.\n");
4263  } else {
4264  start_batch_mode();
4265  ast_cli(a->fd, "Submitted CDRs to backend engines for processing. This may take a while.\n");
4266  }
4267  ao2_cleanup(mod_cfg);
4268 
4269  return CLI_SUCCESS;
4270 }
4271 
4272 static struct ast_cli_entry cli_commands[] = {
4273  AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data"),
4274  AST_CLI_DEFINE(handle_cli_status, "Display the CDR status"),
4275  AST_CLI_DEFINE(handle_cli_show, "Display active CDRs for channels"),
4276  AST_CLI_DEFINE(handle_cli_debug, "Enable debugging in the CDR engine"),
4277 };
4278 
4279 /*!
4280  * \brief This dispatches *all* \ref cdr_object. It should only be used during
4281  * shutdown, so that we get billing records for everything that we can.
4282  */
4283 static int cdr_object_dispatch_all_cb(void *obj, void *arg, int flags)
4284 {
4285  struct cdr_object *cdr = obj;
4286  struct cdr_object *it_cdr;
4287 
4288  ao2_lock(cdr);
4289  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4291  }
4292  cdr_object_dispatch(cdr);
4293  ao2_unlock(cdr);
4294 
4295  cdr_all_unlink(cdr);
4296 
4297  return CMP_MATCH;
4298 }
4299 
4300 static void finalize_batch_mode(void)
4301 {
4302  if (cdr_thread == AST_PTHREADT_NULL) {
4303  return;
4304  }
4305  /* wake up the thread so it will exit */
4306  pthread_cancel(cdr_thread);
4307  pthread_kill(cdr_thread, SIGURG);
4308  pthread_join(cdr_thread, NULL);
4312 }
4313 
4315 {
4316  if (!stasis_router) {
4317  return NULL;
4318  }
4319 
4321  return stasis_router;
4322 }
4323 
4324 /*!
4325  * \brief Destroy the active Stasis subscriptions
4326  */
4327 static void destroy_subscriptions(void)
4328 {
4332 }
4333 
4334 /*!
4335  * \brief Create the Stasis subcriptions for CDRs
4336  */
4337 static int create_subscriptions(void)
4338 {
4339  if (!cdr_topic) {
4340  return -1;
4341  }
4342 
4344  return 0;
4345  }
4346 
4348  if (!channel_subscription) {
4349  return -1;
4350  }
4352  if (!bridge_subscription) {
4353  return -1;
4354  }
4356  if (!parking_subscription) {
4357  return -1;
4358  }
4359 
4360  return 0;
4361 }
4362 
4363 static int process_config(int reload)
4364 {
4365  if (!reload) {
4366  if (aco_info_init(&cfg_info)) {
4367  return 1;
4368  }
4369 
4382  }
4383 
4384  if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
4385  struct module_config *mod_cfg;
4386 
4387  if (reload) {
4388  return 1;
4389  }
4390 
4391  /* If we couldn't process the configuration and this wasn't a reload,
4392  * create a default config
4393  */
4394  mod_cfg = module_config_alloc();
4395  if (!mod_cfg
4396  || aco_set_defaults(&general_option, "general", mod_cfg->general)) {
4397  ao2_cleanup(mod_cfg);
4398  return 1;
4399  }
4400  ast_log(LOG_NOTICE, "Failed to process CDR configuration; using defaults\n");
4401  ao2_global_obj_replace_unref(module_configs, mod_cfg);
4402  cdr_set_debug_mode(mod_cfg);
4403  ao2_cleanup(mod_cfg);
4404  }
4405 
4406  return 0;
4407 }
4408 
4409 static void cdr_engine_shutdown(void)
4410 {
4412  stasis_router = NULL;
4413 
4415  cdr_topic = NULL;
4416 
4417  STASIS_MESSAGE_TYPE_CLEANUP(cdr_sync_message_type);
4418 
4424  sched = NULL;
4425  ast_free(batch);
4426  batch = NULL;
4427 
4428  aco_info_destroy(&cfg_info);
4429  ao2_global_obj_release(module_configs);
4430 
4431  ao2_container_unregister("cdrs_master");
4434 
4435  ao2_container_unregister("cdrs_all");
4438 }
4439 
4441 {
4442  /* Only create the thread level portions once */
4443  if (cdr_thread == AST_PTHREADT_NULL) {
4446  ast_log(LOG_ERROR, "Unable to start CDR thread.\n");
4447  return;
4448  }
4449  }
4450 
4451  /* Start the batching process */
4452  start_batch_mode();
4453 
4454  ast_log(LOG_NOTICE, "CDR batch mode logging enabled, first of either size %u or time %u seconds.\n",
4455  config->batch_settings.size, config->batch_settings.time);
4456 }
4457 
4458 /*!
4459  * \internal
4460  * \brief Print master CDR container object.
4461  * \since 12.0.0
4462  *
4463  * \param v_obj A pointer to the object we want printed.
4464  * \param where User data needed by prnt to determine where to put output.
4465  * \param prnt Print output callback function to use.
4466  */
4467 static void cdr_master_print_fn(void *v_obj, void *where, ao2_prnt_fn *prnt)
4468 {
4469  struct cdr_object *cdr = v_obj;
4470  struct cdr_object *it_cdr;
4471 
4472  if (!cdr) {
4473  return;
4474  }
4475  for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4476  prnt(where, "Party A: %s; Party B: %s; Bridge %s\n",
4477  it_cdr->party_a.snapshot->base->name,
4478  it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->base->name : "<unknown>",
4479  it_cdr->bridge);
4480  }
4481 }
4482 
4483 /*!
4484  * \internal
4485  * \brief Print all CDR container object.
4486  * \since 13.19.0
4487  *
4488  * \param v_obj A pointer to the object we want printed.
4489  * \param where User data needed by prnt to determine where to put output.
4490  * \param prnt Print output callback function to use.
4491  */
4492 static void cdr_all_print_fn(void *v_obj, void *where, ao2_prnt_fn *prnt)
4493 {
4494  struct cdr_object *cdr = v_obj;
4495 
4496  if (!cdr) {
4497  return;
4498  }
4499  prnt(where, "Party A: %s; Party B: %s; Bridge %s",
4500  cdr->party_a.snapshot->base->name,
4501  cdr->party_b.snapshot ? cdr->party_b.snapshot->base->name : "<unknown>",
4502  cdr->bridge);
4503 }
4504 
4505 /*!
4506  * \brief Checks if CDRs are enabled and enables/disables the necessary options
4507  */
4509 {
4510  struct module_config *mod_cfg;
4511 
4512  mod_cfg = ao2_global_obj_ref(module_configs);
4513  if (mod_cfg
4514  && ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
4515  if (create_subscriptions()) {
4517  ast_log(AST_LOG_ERROR, "Failed to create Stasis subscriptions\n");
4518  ao2_cleanup(mod_cfg);
4519  return -1;
4520  }
4521  if (ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
4522  cdr_enable_batch_mode(mod_cfg->general);
4523  } else {
4524  ast_log(LOG_NOTICE, "CDR simple logging enabled.\n");
4525  }
4526  } else {
4528  ast_log(LOG_NOTICE, "CDR logging disabled.\n");
4529  }
4530  ao2_cleanup(mod_cfg);
4531 
4532  return mod_cfg ? 0 : -1;
4533 }
4534 
4535 static int unload_module(void)
4536 {
4538 
4539  return 0;
4540 }
4541 
4542 static int load_module(void)
4543 {
4544  if (process_config(0)) {
4545  return AST_MODULE_LOAD_FAILURE;
4546  }
4547 
4548  cdr_topic = stasis_topic_create("cdr:aggregator");
4549  if (!cdr_topic) {
4550  return AST_MODULE_LOAD_FAILURE;
4551  }
4552 
4554  if (!stasis_router) {
4555  return AST_MODULE_LOAD_FAILURE;
4556  }