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