cdr.c: Rename the Party A CDR container.
[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 master CDRs indexed by Party A channel uniqueid */
352 static struct ao2_container *active_cdrs_master;
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 master CDR container key */
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
801 /*!
802  * \internal
803  * \brief Hash function for master CDR container indexed by Party A uniqueid.
804  */
805 static int cdr_master_hash_fn(const void *obj, const int flags)
806 {
807         const struct cdr_object *cdr;
808         const char *key;
809
810         switch (flags & OBJ_SEARCH_MASK) {
811         case OBJ_SEARCH_KEY:
812                 key = obj;
813                 break;
814         case OBJ_SEARCH_OBJECT:
815                 cdr = obj;
816                 key = cdr->uniqueid;
817                 break;
818         default:
819                 ast_assert(0);
820                 return 0;
821         }
822         return ast_str_case_hash(key);
823 }
824
825 /*!
826  * \internal
827  * \brief Comparison function for master CDR container indexed by Party A uniqueid.
828  */
829 static int cdr_master_cmp_fn(void *obj, void *arg, int flags)
830 {
831     struct cdr_object *left = obj;
832     struct cdr_object *right = arg;
833     const char *right_key = arg;
834     int cmp;
835
836     switch (flags & OBJ_SEARCH_MASK) {
837     case OBJ_SEARCH_OBJECT:
838         right_key = right->uniqueid;
839         /* Fall through */
840     case OBJ_SEARCH_KEY:
841         cmp = strcmp(left->uniqueid, right_key);
842         break;
843     case OBJ_SEARCH_PARTIAL_KEY:
844         /*
845          * We could also use a partial key struct containing a length
846          * so strlen() does not get called for every comparison instead.
847          */
848         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
849         break;
850     default:
851         /* Sort can only work on something with a full or partial key. */
852         ast_assert(0);
853         cmp = 0;
854         break;
855     }
856     return cmp ? 0 : CMP_MATCH;
857 }
858
859 /*!
860  * \internal
861  * \brief Hash function for all CDR container indexed by Party B channel name.
862  */
863 static int cdr_all_hash_fn(const void *obj, const int flags)
864 {
865         const struct cdr_object *cdr;
866         const char *key;
867
868         switch (flags & OBJ_SEARCH_MASK) {
869         case OBJ_SEARCH_KEY:
870                 key = obj;
871                 break;
872         case OBJ_SEARCH_OBJECT:
873                 cdr = obj;
874                 key = cdr->party_b_name;
875                 break;
876         default:
877                 ast_assert(0);
878                 return 0;
879         }
880         return ast_str_case_hash(key);
881 }
882
883 /*!
884  * \internal
885  * \brief Comparison function for all CDR container indexed by Party B channel name.
886  */
887 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
888 {
889     struct cdr_object *left = obj;
890     struct cdr_object *right = arg;
891     const char *right_key = arg;
892     int cmp;
893
894     switch (flags & OBJ_SEARCH_MASK) {
895     case OBJ_SEARCH_OBJECT:
896         right_key = right->party_b_name;
897         /* Fall through */
898     case OBJ_SEARCH_KEY:
899         cmp = strcasecmp(left->party_b_name, right_key);
900         break;
901     case OBJ_SEARCH_PARTIAL_KEY:
902         /*
903          * We could also use a partial key struct containing a length
904          * so strlen() does not get called for every comparison instead.
905          */
906         cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
907         break;
908     default:
909         /* Sort can only work on something with a full or partial key. */
910         ast_assert(0);
911         cmp = 0;
912         break;
913     }
914     return cmp ? 0 : CMP_MATCH;
915 }
916
917 /*!
918  * \internal
919  * \brief Relink the CDR because Party B's snapshot changed.
920  * \since 13.19.0
921  *
922  * \return Nothing
923  */
924 static void cdr_all_relink(struct cdr_object *cdr)
925 {
926         ao2_lock(active_cdrs_all);
927         if (cdr->party_b.snapshot) {
928                 if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->name)) {
929                         ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
930                         ast_string_field_set(cdr, party_b_name, cdr->party_b.snapshot->name);
931                         ao2_link_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
932                 }
933         } else {
934                 ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
935                 ast_string_field_set(cdr, party_b_name, "");
936         }
937         ao2_unlock(active_cdrs_all);
938 }
939
940 /*!
941  * \internal
942  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
943  * \since 13.19.0
944  *
945  * \return Nothing
946  */
947 static void cdr_all_unlink(struct cdr_object *cdr)
948 {
949         struct cdr_object *cur;
950         struct cdr_object *next;
951
952         ast_assert(cdr->is_root);
953
954         ao2_lock(active_cdrs_all);
955         for (cur = cdr->next; cur; cur = next) {
956                 next = cur->next;
957                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
958                 ast_string_field_set(cur, party_b_name, "");
959         }
960         ao2_unlock(active_cdrs_all);
961 }
962
963 /*!
964  * \brief \ref cdr_object Destructor
965  */
966 static void cdr_object_dtor(void *obj)
967 {
968         struct cdr_object *cdr = obj;
969         struct ast_var_t *it_var;
970
971         ao2_cleanup(cdr->party_a.snapshot);
972         ao2_cleanup(cdr->party_b.snapshot);
973         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
974                 ast_var_delete(it_var);
975         }
976         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
977                 ast_var_delete(it_var);
978         }
979         ast_string_field_free_memory(cdr);
980
981         /* CDR destruction used to work by calling ao2_cleanup(next) and
982          * allowing the chain to destroy itself neatly. Unfortunately, for
983          * really long chains, this can result in a stack overflow. So now
984          * when the root CDR is destroyed, it is responsible for unreffing
985          * all CDRs in the chain
986          */
987         if (cdr->is_root) {
988                 struct cdr_object *curr = cdr->next;
989                 struct cdr_object *next;
990
991                 while (curr) {
992                         next = curr->next;
993                         ao2_cleanup(curr);
994                         curr = next;
995                 }
996         }
997 }
998
999 /*!
1000  * \brief \ref cdr_object constructor
1001  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1002  *
1003  * This implicitly sets the state of the newly created CDR to the Single state
1004  * (\ref single_state_fn_table)
1005  */
1006 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
1007 {
1008         struct cdr_object *cdr;
1009
1010         ast_assert(chan != NULL);
1011
1012         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1013         if (!cdr) {
1014                 return NULL;
1015         }
1016         cdr->last = cdr;
1017         if (ast_string_field_init(cdr, 64)) {
1018                 ao2_cleanup(cdr);
1019                 return NULL;
1020         }
1021         ast_string_field_set(cdr, uniqueid, chan->uniqueid);
1022         ast_string_field_set(cdr, name, chan->name);
1023         ast_string_field_set(cdr, linkedid, chan->linkedid);
1024         cdr->disposition = AST_CDR_NULL;
1025         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1026
1027         cdr->party_a.snapshot = chan;
1028         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1029
1030         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->name);
1031
1032         cdr_object_transition_state(cdr, &single_state_fn_table);
1033
1034         return cdr;
1035 }
1036
1037 /*!
1038  * \brief Create a new \ref cdr_object and append it to an existing chain
1039  * \param cdr The \ref cdr_object to append to
1040  */
1041 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
1042 {
1043         struct cdr_object *new_cdr;
1044         struct cdr_object *it_cdr;
1045         struct cdr_object *cdr_last;
1046
1047         cdr_last = cdr->last;
1048         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
1049         if (!new_cdr) {
1050                 return NULL;
1051         }
1052         new_cdr->disposition = AST_CDR_NULL;
1053
1054         /* Copy over the linkedid, as it may have changed */
1055         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1056         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1057         ast_string_field_set(new_cdr, data, cdr_last->data);
1058         ast_string_field_set(new_cdr, context, cdr_last->context);
1059         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1060
1061         /*
1062          * If the current CDR says to disable all future ones,
1063          * keep the disable chain going
1064          */
1065         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1066                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1067         }
1068
1069         /* Copy over other Party A information */
1070         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1071
1072         /* Append the CDR to the end of the list */
1073         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1074                 it_cdr->last = new_cdr;
1075         }
1076         it_cdr->last = new_cdr;
1077         it_cdr->next = new_cdr;
1078
1079         return new_cdr;
1080 }
1081
1082 /*!
1083  * \internal
1084  * \brief Determine if CDR flag is configured.
1085  *
1086  * \param cdr_flag The configured CDR flag to check.
1087  *
1088  * \retval 0 if the CDR flag is not configured.
1089  * \retval non-zero if the CDR flag is configured.
1090  *
1091  * \return Nothing
1092  */
1093 static int is_cdr_flag_set(unsigned int cdr_flag)
1094 {
1095         struct module_config *mod_cfg;
1096         int flag_set;
1097
1098         mod_cfg = ao2_global_obj_ref(module_configs);
1099         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1100         ao2_cleanup(mod_cfg);
1101         return flag_set;
1102 }
1103
1104 /*!
1105  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1106  * to endbeforehexten logic
1107  *
1108  * \param old_snapshot The previous state
1109  * \param new_snapshot The new state
1110  *
1111  * \retval 0 if the state has not changed
1112  * \retval 1 if the state changed
1113  */
1114 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1115         struct ast_channel_snapshot *new_snapshot)
1116 {
1117         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1118         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1119                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1120                 return 0;
1121         }
1122
1123         /* When Party A is originated to an application and the application exits, the stack
1124          * will attempt to clear the application and restore the dummy originate application
1125          * of "AppDialX". Ignore application changes to AppDialX as a result.
1126          */
1127         if (strcmp(new_snapshot->appl, old_snapshot->appl)
1128                 && strncasecmp(new_snapshot->appl, "appdial", 7)
1129                 && (strcmp(new_snapshot->context, old_snapshot->context)
1130                         || strcmp(new_snapshot->exten, old_snapshot->exten)
1131                         || new_snapshot->priority != old_snapshot->priority)) {
1132                 return 1;
1133         }
1134
1135         return 0;
1136 }
1137
1138 /*!
1139  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1140  * that was created as the result of a dial operation
1141  *
1142  * \retval 0 the channel was not created as the result of a dial
1143  * \retval 1 the channel was created as the result of a dial
1144  */
1145 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1146 {
1147         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1148                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1149 }
1150
1151 /*!
1152  * \brief Given two CDR snapshots, figure out who should be Party A for the
1153  * resulting CDR
1154  * \param left One of the snapshots
1155  * \param right The other snapshot
1156  * \retval The snapshot that won
1157  */
1158 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1159 {
1160         /* Check whether or not the party is dialed. A dialed party is never the
1161          * Party A with a party that was not dialed.
1162          */
1163         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1164                 return left;
1165         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1166                 return right;
1167         }
1168
1169         /* Try the Party A flag */
1170         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1171                 return left;
1172         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1173                 return right;
1174         }
1175
1176         /* Neither party is dialed and neither has the Party A flag - defer to
1177          * creation time */
1178         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1179                 return left;
1180         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1181                 return right;
1182         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1183                 return right;
1184         } else {
1185                 /* Okay, fine, take the left one */
1186                 return left;
1187         }
1188 }
1189
1190 /*!
1191  * Compute the duration for a \ref cdr_object
1192  */
1193 static long cdr_object_get_duration(struct cdr_object *cdr)
1194 {
1195         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1196 }
1197
1198 /*!
1199  * \brief Compute the billsec for a \ref cdr_object
1200  */
1201 static long cdr_object_get_billsec(struct cdr_object *cdr)
1202 {
1203         long int ms;
1204
1205         if (ast_tvzero(cdr->answer)) {
1206                 return 0;
1207         }
1208
1209         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1210         if (ms % 1000 >= 500
1211                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1212                 ms = (ms / 1000) + 1;
1213         } else {
1214                 ms = ms / 1000;
1215         }
1216
1217         return ms;
1218 }
1219
1220 /*!
1221  * \internal
1222  * \brief Set a variable on a CDR object
1223  *
1224  * \param headp The header pointer to the variable to set
1225  * \param name The name of the variable
1226  * \param value The value of the variable
1227  */
1228 static void set_variable(struct varshead *headp, const char *name, const char *value)
1229 {
1230         struct ast_var_t *newvariable;
1231
1232         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1233                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1234                         AST_LIST_REMOVE_CURRENT(entries);
1235                         ast_var_delete(newvariable);
1236                         break;
1237                 }
1238         }
1239         AST_LIST_TRAVERSE_SAFE_END;
1240
1241         if (value && (newvariable = ast_var_assign(name, value))) {
1242                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1243         }
1244 }
1245
1246 /*!
1247  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1248  * suitable for consumption by the registered CDR backends
1249  * \param cdr The \ref cdr_object to convert to a public record
1250  * \retval A chain of \ref ast_cdr objects on success
1251  * \retval NULL on failure
1252  */
1253 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1254 {
1255         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1256         struct cdr_object *it_cdr;
1257         struct ast_var_t *it_var, *it_copy_var;
1258         struct ast_channel_snapshot *party_a;
1259         struct ast_channel_snapshot *party_b;
1260
1261         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1262                 struct ast_cdr *cdr_copy;
1263
1264                 /* Don't create records for CDRs where the party A was a dialed channel */
1265                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1266                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1267                                 it_cdr->party_a.snapshot->name);
1268                         continue;
1269                 }
1270
1271                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1272                 if (!cdr_copy) {
1273                         ast_free(pub_cdr);
1274                         return NULL;
1275                 }
1276
1277                 party_a = it_cdr->party_a.snapshot;
1278                 party_b = it_cdr->party_b.snapshot;
1279
1280                 /* Party A */
1281                 ast_assert(party_a != NULL);
1282                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1283                 cdr_copy->amaflags = party_a->amaflags;
1284                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1285                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1286                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1287                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1288                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1289                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1290                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1291                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1292
1293                 /* Party B */
1294                 if (party_b) {
1295                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1296                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1297                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1298                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1299                         }
1300                 }
1301                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1302                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1303                 }
1304
1305                 /* Timestamps/durations */
1306                 cdr_copy->start = it_cdr->start;
1307                 cdr_copy->answer = it_cdr->answer;
1308                 cdr_copy->end = it_cdr->end;
1309                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1310                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1311
1312                 /* Flags and IDs */
1313                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1314                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1315                 cdr_copy->disposition = it_cdr->disposition;
1316                 cdr_copy->sequence = it_cdr->sequence;
1317
1318                 /* Variables */
1319                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1320                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1321                         int found = 0;
1322                         struct ast_var_t *newvariable;
1323                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1324                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1325                                         found = 1;
1326                                         break;
1327                                 }
1328                         }
1329                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1330                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1331                         }
1332                 }
1333
1334                 if (!pub_cdr) {
1335                         pub_cdr = cdr_copy;
1336                         cdr_prev = pub_cdr;
1337                 } else {
1338                         cdr_prev->next = cdr_copy;
1339                         cdr_prev = cdr_copy;
1340                 }
1341         }
1342
1343         return pub_cdr;
1344 }
1345
1346 /*!
1347  * \brief Dispatch a CDR.
1348  * \param cdr The \ref cdr_object to dispatch
1349  *
1350  * This will create a \ref ast_cdr object and publish it to the various backends
1351  */
1352 static void cdr_object_dispatch(struct cdr_object *cdr)
1353 {
1354         struct ast_cdr *pub_cdr;
1355
1356         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1357                 cdr->party_a.snapshot->name,
1358                 cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1359         pub_cdr = cdr_object_create_public_records(cdr);
1360         cdr_detach(pub_cdr);
1361 }
1362
1363 /*!
1364  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1365  * \param cdr The \ref cdr_object
1366  * \param hangupcause The Asterisk hangup cause code
1367  */
1368 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1369 {
1370         /* Change the disposition based on the hang up cause */
1371         switch (hangupcause) {
1372         case AST_CAUSE_BUSY:
1373                 cdr->disposition = AST_CDR_BUSY;
1374                 break;
1375         case AST_CAUSE_CONGESTION:
1376                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1377                         cdr->disposition = AST_CDR_FAILED;
1378                 } else {
1379                         cdr->disposition = AST_CDR_CONGESTION;
1380                 }
1381                 break;
1382         case AST_CAUSE_NO_ROUTE_DESTINATION:
1383         case AST_CAUSE_UNREGISTERED:
1384                 cdr->disposition = AST_CDR_FAILED;
1385                 break;
1386         case AST_CAUSE_NORMAL_CLEARING:
1387         case AST_CAUSE_NO_ANSWER:
1388                 cdr->disposition = AST_CDR_NOANSWER;
1389                 break;
1390         default:
1391                 break;
1392         }
1393 }
1394
1395 /*!
1396  * \brief Finalize a CDR.
1397  *
1398  * This function is safe to call multiple times. Note that you can call this
1399  * explicitly before going to the finalized state if there's a chance the CDR
1400  * will be re-activated, in which case the \ref cdr_object's end time should be
1401  * cleared. This function is implicitly called when a CDR transitions to the
1402  * finalized state and right before it is dispatched
1403  *
1404  * \param cdr_object The CDR to finalize
1405  */
1406 static void cdr_object_finalize(struct cdr_object *cdr)
1407 {
1408         if (!ast_tvzero(cdr->end)) {
1409                 return;
1410         }
1411         cdr->end = ast_tvnow();
1412
1413         if (cdr->disposition == AST_CDR_NULL) {
1414                 if (!ast_tvzero(cdr->answer)) {
1415                         cdr->disposition = AST_CDR_ANSWERED;
1416                 } else if (cdr->party_a.snapshot->hangupcause) {
1417                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1418                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1419                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1420                 } else {
1421                         cdr->disposition = AST_CDR_FAILED;
1422                 }
1423         }
1424
1425         /* tv_usec is suseconds_t, which could be int or long */
1426         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1427                         cdr->party_a.snapshot->name,
1428                         (long)cdr->start.tv_sec,
1429                         (long)cdr->start.tv_usec,
1430                         (long)cdr->answer.tv_sec,
1431                         (long)cdr->answer.tv_usec,
1432                         (long)cdr->end.tv_sec,
1433                         (long)cdr->end.tv_usec,
1434                         ast_cdr_disp2str(cdr->disposition));
1435 }
1436
1437 /*!
1438  * \brief Check to see if a CDR needs to move to the finalized state because
1439  * its Party A hungup.
1440  */
1441 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1442 {
1443         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1444                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1445                 cdr_object_finalize(cdr);
1446         }
1447
1448         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1449                 && cdr->fn_table != &finalized_state_fn_table) {
1450                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1451         }
1452 }
1453
1454 /*!
1455  * \brief Check to see if a CDR needs to be answered based on its Party A.
1456  * Note that this is safe to call as much as you want - we won't answer twice
1457  */
1458 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1459 {
1460         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1461                 cdr->answer = ast_tvnow();
1462                 /* tv_usec is suseconds_t, which could be int or long */
1463                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1464                         (long)cdr->answer.tv_sec,
1465                         (long)cdr->answer.tv_usec);
1466         }
1467 }
1468
1469 /* \brief Set Caller ID information on a CDR */
1470 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1471 {
1472         if (!old_snapshot->snapshot) {
1473                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1474                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1475                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1476                 return;
1477         }
1478         if (strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1479                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1480         }
1481         if (strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1482                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1483         }
1484         if (strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1485                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1486         }
1487 }
1488
1489 /*!
1490  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1491  * a new \ref ast_channel_snapshot
1492  * \param old_snapshot The old \ref cdr_object_snapshot
1493  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1494  */
1495 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1496                 struct ast_channel_snapshot *new_snapshot)
1497 {
1498         cdr_object_update_cid(old_snapshot, new_snapshot);
1499         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1500 }
1501
1502 /* BASE METHOD IMPLEMENTATIONS */
1503
1504 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1505 {
1506         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1507
1508         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1509         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1510                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1511                 cdr_object_finalize(cdr);
1512                 return 0;
1513         }
1514
1515         /*
1516          * Only record the context and extension if we aren't in a subroutine, or if
1517          * we are executing hangup logic.
1518          */
1519         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1520                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1521                 if (strcmp(cdr->context, snapshot->context)) {
1522                         ast_string_field_set(cdr, context, snapshot->context);
1523                 }
1524                 if (strcmp(cdr->exten, snapshot->exten)) {
1525                         ast_string_field_set(cdr, exten, snapshot->exten);
1526                 }
1527         }
1528
1529         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1530
1531         /* When Party A is originated to an application and the application exits, the stack
1532          * will attempt to clear the application and restore the dummy originate application
1533          * of "AppDialX". Prevent that, and any other application changes we might not want
1534          * here.
1535          */
1536         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1537                 && !ast_strlen_zero(snapshot->appl)
1538                 && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1539                 if (strcmp(cdr->appl, snapshot->appl)) {
1540                         ast_string_field_set(cdr, appl, snapshot->appl);
1541                 }
1542                 if (strcmp(cdr->data, snapshot->data)) {
1543                         ast_string_field_set(cdr, data, snapshot->data);
1544                 }
1545
1546                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1547                  * execute before the dial begins, will alter the application/data to
1548                  * something people typically don't want to see, if we see a channel enter
1549                  * into Dial here, we set the appl/data accordingly and lock it.
1550                  */
1551                 if (!strcmp(snapshot->appl, "Dial")) {
1552                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1553                 }
1554         }
1555
1556         if (strcmp(cdr->linkedid, snapshot->linkedid)) {
1557                 ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1558         }
1559         cdr_object_check_party_a_answer(cdr);
1560         cdr_object_check_party_a_hangup(cdr);
1561
1562         return 0;
1563 }
1564
1565 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1566 {
1567         return 0;
1568 }
1569
1570 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1571 {
1572         return 0;
1573 }
1574
1575 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1576 {
1577         /* Base process bridge enter simply indicates that we can't handle it */
1578         return BRIDGE_ENTER_NEED_CDR;
1579 }
1580
1581 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1582 {
1583         char park_info[128];
1584
1585         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1586
1587         /* Update Party A information regardless */
1588         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1589
1590         /* Fake out where we're parked */
1591         ast_string_field_set(cdr, appl, "Park");
1592         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1593         ast_string_field_set(cdr, data, park_info);
1594
1595         /* Prevent any further changes to the App/Data fields for this record */
1596         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1597
1598         return 0;
1599 }
1600
1601 /* SINGLE STATE */
1602
1603 static void single_state_init_function(struct cdr_object *cdr)
1604 {
1605         cdr->start = ast_tvnow();
1606         cdr_object_check_party_a_answer(cdr);
1607 }
1608
1609 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1610 {
1611         /* This should never happen! */
1612         ast_assert(cdr->party_b.snapshot == NULL);
1613         ast_assert(0);
1614         return;
1615 }
1616
1617 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1618 {
1619         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1620                 base_process_party_a(cdr, caller);
1621                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1622                         cdr->party_a.snapshot->name);
1623                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1624                 cdr_all_relink(cdr);
1625                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1626                         cdr->party_b.snapshot->name);
1627
1628                 /* If we have two parties, lock the application that caused the
1629                  * two parties to be associated. This prevents mid-call event
1630                  * macros/gosubs from perturbing the CDR application/data
1631                  */
1632                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1633         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1634                 /* We're the entity being dialed, i.e., outbound origination */
1635                 base_process_party_a(cdr, peer);
1636                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1637                         cdr->party_a.snapshot->name);
1638         }
1639
1640         cdr_object_transition_state(cdr, &dial_state_fn_table);
1641         return 0;
1642 }
1643
1644 /*!
1645  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1646  * already in the bridge while in the Single state. The goal of this is to find
1647  * a Party B for our CDR.
1648  *
1649  * \param cdr Our \ref cdr_object in the Single state
1650  * \param cand_cdr The \ref cdr_object already in the Bridge state
1651  *
1652  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1653  * Party B
1654  * \retval 1 No party in the cand_cdr could be used as our Party B
1655  */
1656 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1657                 struct cdr_object *cand_cdr)
1658 {
1659         struct cdr_object_snapshot *party_a;
1660
1661         /* Don't match on ourselves */
1662         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1663                 return 1;
1664         }
1665
1666         /* Try the candidate CDR's Party A first */
1667         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1668         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1669                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1670                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1671                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1672                 cdr_all_relink(cdr);
1673                 if (!cand_cdr->party_b.snapshot) {
1674                         /* We just stole them - finalize their CDR. Note that this won't
1675                          * transition their state, it just sets the end time and the
1676                          * disposition - if we need to re-activate them later, we can.
1677                          */
1678                         cdr_object_finalize(cand_cdr);
1679                 }
1680                 return 0;
1681         }
1682
1683         /* Try their Party B, unless it's us */
1684         if (!cand_cdr->party_b.snapshot
1685                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1686                 return 1;
1687         }
1688         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1689         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1690                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1691                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1692                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1693                 cdr_all_relink(cdr);
1694                 return 0;
1695         }
1696
1697         return 1;
1698 }
1699
1700 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)
1701 {
1702         struct ao2_iterator it_cdrs;
1703         char *channel_id;
1704         int success = 0;
1705
1706         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1707
1708         if (ao2_container_count(bridge->channels) == 1) {
1709                 /* No one in the bridge yet but us! */
1710                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1711                 return BRIDGE_ENTER_ONLY_PARTY;
1712         }
1713
1714         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1715                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1716                 ao2_ref(channel_id, -1)) {
1717                 struct cdr_object *cand_cdr_master;
1718                 struct cdr_object *cand_cdr;
1719
1720                 cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1721                 if (!cand_cdr_master) {
1722                         continue;
1723                 }
1724
1725                 ao2_lock(cand_cdr_master);
1726                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1727                         /* Skip any records that are not in a bridge or in this bridge.
1728                          * I'm not sure how that would happen, but it pays to be careful. */
1729                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1730                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1731                                 continue;
1732                         }
1733
1734                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1735                                 continue;
1736                         }
1737                         /* We successfully got a party B - break out */
1738                         success = 1;
1739                         break;
1740                 }
1741                 ao2_unlock(cand_cdr_master);
1742                 ao2_cleanup(cand_cdr_master);
1743         }
1744         ao2_iterator_destroy(&it_cdrs);
1745
1746         /* We always transition state, even if we didn't get a peer */
1747         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1748
1749         /* Success implies that we have a Party B */
1750         if (success) {
1751                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1752         }
1753
1754         return BRIDGE_ENTER_NO_PARTY_B;
1755 }
1756
1757 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1758 {
1759         cdr_object_transition_state(cdr, &parked_state_fn_table);
1760         return 0;
1761 }
1762
1763
1764 /* DIAL STATE */
1765
1766 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1767 {
1768         ast_assert(snapshot != NULL);
1769         ast_assert(cdr->party_b.snapshot
1770                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1771
1772         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1773
1774         /* If party B hangs up, finalize this CDR */
1775         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1776                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1777         }
1778 }
1779
1780 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1781 {
1782         /* Don't process a begin dial here. A party A already in the dial state will
1783          * who receives a dial begin for something else will be handled by the
1784          * message router callback and will add a new CDR for the party A */
1785         return 1;
1786 }
1787
1788 /*!
1789  * \internal
1790  * \brief Convert a dial status to a CDR disposition
1791  */
1792 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1793 {
1794         if (!strcmp(dial_status, "ANSWER")) {
1795                 return AST_CDR_ANSWERED;
1796         } else if (!strcmp(dial_status, "BUSY")) {
1797                 return AST_CDR_BUSY;
1798         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1799                 return AST_CDR_NOANSWER;
1800         } else if (!strcmp(dial_status, "CONGESTION")) {
1801                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1802                         return AST_CDR_FAILED;
1803                 } else {
1804                         return AST_CDR_CONGESTION;
1805                 }
1806         } else if (!strcmp(dial_status, "FAILED")) {
1807                 return AST_CDR_FAILED;
1808         }
1809         return AST_CDR_FAILED;
1810 }
1811
1812 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)
1813 {
1814         struct ast_channel_snapshot *party_a;
1815
1816         if (caller) {
1817                 party_a = caller;
1818         } else {
1819                 party_a = peer;
1820         }
1821         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1822         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1823
1824         if (cdr->party_b.snapshot) {
1825                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1826                         /* Not the status for this CDR - defer back to the message router */
1827                         return 1;
1828                 }
1829                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1830         }
1831
1832         /* Set the disposition based on the dial string. */
1833         cdr->disposition = dial_status_to_disposition(dial_status);
1834         if (cdr->disposition == AST_CDR_ANSWERED) {
1835                 /* Switch to dial pending to wait and see what the caller does */
1836                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1837         } else {
1838                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1839         }
1840
1841         return 0;
1842 }
1843
1844 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)
1845 {
1846         int success = 0;
1847
1848         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1849
1850         /* Get parties in the bridge */
1851         if (ao2_container_count(bridge->channels) == 1) {
1852                 /* No one in the bridge yet but us! */
1853                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1854                 return BRIDGE_ENTER_ONLY_PARTY;
1855         }
1856
1857         /* If we don't have a Party B (originated channel), skip it */
1858         if (cdr->party_b.snapshot) {
1859                 struct ao2_iterator it_cdrs;
1860                 char *channel_id;
1861
1862                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1863                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1864                         ao2_ref(channel_id, -1)) {
1865                         struct cdr_object *cand_cdr_master;
1866                         struct cdr_object *cand_cdr;
1867
1868                         cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1869                         if (!cand_cdr_master) {
1870                                 continue;
1871                         }
1872
1873                         ao2_lock(cand_cdr_master);
1874                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1875                                 /* Skip any records that are not in a bridge or in this bridge.
1876                                  * I'm not sure how that would happen, but it pays to be careful. */
1877                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1878                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1879                                         continue;
1880                                 }
1881
1882                                 /* Skip any records that aren't our Party B */
1883                                 if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1884                                         continue;
1885                                 }
1886                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1887                                 /* If they have a Party B, they joined up with someone else as their
1888                                  * Party A. Don't finalize them as they're active. Otherwise, we
1889                                  * have stolen them so they need to be finalized.
1890                                  */
1891                                 if (!cand_cdr->party_b.snapshot) {
1892                                         cdr_object_finalize(cand_cdr);
1893                                 }
1894                                 success = 1;
1895                                 break;
1896                         }
1897                         ao2_unlock(cand_cdr_master);
1898                         ao2_cleanup(cand_cdr_master);
1899                 }
1900                 ao2_iterator_destroy(&it_cdrs);
1901         }
1902
1903         /* We always transition state, even if we didn't get a peer */
1904         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1905
1906         /* Success implies that we have a Party B */
1907         if (success) {
1908                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1909         }
1910         return BRIDGE_ENTER_NO_PARTY_B;
1911 }
1912
1913 /* DIALED PENDING STATE */
1914
1915 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1916 {
1917         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1918          * that means we need a new CDR; otherwise, switch us over to single.
1919          */
1920         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1921                 if (cdr->party_b.snapshot) {
1922                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1923                         cdr->fn_table->process_party_a(cdr, snapshot);
1924                         return 1;
1925                 } else {
1926                         cdr_object_transition_state(cdr, &single_state_fn_table);
1927                         cdr->fn_table->process_party_a(cdr, snapshot);
1928                         return 0;
1929                 }
1930         }
1931         base_process_party_a(cdr, snapshot);
1932         return 0;
1933 }
1934
1935 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)
1936 {
1937         cdr_object_transition_state(cdr, &dial_state_fn_table);
1938         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1939 }
1940
1941 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1942 {
1943         if (cdr->party_b.snapshot) {
1944                 /* We can't handle this as we have a Party B - ask for a new one */
1945                 return 1;
1946         }
1947         cdr_object_transition_state(cdr, &parked_state_fn_table);
1948         return 0;
1949 }
1950
1951 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1952 {
1953         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1954
1955         /* Ask for a new CDR */
1956         return 1;
1957 }
1958
1959 /* BRIDGE STATE */
1960
1961 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1962 {
1963         ast_assert(cdr->party_b.snapshot
1964                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1965
1966         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1967
1968         /* If party B hangs up, finalize this CDR */
1969         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1970                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1971         }
1972 }
1973
1974 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1975 {
1976         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1977                 return 1;
1978         }
1979         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
1980                 && cdr->party_b.snapshot
1981                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
1982                 return 1;
1983         }
1984         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1985
1986         return 0;
1987 }
1988
1989 /* PARKED STATE */
1990
1991 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1992 {
1993         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
1994                 return 1;
1995         }
1996         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1997
1998         return 0;
1999 }
2000
2001 /* FINALIZED STATE */
2002
2003 static void finalized_state_init_function(struct cdr_object *cdr)
2004 {
2005         cdr_object_finalize(cdr);
2006 }
2007
2008 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2009 {
2010         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2011                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2012                 return 0;
2013         }
2014
2015         /* Indicate that, if possible, we should get a new CDR */
2016         return 1;
2017 }
2018
2019 /*!
2020  * \internal
2021  * \brief Filter channel snapshots by technology
2022  */
2023 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2024 {
2025         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
2026 }
2027
2028 /*!
2029  * \internal
2030  * \brief Filter a channel cache update
2031  */
2032 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
2033                 struct ast_channel_snapshot *new_snapshot)
2034 {
2035         int ret = 0;
2036
2037         /* Drop cache updates from certain channel technologies */
2038         if (old_snapshot) {
2039                 ret |= filter_channel_snapshot(old_snapshot);
2040         }
2041         if (new_snapshot) {
2042                 ret |= filter_channel_snapshot(new_snapshot);
2043         }
2044
2045         return ret;
2046 }
2047
2048 static int dial_status_end(const char *dialstatus)
2049 {
2050         return (strcmp(dialstatus, "RINGING") &&
2051                         strcmp(dialstatus, "PROCEEDING") &&
2052                         strcmp(dialstatus, "PROGRESS"));
2053 }
2054
2055 /* TOPIC ROUTER CALLBACKS */
2056
2057 /*!
2058  * \brief Handler for Stasis-Core dial messages
2059  * \param data Passed on
2060  * \param sub The stasis subscription for this message callback
2061  * \param topic The topic this message was published for
2062  * \param message The message
2063  */
2064 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2065 {
2066         struct cdr_object *cdr;
2067         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2068         struct ast_channel_snapshot *caller;
2069         struct ast_channel_snapshot *peer;
2070         struct cdr_object *it_cdr;
2071         struct ast_json *dial_status_blob;
2072         const char *dial_status = NULL;
2073         int res = 1;
2074
2075         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2076         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2077         if (!peer && !caller) {
2078                 return;
2079         }
2080         if (filter_channel_snapshot(peer) || (caller && filter_channel_snapshot(caller))) {
2081                 return;
2082         }
2083
2084         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2085         if (dial_status_blob) {
2086                 dial_status = ast_json_string_get(dial_status_blob);
2087         }
2088
2089         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2090                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2091                 caller ? caller->name : "(none)",
2092                 peer ? peer->name : "(none)",
2093                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2094                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2095
2096         /* Figure out who is running this show */
2097         if (caller) {
2098                 cdr = ao2_find(active_cdrs_master, caller->uniqueid, OBJ_SEARCH_KEY);
2099         } else {
2100                 cdr = ao2_find(active_cdrs_master, peer->uniqueid, OBJ_SEARCH_KEY);
2101         }
2102         if (!cdr) {
2103                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
2104                 ast_assert(0);
2105                 return;
2106         }
2107
2108         ao2_lock(cdr);
2109         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2110                 if (ast_strlen_zero(dial_status)) {
2111                         if (!it_cdr->fn_table->process_dial_begin) {
2112                                 continue;
2113                         }
2114                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2115                                 it_cdr,
2116                                 caller ? caller->name : "(none)",
2117                                 peer ? peer->name : "(none)");
2118                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2119                                         caller,
2120                                         peer);
2121                 } else if (dial_status_end(dial_status)) {
2122                         if (!it_cdr->fn_table->process_dial_end) {
2123                                 continue;
2124                         }
2125                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2126                                 it_cdr,
2127                                 caller ? caller->name : "(none)",
2128                                 peer ? peer->name : "(none)");
2129                         it_cdr->fn_table->process_dial_end(it_cdr,
2130                                         caller,
2131                                         peer,
2132                                         dial_status);
2133                 }
2134         }
2135
2136         /* If no CDR handled a dial begin message, make a new one */
2137         if (res && ast_strlen_zero(dial_status)) {
2138                 struct cdr_object *new_cdr;
2139
2140                 new_cdr = cdr_object_create_and_append(cdr);
2141                 if (new_cdr) {
2142                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2143                 }
2144         }
2145         ao2_unlock(cdr);
2146         ao2_cleanup(cdr);
2147 }
2148
2149 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2150 {
2151         struct cdr_object *cdr = obj;
2152
2153         if (!strcasecmp(cdr->party_b_name, arg)) {
2154 #ifdef AST_DEVMODE
2155                 struct ast_channel_snapshot *party_b = data;
2156
2157                 /*
2158                  * For sanity's sake we also assert the party_b snapshot
2159                  * is consistent with the key.
2160                  */
2161                 ast_assert(cdr->party_b.snapshot
2162                         && !strcasecmp(cdr->party_b.snapshot->name, party_b->name));
2163 #endif
2164
2165                 /* Don't transition to the finalized state - let the Party A do
2166                  * that when its ready
2167                  */
2168                 cdr_object_finalize(cdr);
2169         }
2170         return 0;
2171 }
2172
2173 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2174 {
2175         struct cdr_object *cdr = obj;
2176
2177         if (cdr->fn_table->process_party_b
2178                 && !strcasecmp(cdr->party_b_name, arg)) {
2179                 struct ast_channel_snapshot *party_b = data;
2180
2181                 /*
2182                  * For sanity's sake we also check the party_b snapshot
2183                  * for consistency with the key.  The callback needs and
2184                  * asserts the snapshot to be this way.
2185                  */
2186                 if (!cdr->party_b.snapshot
2187                         || strcasecmp(cdr->party_b.snapshot->name, party_b->name)) {
2188                         ast_log(LOG_NOTICE,
2189                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2190                                 cdr->linkedid,
2191                                 cdr->party_a.snapshot->name,
2192                                 cdr->party_b_name);
2193                         return 0;
2194                 }
2195
2196                 cdr->fn_table->process_party_b(cdr, party_b);
2197         }
2198         return 0;
2199 }
2200
2201 /*! \brief Determine if we need to add a new CDR based on snapshots */
2202 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2203                 struct ast_channel_snapshot *new_snapshot)
2204 {
2205         /* If we're dead, we don't need a new CDR */
2206         if (!new_snapshot
2207                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2208                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2209                 return 0;
2210         }
2211
2212         /* Auto-fall through will increment the priority but have no application */
2213         if (ast_strlen_zero(new_snapshot->appl)) {
2214                 return 0;
2215         }
2216
2217         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2218                 return 0;
2219         }
2220
2221         return 1;
2222 }
2223
2224 /*!
2225  * \brief Handler for Stasis-Core channel cache update messages
2226  * \param data Passed on
2227  * \param sub The stasis subscription for this message callback
2228  * \param topic The topic this message was published for
2229  * \param message The message
2230  */
2231 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2232 {
2233         struct cdr_object *cdr;
2234         struct stasis_cache_update *update = stasis_message_data(message);
2235         struct ast_channel_snapshot *old_snapshot;
2236         struct ast_channel_snapshot *new_snapshot;
2237         struct cdr_object *it_cdr;
2238
2239         ast_assert(update != NULL);
2240         ast_assert(ast_channel_snapshot_type() == update->type);
2241
2242         old_snapshot = stasis_message_data(update->old_snapshot);
2243         new_snapshot = stasis_message_data(update->new_snapshot);
2244
2245         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2246                 return;
2247         }
2248
2249         if (new_snapshot && !old_snapshot) {
2250                 cdr = cdr_object_alloc(new_snapshot);
2251                 if (!cdr) {
2252                         return;
2253                 }
2254                 cdr->is_root = 1;
2255                 ao2_link(active_cdrs_master, cdr);
2256         } else {
2257                 const char *uniqueid;
2258
2259                 uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2260                 cdr = ao2_find(active_cdrs_master, uniqueid, OBJ_SEARCH_KEY);
2261         }
2262
2263         /* Handle Party A */
2264         if (!cdr) {
2265                 const char *name;
2266
2267                 name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2268                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2269                 ast_assert(0);
2270         } else if (new_snapshot) {
2271                 int all_reject = 1;
2272
2273                 ao2_lock(cdr);
2274                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2275                         if (!it_cdr->fn_table->process_party_a) {
2276                                 continue;
2277                         }
2278                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2279                 }
2280                 if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2281                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2282                         struct cdr_object *new_cdr;
2283
2284                         new_cdr = cdr_object_create_and_append(cdr);
2285                         if (new_cdr) {
2286                                 new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2287                         }
2288                 }
2289                 ao2_unlock(cdr);
2290         } else {
2291                 ao2_lock(cdr);
2292                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2293                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2294                         cdr_object_finalize(it_cdr);
2295                 }
2296                 cdr_object_dispatch(cdr);
2297                 ao2_unlock(cdr);
2298
2299                 cdr_all_unlink(cdr);
2300                 ao2_unlink(active_cdrs_master, cdr);
2301         }
2302
2303         /* Handle Party B */
2304         if (new_snapshot) {
2305                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2306                         cdr_object_update_party_b, (char *) new_snapshot->name, new_snapshot);
2307         } else {
2308                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2309                         cdr_object_finalize_party_b, (char *) old_snapshot->name, old_snapshot);
2310         }
2311
2312         ao2_cleanup(cdr);
2313 }
2314
2315 struct bridge_leave_data {
2316         struct ast_bridge_snapshot *bridge;
2317         struct ast_channel_snapshot *channel;
2318 };
2319
2320 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2321 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2322 {
2323         struct cdr_object *cdr = obj;
2324         struct bridge_leave_data *leave_data = data;
2325
2326         if (cdr->fn_table == &bridge_state_fn_table
2327                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2328                 && !strcasecmp(cdr->party_b_name, arg)) {
2329                 /*
2330                  * For sanity's sake we also assert the party_b snapshot
2331                  * is consistent with the key.
2332                  */
2333                 ast_assert(cdr->party_b.snapshot
2334                         && !strcasecmp(cdr->party_b.snapshot->name, leave_data->channel->name));
2335
2336                 /* It is our Party B, in our bridge. Set the end time and let the handler
2337                  * transition our CDR appropriately when we leave the bridge.
2338                  */
2339                 cdr_object_finalize(cdr);
2340         }
2341         return 0;
2342 }
2343
2344 /*! \brief Filter bridge messages based on bridge technology */
2345 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2346 {
2347         /* Ignore holding bridge technology messages. We treat this simply as an application
2348          * that a channel enters into.
2349          */
2350         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2351                 return 1;
2352         }
2353         return 0;
2354 }
2355
2356 /*!
2357  * \brief Handler for when a channel leaves a bridge
2358  * \param data Passed on
2359  * \param sub The stasis subscription for this message callback
2360  * \param topic The topic this message was published for
2361  * \param message The message - hopefully a bridge one!
2362  */
2363 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2364                 struct stasis_message *message)
2365 {
2366         struct ast_bridge_blob *update = stasis_message_data(message);
2367         struct ast_bridge_snapshot *bridge = update->bridge;
2368         struct ast_channel_snapshot *channel = update->channel;
2369         struct cdr_object *cdr;
2370         struct cdr_object *it_cdr;
2371         struct bridge_leave_data leave_data = {
2372                 .bridge = bridge,
2373                 .channel = channel,
2374         };
2375         int left_bridge = 0;
2376
2377         if (filter_bridge_messages(bridge)) {
2378                 return;
2379         }
2380
2381         if (filter_channel_snapshot(channel)) {
2382                 return;
2383         }
2384
2385         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2386                 channel->name,
2387                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2388                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2389
2390         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2391         if (!cdr) {
2392                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2393                 ast_assert(0);
2394                 return;
2395         }
2396
2397         /* Party A */
2398         ao2_lock(cdr);
2399         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2400                 if (!it_cdr->fn_table->process_bridge_leave) {
2401                         continue;
2402                 }
2403                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2404                         it_cdr, channel->name);
2405                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2406                         ast_string_field_set(it_cdr, bridge, "");
2407                         left_bridge = 1;
2408                 }
2409         }
2410         ao2_unlock(cdr);
2411
2412         /* Party B */
2413         if (left_bridge
2414                 && strcmp(bridge->subclass, "parking")) {
2415                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2416                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->name,
2417                         &leave_data);
2418         }
2419
2420         ao2_cleanup(cdr);
2421 }
2422
2423 /*!
2424  * \internal
2425  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2426  *
2427  * \note The new CDR will be automatically transitioned to the bridge state
2428  */
2429 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2430                 struct cdr_object_snapshot *party_b)
2431 {
2432         struct cdr_object *new_cdr;
2433
2434         new_cdr = cdr_object_create_and_append(cdr);
2435         if (!new_cdr) {
2436                 return;
2437         }
2438         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2439         cdr_all_relink(new_cdr);
2440         cdr_object_check_party_a_answer(new_cdr);
2441         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2442         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2443         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2444                 new_cdr, new_cdr->party_a.snapshot->name,
2445                 party_b->snapshot->name);
2446 }
2447
2448 /*!
2449  * \brief Process a single \ref bridge_candidate
2450  *
2451  * When a CDR enters a bridge, it needs to make pairings with everyone else
2452  * that it is not currently paired with. This function determines, for the
2453  * CDR for the channel that entered the bridge and the CDR for every other
2454  * channel currently in the bridge, who is Party A and makes new CDRs.
2455  *
2456  * \param cdr The \ref cdr_obj being processed
2457  * \param cand_cdr The \ref cdr_object that is a candidate
2458  *
2459  */
2460 static int bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2461 {
2462         struct cdr_object_snapshot *party_a;
2463         struct cdr_object *cand_cdr;
2464
2465         SCOPED_AO2LOCK(lock, base_cand_cdr);
2466
2467         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2468                 /* Skip any records that are not in this bridge */
2469                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2470                         continue;
2471                 }
2472
2473                 /* If the candidate is us or someone we've taken on, pass on by */
2474                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2475                         || (cdr->party_b.snapshot
2476                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2477                         return 0;
2478                 }
2479
2480                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2481                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2482                  * Party B */
2483                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2484                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2485                         return 0;
2486                 }
2487
2488                 /* We're Party B. Check if we can add ourselves immediately or if we need
2489                  * a new CDR for them (they already have a Party B) */
2490                 if (cand_cdr->party_b.snapshot
2491                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2492                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2493                 } else {
2494                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2495                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2496                                 cdr->party_a.snapshot->name);
2497                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2498                         cdr_all_relink(cand_cdr);
2499                         /* It's possible that this joined at one point and was never chosen
2500                          * as party A. Clear their end time, as it would be set in such a
2501                          * case.
2502                          */
2503                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2504                 }
2505                 return 0;
2506         }
2507         return 0;
2508 }
2509
2510 /*!
2511  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2512  * entered a bridge
2513  * \param cdr The \ref cdr_object that just entered the bridge
2514  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2515  */
2516 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2517 {
2518         struct ao2_iterator it_channels;
2519         char *channel_id;
2520
2521         it_channels = ao2_iterator_init(bridge->channels, 0);
2522         while ((channel_id = ao2_iterator_next(&it_channels))) {
2523                 struct cdr_object *cand_cdr;
2524
2525                 cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2526                 if (cand_cdr) {
2527                         bridge_candidate_process(cdr, cand_cdr);
2528                         ao2_ref(cand_cdr, -1);
2529                 }
2530
2531                 ao2_ref(channel_id, -1);
2532         }
2533         ao2_iterator_destroy(&it_channels);
2534 }
2535
2536 /*! \brief Handle entering into a parking bridge
2537  * \param cdr The CDR to operate on
2538  * \param bridge The bridge the channel just entered
2539  * \param channel The channel snapshot
2540  */
2541 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2542                 struct ast_bridge_snapshot *bridge,
2543                 struct ast_channel_snapshot *channel)
2544 {
2545         int res = 1;
2546         struct cdr_object *it_cdr;
2547         struct cdr_object *new_cdr;
2548
2549         ao2_lock(cdr);
2550
2551         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2552                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2553                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2554                 }
2555                 if (it_cdr->fn_table->process_party_a) {
2556                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2557                                 channel->name);
2558                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2559                 }
2560         }
2561
2562         if (res) {
2563                 /* No one handled it - we need a new one! */
2564                 new_cdr = cdr_object_create_and_append(cdr);
2565                 if (new_cdr) {
2566                         /* Let the single state transition us to Parked */
2567                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2568                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2569                 }
2570         }
2571         ao2_unlock(cdr);
2572 }
2573
2574 /*! \brief Handle a bridge enter message for a 'normal' bridge
2575  * \param cdr The CDR to operate on
2576  * \param bridge The bridge the channel just entered
2577  * \param channel The channel snapshot
2578  */
2579 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2580                 struct ast_bridge_snapshot *bridge,
2581                 struct ast_channel_snapshot *channel)
2582 {
2583         enum process_bridge_enter_results result;
2584         struct cdr_object *it_cdr;
2585         struct cdr_object *new_cdr;
2586         struct cdr_object *handled_cdr = NULL;
2587
2588         ao2_lock(cdr);
2589
2590         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2591                 if (it_cdr->fn_table->process_party_a) {
2592                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2593                                 channel->name);
2594                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2595                 }
2596
2597                 /* Notify all states that they have entered a bridge */
2598                 if (it_cdr->fn_table->process_bridge_enter) {
2599                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2600                                 channel->name);
2601                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2602                         switch (result) {
2603                         case BRIDGE_ENTER_ONLY_PARTY:
2604                                 /* Fall through */
2605                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2606                                 if (!handled_cdr) {
2607                                         handled_cdr = it_cdr;
2608                                 }
2609                                 break;
2610                         case BRIDGE_ENTER_NEED_CDR:
2611                                 /* Pass */
2612                                 break;
2613                         case BRIDGE_ENTER_NO_PARTY_B:
2614                                 /* We didn't win on any - end this CDR. If someone else comes in later
2615                                  * that is Party B to this CDR, it can re-activate this CDR.
2616                                  */
2617                                 if (!handled_cdr) {
2618                                         handled_cdr = it_cdr;
2619                                 }
2620                                 cdr_object_finalize(cdr);
2621                                 break;
2622                         }
2623                 }
2624         }
2625
2626         /* Create the new matchings, but only for either:
2627          *  * The first CDR in the chain that handled it. This avoids issues with
2628          *    forked CDRs.
2629          *  * If no one handled it, the last CDR in the chain. This would occur if
2630          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2631          *    to make pairings with everyone in the bridge.
2632          */
2633         if (handled_cdr) {
2634                 handle_bridge_pairings(handled_cdr, bridge);
2635         } else {
2636                 /* Nothing handled it - we need a new one! */
2637                 new_cdr = cdr_object_create_and_append(cdr);
2638                 if (new_cdr) {
2639                         /* This is guaranteed to succeed: the new CDR is created in the single state
2640                          * and will be able to handle the bridge enter message
2641                          */
2642                         handle_standard_bridge_enter_message(cdr, bridge, channel);
2643                 }
2644         }
2645         ao2_unlock(cdr);
2646 }
2647
2648 /*!
2649  * \internal
2650  * \brief Handler for Stasis-Core bridge enter messages
2651  * \param data Passed on
2652  * \param sub The stasis subscription for this message callback
2653  * \param topic The topic this message was published for
2654  * \param message The message - hopefully a bridge one!
2655  */
2656 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2657                 struct stasis_message *message)
2658 {
2659         struct ast_bridge_blob *update = stasis_message_data(message);
2660         struct ast_bridge_snapshot *bridge = update->bridge;
2661         struct ast_channel_snapshot *channel = update->channel;
2662         struct cdr_object *cdr;
2663
2664         if (filter_bridge_messages(bridge)) {
2665                 return;
2666         }
2667
2668         if (filter_channel_snapshot(channel)) {
2669                 return;
2670         }
2671
2672         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2673                 channel->name,
2674                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2675                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2676
2677         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2678         if (!cdr) {
2679                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2680                 ast_assert(0);
2681                 return;
2682         }
2683
2684         if (!strcmp(bridge->subclass, "parking")) {
2685                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2686         } else {
2687                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2688         }
2689         ao2_cleanup(cdr);
2690 }
2691
2692 /*!
2693  * \brief Handler for when a channel is parked
2694  * \param data Passed on
2695  * \param sub The stasis subscription for this message callback
2696  * \param topic The topic this message was published for
2697  * \param message The message about who got parked
2698  * */
2699 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2700                 struct stasis_message *message)
2701 {
2702         struct ast_parked_call_payload *payload = stasis_message_data(message);
2703         struct ast_channel_snapshot *channel = payload->parkee;
2704         struct cdr_object *cdr;
2705         int unhandled = 1;
2706         struct cdr_object *it_cdr;
2707
2708         /* Anything other than getting parked will be handled by other updates */
2709         if (payload->event_type != PARKED_CALL) {
2710                 return;
2711         }
2712
2713         /* No one got parked? */
2714         if (!channel) {
2715                 return;
2716         }
2717
2718         if (filter_channel_snapshot(channel)) {
2719                 return;
2720         }
2721
2722         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2723                 channel->name,
2724                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2725                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2726
2727         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2728         if (!cdr) {
2729                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2730                 ast_assert(0);
2731                 return;
2732         }
2733
2734         ao2_lock(cdr);
2735
2736         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2737                 if (it_cdr->fn_table->process_parked_channel) {
2738                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2739                 }
2740         }
2741
2742         if (unhandled) {
2743                 /* Nothing handled the messgae - we need a new one! */
2744                 struct cdr_object *new_cdr;
2745
2746                 new_cdr = cdr_object_create_and_append(cdr);
2747                 if (new_cdr) {
2748                         /* As the new CDR is created in the single state, it is guaranteed
2749                          * to have a function for the parked call message and will handle
2750                          * the message */
2751                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2752                 }
2753         }
2754
2755         ao2_unlock(cdr);
2756
2757         ao2_cleanup(cdr);
2758 }
2759
2760 /*!
2761  * \brief Handler for a synchronization message
2762  * \param data Passed on
2763  * \param sub The stasis subscription for this message callback
2764  * \param topic The topic this message was published for
2765  * \param message A blank ao2 object
2766  * */
2767 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2768                 struct stasis_message *message)
2769 {
2770         return;
2771 }
2772
2773 struct ast_cdr_config *ast_cdr_get_config(void)
2774 {
2775         struct ast_cdr_config *general;
2776         struct module_config *mod_cfg;
2777
2778         mod_cfg = ao2_global_obj_ref(module_configs);
2779         if (!mod_cfg) {
2780                 return NULL;
2781         }
2782         general = ao2_bump(mod_cfg->general);
2783         ao2_cleanup(mod_cfg);
2784         return general;
2785 }
2786
2787 void ast_cdr_set_config(struct ast_cdr_config *config)
2788 {
2789         struct module_config *mod_cfg;
2790
2791         if (!config) {
2792                 return;
2793         }
2794
2795         mod_cfg = ao2_global_obj_ref(module_configs);
2796         if (!mod_cfg) {
2797                 return;
2798         }
2799
2800         ao2_replace(mod_cfg->general, config);
2801
2802         cdr_set_debug_mode(mod_cfg);
2803         cdr_toggle_runtime_options();
2804
2805         ao2_cleanup(mod_cfg);
2806 }
2807
2808 int ast_cdr_is_enabled(void)
2809 {
2810         return is_cdr_flag_set(CDR_ENABLED);
2811 }
2812
2813 int ast_cdr_backend_suspend(const char *name)
2814 {
2815         int success = -1;
2816         struct cdr_beitem *i = NULL;
2817
2818         AST_RWLIST_WRLOCK(&be_list);
2819         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2820                 if (!strcasecmp(name, i->name)) {
2821                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2822                         i->suspended = 1;
2823                         success = 0;
2824                 }
2825         }
2826         AST_RWLIST_UNLOCK(&be_list);
2827
2828         return success;
2829 }
2830
2831 int ast_cdr_backend_unsuspend(const char *name)
2832 {
2833         int success = -1;
2834         struct cdr_beitem *i = NULL;
2835
2836         AST_RWLIST_WRLOCK(&be_list);
2837         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2838                 if (!strcasecmp(name, i->name)) {
2839                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2840                         i->suspended = 0;
2841                         success = 0;
2842                 }
2843         }
2844         AST_RWLIST_UNLOCK(&be_list);
2845
2846         return success;
2847 }
2848
2849 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2850 {
2851         struct cdr_beitem *i = NULL;
2852
2853         if (!name)
2854                 return -1;
2855
2856         if (!be) {
2857                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2858                 return -1;
2859         }
2860
2861         AST_RWLIST_WRLOCK(generic_list);
2862         AST_RWLIST_TRAVERSE(generic_list, i, list) {
2863                 if (!strcasecmp(name, i->name)) {
2864                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2865                         AST_RWLIST_UNLOCK(generic_list);
2866                         return -1;
2867                 }
2868         }
2869
2870         if (!(i = ast_calloc(1, sizeof(*i))))
2871                 return -1;
2872
2873         i->be = be;
2874         ast_copy_string(i->name, name, sizeof(i->name));
2875         ast_copy_string(i->desc, desc, sizeof(i->desc));
2876
2877         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2878         AST_RWLIST_UNLOCK(generic_list);
2879
2880         return 0;
2881 }
2882
2883 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2884 {
2885         return cdr_generic_register(&be_list, name, desc, be);
2886 }
2887
2888 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2889 {
2890         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2891 }
2892
2893 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2894 {
2895         struct cdr_beitem *match = NULL;
2896         int active_count;
2897
2898         AST_RWLIST_WRLOCK(generic_list);
2899         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2900                 if (!strcasecmp(name, match->name)) {
2901                         break;
2902                 }
2903         }
2904
2905         if (!match) {
2906                 AST_RWLIST_UNLOCK(generic_list);
2907                 return 0;
2908         }
2909
2910         active_count = ao2_container_count(active_cdrs_master);
2911
2912         if (!match->suspended && active_count != 0) {
2913                 AST_RWLIST_UNLOCK(generic_list);
2914                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2915                         name, active_count);
2916                 return -1;
2917         }
2918
2919         AST_RWLIST_REMOVE(generic_list, match, list);
2920         AST_RWLIST_UNLOCK(generic_list);
2921
2922         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2923         ast_free(match);
2924
2925         return 0;
2926 }
2927
2928 int ast_cdr_unregister(const char *name)
2929 {
2930         return ast_cdr_generic_unregister(&be_list, name);
2931 }
2932
2933 int ast_cdr_modifier_unregister(const char *name)
2934 {
2935         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2936 }
2937
2938 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2939 {
2940         struct ast_cdr *newcdr;
2941
2942         if (!cdr) {
2943                 return NULL;
2944         }
2945         newcdr = ast_cdr_alloc();
2946         if (!newcdr) {
2947                 return NULL;
2948         }
2949
2950         *newcdr = *cdr;
2951         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2952         copy_variables(&newcdr->varshead, &cdr->varshead);
2953         newcdr->next = NULL;
2954
2955         return newcdr;
2956 }
2957
2958 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2959 {
2960         struct ast_var_t *variables;
2961
2962         if (ast_strlen_zero(name)) {
2963                 return NULL;
2964         }
2965
2966         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
2967                 if (!strcasecmp(name, ast_var_name(variables))) {
2968                         return ast_var_value(variables);
2969                 }
2970         }
2971
2972         return NULL;
2973 }
2974
2975 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
2976 {
2977         if (fmt == NULL) {      /* raw mode */
2978                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
2979         } else {
2980                 buf[0] = '\0';/* Ensure the buffer is initialized. */
2981                 if (when.tv_sec) {
2982                         struct ast_tm tm;
2983
2984                         ast_localtime(&when, &tm, NULL);
2985                         ast_strftime(buf, bufsize, fmt, &tm);
2986                 }
2987         }
2988 }
2989
2990 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
2991 {
2992         const char *fmt = "%Y-%m-%d %T";
2993         const char *varbuf;
2994
2995         if (!cdr) {
2996                 return;
2997         }
2998
2999         *ret = NULL;
3000
3001         if (!strcasecmp(name, "clid")) {
3002                 ast_copy_string(workspace, cdr->clid, workspacelen);
3003         } else if (!strcasecmp(name, "src")) {
3004                 ast_copy_string(workspace, cdr->src, workspacelen);
3005         } else if (!strcasecmp(name, "dst")) {
3006                 ast_copy_string(workspace, cdr->dst, workspacelen);
3007         } else if (!strcasecmp(name, "dcontext")) {
3008                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3009         } else if (!strcasecmp(name, "channel")) {
3010                 ast_copy_string(workspace, cdr->channel, workspacelen);
3011         } else if (!strcasecmp(name, "dstchannel")) {
3012                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3013         } else if (!strcasecmp(name, "lastapp")) {
3014                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3015         } else if (!strcasecmp(name, "lastdata")) {
3016                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3017         } else if (!strcasecmp(name, "start")) {
3018                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3019         } else if (!strcasecmp(name, "answer")) {
3020                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3021         } else if (!strcasecmp(name, "end")) {
3022                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3023         } else if (!strcasecmp(name, "duration")) {
3024                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3025         } else if (!strcasecmp(name, "billsec")) {
3026                 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);
3027         } else if (!strcasecmp(name, "disposition")) {
3028                 if (raw) {
3029                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3030                 } else {
3031                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3032                 }
3033         } else if (!strcasecmp(name, "amaflags")) {
3034                 if (raw) {
3035                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3036                 } else {
3037                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3038                 }
3039         } else if (!strcasecmp(name, "accountcode")) {
3040                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3041         } else if (!strcasecmp(name, "peeraccount")) {
3042                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3043         } else if (!strcasecmp(name, "uniqueid")) {
3044                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3045         } else if (!strcasecmp(name, "linkedid")) {
3046                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3047         } else if (!strcasecmp(name, "userfield")) {
3048                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3049         } else if (!strcasecmp(name, "sequence")) {
3050                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3051         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3052                 ast_copy_string(workspace, varbuf, workspacelen);
3053         } else {
3054                 workspace[0] = '\0';
3055         }
3056
3057         if (!ast_strlen_zero(workspace)) {
3058                 *ret = workspace;
3059         }
3060 }
3061
3062 /*!
3063  * \internal
3064  * \brief Callback that finds all CDRs that reference a particular channel by name
3065  */
3066 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3067 {
3068         struct cdr_object *cdr = obj;
3069         const char *name = arg;
3070
3071         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
3072                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
3073                 return CMP_MATCH;
3074         }
3075         return 0;
3076 }
3077
3078 /*!
3079  * \internal
3080  * \brief Callback that finds a CDR by channel name
3081  */
3082 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3083 {
3084         struct cdr_object *cdr = obj;
3085         const char *name = arg;
3086
3087         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
3088                 return CMP_MATCH;
3089         }
3090         return 0;
3091 }
3092
3093 /* Read Only CDR variables */
3094 static const char * const cdr_readonly_vars[] = {
3095         "clid",
3096         "src",
3097         "dst",
3098         "dcontext",
3099         "channel",
3100         "dstchannel",
3101         "lastapp",
3102         "lastdata",
3103         "start",
3104         "answer",
3105         "end",
3106         "duration",
3107         "billsec",
3108         "disposition",
3109         "amaflags",
3110         "accountcode",
3111         "uniqueid",
3112         "linkedid",
3113         "userfield",
3114         "sequence",
3115         NULL
3116 };
3117
3118 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3119 {
3120         struct cdr_object *cdr;
3121         struct cdr_object *it_cdr;
3122         struct ao2_iterator *it_cdrs;
3123         char *arg = ast_strdupa(channel_name);
3124         int x;
3125
3126         for (x = 0; cdr_readonly_vars[x]; x++) {
3127                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3128                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3129                         return -1;
3130                 }
3131         }
3132
3133         it_cdrs = ao2_callback(active_cdrs_master, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3134         if (!it_cdrs) {
3135                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3136                 return -1;
3137         }
3138
3139         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3140                 ao2_lock(cdr);
3141                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3142                         struct varshead *headp = NULL;
3143
3144                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3145                                 continue;
3146                         }
3147                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
3148                                 headp = &it_cdr->party_a.variables;
3149                         } else if (it_cdr->party_b.snapshot
3150                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
3151                                 headp = &it_cdr->party_b.variables;
3152                         }
3153                         if (headp) {
3154                                 set_variable(headp, name, value);
3155                         }
3156                 }
3157         }
3158         ao2_iterator_destroy(it_cdrs);
3159
3160         return 0;
3161 }
3162
3163 /*!
3164  * \brief Format a variable on a \ref cdr_object
3165  */
3166 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3167 {
3168         struct ast_var_t *variable;
3169
3170         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3171                 if (!strcasecmp(name, ast_var_name(variable))) {
3172                         ast_copy_string(value, ast_var_value(variable), length);
3173                         return;
3174                 }
3175         }
3176
3177         *value = '\0';
3178 }
3179
3180 /*!
3181  * \brief Format one of the standard properties on a \ref cdr_object
3182  */
3183 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3184 {
3185         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3186         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3187
3188         if (!strcasecmp(name, "clid")) {
3189                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3190         } else if (!strcasecmp(name, "src")) {
3191                 ast_copy_string(value, party_a->caller_number, length);
3192         } else if (!strcasecmp(name, "dst")) {
3193                 ast_copy_string(value, party_a->exten, length);
3194         } else if (!strcasecmp(name, "dcontext")) {
3195                 ast_copy_string(value, party_a->context, length);
3196         } else if (!strcasecmp(name, "channel")) {
3197                 ast_copy_string(value, party_a->name, length);
3198         } else if (!strcasecmp(name, "dstchannel")) {
3199                 if (party_b) {
3200                         ast_copy_string(value, party_b->name, length);
3201                 } else {
3202                         ast_copy_string(value, "", length);
3203                 }
3204         } else if (!strcasecmp(name, "lastapp")) {
3205                 ast_copy_string(value, party_a->appl, length);
3206         } else if (!strcasecmp(name, "lastdata")) {
3207                 ast_copy_string(value, party_a->data, length);
3208         } else if (!strcasecmp(name, "start")) {
3209                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3210         } else if (!strcasecmp(name, "answer")) {
3211                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3212         } else if (!strcasecmp(name, "end")) {
3213                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3214         } else if (!strcasecmp(name, "duration")) {
3215                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3216         } else if (!strcasecmp(name, "billsec")) {
3217                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3218         } else if (!strcasecmp(name, "disposition")) {
3219                 snprintf(value, length, "%u", cdr_obj->disposition);
3220         } else if (!strcasecmp(name, "amaflags")) {
3221                 snprintf(value, length, "%d", party_a->amaflags);
3222         } else if (!strcasecmp(name, "accountcode")) {
3223                 ast_copy_string(value, party_a->accountcode, length);
3224         } else if (!strcasecmp(name, "peeraccount")) {
3225                 if (party_b) {
3226                         ast_copy_string(value, party_b->accountcode, length);
3227                 } else {
3228                         ast_copy_string(value, "", length);
3229                 }
3230         } else if (!strcasecmp(name, "uniqueid")) {
3231                 ast_copy_string(value, party_a->uniqueid, length);
3232         } else if (!strcasecmp(name, "linkedid")) {
3233                 ast_copy_string(value, cdr_obj->linkedid, length);
3234         } else if (!strcasecmp(name, "userfield")) {
3235                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3236         } else if (!strcasecmp(name, "sequence")) {
3237                 snprintf(value, length, "%u", cdr_obj->sequence);
3238         } else {
3239                 return 1;
3240         }
3241
3242         return 0;
3243 }
3244
3245 /*! \internal
3246  * \brief Look up and retrieve a CDR object by channel name
3247  * \param name The name of the channel
3248  * \retval NULL on error
3249  * \retval The \ref cdr_object for the channel on success, with the reference
3250  *      count bumped by one.
3251  */
3252 static struct cdr_object *cdr_object_get_by_name(const char *name)
3253 {
3254         char *param;
3255
3256         if (ast_strlen_zero(name)) {
3257                 return NULL;
3258         }
3259
3260         param = ast_strdupa(name);
3261         return ao2_callback(active_cdrs_master, 0, cdr_object_get_by_name_cb, param);
3262 }
3263
3264 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3265 {
3266         struct cdr_object *cdr;
3267         struct cdr_object *cdr_obj;
3268
3269         if (ast_strlen_zero(name)) {
3270                 return 1;
3271         }
3272
3273         cdr = cdr_object_get_by_name(channel_name);
3274         if (!cdr) {
3275                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3276                 return 1;
3277         }
3278
3279         ao2_lock(cdr);
3280
3281         cdr_obj = cdr->last;
3282         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3283                 /* Property failed; attempt variable */
3284                 cdr_object_format_var_internal(cdr_obj, name, value, length);
3285         }
3286
3287         ao2_unlock(cdr);
3288
3289         ao2_cleanup(cdr);
3290         return 0;
3291 }
3292
3293 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3294 {
3295         struct cdr_object *cdr;
3296         struct cdr_object *it_cdr;
3297         struct ast_var_t *variable;
3298         const char *var;
3299         char workspace[256];
3300         int total = 0, x = 0, i;
3301
3302         cdr = cdr_object_get_by_name(channel_name);
3303         if (!cdr) {
3304                 if (is_cdr_flag_set(CDR_ENABLED)) {
3305                         ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3306                 }
3307                 return 0;
3308         }
3309
3310         ast_str_reset(*buf);
3311
3312         ao2_lock(cdr);
3313         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3314                 if (++x > 1) {
3315                         ast_str_append(buf, 0, "\n");
3316                 }
3317
3318                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3319                         if (!(var = ast_var_name(variable))) {
3320                                 continue;
3321                         }
3322
3323                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
3324                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3325                                 break;
3326                         }
3327
3328                         total++;
3329                 }
3330
3331                 for (i = 0; cdr_readonly_vars[i]; i++) {
3332                         if (cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace))) {
3333                                 /* Unhandled read-only CDR variable. */
3334                                 ast_assert(0);
3335                                 continue;
3336                         }
3337
3338                         if (!ast_strlen_zero(workspace)
3339                                 && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
3340                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3341                                 break;
3342                         }
3343                         total++;
3344                 }
3345         }
3346         ao2_unlock(cdr);
3347         ao2_cleanup(cdr);
3348         return total;
3349 }
3350
3351 void ast_cdr_free(struct ast_cdr *cdr)
3352 {
3353         while (cdr) {
3354                 struct ast_cdr *next = cdr->next;
3355
3356                 free_variables(&cdr->varshead);
3357                 ast_free(cdr);
3358                 cdr = next;
3359         }
3360 }
3361
3362 struct ast_cdr *ast_cdr_alloc(void)
3363 {
3364         struct ast_cdr *x;
3365
3366         x = ast_calloc(1, sizeof(*x));
3367         return x;
3368 }
3369
3370 const char *ast_cdr_disp2str(int disposition)
3371 {
3372         switch (disposition) {
3373         case AST_CDR_NULL:
3374                 return "NO ANSWER"; /* by default, for backward compatibility */
3375         case AST_CDR_NOANSWER:
3376                 return "NO ANSWER";
3377         case AST_CDR_FAILED:
3378                 return "FAILED";
3379         case AST_CDR_BUSY:
3380                 return "BUSY";
3381         case AST_CDR_ANSWERED:
3382                 return "ANSWERED";
3383         case AST_CDR_CONGESTION:
3384                 return "CONGESTION";
3385         }
3386         return "UNKNOWN";
3387 }
3388
3389 struct party_b_userfield_update {
3390         const char *channel_name;
3391         const char *userfield;
3392 };
3393
3394 /*! \brief Callback used to update the userfield on Party B on all CDRs */
3395 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, void *data, int flags)
3396 {
3397         struct cdr_object *cdr = obj;
3398
3399         if ((cdr->fn_table != &finalized_state_fn_table || !cdr->next)
3400                 && !strcasecmp(cdr->party_b_name, arg)) {
3401                 struct party_b_userfield_update *info = data;
3402
3403                 /*
3404                  * For sanity's sake we also assert the party_b snapshot
3405                  * is consistent with the key.
3406                  */
3407                 ast_assert(cdr->party_b.snapshot
3408                         && !strcasecmp(cdr->party_b.snapshot->name, info->channel_name));
3409
3410                 strcpy(cdr->party_b.userfield, info->userfield);
3411         }
3412
3413         return 0;
3414 }
3415
3416 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
3417 {
3418         struct cdr_object *cdr;
3419         struct party_b_userfield_update party_b_info = {
3420                 .channel_name = channel_name,
3421                 .userfield = userfield,
3422         };
3423         struct cdr_object *it_cdr;
3424
3425         /* Handle Party A */
3426         cdr = cdr_object_get_by_name(channel_name);
3427         if (cdr) {
3428                 ao2_lock(cdr);
3429                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3430                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3431                                 continue;
3432                         }
3433                         ast_copy_string(it_cdr->party_a.userfield, userfield, AST_MAX_USER_FIELD);
3434                 }
3435                 ao2_unlock(cdr);
3436         }
3437
3438         /* Handle Party B */
3439         ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
3440                 cdr_object_update_party_b_userfield_cb, (char *) party_b_info.channel_name,
3441                 &party_b_info);
3442
3443         ao2_cleanup(cdr);
3444 }
3445
3446 static void post_cdr(struct ast_cdr *cdr)
3447 {
3448         struct module_config *mod_cfg;
3449         struct cdr_beitem *i;
3450
3451         mod_cfg = ao2_global_obj_ref(module_configs);
3452         if (!mod_cfg) {
3453                 return;
3454         }
3455
3456         for (; cdr ; cdr = cdr->next) {
3457                 /* For people, who don't want to see unanswered single-channel events */
3458                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
3459                                 cdr->disposition < AST_CDR_ANSWERED &&
3460                                 (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
3461                         ast_debug(1, "Skipping CDR for %s since we weren't answered\n", cdr->channel);
3462                         continue;
3463                 }
3464
3465                 /* Modify CDR's */
3466                 AST_RWLIST_RDLOCK(&mo_list);
3467                 AST_RWLIST_TRAVERSE(&mo_list, i, list) {
3468                         i->be(cdr);
3469                 }
3470                 AST_RWLIST_UNLOCK(&mo_list);
3471
3472                 if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
3473                         continue;
3474                 }
3475                 AST_RWLIST_RDLOCK(&be_list);
3476                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
3477                         if (!i->suspended) {
3478                                 i->be(cdr);
3479                         }
3480                 }
3481                 AST_RWLIST_UNLOCK(&be_list);
3482         }
3483         ao2_cleanup(mod_cfg);
3484 }
3485
3486 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
3487 {
3488         struct cdr_object *cdr;
3489         struct cdr_object *it_cdr;
3490
3491         cdr = cdr_object_get_by_name(channel_name);
3492         if (!cdr) {
3493                 return -1;
3494         }
3495
3496         ao2_lock(cdr);
3497         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3498                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3499                         continue;
3500                 }
3501                 /* Note: in general, set the flags on both the CDR record as well as the
3502                  * Party A. Sometimes all we have is the Party A to look at.
3503                  */
3504                 ast_set_flag(&it_cdr->flags, option);
3505                 ast_set_flag(&it_cdr->party_a, option);
3506         }
3507         ao2_unlock(cdr);
3508
3509         ao2_cleanup(cdr);
3510         return 0;
3511 }
3512
3513 int ast_cdr_clear_property(const char *channel_name, enum ast_cdr_options option)
3514 {
3515         struct cdr_object *cdr;
3516         struct cdr_object *it_cdr;
3517
3518         cdr = cdr_object_get_by_name(channel_name);
3519         if (!cdr) {
3520                 return -1;
3521         }
3522
3523         ao2_lock(cdr);
3524         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3525                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3526                         continue;
3527                 }
3528                 ast_clear_flag(&it_cdr->flags, option);
3529         }
3530         ao2_unlock(cdr);
3531
3532         ao2_cleanup(cdr);
3533         return 0;
3534 }
3535
3536 int ast_cdr_reset(const char *channel_name, int keep_variables)
3537 {
3538         struct cdr_object *cdr;
3539         struct ast_var_t *vardata;
3540         struct cdr_object *it_cdr;
3541
3542         cdr = cdr_object_get_by_name(channel_name);
3543         if (!cdr) {
3544                 return -1;
3545         }
3546
3547         ao2_lock(cdr);
3548         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3549                 /* clear variables */
3550                 if (!keep_variables) {
3551                         while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_a.variables, entries))) {
3552                                 ast_var_delete(vardata);
3553                         }
3554                         if (cdr->party_b.snapshot) {
3555                                 while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_b.variables, entries))) {
3556                                         ast_var_delete(vardata);
3557                                 }
3558                         }
3559                 }
3560
3561                 /* Reset to initial state */
3562                 memset(&it_cdr->start, 0, sizeof(it_cdr->start));
3563                 memset(&it_cdr->end, 0, sizeof(it_cdr->end));
3564                 memset(&it_cdr->answer, 0, sizeof(it_cdr->answer));
3565                 it_cdr->start = ast_tvnow();
3566                 cdr_object_check_party_a_answer(it_cdr);
3567         }
3568         ao2_unlock(cdr);
3569
3570         ao2_cleanup(cdr);
3571         return 0;
3572 }
3573
3574 int ast_cdr_fork(const char *channel_name, struct ast_flags *options)
3575 {
3576         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3577         struct cdr_object *new_cdr;
3578         struct cdr_object *it_cdr;
3579         struct cdr_object *cdr_obj;
3580
3581         if (!cdr) {
3582                 return -1;
3583         }
3584
3585         {
3586                 SCOPED_AO2LOCK(lock, cdr);
3587
3588                 cdr_obj = cdr->last;
3589                 if (cdr_obj->fn_table == &finalized_state_fn_table) {
3590                         /* If the last CDR in the chain is finalized, don't allow a fork -
3591                          * things are already dying at this point
3592                          */
3593                         return -1;
3594                 }
3595
3596                 /* Copy over the basic CDR information. The Party A information is
3597                  * copied over automatically as part of the append
3598                  */
3599                 ast_debug(1, "Forking CDR for channel %s\n", cdr->party_a.snapshot->name);
3600                 new_cdr = cdr_object_create_and_append(cdr);
3601                 if (!new_cdr) {
3602                         return -1;
3603                 }
3604                 new_cdr->fn_table = cdr_obj->fn_table;
3605                 ast_string_field_set(new_cdr, bridge, cdr->bridge);
3606                 ast_string_field_set(new_cdr, appl, cdr->appl);
3607                 ast_string_field_set(new_cdr, data, cdr->data);
3608                 ast_string_field_set(new_cdr, context, cdr->context);
3609                 ast_string_field_set(new_cdr, exten, cdr->exten);
3610                 new_cdr->flags = cdr->flags;
3611                 /* Explicitly clear the AST_CDR_LOCK_APP flag - we want
3612                  * the application to be changed on the new CDR if the
3613                  * dialplan demands it
3614                  */
3615                 ast_clear_flag(&new_cdr->flags, AST_CDR_LOCK_APP);
3616
3617                 /* If there's a Party B, copy it over as well */
3618                 if (cdr_obj->party_b.snapshot) {
3619                         new_cdr->party_b.snapshot = cdr_obj->party_b.snapshot;
3620                         ao2_ref(new_cdr->party_b.snapshot, +1);
3621                         cdr_all_relink(new_cdr);
3622                         strcpy(new_cdr->party_b.userfield, cdr_obj->party_b.userfield);
3623                         new_cdr->party_b.flags = cdr_obj->party_b.flags;
3624                         if (ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3625                                 copy_variables(&new_cdr->party_b.variables, &cdr_obj->party_b.variables);
3626                         }
3627                 }
3628                 new_cdr->start = cdr_obj->start;
3629                 new_cdr->answer = cdr_obj->answer;
3630
3631                 /* Modify the times based on the flags passed in */
3632                 if (ast_test_flag(options, AST_CDR_FLAG_SET_ANSWER)
3633                                 && new_cdr->party_a.snapshot->state == AST_STATE_UP) {
3634                         new_cdr->answer = ast_tvnow();
3635                 }
3636                 if (ast_test_flag(options, AST_CDR_FLAG_RESET)) {
3637                         new_cdr->answer = ast_tvnow();
3638                         new_cdr->start = ast_tvnow();
3639                 }
3640
3641                 /* Create and append, by default, copies over the variables */
3642                 if (!ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3643                         free_variables(&new_cdr->party_a.variables);
3644                 }
3645
3646                 /* Finalize any current CDRs */
3647                 if (ast_test_flag(options, AST_CDR_FLAG_FINALIZE)) {
3648                         for (it_cdr = cdr; it_cdr != new_cdr; it_cdr = it_cdr->next) {
3649                                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3650                                         continue;
3651                                 }
3652                                 /* Force finalization on the CDR. This will bypass any checks for
3653                                  * end before 'h' extension.
3654                                  */
3655                                 cdr_object_finalize(it_cdr);
3656                                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
3657                         }
3658                 }
3659         }
3660
3661         return 0;
3662 }
3663
3664 /*! \note Don't call without cdr_batch_lock */
3665 static void reset_batch(void)
3666 {
3667         batch->size = 0;
3668         batch->head = NULL;
3669         batch->tail = NULL;
3670 }
3671
3672 /*! \note Don't call without cdr_batch_lock */
3673 static int init_batch(void)
3674 {
3675         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
3676         if (!(batch = ast_malloc(sizeof(*batch))))
3677                 return -1;
3678
3679         reset_batch();
3680
3681         return 0;
3682 }
3683
3684 static void *do_batch_backend_process(void *data)
3685 {
3686         struct cdr_batch_item *processeditem;
3687         struct cdr_batch_item *batchitem = data;
3688
3689         /* Push each CDR into storage mechanism(s) and free all the memory */
3690         while (batchitem) {
3691                 post_cdr(batchitem->cdr);
3692                 ast_cdr_free(batchitem->cdr);
3693                 processeditem = batchitem;
3694                 batchitem = batchitem->next;
3695                 ast_free(processeditem);
3696         }
3697
3698         return NULL;
3699 }
3700
3701 static void cdr_submit_batch(int do_shutdown)
3702 {
3703         struct module_config *mod_cfg;
3704         struct cdr_batch_item *oldbatchitems = NULL;
3705         pthread_t batch_post_thread = AST_PTHREADT_NULL;
3706
3707         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
3708         if (!batch || !batch->head) {
3709                 return;
3710         }
3711
3712         /* move the old CDRs aside, and prepare a new CDR batch */
3713         ast_mutex_lock(&cdr_batch_lock);
3714         oldbatchitems = batch->head;
3715         reset_batch();
3716         ast_mutex_unlock(&cdr_batch_lock);
3717
3718         mod_cfg = ao2_global_obj_ref(module_configs);
3719
3720         /* if configured, spawn a new thread to post these CDRs,
3721            also try to save as much as possible if we are shutting down safely */
3722         if (!mod_cfg
3723                 || ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY)
3724                 || do_shutdown) {
3725                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
3726                 do_batch_backend_process(oldbatchitems);
3727         } else {
3728                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
3729                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
3730                         do_batch_backend_process(oldbatchitems);
3731                 } else {
3732                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
3733                 }
3734         }
3735
3736         ao2_cleanup(mod_cfg);
3737 }
3738
3739 static int submit_scheduled_batch(const void *data)
3740 {
3741         struct module_config *mod_cfg;
3742
3743         cdr_submit_batch(0);
3744
3745         mod_cfg = ao2_global_obj_ref(module_configs);
3746         if (!mod_cfg) {
3747                 return 0;
3748         }
3749
3750         /* manually reschedule from this point in time */
3751         ast_mutex_lock(&cdr_sched_lock);
3752         cdr_sched = ast_sched_add(sched, mod_cfg->general->batch_settings.time * 1000, submit_scheduled_batch, NULL);
3753         ast_mutex_unlock(&cdr_sched_lock);
3754
3755         ao2_cleanup(mod_cfg);
3756         /* returning zero so the scheduler does not automatically reschedule */
3757         return 0;
3758 }
3759
3760 /*! Do not hold the batch lock while calling this function */
3761 static void submit_unscheduled_batch(void)
3762 {
3763         /* Prevent two deletes from happening at the same time */
3764         ast_mutex_lock(&cdr_sched_lock);
3765         /* this is okay since we are not being called from within the scheduler */
3766         AST_SCHED_DEL(sched, cdr_sched);
3767         /* schedule the submission to occur ASAP (1 ms) */
3768         cdr_sched = ast_sched_add(sched, 1, submit_scheduled_batch, NULL);
3769         ast_mutex_unlock(&cdr_sched_lock);
3770
3771         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
3772         ast_mutex_lock(&cdr_pending_lock);
3773         ast_cond_signal(&cdr_pending_cond);
3774         ast_mutex_unlock(&cdr_pending_lock);
3775 }
3776
3777 static void cdr_detach(struct ast_cdr *cdr)
3778 {
3779         struct cdr_batch_item *newtail;
3780         int curr;
3781         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3782         int submit_batch = 0;
3783
3784         if (!cdr) {
3785                 return;
3786         }
3787
3788         /* maybe they disabled CDR stuff completely, so just drop it */
3789         if (!mod_cfg || !ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3790                 ast_debug(1, "Dropping CDR !\n");
3791                 ast_cdr_free(cdr);
3792                 return;
3793         }
3794
3795         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
3796         if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3797                 post_cdr(cdr);
3798                 ast_cdr_free(cdr);
3799                 return;
3800         }
3801
3802         /* otherwise, each CDR gets put into a batch list (at the end) */
3803         ast_debug(1, "CDR detaching from this thread\n");
3804
3805         /* we'll need a new tail for every CDR */
3806         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
3807                 post_cdr(cdr);
3808                 ast_cdr_free(cdr);
3809                 return;
3810         }
3811
3812         /* don't traverse a whole list (just keep track of the tail) */
3813         ast_mutex_lock(&cdr_batch_lock);
3814         if (!batch)
3815                 init_batch();
3816         if (!batch->head) {
3817                 /* new batch is empty, so point the head at the new tail */
3818                 batch->head = newtail;
3819         } else {
3820                 /* already got a batch with something in it, so just append a new tail */
3821                 batch->tail->next = newtail;
3822         }
3823         newtail->cdr = cdr;
3824         batch->tail = newtail;
3825         curr = batch->size++;
3826
3827         /* if we have enough stuff to post, then do it */
3828         if (curr >= (mod_cfg->general->batch_settings.size - 1)) {
3829                 submit_batch = 1;
3830         }
3831         ast_mutex_unlock(&cdr_batch_lock);
3832
3833         /* Don't call submit_unscheduled_batch with the cdr_batch_lock held */
3834         if (submit_batch) {
3835                 submit_unscheduled_batch();
3836         }
3837 }
3838
3839 static void *do_cdr(void *data)