Generic Advice of Charge.
[asterisk/asterisk.git] / channels / sig_pri.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2009, 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 PRI signaling module
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  */
25
26
27 #include "asterisk.h"
28
29 #ifdef HAVE_PRI
30
31 #include <errno.h>
32 #include <ctype.h>
33 #include <signal.h>
34
35 #include "asterisk/utils.h"
36 #include "asterisk/options.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/app.h"
39 #include "asterisk/file.h"
40 #include "asterisk/callerid.h"
41 #include "asterisk/say.h"
42 #include "asterisk/manager.h"
43 #include "asterisk/astdb.h"
44 #include "asterisk/causes.h"
45 #include "asterisk/musiconhold.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/transcap.h"
48 #include "asterisk/features.h"
49 #include "asterisk/aoc.h"
50
51 #include "sig_pri.h"
52 #ifndef PRI_EVENT_FACILITY
53 #error please update libpri
54 #endif
55
56 /* define this to send PRI user-user information elements */
57 #undef SUPPORT_USERUSER
58
59 #if defined(HAVE_PRI_CCSS)
60 struct sig_pri_cc_agent_prv {
61         /*! Asterisk span D channel control structure. */
62         struct sig_pri_pri *pri;
63         /*! CC id value to use with libpri. -1 if invalid. */
64         long cc_id;
65         /*! TRUE if CC has been requested and we are waiting for the response. */
66         unsigned char cc_request_response_pending;
67 };
68
69 struct sig_pri_cc_monitor_instance {
70         /*! \brief Asterisk span D channel control structure. */
71         struct sig_pri_pri *pri;
72         /*! CC id value to use with libpri. (-1 if already canceled). */
73         long cc_id;
74         /*! CC core id value. */
75         int core_id;
76         /*! Device name(Channel name less sequence number) */
77         char name[1];
78 };
79
80 /*! Upper level agent/monitor type name. */
81 static const char *sig_pri_cc_type_name;
82 /*! Container of sig_pri monitor instances. */
83 static struct ao2_container *sig_pri_cc_monitors;
84 #endif  /* defined(HAVE_PRI_CCSS) */
85
86 static int pri_matchdigittimeout = 3000;
87
88 static int pri_gendigittimeout = 8000;
89
90 #define DCHAN_NOTINALARM  (1 << 0)
91 #define DCHAN_UP          (1 << 1)
92
93 /* Defines to help decode the encoded event channel id. */
94 #define PRI_CHANNEL(p)  ((p) & 0xff)
95 #define PRI_SPAN(p)             (((p) >> 8) & 0xff)
96 #define PRI_EXPLICIT    (1 << 16)
97 #define PRI_CIS_CALL    (1 << 17)       /* Call is using the D channel only. */
98 #define PRI_HELD_CALL   (1 << 18)
99
100
101 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
102
103 #define PRI_DEADLOCK_AVOIDANCE(p) \
104         do { \
105                 sig_pri_unlock_private(p); \
106                 usleep(1); \
107                 sig_pri_lock_private(p); \
108         } while (0)
109
110 static int pri_active_dchan_index(struct sig_pri_pri *pri);
111
112 static inline void pri_rel(struct sig_pri_pri *pri)
113 {
114         ast_mutex_unlock(&pri->lock);
115 }
116
117 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
118 {
119         int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
120         ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
121                 p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
122
123         return res;
124 }
125
126 static void sig_pri_handle_dchan_exception(struct sig_pri_pri *pri, int index)
127 {
128         if (pri->calls->handle_dchan_exception)
129                 pri->calls->handle_dchan_exception(pri, index);
130 }
131
132 static void sig_pri_set_dialing(struct sig_pri_chan *p, int is_dialing)
133 {
134         if (p->calls->set_dialing) {
135                 p->calls->set_dialing(p->chan_pvt, is_dialing);
136         }
137 }
138
139 static void sig_pri_set_digital(struct sig_pri_chan *p, int is_digital)
140 {
141         p->digital = is_digital;
142         if (p->calls->set_digital) {
143                 p->calls->set_digital(p->chan_pvt, is_digital);
144         }
145 }
146
147 static void sig_pri_set_alarm(struct sig_pri_chan *p, int in_alarm)
148 {
149         p->inalarm = in_alarm;
150         if (p->calls->set_alarm) {
151                 p->calls->set_alarm(p->chan_pvt, in_alarm);
152         }
153 }
154
155 static const char *sig_pri_get_orig_dialstring(struct sig_pri_chan *p)
156 {
157         if (p->calls->get_orig_dialstring) {
158                 return p->calls->get_orig_dialstring(p->chan_pvt);
159         }
160         ast_log(LOG_ERROR, "get_orig_dialstring callback not defined\n");
161         return "";
162 }
163
164 #if defined(HAVE_PRI_CCSS)
165 static void sig_pri_make_cc_dialstring(struct sig_pri_chan *p, char *buf, size_t buf_size)
166 {
167         if (p->calls->make_cc_dialstring) {
168                 p->calls->make_cc_dialstring(p->chan_pvt, buf, buf_size);
169         } else {
170                 ast_log(LOG_ERROR, "make_cc_dialstring callback not defined\n");
171                 buf[0] = '\0';
172         }
173 }
174 #endif  /* defined(HAVE_PRI_CCSS) */
175
176 /*!
177  * \internal
178  * \brief Reevaluate the PRI span device state.
179  * \since 1.8
180  *
181  * \param pri Asterisk D channel control structure.
182  *
183  * \return Nothing
184  *
185  * \note Assumes the pri->lock is already obtained.
186  */
187 static void sig_pri_span_devstate_changed(struct sig_pri_pri *pri)
188 {
189         if (pri->calls->update_span_devstate) {
190                 pri->calls->update_span_devstate(pri);
191         }
192 }
193
194 /*!
195  * \internal
196  * \brief Set the caller id information in the parent module.
197  * \since 1.8
198  *
199  * \param p sig_pri channel structure.
200  *
201  * \return Nothing
202  */
203 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
204 {
205         struct ast_party_caller caller;
206
207         if (p->calls->set_callerid) {
208                 ast_party_caller_init(&caller);
209                 caller.id.number = p->cid_num;
210                 caller.id.name = p->cid_name;
211                 if (!ast_strlen_zero(p->cid_subaddr)) {
212                         caller.id.subaddress.valid = 1;
213                         //caller.id.subaddress.type = 0;/* nsap */
214                         //caller.id.subaddress.odd_even_indicator = 0;
215                         caller.id.subaddress.str = p->cid_subaddr;
216                 }
217                 caller.id.number_type = p->cid_ton;
218                 caller.id.number_presentation = p->callingpres;
219                 caller.ani = p->cid_ani;
220                 caller.ani2 = p->cid_ani2;
221                 p->calls->set_callerid(p->chan_pvt, &caller);
222         }
223 }
224
225 /*!
226  * \internal
227  * \brief Set the Dialed Number Identifier.
228  * \since 1.8
229  *
230  * \param p sig_pri channel structure.
231  * \param dnid Dialed Number Identifier string.
232  *
233  * \return Nothing
234  */
235 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
236 {
237         if (p->calls->set_dnid) {
238                 p->calls->set_dnid(p->chan_pvt, dnid);
239         }
240 }
241
242 /*!
243  * \internal
244  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
245  * \since 1.8
246  *
247  * \param p sig_pri channel structure.
248  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
249  *
250  * \return Nothing
251  */
252 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
253 {
254         if (p->calls->set_rdnis) {
255                 p->calls->set_rdnis(p->chan_pvt, rdnis);
256         }
257 }
258
259 static void sig_pri_unlock_private(struct sig_pri_chan *p)
260 {
261         if (p->calls->unlock_private)
262                 p->calls->unlock_private(p->chan_pvt);
263 }
264
265 static void sig_pri_lock_private(struct sig_pri_chan *p)
266 {
267         if (p->calls->lock_private)
268                 p->calls->lock_private(p->chan_pvt);
269 }
270
271 static inline int pri_grab(struct sig_pri_chan *p, struct sig_pri_pri *pri)
272 {
273         int res;
274         /* Grab the lock first */
275         do {
276                 res = ast_mutex_trylock(&pri->lock);
277                 if (res) {
278                         PRI_DEADLOCK_AVOIDANCE(p);
279                 }
280         } while (res);
281         /* Then break the poll */
282         pthread_kill(pri->master, SIGURG);
283         return 0;
284 }
285
286 /*!
287  * \internal
288  * \brief Convert PRI redirecting reason to asterisk version.
289  * \since 1.8
290  *
291  * \param pri_reason PRI redirecting reason.
292  *
293  * \return Equivalent asterisk redirecting reason value.
294  */
295 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
296 {
297         enum AST_REDIRECTING_REASON ast_reason;
298
299         switch (pri_reason) {
300         case PRI_REDIR_FORWARD_ON_BUSY:
301                 ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
302                 break;
303         case PRI_REDIR_FORWARD_ON_NO_REPLY:
304                 ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
305                 break;
306         case PRI_REDIR_DEFLECTION:
307                 ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
308                 break;
309         case PRI_REDIR_UNCONDITIONAL:
310                 ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
311                 break;
312         case PRI_REDIR_UNKNOWN:
313         default:
314                 ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
315                 break;
316         }
317
318         return ast_reason;
319 }
320
321 /*!
322  * \internal
323  * \brief Convert asterisk redirecting reason to PRI version.
324  * \since 1.8
325  *
326  * \param ast_reason Asterisk redirecting reason.
327  *
328  * \return Equivalent PRI redirecting reason value.
329  */
330 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
331 {
332         int pri_reason;
333
334         switch (ast_reason) {
335         case AST_REDIRECTING_REASON_USER_BUSY:
336                 pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
337                 break;
338         case AST_REDIRECTING_REASON_NO_ANSWER:
339                 pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
340                 break;
341         case AST_REDIRECTING_REASON_UNCONDITIONAL:
342                 pri_reason = PRI_REDIR_UNCONDITIONAL;
343                 break;
344         case AST_REDIRECTING_REASON_DEFLECTION:
345                 pri_reason = PRI_REDIR_DEFLECTION;
346                 break;
347         case AST_REDIRECTING_REASON_UNKNOWN:
348         default:
349                 pri_reason = PRI_REDIR_UNKNOWN;
350                 break;
351         }
352
353         return pri_reason;
354 }
355
356 /*!
357  * \internal
358  * \brief Convert PRI number presentation to asterisk version.
359  * \since 1.8
360  *
361  * \param pri_presentation PRI number presentation.
362  *
363  * \return Equivalent asterisk number presentation value.
364  */
365 static int pri_to_ast_presentation(int pri_presentation)
366 {
367         int ast_presentation;
368
369         switch (pri_presentation) {
370         case PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
371                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
372                 break;
373         case PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
374                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
375                 break;
376         case PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
377                 ast_presentation = AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
378                 break;
379         case PRES_ALLOWED_NETWORK_NUMBER:
380                 ast_presentation = AST_PRES_ALLOWED_NETWORK_NUMBER;
381                 break;
382         case PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
383                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
384                 break;
385         case PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
386                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
387                 break;
388         case PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
389                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
390                 break;
391         case PRES_PROHIB_NETWORK_NUMBER:
392                 ast_presentation = AST_PRES_PROHIB_NETWORK_NUMBER;
393                 break;
394         case PRES_NUMBER_NOT_AVAILABLE:
395                 ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
396                 break;
397         default:
398                 ast_presentation = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
399                 break;
400         }
401
402         return ast_presentation;
403 }
404
405 /*!
406  * \internal
407  * \brief Convert asterisk number presentation to PRI version.
408  * \since 1.8
409  *
410  * \param ast_presentation Asterisk number presentation.
411  *
412  * \return Equivalent PRI number presentation value.
413  */
414 static int ast_to_pri_presentation(int ast_presentation)
415 {
416         int pri_presentation;
417
418         switch (ast_presentation) {
419         case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
420                 pri_presentation = PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
421                 break;
422         case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
423                 pri_presentation = PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
424                 break;
425         case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
426                 pri_presentation = PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN;
427                 break;
428         case AST_PRES_ALLOWED_NETWORK_NUMBER:
429                 pri_presentation = PRES_ALLOWED_NETWORK_NUMBER;
430                 break;
431         case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
432                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
433                 break;
434         case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
435                 pri_presentation = PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
436                 break;
437         case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
438                 pri_presentation = PRES_PROHIB_USER_NUMBER_FAILED_SCREEN;
439                 break;
440         case AST_PRES_PROHIB_NETWORK_NUMBER:
441                 pri_presentation = PRES_PROHIB_NETWORK_NUMBER;
442                 break;
443         case AST_PRES_NUMBER_NOT_AVAILABLE:
444                 pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
445                 break;
446         default:
447                 pri_presentation = PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
448                 break;
449         }
450
451         return pri_presentation;
452 }
453
454 /*!
455  * \internal
456  * \brief Determine the overall presentation value for the given party.
457  * \since 1.8
458  *
459  * \param id Party to determine the overall presentation value.
460  *
461  * \return Overall presentation value for the given party converted to ast values.
462  */
463 static int overall_ast_presentation(const struct pri_party_id *id)
464 {
465         int number_priority;
466         int number_value;
467         int number_screening;
468         int name_priority;
469         int name_value;
470
471         /* Determine name presentation priority. */
472         if (!id->name.valid) {
473                 name_value = PRI_PRES_UNAVAILABLE;
474                 name_priority = 3;
475         } else {
476                 name_value = id->name.presentation & PRI_PRES_RESTRICTION;
477                 switch (name_value) {
478                 case PRI_PRES_RESTRICTED:
479                         name_priority = 0;
480                         break;
481                 case PRI_PRES_ALLOWED:
482                         name_priority = 1;
483                         break;
484                 case PRI_PRES_UNAVAILABLE:
485                         name_priority = 2;
486                         break;
487                 default:
488                         name_value = PRI_PRES_UNAVAILABLE;
489                         name_priority = 3;
490                         break;
491                 }
492         }
493
494         /* Determine number presentation priority. */
495         if (!id->number.valid) {
496                 number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
497                 number_value = PRI_PRES_UNAVAILABLE;
498                 number_priority = 3;
499         } else {
500                 number_screening = id->number.presentation & PRI_PRES_NUMBER_TYPE;
501                 number_value = id->number.presentation & PRI_PRES_RESTRICTION;
502                 switch (number_value) {
503                 case PRI_PRES_RESTRICTED:
504                         number_priority = 0;
505                         break;
506                 case PRI_PRES_ALLOWED:
507                         number_priority = 1;
508                         break;
509                 case PRI_PRES_UNAVAILABLE:
510                         number_priority = 2;
511                         break;
512                 default:
513                         number_screening = PRI_PRES_USER_NUMBER_UNSCREENED;
514                         number_value = PRI_PRES_UNAVAILABLE;
515                         number_priority = 3;
516                         break;
517                 }
518         }
519
520         /* Select the wining presentation value. */
521         if (name_priority < number_priority) {
522                 number_value = name_value;
523         }
524
525         return pri_to_ast_presentation(number_value | number_screening);
526 }
527
528 #if defined(HAVE_PRI_SUBADDR)
529 /*!
530  * \internal
531  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
532  * \since 1.8
533  *
534  * \param ast_subaddress Asterisk party subaddress structure.
535  * \param pri_subaddress PRI party subaddress structure.
536  *
537  * \return Nothing
538  *
539  */
540 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
541 {
542         char *cnum, *ptr;
543         int x, len;
544
545         if (ast_subaddress->str) {
546                 ast_free(ast_subaddress->str);
547         }
548         if (pri_subaddress->length <= 0) {
549                 ast_party_subaddress_init(ast_subaddress);
550                 return;
551         }
552
553         if (!pri_subaddress->type) {
554                 /* NSAP */
555                 ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
556         } else {
557                 /* User Specified */
558                 if (!(cnum = ast_malloc(2 * pri_subaddress->length + 1))) {
559                         ast_party_subaddress_init(ast_subaddress);
560                         return;
561                 }
562
563                 ptr = cnum;
564                 len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
565                 for (x = 0; x < len; ++x) {
566                         ptr += sprintf(ptr, "%02x", pri_subaddress->data[x]);
567                 }
568
569                 if (pri_subaddress->odd_even_indicator) {
570                         /* ODD */
571                         sprintf(ptr, "%01x", (pri_subaddress->data[len]) >> 4);
572                 } else {
573                         /* EVEN */
574                         sprintf(ptr, "%02x", pri_subaddress->data[len]);
575                 }
576                 ast_subaddress->str = cnum;
577         }
578         ast_subaddress->type = pri_subaddress->type;
579         ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
580         ast_subaddress->valid = 1;
581 }
582 #endif  /* defined(HAVE_PRI_SUBADDR) */
583
584 #if defined(HAVE_PRI_SUBADDR)
585 static unsigned char ast_pri_pack_hex_char(char c)
586 {
587         unsigned char res;
588
589         if (c < '0') {
590                 res = 0;
591         } else if (c < ('9' + 1)) {
592                 res = c - '0';
593         } else if (c < 'A') {
594                 res = 0;
595         } else if (c < ('F' + 1)) {
596                 res = c - 'A' + 10;
597         } else if (c < 'a') {
598                 res = 0;
599         } else if (c < ('f' + 1)) {
600                 res = c - 'a' + 10;
601         } else {
602                 res = 0;
603         }
604         return res;
605 }
606 #endif  /* defined(HAVE_PRI_SUBADDR) */
607
608 #if defined(HAVE_PRI_SUBADDR)
609 /*!
610  * \internal
611  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
612  * \details left justified, with 0 padding if odd length.
613  * \since 1.8
614  *
615  * \param dst pointer to packed byte array.
616  * \param src pointer to null terminated hexadecimal string.
617  * \param maxlen destination array size.
618  *
619  * \return Length of byte array
620  *
621  * \note The dst is not an ASCIIz string.
622  * \note The src is an ASCIIz hex string.
623  */
624 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
625 {
626         int res = 0;
627         int len = strlen(src);
628
629         if (len > (2 * maxlen)) {
630                 len = 2 * maxlen;
631         }
632
633         res = len / 2 + len % 2;
634
635         while (len > 1) {
636                 *dst = ast_pri_pack_hex_char(*src) << 4;
637                 src++;
638                 *dst |= ast_pri_pack_hex_char(*src);
639                 dst++, src++;
640                 len -= 2;
641         }
642         if (len) { /* 1 left */
643                 *dst = ast_pri_pack_hex_char(*src) << 4;
644         }
645         return res;
646 }
647 #endif  /* defined(HAVE_PRI_SUBADDR) */
648
649 #if defined(HAVE_PRI_SUBADDR)
650 /*!
651  * \internal
652  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
653  * \since 1.8
654  *
655  * \param pri_subaddress PRI party subaddress structure.
656  * \param ast_subaddress Asterisk party subaddress structure.
657  *
658  * \return Nothing
659  *
660  * \note Assumes that pri_subaddress has been previously memset to zero.
661  */
662 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
663 {
664         if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
665                 pri_subaddress->type = ast_subaddress->type;
666                 if (!ast_subaddress->type) {
667                         /* 0 = NSAP */
668                         ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
669                                 sizeof(pri_subaddress->data));
670                         pri_subaddress->length = strlen((char *) pri_subaddress->data);
671                         pri_subaddress->odd_even_indicator = 0;
672                         pri_subaddress->valid = 1;
673                 } else {
674                         /* 2 = User Specified */
675                         /*
676                          * Copy HexString to packed HexData,
677                          * if odd length then right pad trailing byte with 0
678                          */
679                         int length = ast_pri_pack_hex_string(pri_subaddress->data,
680                                 ast_subaddress->str, sizeof(pri_subaddress->data));
681
682                         pri_subaddress->length = length;
683                         pri_subaddress->odd_even_indicator = (length & 1);
684                         pri_subaddress->valid = 1;
685                 }
686         }
687 }
688 #endif  /* defined(HAVE_PRI_SUBADDR) */
689
690 /*!
691  * \internal
692  * \brief Fill in the PRI party id from the given asterisk party id.
693  * \since 1.8
694  *
695  * \param pri_id PRI party id structure.
696  * \param ast_id Asterisk party id structure.
697  *
698  * \return Nothing
699  *
700  * \note Assumes that pri_id has been previously memset to zero.
701  */
702 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
703 {
704         int presentation;
705
706         presentation = ast_to_pri_presentation(ast_id->number_presentation);
707         if (!ast_strlen_zero(ast_id->name)) {
708                 pri_id->name.valid = 1;
709                 pri_id->name.presentation = presentation;
710                 pri_id->name.char_set = PRI_CHAR_SET_ISO8859_1;
711                 ast_copy_string(pri_id->name.str, ast_id->name, sizeof(pri_id->name.str));
712         }
713         if (!ast_strlen_zero(ast_id->number)) {
714                 pri_id->number.valid = 1;
715                 pri_id->number.presentation = presentation;
716                 pri_id->number.plan = ast_id->number_type;
717                 ast_copy_string(pri_id->number.str, ast_id->number, sizeof(pri_id->number.str));
718         }
719 #if defined(HAVE_PRI_SUBADDR)
720         sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
721 #endif  /* defined(HAVE_PRI_SUBADDR) */
722 }
723
724 /*!
725  * \internal
726  * \brief Update the PRI redirecting information for the current call.
727  * \since 1.8
728  *
729  * \param pvt sig_pri private channel structure.
730  * \param ast Asterisk channel
731  *
732  * \return Nothing
733  *
734  * \note Assumes that the PRI lock is already obtained.
735  */
736 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
737 {
738         struct pri_party_redirecting pri_redirecting;
739
740 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
741
742         memset(&pri_redirecting, 0, sizeof(pri_redirecting));
743         sig_pri_party_id_from_ast(&pri_redirecting.from, &ast->redirecting.from);
744         sig_pri_party_id_from_ast(&pri_redirecting.to, &ast->redirecting.to);
745         pri_redirecting.count = ast->redirecting.count;
746         pri_redirecting.reason = ast_to_pri_reason(ast->redirecting.reason);
747
748         pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
749 }
750
751 /*!
752  * \internal
753  * \brief Reset DTMF detector.
754  * \since 1.8
755  *
756  * \param p sig_pri channel structure.
757  *
758  * \return Nothing
759  */
760 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
761 {
762         if (p->calls->dsp_reset_and_flush_digits) {
763                 p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
764         }
765 }
766
767 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
768 {
769         if (p->calls->set_echocanceller)
770                 return p->calls->set_echocanceller(p->chan_pvt, enable);
771         else
772                 return -1;
773 }
774
775 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
776 {
777         if (old_chan->calls->fixup_chans)
778                 old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
779 }
780
781 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
782 {
783         if (p->calls->play_tone)
784                 return p->calls->play_tone(p->chan_pvt, tone);
785         else
786                 return -1;
787 }
788
789 static struct ast_channel *sig_pri_new_ast_channel(struct sig_pri_chan *p, int state, int startpbx, int ulaw, int transfercapability, char *exten, const struct ast_channel *requestor)
790 {
791         struct ast_channel *c;
792
793         if (p->calls->new_ast_channel)
794                 c = p->calls->new_ast_channel(p->chan_pvt, state, startpbx, ulaw, transfercapability, exten, requestor);
795         else
796                 return NULL;
797
798         if (!p->owner)
799                 p->owner = c;
800         p->isidlecall = 0;
801         p->alreadyhungup = 0;
802         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
803                 c->transfercapability = transfercapability;
804                 pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
805                 sig_pri_set_digital(p, 1);
806         }
807         if (p->pri && !pri_grab(p, p->pri)) {
808                 sig_pri_span_devstate_changed(p->pri);
809                 pri_rel(p->pri);
810         } else {
811                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
812         }
813
814         return c;
815 }
816
817 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
818 {
819         struct ast_channel *ast;
820
821         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
822
823         p->outgoing = 1;
824         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, 0, law, transfercapability, p->exten, requestor);
825         if (!ast) {
826                 p->outgoing = 0;
827         }
828         return ast;
829 }
830
831 int pri_is_up(struct sig_pri_pri *pri)
832 {
833         int x;
834         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
835                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
836                         return 1;
837         }
838         return 0;
839 }
840
841 static char *pri_order(int level)
842 {
843         switch (level) {
844         case 0:
845                 return "Primary";
846         case 1:
847                 return "Secondary";
848         case 2:
849                 return "Tertiary";
850         case 3:
851                 return "Quaternary";
852         default:
853                 return "<Unknown>";
854         }
855 }
856
857 /* Returns index of the active dchan */
858 static int pri_active_dchan_index(struct sig_pri_pri *pri)
859 {
860         int x;
861
862         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
863                 if ((pri->dchans[x] == pri->pri))
864                         return x;
865         }
866
867         ast_log(LOG_WARNING, "No active dchan found!\n");
868         return -1;
869 }
870
871 static int pri_find_dchan(struct sig_pri_pri *pri)
872 {
873         int oldslot = -1;
874         struct pri *old;
875         int newslot = -1;
876         int x;
877         old = pri->pri;
878         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
879                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
880                         newslot = x;
881                 if (pri->dchans[x] == old) {
882                         oldslot = x;
883                 }
884         }
885         if (newslot < 0) {
886                 newslot = 0;
887                 /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
888                 if (pri->sig != SIG_BRI_PTMP) {
889                         ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel as D-channel anyway!\n");
890                 }
891         }
892         if (old && (oldslot != newslot))
893                 ast_log(LOG_NOTICE, "Switching from d-channel fd %d to fd %d!\n",
894                         pri->fds[oldslot], pri->fds[newslot]);
895         pri->pri = pri->dchans[newslot];
896         return 0;
897 }
898
899 /*!
900  * \internal
901  * \brief Obtain the sig_pri owner channel lock if the owner exists.
902  * \since 1.8
903  *
904  * \param pri sig_pri PRI control structure.
905  * \param chanpos Channel position in the span.
906  *
907  * \note Assumes the pri->lock is already obtained.
908  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
909  *
910  * \return Nothing
911  */
912 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
913 {
914         for (;;) {
915                 if (!pri->pvts[chanpos]->owner) {
916                         /* There is no owner lock to get. */
917                         break;
918                 }
919                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
920                         /* We got the lock */
921                         break;
922                 }
923                 /* We must unlock the PRI to avoid the possibility of a deadlock */
924                 ast_mutex_unlock(&pri->lock);
925                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
926                 ast_mutex_lock(&pri->lock);
927         }
928 }
929
930 /*!
931  * \internal
932  * \brief Queue the given frame onto the owner channel.
933  * \since 1.8
934  *
935  * \param pri sig_pri PRI control structure.
936  * \param chanpos Channel position in the span.
937  * \param frame Frame to queue onto the owner channel.
938  *
939  * \note Assumes the pri->lock is already obtained.
940  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
941  *
942  * \return Nothing
943  */
944 static void pri_queue_frame(struct sig_pri_pri *pri, int chanpos, struct ast_frame *frame)
945 {
946         sig_pri_lock_owner(pri, chanpos);
947         if (pri->pvts[chanpos]->owner) {
948                 ast_queue_frame(pri->pvts[chanpos]->owner, frame);
949                 ast_channel_unlock(pri->pvts[chanpos]->owner);
950         }
951 }
952
953 /*!
954  * \internal
955  * \brief Queue a control frame of the specified subclass onto the owner channel.
956  * \since 1.8
957  *
958  * \param pri sig_pri PRI control structure.
959  * \param chanpos Channel position in the span.
960  * \param subclass Control frame subclass to queue onto the owner channel.
961  *
962  * \note Assumes the pri->lock is already obtained.
963  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
964  *
965  * \return Nothing
966  */
967 static void pri_queue_control(struct sig_pri_pri *pri, int chanpos, int subclass)
968 {
969         struct ast_frame f = {AST_FRAME_CONTROL, };
970         struct sig_pri_chan *p = pri->pvts[chanpos];
971
972         if (p->calls->queue_control) {
973                 p->calls->queue_control(p->chan_pvt, subclass);
974         }
975
976         f.subclass.integer = subclass;
977         pri_queue_frame(pri, chanpos, &f);
978 }
979
980 static int pri_find_principle(struct sig_pri_pri *pri, int channel, q931_call *call)
981 {
982         int x;
983         int span;
984         int principle;
985
986         if (channel < 0) {
987                 /* Channel is not picked yet. */
988                 return -1;
989         }
990
991         if (channel & PRI_HELD_CALL) {
992                 if (!call) {
993                         /* Cannot find a held call without a call. */
994                         return -1;
995                 }
996                 principle = -1;
997                 for (x = 0; x < pri->numchans; ++x) {
998                         if (pri->pvts[x]
999                                 && pri->pvts[x]->call == call) {
1000                                 principle = x;
1001                                 break;
1002                         }
1003                 }
1004                 return principle;
1005         }
1006
1007         span = PRI_SPAN(channel);
1008         if (!(channel & PRI_EXPLICIT)) {
1009                 int index;
1010
1011                 index = pri_active_dchan_index(pri);
1012                 if (index == -1) {
1013                         return -1;
1014                 }
1015                 span = pri->dchan_logical_span[index];
1016         }
1017
1018         channel = PRI_CHANNEL(channel);
1019         principle = -1;
1020         for (x = 0; x < pri->numchans; x++) {
1021                 if (pri->pvts[x]
1022                         && pri->pvts[x]->prioffset == channel
1023                         && pri->pvts[x]->logicalspan == span
1024                         && !pri->pvts[x]->no_b_channel) {
1025                         principle = x;
1026                         break;
1027                 }
1028         }
1029
1030         return principle;
1031 }
1032
1033 static int pri_fixup_principle(struct sig_pri_pri *pri, int principle, q931_call *call)
1034 {
1035         int x;
1036
1037         if (principle < 0 || pri->numchans <= principle) {
1038                 /* Out of rannge */
1039                 return -1;
1040         }
1041         if (!call) {
1042                 /* No call */
1043                 return principle;
1044         }
1045         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
1046                 /* Call is already on the specified principle. */
1047                 return principle;
1048         }
1049
1050         /* Find the old principle location. */
1051         for (x = 0; x < pri->numchans; x++) {
1052                 struct sig_pri_chan *new_chan;
1053                 struct sig_pri_chan *old_chan;
1054
1055                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
1056                         continue;
1057                 }
1058
1059                 /* Found our call */
1060                 new_chan = pri->pvts[principle];
1061                 old_chan = pri->pvts[x];
1062
1063                 ast_verb(3, "Moving call from channel %d to channel %d\n",
1064                         old_chan->channel, new_chan->channel);
1065                 if (new_chan->owner) {
1066                         ast_log(LOG_WARNING,
1067                                 "Can't fix up channel from %d to %d because %d is already in use\n",
1068                                 old_chan->channel, new_chan->channel, new_chan->channel);
1069                         return -1;
1070                 }
1071
1072                 sig_pri_fixup_chans(old_chan, new_chan);
1073
1074                 /* Fix it all up now */
1075                 new_chan->owner = old_chan->owner;
1076                 old_chan->owner = NULL;
1077
1078                 new_chan->call = old_chan->call;
1079                 old_chan->call = NULL;
1080
1081                 /* Transfer flags from the old channel. */
1082                 new_chan->alerting = old_chan->alerting;
1083                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1084                 new_chan->isidlecall = old_chan->isidlecall;
1085                 new_chan->proceeding = old_chan->proceeding;
1086                 new_chan->progress = old_chan->progress;
1087                 new_chan->setup_ack = old_chan->setup_ack;
1088                 new_chan->outgoing = old_chan->outgoing;
1089                 new_chan->digital = old_chan->digital;
1090 #if defined(HAVE_PRI_AOC_EVENTS)
1091                 new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
1092                 new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
1093                 new_chan->holding_aoce = old_chan->holding_aoce;
1094                 new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
1095                 new_chan->aoc_e = old_chan->aoc_e;
1096
1097                 old_chan->holding_aoce = 0;
1098                 old_chan->aoc_s_request_invoke_id_valid = 0;
1099                 old_chan->waiting_for_aoce = 0;
1100                 memset(&old_chan->aoc_e, 0, sizeof(&old_chan->aoc_e));
1101 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1102                 old_chan->alerting = 0;
1103                 old_chan->alreadyhungup = 0;
1104                 old_chan->isidlecall = 0;
1105                 old_chan->proceeding = 0;
1106                 old_chan->progress = 0;
1107                 old_chan->setup_ack = 0;
1108                 old_chan->outgoing = 0;
1109                 old_chan->digital = 0;
1110
1111                 /* More stuff to transfer to the new channel. */
1112 #if defined(HAVE_PRI_REVERSE_CHARGE)
1113                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1114 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1115 #if defined(HAVE_PRI_SETUP_KEYPAD)
1116                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1117 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1118
1119                 if (new_chan->no_b_channel) {
1120                         /* Copy the real channel configuration to the no B channel interface. */
1121                         new_chan->hidecallerid = old_chan->hidecallerid;
1122                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1123                         new_chan->immediate = old_chan->immediate;
1124                         new_chan->priexclusive = old_chan->priexclusive;
1125                         new_chan->priindication_oob = old_chan->priindication_oob;
1126                         new_chan->use_callerid = old_chan->use_callerid;
1127                         new_chan->use_callingpres = old_chan->use_callingpres;
1128                         new_chan->stripmsd = old_chan->stripmsd;
1129                         strcpy(new_chan->context, old_chan->context);
1130                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1131
1132                         /* Become a member of the old channel span/trunk-group. */
1133                         new_chan->logicalspan = old_chan->logicalspan;
1134                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1135                 }
1136
1137                 return principle;
1138         }
1139         ast_verb(3, "Call specified, but not found.\n");
1140         return -1;
1141 }
1142
1143 static char * redirectingreason2str(int redirectingreason)
1144 {
1145         switch (redirectingreason) {
1146         case 0:
1147                 return "UNKNOWN";
1148         case 1:
1149                 return "BUSY";
1150         case 2:
1151                 return "NO_REPLY";
1152         case 0xF:
1153                 return "UNCONDITIONAL";
1154         default:
1155                 return "NOREDIRECT";
1156         }
1157 }
1158
1159 static char *dialplan2str(int dialplan)
1160 {
1161         if (dialplan == -1) {
1162                 return("Dynamically set dialplan in ISDN");
1163         }
1164         return (pri_plan2str(dialplan));
1165 }
1166
1167 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_pri *pri, const char *number, const int plan)
1168 {
1169         switch (plan) {
1170         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1171                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1172                 break;
1173         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1174                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1175                 break;
1176         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1177                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1178                 break;
1179         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1180                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1181                 break;
1182         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1183                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1184                 break;
1185         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1186                 snprintf(buf, size, "%s", number);
1187                 break;
1188         }
1189 }
1190
1191 /*! \note Assumes the pri->lock is already obtained. */
1192 static int pri_check_restart(struct sig_pri_pri *pri)
1193 {
1194 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1195 tryanotherpos:
1196 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1197         do {
1198                 pri->resetpos++;
1199         } while (pri->resetpos < pri->numchans
1200                 && (!pri->pvts[pri->resetpos]
1201                         || pri->pvts[pri->resetpos]->no_b_channel
1202                         || pri->pvts[pri->resetpos]->call
1203                         || pri->pvts[pri->resetpos]->resetting));
1204         if (pri->resetpos < pri->numchans) {
1205 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1206                 unsigned why;
1207
1208                 why = pri->pvts[pri->resetpos]->service_status;
1209                 if (why) {
1210                         ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1211                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1212                         goto tryanotherpos;
1213                 }
1214 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1215
1216                 /* Mark the channel as resetting and restart it */
1217                 pri->pvts[pri->resetpos]->resetting = 1;
1218                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1219         } else {
1220                 pri->resetting = 0;
1221                 time(&pri->lastreset);
1222         }
1223         return 0;
1224 }
1225
1226 static int pri_find_empty_chan(struct sig_pri_pri *pri, int backwards)
1227 {
1228         int x;
1229         if (backwards)
1230                 x = pri->numchans;
1231         else
1232                 x = 0;
1233         for (;;) {
1234                 if (backwards && (x < 0))
1235                         break;
1236                 if (!backwards && (x >= pri->numchans))
1237                         break;
1238                 if (pri->pvts[x]
1239                         && !pri->pvts[x]->no_b_channel
1240                         && !pri->pvts[x]->inalarm
1241                         && !pri->pvts[x]->owner) {
1242                         ast_debug(1, "Found empty available channel %d/%d\n",
1243                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1244                         return x;
1245                 }
1246                 if (backwards)
1247                         x--;
1248                 else
1249                         x++;
1250         }
1251         return -1;
1252 }
1253
1254 #if defined(HAVE_PRI_CALL_HOLD)
1255 /*!
1256  * \internal
1257  * \brief Find or create an empty no-B-channel interface to use.
1258  * \since 1.8
1259  *
1260  * \param pri sig_pri span controller to find interface.
1261  *
1262  * \note Assumes the pri->lock is already obtained.
1263  *
1264  * \retval array-index into private pointer array on success.
1265  * \retval -1 on error.
1266  */
1267 static int pri_find_empty_nobch(struct sig_pri_pri *pri)
1268 {
1269         int idx;
1270
1271         for (idx = 0; idx < pri->numchans; ++idx) {
1272                 if (pri->pvts[idx]
1273                         && pri->pvts[idx]->no_b_channel
1274                         && !pri->pvts[idx]->inalarm
1275                         && !pri->pvts[idx]->owner) {
1276                         ast_debug(1, "Found empty available no B channel interface\n");
1277                         return idx;
1278                 }
1279         }
1280
1281         /* Need to create a new interface. */
1282         if (pri->calls->new_nobch_intf) {
1283                 idx = pri->calls->new_nobch_intf(pri);
1284         } else {
1285                 idx = -1;
1286         }
1287         return idx;
1288 }
1289 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1290
1291 #if defined(HAVE_PRI_CALL_HOLD)
1292 /*!
1293  * \internal
1294  * \brief Find the channel associated with the libpri call.
1295  * \since 1.8
1296  *
1297  * \param pri sig_pri span controller to find interface.
1298  * \param call LibPRI opaque call pointer to find.
1299  *
1300  * \note Assumes the pri->lock is already obtained.
1301  *
1302  * \retval array-index into private pointer array on success.
1303  * \retval -1 on error.
1304  */
1305 static int pri_find_pri_call(struct sig_pri_pri *pri, q931_call *call)
1306 {
1307         int idx;
1308
1309         for (idx = 0; idx < pri->numchans; ++idx) {
1310                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1311                         /* Found the channel */
1312                         return idx;
1313                 }
1314         }
1315         return -1;
1316 }
1317 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1318
1319 static void *do_idle_thread(void *v_pvt)
1320 {
1321         struct sig_pri_chan *pvt = v_pvt;
1322         struct ast_channel *chan = pvt->owner;
1323         struct ast_frame *f;
1324         char ex[80];
1325         /* Wait up to 30 seconds for an answer */
1326         int newms, ms = 30000;
1327
1328         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1329         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1330         if (ast_call(chan, ex, 0)) {
1331                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1332                 ast_hangup(chan);
1333                 return NULL;
1334         }
1335         while ((newms = ast_waitfor(chan, ms)) > 0) {
1336                 f = ast_read(chan);
1337                 if (!f) {
1338                         /* Got hangup */
1339                         break;
1340                 }
1341                 if (f->frametype == AST_FRAME_CONTROL) {
1342                         switch (f->subclass.integer) {
1343                         case AST_CONTROL_ANSWER:
1344                                 /* Launch the PBX */
1345                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1346                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1347                                 chan->priority = 1;
1348                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1349                                 ast_pbx_run(chan);
1350                                 /* It's already hungup, return immediately */
1351                                 return NULL;
1352                         case AST_CONTROL_BUSY:
1353                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1354                                 break;
1355                         case AST_CONTROL_CONGESTION:
1356                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1357                                 break;
1358                         };
1359                 }
1360                 ast_frfree(f);
1361                 ms = newms;
1362         }
1363         /* Hangup the channel since nothing happend */
1364         ast_hangup(chan);
1365         return NULL;
1366 }
1367
1368 static void *pri_ss_thread(void *data)
1369 {
1370         struct sig_pri_chan *p = data;
1371         struct ast_channel *chan = p->owner;
1372         char exten[AST_MAX_EXTENSION];
1373         int res;
1374         int len;
1375         int timeout;
1376
1377         if (!chan) {
1378                 /* We lost the owner before we could get started. */
1379                 return NULL;
1380         }
1381
1382         /*
1383          * In the bizarre case where the channel has become a zombie before we
1384          * even get started here, abort safely.
1385          */
1386         if (!chan->tech_pvt) {
1387                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1388                 ast_hangup(chan);
1389                 return NULL;
1390         }
1391
1392         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1393
1394         sig_pri_dsp_reset_and_flush_digits(p);
1395
1396         /* Now loop looking for an extension */
1397         ast_copy_string(exten, p->exten, sizeof(exten));
1398         len = strlen(exten);
1399         res = 0;
1400         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1401                 if (len && !ast_ignore_pattern(chan->context, exten))
1402                         sig_pri_play_tone(p, -1);
1403                 else
1404                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1405                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1406                         timeout = pri_matchdigittimeout;
1407                 else
1408                         timeout = pri_gendigittimeout;
1409                 res = ast_waitfordigit(chan, timeout);
1410                 if (res < 0) {
1411                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
1412                         ast_hangup(chan);
1413                         return NULL;
1414                 } else if (res) {
1415                         exten[len++] = res;
1416                         exten[len] = '\0';
1417                 } else
1418                         goto exit;
1419         }
1420         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1421         if (ast_strlen_zero(exten)) {
1422                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1423                 exten[0] = 's';
1424                 exten[1] = '\0';
1425         } else {
1426                 if (chan->cid.cid_dnid) {
1427                         ast_free(chan->cid.cid_dnid);
1428                 }
1429                 chan->cid.cid_dnid = ast_strdup(exten);
1430         }
1431         sig_pri_play_tone(p, -1);
1432         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1433                 /* Start the real PBX */
1434                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1435                 sig_pri_dsp_reset_and_flush_digits(p);
1436                 if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
1437                         if (p->pri->pri) {              
1438                                 if (!pri_grab(p, p->pri)) {
1439                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1440                                         p->proceeding = 1;
1441                                         pri_rel(p->pri);
1442                                 } else {
1443                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1444                                 }
1445                         }
1446                 }
1447
1448                 sig_pri_set_echocanceller(p, 1);
1449                 ast_setstate(chan, AST_STATE_RING);
1450                 res = ast_pbx_run(chan);
1451                 if (res) {
1452                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1453                 }
1454         } else {
1455                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1456                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1457                 ast_hangup(chan);
1458                 p->exten[0] = '\0';
1459                 /* Since we send release complete here, we won't get one */
1460                 p->call = NULL;
1461         }
1462         return NULL;
1463
1464 exit:
1465         res = sig_pri_play_tone(p, SIG_PRI_TONE_CONGESTION);
1466         if (res < 0)
1467                 ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
1468         ast_hangup(chan);
1469         return NULL;
1470 }
1471
1472 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1473 {
1474         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1475         if (!before_start_pri)
1476                 pri_find_dchan(pri);
1477 }
1478
1479 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1480 {
1481         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1482         if (!before_start_pri)
1483                 pri_restart(pri->dchans[index]);
1484 }
1485
1486 /*!
1487  * \internal
1488  * \brief Convert libpri party id into asterisk party id.
1489  * \since 1.8
1490  *
1491  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1492  * \param pri_id libpri party id structure containing source information.
1493  * \param pri Span controlling structure.
1494  *
1495  * \note The filled in ast_id structure needs to be destroyed by
1496  * ast_party_id_free() when it is no longer needed.
1497  *
1498  * \return Nothing
1499  */
1500 static void sig_pri_party_id_convert(struct ast_party_id *ast_id,
1501         const struct pri_party_id *pri_id, struct sig_pri_pri *pri)
1502 {
1503         char number[AST_MAX_EXTENSION];
1504
1505         if (pri_id->name.valid) {
1506                 ast_id->name = ast_strdup(pri_id->name.str);
1507         }
1508         if (pri_id->number.valid) {
1509                 apply_plan_to_number(number, sizeof(number), pri, pri_id->number.str,
1510                         pri_id->number.plan);
1511                 ast_id->number = ast_strdup(number);
1512                 ast_id->number_type = pri_id->number.plan;
1513         }
1514         if (pri_id->name.valid || pri_id->number.valid) {
1515                 ast_id->number_presentation = overall_ast_presentation(pri_id);
1516         }
1517 #if defined(HAVE_PRI_SUBADDR)
1518         if (pri_id->subaddress.valid) {
1519                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1520         }
1521 #endif  /* defined(HAVE_PRI_SUBADDR) */
1522 }
1523
1524 /*!
1525  * \internal
1526  * \brief Convert libpri redirecting information into asterisk redirecting information.
1527  * \since 1.8
1528  *
1529  * \param ast_redirecting Asterisk redirecting structure to fill.
1530  * \param pri_redirecting libpri redirecting structure containing source information.
1531  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1532  * \param pri Span controlling structure.
1533  *
1534  * \note The filled in ast_redirecting structure needs to be destroyed by
1535  * ast_party_redirecting_free() when it is no longer needed.
1536  *
1537  * \return Nothing
1538  */
1539 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1540         const struct pri_party_redirecting *pri_redirecting,
1541         const struct ast_party_redirecting *ast_guide,
1542         struct sig_pri_pri *pri)
1543 {
1544         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1545
1546         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1547         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1548         ast_redirecting->count = pri_redirecting->count;
1549         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1550 }
1551
1552 /*!
1553  * \internal
1554  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1555  * \since 1.8
1556  *
1557  * \param msn_patterns Comma separated list of MSN patterns to match.
1558  * \param exten Extension to match in the MSN list.
1559  *
1560  * \retval 1 if matches.
1561  * \retval 0 if no match.
1562  */
1563 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1564 {
1565         char *pattern;
1566         char *msn_list;
1567         char *list_tail;
1568
1569         msn_list = strdupa(msn_patterns);
1570
1571         list_tail = NULL;
1572         pattern = strtok_r(msn_list, ",", &list_tail);
1573         while (pattern) {
1574                 pattern = ast_strip(pattern);
1575                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1576                         /* Extension matched the pattern. */
1577                         return 1;
1578                 }
1579                 pattern = strtok_r(NULL, ",", &list_tail);
1580         }
1581         /* Did not match any pattern in the list. */
1582         return 0;
1583 }
1584
1585 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
1586 /*!
1587  * \internal
1588  * \brief Attempt to transfer the two calls to each other.
1589  * \since 1.8
1590  *
1591  * \param pri sig_pri PRI control structure.
1592  * \param call_1 First call involved in the transfer.
1593  * \param call_1_held TRUE if call_1 is on hold.
1594  * \param call_2 Second call involved in the transfer.
1595  * \param call_2_held TRUE if call_2 is on hold.
1596  *
1597  * \note Assumes the pri->lock is already obtained.
1598  *
1599  * \retval 0 on success.
1600  * \retval -1 on error.
1601  */
1602 static int sig_pri_attempt_transfer(struct sig_pri_pri *pri, q931_call *call_1, int call_1_held, q931_call *call_2, int call_2_held)
1603 {
1604         int retval;
1605         int call_1_chanpos;
1606         int call_2_chanpos;
1607         struct ast_channel *call_1_ast;
1608         struct ast_channel *call_2_ast;
1609         struct ast_channel *bridged;
1610
1611         call_1_chanpos = pri_find_pri_call(pri, call_1);
1612         call_2_chanpos = pri_find_pri_call(pri, call_2);
1613         if (call_1_chanpos < 0 || call_2_chanpos < 0) {
1614                 return -1;
1615         }
1616
1617         /* Deadlock avoidance is attempted. */
1618         sig_pri_lock_private(pri->pvts[call_1_chanpos]);
1619         sig_pri_lock_owner(pri, call_1_chanpos);
1620         sig_pri_lock_private(pri->pvts[call_2_chanpos]);
1621         sig_pri_lock_owner(pri, call_2_chanpos);
1622
1623         call_1_ast = pri->pvts[call_1_chanpos]->owner;
1624         call_2_ast = pri->pvts[call_2_chanpos]->owner;
1625         if (!call_1_ast || !call_2_ast) {
1626                 if (call_1_ast) {
1627                         ast_channel_unlock(call_1_ast);
1628                 }
1629                 if (call_2_ast) {
1630                         ast_channel_unlock(call_2_ast);
1631                 }
1632                 sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1633                 sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1634                 return -1;
1635         }
1636
1637         bridged = ast_bridged_channel(call_2_ast);
1638         if (bridged) {
1639                 if (call_1_held) {
1640                         ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1641                 }
1642                 if (call_2_held) {
1643                         ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1644                 }
1645
1646                 ast_verb(3, "TRANSFERRING %s to %s\n", call_2_ast->name, call_1_ast->name);
1647                 retval = ast_channel_masquerade(call_1_ast, bridged);
1648         } else {
1649                 /* Try masquerading the other way. */
1650                 bridged = ast_bridged_channel(call_1_ast);
1651                 if (bridged) {
1652                         if (call_1_held) {
1653                                 ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1654                         }
1655                         if (call_2_held) {
1656                                 ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1657                         }
1658
1659                         ast_verb(3, "TRANSFERRING %s to %s\n", call_1_ast->name, call_2_ast->name);
1660                         retval = ast_channel_masquerade(call_2_ast, bridged);
1661                 } else {
1662                         /* Could not transfer. */
1663                         retval = -1;
1664                 }
1665         }
1666         if (bridged && retval) {
1667                 /* Restore HOLD on held calls because masquerade failed. */
1668                 if (call_1_held) {
1669                         ast_queue_control(call_1_ast, AST_CONTROL_HOLD);
1670                 }
1671                 if (call_2_held) {
1672                         ast_queue_control(call_2_ast, AST_CONTROL_HOLD);
1673                 }
1674         }
1675
1676         ast_channel_unlock(call_1_ast);
1677         ast_channel_unlock(call_2_ast);
1678         sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1679         sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1680
1681         return retval;
1682 }
1683 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
1684
1685 #if defined(HAVE_PRI_CCSS)
1686 /*!
1687  * \internal
1688  * \brief Compare the CC agent private data by libpri cc_id.
1689  * \since 1.8
1690  *
1691  * \param obj pointer to the (user-defined part) of an object.
1692  * \param arg callback argument from ao2_callback()
1693  * \param flags flags from ao2_callback()
1694  *
1695  * \return values are a combination of enum _cb_results.
1696  */
1697 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
1698 {
1699         struct ast_cc_agent *agent_1 = obj;
1700         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
1701         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
1702
1703         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
1704                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1705 }
1706 #endif  /* defined(HAVE_PRI_CCSS) */
1707
1708 #if defined(HAVE_PRI_CCSS)
1709 /*!
1710  * \internal
1711  * \brief Find the CC agent by libpri cc_id.
1712  * \since 1.8
1713  *
1714  * \param pri sig_pri PRI control structure.
1715  * \param cc_id CC record ID to find.
1716  *
1717  * \note
1718  * Since agents are refcounted, and this function returns
1719  * a reference to the agent, it is imperative that you decrement
1720  * the refcount of the agent once you have finished using it.
1721  *
1722  * \retval agent on success.
1723  * \retval NULL not found.
1724  */
1725 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1726 {
1727         struct sig_pri_cc_agent_prv finder = {
1728                 .pri = pri,
1729                 .cc_id = cc_id,
1730         };
1731
1732         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
1733                 sig_pri_cc_type_name);
1734 }
1735 #endif  /* defined(HAVE_PRI_CCSS) */
1736
1737 #if defined(HAVE_PRI_CCSS)
1738 /*!
1739  * \internal
1740  * \brief Compare the CC monitor instance by libpri cc_id.
1741  * \since 1.8
1742  *
1743  * \param obj pointer to the (user-defined part) of an object.
1744  * \param arg callback argument from ao2_callback()
1745  * \param flags flags from ao2_callback()
1746  *
1747  * \return values are a combination of enum _cb_results.
1748  */
1749 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
1750 {
1751         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
1752         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
1753
1754         return (monitor_1->pri == monitor_2->pri
1755                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1756 }
1757 #endif  /* defined(HAVE_PRI_CCSS) */
1758
1759 #if defined(HAVE_PRI_CCSS)
1760 /*!
1761  * \internal
1762  * \brief Find the CC monitor instance by libpri cc_id.
1763  * \since 1.8
1764  *
1765  * \param pri sig_pri PRI control structure.
1766  * \param cc_id CC record ID to find.
1767  *
1768  * \note
1769  * Since monitor_instances are refcounted, and this function returns
1770  * a reference to the instance, it is imperative that you decrement
1771  * the refcount of the instance once you have finished using it.
1772  *
1773  * \retval monitor_instance on success.
1774  * \retval NULL not found.
1775  */
1776 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1777 {
1778         struct sig_pri_cc_monitor_instance finder = {
1779                 .pri = pri,
1780                 .cc_id = cc_id,
1781         };
1782
1783         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
1784 }
1785 #endif  /* defined(HAVE_PRI_CCSS) */
1786
1787 #if defined(HAVE_PRI_CCSS)
1788 /*!
1789  * \internal
1790  * \brief Destroy the given monitor instance.
1791  * \since 1.8
1792  *
1793  * \param data Monitor instance to destroy.
1794  *
1795  * \return Nothing
1796  */
1797 static void sig_pri_cc_monitor_instance_destroy(void *data)
1798 {
1799         struct sig_pri_cc_monitor_instance *monitor_instance = data;
1800
1801         if (monitor_instance->cc_id != -1) {
1802                 ast_mutex_lock(&monitor_instance->pri->lock);
1803                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
1804                 ast_mutex_unlock(&monitor_instance->pri->lock);
1805         }
1806         monitor_instance->pri->calls->module_unref();
1807 }
1808 #endif  /* defined(HAVE_PRI_CCSS) */
1809
1810 #if defined(HAVE_PRI_CCSS)
1811 /*!
1812  * \internal
1813  * \brief Construct a new monitor instance.
1814  * \since 1.8
1815  *
1816  * \param core_id CC core ID.
1817  * \param pri sig_pri PRI control structure.
1818  * \param cc_id CC record ID.
1819  * \param device_name Name of device (Asterisk channel name less sequence number).
1820  *
1821  * \note
1822  * Since monitor_instances are refcounted, and this function returns
1823  * a reference to the instance, it is imperative that you decrement
1824  * the refcount of the instance once you have finished using it.
1825  *
1826  * \retval monitor_instance on success.
1827  * \retval NULL on error.
1828  */
1829 static struct sig_pri_cc_monitor_instance *sig_pri_cc_monitor_instance_init(int core_id, struct sig_pri_pri *pri, long cc_id, const char *device_name)
1830 {
1831         struct sig_pri_cc_monitor_instance *monitor_instance;
1832
1833         if (!pri->calls->module_ref || !pri->calls->module_unref) {
1834                 return NULL;
1835         }
1836
1837         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
1838                 sig_pri_cc_monitor_instance_destroy);
1839         if (!monitor_instance) {
1840                 return NULL;
1841         }
1842
1843         monitor_instance->cc_id = cc_id;
1844         monitor_instance->pri = pri;
1845         monitor_instance->core_id = core_id;
1846         strcpy(monitor_instance->name, device_name);
1847
1848         pri->calls->module_ref();
1849
1850         ao2_link(sig_pri_cc_monitors, monitor_instance);
1851         return monitor_instance;
1852 }
1853 #endif  /* defined(HAVE_PRI_CCSS) */
1854
1855 #if defined(HAVE_PRI_CCSS)
1856 /*!
1857  * \internal
1858  * \brief Announce to the CC core that protocol CC monitor is available for this call.
1859  * \since 1.8
1860  *
1861  * \param pri sig_pri PRI control structure.
1862  * \param chanpos Channel position in the span.
1863  * \param cc_id CC record ID.
1864  * \param service CCBS/CCNR indication.
1865  *
1866  * \note Assumes the pri->lock is already obtained.
1867  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1868  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
1869  *
1870  * \retval 0 on success.
1871  * \retval -1 on error.
1872  */
1873 static int sig_pri_cc_available(struct sig_pri_pri *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
1874 {
1875         struct sig_pri_chan *pvt;
1876         struct ast_cc_config_params *cc_params;
1877         struct sig_pri_cc_monitor_instance *monitor;
1878         enum ast_cc_monitor_policies monitor_policy;
1879         int core_id;
1880         int res;
1881         char device_name[AST_CHANNEL_NAME];
1882         char dialstring[AST_CHANNEL_NAME];
1883
1884         pvt = pri->pvts[chanpos];
1885
1886         core_id = ast_cc_get_current_core_id(pvt->owner);
1887         if (core_id == -1) {
1888                 return -1;
1889         }
1890
1891         cc_params = ast_channel_get_cc_config_params(pvt->owner);
1892         if (!cc_params) {
1893                 return -1;
1894         }
1895
1896         res = -1;
1897         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1898         switch (monitor_policy) {
1899         case AST_CC_MONITOR_NEVER:
1900                 /* CCSS is not enabled. */
1901                 break;
1902         case AST_CC_MONITOR_NATIVE:
1903         case AST_CC_MONITOR_ALWAYS:
1904                 /*
1905                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
1906                  * later in the call to sig_pri_cc_generic_check().
1907                  */
1908                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
1909                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
1910                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
1911                 if (!monitor) {
1912                         break;
1913                 }
1914                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
1915                         monitor);
1916                 if (res) {
1917                         monitor->cc_id = -1;
1918                         ao2_unlink(sig_pri_cc_monitors, monitor);
1919                         ao2_ref(monitor, -1);
1920                 }
1921                 break;
1922         case AST_CC_MONITOR_GENERIC:
1923                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
1924                         sig_pri_get_orig_dialstring(pvt), service, NULL);
1925                 /* Say it failed to force caller to cancel native CC. */
1926                 break;
1927         }
1928         return res;
1929 }
1930 #endif  /* defined(HAVE_PRI_CCSS) */
1931
1932 /*!
1933  * \internal
1934  * \brief Check if generic CC monitor is needed and request it.
1935  * \since 1.8
1936  *
1937  * \param pri sig_pri PRI control structure.
1938  * \param chanpos Channel position in the span.
1939  * \param service CCBS/CCNR indication.
1940  *
1941  * \note Assumes the pri->lock is already obtained.
1942  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1943  *
1944  * \return Nothing
1945  */
1946 static void sig_pri_cc_generic_check(struct sig_pri_pri *pri, int chanpos, enum ast_cc_service_type service)
1947 {
1948         struct ast_channel *owner;
1949         struct ast_cc_config_params *cc_params;
1950 #if defined(HAVE_PRI_CCSS)
1951         struct ast_cc_monitor *monitor;
1952         char device_name[AST_CHANNEL_NAME];
1953 #endif  /* defined(HAVE_PRI_CCSS) */
1954         enum ast_cc_monitor_policies monitor_policy;
1955         int core_id;
1956
1957         if (!pri->pvts[chanpos]->outgoing) {
1958                 /* This is not an outgoing call so it cannot be CC monitor. */
1959                 return;
1960         }
1961
1962         sig_pri_lock_owner(pri, chanpos);
1963         owner = pri->pvts[chanpos]->owner;
1964         if (!owner) {
1965                 return;
1966         }
1967         core_id = ast_cc_get_current_core_id(owner);
1968         if (core_id == -1) {
1969                 /* No CC core setup */
1970                 goto done;
1971         }
1972
1973         cc_params = ast_channel_get_cc_config_params(owner);
1974         if (!cc_params) {
1975                 /* Could not get CC config parameters. */
1976                 goto done;
1977         }
1978
1979 #if defined(HAVE_PRI_CCSS)
1980         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
1981         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
1982         if (monitor) {
1983                 /* CC monitor is already present so no need for generic CC. */
1984                 ao2_ref(monitor, -1);
1985                 goto done;
1986         }
1987 #endif  /* defined(HAVE_PRI_CCSS) */
1988
1989         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1990         switch (monitor_policy) {
1991         case AST_CC_MONITOR_NEVER:
1992                 /* CCSS is not enabled. */
1993                 break;
1994         case AST_CC_MONITOR_NATIVE:
1995                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
1996                         /* Request generic CC monitor. */
1997                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1998                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1999                 }
2000                 break;
2001         case AST_CC_MONITOR_ALWAYS:
2002                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2003                         /*
2004                          * Cannot monitor PTMP TE side since this is not defined.
2005                          * We are playing the roll of a phone in this case and
2006                          * a phone cannot monitor a party over the network without
2007                          * protocol help.
2008                          */
2009                         break;
2010                 }
2011                 /*
2012                  * We are either falling back or this is a PTMP NT span.
2013                  * Request generic CC monitor.
2014                  */
2015                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2016                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2017                 break;
2018         case AST_CC_MONITOR_GENERIC:
2019                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2020                         /* Request generic CC monitor. */
2021                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2022                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2023                 }
2024                 break;
2025         }
2026
2027 done:
2028         ast_channel_unlock(owner);
2029 }
2030
2031 #if defined(HAVE_PRI_CCSS)
2032 /*!
2033  * \internal
2034  * \brief The CC link canceled the CC instance.
2035  * \since 1.8
2036  *
2037  * \param pri sig_pri PRI control structure.
2038  * \param cc_id CC record ID.
2039  * \param is_agent TRUE if the cc_id is for an agent.
2040  *
2041  * \return Nothing
2042  */
2043 static void sig_pri_cc_link_canceled(struct sig_pri_pri *pri, long cc_id, int is_agent)
2044 {
2045         if (is_agent) {
2046                 struct ast_cc_agent *agent;
2047
2048                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2049                 if (!agent) {
2050                         return;
2051                 }
2052                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2053                         sig_pri_cc_type_name);
2054                 ao2_ref(agent, -1);
2055         } else {
2056                 struct sig_pri_cc_monitor_instance *monitor;
2057
2058                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2059                 if (!monitor) {
2060                         return;
2061                 }
2062                 monitor->cc_id = -1;
2063                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2064                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2065                 ao2_ref(monitor, -1);
2066         }
2067 }
2068 #endif  /* defined(HAVE_PRI_CCSS) */
2069
2070 #if defined(HAVE_PRI_AOC_EVENTS)
2071 /*!
2072  * \internal
2073  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2074  * \since 1.8
2075  *
2076  * \param value Value to convert to string.
2077  *
2078  * \return PRI_AOC_CHARGED_ITEM
2079  */
2080 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2081 {
2082         switch (value) {
2083         case AST_AOC_CHARGED_ITEM_NA:
2084                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2085         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2086                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2087         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2088                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2089         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2090                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2091         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2092                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2093         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2094                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2095         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2096                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2097         }
2098         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2099 }
2100 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2101
2102 #if defined(HAVE_PRI_AOC_EVENTS)
2103 /*!
2104  * \internal
2105  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2106  * \since 1.8
2107  *
2108  * \param value Value to convert to string.
2109  *
2110  * \return ast_aoc_charged_item
2111  */
2112 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2113 {
2114         switch (value) {
2115         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2116                 return AST_AOC_CHARGED_ITEM_NA;
2117         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2118                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2119         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2120                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2121         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2122                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2123         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2124                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2125         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2126                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2127         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2128                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2129         }
2130         return AST_AOC_CHARGED_ITEM_NA;
2131 }
2132 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2133
2134 #if defined(HAVE_PRI_AOC_EVENTS)
2135 /*!
2136  * \internal
2137  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2138  * \since 1.8
2139  *
2140  * \return pri enum equivalent.
2141  */
2142 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2143 {
2144         switch (mult) {
2145         case AST_AOC_MULT_ONETHOUSANDTH:
2146                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2147         case AST_AOC_MULT_ONEHUNDREDTH:
2148                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2149         case AST_AOC_MULT_ONETENTH:
2150                 return PRI_AOC_MULTIPLIER_TENTH;
2151         case AST_AOC_MULT_ONE:
2152                 return PRI_AOC_MULTIPLIER_ONE;
2153         case AST_AOC_MULT_TEN:
2154                 return PRI_AOC_MULTIPLIER_TEN;
2155         case AST_AOC_MULT_HUNDRED:
2156                 return PRI_AOC_MULTIPLIER_HUNDRED;
2157         case AST_AOC_MULT_THOUSAND:
2158                 return PRI_AOC_MULTIPLIER_THOUSAND;
2159         default:
2160                 return PRI_AOC_MULTIPLIER_ONE;
2161         }
2162 }
2163 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2164
2165 #if defined(HAVE_PRI_AOC_EVENTS)
2166 /*!
2167  * \internal
2168  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2169  * \since 1.8
2170  *
2171  * \return ast enum equivalent.
2172  */
2173 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2174 {
2175         switch (mult) {
2176         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2177                 return AST_AOC_MULT_ONETHOUSANDTH;
2178         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2179                 return AST_AOC_MULT_ONEHUNDREDTH;
2180         case PRI_AOC_MULTIPLIER_TENTH:
2181                 return AST_AOC_MULT_ONETENTH;
2182         case PRI_AOC_MULTIPLIER_ONE:
2183                 return AST_AOC_MULT_ONE;
2184         case PRI_AOC_MULTIPLIER_TEN:
2185                 return AST_AOC_MULT_TEN;
2186         case PRI_AOC_MULTIPLIER_HUNDRED:
2187                 return AST_AOC_MULT_HUNDRED;
2188         case PRI_AOC_MULTIPLIER_THOUSAND:
2189                 return AST_AOC_MULT_THOUSAND;
2190         default:
2191                 return AST_AOC_MULT_ONE;
2192         }
2193 }
2194 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2195
2196 #if defined(HAVE_PRI_AOC_EVENTS)
2197 /*!
2198  * \internal
2199  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
2200  * \since 1.8
2201  *
2202  * \param value Value to convert to ast representation
2203  *
2204  * \return PRI_AOC_TIME_SCALE
2205  */
2206 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
2207 {
2208         switch (value) {
2209         default:
2210         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2211                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2212         case AST_AOC_TIME_SCALE_TENTH_SECOND:
2213                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
2214         case AST_AOC_TIME_SCALE_SECOND:
2215                 return PRI_AOC_TIME_SCALE_SECOND;
2216         case AST_AOC_TIME_SCALE_TEN_SECOND:
2217                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
2218         case AST_AOC_TIME_SCALE_MINUTE:
2219                 return PRI_AOC_TIME_SCALE_MINUTE;
2220         case AST_AOC_TIME_SCALE_HOUR:
2221                 return PRI_AOC_TIME_SCALE_HOUR;
2222         case AST_AOC_TIME_SCALE_DAY:
2223                 return PRI_AOC_TIME_SCALE_DAY;
2224         }
2225 }
2226 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2227
2228 #if defined(HAVE_PRI_AOC_EVENTS)
2229 /*!
2230  * \internal
2231  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
2232  * \since 1.8
2233  *
2234  * \param value Value to convert to ast representation
2235  *
2236  * \return ast aoc time scale
2237  */
2238 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
2239 {
2240         switch (value) {
2241         default:
2242         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2243                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2244         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
2245                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
2246         case PRI_AOC_TIME_SCALE_SECOND:
2247                 return AST_AOC_TIME_SCALE_SECOND;
2248         case PRI_AOC_TIME_SCALE_TEN_SECOND:
2249                 return AST_AOC_TIME_SCALE_TEN_SECOND;
2250         case PRI_AOC_TIME_SCALE_MINUTE:
2251                 return AST_AOC_TIME_SCALE_MINUTE;
2252         case PRI_AOC_TIME_SCALE_HOUR:
2253                 return AST_AOC_TIME_SCALE_HOUR;
2254         case PRI_AOC_TIME_SCALE_DAY:
2255                 return AST_AOC_TIME_SCALE_DAY;
2256         }
2257         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2258 }
2259 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2260
2261 #if defined(HAVE_PRI_AOC_EVENTS)
2262 /*!
2263  * \internal
2264  * \brief Handle AOC-S control frame
2265  * \since 1.8
2266  *
2267  * \param aoc_s AOC-S event parameters.
2268  * \param owner Asterisk channel associated with the call.
2269  * \param passthrough indicating if this message should be queued on the ast channel
2270  *
2271  * \note Assumes the pri->lock is already obtained.
2272  * \note Assumes the sig_pri private is locked
2273  * \note Assumes the owner channel lock is already obtained.
2274  *
2275  * \return Nothing
2276  */
2277 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
2278 {
2279         struct ast_aoc_decoded *decoded = NULL;
2280         struct ast_aoc_encoded *encoded = NULL;
2281         size_t encoded_size = 0;
2282         int idx;
2283
2284         if (!owner || !aoc_s) {
2285                 return;
2286         }
2287
2288         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
2289                 return;
2290         }
2291
2292         for (idx = 0; idx < aoc_s->num_items; ++idx) {
2293                 enum ast_aoc_s_charged_item charged_item;
2294
2295                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
2296                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
2297                         /* Delete the unknown charged item from the list. */
2298                         continue;
2299                 }
2300                 switch (aoc_s->item[idx].rate_type) {
2301                 case PRI_AOC_RATE_TYPE_DURATION:
2302                         ast_aoc_s_add_rate_duration(decoded,
2303                                 charged_item,
2304                                 aoc_s->item[idx].rate.duration.amount.cost,
2305                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
2306                                 aoc_s->item[idx].rate.duration.currency,
2307                                 aoc_s->item[idx].rate.duration.time.length,
2308                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
2309                                 aoc_s->item[idx].rate.duration.granularity.length,
2310                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
2311                                 aoc_s->item[idx].rate.duration.charging_type);
2312                         break;
2313                 case PRI_AOC_RATE_TYPE_FLAT:
2314                         ast_aoc_s_add_rate_flat(decoded,
2315                                 charged_item,
2316                                 aoc_s->item[idx].rate.flat.amount.cost,
2317                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
2318                                 aoc_s->item[idx].rate.flat.currency);
2319                         break;
2320                 case PRI_AOC_RATE_TYPE_VOLUME:
2321                         ast_aoc_s_add_rate_volume(decoded,
2322                                 charged_item,
2323                                 aoc_s->item[idx].rate.volume.unit,
2324                                 aoc_s->item[idx].rate.volume.amount.cost,
2325                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
2326                                 aoc_s->item[idx].rate.volume.currency);
2327                         break;
2328                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
2329                         ast_aoc_s_add_rate_special_charge_code(decoded,
2330                                 charged_item,
2331                                 aoc_s->item[idx].rate.special);
2332                         break;
2333                 case PRI_AOC_RATE_TYPE_FREE:
2334                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
2335                         break;
2336                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2337                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
2338                         break;
2339                 default:
2340                         ast_aoc_s_add_rate_na(decoded, charged_item);
2341                         break;
2342                 }
2343         }
2344
2345         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2346                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2347         }
2348
2349         ast_aoc_manager_event(decoded, owner);
2350
2351         ast_aoc_destroy_decoded(decoded);
2352         ast_aoc_destroy_encoded(encoded);
2353 }
2354 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2355
2356 #if defined(HAVE_PRI_AOC_EVENTS)
2357 /*!
2358  * \internal
2359  * \brief Generate AOC Request Response
2360  * \since 1.8
2361  *
2362  * \param aoc_request
2363  *
2364  * \note Assumes the pri->lock is already obtained.
2365  * \note Assumes the sig_pri private is locked
2366  * \note Assumes the owner channel lock is already obtained.
2367  *
2368  * \return Nothing
2369  */
2370 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
2371 {
2372         int request;
2373
2374         if (!aoc_request) {
2375                 return;
2376         }
2377
2378         request = aoc_request->charging_request;
2379
2380         if (request & PRI_AOC_REQUEST_S) {
2381                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
2382                         /* An AOC-S response must come from the other side, so save off this invoke_id
2383                          * and see if an AOC-S message comes in before the call is answered. */
2384                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
2385                         pvt->aoc_s_request_invoke_id_valid = 1;
2386
2387                 } else {
2388                         pri_aoc_s_request_response_send(pvt->pri->pri,
2389                                 call,
2390                                 aoc_request->invoke_id,
2391                                 NULL);
2392                 }
2393         }
2394
2395         if (request & PRI_AOC_REQUEST_D) {
2396                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
2397                         pri_aoc_de_request_response_send(pvt->pri->pri,
2398                                 call,
2399                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2400                                 aoc_request->invoke_id);
2401                 } else {
2402                         pri_aoc_de_request_response_send(pvt->pri->pri,
2403                                 call,
2404                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2405                                 aoc_request->invoke_id);
2406                 }
2407         }
2408
2409         if (request & PRI_AOC_REQUEST_E) {
2410                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
2411                         pri_aoc_de_request_response_send(pvt->pri->pri,
2412                                 call,
2413                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2414                                 aoc_request->invoke_id);
2415                 } else {
2416                         pri_aoc_de_request_response_send(pvt->pri->pri,
2417                                 call,
2418                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2419                                 aoc_request->invoke_id);
2420                 }
2421         }
2422 }
2423 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2424
2425 #if defined(HAVE_PRI_AOC_EVENTS)
2426 /*!
2427  * \internal
2428  * \brief Generate AOC-D AST_CONTROL_AOC frame
2429  * \since 1.8
2430  *
2431  * \param aoc_e AOC-D event parameters.
2432  * \param owner Asterisk channel associated with the call.
2433  * \param passthrough indicating if this message should be queued on the ast channel
2434  *
2435  * \note Assumes the pri->lock is already obtained.
2436  * \note Assumes the sig_pri private is locked
2437  * \note Assumes the owner channel lock is already obtained.
2438  *
2439  * \return Nothing
2440  */
2441 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
2442 {
2443         struct ast_aoc_decoded *decoded = NULL;
2444         struct ast_aoc_encoded *encoded = NULL;
2445         size_t encoded_size = 0;
2446         enum ast_aoc_charge_type type;
2447
2448         if (!owner || !aoc_d) {
2449                 return;
2450         }
2451
2452         switch (aoc_d->charge) {
2453         case PRI_AOC_DE_CHARGE_CURRENCY:
2454                 type = AST_AOC_CHARGE_CURRENCY;
2455                 break;
2456         case PRI_AOC_DE_CHARGE_UNITS:
2457                 type = AST_AOC_CHARGE_UNIT;
2458                 break;
2459         case PRI_AOC_DE_CHARGE_FREE:
2460                 type = AST_AOC_CHARGE_FREE;
2461                 break;
2462         default:
2463                 type = AST_AOC_CHARGE_NA;
2464                 break;
2465         }
2466
2467         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
2468                 return;
2469         }
2470
2471         switch (aoc_d->billing_accumulation) {
2472         default:
2473                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
2474                         aoc_d->billing_accumulation);
2475                 /* Fall through */
2476         case 0:/* subTotal */
2477                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
2478                 break;
2479         case 1:/* total */
2480                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
2481                 break;
2482         }
2483
2484         switch (aoc_d->billing_id) {
2485         case PRI_AOC_D_BILLING_ID_NORMAL:
2486                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2487                 break;
2488         case PRI_AOC_D_BILLING_ID_REVERSE:
2489                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2490                 break;
2491         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
2492                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2493                 break;
2494         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
2495         default:
2496                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2497                 break;
2498         }
2499
2500         switch (aoc_d->charge) {
2501         case PRI_AOC_DE_CHARGE_CURRENCY:
2502                 ast_aoc_set_currency_info(decoded,
2503                         aoc_d->recorded.money.amount.cost,
2504                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
2505                         aoc_d->recorded.money.currency);
2506                 break;
2507         case PRI_AOC_DE_CHARGE_UNITS:
2508                 {
2509                         int i;
2510                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
2511                                 /* if type or number are negative, then they are not present */
2512                                 ast_aoc_add_unit_entry(decoded,
2513                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
2514                                         aoc_d->recorded.unit.item[i].number,
2515                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
2516                                         aoc_d->recorded.unit.item[i].type);
2517                         }
2518                 }
2519                 break;
2520         }
2521
2522         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2523                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2524         }
2525
2526         ast_aoc_manager_event(decoded, owner);
2527
2528         ast_aoc_destroy_decoded(decoded);
2529         ast_aoc_destroy_encoded(encoded);
2530 }
2531 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2532
2533 #if defined(HAVE_PRI_AOC_EVENTS)
2534 /*!
2535  * \internal
2536  * \brief Generate AOC-E AST_CONTROL_AOC frame
2537  * \since 1.8
2538  *
2539  * \param aoc_e AOC-E event parameters.
2540  * \param owner Asterisk channel associated with the call.
2541  * \param passthrough indicating if this message should be queued on the ast channel
2542  *
2543  * \note Assumes the pri->lock is already obtained.
2544  * \note Assumes the sig_pri private is locked
2545  * \note Assumes the owner channel lock is already obtained.
2546  * \note owner channel may be NULL. In that case, generate event only
2547  *
2548  * \return Nothing
2549  */
2550 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
2551 {
2552         struct ast_aoc_decoded *decoded = NULL;
2553         struct ast_aoc_encoded *encoded = NULL;
2554         size_t encoded_size = 0;
2555         enum ast_aoc_charge_type type;
2556
2557         if (!aoc_e) {
2558                 return;
2559         }
2560
2561         switch (aoc_e->charge) {
2562         case PRI_AOC_DE_CHARGE_CURRENCY:
2563                 type = AST_AOC_CHARGE_CURRENCY;
2564                 break;
2565         case PRI_AOC_DE_CHARGE_UNITS:
2566                 type = AST_AOC_CHARGE_UNIT;
2567                 break;
2568         case PRI_AOC_DE_CHARGE_FREE:
2569                 type = AST_AOC_CHARGE_FREE;
2570                 break;
2571         default:
2572                 type = AST_AOC_CHARGE_NA;
2573                 break;
2574         }
2575
2576         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
2577                 return;
2578         }
2579
2580         switch (aoc_e->associated.charging_type) {
2581         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
2582                 if (!aoc_e->associated.charge.number.valid) {
2583                         break;
2584                 }
2585                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
2586                 break;
2587         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
2588                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
2589                 break;
2590         default:
2591                 break;
2592         }
2593
2594         switch (aoc_e->billing_id) {
2595         case PRI_AOC_E_BILLING_ID_NORMAL:
2596                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2597                 break;
2598         case PRI_AOC_E_BILLING_ID_REVERSE:
2599                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2600                 break;
2601         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
2602                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2603                 break;
2604         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
2605                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
2606                 break;
2607         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
2608                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
2609                 break;
2610         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
2611                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
2612                 break;
2613         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
2614                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
2615                 break;
2616         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
2617                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
2618                 break;
2619         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
2620         default:
2621                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2622                 break;
2623         }
2624
2625         switch (aoc_e->charge) {
2626         case PRI_AOC_DE_CHARGE_CURRENCY:
2627                 ast_aoc_set_currency_info(decoded,
2628                         aoc_e->recorded.money.amount.cost,
2629                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
2630                         aoc_e->recorded.money.currency);
2631                 break;
2632         case PRI_AOC_DE_CHARGE_UNITS:
2633                 {
2634                         int i;
2635                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
2636                                 /* if type or number are negative, then they are not present */
2637                                 ast_aoc_add_unit_entry(decoded,
2638                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
2639                                         aoc_e->recorded.unit.item[i].number,
2640                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
2641                                         aoc_e->recorded.unit.item[i].type);
2642                         }
2643                 }
2644         }
2645
2646         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2647                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2648         }
2649
2650         ast_aoc_manager_event(decoded, owner);
2651
2652         ast_aoc_destroy_decoded(decoded);
2653         ast_aoc_destroy_encoded(encoded);
2654 }
2655 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2656
2657 #if defined(HAVE_PRI_AOC_EVENTS)
2658 /*!
2659  * \internal
2660  * \brief send an AOC-S message on the current call
2661  *
2662  * \param pvt sig_pri private channel structure.
2663  * \param generic decoded ast AOC message
2664  *
2665  * \return Nothing
2666  *
2667  * \note Assumes that the PRI lock is already obtained.
2668  */
2669 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2670 {
2671         struct pri_subcmd_aoc_s aoc_s = { 0, };
2672         const struct ast_aoc_s_entry *entry;
2673         int idx;
2674
2675         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
2676                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
2677                         break;
2678                 }
2679
2680                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
2681
2682                 switch (entry->rate_type) {
2683                 case AST_AOC_RATE_TYPE_DURATION:
2684                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
2685                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
2686                         aoc_s.item[idx].rate.duration.amount.multiplier =
2687                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
2688                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
2689                         aoc_s.item[idx].rate.duration.time.scale =
2690                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
2691                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
2692                         aoc_s.item[idx].rate.duration.granularity.scale =
2693                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
2694                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
2695
2696                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
2697                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
2698                                         entry->rate.duration.currency_name,
2699                                         sizeof(aoc_s.item[idx].rate.duration.currency));
2700                         }
2701                         break;
2702                 case AST_AOC_RATE_TYPE_FLAT:
2703                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
2704                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
2705                         aoc_s.item[idx].rate.flat.amount.multiplier =
2706                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
2707
2708                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
2709                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
2710                                         entry->rate.flat.currency_name,
2711                                         sizeof(aoc_s.item[idx].rate.flat.currency));
2712                         }
2713                         break;
2714                 case AST_AOC_RATE_TYPE_VOLUME:
2715                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
2716                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
2717                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
2718                         aoc_s.item[idx].rate.volume.amount.multiplier =
2719                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
2720
2721                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
2722                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
2723                                         entry->rate.volume.currency_name,
2724                                         sizeof(aoc_s.item[idx].rate.volume.currency));
2725                         }
2726                         break;
2727                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
2728                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
2729                         aoc_s.item[idx].rate.special = entry->rate.special_code;
2730                         break;
2731                 case AST_AOC_RATE_TYPE_FREE:
2732                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
2733                         break;
2734                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2735                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
2736                         break;
2737                 default:
2738                 case AST_AOC_RATE_TYPE_NA:
2739                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
2740                         break;
2741                 }
2742         }
2743         aoc_s.num_items = idx;
2744
2745         /* if this rate should be sent as a response to an AOC-S request we will
2746          * have an aoc_s_request_invoke_id associated with this pvt */
2747         if (pvt->aoc_s_request_invoke_id_valid) {
2748                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
2749                 pvt->aoc_s_request_invoke_id_valid = 0;
2750         } else {
2751                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
2752         }
2753 }
2754 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2755
2756 #if defined(HAVE_PRI_AOC_EVENTS)
2757 /*!
2758  * \internal
2759  * \brief send an AOC-D message on the current call
2760  *
2761  * \param pvt sig_pri private channel structure.
2762  * \param generic decoded ast AOC message
2763  *
2764  * \return Nothing
2765  *
2766  * \note Assumes that the PRI lock is already obtained.
2767  */
2768 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2769 {
2770         struct pri_subcmd_aoc_d aoc_d = { 0, };
2771
2772         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
2773
2774         switch (ast_aoc_get_billing_id(decoded)) {
2775         case AST_AOC_BILLING_NORMAL:
2776                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
2777                 break;
2778         case AST_AOC_BILLING_REVERSE_CHARGE:
2779                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
2780                 break;
2781         case AST_AOC_BILLING_CREDIT_CARD:
2782                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
2783                 break;
2784         case AST_AOC_BILLING_NA:
2785         default:
2786                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
2787                 break;
2788         }
2789
2790         switch (ast_aoc_get_charge_type(decoded)) {
2791         case AST_AOC_CHARGE_FREE:
2792                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
2793                 break;
2794         case AST_AOC_CHARGE_CURRENCY:
2795                 {
2796                         const char *currency_name = ast_aoc_get_currency_name(decoded);
2797                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
2798                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
2799                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
2800                         if (!ast_strlen_zero(currency_name)) {
2801                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
2802                         }
2803                 }
2804                 break;
2805         case AST_AOC_CHARGE_UNIT:
2806                 {
2807                         const struct ast_aoc_unit_entry *entry;
2808                         int i;
2809                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
2810                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
2811                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
2812                                         if (entry->valid_amount) {
2813                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
2814                                         } else {
2815                                                 aoc_d.recorded.unit.item[i].number = -1;
2816                                         }
2817                                         if (entry->valid_type) {
2818                                                 aoc_d.recorded.unit.item[i].type = entry->type;
2819                                         } else {
2820                                                 aoc_d.recorded.unit.item[i].type = -1;
2821                                         }
2822                                         aoc_d.recorded.unit.num_items++;
2823                                 } else {
2824                                         break;
2825                                 }
2826                         }
2827                 }
2828                 break;
2829         case AST_AOC_CHARGE_NA:
2830         default:
2831                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
2832                 break;
2833         }
2834
2835         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
2836 }
2837 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2838
2839 #if defined(HAVE_PRI_AOC_EVENTS)
2840 /*!
2841  * \internal
2842  * \brief send an AOC-E message on the current call
2843  *
2844  * \param pvt sig_pri private channel structure.
2845  * \param generic decoded ast AOC message
2846  *
2847  * \return Nothing
2848  *
2849  * \note Assumes that the PRI lock is already obtained.
2850  */
2851 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2852 {
2853         struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
2854         const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
2855
2856         memset(aoc_e, 0, sizeof(*aoc_e));
2857         pvt->holding_aoce = 1;
2858
2859         switch (ca->charging_type) {
2860         case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
2861                 aoc_e->associated.charge.number.valid = 1;
2862                 ast_copy_string(aoc_e->associated.charge.number.str,
2863                         ca->charge.number.number,
2864                         sizeof(aoc_e->associated.charge.number.str));
2865                 aoc_e->associated.charge.number.plan = ca->charge.number.plan;
2866                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
2867                 break;
2868         case AST_AOC_CHARGING_ASSOCIATION_ID:
2869                 aoc_e->associated.charge.id = ca->charge.id;
2870                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
2871                 break;
2872         case AST_AOC_CHARGING_ASSOCIATION_NA:
2873         default:
2874                 break;
2875         }
2876
2877         switch (ast_aoc_get_billing_id(decoded)) {
2878         case AST_AOC_BILLING_NORMAL:
2879                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
2880                 break;
2881         case AST_AOC_BILLING_REVERSE_CHARGE:
2882                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
2883                 break;
2884         case AST_AOC_BILLING_CREDIT_CARD:
2885                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
2886                 break;
2887         case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
2888                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
2889                 break;
2890         case AST_AOC_BILLING_CALL_FWD_BUSY:
2891                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
2892                 break;
2893         case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
2894                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
2895                 break;
2896         case AST_AOC_BILLING_CALL_DEFLECTION:
2897                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
2898                 break;
2899         case AST_AOC_BILLING_CALL_TRANSFER:
2900                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
2901                 break;
2902         case AST_AOC_BILLING_NA:
2903         default:
2904                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
2905                 break;
2906         }
2907
2908         switch (ast_aoc_get_charge_type(decoded)) {
2909         case AST_AOC_CHARGE_FREE:
2910                 aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
2911                 break;
2912         case AST_AOC_CHARGE_CURRENCY:
2913                 {
2914                         const char *currency_name = ast_aoc_get_currency_name(decoded);
2915                         aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
2916                         aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
2917                         aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
2918                         if (!ast_strlen_zero(currency_name)) {
2919                                 ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
2920                         }
2921                 }
2922                 break;
2923         case AST_AOC_CHARGE_UNIT:
2924                 {
2925                         const struct ast_aoc_unit_entry *entry;
2926                         int i;
2927                         aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
2928                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
2929                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
2930                                         if (entry->valid_amount) {
2931                                                 aoc_e->recorded.unit.item[i].number = entry->amount;
2932                                         } else {
2933                                                 aoc_e->recorded.unit.item[i].number = -1;
2934                                         }
2935                                         if (entry->valid_type) {
2936                                                 aoc_e->recorded.unit.item[i].type = entry->type;
2937                                         } else {
2938                                                 aoc_e->recorded.unit.item[i].type = -1;
2939                                         }
2940                                         aoc_e->recorded.unit.num_items++;
2941                                 }
2942                         }
2943                 }
2944                 break;
2945         case AST_AOC_CHARGE_NA:
2946         default:
2947                 aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
2948                 break;
2949         }
2950 }
2951 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2952
2953 #if defined(HAVE_PRI_AOC_EVENTS)
2954 /*!
2955  * \internal
2956  * \brief send an AOC-E termination request on ast_channel and set
2957  * hangup delay.
2958  *
2959  * \param sig_pri_chan private
2960  * \param ms to delay hangup
2961  *
2962  * \note assumes pvt is locked
2963  *
2964  * \return Nothing
2965  */
2966 static void sig_pri_send_aoce_termination_request(struct sig_pri_chan *pvt, unsigned int ms)
2967 {
2968         struct ast_aoc_decoded *decoded = NULL;
2969         struct ast_aoc_encoded *encoded = NULL;
2970         size_t encoded_size;
2971         struct timeval whentohangup = { 0, };
2972
2973         if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
2974                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
2975                 goto cleanup_termination_request;
2976         }
2977
2978         ast_aoc_set_termination_request(decoded);
2979
2980         if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
2981                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
2982                 goto cleanup_termination_request;
2983         }
2984
2985         /* convert ms to timeval */
2986         whentohangup.tv_usec = (ms % 1000) * 1000;
2987         whentohangup.tv_sec = ms / 1000;
2988
2989         if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
2990                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
2991                 goto cleanup_termination_request;
2992         }
2993
2994         pvt->waiting_for_aoce = 1;
2995         ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
2996         ast_log(LOG_DEBUG, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
2997
2998 cleanup_termination_request:
2999         ast_aoc_destroy_decoded(decoded);
3000         ast_aoc_destroy_encoded(encoded);
3001 }
3002 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3003
3004 /*!
3005  * \internal
3006  * \brief TRUE if PRI event came in on a CIS call.
3007  * \since 1.8
3008  *
3009  * \param channel PRI encoded span/channel
3010  *
3011  * \retval non-zero if CIS call.
3012  */
3013 static int sig_pri_is_cis_call(int channel)
3014 {
3015         return channel != -1 && (channel & PRI_CIS_CALL);
3016 }
3017
3018 /*!
3019  * \internal
3020  * \brief Handle the CIS associated PRI subcommand events.
3021  * \since 1.8
3022  *
3023  * \param pri sig_pri PRI control structure.
3024  * \param event_id PRI event id
3025  * \param subcmds Subcommands to process if any. (Could be NULL).
3026  * \param call_rsp libpri opaque call structure to send any responses toward.
3027  * Could be NULL either because it is not available or the call is for the
3028  * dummy call reference.  However, this should not be NULL in the cases that
3029  * need to use the pointer to send a response message back.
3030  *
3031  * \note Assumes the pri->lock is already obtained.
3032  *
3033  * \return Nothing
3034  */
3035 static void sig_pri_handle_cis_subcmds(struct sig_pri_pri *pri, int event_id,
3036         const struct pri_subcommands *subcmds, q931_call *call_rsp)
3037 {
3038         int index;
3039 #if defined(HAVE_PRI_CCSS)
3040         struct ast_cc_agent *agent;
3041         struct sig_pri_cc_agent_prv *agent_prv;
3042         struct sig_pri_cc_monitor_instance *monitor;
3043 #endif  /* defined(HAVE_PRI_CCSS) */
3044
3045         if (!subcmds) {
3046                 return;
3047         }
3048         for (index = 0; index < subcmds->counter_subcmd; ++index) {
3049                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
3050
3051                 switch (subcmd->cmd) {
3052 #if defined(STATUS_REQUEST_PLACE_HOLDER)
3053                 case PRI_SUBCMD_STATUS_REQ:
3054                 case PRI_SUBCMD_STATUS_REQ_RSP:
3055                         /* Ignore for now. */
3056                         break;
3057 #endif  /* defined(STATUS_REQUEST_PLACE_HOLDER) */
3058 #if defined(HAVE_PRI_CCSS)
3059                 case PRI_SUBCMD_CC_REQ:
3060                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
3061                         if (!agent) {
3062                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3063                                 break;
3064                         }
3065                         if (!ast_cc_request_is_within_limits()) {
3066                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3067                                         5/* queue_full */)) {
3068                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3069                                 }
3070                                 ast_cc_failed(agent->core_id, "%s agent system CC queue full",
3071                                         sig_pri_cc_type_name);
3072                                 ao2_ref(agent, -1);
3073                                 break;
3074                         }
3075                         agent_prv = agent->private_data;
3076                         agent_prv->cc_request_response_pending = 1;
3077                         if (ast_cc_agent_accept_request(agent->core_id,
3078                                 "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
3079                                 agent_prv->cc_request_response_pending = 0;
3080                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3081                                         2/* short_term_denial */)) {
3082                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3083                                 }
3084                                 ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
3085                                         sig_pri_cc_type_name);
3086                         }
3087                         ao2_ref(agent, -1);
3088                         break;
3089 #endif  /* defined(HAVE_PRI_CCSS) */
3090 #if defined(HAVE_PRI_CCSS)
3091                 case PRI_SUBCMD_CC_REQ_RSP:
3092                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3093                                 subcmd->u.cc_request_rsp.cc_id);
3094                         if (!monitor) {
3095                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
3096                                 break;
3097                         }
3098                         switch (subcmd->u.cc_request_rsp.status) {
3099                         case 0:/* success */
3100                                 ast_cc_monitor_request_acked(monitor->core_id,
3101                                         "%s far end accepted CC request", sig_pri_cc_type_name);
3102                                 break;
3103                         case 1:/* timeout */
3104                                 ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
3105                                         sig_pri_cc_type_name);
3106                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3107                                         "%s CC request timeout", sig_pri_cc_type_name);
3108                                 break;
3109                         case 2:/* error */
3110                                 ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
3111                                         sig_pri_cc_type_name,
3112                                         pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
3113                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3114                                         "%s CC request error", sig_pri_cc_type_name);
3115                                 break;
3116                         case 3:/* reject */
3117                                 ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
3118                                         sig_pri_cc_type_name,
3119                                         pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
3120                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3121                                         "%s CC request reject", sig_pri_cc_type_name);
3122                                 break;
3123                         default:
3124                                 ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
3125                                         monitor->core_id, sig_pri_cc_type_name,
3126                                         subcmd->u.cc_request_rsp.status);
3127                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3128                                         "%s CC request unknown status", sig_pri_cc_type_name);
3129                                 break;
3130                         }
3131                         ao2_ref(monitor, -1);
3132                         break;
3133 #endif  /* defined(HAVE_PRI_CCSS) */
3134 #if defined(HAVE_PRI_CCSS)
3135                 case PRI_SUBCMD_CC_REMOTE_USER_FREE:
3136                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3137                                 subcmd->u.cc_remote_user_free.cc_id);
3138                         if (!monitor) {
3139                                 pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
3140                                 break;
3141                         }
3142                         ast_cc_monitor_callee_available(monitor->core_id,
3143                                 "%s callee has become available", sig_pri_cc_type_name);
3144                         ao2_ref(monitor, -1);
3145                         break;
3146 #endif  /* defined(HAVE_PRI_CCSS) */
3147 #if defined(HAVE_PRI_CCSS)
3148                 case PRI_SUBCMD_CC_B_FREE:
3149                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3150                                 subcmd->u.cc_b_free.cc_id);
3151                         if (!monitor) {
3152                                 pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
3153                                 break;
3154                         }
3155                         ast_cc_monitor_party_b_free(monitor->core_id);
3156                         ao2_ref(monitor, -1);
3157                         break;
3158 #endif  /* defined(HAVE_PRI_CCSS) */
3159 #if defined(HAVE_PRI_CCSS)
3160                 case PRI_SUBCMD_CC_STATUS_REQ:
3161                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3162                                 subcmd->u.cc_status_req.cc_id);
3163                         if (!monitor) {
3164                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
3165                                 break;
3166                         }
3167                         ast_cc_monitor_status_request(monitor->core_id);
3168                         ao2_ref(monitor, -1);
3169                         break;
3170 #endif  /* defined(HAVE_PRI_CCSS) */
3171 #if defined(HAVE_PRI_CCSS)
3172                 case PRI_SUBCMD_CC_STATUS_REQ_RSP:
3173                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
3174                         if (!agent) {
3175                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
3176                                 break;
3177                         }
3178                         ast_cc_agent_status_response(agent->core_id,
3179                                 subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
3180                                 : AST_DEVICE_NOT_INUSE);
3181                         ao2_ref(agent, -1);
3182                         break;
3183 #endif  /* defined(HAVE_PRI_CCSS) */
3184 #if defined(HAVE_PRI_CCSS)
3185                 case PRI_SUBCMD_CC_STATUS:
3186                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
3187                         if (!agent) {
3188                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
3189                                 break;
3190                         }
3191                         if (subcmd->u.cc_status.status) {
3192                                 ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
3193                                         sig_pri_cc_type_name);
3194                         } else {
3195                                 ast_cc_agent_caller_available(agent->core_id,
3196                                         "%s agent caller is available", sig_pri_cc_type_name);
3197                         }
3198                         ao2_ref(agent, -1);
3199                         break;
3200 #endif  /* defined(HAVE_PRI_CCSS) */
3201 #if defined(HAVE_PRI_CCSS)
3202                 case PRI_SUBCMD_CC_CANCEL:
3203                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
3204                                 subcmd->u.cc_cancel.is_agent);
3205                         break;
3206 #endif  /* defined(HAVE_PRI_CCSS) */
3207 #if defined(HAVE_PRI_CCSS)
3208                 case PRI_SUBCMD_CC_STOP_ALERTING:
3209                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3210                                 subcmd->u.cc_stop_alerting.cc_id);
3211                         if (!monitor) {
3212                                 pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
3213                                 break;
3214                         }
3215                         ast_cc_monitor_stop_ringing(monitor->core_id);
3216                         ao2_ref(monitor, -1);
3217                         break;
3218 #endif  /* defined(HAVE_PRI_CCSS) */
3219 #if defined(HAVE_PRI_AOC_EVENTS)
3220                 case PRI_SUBCMD_AOC_E:
3221                         /* Queue AST_CONTROL_AOC frame */
3222                         sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, NULL, 0);
3223                         break;
3224 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3225                 default:
3226                         ast_debug(2,
3227                                 "Unknown CIS subcommand(%d) in %s event on span %d.\n",
3228                                 subcmd->cmd, pri_event2str(event_id), pri->span);
3229                         break;
3230                 }
3231         }
3232 }
3233
3234 #if defined(HAVE_PRI_AOC_EVENTS)
3235 /*!
3236  * \internal
3237  * \brief detect if AOC-S subcmd is present.
3238  * \since 1.8
3239  *
3240  * \param subcmds Subcommands to process if any. (Could be NULL).
3241  *
3242  * \note Knowing whether or not an AOC-E subcmd is present on certain
3243  * PRI hangup events is necessary to determine what method to use to hangup
3244  * the ast_channel.  If an AOC-E subcmd just came in, then a new AOC-E was queued
3245  * on the ast_channel.  If a soft hangup is used, the AOC-E msg will never make it
3246  * across the bridge, but if a AST_CONTROL_HANGUP frame is queued behind it
3247  * we can ensure the AOC-E frame makes it to it's destination before the hangup
3248  * frame is read.
3249  *
3250  *
3251  * \retval 0 AOC-E is not present in subcmd list
3252  * \retval 1 AOC-E is present in subcmd list
3253  */
3254 static int detect_aoc_e_subcmd(const struct pri_subcommands *subcmds)
3255 {
3256         int i;
3257
3258         if (!subcmds) {
3259                 return 0;