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