Extract sig_ss7 out of chan_dahdi.
[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 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, ulaw, 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         c->transfercapability = transfercapability;
803         pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY",
804                 ast_transfercapability2str(transfercapability));
805         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
806                 sig_pri_set_digital(p, 1);
807         }
808         if (p->pri && !pri_grab(p, p->pri)) {
809                 sig_pri_span_devstate_changed(p->pri);
810                 pri_rel(p->pri);
811         } else {
812                 ast_log(LOG_WARNING, "Failed to grab PRI!\n");
813         }
814
815         return c;
816 }
817
818 /*!
819  * \internal
820  * \brief Open the PRI channel media path.
821  * \since 1.8
822  *
823  * \param p Channel private control structure.
824  *
825  * \return Nothing
826  */
827 static void sig_pri_open_media(struct sig_pri_chan *p)
828 {
829         if (p->no_b_channel) {
830                 return;
831         }
832
833         if (p->calls->open_media) {
834                 p->calls->open_media(p->chan_pvt);
835         }
836 }
837
838 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
839 {
840         struct ast_channel *ast;
841
842         ast_log(LOG_DEBUG, "%s %d\n", __FUNCTION__, p->channel);
843
844         p->outgoing = 1;
845         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
846         if (!ast) {
847                 p->outgoing = 0;
848         }
849         return ast;
850 }
851
852 int pri_is_up(struct sig_pri_pri *pri)
853 {
854         int x;
855         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
856                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
857                         return 1;
858         }
859         return 0;
860 }
861
862 static char *pri_order(int level)
863 {
864         switch (level) {
865         case 0:
866                 return "Primary";
867         case 1:
868                 return "Secondary";
869         case 2:
870                 return "Tertiary";
871         case 3:
872                 return "Quaternary";
873         default:
874                 return "<Unknown>";
875         }
876 }
877
878 /* Returns index of the active dchan */
879 static int pri_active_dchan_index(struct sig_pri_pri *pri)
880 {
881         int x;
882
883         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
884                 if ((pri->dchans[x] == pri->pri))
885                         return x;
886         }
887
888         ast_log(LOG_WARNING, "No active dchan found!\n");
889         return -1;
890 }
891
892 static int pri_find_dchan(struct sig_pri_pri *pri)
893 {
894         int oldslot = -1;
895         struct pri *old;
896         int newslot = -1;
897         int x;
898         old = pri->pri;
899         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
900                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
901                         newslot = x;
902                 if (pri->dchans[x] == old) {
903                         oldslot = x;
904                 }
905         }
906         if (newslot < 0) {
907                 newslot = 0;
908                 /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
909                 if (pri->sig != SIG_BRI_PTMP) {
910                         ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel as D-channel anyway!\n");
911                 }
912         }
913         if (old && (oldslot != newslot))
914                 ast_log(LOG_NOTICE, "Switching from d-channel fd %d to fd %d!\n",
915                         pri->fds[oldslot], pri->fds[newslot]);
916         pri->pri = pri->dchans[newslot];
917         return 0;
918 }
919
920 /*!
921  * \internal
922  * \brief Obtain the sig_pri owner channel lock if the owner exists.
923  * \since 1.8
924  *
925  * \param pri sig_pri PRI control structure.
926  * \param chanpos Channel position in the span.
927  *
928  * \note Assumes the pri->lock is already obtained.
929  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
930  *
931  * \return Nothing
932  */
933 static void sig_pri_lock_owner(struct sig_pri_pri *pri, int chanpos)
934 {
935         for (;;) {
936                 if (!pri->pvts[chanpos]->owner) {
937                         /* There is no owner lock to get. */
938                         break;
939                 }
940                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
941                         /* We got the lock */
942                         break;
943                 }
944                 /* We must unlock the PRI to avoid the possibility of a deadlock */
945                 ast_mutex_unlock(&pri->lock);
946                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
947                 ast_mutex_lock(&pri->lock);
948         }
949 }
950
951 /*!
952  * \internal
953  * \brief Queue the given frame onto the owner channel.
954  * \since 1.8
955  *
956  * \param pri sig_pri PRI control structure.
957  * \param chanpos Channel position in the span.
958  * \param frame Frame to queue onto the owner channel.
959  *
960  * \note Assumes the pri->lock is already obtained.
961  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
962  *
963  * \return Nothing
964  */
965 static void pri_queue_frame(struct sig_pri_pri *pri, int chanpos, struct ast_frame *frame)
966 {
967         sig_pri_lock_owner(pri, chanpos);
968         if (pri->pvts[chanpos]->owner) {
969                 ast_queue_frame(pri->pvts[chanpos]->owner, frame);
970                 ast_channel_unlock(pri->pvts[chanpos]->owner);
971         }
972 }
973
974 /*!
975  * \internal
976  * \brief Queue a control frame of the specified subclass onto the owner channel.
977  * \since 1.8
978  *
979  * \param pri sig_pri PRI control structure.
980  * \param chanpos Channel position in the span.
981  * \param subclass Control frame subclass to queue onto the owner channel.
982  *
983  * \note Assumes the pri->lock is already obtained.
984  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
985  *
986  * \return Nothing
987  */
988 static void pri_queue_control(struct sig_pri_pri *pri, int chanpos, int subclass)
989 {
990         struct ast_frame f = {AST_FRAME_CONTROL, };
991         struct sig_pri_chan *p = pri->pvts[chanpos];
992
993         if (p->calls->queue_control) {
994                 p->calls->queue_control(p->chan_pvt, subclass);
995         }
996
997         f.subclass.integer = subclass;
998         pri_queue_frame(pri, chanpos, &f);
999 }
1000
1001 static int pri_find_principle(struct sig_pri_pri *pri, int channel, q931_call *call)
1002 {
1003         int x;
1004         int span;
1005         int principle;
1006         int prioffset;
1007
1008         if (channel < 0) {
1009                 /* Channel is not picked yet. */
1010                 return -1;
1011         }
1012
1013         prioffset = PRI_CHANNEL(channel);
1014         if (!prioffset || (channel & PRI_HELD_CALL)) {
1015                 if (!call) {
1016                         /* Cannot find a call waiting call or held call without a call. */
1017                         return -1;
1018                 }
1019                 principle = -1;
1020                 for (x = 0; x < pri->numchans; ++x) {
1021                         if (pri->pvts[x]
1022                                 && pri->pvts[x]->call == call) {
1023                                 principle = x;
1024                                 break;
1025                         }
1026                 }
1027                 return principle;
1028         }
1029
1030         span = PRI_SPAN(channel);
1031         if (!(channel & PRI_EXPLICIT)) {
1032                 int index;
1033
1034                 index = pri_active_dchan_index(pri);
1035                 if (index == -1) {
1036                         return -1;
1037                 }
1038                 span = pri->dchan_logical_span[index];
1039         }
1040
1041         principle = -1;
1042         for (x = 0; x < pri->numchans; x++) {
1043                 if (pri->pvts[x]
1044                         && pri->pvts[x]->prioffset == prioffset
1045                         && pri->pvts[x]->logicalspan == span
1046                         && !pri->pvts[x]->no_b_channel) {
1047                         principle = x;
1048                         break;
1049                 }
1050         }
1051
1052         return principle;
1053 }
1054
1055 static int pri_fixup_principle(struct sig_pri_pri *pri, int principle, q931_call *call)
1056 {
1057         int x;
1058
1059         if (principle < 0 || pri->numchans <= principle) {
1060                 /* Out of rannge */
1061                 return -1;
1062         }
1063         if (!call) {
1064                 /* No call */
1065                 return principle;
1066         }
1067         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
1068                 /* Call is already on the specified principle. */
1069                 return principle;
1070         }
1071
1072         /* Find the old principle location. */
1073         for (x = 0; x < pri->numchans; x++) {
1074                 struct sig_pri_chan *new_chan;
1075                 struct sig_pri_chan *old_chan;
1076
1077                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
1078                         continue;
1079                 }
1080
1081                 /* Found our call */
1082                 new_chan = pri->pvts[principle];
1083                 old_chan = pri->pvts[x];
1084
1085                 ast_verb(3, "Moving call from channel %d to channel %d\n",
1086                         old_chan->channel, new_chan->channel);
1087                 if (new_chan->owner) {
1088                         ast_log(LOG_WARNING,
1089                                 "Can't fix up channel from %d to %d because %d is already in use\n",
1090                                 old_chan->channel, new_chan->channel, new_chan->channel);
1091                         return -1;
1092                 }
1093
1094                 sig_pri_fixup_chans(old_chan, new_chan);
1095
1096                 /* Fix it all up now */
1097                 new_chan->owner = old_chan->owner;
1098                 old_chan->owner = NULL;
1099
1100                 new_chan->call = old_chan->call;
1101                 old_chan->call = NULL;
1102
1103                 /* Transfer flags from the old channel. */
1104 #if defined(HAVE_PRI_AOC_EVENTS)
1105                 new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
1106                 new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
1107                 new_chan->holding_aoce = old_chan->holding_aoce;
1108 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1109                 new_chan->alerting = old_chan->alerting;
1110                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1111                 new_chan->isidlecall = old_chan->isidlecall;
1112                 new_chan->proceeding = old_chan->proceeding;
1113                 new_chan->progress = old_chan->progress;
1114                 new_chan->setup_ack = old_chan->setup_ack;
1115                 new_chan->outgoing = old_chan->outgoing;
1116                 new_chan->digital = old_chan->digital;
1117 #if defined(HAVE_PRI_CALL_WAITING)
1118                 new_chan->is_call_waiting = old_chan->is_call_waiting;
1119 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1120
1121 #if defined(HAVE_PRI_AOC_EVENTS)
1122                 old_chan->aoc_s_request_invoke_id_valid = 0;
1123                 old_chan->waiting_for_aoce = 0;
1124                 old_chan->holding_aoce = 0;
1125 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1126                 old_chan->alerting = 0;
1127                 old_chan->alreadyhungup = 0;
1128                 old_chan->isidlecall = 0;
1129                 old_chan->proceeding = 0;
1130                 old_chan->progress = 0;
1131                 old_chan->setup_ack = 0;
1132                 old_chan->outgoing = 0;
1133                 old_chan->digital = 0;
1134 #if defined(HAVE_PRI_CALL_WAITING)
1135                 old_chan->is_call_waiting = 0;
1136 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1137
1138                 /* More stuff to transfer to the new channel. */
1139 #if defined(HAVE_PRI_REVERSE_CHARGE)
1140                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1141 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1142 #if defined(HAVE_PRI_SETUP_KEYPAD)
1143                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1144 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1145 #if defined(HAVE_PRI_AOC_EVENTS)
1146                 new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
1147                 new_chan->aoc_e = old_chan->aoc_e;
1148 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1149
1150                 if (new_chan->no_b_channel) {
1151                         /* Copy the real channel configuration to the no B channel interface. */
1152                         new_chan->hidecallerid = old_chan->hidecallerid;
1153                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1154                         new_chan->immediate = old_chan->immediate;
1155                         new_chan->priexclusive = old_chan->priexclusive;
1156                         new_chan->priindication_oob = old_chan->priindication_oob;
1157                         new_chan->use_callerid = old_chan->use_callerid;
1158                         new_chan->use_callingpres = old_chan->use_callingpres;
1159                         new_chan->stripmsd = old_chan->stripmsd;
1160                         strcpy(new_chan->context, old_chan->context);
1161                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1162
1163                         /* Become a member of the old channel span/trunk-group. */
1164                         new_chan->logicalspan = old_chan->logicalspan;
1165                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1166                 }
1167
1168                 return principle;
1169         }
1170         ast_verb(3, "Call specified, but not found.\n");
1171         return -1;
1172 }
1173
1174 static char * redirectingreason2str(int redirectingreason)
1175 {
1176         switch (redirectingreason) {
1177         case 0:
1178                 return "UNKNOWN";
1179         case 1:
1180                 return "BUSY";
1181         case 2:
1182                 return "NO_REPLY";
1183         case 0xF:
1184                 return "UNCONDITIONAL";
1185         default:
1186                 return "NOREDIRECT";
1187         }
1188 }
1189
1190 static char *dialplan2str(int dialplan)
1191 {
1192         if (dialplan == -1) {
1193                 return("Dynamically set dialplan in ISDN");
1194         }
1195         return (pri_plan2str(dialplan));
1196 }
1197
1198 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_pri *pri, const char *number, const int plan)
1199 {
1200         switch (plan) {
1201         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1202                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1203                 break;
1204         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1205                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1206                 break;
1207         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1208                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1209                 break;
1210         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1211                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1212                 break;
1213         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1214                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1215                 break;
1216         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1217                 snprintf(buf, size, "%s", number);
1218                 break;
1219         }
1220 }
1221
1222 /*! \note Assumes the pri->lock is already obtained. */
1223 static int pri_check_restart(struct sig_pri_pri *pri)
1224 {
1225 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1226 tryanotherpos:
1227 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1228         do {
1229                 pri->resetpos++;
1230         } while (pri->resetpos < pri->numchans
1231                 && (!pri->pvts[pri->resetpos]
1232                         || pri->pvts[pri->resetpos]->no_b_channel
1233                         || pri->pvts[pri->resetpos]->call
1234                         || pri->pvts[pri->resetpos]->resetting));
1235         if (pri->resetpos < pri->numchans) {
1236 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1237                 unsigned why;
1238
1239                 why = pri->pvts[pri->resetpos]->service_status;
1240                 if (why) {
1241                         ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1242                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1243                         goto tryanotherpos;
1244                 }
1245 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1246
1247                 /* Mark the channel as resetting and restart it */
1248                 pri->pvts[pri->resetpos]->resetting = 1;
1249                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1250         } else {
1251                 pri->resetting = 0;
1252                 time(&pri->lastreset);
1253         }
1254         return 0;
1255 }
1256
1257 #if defined(HAVE_PRI_CALL_WAITING)
1258 /*!
1259  * \internal
1260  * \brief Init the private channel configuration using the span controller.
1261  * \since 1.8
1262  *
1263  * \param pvt Channel to init the configuration.
1264  * \param pri sig_pri PRI control structure.
1265  *
1266  * \note Assumes the pri->lock is already obtained.
1267  *
1268  * \return Nothing
1269  */
1270 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_pri *pri)
1271 {
1272         pvt->stripmsd = pri->ch_cfg.stripmsd;
1273         pvt->hidecallerid = pri->ch_cfg.hidecallerid;
1274         pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
1275         pvt->immediate = pri->ch_cfg.immediate;
1276         pvt->priexclusive = pri->ch_cfg.priexclusive;
1277         pvt->priindication_oob = pri->ch_cfg.priindication_oob;
1278         pvt->use_callerid = pri->ch_cfg.use_callerid;
1279         pvt->use_callingpres = pri->ch_cfg.use_callingpres;
1280         ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
1281         ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
1282
1283         if (pri->calls->init_config) {
1284                 pri->calls->init_config(pvt->chan_pvt, pri);
1285         }
1286 }
1287 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1288
1289 static int pri_find_empty_chan(struct sig_pri_pri *pri, int backwards)
1290 {
1291         int x;
1292         if (backwards)
1293                 x = pri->numchans;
1294         else
1295                 x = 0;
1296         for (;;) {
1297                 if (backwards && (x < 0))
1298                         break;
1299                 if (!backwards && (x >= pri->numchans))
1300                         break;
1301                 if (pri->pvts[x]
1302                         && !pri->pvts[x]->no_b_channel
1303                         && !pri->pvts[x]->inalarm
1304                         && !pri->pvts[x]->owner) {
1305                         ast_debug(1, "Found empty available channel %d/%d\n",
1306                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1307                         return x;
1308                 }
1309                 if (backwards)
1310                         x--;
1311                 else
1312                         x++;
1313         }
1314         return -1;
1315 }
1316
1317 #if defined(HAVE_PRI_CALL_HOLD)
1318 /*!
1319  * \internal
1320  * \brief Find or create an empty no-B-channel interface to use.
1321  * \since 1.8
1322  *
1323  * \param pri sig_pri span controller to find interface.
1324  *
1325  * \note Assumes the pri->lock is already obtained.
1326  *
1327  * \retval array-index into private pointer array on success.
1328  * \retval -1 on error.
1329  */
1330 static int pri_find_empty_nobch(struct sig_pri_pri *pri)
1331 {
1332         int idx;
1333
1334         for (idx = 0; idx < pri->numchans; ++idx) {
1335                 if (pri->pvts[idx]
1336                         && pri->pvts[idx]->no_b_channel
1337                         && !pri->pvts[idx]->inalarm
1338                         && !pri->pvts[idx]->owner) {
1339                         ast_debug(1, "Found empty available no B channel interface\n");
1340                         return idx;
1341                 }
1342         }
1343
1344         /* Need to create a new interface. */
1345         if (pri->calls->new_nobch_intf) {
1346                 idx = pri->calls->new_nobch_intf(pri);
1347         } else {
1348                 idx = -1;
1349         }
1350         return idx;
1351 }
1352 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1353
1354 #if defined(HAVE_PRI_CALL_HOLD)
1355 /*!
1356  * \internal
1357  * \brief Find the channel associated with the libpri call.
1358  * \since 1.8
1359  *
1360  * \param pri sig_pri span controller to find interface.
1361  * \param call LibPRI opaque call pointer to find.
1362  *
1363  * \note Assumes the pri->lock is already obtained.
1364  *
1365  * \retval array-index into private pointer array on success.
1366  * \retval -1 on error.
1367  */
1368 static int pri_find_pri_call(struct sig_pri_pri *pri, q931_call *call)
1369 {
1370         int idx;
1371
1372         for (idx = 0; idx < pri->numchans; ++idx) {
1373                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1374                         /* Found the channel */
1375                         return idx;
1376                 }
1377         }
1378         return -1;
1379 }
1380 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1381
1382 static void *do_idle_thread(void *v_pvt)
1383 {
1384         struct sig_pri_chan *pvt = v_pvt;
1385         struct ast_channel *chan = pvt->owner;
1386         struct ast_frame *f;
1387         char ex[80];
1388         /* Wait up to 30 seconds for an answer */
1389         int newms, ms = 30000;
1390
1391         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1392         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1393         if (ast_call(chan, ex, 0)) {
1394                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1395                 ast_hangup(chan);
1396                 return NULL;
1397         }
1398         while ((newms = ast_waitfor(chan, ms)) > 0) {
1399                 f = ast_read(chan);
1400                 if (!f) {
1401                         /* Got hangup */
1402                         break;
1403                 }
1404                 if (f->frametype == AST_FRAME_CONTROL) {
1405                         switch (f->subclass.integer) {
1406                         case AST_CONTROL_ANSWER:
1407                                 /* Launch the PBX */
1408                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1409                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1410                                 chan->priority = 1;
1411                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1412                                 ast_pbx_run(chan);
1413                                 /* It's already hungup, return immediately */
1414                                 return NULL;
1415                         case AST_CONTROL_BUSY:
1416                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1417                                 break;
1418                         case AST_CONTROL_CONGESTION:
1419                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1420                                 break;
1421                         };
1422                 }
1423                 ast_frfree(f);
1424                 ms = newms;
1425         }
1426         /* Hangup the channel since nothing happend */
1427         ast_hangup(chan);
1428         return NULL;
1429 }
1430
1431 static void *pri_ss_thread(void *data)
1432 {
1433         struct sig_pri_chan *p = data;
1434         struct ast_channel *chan = p->owner;
1435         char exten[AST_MAX_EXTENSION];
1436         int res;
1437         int len;
1438         int timeout;
1439
1440         if (!chan) {
1441                 /* We lost the owner before we could get started. */
1442                 return NULL;
1443         }
1444
1445         /*
1446          * In the bizarre case where the channel has become a zombie before we
1447          * even get started here, abort safely.
1448          */
1449         if (!chan->tech_pvt) {
1450                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1451                 ast_hangup(chan);
1452                 return NULL;
1453         }
1454
1455         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1456
1457         sig_pri_dsp_reset_and_flush_digits(p);
1458
1459         /* Now loop looking for an extension */
1460         ast_copy_string(exten, p->exten, sizeof(exten));
1461         len = strlen(exten);
1462         res = 0;
1463         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1464                 if (len && !ast_ignore_pattern(chan->context, exten))
1465                         sig_pri_play_tone(p, -1);
1466                 else
1467                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1468                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1469                         timeout = pri_matchdigittimeout;
1470                 else
1471                         timeout = pri_gendigittimeout;
1472                 res = ast_waitfordigit(chan, timeout);
1473                 if (res < 0) {
1474                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
1475                         ast_hangup(chan);
1476                         return NULL;
1477                 } else if (res) {
1478                         exten[len++] = res;
1479                         exten[len] = '\0';
1480                 } else
1481                         break;
1482         }
1483         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1484         if (ast_strlen_zero(exten)) {
1485                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1486                 exten[0] = 's';
1487                 exten[1] = '\0';
1488         } else {
1489                 if (chan->cid.cid_dnid) {
1490                         ast_free(chan->cid.cid_dnid);
1491                 }
1492                 chan->cid.cid_dnid = ast_strdup(exten);
1493         }
1494         sig_pri_play_tone(p, -1);
1495         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1496                 /* Start the real PBX */
1497                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1498                 sig_pri_dsp_reset_and_flush_digits(p);
1499                 if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
1500                         if (p->pri->pri) {              
1501                                 if (!pri_grab(p, p->pri)) {
1502                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1503                                         p->proceeding = 1;
1504                                         pri_rel(p->pri);
1505                                 } else {
1506                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1507                                 }
1508                         }
1509                 }
1510
1511                 sig_pri_set_echocanceller(p, 1);
1512                 ast_setstate(chan, AST_STATE_RING);
1513                 res = ast_pbx_run(chan);
1514                 if (res) {
1515                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1516                 }
1517         } else {
1518                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1519                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1520                 ast_hangup(chan);
1521                 p->exten[0] = '\0';
1522                 /* Since we send release complete here, we won't get one */
1523                 p->call = NULL;
1524         }
1525         return NULL;
1526 }
1527
1528 void pri_event_alarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1529 {
1530         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1531         if (!before_start_pri)
1532                 pri_find_dchan(pri);
1533 }
1534
1535 void pri_event_noalarm(struct sig_pri_pri *pri, int index, int before_start_pri)
1536 {
1537         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1538         if (!before_start_pri)
1539                 pri_restart(pri->dchans[index]);
1540 }
1541
1542 /*!
1543  * \internal
1544  * \brief Convert libpri party id into asterisk party id.
1545  * \since 1.8
1546  *
1547  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1548  * \param pri_id libpri party id structure containing source information.
1549  * \param pri Span controlling structure.
1550  *
1551  * \note The filled in ast_id structure needs to be destroyed by
1552  * ast_party_id_free() when it is no longer needed.
1553  *
1554  * \return Nothing
1555  */
1556 static void sig_pri_party_id_convert(struct ast_party_id *ast_id,
1557         const struct pri_party_id *pri_id, struct sig_pri_pri *pri)
1558 {
1559         char number[AST_MAX_EXTENSION];
1560
1561         if (pri_id->name.valid) {
1562                 ast_id->name = ast_strdup(pri_id->name.str);
1563         }
1564         if (pri_id->number.valid) {
1565                 apply_plan_to_number(number, sizeof(number), pri, pri_id->number.str,
1566                         pri_id->number.plan);
1567                 ast_id->number = ast_strdup(number);
1568                 ast_id->number_type = pri_id->number.plan;
1569         }
1570         if (pri_id->name.valid || pri_id->number.valid) {
1571                 ast_id->number_presentation = overall_ast_presentation(pri_id);
1572         }
1573 #if defined(HAVE_PRI_SUBADDR)
1574         if (pri_id->subaddress.valid) {
1575                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1576         }
1577 #endif  /* defined(HAVE_PRI_SUBADDR) */
1578 }
1579
1580 /*!
1581  * \internal
1582  * \brief Convert libpri redirecting information into asterisk redirecting information.
1583  * \since 1.8
1584  *
1585  * \param ast_redirecting Asterisk redirecting structure to fill.
1586  * \param pri_redirecting libpri redirecting structure containing source information.
1587  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1588  * \param pri Span controlling structure.
1589  *
1590  * \note The filled in ast_redirecting structure needs to be destroyed by
1591  * ast_party_redirecting_free() when it is no longer needed.
1592  *
1593  * \return Nothing
1594  */
1595 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1596         const struct pri_party_redirecting *pri_redirecting,
1597         const struct ast_party_redirecting *ast_guide,
1598         struct sig_pri_pri *pri)
1599 {
1600         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1601
1602         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1603         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1604         ast_redirecting->count = pri_redirecting->count;
1605         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1606 }
1607
1608 /*!
1609  * \internal
1610  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1611  * \since 1.8
1612  *
1613  * \param msn_patterns Comma separated list of MSN patterns to match.
1614  * \param exten Extension to match in the MSN list.
1615  *
1616  * \retval 1 if matches.
1617  * \retval 0 if no match.
1618  */
1619 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1620 {
1621         char *pattern;
1622         char *msn_list;
1623         char *list_tail;
1624
1625         msn_list = strdupa(msn_patterns);
1626
1627         list_tail = NULL;
1628         pattern = strtok_r(msn_list, ",", &list_tail);
1629         while (pattern) {
1630                 pattern = ast_strip(pattern);
1631                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1632                         /* Extension matched the pattern. */
1633                         return 1;
1634                 }
1635                 pattern = strtok_r(NULL, ",", &list_tail);
1636         }
1637         /* Did not match any pattern in the list. */
1638         return 0;
1639 }
1640
1641 #if defined(HAVE_PRI_MCID)
1642 /*!
1643  * \internal
1644  * \brief Append the given party id to the event string.
1645  * \since 1.8
1646  *
1647  * \param msg Event message string being built.
1648  * \param prefix Prefix to add to the party id lines.
1649  * \param party Party information to encode.
1650  *
1651  * \return Nothing
1652  */
1653 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
1654 {
1655         ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix,
1656                 party->number_presentation,
1657                 ast_describe_caller_presentation(party->number_presentation));
1658         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix, S_OR(party->number, ""));
1659         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number_type);
1660         ast_str_append(msg, 0, "%sName: %s\r\n", prefix, S_OR(party->name, ""));
1661 #if defined(HAVE_PRI_SUBADDR)
1662         if (party->subaddress.valid) {
1663                 static const char subaddress[] = "Subaddr";
1664
1665                 ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
1666                         S_OR(party->subaddress.str, ""));
1667                 ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
1668                         party->subaddress.type);
1669                 ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
1670                         party->subaddress.odd_even_indicator);
1671         }
1672 #endif  /* defined(HAVE_PRI_SUBADDR) */
1673 }
1674 #endif  /* defined(HAVE_PRI_MCID) */
1675
1676 #if defined(HAVE_PRI_MCID)
1677 /*!
1678  * \internal
1679  * \brief Handle the MCID event.
1680  * \since 1.8
1681  *
1682  * \param pri sig_pri PRI control structure.
1683  * \param mcid MCID event parameters.
1684  * \param owner Asterisk channel associated with the call.
1685  * NULL if Asterisk no longer has the ast_channel struct.
1686  *
1687  * \note Assumes the pri->lock is already obtained.
1688  * \note Assumes the owner channel lock is already obtained if still present.
1689  *
1690  * \return Nothing
1691  */
1692 static void sig_pri_mcid_event(struct sig_pri_pri *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
1693 {
1694         struct ast_channel *chans[1];
1695         struct ast_str *msg;
1696         struct ast_party_id party;
1697
1698         msg = ast_str_create(4096);
1699         if (!msg) {
1700                 return;
1701         }
1702
1703         if (owner) {
1704                 /* The owner channel is present. */
1705                 ast_str_append(&msg, 0, "Channel: %s\r\n", owner->name);
1706                 ast_str_append(&msg, 0, "UniqueID: %s\r\n", owner->uniqueid);
1707
1708                 sig_pri_event_party_id(&msg, "CallerID", &owner->connected.id);
1709         } else {
1710                 /*
1711                  * Since we no longer have an owner channel,
1712                  * we have to use the caller information supplied by libpri.
1713                  */
1714                 ast_party_id_init(&party);
1715                 sig_pri_party_id_convert(&party, &mcid->originator, pri);
1716                 sig_pri_event_party_id(&msg, "CallerID", &party);
1717                 ast_party_id_free(&party);
1718         }
1719
1720         /* Always use libpri's called party information. */
1721         ast_party_id_init(&party);
1722         sig_pri_party_id_convert(&party, &mcid->answerer, pri);
1723         sig_pri_event_party_id(&msg, "ConnectedID", &party);
1724         ast_party_id_free(&party);
1725
1726         chans[0] = owner;
1727         ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
1728                 ast_str_buffer(msg));
1729         ast_free(msg);
1730 }
1731 #endif  /* defined(HAVE_PRI_MCID) */
1732
1733 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
1734 /*!
1735  * \internal
1736  * \brief Attempt to transfer the two calls to each other.
1737  * \since 1.8
1738  *
1739  * \param pri sig_pri PRI control structure.
1740  * \param call_1 First call involved in the transfer.
1741  * \param call_1_held TRUE if call_1 is on hold.
1742  * \param call_2 Second call involved in the transfer.
1743  * \param call_2_held TRUE if call_2 is on hold.
1744  *
1745  * \note Assumes the pri->lock is already obtained.
1746  *
1747  * \retval 0 on success.
1748  * \retval -1 on error.
1749  */
1750 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)
1751 {
1752         int retval;
1753         int call_1_chanpos;
1754         int call_2_chanpos;
1755         struct ast_channel *call_1_ast;
1756         struct ast_channel *call_2_ast;
1757         struct ast_channel *bridged;
1758
1759         call_1_chanpos = pri_find_pri_call(pri, call_1);
1760         call_2_chanpos = pri_find_pri_call(pri, call_2);
1761         if (call_1_chanpos < 0 || call_2_chanpos < 0) {
1762                 return -1;
1763         }
1764
1765         /* Deadlock avoidance is attempted. */
1766         sig_pri_lock_private(pri->pvts[call_1_chanpos]);
1767         sig_pri_lock_owner(pri, call_1_chanpos);
1768         sig_pri_lock_private(pri->pvts[call_2_chanpos]);
1769         sig_pri_lock_owner(pri, call_2_chanpos);
1770
1771         call_1_ast = pri->pvts[call_1_chanpos]->owner;
1772         call_2_ast = pri->pvts[call_2_chanpos]->owner;
1773         if (!call_1_ast || !call_2_ast) {
1774                 if (call_1_ast) {
1775                         ast_channel_unlock(call_1_ast);
1776                 }
1777                 if (call_2_ast) {
1778                         ast_channel_unlock(call_2_ast);
1779                 }
1780                 sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1781                 sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1782                 return -1;
1783         }
1784
1785         bridged = ast_bridged_channel(call_2_ast);
1786         if (bridged) {
1787                 if (call_1_held) {
1788                         ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1789                 }
1790                 if (call_2_held) {
1791                         ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1792                 }
1793
1794                 ast_verb(3, "TRANSFERRING %s to %s\n", call_2_ast->name, call_1_ast->name);
1795                 retval = ast_channel_masquerade(call_1_ast, bridged);
1796         } else {
1797                 /* Try masquerading the other way. */
1798                 bridged = ast_bridged_channel(call_1_ast);
1799                 if (bridged) {
1800                         if (call_1_held) {
1801                                 ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1802                         }
1803                         if (call_2_held) {
1804                                 ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1805                         }
1806
1807                         ast_verb(3, "TRANSFERRING %s to %s\n", call_1_ast->name, call_2_ast->name);
1808                         retval = ast_channel_masquerade(call_2_ast, bridged);
1809                 } else {
1810                         /* Could not transfer. */
1811                         retval = -1;
1812                 }
1813         }
1814         if (bridged && retval) {
1815                 /* Restore HOLD on held calls because masquerade failed. */
1816                 if (call_1_held) {
1817                         ast_queue_control(call_1_ast, AST_CONTROL_HOLD);
1818                 }
1819                 if (call_2_held) {
1820                         ast_queue_control(call_2_ast, AST_CONTROL_HOLD);
1821                 }
1822         }
1823
1824         ast_channel_unlock(call_1_ast);
1825         ast_channel_unlock(call_2_ast);
1826         sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1827         sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1828
1829         return retval;
1830 }
1831 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
1832
1833 #if defined(HAVE_PRI_CCSS)
1834 /*!
1835  * \internal
1836  * \brief Compare the CC agent private data by libpri cc_id.
1837  * \since 1.8
1838  *
1839  * \param obj pointer to the (user-defined part) of an object.
1840  * \param arg callback argument from ao2_callback()
1841  * \param flags flags from ao2_callback()
1842  *
1843  * \return values are a combination of enum _cb_results.
1844  */
1845 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
1846 {
1847         struct ast_cc_agent *agent_1 = obj;
1848         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
1849         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
1850
1851         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
1852                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1853 }
1854 #endif  /* defined(HAVE_PRI_CCSS) */
1855
1856 #if defined(HAVE_PRI_CCSS)
1857 /*!
1858  * \internal
1859  * \brief Find the CC agent by libpri cc_id.
1860  * \since 1.8
1861  *
1862  * \param pri sig_pri PRI control structure.
1863  * \param cc_id CC record ID to find.
1864  *
1865  * \note
1866  * Since agents are refcounted, and this function returns
1867  * a reference to the agent, it is imperative that you decrement
1868  * the refcount of the agent once you have finished using it.
1869  *
1870  * \retval agent on success.
1871  * \retval NULL not found.
1872  */
1873 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1874 {
1875         struct sig_pri_cc_agent_prv finder = {
1876                 .pri = pri,
1877                 .cc_id = cc_id,
1878         };
1879
1880         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
1881                 sig_pri_cc_type_name);
1882 }
1883 #endif  /* defined(HAVE_PRI_CCSS) */
1884
1885 #if defined(HAVE_PRI_CCSS)
1886 /*!
1887  * \internal
1888  * \brief Compare the CC monitor instance by libpri cc_id.
1889  * \since 1.8
1890  *
1891  * \param obj pointer to the (user-defined part) of an object.
1892  * \param arg callback argument from ao2_callback()
1893  * \param flags flags from ao2_callback()
1894  *
1895  * \return values are a combination of enum _cb_results.
1896  */
1897 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
1898 {
1899         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
1900         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
1901
1902         return (monitor_1->pri == monitor_2->pri
1903                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1904 }
1905 #endif  /* defined(HAVE_PRI_CCSS) */
1906
1907 #if defined(HAVE_PRI_CCSS)
1908 /*!
1909  * \internal
1910  * \brief Find the CC monitor instance by libpri cc_id.
1911  * \since 1.8
1912  *
1913  * \param pri sig_pri PRI control structure.
1914  * \param cc_id CC record ID to find.
1915  *
1916  * \note
1917  * Since monitor_instances are refcounted, and this function returns
1918  * a reference to the instance, it is imperative that you decrement
1919  * the refcount of the instance once you have finished using it.
1920  *
1921  * \retval monitor_instance on success.
1922  * \retval NULL not found.
1923  */
1924 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1925 {
1926         struct sig_pri_cc_monitor_instance finder = {
1927                 .pri = pri,
1928                 .cc_id = cc_id,
1929         };
1930
1931         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
1932 }
1933 #endif  /* defined(HAVE_PRI_CCSS) */
1934
1935 #if defined(HAVE_PRI_CCSS)
1936 /*!
1937  * \internal
1938  * \brief Destroy the given monitor instance.
1939  * \since 1.8
1940  *
1941  * \param data Monitor instance to destroy.
1942  *
1943  * \return Nothing
1944  */
1945 static void sig_pri_cc_monitor_instance_destroy(void *data)
1946 {
1947         struct sig_pri_cc_monitor_instance *monitor_instance = data;
1948
1949         if (monitor_instance->cc_id != -1) {
1950                 ast_mutex_lock(&monitor_instance->pri->lock);
1951                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
1952                 ast_mutex_unlock(&monitor_instance->pri->lock);
1953         }
1954         monitor_instance->pri->calls->module_unref();
1955 }
1956 #endif  /* defined(HAVE_PRI_CCSS) */
1957
1958 #if defined(HAVE_PRI_CCSS)
1959 /*!
1960  * \internal
1961  * \brief Construct a new monitor instance.
1962  * \since 1.8
1963  *
1964  * \param core_id CC core ID.
1965  * \param pri sig_pri PRI control structure.
1966  * \param cc_id CC record ID.
1967  * \param device_name Name of device (Asterisk channel name less sequence number).
1968  *
1969  * \note
1970  * Since monitor_instances are refcounted, and this function returns
1971  * a reference to the instance, it is imperative that you decrement
1972  * the refcount of the instance once you have finished using it.
1973  *
1974  * \retval monitor_instance on success.
1975  * \retval NULL on error.
1976  */
1977 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)
1978 {
1979         struct sig_pri_cc_monitor_instance *monitor_instance;
1980
1981         if (!pri->calls->module_ref || !pri->calls->module_unref) {
1982                 return NULL;
1983         }
1984
1985         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
1986                 sig_pri_cc_monitor_instance_destroy);
1987         if (!monitor_instance) {
1988                 return NULL;
1989         }
1990
1991         monitor_instance->cc_id = cc_id;
1992         monitor_instance->pri = pri;
1993         monitor_instance->core_id = core_id;
1994         strcpy(monitor_instance->name, device_name);
1995
1996         pri->calls->module_ref();
1997
1998         ao2_link(sig_pri_cc_monitors, monitor_instance);
1999         return monitor_instance;
2000 }
2001 #endif  /* defined(HAVE_PRI_CCSS) */
2002
2003 #if defined(HAVE_PRI_CCSS)
2004 /*!
2005  * \internal
2006  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2007  * \since 1.8
2008  *
2009  * \param pri sig_pri PRI control structure.
2010  * \param chanpos Channel position in the span.
2011  * \param cc_id CC record ID.
2012  * \param service CCBS/CCNR indication.
2013  *
2014  * \note Assumes the pri->lock is already obtained.
2015  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2016  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2017  *
2018  * \retval 0 on success.
2019  * \retval -1 on error.
2020  */
2021 static int sig_pri_cc_available(struct sig_pri_pri *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2022 {
2023         struct sig_pri_chan *pvt;
2024         struct ast_cc_config_params *cc_params;
2025         struct sig_pri_cc_monitor_instance *monitor;
2026         enum ast_cc_monitor_policies monitor_policy;
2027         int core_id;
2028         int res;
2029         char device_name[AST_CHANNEL_NAME];
2030         char dialstring[AST_CHANNEL_NAME];
2031
2032         pvt = pri->pvts[chanpos];
2033
2034         core_id = ast_cc_get_current_core_id(pvt->owner);
2035         if (core_id == -1) {
2036                 return -1;
2037         }
2038
2039         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2040         if (!cc_params) {
2041                 return -1;
2042         }
2043
2044         res = -1;
2045         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2046         switch (monitor_policy) {
2047         case AST_CC_MONITOR_NEVER:
2048                 /* CCSS is not enabled. */
2049                 break;
2050         case AST_CC_MONITOR_NATIVE:
2051         case AST_CC_MONITOR_ALWAYS:
2052                 /*
2053                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2054                  * later in the call to sig_pri_cc_generic_check().
2055                  */
2056                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2057                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2058                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2059                 if (!monitor) {
2060                         break;
2061                 }
2062                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2063                         monitor);
2064                 if (res) {
2065                         monitor->cc_id = -1;
2066                         ao2_unlink(sig_pri_cc_monitors, monitor);
2067                         ao2_ref(monitor, -1);
2068                 }
2069                 break;
2070         case AST_CC_MONITOR_GENERIC:
2071                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2072                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2073                 /* Say it failed to force caller to cancel native CC. */
2074                 break;
2075         }
2076         return res;
2077 }
2078 #endif  /* defined(HAVE_PRI_CCSS) */
2079
2080 /*!
2081  * \internal
2082  * \brief Check if generic CC monitor is needed and request it.
2083  * \since 1.8
2084  *
2085  * \param pri sig_pri PRI control structure.
2086  * \param chanpos Channel position in the span.
2087  * \param service CCBS/CCNR indication.
2088  *
2089  * \note Assumes the pri->lock is already obtained.
2090  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2091  *
2092  * \return Nothing
2093  */
2094 static void sig_pri_cc_generic_check(struct sig_pri_pri *pri, int chanpos, enum ast_cc_service_type service)
2095 {
2096         struct ast_channel *owner;
2097         struct ast_cc_config_params *cc_params;
2098 #if defined(HAVE_PRI_CCSS)
2099         struct ast_cc_monitor *monitor;
2100         char device_name[AST_CHANNEL_NAME];
2101 #endif  /* defined(HAVE_PRI_CCSS) */
2102         enum ast_cc_monitor_policies monitor_policy;
2103         int core_id;
2104
2105         if (!pri->pvts[chanpos]->outgoing) {
2106                 /* This is not an outgoing call so it cannot be CC monitor. */
2107                 return;
2108         }
2109
2110         sig_pri_lock_owner(pri, chanpos);
2111         owner = pri->pvts[chanpos]->owner;
2112         if (!owner) {
2113                 return;
2114         }
2115         core_id = ast_cc_get_current_core_id(owner);
2116         if (core_id == -1) {
2117                 /* No CC core setup */
2118                 goto done;
2119         }
2120
2121         cc_params = ast_channel_get_cc_config_params(owner);
2122         if (!cc_params) {
2123                 /* Could not get CC config parameters. */
2124                 goto done;
2125         }
2126
2127 #if defined(HAVE_PRI_CCSS)
2128         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
2129         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
2130         if (monitor) {
2131                 /* CC monitor is already present so no need for generic CC. */
2132                 ao2_ref(monitor, -1);
2133                 goto done;
2134         }
2135 #endif  /* defined(HAVE_PRI_CCSS) */
2136
2137         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2138         switch (monitor_policy) {
2139         case AST_CC_MONITOR_NEVER:
2140                 /* CCSS is not enabled. */
2141                 break;
2142         case AST_CC_MONITOR_NATIVE:
2143                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2144                         /* Request generic CC monitor. */
2145                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2146                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2147                 }
2148                 break;
2149         case AST_CC_MONITOR_ALWAYS:
2150                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2151                         /*
2152                          * Cannot monitor PTMP TE side since this is not defined.
2153                          * We are playing the roll of a phone in this case and
2154                          * a phone cannot monitor a party over the network without
2155                          * protocol help.
2156                          */
2157                         break;
2158                 }
2159                 /*
2160                  * We are either falling back or this is a PTMP NT span.
2161                  * Request generic CC monitor.
2162                  */
2163                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2164                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2165                 break;
2166         case AST_CC_MONITOR_GENERIC:
2167                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2168                         /* Request generic CC monitor. */
2169                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2170                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2171                 }
2172                 break;
2173         }
2174
2175 done:
2176         ast_channel_unlock(owner);
2177 }
2178
2179 #if defined(HAVE_PRI_CCSS)
2180 /*!
2181  * \internal
2182  * \brief The CC link canceled the CC instance.
2183  * \since 1.8
2184  *
2185  * \param pri sig_pri PRI control structure.
2186  * \param cc_id CC record ID.
2187  * \param is_agent TRUE if the cc_id is for an agent.
2188  *
2189  * \return Nothing
2190  */
2191 static void sig_pri_cc_link_canceled(struct sig_pri_pri *pri, long cc_id, int is_agent)
2192 {
2193         if (is_agent) {
2194                 struct ast_cc_agent *agent;
2195
2196                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2197                 if (!agent) {
2198                         return;
2199                 }
2200                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2201                         sig_pri_cc_type_name);
2202                 ao2_ref(agent, -1);
2203         } else {
2204                 struct sig_pri_cc_monitor_instance *monitor;
2205
2206                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2207                 if (!monitor) {
2208                         return;
2209                 }
2210                 monitor->cc_id = -1;
2211                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2212                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2213                 ao2_ref(monitor, -1);
2214         }
2215 }
2216 #endif  /* defined(HAVE_PRI_CCSS) */
2217
2218 #if defined(HAVE_PRI_AOC_EVENTS)
2219 /*!
2220  * \internal
2221  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2222  * \since 1.8
2223  *
2224  * \param value Value to convert to string.
2225  *
2226  * \return PRI_AOC_CHARGED_ITEM
2227  */
2228 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2229 {
2230         switch (value) {
2231         case AST_AOC_CHARGED_ITEM_NA:
2232                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2233         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2234                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2235         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2236                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2237         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2238                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2239         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2240                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2241         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2242                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2243         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2244                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2245         }
2246         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2247 }
2248 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2249
2250 #if defined(HAVE_PRI_AOC_EVENTS)
2251 /*!
2252  * \internal
2253  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2254  * \since 1.8
2255  *
2256  * \param value Value to convert to string.
2257  *
2258  * \return ast_aoc_charged_item
2259  */
2260 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2261 {
2262         switch (value) {
2263         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2264                 return AST_AOC_CHARGED_ITEM_NA;
2265         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2266                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2267         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2268                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2269         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2270                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2271         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2272                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2273         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2274                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2275         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2276                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2277         }
2278         return AST_AOC_CHARGED_ITEM_NA;
2279 }
2280 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2281
2282 #if defined(HAVE_PRI_AOC_EVENTS)
2283 /*!
2284  * \internal
2285  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2286  * \since 1.8
2287  *
2288  * \return pri enum equivalent.
2289  */
2290 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2291 {
2292         switch (mult) {
2293         case AST_AOC_MULT_ONETHOUSANDTH:
2294                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2295         case AST_AOC_MULT_ONEHUNDREDTH:
2296                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2297         case AST_AOC_MULT_ONETENTH:
2298                 return PRI_AOC_MULTIPLIER_TENTH;
2299         case AST_AOC_MULT_ONE:
2300                 return PRI_AOC_MULTIPLIER_ONE;
2301         case AST_AOC_MULT_TEN:
2302                 return PRI_AOC_MULTIPLIER_TEN;
2303         case AST_AOC_MULT_HUNDRED:
2304                 return PRI_AOC_MULTIPLIER_HUNDRED;
2305         case AST_AOC_MULT_THOUSAND:
2306                 return PRI_AOC_MULTIPLIER_THOUSAND;
2307         default:
2308                 return PRI_AOC_MULTIPLIER_ONE;
2309         }
2310 }
2311 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2312
2313 #if defined(HAVE_PRI_AOC_EVENTS)
2314 /*!
2315  * \internal
2316  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2317  * \since 1.8
2318  *
2319  * \return ast enum equivalent.
2320  */
2321 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2322 {
2323         switch (mult) {
2324         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2325                 return AST_AOC_MULT_ONETHOUSANDTH;
2326         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2327                 return AST_AOC_MULT_ONEHUNDREDTH;
2328         case PRI_AOC_MULTIPLIER_TENTH:
2329                 return AST_AOC_MULT_ONETENTH;
2330         case PRI_AOC_MULTIPLIER_ONE:
2331                 return AST_AOC_MULT_ONE;
2332         case PRI_AOC_MULTIPLIER_TEN:
2333                 return AST_AOC_MULT_TEN;
2334         case PRI_AOC_MULTIPLIER_HUNDRED:
2335                 return AST_AOC_MULT_HUNDRED;
2336         case PRI_AOC_MULTIPLIER_THOUSAND:
2337                 return AST_AOC_MULT_THOUSAND;
2338         default:
2339                 return AST_AOC_MULT_ONE;
2340         }
2341 }
2342 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2343
2344 #if defined(HAVE_PRI_AOC_EVENTS)
2345 /*!
2346  * \internal
2347  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
2348  * \since 1.8
2349  *
2350  * \param value Value to convert to ast representation
2351  *
2352  * \return PRI_AOC_TIME_SCALE
2353  */
2354 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
2355 {
2356         switch (value) {
2357         default:
2358         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2359                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2360         case AST_AOC_TIME_SCALE_TENTH_SECOND:
2361                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
2362         case AST_AOC_TIME_SCALE_SECOND:
2363                 return PRI_AOC_TIME_SCALE_SECOND;
2364         case AST_AOC_TIME_SCALE_TEN_SECOND:
2365                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
2366         case AST_AOC_TIME_SCALE_MINUTE:
2367                 return PRI_AOC_TIME_SCALE_MINUTE;
2368         case AST_AOC_TIME_SCALE_HOUR:
2369                 return PRI_AOC_TIME_SCALE_HOUR;
2370         case AST_AOC_TIME_SCALE_DAY:
2371                 return PRI_AOC_TIME_SCALE_DAY;
2372         }
2373 }
2374 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2375
2376 #if defined(HAVE_PRI_AOC_EVENTS)
2377 /*!
2378  * \internal
2379  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
2380  * \since 1.8
2381  *
2382  * \param value Value to convert to ast representation
2383  *
2384  * \return ast aoc time scale
2385  */
2386 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
2387 {
2388         switch (value) {
2389         default:
2390         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2391                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2392         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
2393                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
2394         case PRI_AOC_TIME_SCALE_SECOND:
2395                 return AST_AOC_TIME_SCALE_SECOND;
2396         case PRI_AOC_TIME_SCALE_TEN_SECOND:
2397                 return AST_AOC_TIME_SCALE_TEN_SECOND;
2398         case PRI_AOC_TIME_SCALE_MINUTE:
2399                 return AST_AOC_TIME_SCALE_MINUTE;
2400         case PRI_AOC_TIME_SCALE_HOUR:
2401                 return AST_AOC_TIME_SCALE_HOUR;
2402         case PRI_AOC_TIME_SCALE_DAY:
2403                 return AST_AOC_TIME_SCALE_DAY;
2404         }
2405         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2406 }
2407 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2408
2409 #if defined(HAVE_PRI_AOC_EVENTS)
2410 /*!
2411  * \internal
2412  * \brief Handle AOC-S control frame
2413  * \since 1.8
2414  *
2415  * \param aoc_s AOC-S event parameters.
2416  * \param owner Asterisk channel associated with the call.
2417  * \param passthrough indicating if this message should be queued on the ast channel
2418  *
2419  * \note Assumes the pri->lock is already obtained.
2420  * \note Assumes the sig_pri private is locked
2421  * \note Assumes the owner channel lock is already obtained.
2422  *
2423  * \return Nothing
2424  */
2425 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
2426 {
2427         struct ast_aoc_decoded *decoded = NULL;
2428         struct ast_aoc_encoded *encoded = NULL;
2429         size_t encoded_size = 0;
2430         int idx;
2431
2432         if (!owner || !aoc_s) {
2433                 return;
2434         }
2435
2436         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
2437                 return;
2438         }
2439
2440         for (idx = 0; idx < aoc_s->num_items; ++idx) {
2441                 enum ast_aoc_s_charged_item charged_item;
2442
2443                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
2444                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
2445                         /* Delete the unknown charged item from the list. */
2446                         continue;
2447                 }
2448                 switch (aoc_s->item[idx].rate_type) {
2449                 case PRI_AOC_RATE_TYPE_DURATION:
2450                         ast_aoc_s_add_rate_duration(decoded,
2451                                 charged_item,
2452                                 aoc_s->item[idx].rate.duration.amount.cost,
2453                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
2454                                 aoc_s->item[idx].rate.duration.currency,
2455                                 aoc_s->item[idx].rate.duration.time.length,
2456                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
2457                                 aoc_s->item[idx].rate.duration.granularity.length,
2458                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
2459                                 aoc_s->item[idx].rate.duration.charging_type);
2460                         break;
2461                 case PRI_AOC_RATE_TYPE_FLAT:
2462                         ast_aoc_s_add_rate_flat(decoded,
2463                                 charged_item,
2464                                 aoc_s->item[idx].rate.flat.amount.cost,
2465                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
2466                                 aoc_s->item[idx].rate.flat.currency);
2467                         break;
2468                 case PRI_AOC_RATE_TYPE_VOLUME:
2469                         ast_aoc_s_add_rate_volume(decoded,
2470                                 charged_item,
2471                                 aoc_s->item[idx].rate.volume.unit,
2472                                 aoc_s->item[idx].rate.volume.amount.cost,
2473                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
2474                                 aoc_s->item[idx].rate.volume.currency);
2475                         break;
2476                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
2477                         ast_aoc_s_add_rate_special_charge_code(decoded,
2478                                 charged_item,
2479                                 aoc_s->item[idx].rate.special);
2480                         break;
2481                 case PRI_AOC_RATE_TYPE_FREE:
2482                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
2483                         break;
2484                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2485                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
2486                         break;
2487                 default:
2488                         ast_aoc_s_add_rate_na(decoded, charged_item);
2489                         break;
2490                 }
2491         }
2492
2493         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2494                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2495         }
2496
2497         ast_aoc_manager_event(decoded, owner);
2498
2499         ast_aoc_destroy_decoded(decoded);
2500         ast_aoc_destroy_encoded(encoded);
2501 }
2502 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2503
2504 #if defined(HAVE_PRI_AOC_EVENTS)
2505 /*!
2506  * \internal
2507  * \brief Generate AOC Request Response
2508  * \since 1.8
2509  *
2510  * \param aoc_request
2511  *
2512  * \note Assumes the pri->lock is already obtained.
2513  * \note Assumes the sig_pri private is locked
2514  * \note Assumes the owner channel lock is already obtained.
2515  *
2516  * \return Nothing
2517  */
2518 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
2519 {
2520         int request;
2521
2522         if (!aoc_request) {
2523                 return;
2524         }
2525
2526         request = aoc_request->charging_request;
2527
2528         if (request & PRI_AOC_REQUEST_S) {
2529                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
2530                         /* An AOC-S response must come from the other side, so save off this invoke_id
2531                          * and see if an AOC-S message comes in before the call is answered. */
2532                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
2533                         pvt->aoc_s_request_invoke_id_valid = 1;
2534
2535                 } else {
2536                         pri_aoc_s_request_response_send(pvt->pri->pri,
2537                                 call,
2538                                 aoc_request->invoke_id,
2539                                 NULL);
2540                 }
2541         }
2542
2543         if (request & PRI_AOC_REQUEST_D) {
2544                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
2545                         pri_aoc_de_request_response_send(pvt->pri->pri,
2546                                 call,
2547                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2548                                 aoc_request->invoke_id);
2549                 } else {
2550                         pri_aoc_de_request_response_send(pvt->pri->pri,
2551                                 call,
2552                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2553                                 aoc_request->invoke_id);
2554                 }
2555         }
2556
2557         if (request & PRI_AOC_REQUEST_E) {
2558                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
2559                         pri_aoc_de_request_response_send(pvt->pri->pri,
2560                                 call,
2561                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2562                                 aoc_request->invoke_id);
2563                 } else {
2564                         pri_aoc_de_request_response_send(pvt->pri->pri,
2565                                 call,
2566                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2567                                 aoc_request->invoke_id);
2568                 }
2569         }
2570 }
2571 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2572
2573 #if defined(HAVE_PRI_AOC_EVENTS)
2574 /*!
2575  * \internal
2576  * \brief Generate AOC-D AST_CONTROL_AOC frame
2577  * \since 1.8
2578  *
2579  * \param aoc_e AOC-D event parameters.
2580  * \param owner Asterisk channel associated with the call.
2581  * \param passthrough indicating if this message should be queued on the ast channel
2582  *
2583  * \note Assumes the pri->lock is already obtained.
2584  * \note Assumes the sig_pri private is locked
2585  * \note Assumes the owner channel lock is already obtained.
2586  *
2587  * \return Nothing
2588  */
2589 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
2590 {
2591         struct ast_aoc_decoded *decoded = NULL;
2592         struct ast_aoc_encoded *encoded = NULL;
2593         size_t encoded_size = 0;
2594         enum ast_aoc_charge_type type;
2595
2596         if (!owner || !aoc_d) {
2597                 return;
2598         }
2599
2600         switch (aoc_d->charge) {
2601         case PRI_AOC_DE_CHARGE_CURRENCY:
2602                 type = AST_AOC_CHARGE_CURRENCY;
2603                 break;
2604         case PRI_AOC_DE_CHARGE_UNITS:
2605                 type = AST_AOC_CHARGE_UNIT;
2606                 break;
2607         case PRI_AOC_DE_CHARGE_FREE:
2608                 type = AST_AOC_CHARGE_FREE;
2609                 break;
2610         default:
2611                 type = AST_AOC_CHARGE_NA;
2612                 break;
2613         }
2614
2615         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
2616                 return;
2617         }
2618
2619         switch (aoc_d->billing_accumulation) {
2620         default:
2621                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
2622                         aoc_d->billing_accumulation);
2623                 /* Fall through */
2624         case 0:/* subTotal */
2625                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
2626                 break;
2627         case 1:/* total */
2628                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
2629                 break;
2630         }
2631
2632         switch (aoc_d->billing_id) {
2633         case PRI_AOC_D_BILLING_ID_NORMAL:
2634                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2635                 break;
2636         case PRI_AOC_D_BILLING_ID_REVERSE:
2637                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2638                 break;
2639         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
2640                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2641                 break;
2642         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
2643         default:
2644                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2645                 break;
2646         }
2647
2648         switch (aoc_d->charge) {
2649         case PRI_AOC_DE_CHARGE_CURRENCY:
2650                 ast_aoc_set_currency_info(decoded,
2651                         aoc_d->recorded.money.amount.cost,
2652                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
2653                         aoc_d->recorded.money.currency);
2654                 break;
2655         case PRI_AOC_DE_CHARGE_UNITS:
2656                 {
2657                         int i;
2658                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
2659                                 /* if type or number are negative, then they are not present */
2660                                 ast_aoc_add_unit_entry(decoded,
2661                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
2662                                         aoc_d->recorded.unit.item[i].number,
2663                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
2664                                         aoc_d->recorded.unit.item[i].type);
2665                         }
2666                 }
2667                 break;
2668         }
2669
2670         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2671                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2672         }
2673
2674         ast_aoc_manager_event(decoded, owner);
2675
2676         ast_aoc_destroy_decoded(decoded);
2677         ast_aoc_destroy_encoded(encoded);
2678 }
2679 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2680
2681 #if defined(HAVE_PRI_AOC_EVENTS)
2682 /*!
2683  * \internal
2684  * \brief Generate AOC-E AST_CONTROL_AOC frame
2685  * \since 1.8
2686  *
2687  * \param aoc_e AOC-E event parameters.
2688  * \param owner Asterisk channel associated with the call.
2689  * \param passthrough indicating if this message should be queued on the ast channel
2690  *
2691  * \note Assumes the pri->lock is already obtained.
2692  * \note Assumes the sig_pri private is locked
2693  * \note Assumes the owner channel lock is already obtained.
2694  * \note owner channel may be NULL. In that case, generate event only
2695  *
2696  * \return Nothing
2697  */
2698 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
2699 {
2700         struct ast_aoc_decoded *decoded = NULL;
2701         struct ast_aoc_encoded *encoded = NULL;
2702         size_t encoded_size = 0;
2703         enum ast_aoc_charge_type type;
2704
2705         if (!aoc_e) {
2706                 return;
2707         }
2708
2709         switch (aoc_e->charge) {
2710         case PRI_AOC_DE_CHARGE_CURRENCY:
2711                 type = AST_AOC_CHARGE_CURRENCY;
2712                 break;
2713         case PRI_AOC_DE_CHARGE_UNITS:
2714                 type = AST_AOC_CHARGE_UNIT;
2715                 break;
2716         case PRI_AOC_DE_CHARGE_FREE:
2717                 type = AST_AOC_CHARGE_FREE;
2718                 break;
2719         default:
2720                 type = AST_AOC_CHARGE_NA;
2721                 break;
2722         }
2723
2724         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
2725                 return;
2726         }
2727
2728         switch (aoc_e->associated.charging_type) {
2729         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
2730                 if (!aoc_e->associated.charge.number.valid) {
2731                         break;
2732                 }
2733                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
2734                 break;
2735         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
2736                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
2737                 break;
2738         default:
2739                 break;
2740         }
2741
2742         switch (aoc_e->billing_id) {
2743         case PRI_AOC_E_BILLING_ID_NORMAL:
2744                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2745                 break;
2746         case PRI_AOC_E_BILLING_ID_REVERSE:
2747                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2748                 break;
2749         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
2750                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2751                 break;
2752         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
2753                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
2754                 break;
2755         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
2756                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
2757                 break;
2758         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
2759                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
2760                 break;
2761         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
2762                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
2763                 break;
2764         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
2765                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
2766                 break;
2767         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
2768         default:
2769                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2770                 break;
2771         }
2772
2773         switch (aoc_e->charge) {
2774         case PRI_AOC_DE_CHARGE_CURRENCY:
2775                 ast_aoc_set_currency_info(decoded,
2776                         aoc_e->recorded.money.amount.cost,
2777                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
2778                         aoc_e->recorded.money.currency);
2779                 break;
2780         case PRI_AOC_DE_CHARGE_UNITS:
2781                 {
2782                         int i;
2783                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
2784                                 /* if type or number are negative, then they are not present */
2785                                 ast_aoc_add_unit_entry(decoded,
2786                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
2787                                         aoc_e->recorded.unit.item[i].number,
2788                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
2789                                         aoc_e->recorded.unit.item[i].type);
2790                         }
2791                 }
2792         }
2793
2794         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2795                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2796         }
2797
2798         ast_aoc_manager_event(decoded, owner);
2799
2800         ast_aoc_destroy_decoded(decoded);
2801         ast_aoc_destroy_encoded(encoded);
2802 }
2803 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2804
2805 #if defined(HAVE_PRI_AOC_EVENTS)
2806 /*!
2807  * \internal
2808  * \brief send an AOC-S message on the current call
2809  *
2810  * \param pvt sig_pri private channel structure.
2811  * \param generic decoded ast AOC message
2812  *
2813  * \return Nothing
2814  *
2815  * \note Assumes that the PRI lock is already obtained.
2816  */
2817 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2818 {
2819         struct pri_subcmd_aoc_s aoc_s = { 0, };
2820         const struct ast_aoc_s_entry *entry;
2821         int idx;
2822
2823         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
2824                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
2825                         break;
2826                 }
2827
2828                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
2829
2830                 switch (entry->rate_type) {
2831                 case AST_AOC_RATE_TYPE_DURATION:
2832                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
2833                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
2834                         aoc_s.item[idx].rate.duration.amount.multiplier =
2835                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
2836                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
2837                         aoc_s.item[idx].rate.duration.time.scale =
2838                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
2839                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
2840                         aoc_s.item[idx].rate.duration.granularity.scale =
2841                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
2842                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
2843
2844                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
2845                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
2846                                         entry->rate.duration.currency_name,
2847                                         sizeof(aoc_s.item[idx].rate.duration.currency));
2848                         }
2849                         break;
2850                 case AST_AOC_RATE_TYPE_FLAT:
2851                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
2852                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
2853                         aoc_s.item[idx].rate.flat.amount.multiplier =
2854                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
2855
2856                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
2857                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
2858                                         entry->rate.flat.currency_name,
2859                                         sizeof(aoc_s.item[idx].rate.flat.currency));
2860                         }
2861                         break;
2862                 case AST_AOC_RATE_TYPE_VOLUME:
2863                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
2864                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
2865                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
2866                         aoc_s.item[idx].rate.volume.amount.multiplier =
2867                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
2868
2869                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
2870                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
2871                                         entry->rate.volume.currency_name,
2872                                         sizeof(aoc_s.item[idx].rate.volume.currency));
2873                         }
2874                         break;
2875                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
2876                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
2877                         aoc_s.item[idx].rate.special = entry->rate.special_code;
2878                         break;
2879                 case AST_AOC_RATE_TYPE_FREE:
2880                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
2881                         break;
2882                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2883                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
2884                         break;
2885                 default:
2886                 case AST_AOC_RATE_TYPE_NA:
2887                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
2888                         break;
2889                 }
2890         }
2891         aoc_s.num_items = idx;
2892
2893         /* if this rate should be sent as a response to an AOC-S request we will
2894          * have an aoc_s_request_invoke_id associated with this pvt */
2895         if (pvt->aoc_s_request_invoke_id_valid) {
2896                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
2897                 pvt->aoc_s_request_invoke_id_valid = 0;
2898         } else {
2899                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
2900         }
2901 }
2902 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2903
2904 #if defined(HAVE_PRI_AOC_EVENTS)
2905 /*!
2906  * \internal
2907  * \brief send an AOC-D message on the current call
2908  *
2909  * \param pvt sig_pri private channel structure.
2910  * \param generic decoded ast AOC message
2911  *
2912  * \return Nothing
2913  *
2914  * \note Assumes that the PRI lock is already obtained.
2915  */
2916 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2917 {
2918         struct pri_subcmd_aoc_d aoc_d = { 0, };
2919
2920         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
2921
2922         switch (ast_aoc_get_billing_id(decoded)) {
2923         case AST_AOC_BILLING_NORMAL:
2924                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
2925                 break;
2926         case AST_AOC_BILLING_REVERSE_CHARGE:
2927                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
2928                 break;
2929         case AST_AOC_BILLING_CREDIT_CARD:
2930                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
2931                 break;
2932         case AST_AOC_BILLING_NA:
2933         default:
2934                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
2935                 break;
2936         }
2937
2938         switch (ast_aoc_get_charge_type(decoded)) {
2939         case AST_AOC_CHARGE_FREE:
2940                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
2941                 break;
2942         case AST_AOC_CHARGE_CURRENCY:
2943                 {
2944                         const char *currency_name = ast_aoc_get_currency_name(decoded);
2945                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
2946                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
2947                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
2948                         if (!ast_strlen_zero(currency_name)) {
2949                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
2950                         }
2951                 }
2952                 break;
2953         case AST_AOC_CHARGE_UNIT:
2954                 {
2955                         const struct ast_aoc_unit_entry *entry;
2956                         int i;
2957                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
2958                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
2959                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
2960                                         if (entry->valid_amount) {
2961                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
2962                                         } else {
2963                                                 aoc_d.recorded.unit.item[i].number = -1;
2964                                         }
2965                                         if (entry->valid_type) {
2966                                                 aoc_d.recorded.unit.item[i].type = entry->type;
2967                                         } else {
2968                                                 aoc_d.recorded.unit.item[i].type = -1;
2969                                         }
2970                                         aoc_d.recorded.unit.num_items++;
2971                                 } else {
2972                                         break;
2973                                 }
2974                         }
2975                 }
2976                 break;
2977         case AST_AOC_CHARGE_NA:
2978         default:
2979                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
2980                 break;
2981         }
2982
2983         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
2984 }
2985 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2986
2987 #if defined(HAVE_PRI_AOC_EVENTS)
2988 /*!
2989  * \internal
2990  * \brief send an AOC-E message on the current call
2991  *
2992  * \param pvt sig_pri private channel structure.
2993  * \param generic decoded ast AOC message
2994  *
2995  * \return Nothing
2996  *
2997  * \note Assumes that the PRI lock is already obtained.
2998  */
2999 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3000 {
3001         struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
3002         const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
3003
3004         memset(aoc_e, 0, sizeof(*aoc_e));
3005         pvt->holding_aoce = 1;
3006
3007         switch (ca->charging_type) {
3008         case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
3009                 aoc_e->associated.charge.number.valid = 1;
3010                 ast_copy_string(aoc_e->associated.charge.number.str,
3011                         ca->charge.number.number,
3012                         sizeof(aoc_e->associated.charge.number.str));
3013                 aoc_e->associated.charge.number.plan = ca->charge.number.plan;
3014                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
3015                 break;
3016         case AST_AOC_CHARGING_ASSOCIATION_ID:
3017                 aoc_e->associated.charge.id = ca->charge.id;
3018                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
3019                 break;
3020         case AST_AOC_CHARGING_ASSOCIATION_NA:
3021         default:
3022                 break;
3023         }
3024
3025         switch (ast_aoc_get_billing_id(decoded)) {
3026         case AST_AOC_BILLING_NORMAL:
3027                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
3028                 break;
3029         case AST_AOC_BILLING_REVERSE_CHARGE:
3030                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
3031                 break;
3032         case AST_AOC_BILLING_CREDIT_CARD:
3033                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
3034                 break;
3035         case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
3036                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
3037                 break;
3038         case AST_AOC_BILLING_CALL_FWD_BUSY:
3039                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
3040                 break;
3041         case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
3042                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
3043                 break;
3044         case AST_AOC_BILLING_CALL_DEFLECTION:
3045                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
3046                 break;
3047         case AST_AOC_BILLING_CALL_TRANSFER:
3048                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
3049                 break;
3050         case AST_AOC_BILLING_NA:
3051         default:
3052                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
3053                 break;
3054         }
3055
3056         switch (ast_aoc_get_charge_type(decoded)) {
3057         case AST_AOC_CHARGE_FREE:
3058                 aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
3059                 break;
3060         case AST_AOC_CHARGE_CURRENCY:
3061                 {
3062                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3063                         aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
3064                         aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3065                         aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3066                         if (!ast_strlen_zero(currency_name)) {
3067                                 ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
3068                         }
3069                 }
3070                 break;
3071         case AST_AOC_CHARGE_UNIT:
3072                 {
3073                         const struct ast_aoc_unit_entry *entry;
3074                         int i;
3075                         aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
3076                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3077                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
3078                                         if (entry->valid_amount) {
3079                                                 aoc_e->recorded.unit.item[i].number = entry->amount;
3080                                         } else {
3081                                                 aoc_e->recorded.unit.item[i].number = -1;
3082                                         }
3083                                         if (entry->valid_type) {
3084                                                 aoc_e->recorded.unit.item[i].type = entry->type;
3085                                         } else {
3086                                                 aoc_e->recorded.unit.item[i].type = -1;
3087                                         }
3088                                         aoc_e->recorded.unit.num_items++;
3089                                 }
3090                         }
3091                 }
3092                 break;
3093         case AST_AOC_CHARGE_NA:
3094         default:
3095                 aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3096                 break;
3097         }
3098 }
3099 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3100
3101 #if defined(HAVE_PRI_AOC_EVENTS)
3102 /*!
3103  * \internal
3104  * \brief send an AOC-E termination request on ast_channel and set
3105  * hangup delay.
3106  *
3107  * \param sig_pri_chan private
3108  * \param ms to delay hangup
3109  *
3110  * \note assumes pvt is locked
3111  *
3112  * \return Nothing
3113  */
3114 static void sig_pri_send_aoce_termination_request(struct sig_pri_chan *pvt, unsigned int ms)
3115 {
3116         struct ast_aoc_decoded *decoded = NULL;
3117         struct ast_aoc_encoded *encoded = NULL;
3118         size_t encoded_size;
3119         struct timeval whentohangup = { 0, };
3120
3121         if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
3122                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3123                 goto cleanup_termination_request;
3124         }
3125
3126         ast_aoc_set_termination_request(decoded);
3127
3128         if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
3129                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3130                 goto cleanup_termination_request;
3131         }
3132
3133         /* convert ms to timeval */
3134         whentohangup.tv_usec = (ms % 1000) * 1000;
3135         whentohangup.tv_sec = ms / 1000;
3136
3137         if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
3138                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3139                 goto cleanup_termination_request;
3140         }
3141
3142         pvt->waiting_for_aoce = 1;
3143         ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
3144         ast_log(LOG_DEBUG, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
3145
3146 cleanup_termination_request:
3147         ast_aoc_destroy_decoded(decoded);
3148         ast_aoc_destroy_encoded(encoded);
3149 }
3150 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3151
3152 /*!
3153  * \internal
3154  * \brief TRUE if PRI event came in on a CIS call.
3155  * \since 1.8
3156  *
3157  * \param channel PRI encoded span/channel
3158  *
3159  * \retval non-zero if CIS call.
3160  */
3161 static int sig_pri_is_cis_call(int channel)
3162 {
3163         return channel != -1 && (channel & PRI_CIS_CALL);
3164 }
3165
3166 /*!
3167  * \internal
3168  * \brief Handle the CIS associated PRI subcommand events.
3169  * \since 1.8
3170  *
3171  * \param pri sig_pri PRI control structure.
3172  * \param event_id PRI event id
3173  * \param subcmds Subcommands to process if any. (Could be NULL).
3174  * \param call_rsp libpri opaque call structure to send any responses toward.
3175  * Could be NULL either because it is not available or the call is for the
3176  * dummy call reference.  However, this should not be NULL in the cases that
3177  * need to use the pointer to send a response message back.
3178  *
3179  * \note Assumes the pri->lock is already obtained.
3180  *
3181  * \return Nothing
3182  */
3183 static void sig_pri_handle_cis_subcmds(struct sig_pri_pri *pri, int event_id,
3184         const struct pri_subcommands *subcmds, q931_call *call_rsp)
3185 {
3186         int index;
3187 #if defined(HAVE_PRI_CCSS)
3188         struct ast_cc_agent *agent;
3189         struct sig_pri_cc_agent_prv *agent_prv;
3190         struct sig_pri_cc_monitor_instance *monitor;
3191 #endif  /* defined(HAVE_PRI_CCSS) */
3192
3193         if (!subcmds) {
3194                 return;
3195         }
3196         for (index = 0; index < subcmds->counter_subcmd; ++index) {
3197                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
3198
3199                 switch (subcmd->cmd) {
3200 #if defined(STATUS_REQUEST_PLACE_HOLDER)
3201                 case PRI_SUBCMD_STATUS_REQ:
3202                 case PRI_SUBCMD_STATUS_REQ_RSP:
3203                         /* Ignore for now. */
3204                         break;
3205 #endif  /* defined(STATUS_REQUEST_PLACE_HOLDER) */
3206 #if defined(HAVE_PRI_CCSS)
3207                 case PRI_SUBCMD_CC_REQ:
3208                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
3209                         if (!agent) {
3210                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3211                                 break;
3212                         }
3213                         if (!ast_cc_request_is_within_limits()) {
3214                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3215                                         5/* queue_full */)) {
3216                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3217                                 }
3218                                 ast_cc_failed(agent->core_id, "%s agent system CC queue full",
3219                                         sig_pri_cc_type_name);
3220                                 ao2_ref(agent, -1);
3221                                 break;
3222                         }
3223                         agent_prv = agent->private_data;
3224                         agent_prv->cc_request_response_pending = 1;
3225                         if (ast_cc_agent_accept_request(agent->core_id,
3226                                 "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
3227                                 agent_prv->cc_request_response_pending = 0;
3228                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3229                                         2/* short_term_denial */)) {
3230                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3231                                 }
3232                                 ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
3233                                         sig_pri_cc_type_name);
3234                         }
3235                         ao2_ref(agent, -1);
3236                         break;
3237 #endif  /* defined(HAVE_PRI_CCSS) */
3238 #if defined(HAVE_PRI_CCSS)
3239                 case PRI_SUBCMD_CC_REQ_RSP:
3240                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3241                                 subcmd->u.cc_request_rsp.cc_id);
3242                         if (!monitor) {
3243                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
3244                                 break;
3245                         }
3246                         switch (subcmd->u.cc_request_rsp.status) {
3247                         case 0:/* success */
3248                                 ast_cc_monitor_request_acked(monitor->core_id,
3249                                         "%s far end accepted CC request", sig_pri_cc_type_name);
3250                                 break;
3251                         case 1:/* timeout */
3252                                 ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
3253                                         sig_pri_cc_type_name);
3254                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3255                                         "%s CC request timeout", sig_pri_cc_type_name);
3256                                 break;
3257                         case 2:/* error */
3258                                 ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
3259                                         sig_pri_cc_type_name,
3260                                         pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
3261                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3262                                         "%s CC request error", sig_pri_cc_type_name);
3263                                 break;
3264                         case 3:/* reject */
3265                                 ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
3266                                         sig_pri_cc_type_name,
3267                                         pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
3268                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3269                                         "%s CC request reject", sig_pri_cc_type_name);
3270                                 break;
3271                         default:
3272                                 ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
3273                                         monitor->core_id, sig_pri_cc_type_name,
3274                                         subcmd->u.cc_request_rsp.status);
3275                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3276                                         "%s CC request unknown status", sig_pri_cc_type_name);
3277                                 break;
3278                         }
3279                         ao2_ref(monitor, -1);
3280                         break;
3281 #endif  /* defined(HAVE_PRI_CCSS) */
3282 #if defined(HAVE_PRI_CCSS)
3283                 case PRI_SUBCMD_CC_REMOTE_USER_FREE:
3284                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3285                                 subcmd->u.cc_remote_user_free.cc_id);
3286                         if (!monitor) {