cdr.c: Add container to key off of Party B channel names.
[asterisk/asterisk.git] / main / cdr.c
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/causes.h"
57 #include "asterisk/linkedlists.h"
58 #include "asterisk/utils.h"
59 #include "asterisk/sched.h"
60 #include "asterisk/config.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/config_options.h"
64 #include "asterisk/json.h"
65 #include "asterisk/parking.h"
66 #include "asterisk/stasis.h"
67 #include "asterisk/stasis_channels.h"
68 #include "asterisk/stasis_bridges.h"
69 #include "asterisk/stasis_message_router.h"
70 #include "asterisk/astobj2.h"
71 #include "asterisk/taskprocessor.h"
72
73 /*** DOCUMENTATION
74         <configInfo name="cdr" language="en_US">
75                 <synopsis>Call Detail Record configuration</synopsis>
76                 <description>
77                         <para>CDR is Call Detail Record, which provides logging services via a variety of
78                         pluggable backend modules. Detailed call information can be recorded to
79                         databases, files, etc. Useful for billing, fraud prevention, compliance with
80                         Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
81                 </description>
82                 <configFile name="cdr.conf">
83                         <configObject name="general">
84                                 <synopsis>Global settings applied to the CDR engine.</synopsis>
85                                 <configOption name="debug">
86                                         <synopsis>Enable/disable verbose CDR debugging.</synopsis>
87                                         <description><para>When set to <literal>True</literal>, verbose updates
88                                         of changes in CDR information will be logged. Note that this is only
89                                         of use when debugging CDR behavior.</para>
90                                         </description>
91                                 </configOption>
92                                 <configOption name="enable">
93                                         <synopsis>Enable/disable CDR logging.</synopsis>
94                                         <description><para>Define whether or not to use CDR logging. Setting this to "no" will override
95                                         any loading of backend CDR modules.  Default is "yes".</para>
96                                         </description>
97                                 </configOption>
98                                 <configOption name="unanswered">
99                                         <synopsis>Log calls that are never answered and don't set an outgoing party.</synopsis>
100                                         <description><para>
101                                         Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
102                                         this to "yes" will make calls to extensions that don't answer and don't set a side B channel
103                                         (such as by using the Dial application) receive CDR log entries. If this option is set to
104                                         "no", then those log entries will not be created. Unanswered calls which get offered to an
105                                         outgoing line will always receive log entries regardless of this option, and that is the
106                                         intended behavior.
107                                         </para>
108                                         </description>
109                                 </configOption>
110                                 <configOption name="congestion">
111                                         <synopsis>Log congested calls.</synopsis>
112                                         <description><para>Define whether or not to log congested calls. Setting this to "yes" will
113                                         report each call that fails to complete due to congestion conditions.</para>
114                                         </description>
115                                 </configOption>
116                                 <configOption name="endbeforehexten">
117                                         <synopsis>Don't produce CDRs while executing hangup logic</synopsis>
118                                         <description>
119                                                 <para>As each CDR for a channel is finished, its end time is updated
120                                                 and the CDR is finalized. When a channel is hung up and hangup
121                                                 logic is present (in the form of a hangup handler or the
122                                                 <literal>h</literal> extension), a new CDR is generated for the
123                                                 channel. Any statistics are gathered from this new CDR. By enabling
124                                                 this option, no new CDR is created for the dialplan logic that is
125                                                 executed in <literal>h</literal> extensions or attached hangup handler
126                                                 subroutines. The default value is <literal>yes</literal>, indicating
127                                                 that a CDR will be generated during hangup logic.</para>
128                                         </description>
129                                 </configOption>
130                                 <configOption name="initiatedseconds">
131                                         <synopsis>Count microseconds for billsec purposes</synopsis>
132                                         <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
133                                         is simply the end time (hangup time) minus the answer time in seconds. Internally,
134                                         asterisk stores the time in terms of microseconds and seconds. By setting
135                                         initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
136                                         that were initiated (a sort of round up method). Technically, this is
137                                         when the microsecond part of the end time is greater than the microsecond
138                                         part of the answer time, then the billsec time is incremented one second.</para>
139                                         </description>
140                                 </configOption>
141                                 <configOption name="batch">
142                                         <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
143                                         <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
144                                         every call, the data will be stored in a buffer to help alleviate load on the
145                                         asterisk server.</para>
146                                         <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
147                                         i.e., software crash, power failure, kill -9, etc.</para>
148                                         </warning>
149                                         </description>
150                                 </configOption>
151                                 <configOption name="size">
152                                         <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
153                                         <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
154                                         them to the backend engines. batch must be set to <literal>yes</literal>.</para>
155                                         </description>
156                                 </configOption>
157                                 <configOption name="time">
158                                         <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
159                                         <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
160                                         backend engines. If this time limit is reached, then it will post the records, regardless of the value
161                                         defined for size. batch must be set to <literal>yes</literal>.</para>
162                                         <note><para>Time is expressed in seconds.</para></note>
163                                         </description>
164                                 </configOption>
165                                 <configOption name="scheduleronly">
166                                         <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
167                                         <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
168                                         records.  Posting can either occur inside the scheduler thread, or a new
169                                         thread can be spawned for the submission of every batch.  For small batches,
170                                         it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
171                                         For large batches, say anything over size=10, a new thread is recommended, so
172                                         set this to <literal>no</literal>.</para>
173                                         </description>
174                                 </configOption>
175                                 <configOption name="safeshutdown">
176                                         <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
177                                         <description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
178                                         you don't, then data will likely be lost.  You can always check the size of
179                                         the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
180                                         submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
181                                         </description>
182                                 </configOption>
183                         </configObject>
184                 </configFile>
185         </configInfo>
186  ***/
187
188
189 /* The prime here should be similar in size to the channel container. */
190 #ifdef LOW_MEMORY
191 #define NUM_CDR_BUCKETS 61
192 #else
193 #define NUM_CDR_BUCKETS 769
194 #endif
195
196 #define DEFAULT_ENABLED "1"
197 #define DEFAULT_BATCHMODE "0"
198 #define DEFAULT_UNANSWERED "0"
199 #define DEFAULT_CONGESTION "0"
200 #define DEFAULT_END_BEFORE_H_EXTEN "1"
201 #define DEFAULT_INITIATED_SECONDS "0"
202
203 #define DEFAULT_BATCH_SIZE "100"
204 #define MAX_BATCH_SIZE 1000
205 #define DEFAULT_BATCH_TIME "300"
206 #define MAX_BATCH_TIME 86400
207 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
208 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
209
210 #define cdr_set_debug_mode(mod_cfg) \
211         do { \
212                 cdr_debug_enabled = ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG); \
213         } while (0)
214
215 static int cdr_debug_enabled;
216
217 #define CDR_DEBUG(fmt, ...) \
218         do { \
219                 if (cdr_debug_enabled) { \
220                         ast_verbose((fmt), ##__VA_ARGS__); \
221                 } \
222         } while (0)
223
224 static void cdr_detach(struct ast_cdr *cdr);
225 static void cdr_submit_batch(int shutdown);
226 static int cdr_toggle_runtime_options(void);
227
228 /*! \brief The configuration settings for this module */
229 struct module_config {
230         struct ast_cdr_config *general;         /*!< CDR global settings */
231 };
232
233 /*! \brief The container for the module configuration */
234 static AO2_GLOBAL_OBJ_STATIC(module_configs);
235
236 /*! \brief The type definition for general options */
237 static struct aco_type general_option = {
238         .type = ACO_GLOBAL,
239         .name = "general",
240         .item_offset = offsetof(struct module_config, general),
241         .category = "^general$",
242         .category_match = ACO_WHITELIST,
243 };
244
245 static void *module_config_alloc(void);
246 static void module_config_destructor(void *obj);
247 static void module_config_post_apply(void);
248
249 /*! \brief The file definition */
250 static struct aco_file module_file_conf = {
251         .filename = "cdr.conf",
252         .skip_category = "(^csv$|^custom$|^manager$|^odbc$|^pgsql$|^radius$|^sqlite$|^tds$|^mysql$)",
253         .types = ACO_TYPES(&general_option),
254 };
255
256 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
257         .files = ACO_FILES(&module_file_conf),
258         .post_apply_config = module_config_post_apply,
259 );
260
261 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
262
263 static void module_config_post_apply(void)
264 {
265         struct module_config *mod_cfg;
266
267         mod_cfg = ao2_global_obj_ref(module_configs);
268         if (!mod_cfg) {
269                 return;
270         }
271         cdr_set_debug_mode(mod_cfg);
272         ao2_cleanup(mod_cfg);
273 }
274
275 /*! \brief Dispose of a module config object */
276 static void module_config_destructor(void *obj)
277 {
278         struct module_config *cfg = obj;
279
280         if (!cfg) {
281                 return;
282         }
283         ao2_ref(cfg->general, -1);
284 }
285
286 /*! \brief Create a new module config object */
287 static void *module_config_alloc(void)
288 {
289         struct module_config *mod_cfg;
290         struct ast_cdr_config *cdr_config;
291
292         mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
293         if (!mod_cfg) {
294                 return NULL;
295         }
296
297         cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
298         if (!cdr_config) {
299                 ao2_ref(cdr_config, -1);
300                 return NULL;
301         }
302         mod_cfg->general = cdr_config;
303
304         return mod_cfg;
305 }
306
307 /*! \brief Registration object for CDR backends */
308 struct cdr_beitem {
309         char name[20];
310         char desc[80];
311         ast_cdrbe be;
312         AST_RWLIST_ENTRY(cdr_beitem) list;
313         int suspended:1;
314 };
315
316 /*! \brief List of registered backends */
317 static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
318
319 /*! \brief List of registered modifiers */
320 static AST_RWLIST_HEAD_STATIC(mo_list, cdr_beitem);
321
322 /*! \brief Queued CDR waiting to be batched */
323 struct cdr_batch_item {
324         struct ast_cdr *cdr;
325         struct cdr_batch_item *next;
326 };
327
328 /*! \brief The actual batch queue */
329 static struct cdr_batch {
330         int size;
331         struct cdr_batch_item *head;
332         struct cdr_batch_item *tail;
333 } *batch = NULL;
334
335 /*! \brief The global sequence counter used for CDRs */
336 static int global_cdr_sequence =  0;
337
338 /*! \brief Scheduler items */
339 static struct ast_sched_context *sched;
340 static int cdr_sched = -1;
341 AST_MUTEX_DEFINE_STATIC(cdr_sched_lock);
342 static pthread_t cdr_thread = AST_PTHREADT_NULL;
343
344 /*! \brief Lock protecting modifications to the batch queue */
345 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
346
347 /*! \brief These are used to wake up the CDR thread when there's work to do */
348 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
349 static ast_cond_t cdr_pending_cond;
350
351 /*! \brief A container of the active CDRs indexed by Party A channel id */
352 static struct ao2_container *active_cdrs_by_channel;
353
354 /*! \brief A container of all active CDRs indexed by Party B channel name */
355 static struct ao2_container *active_cdrs_all;
356
357 /*! \brief Message router for stasis messages regarding channel state */
358 static struct stasis_message_router *stasis_router;
359
360 /*! \brief Our subscription for bridges */
361 static struct stasis_forward *bridge_subscription;
362
363 /*! \brief Our subscription for channels */
364 static struct stasis_forward *channel_subscription;
365
366 /*! \brief Our subscription for parking */
367 static struct stasis_forward *parking_subscription;
368
369 /*! \brief The parent topic for all topics we want to aggregate for CDRs */
370 static struct stasis_topic *cdr_topic;
371
372 /*! \brief A message type used to synchronize with the CDR topic */
373 STASIS_MESSAGE_TYPE_DEFN_LOCAL(cdr_sync_message_type);
374
375 struct cdr_object;
376
377 /*! \brief Return types for \ref process_bridge_enter functions */
378 enum process_bridge_enter_results {
379         /*!
380          * The CDR was the only party in the bridge.
381          */
382         BRIDGE_ENTER_ONLY_PARTY,
383         /*!
384          * The CDR was able to obtain a Party B from some other party already in the bridge
385          */
386         BRIDGE_ENTER_OBTAINED_PARTY_B,
387         /*!
388          * The CDR was not able to obtain a Party B
389          */
390         BRIDGE_ENTER_NO_PARTY_B,
391         /*!
392          * This CDR can't handle a bridge enter message and a new CDR needs to be created
393          */
394         BRIDGE_ENTER_NEED_CDR,
395 };
396
397 /*!
398  * \brief A virtual table used for \ref cdr_object.
399  *
400  * Note that all functions are optional - if a subclass does not need an
401  * implementation, it is safe to leave it NULL.
402  */
403 struct cdr_object_fn_table {
404         /*! \brief Name of the subclass */
405         const char *name;
406
407         /*!
408          * \brief An initialization function. This will be called automatically
409          * when a \ref cdr_object is switched to this type in
410          * \ref cdr_object_transition_state
411          *
412          * \param cdr The \ref cdr_object that was just transitioned
413          */
414         void (* const init_function)(struct cdr_object *cdr);
415
416         /*!
417          * \brief Process a Party A update for the \ref cdr_object
418          *
419          * \param cdr The \ref cdr_object to process the update
420          * \param snapshot The snapshot for the CDR's Party A
421          * \retval 0 the CDR handled the update or ignored it
422          * \retval 1 the CDR is finalized and a new one should be made to handle it
423          */
424         int (* const process_party_a)(struct cdr_object *cdr,
425                         struct ast_channel_snapshot *snapshot);
426
427         /*!
428          * \brief Process a Party B update for the \ref cdr_object
429          *
430          * \param cdr The \ref cdr_object to process the update
431          * \param snapshot The snapshot for the CDR's Party B
432          */
433         void (* const process_party_b)(struct cdr_object *cdr,
434                         struct ast_channel_snapshot *snapshot);
435
436         /*!
437          * \brief Process the beginning of a dial. A dial message implies one of two
438          * things:
439          * The \ref cdr_object's Party A has been originated
440          * The \ref cdr_object's Party A is dialing its Party B
441          *
442          * \param cdr The \ref cdr_object
443          * \param caller The originator of the dial attempt
444          * \param peer The destination of the dial attempt
445          *
446          * \retval 0 if the parties in the dial were handled by this CDR
447          * \retval 1 if the parties could not be handled by this CDR
448          */
449         int (* const process_dial_begin)(struct cdr_object *cdr,
450                         struct ast_channel_snapshot *caller,
451                         struct ast_channel_snapshot *peer);
452
453         /*!
454          * \brief Process the end of a dial. At the end of a dial, a CDR can be
455          * transitioned into one of two states - DialedPending
456          * (\ref dialed_pending_state_fn_table) or Finalized
457          * (\ref finalized_state_fn_table).
458          *
459          * \param cdr The \ref cdr_object
460          * \param caller The originator of the dial attempt
461          * \param peer the Destination of the dial attempt
462          * \param dial_status What happened
463          *
464          * \retval 0 if the parties in the dial were handled by this CDR
465          * \retval 1 if the parties could not be handled by this CDR
466          */
467         int (* const process_dial_end)(struct cdr_object *cdr,
468                         struct ast_channel_snapshot *caller,
469                         struct ast_channel_snapshot *peer,
470                         const char *dial_status);
471
472         /*!
473          * \brief Process the entering of a bridge by this CDR. The purpose of this
474          * callback is to have the CDR prepare itself for the bridge and attempt to
475          * find a valid Party B. The act of creating new CDRs based on the entering
476          * of this channel into the bridge is handled by the higher level message
477          * handler.
478          *
479          * Note that this handler is for when a channel enters into a "normal"
480          * bridge, where people actually talk to each other. Parking is its own
481          * thing.
482          *
483          * \param cdr The \ref cdr_object
484          * \param bridge The bridge that the Party A just entered into
485          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
486          *
487          * \retval process_bridge_enter_results Defines whether or not this CDR was able
488          * to fully handle the bridge enter message.
489          */
490         enum process_bridge_enter_results (* const process_bridge_enter)(
491                         struct cdr_object *cdr,
492                         struct ast_bridge_snapshot *bridge,
493                         struct ast_channel_snapshot *channel);
494
495         /*!
496          * \brief Process entering into a parking bridge.
497          *
498          * \param cdr The \ref cdr_object
499          * \param bridge The parking bridge that Party A just entered into
500          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
501          *
502          * \retval 0 This CDR successfully transitioned itself into the parked state
503          * \retval 1 This CDR couldn't handle the parking transition and we need a
504          *  new CDR.
505          */
506         int (* const process_parking_bridge_enter)(struct cdr_object *cdr,
507                         struct ast_bridge_snapshot *bridge,
508                         struct ast_channel_snapshot *channel);
509
510         /*!
511          * \brief Process the leaving of a bridge by this CDR.
512          *
513          * \param cdr The \ref cdr_object
514          * \param bridge The bridge that the Party A just left
515          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
516          *
517          * \retval 0 This CDR left successfully
518          * \retval 1 Error
519          */
520         int (* const process_bridge_leave)(struct cdr_object *cdr,
521                         struct ast_bridge_snapshot *bridge,
522                         struct ast_channel_snapshot *channel);
523
524         /*!
525          * \brief Process an update informing us that the channel got itself parked
526          *
527          * \param cdr The \ref cdr_object
528          * \param channel The parking information for this CDR's party A
529          *
530          * \retval 0 This CDR successfully parked itself
531          * \retval 1 This CDR couldn't handle the park
532          */
533         int (* const process_parked_channel)(struct cdr_object *cdr,
534                         struct ast_parked_call_payload *parking_info);
535 };
536
537 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
538 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
539 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
540 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
541 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info);
542
543 static void single_state_init_function(struct cdr_object *cdr);
544 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
545 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
546 static enum process_bridge_enter_results single_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
547 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
548
549 /*!
550  * \brief The virtual table for the Single state.
551  *
552  * A \ref cdr_object starts off in this state. This represents a channel that
553  * has no Party B information itself.
554  *
555  * A \ref cdr_object from this state can go into any of the following states:
556  * * \ref dial_state_fn_table
557  * * \ref bridge_state_fn_table
558  * * \ref finalized_state_fn_table
559  */
560 struct cdr_object_fn_table single_state_fn_table = {
561         .name = "Single",
562         .init_function = single_state_init_function,
563         .process_party_a = base_process_party_a,
564         .process_party_b = single_state_process_party_b,
565         .process_dial_begin = single_state_process_dial_begin,
566         .process_dial_end = base_process_dial_end,
567         .process_bridge_enter = single_state_process_bridge_enter,
568         .process_parking_bridge_enter = single_state_process_parking_bridge_enter,
569         .process_bridge_leave = base_process_bridge_leave,
570         .process_parked_channel = base_process_parked_channel,
571 };
572
573 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
574 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
575 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);
576 static enum process_bridge_enter_results dial_state_process_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 Dial state.
580  *
581  * A \ref cdr_object that has begun a dial operation. This state is entered when
582  * the Party A for a CDR is determined to be dialing out to a Party B or when
583  * a CDR is for an originated channel (in which case the Party A information is
584  * the originated channel, and there is no Party B).
585  *
586  * A \ref cdr_object from this state can go in any of the following states:
587  * * \ref dialed_pending_state_fn_table
588  * * \ref bridge_state_fn_table
589  * * \ref finalized_state_fn_table
590  */
591 struct cdr_object_fn_table dial_state_fn_table = {
592         .name = "Dial",
593         .process_party_a = base_process_party_a,
594         .process_party_b = dial_state_process_party_b,
595         .process_dial_begin = dial_state_process_dial_begin,
596         .process_dial_end = dial_state_process_dial_end,
597         .process_bridge_enter = dial_state_process_bridge_enter,
598         .process_bridge_leave = base_process_bridge_leave,
599 };
600
601 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
602 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
603 static enum process_bridge_enter_results dialed_pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
604 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
605
606 /*!
607  * \brief The virtual table for the Dialed Pending state.
608  *
609  * A \ref cdr_object that has successfully finished a dial operation, but we
610  * don't know what they're going to do yet. It's theoretically possible to dial
611  * a party and then have that party not be bridged with the caller; likewise,
612  * an origination can complete and the channel go off and execute dialplan. The
613  * pending state acts as a bridge between either:
614  * * Entering a bridge
615  * * Getting a new CDR for new dialplan execution
616  * * Switching from being originated to executing dialplan
617  *
618  * A \ref cdr_object from this state can go in any of the following states:
619  * * \ref single_state_fn_table
620  * * \ref dialed_pending_state_fn_table
621  * * \ref bridge_state_fn_table
622  * * \ref finalized_state_fn_table
623  */
624 struct cdr_object_fn_table dialed_pending_state_fn_table = {
625         .name = "DialedPending",
626         .process_party_a = dialed_pending_state_process_party_a,
627         .process_dial_begin = dialed_pending_state_process_dial_begin,
628         .process_bridge_enter = dialed_pending_state_process_bridge_enter,
629         .process_parking_bridge_enter = dialed_pending_state_process_parking_bridge_enter,
630         .process_bridge_leave = base_process_bridge_leave,
631         .process_parked_channel = base_process_parked_channel,
632 };
633
634 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
635 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
636
637 /*!
638  * \brief The virtual table for the Bridged state
639  *
640  * A \ref cdr_object enters this state when it receives notification that the
641  * channel has entered a bridge.
642  *
643  * A \ref cdr_object from this state can go to:
644  * * \ref finalized_state_fn_table
645  */
646 struct cdr_object_fn_table bridge_state_fn_table = {
647         .name = "Bridged",
648         .process_party_a = base_process_party_a,
649         .process_party_b = bridge_state_process_party_b,
650         .process_bridge_leave = bridge_state_process_bridge_leave,
651         .process_parked_channel = base_process_parked_channel,
652 };
653
654 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
655
656 /*!
657  * \brief The virtual table for the Parked state
658  *
659  * Parking is weird. Unlike typical bridges, it has to be treated somewhat
660  * uniquely - a channel in a parking bridge (which is a subclass of a holding
661  * bridge) has to be handled as if the channel went into an application.
662  * However, when the channel comes out, we need a new CDR - unlike the Single
663  * state.
664  */
665 struct cdr_object_fn_table parked_state_fn_table = {
666         .name = "Parked",
667         .process_party_a = base_process_party_a,
668         .process_bridge_leave = parked_state_process_bridge_leave,
669         .process_parked_channel = base_process_parked_channel,
670 };
671
672 static void finalized_state_init_function(struct cdr_object *cdr);
673 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
674
675 /*!
676  * \brief The virtual table for the finalized state.
677  *
678  * Once in the finalized state, the CDR is done. No modifications can be made
679  * to the CDR.
680  */
681 struct cdr_object_fn_table finalized_state_fn_table = {
682         .name = "Finalized",
683         .init_function = finalized_state_init_function,
684         .process_party_a = finalized_state_process_party_a,
685         .process_bridge_enter = base_process_bridge_enter,
686 };
687
688 /*! \brief A wrapper object around a snapshot.
689  * Fields that are mutable by the CDR engine are replicated here.
690  */
691 struct cdr_object_snapshot {
692         struct ast_channel_snapshot *snapshot;  /*!< The channel snapshot */
693         char userfield[AST_MAX_USER_FIELD];     /*!< Userfield for the channel */
694         unsigned int flags;                     /*!< Specific flags for this party */
695         struct varshead variables;              /*!< CDR variables for the channel */
696 };
697
698 /*! \brief An in-memory representation of an active CDR */
699 struct cdr_object {
700         struct cdr_object_snapshot party_a;     /*!< The Party A information */
701         struct cdr_object_snapshot party_b;     /*!< The Party B information */
702         struct cdr_object_fn_table *fn_table;   /*!< The current virtual table */
703
704         enum ast_cdr_disposition disposition;   /*!< The disposition of the CDR */
705         struct timeval start;                   /*!< When this CDR was created */
706         struct timeval answer;                  /*!< Either when the channel was answered, or when the path between channels was established */
707         struct timeval end;                     /*!< When this CDR was finalized */
708         unsigned int sequence;                  /*!< A monotonically increasing number for each CDR */
709         struct ast_flags flags;                 /*!< Flags on the CDR */
710         AST_DECLARE_STRING_FIELDS(
711                 AST_STRING_FIELD(linkedid);         /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
712                 AST_STRING_FIELD(uniqueid);                     /*!< Unique id of party A. Cached here as it is the primary key of this CDR */
713                 AST_STRING_FIELD(name);             /*!< Channel name of party A. Cached here as the party A address may change */
714                 AST_STRING_FIELD(bridge);           /*!< The bridge the party A happens to be in. */
715                 AST_STRING_FIELD(appl);             /*!< The last accepted application party A was in */
716                 AST_STRING_FIELD(data);             /*!< The data for the last accepted application party A was in */
717                 AST_STRING_FIELD(context);          /*!< The accepted context for Party A */
718                 AST_STRING_FIELD(exten);            /*!< The accepted extension for Party A */
719                 AST_STRING_FIELD(party_b_name);     /*!< Party B channel name. Cached here as it is the all CDRs container key */
720         );
721         struct cdr_object *next;                /*!< The next CDR object in the chain */
722         struct cdr_object *last;                /*!< The last CDR object in the chain */
723         int is_root;                            /*!< True if this is the first CDR in the chain */
724 };
725
726 /*!
727  * \brief Copy variables from one list to another
728  * \param to_list destination
729  * \param from_list source
730  * \retval The number of copied variables
731  */
732 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
733 {
734         struct ast_var_t *variables;
735         struct ast_var_t *newvariable;
736         const char *var;
737         const char *val;
738         int x = 0;
739
740         AST_LIST_TRAVERSE(from_list, variables, entries) {
741                 var = ast_var_name(variables);
742                 if (ast_strlen_zero(var)) {
743                         continue;
744                 }
745                 val = ast_var_value(variables);
746                 if (ast_strlen_zero(val)) {
747                         continue;
748                 }
749                 newvariable = ast_var_assign(var, val);
750                 if (newvariable) {
751                         AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
752                         ++x;
753                 }
754         }
755
756         return x;
757 }
758
759 /*!
760  * \brief Delete all variables from a variable list
761  * \param headp The head pointer to the variable list to delete
762  */
763 static void free_variables(struct varshead *headp)
764 {
765         struct ast_var_t *vardata;
766
767         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
768                 ast_var_delete(vardata);
769         }
770 }
771
772 /*!
773  * \brief Copy a snapshot and its details
774  * \param dst The destination
775  * \param src The source
776  */
777 static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
778 {
779         ao2_t_replace(dst->snapshot, src->snapshot, "CDR snapshot copy");
780         strcpy(dst->userfield, src->userfield);
781         dst->flags = src->flags;
782         copy_variables(&dst->variables, &src->variables);
783 }
784
785 /*!
786  * \brief Transition a \ref cdr_object to a new state
787  * \param cdr The \ref cdr_object to transition
788  * \param fn_table The \ref cdr_object_fn_table state to go to
789  */
790 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
791 {
792         CDR_DEBUG("%p - Transitioning CDR for %s from state %s to %s\n",
793                 cdr, cdr->party_a.snapshot->name,
794                 cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
795         cdr->fn_table = fn_table;
796         if (cdr->fn_table->init_function) {
797                 cdr->fn_table->init_function(cdr);
798         }
799 }
800 /*! \internal
801  * \brief Hash function for containers of CDRs indexing by Party A uniqueid */
802 static int cdr_object_channel_hash_fn(const void *obj, const int flags)
803 {
804         const struct cdr_object *cdr;
805         const char *key;
806
807         switch (flags & OBJ_SEARCH_MASK) {
808         case OBJ_SEARCH_KEY:
809                 key = obj;
810                 break;
811         case OBJ_SEARCH_OBJECT:
812                 cdr = obj;
813                 key = cdr->uniqueid;
814                 break;
815         default:
816                 ast_assert(0);
817                 return 0;
818         }
819         return ast_str_case_hash(key);
820 }
821
822 /*! \internal
823  * \brief Comparison function for containers of CDRs indexing by Party A uniqueid
824  */
825 static int cdr_object_channel_cmp_fn(void *obj, void *arg, int flags)
826 {
827     struct cdr_object *left = obj;
828     struct cdr_object *right = arg;
829     const char *right_key = arg;
830     int cmp;
831
832     switch (flags & OBJ_SEARCH_MASK) {
833     case OBJ_SEARCH_OBJECT:
834         right_key = right->uniqueid;
835         /* Fall through */
836     case OBJ_SEARCH_KEY:
837         cmp = strcmp(left->uniqueid, right_key);
838         break;
839     case OBJ_SEARCH_PARTIAL_KEY:
840         /*
841          * We could also use a partial key struct containing a length
842          * so strlen() does not get called for every comparison instead.
843          */
844         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
845         break;
846     default:
847         /* Sort can only work on something with a full or partial key. */
848         ast_assert(0);
849         cmp = 0;
850         break;
851     }
852     return cmp ? 0 : CMP_MATCH;
853 }
854
855 /*!
856  * \internal
857  * \brief Hash function for all CDR container indexed by Party B channel name.
858  */
859 static int cdr_all_hash_fn(const void *obj, const int flags)
860 {
861         const struct cdr_object *cdr;
862         const char *key;
863
864         switch (flags & OBJ_SEARCH_MASK) {
865         case OBJ_SEARCH_KEY:
866                 key = obj;
867                 break;
868         case OBJ_SEARCH_OBJECT:
869                 cdr = obj;
870                 key = cdr->party_b_name;
871                 break;
872         default:
873                 ast_assert(0);
874                 return 0;
875         }
876         return ast_str_case_hash(key);
877 }
878
879 /*!
880  * \internal
881  * \brief Comparison function for all CDR container indexed by Party B channel name.
882  */
883 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
884 {
885     struct cdr_object *left = obj;
886     struct cdr_object *right = arg;
887     const char *right_key = arg;
888     int cmp;
889
890     switch (flags & OBJ_SEARCH_MASK) {
891     case OBJ_SEARCH_OBJECT:
892         right_key = right->party_b_name;
893         /* Fall through */
894     case OBJ_SEARCH_KEY:
895         cmp = strcasecmp(left->party_b_name, right_key);
896         break;
897     case OBJ_SEARCH_PARTIAL_KEY:
898         /*
899          * We could also use a partial key struct containing a length
900          * so strlen() does not get called for every comparison instead.
901          */
902         cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
903         break;
904     default:
905         /* Sort can only work on something with a full or partial key. */
906         ast_assert(0);
907         cmp = 0;
908         break;
909     }
910     return cmp ? 0 : CMP_MATCH;
911 }
912
913 /*!
914  * \internal
915  * \brief Relink the CDR because Party B's snapshot changed.
916  * \since 13.19.0
917  *
918  * \return Nothing
919  */
920 static void cdr_all_relink(struct cdr_object *cdr)
921 {
922         ao2_lock(active_cdrs_all);
923         if (cdr->party_b.snapshot) {
924                 if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->name)) {
925                         ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
926                         ast_string_field_set(cdr, party_b_name, cdr->party_b.snapshot->name);
927                         ao2_link_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
928                 }
929         } else {
930                 ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
931                 ast_string_field_set(cdr, party_b_name, "");
932         }
933         ao2_unlock(active_cdrs_all);
934 }
935
936 /*!
937  * \internal
938  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
939  * \since 13.19.0
940  *
941  * \return Nothing
942  */
943 static void cdr_all_unlink(struct cdr_object *cdr)
944 {
945         struct cdr_object *cur;
946         struct cdr_object *next;
947
948         ast_assert(cdr->is_root);
949
950         ao2_lock(active_cdrs_all);
951         for (cur = cdr->next; cur; cur = next) {
952                 next = cur->next;
953                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
954                 ast_string_field_set(cur, party_b_name, "");
955         }
956         ao2_unlock(active_cdrs_all);
957 }
958
959 /*!
960  * \brief \ref cdr_object Destructor
961  */
962 static void cdr_object_dtor(void *obj)
963 {
964         struct cdr_object *cdr = obj;
965         struct ast_var_t *it_var;
966
967         ao2_cleanup(cdr->party_a.snapshot);
968         ao2_cleanup(cdr->party_b.snapshot);
969         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
970                 ast_var_delete(it_var);
971         }
972         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
973                 ast_var_delete(it_var);
974         }
975         ast_string_field_free_memory(cdr);
976
977         /* CDR destruction used to work by calling ao2_cleanup(next) and
978          * allowing the chain to destroy itself neatly. Unfortunately, for
979          * really long chains, this can result in a stack overflow. So now
980          * when the root CDR is destroyed, it is responsible for unreffing
981          * all CDRs in the chain
982          */
983         if (cdr->is_root) {
984                 struct cdr_object *curr = cdr->next;
985                 struct cdr_object *next;
986
987                 while (curr) {
988                         next = curr->next;
989                         ao2_cleanup(curr);
990                         curr = next;
991                 }
992         }
993 }
994
995 /*!
996  * \brief \ref cdr_object constructor
997  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
998  *
999  * This implicitly sets the state of the newly created CDR to the Single state
1000  * (\ref single_state_fn_table)
1001  */
1002 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
1003 {
1004         struct cdr_object *cdr;
1005
1006         ast_assert(chan != NULL);
1007
1008         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1009         if (!cdr) {
1010                 return NULL;
1011         }
1012         cdr->last = cdr;
1013         if (ast_string_field_init(cdr, 64)) {
1014                 ao2_cleanup(cdr);
1015                 return NULL;
1016         }
1017         ast_string_field_set(cdr, uniqueid, chan->uniqueid);
1018         ast_string_field_set(cdr, name, chan->name);
1019         ast_string_field_set(cdr, linkedid, chan->linkedid);
1020         cdr->disposition = AST_CDR_NULL;
1021         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1022
1023         cdr->party_a.snapshot = chan;
1024         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1025
1026         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->name);
1027
1028         cdr_object_transition_state(cdr, &single_state_fn_table);
1029
1030         return cdr;
1031 }
1032
1033 /*!
1034  * \brief Create a new \ref cdr_object and append it to an existing chain
1035  * \param cdr The \ref cdr_object to append to
1036  */
1037 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
1038 {
1039         struct cdr_object *new_cdr;
1040         struct cdr_object *it_cdr;
1041         struct cdr_object *cdr_last;
1042
1043         cdr_last = cdr->last;
1044         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
1045         if (!new_cdr) {
1046                 return NULL;
1047         }
1048         new_cdr->disposition = AST_CDR_NULL;
1049
1050         /* Copy over the linkedid, as it may have changed */
1051         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1052         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1053         ast_string_field_set(new_cdr, data, cdr_last->data);
1054         ast_string_field_set(new_cdr, context, cdr_last->context);
1055         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1056
1057         /*
1058          * If the current CDR says to disable all future ones,
1059          * keep the disable chain going
1060          */
1061         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1062                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1063         }
1064
1065         /* Copy over other Party A information */
1066         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1067
1068         /* Append the CDR to the end of the list */
1069         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1070                 it_cdr->last = new_cdr;
1071         }
1072         it_cdr->last = new_cdr;
1073         it_cdr->next = new_cdr;
1074
1075         return new_cdr;
1076 }
1077
1078 /*!
1079  * \internal
1080  * \brief Determine if CDR flag is configured.
1081  *
1082  * \param cdr_flag The configured CDR flag to check.
1083  *
1084  * \retval 0 if the CDR flag is not configured.
1085  * \retval non-zero if the CDR flag is configured.
1086  *
1087  * \return Nothing
1088  */
1089 static int is_cdr_flag_set(unsigned int cdr_flag)
1090 {
1091         struct module_config *mod_cfg;
1092         int flag_set;
1093
1094         mod_cfg = ao2_global_obj_ref(module_configs);
1095         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1096         ao2_cleanup(mod_cfg);
1097         return flag_set;
1098 }
1099
1100 /*!
1101  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1102  * to endbeforehexten logic
1103  *
1104  * \param old_snapshot The previous state
1105  * \param new_snapshot The new state
1106  *
1107  * \retval 0 if the state has not changed
1108  * \retval 1 if the state changed
1109  */
1110 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1111         struct ast_channel_snapshot *new_snapshot)
1112 {
1113         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1114         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1115                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1116                 return 0;
1117         }
1118
1119         /* When Party A is originated to an application and the application exits, the stack
1120          * will attempt to clear the application and restore the dummy originate application
1121          * of "AppDialX". Ignore application changes to AppDialX as a result.
1122          */
1123         if (strcmp(new_snapshot->appl, old_snapshot->appl)
1124                 && strncasecmp(new_snapshot->appl, "appdial", 7)
1125                 && (strcmp(new_snapshot->context, old_snapshot->context)
1126                         || strcmp(new_snapshot->exten, old_snapshot->exten)
1127                         || new_snapshot->priority != old_snapshot->priority)) {
1128                 return 1;
1129         }
1130
1131         return 0;
1132 }
1133
1134 /*!
1135  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1136  * that was created as the result of a dial operation
1137  *
1138  * \retval 0 the channel was not created as the result of a dial
1139  * \retval 1 the channel was created as the result of a dial
1140  */
1141 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1142 {
1143         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1144                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1145 }
1146
1147 /*!
1148  * \brief Given two CDR snapshots, figure out who should be Party A for the
1149  * resulting CDR
1150  * \param left One of the snapshots
1151  * \param right The other snapshot
1152  * \retval The snapshot that won
1153  */
1154 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1155 {
1156         /* Check whether or not the party is dialed. A dialed party is never the
1157          * Party A with a party that was not dialed.
1158          */
1159         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1160                 return left;
1161         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1162                 return right;
1163         }
1164
1165         /* Try the Party A flag */
1166         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1167                 return left;
1168         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1169                 return right;
1170         }
1171
1172         /* Neither party is dialed and neither has the Party A flag - defer to
1173          * creation time */
1174         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1175                 return left;
1176         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1177                 return right;
1178         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1179                 return right;
1180         } else {
1181                 /* Okay, fine, take the left one */
1182                 return left;
1183         }
1184 }
1185
1186 /*!
1187  * Compute the duration for a \ref cdr_object
1188  */
1189 static long cdr_object_get_duration(struct cdr_object *cdr)
1190 {
1191         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1192 }
1193
1194 /*!
1195  * \brief Compute the billsec for a \ref cdr_object
1196  */
1197 static long cdr_object_get_billsec(struct cdr_object *cdr)
1198 {
1199         long int ms;
1200
1201         if (ast_tvzero(cdr->answer)) {
1202                 return 0;
1203         }
1204
1205         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1206         if (ms % 1000 >= 500
1207                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1208                 ms = (ms / 1000) + 1;
1209         } else {
1210                 ms = ms / 1000;
1211         }
1212
1213         return ms;
1214 }
1215
1216 /*!
1217  * \internal
1218  * \brief Set a variable on a CDR object
1219  *
1220  * \param headp The header pointer to the variable to set
1221  * \param name The name of the variable
1222  * \param value The value of the variable
1223  */
1224 static void set_variable(struct varshead *headp, const char *name, const char *value)
1225 {
1226         struct ast_var_t *newvariable;
1227
1228         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1229                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1230                         AST_LIST_REMOVE_CURRENT(entries);
1231                         ast_var_delete(newvariable);
1232                         break;
1233                 }
1234         }
1235         AST_LIST_TRAVERSE_SAFE_END;
1236
1237         if (value && (newvariable = ast_var_assign(name, value))) {
1238                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1239         }
1240 }
1241
1242 /*!
1243  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1244  * suitable for consumption by the registered CDR backends
1245  * \param cdr The \ref cdr_object to convert to a public record
1246  * \retval A chain of \ref ast_cdr objects on success
1247  * \retval NULL on failure
1248  */
1249 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1250 {
1251         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1252         struct cdr_object *it_cdr;
1253         struct ast_var_t *it_var, *it_copy_var;
1254         struct ast_channel_snapshot *party_a;
1255         struct ast_channel_snapshot *party_b;
1256
1257         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1258                 struct ast_cdr *cdr_copy;
1259
1260                 /* Don't create records for CDRs where the party A was a dialed channel */
1261                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1262                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1263                                 it_cdr->party_a.snapshot->name);
1264                         continue;
1265                 }
1266
1267                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1268                 if (!cdr_copy) {
1269                         ast_free(pub_cdr);
1270                         return NULL;
1271                 }
1272
1273                 party_a = it_cdr->party_a.snapshot;
1274                 party_b = it_cdr->party_b.snapshot;
1275
1276                 /* Party A */
1277                 ast_assert(party_a != NULL);
1278                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1279                 cdr_copy->amaflags = party_a->amaflags;
1280                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1281                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1282                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1283                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1284                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1285                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1286                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1287                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1288
1289                 /* Party B */
1290                 if (party_b) {
1291                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1292                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1293                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1294                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1295                         }
1296                 }
1297                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1298                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1299                 }
1300
1301                 /* Timestamps/durations */
1302                 cdr_copy->start = it_cdr->start;
1303                 cdr_copy->answer = it_cdr->answer;
1304                 cdr_copy->end = it_cdr->end;
1305                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1306                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1307
1308                 /* Flags and IDs */
1309                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1310                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1311                 cdr_copy->disposition = it_cdr->disposition;
1312                 cdr_copy->sequence = it_cdr->sequence;
1313
1314                 /* Variables */
1315                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1316                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1317                         int found = 0;
1318                         struct ast_var_t *newvariable;
1319                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1320                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1321                                         found = 1;
1322                                         break;
1323                                 }
1324                         }
1325                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1326                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1327                         }
1328                 }
1329
1330                 if (!pub_cdr) {
1331                         pub_cdr = cdr_copy;
1332                         cdr_prev = pub_cdr;
1333                 } else {
1334                         cdr_prev->next = cdr_copy;
1335                         cdr_prev = cdr_copy;
1336                 }
1337         }
1338
1339         return pub_cdr;
1340 }
1341
1342 /*!
1343  * \brief Dispatch a CDR.
1344  * \param cdr The \ref cdr_object to dispatch
1345  *
1346  * This will create a \ref ast_cdr object and publish it to the various backends
1347  */
1348 static void cdr_object_dispatch(struct cdr_object *cdr)
1349 {
1350         struct ast_cdr *pub_cdr;
1351
1352         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1353                 cdr->party_a.snapshot->name,
1354                 cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1355         pub_cdr = cdr_object_create_public_records(cdr);
1356         cdr_detach(pub_cdr);
1357 }
1358
1359 /*!
1360  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1361  * \param cdr The \ref cdr_object
1362  * \param hangupcause The Asterisk hangup cause code
1363  */
1364 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1365 {
1366         /* Change the disposition based on the hang up cause */
1367         switch (hangupcause) {
1368         case AST_CAUSE_BUSY:
1369                 cdr->disposition = AST_CDR_BUSY;
1370                 break;
1371         case AST_CAUSE_CONGESTION:
1372                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1373                         cdr->disposition = AST_CDR_FAILED;
1374                 } else {
1375                         cdr->disposition = AST_CDR_CONGESTION;
1376                 }
1377                 break;
1378         case AST_CAUSE_NO_ROUTE_DESTINATION:
1379         case AST_CAUSE_UNREGISTERED:
1380                 cdr->disposition = AST_CDR_FAILED;
1381                 break;
1382         case AST_CAUSE_NORMAL_CLEARING:
1383         case AST_CAUSE_NO_ANSWER:
1384                 cdr->disposition = AST_CDR_NOANSWER;
1385                 break;
1386         default:
1387                 break;
1388         }
1389 }
1390
1391 /*!
1392  * \brief Finalize a CDR.
1393  *
1394  * This function is safe to call multiple times. Note that you can call this
1395  * explicitly before going to the finalized state if there's a chance the CDR
1396  * will be re-activated, in which case the \ref cdr_object's end time should be
1397  * cleared. This function is implicitly called when a CDR transitions to the
1398  * finalized state and right before it is dispatched
1399  *
1400  * \param cdr_object The CDR to finalize
1401  */
1402 static void cdr_object_finalize(struct cdr_object *cdr)
1403 {
1404         if (!ast_tvzero(cdr->end)) {
1405                 return;
1406         }
1407         cdr->end = ast_tvnow();
1408
1409         if (cdr->disposition == AST_CDR_NULL) {
1410                 if (!ast_tvzero(cdr->answer)) {
1411                         cdr->disposition = AST_CDR_ANSWERED;
1412                 } else if (cdr->party_a.snapshot->hangupcause) {
1413                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1414                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1415                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1416                 } else {
1417                         cdr->disposition = AST_CDR_FAILED;
1418                 }
1419         }
1420
1421         /* tv_usec is suseconds_t, which could be int or long */
1422         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1423                         cdr->party_a.snapshot->name,
1424                         (long)cdr->start.tv_sec,
1425                         (long)cdr->start.tv_usec,
1426                         (long)cdr->answer.tv_sec,
1427                         (long)cdr->answer.tv_usec,
1428                         (long)cdr->end.tv_sec,
1429                         (long)cdr->end.tv_usec,
1430                         ast_cdr_disp2str(cdr->disposition));
1431 }
1432
1433 /*!
1434  * \brief Check to see if a CDR needs to move to the finalized state because
1435  * its Party A hungup.
1436  */
1437 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1438 {
1439         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1440                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1441                 cdr_object_finalize(cdr);
1442         }
1443
1444         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1445                 && cdr->fn_table != &finalized_state_fn_table) {
1446                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1447         }
1448 }
1449
1450 /*!
1451  * \brief Check to see if a CDR needs to be answered based on its Party A.
1452  * Note that this is safe to call as much as you want - we won't answer twice
1453  */
1454 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1455 {
1456         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1457                 cdr->answer = ast_tvnow();
1458                 /* tv_usec is suseconds_t, which could be int or long */
1459                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1460                         (long)cdr->answer.tv_sec,
1461                         (long)cdr->answer.tv_usec);
1462         }
1463 }
1464
1465 /* \brief Set Caller ID information on a CDR */
1466 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1467 {
1468         if (!old_snapshot->snapshot) {
1469                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1470                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1471                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1472                 return;
1473         }
1474         if (strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1475                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1476         }
1477         if (strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1478                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1479         }
1480         if (strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1481                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1482         }
1483 }
1484
1485 /*!
1486  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1487  * a new \ref ast_channel_snapshot
1488  * \param old_snapshot The old \ref cdr_object_snapshot
1489  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1490  */
1491 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1492                 struct ast_channel_snapshot *new_snapshot)
1493 {
1494         cdr_object_update_cid(old_snapshot, new_snapshot);
1495         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1496 }
1497
1498 /* BASE METHOD IMPLEMENTATIONS */
1499
1500 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1501 {
1502         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1503
1504         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1505         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1506                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1507                 cdr_object_finalize(cdr);
1508                 return 0;
1509         }
1510
1511         /*
1512          * Only record the context and extension if we aren't in a subroutine, or if
1513          * we are executing hangup logic.
1514          */
1515         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1516                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1517                 if (strcmp(cdr->context, snapshot->context)) {
1518                         ast_string_field_set(cdr, context, snapshot->context);
1519                 }
1520                 if (strcmp(cdr->exten, snapshot->exten)) {
1521                         ast_string_field_set(cdr, exten, snapshot->exten);
1522                 }
1523         }
1524
1525         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1526
1527         /* When Party A is originated to an application and the application exits, the stack
1528          * will attempt to clear the application and restore the dummy originate application
1529          * of "AppDialX". Prevent that, and any other application changes we might not want
1530          * here.
1531          */
1532         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1533                 && !ast_strlen_zero(snapshot->appl)
1534                 && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1535                 if (strcmp(cdr->appl, snapshot->appl)) {
1536                         ast_string_field_set(cdr, appl, snapshot->appl);
1537                 }
1538                 if (strcmp(cdr->data, snapshot->data)) {
1539                         ast_string_field_set(cdr, data, snapshot->data);
1540                 }
1541
1542                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1543                  * execute before the dial begins, will alter the application/data to
1544                  * something people typically don't want to see, if we see a channel enter
1545                  * into Dial here, we set the appl/data accordingly and lock it.
1546                  */
1547                 if (!strcmp(snapshot->appl, "Dial")) {
1548                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1549                 }
1550         }
1551
1552         if (strcmp(cdr->linkedid, snapshot->linkedid)) {
1553                 ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1554         }
1555         cdr_object_check_party_a_answer(cdr);
1556         cdr_object_check_party_a_hangup(cdr);
1557
1558         return 0;
1559 }
1560
1561 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1562 {
1563         return 0;
1564 }
1565
1566 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1567 {
1568         return 0;
1569 }
1570
1571 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1572 {
1573         /* Base process bridge enter simply indicates that we can't handle it */
1574         return BRIDGE_ENTER_NEED_CDR;
1575 }
1576
1577 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1578 {
1579         char park_info[128];
1580
1581         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1582
1583         /* Update Party A information regardless */
1584         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1585
1586         /* Fake out where we're parked */
1587         ast_string_field_set(cdr, appl, "Park");
1588         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1589         ast_string_field_set(cdr, data, park_info);
1590
1591         /* Prevent any further changes to the App/Data fields for this record */
1592         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1593
1594         return 0;
1595 }
1596
1597 /* SINGLE STATE */
1598
1599 static void single_state_init_function(struct cdr_object *cdr)
1600 {
1601         cdr->start = ast_tvnow();
1602         cdr_object_check_party_a_answer(cdr);
1603 }
1604
1605 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1606 {
1607         /* This should never happen! */
1608         ast_assert(cdr->party_b.snapshot == NULL);
1609         ast_assert(0);
1610         return;
1611 }
1612
1613 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1614 {
1615         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1616                 base_process_party_a(cdr, caller);
1617                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1618                         cdr->party_a.snapshot->name);
1619                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1620                 cdr_all_relink(cdr);
1621                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1622                         cdr->party_b.snapshot->name);
1623
1624                 /* If we have two parties, lock the application that caused the
1625                  * two parties to be associated. This prevents mid-call event
1626                  * macros/gosubs from perturbing the CDR application/data
1627                  */
1628                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1629         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1630                 /* We're the entity being dialed, i.e., outbound origination */
1631                 base_process_party_a(cdr, peer);
1632                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1633                         cdr->party_a.snapshot->name);
1634         }
1635
1636         cdr_object_transition_state(cdr, &dial_state_fn_table);
1637         return 0;
1638 }
1639
1640 /*!
1641  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1642  * already in the bridge while in the Single state. The goal of this is to find
1643  * a Party B for our CDR.
1644  *
1645  * \param cdr Our \ref cdr_object in the Single state
1646  * \param cand_cdr The \ref cdr_object already in the Bridge state
1647  *
1648  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1649  * Party B
1650  * \retval 1 No party in the cand_cdr could be used as our Party B
1651  */
1652 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1653                 struct cdr_object *cand_cdr)
1654 {
1655         struct cdr_object_snapshot *party_a;
1656
1657         /* Don't match on ourselves */
1658         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1659                 return 1;
1660         }
1661
1662         /* Try the candidate CDR's Party A first */
1663         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1664         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1665                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1666                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1667                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1668                 cdr_all_relink(cdr);
1669                 if (!cand_cdr->party_b.snapshot) {
1670                         /* We just stole them - finalize their CDR. Note that this won't
1671                          * transition their state, it just sets the end time and the
1672                          * disposition - if we need to re-activate them later, we can.
1673                          */
1674                         cdr_object_finalize(cand_cdr);
1675                 }
1676                 return 0;
1677         }
1678
1679         /* Try their Party B, unless it's us */
1680         if (!cand_cdr->party_b.snapshot
1681                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1682                 return 1;
1683         }
1684         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1685         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1686                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1687                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1688                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1689                 cdr_all_relink(cdr);
1690                 return 0;
1691         }
1692
1693         return 1;
1694 }
1695
1696 static enum process_bridge_enter_results single_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1697 {
1698         struct ao2_iterator it_cdrs;
1699         char *channel_id;
1700         int success = 0;
1701
1702         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1703
1704         if (ao2_container_count(bridge->channels) == 1) {
1705                 /* No one in the bridge yet but us! */
1706                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1707                 return BRIDGE_ENTER_ONLY_PARTY;
1708         }
1709
1710         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1711                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1712                 ao2_ref(channel_id, -1)) {
1713                 struct cdr_object *cand_cdr_master;
1714                 struct cdr_object *cand_cdr;
1715
1716                 cand_cdr_master = ao2_find(active_cdrs_by_channel, channel_id, OBJ_SEARCH_KEY);
1717                 if (!cand_cdr_master) {
1718                         continue;
1719                 }
1720
1721                 ao2_lock(cand_cdr_master);
1722                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1723                         /* Skip any records that are not in a bridge or in this bridge.
1724                          * I'm not sure how that would happen, but it pays to be careful. */
1725                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1726                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1727                                 continue;
1728                         }
1729
1730                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1731                                 continue;
1732                         }
1733                         /* We successfully got a party B - break out */
1734                         success = 1;
1735                         break;
1736                 }
1737                 ao2_unlock(cand_cdr_master);
1738                 ao2_cleanup(cand_cdr_master);
1739         }
1740         ao2_iterator_destroy(&it_cdrs);
1741
1742         /* We always transition state, even if we didn't get a peer */
1743         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1744
1745         /* Success implies that we have a Party B */
1746         if (success) {
1747                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1748         }
1749
1750         return BRIDGE_ENTER_NO_PARTY_B;
1751 }
1752
1753 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1754 {
1755         cdr_object_transition_state(cdr, &parked_state_fn_table);
1756         return 0;
1757 }
1758
1759
1760 /* DIAL STATE */
1761
1762 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1763 {
1764         ast_assert(snapshot != NULL);
1765         ast_assert(cdr->party_b.snapshot
1766                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1767
1768         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1769
1770         /* If party B hangs up, finalize this CDR */
1771         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1772                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1773         }
1774 }
1775
1776 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1777 {
1778         /* Don't process a begin dial here. A party A already in the dial state will
1779          * who receives a dial begin for something else will be handled by the
1780          * message router callback and will add a new CDR for the party A */
1781         return 1;
1782 }
1783
1784 /*!
1785  * \internal
1786  * \brief Convert a dial status to a CDR disposition
1787  */
1788 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1789 {
1790         if (!strcmp(dial_status, "ANSWER")) {
1791                 return AST_CDR_ANSWERED;
1792         } else if (!strcmp(dial_status, "BUSY")) {
1793                 return AST_CDR_BUSY;
1794         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1795                 return AST_CDR_NOANSWER;
1796         } else if (!strcmp(dial_status, "CONGESTION")) {
1797                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1798                         return AST_CDR_FAILED;
1799                 } else {
1800                         return AST_CDR_CONGESTION;
1801                 }
1802         } else if (!strcmp(dial_status, "FAILED")) {
1803                 return AST_CDR_FAILED;
1804         }
1805         return AST_CDR_FAILED;
1806 }
1807
1808 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)
1809 {
1810         struct ast_channel_snapshot *party_a;
1811
1812         if (caller) {
1813                 party_a = caller;
1814         } else {
1815                 party_a = peer;
1816         }
1817         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1818         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1819
1820         if (cdr->party_b.snapshot) {
1821                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1822                         /* Not the status for this CDR - defer back to the message router */
1823                         return 1;
1824                 }
1825                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1826         }
1827
1828         /* Set the disposition based on the dial string. */
1829         cdr->disposition = dial_status_to_disposition(dial_status);
1830         if (cdr->disposition == AST_CDR_ANSWERED) {
1831                 /* Switch to dial pending to wait and see what the caller does */
1832                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1833         } else {
1834                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1835         }
1836
1837         return 0;
1838 }
1839
1840 static enum process_bridge_enter_results dial_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1841 {
1842         int success = 0;
1843
1844         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1845
1846         /* Get parties in the bridge */
1847         if (ao2_container_count(bridge->channels) == 1) {
1848                 /* No one in the bridge yet but us! */
1849                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1850                 return BRIDGE_ENTER_ONLY_PARTY;
1851         }
1852
1853         /* If we don't have a Party B (originated channel), skip it */
1854         if (cdr->party_b.snapshot) {
1855                 struct ao2_iterator it_cdrs;
1856                 char *channel_id;
1857
1858                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1859                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1860                         ao2_ref(channel_id, -1)) {
1861                         struct cdr_object *cand_cdr_master;
1862                         struct cdr_object *cand_cdr;
1863
1864                         cand_cdr_master = ao2_find(active_cdrs_by_channel, channel_id, OBJ_SEARCH_KEY);
1865                         if (!cand_cdr_master) {
1866                                 continue;
1867                         }
1868
1869                         ao2_lock(cand_cdr_master);
1870                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1871                                 /* Skip any records that are not in a bridge or in this bridge.
1872                                  * I'm not sure how that would happen, but it pays to be careful. */
1873                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1874                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1875                                         continue;
1876                                 }
1877
1878                                 /* Skip any records that aren't our Party B */
1879                                 if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1880                                         continue;
1881                                 }
1882                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1883                                 /* If they have a Party B, they joined up with someone else as their
1884                                  * Party A. Don't finalize them as they're active. Otherwise, we
1885                                  * have stolen them so they need to be finalized.
1886                                  */
1887                                 if (!cand_cdr->party_b.snapshot) {
1888                                         cdr_object_finalize(cand_cdr);
1889                                 }
1890                                 success = 1;
1891                                 break;
1892                         }
1893                         ao2_unlock(cand_cdr_master);
1894                         ao2_cleanup(cand_cdr_master);
1895                 }
1896                 ao2_iterator_destroy(&it_cdrs);
1897         }
1898
1899         /* We always transition state, even if we didn't get a peer */
1900         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1901
1902         /* Success implies that we have a Party B */
1903         if (success) {
1904                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1905         }
1906         return BRIDGE_ENTER_NO_PARTY_B;
1907 }
1908
1909 /* DIALED PENDING STATE */
1910
1911 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1912 {
1913         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1914          * that means we need a new CDR; otherwise, switch us over to single.
1915          */
1916         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1917                 if (cdr->party_b.snapshot) {
1918                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1919                         cdr->fn_table->process_party_a(cdr, snapshot);
1920                         return 1;
1921                 } else {
1922                         cdr_object_transition_state(cdr, &single_state_fn_table);
1923                         cdr->fn_table->process_party_a(cdr, snapshot);
1924                         return 0;
1925                 }
1926         }
1927         base_process_party_a(cdr, snapshot);
1928         return 0;
1929 }
1930
1931 static enum process_bridge_enter_results dialed_pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1932 {
1933         cdr_object_transition_state(cdr, &dial_state_fn_table);
1934         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1935 }
1936
1937 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1938 {
1939         if (cdr->party_b.snapshot) {
1940                 /* We can't handle this as we have a Party B - ask for a new one */
1941                 return 1;
1942         }
1943         cdr_object_transition_state(cdr, &parked_state_fn_table);
1944         return 0;
1945 }
1946
1947 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1948 {
1949         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1950
1951         /* Ask for a new CDR */
1952         return 1;
1953 }
1954
1955 /* BRIDGE STATE */
1956
1957 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1958 {
1959         ast_assert(cdr->party_b.snapshot
1960                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1961
1962         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1963
1964         /* If party B hangs up, finalize this CDR */
1965         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1966                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1967         }
1968 }
1969
1970 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1971 {
1972         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1973                 return 1;
1974         }
1975         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
1976                 && cdr->party_b.snapshot
1977                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
1978                 return 1;
1979         }
1980         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1981
1982         return 0;
1983 }
1984
1985 /* PARKED STATE */
1986
1987 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1988 {
1989         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
1990                 return 1;
1991         }
1992         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1993
1994         return 0;
1995 }
1996
1997 /* FINALIZED STATE */
1998
1999 static void finalized_state_init_function(struct cdr_object *cdr)
2000 {
2001         cdr_object_finalize(cdr);
2002 }
2003
2004 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2005 {
2006         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2007                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2008                 return 0;
2009         }
2010
2011         /* Indicate that, if possible, we should get a new CDR */
2012         return 1;
2013 }
2014
2015 /*!
2016  * \internal
2017  * \brief Filter channel snapshots by technology
2018  */
2019 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2020 {
2021         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
2022 }
2023
2024 /*!
2025  * \internal
2026  * \brief Filter a channel cache update
2027  */
2028 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
2029                 struct ast_channel_snapshot *new_snapshot)
2030 {
2031         int ret = 0;
2032
2033         /* Drop cache updates from certain channel technologies */
2034         if (old_snapshot) {
2035                 ret |= filter_channel_snapshot(old_snapshot);
2036         }
2037         if (new_snapshot) {
2038                 ret |= filter_channel_snapshot(new_snapshot);
2039         }
2040
2041         return ret;
2042 }
2043
2044 static int dial_status_end(const char *dialstatus)
2045 {
2046         return (strcmp(dialstatus, "RINGING") &&
2047                         strcmp(dialstatus, "PROCEEDING") &&
2048                         strcmp(dialstatus, "PROGRESS"));
2049 }
2050
2051 /* TOPIC ROUTER CALLBACKS */
2052
2053 /*!
2054  * \brief Handler for Stasis-Core dial messages
2055  * \param data Passed on
2056  * \param sub The stasis subscription for this message callback
2057  * \param topic The topic this message was published for
2058  * \param message The message
2059  */
2060 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2061 {
2062         struct cdr_object *cdr;
2063         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2064         struct ast_channel_snapshot *caller;
2065         struct ast_channel_snapshot *peer;
2066         struct cdr_object *it_cdr;
2067         struct ast_json *dial_status_blob;
2068         const char *dial_status = NULL;
2069         int res = 1;
2070
2071         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2072         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2073         if (!peer && !caller) {
2074                 return;
2075         }
2076         if (filter_channel_snapshot(peer) || (caller && filter_channel_snapshot(caller))) {
2077                 return;
2078         }
2079
2080         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2081         if (dial_status_blob) {
2082                 dial_status = ast_json_string_get(dial_status_blob);
2083         }
2084
2085         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2086                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2087                 caller ? caller->name : "(none)",
2088                 peer ? peer->name : "(none)",
2089                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2090                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2091
2092         /* Figure out who is running this show */
2093         if (caller) {
2094                 cdr = ao2_find(active_cdrs_by_channel, caller->uniqueid, OBJ_SEARCH_KEY);
2095         } else {
2096                 cdr = ao2_find(active_cdrs_by_channel, peer->uniqueid, OBJ_SEARCH_KEY);
2097         }
2098         if (!cdr) {
2099                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
2100                 ast_assert(0);
2101                 return;
2102         }
2103
2104         ao2_lock(cdr);
2105         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2106                 if (ast_strlen_zero(dial_status)) {
2107                         if (!it_cdr->fn_table->process_dial_begin) {
2108                                 continue;
2109                         }
2110                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2111                                 it_cdr,
2112                                 caller ? caller->name : "(none)",
2113                                 peer ? peer->name : "(none)");
2114                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2115                                         caller,
2116                                         peer);
2117                 } else if (dial_status_end(dial_status)) {
2118                         if (!it_cdr->fn_table->process_dial_end) {
2119                                 continue;
2120                         }
2121                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2122                                 it_cdr,
2123                                 caller ? caller->name : "(none)",
2124                                 peer ? peer->name : "(none)");
2125                         it_cdr->fn_table->process_dial_end(it_cdr,
2126                                         caller,
2127                                         peer,
2128                                         dial_status);
2129                 }
2130         }
2131
2132         /* If no CDR handled a dial begin message, make a new one */
2133         if (res && ast_strlen_zero(dial_status)) {
2134                 struct cdr_object *new_cdr;
2135
2136                 new_cdr = cdr_object_create_and_append(cdr);
2137                 if (new_cdr) {
2138                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2139                 }
2140         }
2141         ao2_unlock(cdr);
2142         ao2_cleanup(cdr);
2143 }
2144
2145 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2146 {
2147         struct cdr_object *cdr = obj;
2148
2149         if (!strcasecmp(cdr->party_b_name, arg)) {
2150 #ifdef AST_DEVMODE
2151                 struct ast_channel_snapshot *party_b = data;
2152
2153                 /*
2154                  * For sanity's sake we also assert the party_b snapshot
2155                  * is consistent with the key.
2156                  */
2157                 ast_assert(cdr->party_b.snapshot
2158                         && !strcasecmp(cdr->party_b.snapshot->name, party_b->name));
2159 #endif
2160
2161                 /* Don't transition to the finalized state - let the Party A do
2162                  * that when its ready
2163                  */
2164                 cdr_object_finalize(cdr);
2165         }
2166         return 0;
2167 }
2168
2169 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2170 {
2171         struct cdr_object *cdr = obj;
2172
2173         if (cdr->fn_table->process_party_b
2174                 && !strcasecmp(cdr->party_b_name, arg)) {
2175                 struct ast_channel_snapshot *party_b = data;
2176
2177                 /*
2178                  * For sanity's sake we also check the party_b snapshot
2179                  * for consistency with the key.  The callback needs and
2180                  * asserts the snapshot to be this way.
2181                  */
2182                 if (!cdr->party_b.snapshot
2183                         || strcasecmp(cdr->party_b.snapshot->name, party_b->name)) {
2184                         ast_log(LOG_NOTICE,
2185                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2186                                 cdr->linkedid,
2187                                 cdr->party_a.snapshot->name,
2188                                 cdr->party_b_name);
2189                         return 0;
2190                 }
2191
2192                 cdr->fn_table->process_party_b(cdr, party_b);
2193         }
2194         return 0;
2195 }
2196
2197 /*! \brief Determine if we need to add a new CDR based on snapshots */
2198 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2199                 struct ast_channel_snapshot *new_snapshot)
2200 {
2201         /* If we're dead, we don't need a new CDR */
2202         if (!new_snapshot
2203                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2204                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2205                 return 0;
2206         }
2207
2208         /* Auto-fall through will increment the priority but have no application */
2209         if (ast_strlen_zero(new_snapshot->appl)) {
2210                 return 0;
2211         }
2212
2213         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2214                 return 0;
2215         }
2216
2217         return 1;
2218 }
2219
2220 /*!
2221  * \brief Handler for Stasis-Core channel cache update messages
2222  * \param data Passed on
2223  * \param sub The stasis subscription for this message callback
2224  * \param topic The topic this message was published for
2225  * \param message The message
2226  */
2227 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2228 {
2229         struct cdr_object *cdr;
2230         struct stasis_cache_update *update = stasis_message_data(message);
2231         struct ast_channel_snapshot *old_snapshot;
2232         struct ast_channel_snapshot *new_snapshot;
2233         struct cdr_object *it_cdr;
2234
2235         ast_assert(update != NULL);
2236         ast_assert(ast_channel_snapshot_type() == update->type);
2237
2238         old_snapshot = stasis_message_data(update->old_snapshot);
2239         new_snapshot = stasis_message_data(update->new_snapshot);
2240
2241         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2242                 return;
2243         }
2244
2245         if (new_snapshot && !old_snapshot) {
2246                 cdr = cdr_object_alloc(new_snapshot);
2247                 if (!cdr) {
2248                         return;
2249                 }
2250                 cdr->is_root = 1;
2251                 ao2_link(active_cdrs_by_channel, cdr);
2252         } else {
2253                 const char *uniqueid;
2254
2255                 uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2256                 cdr = ao2_find(active_cdrs_by_channel, uniqueid, OBJ_SEARCH_KEY);
2257         }
2258
2259         /* Handle Party A */
2260         if (!cdr) {
2261                 const char *name;
2262
2263                 name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2264                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2265                 ast_assert(0);
2266         } else if (new_snapshot) {
2267                 int all_reject = 1;
2268
2269                 ao2_lock(cdr);
2270                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2271                         if (!it_cdr->fn_table->process_party_a) {
2272                                 continue;
2273                         }
2274                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2275                 }
2276                 if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2277                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2278                         struct cdr_object *new_cdr;
2279
2280                         new_cdr = cdr_object_create_and_append(cdr);
2281                         if (new_cdr) {
2282                                 new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2283                         }
2284                 }
2285                 ao2_unlock(cdr);
2286         } else {
2287                 ao2_lock(cdr);
2288                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2289                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2290                         cdr_object_finalize(it_cdr);
2291                 }
2292                 cdr_object_dispatch(cdr);
2293                 ao2_unlock(cdr);
2294
2295                 cdr_all_unlink(cdr);
2296                 ao2_unlink(active_cdrs_by_channel, cdr);
2297         }
2298
2299         /* Handle Party B */
2300         if (new_snapshot) {
2301                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2302                         cdr_object_update_party_b, (char *) new_snapshot->name, new_snapshot);
2303         } else {
2304                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2305                         cdr_object_finalize_party_b, (char *) old_snapshot->name, old_snapshot);
2306         }
2307
2308         ao2_cleanup(cdr);
2309 }
2310
2311 struct bridge_leave_data {
2312         struct ast_bridge_snapshot *bridge;
2313         struct ast_channel_snapshot *channel;
2314 };
2315
2316 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2317 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2318 {
2319         struct cdr_object *cdr = obj;
2320         struct bridge_leave_data *leave_data = data;
2321
2322         if (cdr->fn_table == &bridge_state_fn_table
2323                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2324                 && !strcasecmp(cdr->party_b_name, arg)) {
2325                 /*
2326                  * For sanity's sake we also assert the party_b snapshot
2327                  * is consistent with the key.
2328                  */
2329                 ast_assert(cdr->party_b.snapshot
2330                         && !strcasecmp(cdr->party_b.snapshot->name, leave_data->channel->name));
2331
2332                 /* It is our Party B, in our bridge. Set the end time and let the handler
2333                  * transition our CDR appropriately when we leave the bridge.
2334                  */
2335                 cdr_object_finalize(cdr);
2336         }
2337         return 0;
2338 }
2339
2340 /*! \brief Filter bridge messages based on bridge technology */
2341 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2342 {
2343         /* Ignore holding bridge technology messages. We treat this simply as an application
2344          * that a channel enters into.
2345          */
2346         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2347                 return 1;
2348         }
2349         return 0;
2350 }
2351
2352 /*!
2353  * \brief Handler for when a channel leaves a bridge
2354  * \param data Passed on
2355  * \param sub The stasis subscription for this message callback
2356  * \param topic The topic this message was published for
2357  * \param message The message - hopefully a bridge one!
2358  */
2359 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2360                 struct stasis_message *message)
2361 {
2362         struct ast_bridge_blob *update = stasis_message_data(message);
2363         struct ast_bridge_snapshot *bridge = update->bridge;
2364         struct ast_channel_snapshot *channel = update->channel;
2365         struct cdr_object *cdr;
2366         struct cdr_object *it_cdr;
2367         struct bridge_leave_data leave_data = {
2368                 .bridge = bridge,
2369                 .channel = channel,
2370         };
2371         int left_bridge = 0;
2372
2373         if (filter_bridge_messages(bridge)) {
2374                 return;
2375         }
2376
2377         if (filter_channel_snapshot(channel)) {
2378                 return;
2379         }
2380
2381         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2382                 channel->name,
2383                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2384                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2385
2386         cdr = ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_SEARCH_KEY);
2387         if (!cdr) {
2388                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2389                 ast_assert(0);
2390                 return;
2391         }
2392
2393         /* Party A */
2394         ao2_lock(cdr);
2395         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2396                 if (!it_cdr->fn_table->process_bridge_leave) {
2397                         continue;
2398                 }
2399                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2400                         it_cdr, channel->name);
2401                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2402                         ast_string_field_set(it_cdr, bridge, "");
2403                         left_bridge = 1;
2404                 }
2405         }
2406         ao2_unlock(cdr);
2407
2408         /* Party B */
2409         if (left_bridge
2410                 && strcmp(bridge->subclass, "parking")) {
2411                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2412                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->name,
2413                         &leave_data);
2414         }
2415
2416         ao2_cleanup(cdr);
2417 }
2418
2419 /*!
2420  * \internal
2421  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2422  *
2423  * \note The new CDR will be automatically transitioned to the bridge state
2424  */
2425 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2426                 struct cdr_object_snapshot *party_b)
2427 {
2428         struct cdr_object *new_cdr;
2429
2430         new_cdr = cdr_object_create_and_append(cdr);
2431         if (!new_cdr) {
2432                 return;
2433         }
2434         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2435         cdr_all_relink(new_cdr);
2436         cdr_object_check_party_a_answer(new_cdr);
2437         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2438         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2439         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2440                 new_cdr, new_cdr->party_a.snapshot->name,
2441                 party_b->snapshot->name);
2442 }
2443
2444 /*!
2445  * \brief Process a single \ref bridge_candidate
2446  *
2447  * When a CDR enters a bridge, it needs to make pairings with everyone else
2448  * that it is not currently paired with. This function determines, for the
2449  * CDR for the channel that entered the bridge and the CDR for every other
2450  * channel currently in the bridge, who is Party A and makes new CDRs.
2451  *
2452  * \param cdr The \ref cdr_obj being processed
2453  * \param cand_cdr The \ref cdr_object that is a candidate
2454  *
2455  */
2456 static int bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2457 {
2458         struct cdr_object_snapshot *party_a;
2459         struct cdr_object *cand_cdr;
2460
2461         SCOPED_AO2LOCK(lock, base_cand_cdr);
2462
2463         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2464                 /* Skip any records that are not in this bridge */
2465                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2466                         continue;
2467                 }
2468
2469                 /* If the candidate is us or someone we've taken on, pass on by */
2470                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2471                         || (cdr->party_b.snapshot
2472                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2473                         return 0;
2474                 }
2475
2476                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2477                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2478                  * Party B */
2479                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2480                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2481                         return 0;
2482                 }
2483
2484                 /* We're Party B. Check if we can add ourselves immediately or if we need
2485                  * a new CDR for them (they already have a Party B) */
2486                 if (cand_cdr->party_b.snapshot
2487                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2488                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2489                 } else {
2490                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2491                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2492                                 cdr->party_a.snapshot->name);
2493                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2494                         cdr_all_relink(cand_cdr);
2495                         /* It's possible that this joined at one point and was never chosen
2496                          * as party A. Clear their end time, as it would be set in such a
2497                          * case.
2498                          */
2499                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2500                 }
2501                 return 0;
2502         }
2503         return 0;
2504 }
2505
2506 /*!
2507  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2508  * entered a bridge
2509  * \param cdr The \ref cdr_object that just entered the bridge
2510  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2511  */
2512 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2513 {
2514         struct ao2_iterator it_channels;
2515         char *channel_id;
2516
2517         it_channels = ao2_iterator_init(bridge->channels, 0);
2518         while ((channel_id = ao2_iterator_next(&it_channels))) {
2519                 struct cdr_object *cand_cdr;
2520
2521                 cand_cdr = ao2_find(active_cdrs_by_channel, channel_id, OBJ_SEARCH_KEY);
2522                 if (cand_cdr) {
2523                         bridge_candidate_process(cdr, cand_cdr);
2524                         ao2_ref(cand_cdr, -1);
2525                 }
2526
2527                 ao2_ref(channel_id, -1);
2528         }
2529         ao2_iterator_destroy(&it_channels);
2530 }
2531
2532 /*! \brief Handle entering into a parking bridge
2533  * \param cdr The CDR to operate on
2534  * \param bridge The bridge the channel just entered
2535  * \param channel The channel snapshot
2536  */
2537 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2538                 struct ast_bridge_snapshot *bridge,
2539                 struct ast_channel_snapshot *channel)
2540 {
2541         int res = 1;
2542         struct cdr_object *it_cdr;
2543         struct cdr_object *new_cdr;
2544
2545         ao2_lock(cdr);
2546
2547         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2548                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2549                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2550                 }
2551                 if (it_cdr->fn_table->process_party_a) {
2552                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2553                                 channel->name);
2554                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2555                 }
2556         }
2557
2558         if (res) {
2559                 /* No one handled it - we need a new one! */
2560                 new_cdr = cdr_object_create_and_append(cdr);
2561                 if (new_cdr) {
2562                         /* Let the single state transition us to Parked */
2563                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2564                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2565                 }
2566         }
2567         ao2_unlock(cdr);
2568 }
2569
2570 /*! \brief Handle a bridge enter message for a 'normal' bridge
2571  * \param cdr The CDR to operate on
2572  * \param bridge The bridge the channel just entered
2573  * \param channel The channel snapshot
2574  */
2575 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2576                 struct ast_bridge_snapshot *bridge,
2577                 struct ast_channel_snapshot *channel)
2578 {
2579         enum process_bridge_enter_results result;
2580         struct cdr_object *it_cdr;
2581         struct cdr_object *new_cdr;
2582         struct cdr_object *handled_cdr = NULL;
2583
2584         ao2_lock(cdr);
2585
2586         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2587                 if (it_cdr->fn_table->process_party_a) {
2588                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2589                                 channel->name);
2590                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2591                 }
2592
2593                 /* Notify all states that they have entered a bridge */
2594                 if (it_cdr->fn_table->process_bridge_enter) {
2595                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2596                                 channel->name);
2597                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2598                         switch (result) {
2599                         case BRIDGE_ENTER_ONLY_PARTY:
2600                                 /* Fall through */
2601                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2602                                 if (!handled_cdr) {
2603                                         handled_cdr = it_cdr;
2604                                 }
2605                                 break;
2606                         case BRIDGE_ENTER_NEED_CDR:
2607                                 /* Pass */
2608                                 break;
2609                         case BRIDGE_ENTER_NO_PARTY_B:
2610                                 /* We didn't win on any - end this CDR. If someone else comes in later
2611                                  * that is Party B to this CDR, it can re-activate this CDR.
2612                                  */
2613                                 if (!handled_cdr) {
2614                                         handled_cdr = it_cdr;
2615                                 }
2616                                 cdr_object_finalize(cdr);
2617                                 break;
2618                         }
2619                 }
2620         }
2621
2622         /* Create the new matchings, but only for either:
2623          *  * The first CDR in the chain that handled it. This avoids issues with
2624          *    forked CDRs.
2625          *  * If no one handled it, the last CDR in the chain. This would occur if
2626          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2627          *    to make pairings with everyone in the bridge.
2628          */
2629         if (handled_cdr) {
2630                 handle_bridge_pairings(handled_cdr, bridge);
2631         } else {
2632                 /* Nothing handled it - we need a new one! */
2633                 new_cdr = cdr_object_create_and_append(cdr);
2634                 if (new_cdr) {
2635                         /* This is guaranteed to succeed: the new CDR is created in the single state
2636                          * and will be able to handle the bridge enter message
2637                          */
2638                         handle_standard_bridge_enter_message(cdr, bridge, channel);
2639                 }
2640         }
2641         ao2_unlock(cdr);
2642 }
2643
2644 /*!
2645  * \internal
2646  * \brief Handler for Stasis-Core bridge enter messages
2647  * \param data Passed on
2648  * \param sub The stasis subscription for this message callback
2649  * \param topic The topic this message was published for
2650  * \param message The message - hopefully a bridge one!
2651  */
2652 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2653                 struct stasis_message *message)
2654 {
2655         struct ast_bridge_blob *update = stasis_message_data(message);
2656         struct ast_bridge_snapshot *bridge = update->bridge;
2657         struct ast_channel_snapshot *channel = update->channel;
2658         struct cdr_object *cdr;
2659
2660         if (filter_bridge_messages(bridge)) {
2661                 return;
2662         }
2663
2664         if (filter_channel_snapshot(channel)) {
2665                 return;
2666         }
2667
2668         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2669                 channel->name,
2670                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2671                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2672
2673         cdr = ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_SEARCH_KEY);
2674         if (!cdr) {
2675                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2676                 ast_assert(0);
2677                 return;
2678         }
2679
2680         if (!strcmp(bridge->subclass, "parking")) {
2681                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2682         } else {
2683                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2684         }
2685         ao2_cleanup(cdr);
2686 }
2687
2688 /*!
2689  * \brief Handler for when a channel is parked
2690  * \param data Passed on
2691  * \param sub The stasis subscription for this message callback
2692  * \param topic The topic this message was published for
2693  * \param message The message about who got parked
2694  * */
2695 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2696                 struct stasis_message *message)
2697 {
2698         struct ast_parked_call_payload *payload = stasis_message_data(message);
2699         struct ast_channel_snapshot *channel = payload->parkee;
2700         struct cdr_object *cdr;
2701         int unhandled = 1;
2702         struct cdr_object *it_cdr;
2703
2704         /* Anything other than getting parked will be handled by other updates */
2705         if (payload->event_type != PARKED_CALL) {
2706                 return;
2707         }
2708
2709         /* No one got parked? */
2710         if (!channel) {
2711                 return;
2712         }
2713
2714         if (filter_channel_snapshot(channel)) {
2715                 return;
2716         }
2717
2718         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2719                 channel->name,
2720                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2721                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2722
2723         cdr = ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_SEARCH_KEY);
2724         if (!cdr) {
2725                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2726                 ast_assert(0);
2727                 return;
2728         }
2729
2730         ao2_lock(cdr);
2731
2732         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2733                 if (it_cdr->fn_table->process_parked_channel) {
2734                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2735                 }
2736         }
2737
2738         if (unhandled) {
2739                 /* Nothing handled the messgae - we need a new one! */
2740                 struct cdr_object *new_cdr;
2741
2742                 new_cdr = cdr_object_create_and_append(cdr);
2743                 if (new_cdr) {
2744                         /* As the new CDR is created in the single state, it is guaranteed
2745                          * to have a function for the parked call message and will handle
2746                          * the message */
2747                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2748                 }
2749         }
2750
2751         ao2_unlock(cdr);
2752
2753         ao2_cleanup(cdr);
2754 }
2755
2756 /*!
2757  * \brief Handler for a synchronization message
2758  * \param data Passed on
2759  * \param sub The stasis subscription for this message callback
2760  * \param topic The topic this message was published for
2761  * \param message A blank ao2 object
2762  * */
2763 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2764                 struct stasis_message *message)
2765 {
2766         return;
2767 }
2768
2769 struct ast_cdr_config *ast_cdr_get_config(void)
2770 {
2771         struct ast_cdr_config *general;
2772         struct module_config *mod_cfg;
2773
2774         mod_cfg = ao2_global_obj_ref(module_configs);
2775         if (!mod_cfg) {
2776                 return NULL;
2777         }
2778         general = ao2_bump(mod_cfg->general);
2779         ao2_cleanup(mod_cfg);
2780         return general;
2781 }
2782
2783 void ast_cdr_set_config(struct ast_cdr_config *config)
2784 {
2785         struct module_config *mod_cfg;
2786
2787         if (!config) {
2788                 return;
2789         }
2790
2791         mod_cfg = ao2_global_obj_ref(module_configs);
2792         if (!mod_cfg) {
2793                 return;
2794         }
2795
2796         ao2_replace(mod_cfg->general, config);
2797
2798         cdr_set_debug_mode(mod_cfg);
2799         cdr_toggle_runtime_options();
2800
2801         ao2_cleanup(mod_cfg);
2802 }
2803
2804 int ast_cdr_is_enabled(void)
2805 {
2806         return is_cdr_flag_set(CDR_ENABLED);
2807 }
2808
2809 int ast_cdr_backend_suspend(const char *name)
2810 {
2811         int success = -1;
2812         struct cdr_beitem *i = NULL;
2813
2814         AST_RWLIST_WRLOCK(&be_list);
2815         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2816                 if (!strcasecmp(name, i->name)) {
2817                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2818                         i->suspended = 1;
2819                         success = 0;
2820                 }
2821         }
2822         AST_RWLIST_UNLOCK(&be_list);
2823
2824         return success;
2825 }
2826
2827 int ast_cdr_backend_unsuspend(const char *name)
2828 {
2829         int success = -1;
2830         struct cdr_beitem *i = NULL;
2831
2832         AST_RWLIST_WRLOCK(&be_list);
2833         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2834                 if (!strcasecmp(name, i->name)) {
2835                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2836                         i->suspended = 0;
2837                         success = 0;
2838                 }
2839         }
2840         AST_RWLIST_UNLOCK(&be_list);
2841
2842         return success;
2843 }
2844
2845 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2846 {
2847         struct cdr_beitem *i = NULL;
2848
2849         if (!name)
2850                 return -1;
2851
2852         if (!be) {
2853                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2854                 return -1;
2855         }
2856
2857         AST_RWLIST_WRLOCK(generic_list);
2858         AST_RWLIST_TRAVERSE(generic_list, i, list) {
2859                 if (!strcasecmp(name, i->name)) {
2860                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2861                         AST_RWLIST_UNLOCK(generic_list);
2862                         return -1;
2863                 }
2864         }
2865
2866         if (!(i = ast_calloc(1, sizeof(*i))))
2867                 return -1;
2868
2869         i->be = be;
2870         ast_copy_string(i->name, name, sizeof(i->name));
2871         ast_copy_string(i->desc, desc, sizeof(i->desc));
2872
2873         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2874         AST_RWLIST_UNLOCK(generic_list);
2875
2876         return 0;
2877 }
2878
2879 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2880 {
2881         return cdr_generic_register(&be_list, name, desc, be);
2882 }
2883
2884 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2885 {
2886         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2887 }
2888
2889 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2890 {
2891         struct cdr_beitem *match = NULL;
2892         int active_count;
2893
2894         AST_RWLIST_WRLOCK(generic_list);
2895         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2896                 if (!strcasecmp(name, match->name)) {
2897                         break;
2898                 }
2899         }
2900
2901         if (!match) {
2902                 AST_RWLIST_UNLOCK(generic_list);
2903                 return 0;
2904         }
2905
2906         active_count = ao2_container_count(active_cdrs_by_channel);
2907
2908         if (!match->suspended && active_count != 0) {
2909                 AST_RWLIST_UNLOCK(generic_list);
2910                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2911                         name, active_count);
2912                 return -1;
2913         }
2914
2915         AST_RWLIST_REMOVE(generic_list, match, list);
2916         AST_RWLIST_UNLOCK(generic_list);
2917
2918         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2919         ast_free(match);
2920
2921         return 0;
2922 }
2923
2924 int ast_cdr_unregister(const char *name)
2925 {
2926         return ast_cdr_generic_unregister(&be_list, name);
2927 }
2928
2929 int ast_cdr_modifier_unregister(const char *name)
2930 {
2931         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2932 }
2933
2934 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2935 {
2936         struct ast_cdr *newcdr;
2937
2938         if (!cdr) {
2939                 return NULL;
2940         }
2941         newcdr = ast_cdr_alloc();
2942         if (!newcdr) {
2943                 return NULL;
2944         }
2945
2946         *newcdr = *cdr;
2947         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2948         copy_variables(&newcdr->varshead, &cdr->varshead);
2949         newcdr->next = NULL;
2950
2951         return newcdr;
2952 }
2953
2954 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2955 {
2956         struct ast_var_t *variables;
2957
2958         if (ast_strlen_zero(name)) {
2959                 return NULL;
2960         }
2961
2962         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
2963                 if (!strcasecmp(name, ast_var_name(variables))) {
2964                         return ast_var_value(variables);
2965                 }
2966         }
2967
2968         return NULL;
2969 }
2970
2971 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
2972 {
2973         if (fmt == NULL) {      /* raw mode */
2974                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
2975         } else {
2976                 buf[0] = '\0';/* Ensure the buffer is initialized. */
2977                 if (when.tv_sec) {
2978                         struct ast_tm tm;
2979
2980                         ast_localtime(&when, &tm, NULL);
2981                         ast_strftime(buf, bufsize, fmt, &tm);
2982                 }
2983         }
2984 }
2985
2986 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
2987 {
2988         const char *fmt = "%Y-%m-%d %T";
2989         const char *varbuf;
2990
2991         if (!cdr) {
2992                 return;
2993         }
2994
2995         *ret = NULL;
2996
2997         if (!strcasecmp(name, "clid")) {
2998                 ast_copy_string(workspace, cdr->clid, workspacelen);
2999         } else if (!strcasecmp(name, "src")) {
3000                 ast_copy_string(workspace, cdr->src, workspacelen);
3001         } else if (!strcasecmp(name, "dst")) {
3002                 ast_copy_string(workspace, cdr->dst, workspacelen);
3003         } else if (!strcasecmp(name, "dcontext")) {
3004                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3005         } else if (!strcasecmp(name, "channel")) {
3006                 ast_copy_string(workspace, cdr->channel, workspacelen);
3007         } else if (!strcasecmp(name, "dstchannel")) {
3008                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3009         } else if (!strcasecmp(name, "lastapp")) {
3010                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3011         } else if (!strcasecmp(name, "lastdata")) {
3012                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3013         } else if (!strcasecmp(name, "start")) {
3014                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3015         } else if (!strcasecmp(name, "answer")) {
3016                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3017         } else if (!strcasecmp(name, "end")) {
3018                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3019         } else if (!strcasecmp(name, "duration")) {
3020                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3021         } else if (!strcasecmp(name, "billsec")) {
3022                 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);
3023         } else if (!strcasecmp(name, "disposition")) {
3024                 if (raw) {
3025                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3026                 } else {
3027                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3028                 }
3029         } else if (!strcasecmp(name, "amaflags")) {
3030                 if (raw) {
3031                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3032                 } else {
3033                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3034                 }
3035         } else if (!strcasecmp(name, "accountcode")) {
3036                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3037         } else if (!strcasecmp(name, "peeraccount")) {
3038                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3039         } else if (!strcasecmp(name, "uniqueid")) {
3040                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3041         } else if (!strcasecmp(name, "linkedid")) {
3042                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3043         } else if (!strcasecmp(name, "userfield")) {
3044                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3045         } else if (!strcasecmp(name, "sequence")) {
3046                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3047         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3048                 ast_copy_string(workspace, varbuf, workspacelen);
3049         } else {
3050                 workspace[0] = '\0';
3051         }
3052
3053         if (!ast_strlen_zero(workspace)) {
3054                 *ret = workspace;
3055         }
3056 }
3057
3058 /*!
3059  * \internal
3060  * \brief Callback that finds all CDRs that reference a particular channel by name
3061  */
3062 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3063 {
3064         struct cdr_object *cdr = obj;
3065         const char *name = arg;
3066
3067         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
3068                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
3069                 return CMP_MATCH;
3070         }
3071         return 0;
3072 }
3073
3074 /*!
3075  * \internal
3076  * \brief Callback that finds a CDR by channel name
3077  */
3078 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3079 {
3080         struct cdr_object *cdr = obj;
3081         const char *name = arg;
3082
3083         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
3084                 return CMP_MATCH;
3085         }
3086         return 0;
3087 }
3088
3089 /* Read Only CDR variables */
3090 static const char * const cdr_readonly_vars[] = {
3091         "clid",
3092         "src",
3093         "dst",
3094         "dcontext",
3095         "channel",
3096         "dstchannel",
3097         "lastapp",
3098         "lastdata",
3099         "start",
3100         "answer",
3101         "end",
3102         "duration",
3103         "billsec",
3104         "disposition",
3105         "amaflags",
3106         "accountcode",
3107         "uniqueid",
3108         "linkedid",
3109         "userfield",
3110         "sequence",
3111         NULL
3112 };
3113
3114 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3115 {
3116         struct cdr_object *cdr;
3117         struct cdr_object *it_cdr;
3118         struct ao2_iterator *it_cdrs;
3119         char *arg = ast_strdupa(channel_name);
3120         int x;
3121
3122         for (x = 0; cdr_readonly_vars[x]; x++) {
3123                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3124                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3125                         return -1;
3126                 }
3127         }
3128
3129         it_cdrs = ao2_callback(active_cdrs_by_channel, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3130         if (!it_cdrs) {
3131                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3132                 return -1;
3133         }
3134
3135         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3136                 ao2_lock(cdr);
3137                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3138                         struct varshead *headp = NULL;
3139
3140                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3141                                 continue;
3142                         }
3143                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
3144                                 headp = &it_cdr->party_a.variables;
3145                         } else if (it_cdr->party_b.snapshot
3146                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
3147                                 headp = &it_cdr->party_b.variables;
3148                         }
3149                         if (headp) {
3150                                 set_variable(headp, name, value);
3151                         }
3152                 }
3153         }
3154         ao2_iterator_destroy(it_cdrs);
3155
3156         return 0;
3157 }
3158
3159 /*!
3160  * \brief Format a variable on a \ref cdr_object
3161  */
3162 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3163 {
3164         struct ast_var_t *variable;
3165
3166         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3167                 if (!strcasecmp(name, ast_var_name(variable))) {
3168                         ast_copy_string(value, ast_var_value(variable), length);
3169                         return;
3170                 }
3171         }
3172
3173         *value = '\0';
3174 }
3175
3176 /*!
3177  * \brief Format one of the standard properties on a \ref cdr_object
3178  */
3179 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3180 {
3181         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3182         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3183
3184         if (!strcasecmp(name, "clid")) {
3185                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3186         } else if (!strcasecmp(name, "src")) {
3187                 ast_copy_string(value, party_a->caller_number, length);
3188         } else if (!strcasecmp(name, "dst")) {
3189                 ast_copy_string(value, party_a->exten, length);
3190         } else if (!strcasecmp(name, "dcontext")) {
3191                 ast_copy_string(value, party_a->context, length);
3192         } else if (!strcasecmp(name, "channel")) {
3193                 ast_copy_string(value, party_a->name, length);
3194         } else if (!strcasecmp(name, "dstchannel")) {
3195                 if (party_b) {
3196                         ast_copy_string(value, party_b->name, length);
3197                 } else {
3198                         ast_copy_string(value, "", length);
3199                 }
3200         } else if (!strcasecmp(name, "lastapp")) {
3201                 ast_copy_string(value, party_a->appl, length);
3202         } else if (!strcasecmp(name, "lastdata")) {
3203                 ast_copy_string(value, party_a->data, length);
3204         } else if (!strcasecmp(name, "start")) {
3205                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3206         } else if (!strcasecmp(name, "answer")) {
3207                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3208         } else if (!strcasecmp(name, "end")) {
3209                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3210         } else if (!strcasecmp(name, "duration")) {
3211                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3212         } else if (!strcasecmp(name, "billsec")) {
3213                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3214         } else if (!strcasecmp(name, "disposition")) {
3215                 snprintf(value, length, "%u", cdr_obj->disposition);
3216         } else if (!strcasecmp(name, "amaflags")) {
3217                 snprintf(value, length, "%d", party_a->amaflags);
3218         } else if (!strcasecmp(name, "accountcode")) {
3219                 ast_copy_string(value, party_a->accountcode, length);
3220         } else if (!strcasecmp(name, "peeraccount")) {
3221                 if (party_b) {
3222                         ast_copy_string(value, party_b->accountcode, length);
3223                 } else {
3224                         ast_copy_string(value, "", length);
3225                 }
3226         } else if (!strcasecmp(name, "uniqueid")) {
3227                 ast_copy_string(value, party_a->uniqueid, length);
3228         } else if (!strcasecmp(name, "linkedid")) {
3229                 ast_copy_string(value, cdr_obj->linkedid, length);
3230         } else if (!strcasecmp(name, "userfield")) {
3231                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3232         } else if (!strcasecmp(name, "sequence")) {
3233                 snprintf(value, length, "%u", cdr_obj->sequence);
3234         } else {
3235                 return 1;
3236         }
3237
3238         return 0;
3239 }
3240
3241 /*! \internal
3242  * \brief Look up and retrieve a CDR object by channel name
3243  * \param name The name of the channel
3244  * \retval NULL on error
3245  * \retval The \ref cdr_object for the channel on success, with the reference
3246  *      count bumped by one.
3247  */
3248 static struct cdr_object *cdr_object_get_by_name(const char *name)
3249 {
3250         char *param;
3251
3252         if (ast_strlen_zero(name)) {
3253                 return NULL;
3254         }
3255
3256         param = ast_strdupa(name);
3257         return ao2_callback(active_cdrs_by_channel, 0, cdr_object_get_by_name_cb, param);
3258 }
3259
3260 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3261 {
3262         struct cdr_object *cdr;
3263         struct cdr_object *cdr_obj;
3264
3265         if (ast_strlen_zero(name)) {
3266                 return 1;
3267         }
3268
3269         cdr = cdr_object_get_by_name(channel_name);
3270         if (!cdr) {
3271                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3272                 return 1;
3273         }
3274
3275         ao2_lock(cdr);
3276
3277         cdr_obj = cdr->last;
3278         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3279                 /* Property failed; attempt variable */
3280                 cdr_object_format_var_internal(cdr_obj, name, value, length);
3281         }
3282
3283         ao2_unlock(cdr);
3284
3285         ao2_cleanup(cdr);
3286         return 0;
3287 }
3288
3289 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3290 {
3291         struct cdr_object *cdr;
3292         struct cdr_object *it_cdr;
3293         struct ast_var_t *variable;
3294         const char *var;
3295         char workspace[256];
3296         int total = 0, x = 0, i;
3297
3298         cdr = cdr_object_get_by_name(channel_name);
3299         if (!cdr) {
3300                 if (is_cdr_flag_set(CDR_ENABLED)) {
3301                         ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3302                 }
3303                 return 0;
3304         }
3305
3306         ast_str_reset(*buf);
3307
3308         ao2_lock(cdr);
3309         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3310                 if (++x > 1) {
3311                         ast_str_append(buf, 0, "\n");
3312                 }
3313
3314                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3315    &