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