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