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