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