Merged revisions 311297 via svnmerge from
[asterisk/asterisk.git] / channels / sig_pri.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2009, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief PRI signaling module
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  */
25
26
27 #include "asterisk.h"
28
29 #ifdef HAVE_PRI
30
31 #include <errno.h>
32 #include <ctype.h>
33 #include <signal.h>
34
35 #include "asterisk/utils.h"
36 #include "asterisk/options.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/app.h"
39 #include "asterisk/file.h"
40 #include "asterisk/callerid.h"
41 #include "asterisk/say.h"
42 #include "asterisk/manager.h"
43 #include "asterisk/astdb.h"
44 #include "asterisk/causes.h"
45 #include "asterisk/musiconhold.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/transcap.h"
48 #include "asterisk/features.h"
49 #include "asterisk/aoc.h"
50
51 #include "sig_pri.h"
52 #ifndef PRI_EVENT_FACILITY
53 #error please update libpri
54 #endif
55
56 /* define this to send PRI user-user information elements */
57 #undef SUPPORT_USERUSER
58
59 #if defined(HAVE_PRI_CCSS)
60 struct sig_pri_cc_agent_prv {
61         /*! Asterisk span D channel control structure. */
62         struct sig_pri_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 PRI span 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 /*!
936  * \internal
937  * \brief Post an AMI B channel association event.
938  * \since 1.8
939  *
940  * \param p Channel private control structure.
941  *
942  * \note Assumes the private and owner are locked.
943  *
944  * \return Nothing
945  */
946 static void sig_pri_ami_channel_event(struct sig_pri_chan *p)
947 {
948         if (p->calls->ami_channel_event) {
949                 p->calls->ami_channel_event(p->chan_pvt, p->owner);
950         }
951 }
952
953 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
954 {
955         struct ast_channel *ast;
956
957         ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
958
959         p->outgoing = 1;
960         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
961         if (!ast) {
962                 p->outgoing = 0;
963         }
964         return ast;
965 }
966
967 int pri_is_up(struct sig_pri_span *pri)
968 {
969         int x;
970         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
971                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
972                         return 1;
973         }
974         return 0;
975 }
976
977 static char *pri_order(int level)
978 {
979         switch (level) {
980         case 0:
981                 return "Primary";
982         case 1:
983                 return "Secondary";
984         case 2:
985                 return "Tertiary";
986         case 3:
987                 return "Quaternary";
988         default:
989                 return "<Unknown>";
990         }
991 }
992
993 /* Returns index of the active dchan */
994 static int pri_active_dchan_index(struct sig_pri_span *pri)
995 {
996         int x;
997
998         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
999                 if ((pri->dchans[x] == pri->pri))
1000                         return x;
1001         }
1002
1003         ast_log(LOG_WARNING, "No active dchan found!\n");
1004         return -1;
1005 }
1006
1007 static int pri_find_dchan(struct sig_pri_span *pri)
1008 {
1009         int oldslot = -1;
1010         struct pri *old;
1011         int newslot = -1;
1012         int x;
1013         old = pri->pri;
1014         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
1015                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
1016                         newslot = x;
1017                 if (pri->dchans[x] == old) {
1018                         oldslot = x;
1019                 }
1020         }
1021         if (newslot < 0) {
1022                 newslot = 0;
1023                 /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
1024                 if (pri->sig != SIG_BRI_PTMP && !pri->no_d_channels) {
1025                         pri->no_d_channels = 1;
1026                         ast_log(LOG_WARNING,
1027                                 "Span %d: No D-channels available!  Using Primary channel as D-channel anyway!\n",
1028                                 pri->span);
1029                 }
1030         } else {
1031                 pri->no_d_channels = 0;
1032         }
1033         if (old && (oldslot != newslot))
1034                 ast_log(LOG_NOTICE, "Switching from d-channel fd %d to fd %d!\n",
1035                         pri->fds[oldslot], pri->fds[newslot]);
1036         pri->pri = pri->dchans[newslot];
1037         return 0;
1038 }
1039
1040 /*!
1041  * \internal
1042  * \brief Obtain the sig_pri owner channel lock if the owner exists.
1043  * \since 1.8
1044  *
1045  * \param pri PRI span control structure.
1046  * \param chanpos Channel position in the span.
1047  *
1048  * \note Assumes the pri->lock is already obtained.
1049  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1050  *
1051  * \return Nothing
1052  */
1053 static void sig_pri_lock_owner(struct sig_pri_span *pri, int chanpos)
1054 {
1055         for (;;) {
1056                 if (!pri->pvts[chanpos]->owner) {
1057                         /* There is no owner lock to get. */
1058                         break;
1059                 }
1060                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
1061                         /* We got the lock */
1062                         break;
1063                 }
1064                 /* We must unlock the PRI to avoid the possibility of a deadlock */
1065                 ast_mutex_unlock(&pri->lock);
1066                 PRI_DEADLOCK_AVOIDANCE(pri->pvts[chanpos]);
1067                 ast_mutex_lock(&pri->lock);
1068         }
1069 }
1070
1071 /*!
1072  * \internal
1073  * \brief Queue the given frame onto the owner channel.
1074  * \since 1.8
1075  *
1076  * \param pri PRI span control structure.
1077  * \param chanpos Channel position in the span.
1078  * \param frame Frame to queue onto the owner channel.
1079  *
1080  * \note Assumes the pri->lock is already obtained.
1081  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1082  *
1083  * \return Nothing
1084  */
1085 static void pri_queue_frame(struct sig_pri_span *pri, int chanpos, struct ast_frame *frame)
1086 {
1087         sig_pri_lock_owner(pri, chanpos);
1088         if (pri->pvts[chanpos]->owner) {
1089                 ast_queue_frame(pri->pvts[chanpos]->owner, frame);
1090                 ast_channel_unlock(pri->pvts[chanpos]->owner);
1091         }
1092 }
1093
1094 /*!
1095  * \internal
1096  * \brief Queue a control frame of the specified subclass onto the owner channel.
1097  * \since 1.8
1098  *
1099  * \param pri PRI span control structure.
1100  * \param chanpos Channel position in the span.
1101  * \param subclass Control frame subclass to queue onto the owner channel.
1102  *
1103  * \note Assumes the pri->lock is already obtained.
1104  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1105  *
1106  * \return Nothing
1107  */
1108 static void pri_queue_control(struct sig_pri_span *pri, int chanpos, int subclass)
1109 {
1110         struct ast_frame f = {AST_FRAME_CONTROL, };
1111         struct sig_pri_chan *p = pri->pvts[chanpos];
1112
1113         if (p->calls->queue_control) {
1114                 p->calls->queue_control(p->chan_pvt, subclass);
1115         }
1116
1117         f.subclass.integer = subclass;
1118         pri_queue_frame(pri, chanpos, &f);
1119 }
1120
1121 /*!
1122  * \internal
1123  * \brief Find the channel associated with the libpri call.
1124  * \since 1.10
1125  *
1126  * \param pri PRI span control structure.
1127  * \param call LibPRI opaque call pointer to find.
1128  *
1129  * \note Assumes the pri->lock is already obtained.
1130  *
1131  * \retval array-index into private pointer array on success.
1132  * \retval -1 on error.
1133  */
1134 static int pri_find_principle_by_call(struct sig_pri_span *pri, q931_call *call)
1135 {
1136         int idx;
1137
1138         if (!call) {
1139                 /* Cannot find a call without a call. */
1140                 return -1;
1141         }
1142         for (idx = 0; idx < pri->numchans; ++idx) {
1143                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1144                         /* Found the principle */
1145                         return idx;
1146                 }
1147         }
1148         return -1;
1149 }
1150
1151 /*!
1152  * \internal
1153  * \brief Find the private structure for the libpri call.
1154  *
1155  * \param pri PRI span control structure.
1156  * \param channel LibPRI encoded channel ID.
1157  * \param call LibPRI opaque call pointer.
1158  *
1159  * \note Assumes the pri->lock is already obtained.
1160  *
1161  * \retval array-index into private pointer array on success.
1162  * \retval -1 on error.
1163  */
1164 static int pri_find_principle(struct sig_pri_span *pri, int channel, q931_call *call)
1165 {
1166         int x;
1167         int span;
1168         int principle;
1169         int prioffset;
1170
1171         if (channel < 0) {
1172                 /* Channel is not picked yet. */
1173                 return -1;
1174         }
1175
1176         prioffset = PRI_CHANNEL(channel);
1177         if (!prioffset || (channel & PRI_HELD_CALL)) {
1178                 /* Find the call waiting call or held call. */
1179                 return pri_find_principle_by_call(pri, call);
1180         }
1181
1182         span = PRI_SPAN(channel);
1183         if (!(channel & PRI_EXPLICIT)) {
1184                 int index;
1185
1186                 index = pri_active_dchan_index(pri);
1187                 if (index == -1) {
1188                         return -1;
1189                 }
1190                 span = pri->dchan_logical_span[index];
1191         }
1192
1193         principle = -1;
1194         for (x = 0; x < pri->numchans; x++) {
1195                 if (pri->pvts[x]
1196                         && pri->pvts[x]->prioffset == prioffset
1197                         && pri->pvts[x]->logicalspan == span
1198                         && !pri->pvts[x]->no_b_channel) {
1199                         principle = x;
1200                         break;
1201                 }
1202         }
1203
1204         return principle;
1205 }
1206
1207 /*!
1208  * \internal
1209  * \brief Fixup the private structure associated with the libpri call.
1210  *
1211  * \param pri PRI span control structure.
1212  * \param principle Array-index into private array to move call to if not already there.
1213  * \param call LibPRI opaque call pointer to find if need to move call.
1214  *
1215  * \note Assumes the pri->lock is already obtained.
1216  *
1217  * \retval principle on success.
1218  * \retval -1 on error.
1219  */
1220 static int pri_fixup_principle(struct sig_pri_span *pri, int principle, q931_call *call)
1221 {
1222         int x;
1223
1224         if (principle < 0 || pri->numchans <= principle) {
1225                 /* Out of rannge */
1226                 return -1;
1227         }
1228         if (!call) {
1229                 /* No call */
1230                 return principle;
1231         }
1232         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
1233                 /* Call is already on the specified principle. */
1234                 return principle;
1235         }
1236
1237         /* Find the old principle location. */
1238         for (x = 0; x < pri->numchans; x++) {
1239                 struct sig_pri_chan *new_chan;
1240                 struct sig_pri_chan *old_chan;
1241
1242                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
1243                         continue;
1244                 }
1245
1246                 /* Found our call */
1247                 new_chan = pri->pvts[principle];
1248                 old_chan = pri->pvts[x];
1249
1250                 /* Get locks to safely move to the new private structure. */
1251                 sig_pri_lock_private(old_chan);
1252                 sig_pri_lock_owner(pri, x);
1253                 sig_pri_lock_private(new_chan);
1254
1255                 ast_verb(3, "Moving call (%s) from channel %d to %d.\n",
1256                         old_chan->owner ? old_chan->owner->name : "",
1257                         old_chan->channel, new_chan->channel);
1258                 if (new_chan->owner) {
1259                         ast_log(LOG_WARNING,
1260                                 "Can't move call (%s) from channel %d to %d.  It is already in use.\n",
1261                                 old_chan->owner ? old_chan->owner->name : "",
1262                                 old_chan->channel, new_chan->channel);
1263                         sig_pri_unlock_private(new_chan);
1264                         if (old_chan->owner) {
1265                                 ast_channel_unlock(old_chan->owner);
1266                         }
1267                         sig_pri_unlock_private(old_chan);
1268                         return -1;
1269                 }
1270
1271                 sig_pri_fixup_chans(old_chan, new_chan);
1272
1273                 /* Fix it all up now */
1274                 new_chan->owner = old_chan->owner;
1275                 old_chan->owner = NULL;
1276
1277                 new_chan->call = old_chan->call;
1278                 old_chan->call = NULL;
1279
1280                 /* Transfer flags from the old channel. */
1281 #if defined(HAVE_PRI_AOC_EVENTS)
1282                 new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
1283                 new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
1284                 new_chan->holding_aoce = old_chan->holding_aoce;
1285 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1286                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1287                 new_chan->isidlecall = old_chan->isidlecall;
1288                 new_chan->progress = old_chan->progress;
1289                 new_chan->outgoing = old_chan->outgoing;
1290                 new_chan->digital = old_chan->digital;
1291 #if defined(HAVE_PRI_CALL_WAITING)
1292                 new_chan->is_call_waiting = old_chan->is_call_waiting;
1293 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1294
1295 #if defined(HAVE_PRI_AOC_EVENTS)
1296                 old_chan->aoc_s_request_invoke_id_valid = 0;
1297                 old_chan->waiting_for_aoce = 0;
1298                 old_chan->holding_aoce = 0;
1299 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1300                 old_chan->alreadyhungup = 0;
1301                 old_chan->isidlecall = 0;
1302                 old_chan->progress = 0;
1303                 old_chan->outgoing = 0;
1304                 old_chan->digital = 0;
1305 #if defined(HAVE_PRI_CALL_WAITING)
1306                 old_chan->is_call_waiting = 0;
1307 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1308
1309                 /* More stuff to transfer to the new channel. */
1310                 new_chan->call_level = old_chan->call_level;
1311                 old_chan->call_level = SIG_PRI_CALL_LEVEL_IDLE;
1312 #if defined(HAVE_PRI_REVERSE_CHARGE)
1313                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1314 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1315 #if defined(HAVE_PRI_SETUP_KEYPAD)
1316                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1317 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1318                 strcpy(new_chan->moh_suggested, old_chan->moh_suggested);
1319                 new_chan->moh_state = old_chan->moh_state;
1320                 old_chan->moh_state = SIG_PRI_MOH_STATE_IDLE;
1321
1322 #if defined(HAVE_PRI_AOC_EVENTS)
1323                 new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
1324                 new_chan->aoc_e = old_chan->aoc_e;
1325 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1326                 strcpy(new_chan->user_tag, old_chan->user_tag);
1327
1328                 if (new_chan->no_b_channel) {
1329                         /* Copy the real channel configuration to the no B channel interface. */
1330                         new_chan->hidecallerid = old_chan->hidecallerid;
1331                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1332                         new_chan->immediate = old_chan->immediate;
1333                         new_chan->priexclusive = old_chan->priexclusive;
1334                         new_chan->priindication_oob = old_chan->priindication_oob;
1335                         new_chan->use_callerid = old_chan->use_callerid;
1336                         new_chan->use_callingpres = old_chan->use_callingpres;
1337                         new_chan->stripmsd = old_chan->stripmsd;
1338                         strcpy(new_chan->context, old_chan->context);
1339                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1340
1341                         /* Become a member of the old channel span/trunk-group. */
1342                         new_chan->logicalspan = old_chan->logicalspan;
1343                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1344                 } else if (old_chan->no_b_channel) {
1345                         /*
1346                          * We are transitioning from a held/call-waiting channel to a
1347                          * real channel so we need to make sure that the media path is
1348                          * open.  (Needed especially if the channel is natively
1349                          * bridged.)
1350                          */
1351                         sig_pri_open_media(new_chan);
1352                 }
1353
1354                 if (new_chan->owner) {
1355                         sig_pri_ami_channel_event(new_chan);
1356                 }
1357
1358                 sig_pri_unlock_private(old_chan);
1359                 if (new_chan->owner) {
1360                         ast_channel_unlock(new_chan->owner);
1361                 }
1362                 sig_pri_unlock_private(new_chan);
1363
1364                 return principle;
1365         }
1366         ast_verb(3, "Call specified, but not found.\n");
1367         return -1;
1368 }
1369
1370 static char * redirectingreason2str(int redirectingreason)
1371 {
1372         switch (redirectingreason) {
1373         case 0:
1374                 return "UNKNOWN";
1375         case 1:
1376                 return "BUSY";
1377         case 2:
1378                 return "NO_REPLY";
1379         case 0xF:
1380                 return "UNCONDITIONAL";
1381         default:
1382                 return "NOREDIRECT";
1383         }
1384 }
1385
1386 static char *dialplan2str(int dialplan)
1387 {
1388         if (dialplan == -1) {
1389                 return("Dynamically set dialplan in ISDN");
1390         }
1391         return (pri_plan2str(dialplan));
1392 }
1393
1394 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, const int plan)
1395 {
1396         switch (plan) {
1397         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1398                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1399                 break;
1400         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1401                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1402                 break;
1403         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1404                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1405                 break;
1406         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1407                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1408                 break;
1409         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1410                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1411                 break;
1412         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1413                 snprintf(buf, size, "%s", number);
1414                 break;
1415         }
1416 }
1417
1418 /*! \note Assumes the pri->lock is already obtained. */
1419 static int pri_check_restart(struct sig_pri_span *pri)
1420 {
1421 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1422 tryanotherpos:
1423 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1424         do {
1425                 pri->resetpos++;
1426         } while (pri->resetpos < pri->numchans
1427                 && (!pri->pvts[pri->resetpos]
1428                         || pri->pvts[pri->resetpos]->no_b_channel
1429                         || pri->pvts[pri->resetpos]->call
1430                         || pri->pvts[pri->resetpos]->resetting));
1431         if (pri->resetpos < pri->numchans) {
1432 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1433                 unsigned why;
1434
1435                 why = pri->pvts[pri->resetpos]->service_status;
1436                 if (why) {
1437                         ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1438                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1439                         goto tryanotherpos;
1440                 }
1441 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1442
1443                 /* Mark the channel as resetting and restart it */
1444                 pri->pvts[pri->resetpos]->resetting = 1;
1445                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1446         } else {
1447                 pri->resetting = 0;
1448                 time(&pri->lastreset);
1449         }
1450         return 0;
1451 }
1452
1453 #if defined(HAVE_PRI_CALL_WAITING)
1454 /*!
1455  * \internal
1456  * \brief Init the private channel configuration using the span controller.
1457  * \since 1.8
1458  *
1459  * \param pvt Channel to init the configuration.
1460  * \param pri PRI span control structure.
1461  *
1462  * \note Assumes the pri->lock is already obtained.
1463  *
1464  * \return Nothing
1465  */
1466 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_span *pri)
1467 {
1468         pvt->stripmsd = pri->ch_cfg.stripmsd;
1469         pvt->hidecallerid = pri->ch_cfg.hidecallerid;
1470         pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
1471         pvt->immediate = pri->ch_cfg.immediate;
1472         pvt->priexclusive = pri->ch_cfg.priexclusive;
1473         pvt->priindication_oob = pri->ch_cfg.priindication_oob;
1474         pvt->use_callerid = pri->ch_cfg.use_callerid;
1475         pvt->use_callingpres = pri->ch_cfg.use_callingpres;
1476         ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
1477         ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
1478
1479         if (pri->calls->init_config) {
1480                 pri->calls->init_config(pvt->chan_pvt, pri);
1481         }
1482 }
1483 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1484
1485 static int pri_find_empty_chan(struct sig_pri_span *pri, int backwards)
1486 {
1487         int x;
1488         if (backwards)
1489                 x = pri->numchans;
1490         else
1491                 x = 0;
1492         for (;;) {
1493                 if (backwards && (x < 0))
1494                         break;
1495                 if (!backwards && (x >= pri->numchans))
1496                         break;
1497                 if (pri->pvts[x]
1498                         && !pri->pvts[x]->no_b_channel
1499                         && !pri->pvts[x]->inalarm
1500                         && !pri->pvts[x]->owner) {
1501                         ast_debug(1, "Found empty available channel %d/%d\n",
1502                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1503                         return x;
1504                 }
1505                 if (backwards)
1506                         x--;
1507                 else
1508                         x++;
1509         }
1510         return -1;
1511 }
1512
1513 #if defined(HAVE_PRI_CALL_HOLD)
1514 /*!
1515  * \internal
1516  * \brief Find or create an empty no-B-channel interface to use.
1517  * \since 1.8
1518  *
1519  * \param pri PRI span control structure.
1520  *
1521  * \note Assumes the pri->lock is already obtained.
1522  *
1523  * \retval array-index into private pointer array on success.
1524  * \retval -1 on error.
1525  */
1526 static int pri_find_empty_nobch(struct sig_pri_span *pri)
1527 {
1528         int idx;
1529
1530         for (idx = 0; idx < pri->numchans; ++idx) {
1531                 if (pri->pvts[idx]
1532                         && pri->pvts[idx]->no_b_channel
1533                         && !pri->pvts[idx]->inalarm
1534                         && !pri->pvts[idx]->owner) {
1535                         ast_debug(1, "Found empty available no B channel interface\n");
1536                         return idx;
1537                 }
1538         }
1539
1540         /* Need to create a new interface. */
1541         if (pri->calls->new_nobch_intf) {
1542                 idx = pri->calls->new_nobch_intf(pri);
1543         } else {
1544                 idx = -1;
1545         }
1546         return idx;
1547 }
1548 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1549
1550 static void *do_idle_thread(void *v_pvt)
1551 {
1552         struct sig_pri_chan *pvt = v_pvt;
1553         struct ast_channel *chan = pvt->owner;
1554         struct ast_frame *f;
1555         char ex[80];
1556         /* Wait up to 30 seconds for an answer */
1557         int newms, ms = 30000;
1558
1559         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1560         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1561         if (ast_call(chan, ex, 0)) {
1562                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1563                 ast_hangup(chan);
1564                 return NULL;
1565         }
1566         while ((newms = ast_waitfor(chan, ms)) > 0) {
1567                 f = ast_read(chan);
1568                 if (!f) {
1569                         /* Got hangup */
1570                         break;
1571                 }
1572                 if (f->frametype == AST_FRAME_CONTROL) {
1573                         switch (f->subclass.integer) {
1574                         case AST_CONTROL_ANSWER:
1575                                 /* Launch the PBX */
1576                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1577                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1578                                 chan->priority = 1;
1579                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1580                                 ast_pbx_run(chan);
1581                                 /* It's already hungup, return immediately */
1582                                 return NULL;
1583                         case AST_CONTROL_BUSY:
1584                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1585                                 break;
1586                         case AST_CONTROL_CONGESTION:
1587                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1588                                 break;
1589                         };
1590                 }
1591                 ast_frfree(f);
1592                 ms = newms;
1593         }
1594         /* Hangup the channel since nothing happend */
1595         ast_hangup(chan);
1596         return NULL;
1597 }
1598
1599 static void *pri_ss_thread(void *data)
1600 {
1601         struct sig_pri_chan *p = data;
1602         struct ast_channel *chan = p->owner;
1603         char exten[AST_MAX_EXTENSION];
1604         int res;
1605         int len;
1606         int timeout;
1607
1608         if (!chan) {
1609                 /* We lost the owner before we could get started. */
1610                 return NULL;
1611         }
1612
1613         /*
1614          * In the bizarre case where the channel has become a zombie before we
1615          * even get started here, abort safely.
1616          */
1617         if (!chan->tech_pvt) {
1618                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1619                 ast_hangup(chan);
1620                 return NULL;
1621         }
1622
1623         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1624
1625         sig_pri_dsp_reset_and_flush_digits(p);
1626
1627         /* Now loop looking for an extension */
1628         ast_copy_string(exten, p->exten, sizeof(exten));
1629         len = strlen(exten);
1630         res = 0;
1631         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1632                 if (len && !ast_ignore_pattern(chan->context, exten))
1633                         sig_pri_play_tone(p, -1);
1634                 else
1635                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1636                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1637                         timeout = pri_matchdigittimeout;
1638                 else
1639                         timeout = pri_gendigittimeout;
1640                 res = ast_waitfordigit(chan, timeout);
1641                 if (res < 0) {
1642                         ast_debug(1, "waitfordigit returned < 0...\n");
1643                         ast_hangup(chan);
1644                         return NULL;
1645                 } else if (res) {
1646                         exten[len++] = res;
1647                         exten[len] = '\0';
1648                 } else
1649                         break;
1650         }
1651         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1652         if (ast_strlen_zero(exten)) {
1653                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1654                 exten[0] = 's';
1655                 exten[1] = '\0';
1656         } else {
1657                 ast_free(chan->dialed.number.str);
1658                 chan->dialed.number.str = ast_strdup(exten);
1659
1660                 if (p->pri->append_msn_to_user_tag && p->pri->nodetype != PRI_NETWORK) {
1661                         /*
1662                          * Update the user tag for party id's from this device for this call
1663                          * now that we have a complete MSN from the network.
1664                          */
1665                         snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
1666                                 exten);
1667                         ast_free(chan->caller.id.tag);
1668                         chan->caller.id.tag = ast_strdup(p->user_tag);
1669                 }
1670         }
1671         sig_pri_play_tone(p, -1);
1672         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1673                 /* Start the real PBX */
1674                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1675                 sig_pri_dsp_reset_and_flush_digits(p);
1676 #if defined(ISSUE_16789)
1677                 /*
1678                  * Conditionaled out this code to effectively revert the Mantis
1679                  * issue 16789 change.  It breaks overlap dialing through
1680                  * Asterisk.  There is not enough information available at this
1681                  * point to know if dialing is complete.  The
1682                  * ast_exists_extension(), ast_matchmore_extension(), and
1683                  * ast_canmatch_extension() calls are not adequate to detect a
1684                  * dial through extension pattern of "_9!".
1685                  *
1686                  * Workaround is to use the dialplan Proceeding() application
1687                  * early on non-dial through extensions.
1688                  */
1689                 if ((p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
1690                         && !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1691                         sig_pri_lock_private(p);
1692                         if (p->pri->pri) {
1693                                 if (!pri_grab(p, p->pri)) {
1694                                         if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
1695                                                 p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
1696                                         }
1697                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1698                                         pri_rel(p->pri);
1699                                 } else {
1700                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1701                                 }
1702                         }
1703                         sig_pri_unlock_private(p);
1704                 }
1705 #endif  /* defined(ISSUE_16789) */
1706
1707                 sig_pri_set_echocanceller(p, 1);
1708                 ast_setstate(chan, AST_STATE_RING);
1709                 res = ast_pbx_run(chan);
1710                 if (res) {
1711                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1712                 }
1713         } else {
1714                 ast_debug(1, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1715                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1716                 ast_hangup(chan);
1717                 p->exten[0] = '\0';
1718                 /* Since we send release complete here, we won't get one */
1719                 p->call = NULL;
1720         }
1721         return NULL;
1722 }
1723
1724 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
1725 {
1726         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1727         if (!before_start_pri)
1728                 pri_find_dchan(pri);
1729 }
1730
1731 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
1732 {
1733         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1734         if (!before_start_pri)
1735                 pri_restart(pri->dchans[index]);
1736 }
1737
1738 /*!
1739  * \internal
1740  * \brief Convert libpri party name into asterisk party name.
1741  * \since 1.8
1742  *
1743  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
1744  * \param pri_name libpri party name structure containing source information.
1745  *
1746  * \note The filled in ast_name structure needs to be destroyed by
1747  * ast_party_name_free() when it is no longer needed.
1748  *
1749  * \return Nothing
1750  */
1751 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
1752 {
1753         ast_name->str = ast_strdup(pri_name->str);
1754         ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
1755         ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
1756         ast_name->valid = 1;
1757 }
1758
1759 /*!
1760  * \internal
1761  * \brief Convert libpri party number into asterisk party number.
1762  * \since 1.8
1763  *
1764  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
1765  * \param pri_number libpri party number structure containing source information.
1766  * \param pri PRI span control structure.
1767  *
1768  * \note The filled in ast_number structure needs to be destroyed by
1769  * ast_party_number_free() when it is no longer needed.
1770  *
1771  * \return Nothing
1772  */
1773 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)
1774 {
1775         char number[AST_MAX_EXTENSION];
1776
1777         apply_plan_to_number(number, sizeof(number), pri, pri_number->str, pri_number->plan);
1778         ast_number->str = ast_strdup(number);
1779         ast_number->plan = pri_number->plan;
1780         ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
1781         ast_number->valid = 1;
1782 }
1783
1784 /*!
1785  * \internal
1786  * \brief Convert libpri party id into asterisk party id.
1787  * \since 1.8
1788  *
1789  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1790  * \param pri_id libpri party id structure containing source information.
1791  * \param pri PRI span control structure.
1792  *
1793  * \note The filled in ast_id structure needs to be destroyed by
1794  * ast_party_id_free() when it is no longer needed.
1795  *
1796  * \return Nothing
1797  */
1798 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)
1799 {
1800         if (pri_id->name.valid) {
1801                 sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
1802         }
1803         if (pri_id->number.valid) {
1804                 sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
1805         }
1806 #if defined(HAVE_PRI_SUBADDR)
1807         if (pri_id->subaddress.valid) {
1808                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1809         }
1810 #endif  /* defined(HAVE_PRI_SUBADDR) */
1811 }
1812
1813 /*!
1814  * \internal
1815  * \brief Convert libpri redirecting information into asterisk redirecting information.
1816  * \since 1.8
1817  *
1818  * \param ast_redirecting Asterisk redirecting structure to fill.
1819  * \param pri_redirecting libpri redirecting structure containing source information.
1820  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1821  * \param pri PRI span control structure.
1822  *
1823  * \note The filled in ast_redirecting structure needs to be destroyed by
1824  * ast_party_redirecting_free() when it is no longer needed.
1825  *
1826  * \return Nothing
1827  */
1828 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1829         const struct pri_party_redirecting *pri_redirecting,
1830         const struct ast_party_redirecting *ast_guide,
1831         struct sig_pri_span *pri)
1832 {
1833         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1834
1835         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1836         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1837         ast_redirecting->count = pri_redirecting->count;
1838         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1839 }
1840
1841 /*!
1842  * \internal
1843  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1844  * \since 1.8
1845  *
1846  * \param msn_patterns Comma separated list of MSN patterns to match.
1847  * \param exten Extension to match in the MSN list.
1848  *
1849  * \retval 1 if matches.
1850  * \retval 0 if no match.
1851  */
1852 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1853 {
1854         char *pattern;
1855         char *msn_list;
1856         char *list_tail;
1857
1858         msn_list = ast_strdupa(msn_patterns);
1859
1860         list_tail = NULL;
1861         pattern = strtok_r(msn_list, ",", &list_tail);
1862         while (pattern) {
1863                 pattern = ast_strip(pattern);
1864                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1865                         /* Extension matched the pattern. */
1866                         return 1;
1867                 }
1868                 pattern = strtok_r(NULL, ",", &list_tail);
1869         }
1870         /* Did not match any pattern in the list. */
1871         return 0;
1872 }
1873
1874 #if defined(HAVE_PRI_MCID)
1875 /*!
1876  * \internal
1877  * \brief Append the given party id to the event string.
1878  * \since 1.8
1879  *
1880  * \param msg Event message string being built.
1881  * \param prefix Prefix to add to the party id lines.
1882  * \param party Party information to encode.
1883  *
1884  * \return Nothing
1885  */
1886 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
1887 {
1888         int pres;
1889
1890         /* Combined party presentation */
1891         pres = ast_party_id_presentation(party);
1892         ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix, pres,
1893                 ast_describe_caller_presentation(pres));
1894
1895         /* Party number */
1896         ast_str_append(msg, 0, "%sNumValid: %d\r\n", prefix,
1897                 (unsigned) party->number.valid);
1898         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix,
1899                 S_COR(party->number.valid, party->number.str, ""));
1900         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number.plan);
1901         if (party->number.valid) {
1902                 ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, party->number.plan);
1903                 ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix,
1904                         party->number.presentation,
1905                         ast_describe_caller_presentation(party->number.presentation));
1906         }
1907
1908         /* Party name */
1909         ast_str_append(msg, 0, "%sNameValid: %d\r\n", prefix,
1910                 (unsigned) party->name.valid);
1911         ast_str_append(msg, 0, "%sName: %s\r\n", prefix,
1912                 S_COR(party->name.valid, party->name.str, ""));
1913         if (party->name.valid) {
1914                 ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix,
1915                         ast_party_name_charset_describe(party->name.char_set));
1916                 ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix,
1917                         party->name.presentation,
1918                         ast_describe_caller_presentation(party->name.presentation));
1919         }
1920
1921 #if defined(HAVE_PRI_SUBADDR)
1922         /* Party subaddress */
1923         if (party->subaddress.valid) {
1924                 static const char subaddress[] = "Subaddr";
1925
1926                 ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
1927                         S_OR(party->subaddress.str, ""));
1928                 ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
1929                         party->subaddress.type);
1930                 ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
1931                         party->subaddress.odd_even_indicator);
1932         }
1933 #endif  /* defined(HAVE_PRI_SUBADDR) */
1934 }
1935 #endif  /* defined(HAVE_PRI_MCID) */
1936
1937 #if defined(HAVE_PRI_MCID)
1938 /*!
1939  * \internal
1940  * \brief Handle the MCID event.
1941  * \since 1.8
1942  *
1943  * \param pri PRI span control structure.
1944  * \param mcid MCID event parameters.
1945  * \param owner Asterisk channel associated with the call.
1946  * NULL if Asterisk no longer has the ast_channel struct.
1947  *
1948  * \note Assumes the pri->lock is already obtained.
1949  * \note Assumes the owner channel lock is already obtained if still present.
1950  *
1951  * \return Nothing
1952  */
1953 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
1954 {
1955         struct ast_channel *chans[1];
1956         struct ast_str *msg;
1957         struct ast_party_id party;
1958
1959         msg = ast_str_create(4096);
1960         if (!msg) {
1961                 return;
1962         }
1963
1964         if (owner) {
1965                 /*
1966                  * The owner channel is present.
1967                  * Pass the event to the peer as well.
1968                  */
1969                 ast_queue_control(owner, AST_CONTROL_MCID);
1970
1971                 ast_str_append(&msg, 0, "Channel: %s\r\n", owner->name);
1972                 ast_str_append(&msg, 0, "UniqueID: %s\r\n", owner->uniqueid);
1973
1974                 sig_pri_event_party_id(&msg, "CallerID", &owner->connected.id);
1975         } else {
1976                 /*
1977                  * Since we no longer have an owner channel,
1978                  * we have to use the caller information supplied by libpri.
1979                  */
1980                 ast_party_id_init(&party);
1981                 sig_pri_party_id_convert(&party, &mcid->originator, pri);
1982                 sig_pri_event_party_id(&msg, "CallerID", &party);
1983                 ast_party_id_free(&party);
1984         }
1985
1986         /* Always use libpri's called party information. */
1987         ast_party_id_init(&party);
1988         sig_pri_party_id_convert(&party, &mcid->answerer, pri);
1989         sig_pri_event_party_id(&msg, "ConnectedID", &party);
1990         ast_party_id_free(&party);
1991
1992         chans[0] = owner;
1993         ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
1994                 ast_str_buffer(msg));
1995         ast_free(msg);
1996 }
1997 #endif  /* defined(HAVE_PRI_MCID) */
1998
1999 #if defined(HAVE_PRI_TRANSFER)
2000 struct xfer_rsp_data {
2001         struct sig_pri_span *pri;
2002         /*! Call to send transfer success/fail response over. */
2003         q931_call *call;
2004         /*! Invocation ID to use when sending a reply to the transfer request. */
2005         int invoke_id;
2006 };
2007 #endif  /* defined(HAVE_PRI_TRANSFER) */
2008
2009 #if defined(HAVE_PRI_TRANSFER)
2010 /*!
2011  * \internal
2012  * \brief Send the transfer success/fail response message.
2013  * \since 1.8
2014  *
2015  * \param data Callback user data pointer
2016  * \param is_successful TRUE if the transfer was successful.
2017  *
2018  * \return Nothing
2019  */
2020 static void sig_pri_transfer_rsp(void *data, int is_successful)
2021 {
2022         struct xfer_rsp_data *rsp = data;
2023
2024         pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
2025 }
2026 #endif  /* defined(HAVE_PRI_TRANSFER) */
2027
2028 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2029 /*!
2030  * \brief Protocol callback to indicate if transfer will happen.
2031  * \since 1.8
2032  *
2033  * \param data Callback user data pointer
2034  * \param is_successful TRUE if the transfer will happen.
2035  *
2036  * \return Nothing
2037  */
2038 typedef void (*xfer_rsp_callback)(void *data, int is_successful);
2039 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2040
2041 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2042 /*!
2043  * \internal
2044  * \brief Attempt to transfer the two calls to each other.
2045  * \since 1.8
2046  *
2047  * \param pri PRI span control structure.
2048  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
2049  * \param call_1_held TRUE if call_1_pri is on hold.
2050  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
2051  * \param call_2_held TRUE if call_2_pri is on hold.
2052  * \param rsp_callback Protocol callback to indicate if transfer will happen. NULL if not used.
2053  * \param data Callback user data pointer
2054  *
2055  * \note Assumes the pri->lock is already obtained.
2056  *
2057  * \retval 0 on success.
2058  * \retval -1 on error.
2059  */
2060 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)
2061 {
2062         struct attempt_xfer_call {
2063                 q931_call *pri;
2064                 struct ast_channel *ast;
2065                 int held;
2066                 int chanpos;
2067         };
2068         int retval;
2069         struct ast_channel *transferee;
2070         struct attempt_xfer_call *call_1;
2071         struct attempt_xfer_call *call_2;
2072         struct attempt_xfer_call *swap_call;
2073         struct attempt_xfer_call c1;
2074         struct attempt_xfer_call c2;
2075
2076         c1.pri = call_1_pri;
2077         c1.held = call_1_held;
2078         call_1 = &c1;
2079
2080         c2.pri = call_2_pri;
2081         c2.held = call_2_held;
2082         call_2 = &c2;
2083
2084         call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
2085         call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
2086         if (call_1->chanpos < 0 || call_2->chanpos < 0) {
2087                 /* Calls not found in span control. */
2088                 if (rsp_callback) {
2089                         /* Transfer failed. */
2090                         rsp_callback(data, 0);
2091                 }
2092                 return -1;
2093         }
2094
2095         /* Attempt to make transferee and target consistent. */
2096         if (!call_1->held && call_2->held) {
2097                 /*
2098                  * Swap call_1 and call_2 to make call_1 the transferee(held call)
2099                  * and call_2 the target(active call).
2100                  */
2101                 swap_call = call_1;
2102                 call_1 = call_2;
2103                 call_2 = swap_call;
2104         }
2105
2106         /* Deadlock avoidance is attempted. */
2107         sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2108         sig_pri_lock_owner(pri, call_1->chanpos);
2109         sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2110         sig_pri_lock_owner(pri, call_2->chanpos);
2111
2112         call_1->ast = pri->pvts[call_1->chanpos]->owner;
2113         call_2->ast = pri->pvts[call_2->chanpos]->owner;
2114         if (!call_1->ast || !call_2->ast) {
2115                 /* At least one owner is not present. */
2116                 if (call_1->ast) {
2117                         ast_channel_unlock(call_1->ast);
2118                 }
2119                 if (call_2->ast) {
2120                         ast_channel_unlock(call_2->ast);
2121                 }
2122                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2123                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2124                 if (rsp_callback) {
2125                         /* Transfer failed. */
2126                         rsp_callback(data, 0);
2127                 }
2128                 return -1;
2129         }
2130
2131         for (;;) {
2132                 transferee = ast_bridged_channel(call_1->ast);
2133                 if (transferee) {
2134                         break;
2135                 }
2136
2137                 /* Try masquerading the other way. */
2138                 swap_call = call_1;
2139                 call_1 = call_2;
2140                 call_2 = swap_call;
2141
2142                 transferee = ast_bridged_channel(call_1->ast);
2143                 if (transferee) {
2144                         break;
2145                 }
2146
2147                 /* Could not transfer.  Neither call is bridged. */
2148                 ast_channel_unlock(call_1->ast);
2149                 ast_channel_unlock(call_2->ast);
2150                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2151                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2152
2153                 if (rsp_callback) {
2154                         /* Transfer failed. */
2155                         rsp_callback(data, 0);
2156                 }
2157                 return -1;
2158         }
2159
2160         ast_verb(3, "TRANSFERRING %s to %s\n", call_1->ast->name, call_2->ast->name);
2161
2162         /*
2163          * Setup transfer masquerade.
2164          *
2165          * Note:  There is an extremely nasty deadlock avoidance issue
2166          * with ast_channel_transfer_masquerade().  Deadlock may be possible if
2167          * the channels involved are proxies (chan_agent channels) and
2168          * it is called with locks.  Unfortunately, there is no simple
2169          * or even merely difficult way to guarantee deadlock avoidance
2170          * and still be able to send an ECT success response without the
2171          * possibility of the bridged channel hanging up on us.
2172          */
2173         ast_mutex_unlock(&pri->lock);
2174         retval = ast_channel_transfer_masquerade(
2175                 call_2->ast,
2176                 &call_2->ast->connected,
2177                 call_2->held,
2178                 transferee,
2179                 &call_1->ast->connected,
2180                 call_1->held);
2181
2182         /* Reacquire the pri->lock to hold off completion of the transfer masquerade. */
2183         ast_mutex_lock(&pri->lock);
2184
2185         ast_channel_unlock(call_1->ast);
2186         ast_channel_unlock(call_2->ast);
2187         sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2188         sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2189
2190         if (rsp_callback) {
2191                 /*
2192                  * Report transfer status.
2193                  *
2194                  * Must do the callback before the masquerade completes to ensure
2195                  * that the protocol message goes out before the call leg is
2196                  * disconnected.
2197                  */
2198                 rsp_callback(data, retval ? 0 : 1);
2199         }
2200         return retval;
2201 }
2202 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2203
2204 #if defined(HAVE_PRI_CCSS)
2205 /*!
2206  * \internal
2207  * \brief Compare the CC agent private data by libpri cc_id.
2208  * \since 1.8
2209  *
2210  * \param obj pointer to the (user-defined part) of an object.
2211  * \param arg callback argument from ao2_callback()
2212  * \param flags flags from ao2_callback()
2213  *
2214  * \return values are a combination of enum _cb_results.
2215  */
2216 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
2217 {
2218         struct ast_cc_agent *agent_1 = obj;
2219         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2220         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2221
2222         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2223                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2224 }
2225 #endif  /* defined(HAVE_PRI_CCSS) */
2226
2227 #if defined(HAVE_PRI_CCSS)
2228 /*!
2229  * \internal
2230  * \brief Find the CC agent by libpri cc_id.
2231  * \since 1.8
2232  *
2233  * \param pri PRI span control structure.
2234  * \param cc_id CC record ID to find.
2235  *
2236  * \note
2237  * Since agents are refcounted, and this function returns
2238  * a reference to the agent, it is imperative that you decrement
2239  * the refcount of the agent once you have finished using it.
2240  *
2241  * \retval agent on success.
2242  * \retval NULL not found.
2243  */
2244 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2245 {
2246         struct sig_pri_cc_agent_prv finder = {
2247                 .pri = pri,
2248                 .cc_id = cc_id,
2249         };
2250
2251         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2252                 sig_pri_cc_type_name);
2253 }
2254 #endif  /* defined(HAVE_PRI_CCSS) */
2255
2256 #if defined(HAVE_PRI_CCSS)
2257 /*!
2258  * \internal
2259  * \brief Compare the CC monitor instance by libpri cc_id.
2260  * \since 1.8
2261  *
2262  * \param obj pointer to the (user-defined part) of an object.
2263  * \param arg callback argument from ao2_callback()
2264  * \param flags flags from ao2_callback()
2265  *
2266  * \return values are a combination of enum _cb_results.
2267  */
2268 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2269 {
2270         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2271         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2272
2273         return (monitor_1->pri == monitor_2->pri
2274                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2275 }
2276 #endif  /* defined(HAVE_PRI_CCSS) */
2277
2278 #if defined(HAVE_PRI_CCSS)
2279 /*!
2280  * \internal
2281  * \brief Find the CC monitor instance by libpri cc_id.
2282  * \since 1.8
2283  *
2284  * \param pri PRI span control structure.
2285  * \param cc_id CC record ID to find.
2286  *
2287  * \note
2288  * Since monitor_instances are refcounted, and this function returns
2289  * a reference to the instance, it is imperative that you decrement
2290  * the refcount of the instance once you have finished using it.
2291  *
2292  * \retval monitor_instance on success.
2293  * \retval NULL not found.
2294  */
2295 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2296 {
2297         struct sig_pri_cc_monitor_instance finder = {
2298                 .pri = pri,
2299                 .cc_id = cc_id,
2300         };
2301
2302         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2303 }
2304 #endif  /* defined(HAVE_PRI_CCSS) */
2305
2306 #if defined(HAVE_PRI_CCSS)
2307 /*!
2308  * \internal
2309  * \brief Destroy the given monitor instance.
2310  * \since 1.8
2311  *
2312  * \param data Monitor instance to destroy.
2313  *
2314  * \return Nothing
2315  */
2316 static void sig_pri_cc_monitor_instance_destroy(void *data)
2317 {
2318         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2319
2320         if (monitor_instance->cc_id != -1) {
2321                 ast_mutex_lock(&monitor_instance->pri->lock);
2322                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2323                 ast_mutex_unlock(&monitor_instance->pri->lock);
2324         }
2325         monitor_instance->pri->calls->module_unref();
2326 }
2327 #endif  /* defined(HAVE_PRI_CCSS) */
2328
2329 #if defined(HAVE_PRI_CCSS)
2330 /*!
2331  * \internal
2332  * \brief Construct a new monitor instance.
2333  * \since 1.8
2334  *
2335  * \param core_id CC core ID.
2336  * \param pri PRI span control structure.
2337  * \param cc_id CC record ID.
2338  * \param device_name Name of device (Asterisk channel name less sequence number).
2339  *
2340  * \note
2341  * Since monitor_instances are refcounted, and this function returns
2342  * a reference to the instance, it is imperative that you decrement
2343  * the refcount of the instance once you have finished using it.
2344  *
2345  * \retval monitor_instance on success.
2346  * \retval NULL on error.
2347  */
2348 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)
2349 {
2350         struct sig_pri_cc_monitor_instance *monitor_instance;
2351
2352         if (!pri->calls->module_ref || !pri->calls->module_unref) {
2353                 return NULL;
2354         }
2355
2356         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2357                 sig_pri_cc_monitor_instance_destroy);
2358         if (!monitor_instance) {
2359                 return NULL;
2360         }
2361
2362         monitor_instance->cc_id = cc_id;
2363         monitor_instance->pri = pri;
2364         monitor_instance->core_id = core_id;
2365         strcpy(monitor_instance->name, device_name);
2366
2367         pri->calls->module_ref();
2368
2369         ao2_link(sig_pri_cc_monitors, monitor_instance);
2370         return monitor_instance;
2371 }
2372 #endif  /* defined(HAVE_PRI_CCSS) */
2373
2374 #if defined(HAVE_PRI_CCSS)
2375 /*!
2376  * \internal
2377  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2378  * \since 1.8
2379  *
2380  * \param pri PRI span control structure.
2381  * \param chanpos Channel position in the span.
2382  * \param cc_id CC record ID.
2383  * \param service CCBS/CCNR indication.
2384  *
2385  * \note Assumes the pri->lock is already obtained.
2386  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2387  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2388  *
2389  * \retval 0 on success.
2390  * \retval -1 on error.
2391  */
2392 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2393 {
2394         struct sig_pri_chan *pvt;
2395         struct ast_cc_config_params *cc_params;
2396         struct sig_pri_cc_monitor_instance *monitor;
2397         enum ast_cc_monitor_policies monitor_policy;
2398         int core_id;
2399         int res;
2400         char device_name[AST_CHANNEL_NAME];
2401         char dialstring[AST_CHANNEL_NAME];
2402
2403         pvt = pri->pvts[chanpos];
2404
2405         core_id = ast_cc_get_current_core_id(pvt->owner);
2406         if (core_id == -1) {
2407                 return -1;
2408         }
2409
2410         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2411         if (!cc_params) {
2412                 return -1;
2413         }
2414
2415         res = -1;
2416         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2417         switch (monitor_policy) {
2418         case AST_CC_MONITOR_NEVER:
2419                 /* CCSS is not enabled. */
2420                 break;
2421         case AST_CC_MONITOR_NATIVE:
2422         case AST_CC_MONITOR_ALWAYS:
2423                 /*
2424                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2425                  * later in the call to sig_pri_cc_generic_check().
2426                  */
2427                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2428                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2429                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2430                 if (!monitor) {
2431                         break;
2432                 }
2433                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2434                         monitor);
2435                 if (res) {
2436                         monitor->cc_id = -1;
2437                         ao2_unlink(sig_pri_cc_monitors, monitor);
2438                         ao2_ref(monitor, -1);
2439                 }
2440                 break;
2441         case AST_CC_MONITOR_GENERIC:
2442                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2443                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2444                 /* Say it failed to force caller to cancel native CC. */
2445                 break;
2446         }
2447         return res;
2448 }
2449 #endif  /* defined(HAVE_PRI_CCSS) */
2450
2451 /*!
2452  * \internal
2453  * \brief Check if generic CC monitor is needed and request it.
2454  * \since 1.8
2455  *
2456  * \param pri PRI span control structure.
2457  * \param chanpos Channel position in the span.
2458  * \param service CCBS/CCNR indication.
2459  *
2460  * \note Assumes the pri->lock is already obtained.
2461  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2462  *
2463  * \return Nothing
2464  */
2465 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
2466 {
2467         struct ast_channel *owner;
2468         struct ast_cc_config_params *cc_params;
2469 #if defined(HAVE_PRI_CCSS)
2470         struct ast_cc_monitor *monitor;
2471         char device_name[AST_CHANNEL_NAME];
2472 #endif  /* defined(HAVE_PRI_CCSS) */
2473         enum ast_cc_monitor_policies monitor_policy;
2474         int core_id;
2475
2476         if (!pri->pvts[chanpos]->outgoing) {
2477                 /* This is not an outgoing call so it cannot be CC monitor. */
2478                 return;
2479         }
2480
2481         sig_pri_lock_owner(pri, chanpos);
2482         owner = pri->pvts[chanpos]->owner;
2483         if (!owner) {
2484                 return;
2485         }
2486         core_id = ast_cc_get_current_core_id(owner);
2487         if (core_id == -1) {
2488                 /* No CC core setup */
2489                 goto done;
2490         }
2491
2492         cc_params = ast_channel_get_cc_config_params(owner);
2493         if (!cc_params) {
2494                 /* Could not get CC config parameters. */
2495                 goto done;
2496         }
2497
2498 #if defined(HAVE_PRI_CCSS)
2499         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
2500         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
2501         if (monitor) {
2502                 /* CC monitor is already present so no need for generic CC. */
2503                 ao2_ref(monitor, -1);
2504                 goto done;
2505         }
2506 #endif  /* defined(HAVE_PRI_CCSS) */
2507
2508         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2509         switch (monitor_policy) {
2510         case AST_CC_MONITOR_NEVER:
2511                 /* CCSS is not enabled. */
2512                 break;
2513         case AST_CC_MONITOR_NATIVE:
2514                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2515                         /* Request generic CC monitor. */
2516                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2517                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2518                 }
2519                 break;
2520         case AST_CC_MONITOR_ALWAYS:
2521                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2522                         /*
2523                          * Cannot monitor PTMP TE side since this is not defined.
2524                          * We are playing the roll of a phone in this case and
2525                          * a phone cannot monitor a party over the network without
2526                          * protocol help.
2527                          */
2528                         break;
2529                 }
2530                 /*
2531                  * We are either falling back or this is a PTMP NT span.
2532                  * Request generic CC monitor.
2533                  */
2534                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2535                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2536                 break;
2537         case AST_CC_MONITOR_GENERIC:
2538                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2539                         /* Request generic CC monitor. */
2540                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2541                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2542                 }
2543                 break;
2544         }
2545
2546 done:
2547         ast_channel_unlock(owner);
2548 }
2549
2550 #if defined(HAVE_PRI_CCSS)
2551 /*!
2552  * \internal
2553  * \brief The CC link canceled the CC instance.
2554  * \since 1.8
2555  *
2556  * \param pri PRI span control structure.
2557  * \param cc_id CC record ID.
2558  * \param is_agent TRUE if the cc_id is for an agent.
2559  *
2560  * \return Nothing
2561  */
2562 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
2563 {
2564         if (is_agent) {
2565                 struct ast_cc_agent *agent;
2566
2567                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2568                 if (!agent) {
2569                         return;
2570                 }
2571                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2572                         sig_pri_cc_type_name);
2573                 ao2_ref(agent, -1);
2574         } else {
2575                 struct sig_pri_cc_monitor_instance *monitor;
2576
2577                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2578                 if (!monitor) {
2579                         return;
2580                 }
2581                 monitor->cc_id = -1;
2582                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2583                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2584                 ao2_ref(monitor, -1);
2585         }
2586 }
2587 #endif  /* defined(HAVE_PRI_CCSS) */
2588
2589 #if defined(HAVE_PRI_AOC_EVENTS)
2590 /*!
2591  * \internal
2592  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2593  * \since 1.8
2594  *
2595  * \param value Value to convert to string.
2596  *
2597  * \return PRI_AOC_CHARGED_ITEM
2598  */
2599 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2600 {
2601         switch (value) {
2602         case AST_AOC_CHARGED_ITEM_NA:
2603                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2604         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2605                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2606         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2607                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2608         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2609                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2610         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2611                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2612         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2613                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2614         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2615                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2616         }
2617         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2618 }
2619 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2620
2621 #if defined(HAVE_PRI_AOC_EVENTS)
2622 /*!
2623  * \internal
2624  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2625  * \since 1.8
2626  *
2627  * \param value Value to convert to string.
2628  *
2629  * \return ast_aoc_charged_item
2630  */
2631 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2632 {
2633         switch (value) {
2634         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2635                 return AST_AOC_CHARGED_ITEM_NA;
2636         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2637                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2638         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2639                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2640         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2641                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2642         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2643                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2644         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2645                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2646         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2647                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2648         }
2649         return AST_AOC_CHARGED_ITEM_NA;
2650 }
2651 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2652
2653 #if defined(HAVE_PRI_AOC_EVENTS)
2654 /*!
2655  * \internal
2656  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2657  * \since 1.8
2658  *
2659  * \return pri enum equivalent.
2660  */
2661 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2662 {
2663         switch (mult) {
2664         case AST_AOC_MULT_ONETHOUSANDTH:
2665                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2666         case AST_AOC_MULT_ONEHUNDREDTH:
2667                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2668         case AST_AOC_MULT_ONETENTH:
2669                 return PRI_AOC_MULTIPLIER_TENTH;
2670         case AST_AOC_MULT_ONE:
2671                 return PRI_AOC_MULTIPLIER_ONE;
2672         case AST_AOC_MULT_TEN:
2673                 return PRI_AOC_MULTIPLIER_TEN;
2674         case AST_AOC_MULT_HUNDRED:
2675                 return PRI_AOC_MULTIPLIER_HUNDRED;
2676         case AST_AOC_MULT_THOUSAND:
2677                 return PRI_AOC_MULTIPLIER_THOUSAND;
2678         default:
2679                 return PRI_AOC_MULTIPLIER_ONE;
2680         }
2681 }
2682 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2683
2684 #if defined(HAVE_PRI_AOC_EVENTS)
2685 /*!
2686  * \internal
2687  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2688  * \since 1.8
2689  *
2690  * \return ast enum equivalent.
2691  */
2692 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2693 {
2694         switch (mult) {
2695         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2696                 return AST_AOC_MULT_ONETHOUSANDTH;
2697         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2698                 return AST_AOC_MULT_ONEHUNDREDTH;
2699         case PRI_AOC_MULTIPLIER_TENTH:
2700                 return AST_AOC_MULT_ONETENTH;
2701         case PRI_AOC_MULTIPLIER_ONE:
2702                 return AST_AOC_MULT_ONE;
2703         case PRI_AOC_MULTIPLIER_TEN:
2704                 return AST_AOC_MULT_TEN;
2705         case PRI_AOC_MULTIPLIER_HUNDRED:
2706                 return AST_AOC_MULT_HUNDRED;
2707         case PRI_AOC_MULTIPLIER_THOUSAND:
2708                 return AST_AOC_MULT_THOUSAND;
2709         default:
2710                 return AST_AOC_MULT_ONE;
2711         }
2712 }
2713 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2714
2715 #if defined(HAVE_PRI_AOC_EVENTS)
2716 /*!
2717  * \internal
2718  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
2719  * \since 1.8
2720  *
2721  * \param value Value to convert to ast representation
2722  *
2723  * \return PRI_AOC_TIME_SCALE
2724  */
2725 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
2726 {
2727         switch (value) {
2728         default:
2729         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2730                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2731         case AST_AOC_TIME_SCALE_TENTH_SECOND:
2732                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
2733         case AST_AOC_TIME_SCALE_SECOND:
2734                 return PRI_AOC_TIME_SCALE_SECOND;
2735         case AST_AOC_TIME_SCALE_TEN_SECOND:
2736                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
2737         case AST_AOC_TIME_SCALE_MINUTE:
2738                 return PRI_AOC_TIME_SCALE_MINUTE;
2739         case AST_AOC_TIME_SCALE_HOUR:
2740                 return PRI_AOC_TIME_SCALE_HOUR;
2741         case AST_AOC_TIME_SCALE_DAY:
2742                 return PRI_AOC_TIME_SCALE_DAY;
2743         }
2744 }
2745 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2746
2747 #if defined(HAVE_PRI_AOC_EVENTS)
2748 /*!
2749  * \internal
2750  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
2751  * \since 1.8
2752  *
2753  * \param value Value to convert to ast representation
2754  *
2755  * \return ast aoc time scale
2756  */
2757 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
2758 {
2759         switch (value) {
2760         default:
2761         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2762                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2763         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
2764                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
2765         case PRI_AOC_TIME_SCALE_SECOND:
2766                 return AST_AOC_TIME_SCALE_SECOND;
2767         case PRI_AOC_TIME_SCALE_TEN_SECOND:
2768                 return AST_AOC_TIME_SCALE_TEN_SECOND;
2769         case PRI_AOC_TIME_SCALE_MINUTE:
2770                 return AST_AOC_TIME_SCALE_MINUTE;
2771         case PRI_AOC_TIME_SCALE_HOUR:
2772                 return AST_AOC_TIME_SCALE_HOUR;
2773         case PRI_AOC_TIME_SCALE_DAY:
2774                 return AST_AOC_TIME_SCALE_DAY;
2775         }
2776         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2777 }
2778 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2779
2780 #if defined(HAVE_PRI_AOC_EVENTS)
2781 /*!
2782  * \internal
2783  * \brief Handle AOC-S control frame
2784  * \since 1.8
2785  *
2786  * \param aoc_s AOC-S event parameters.
2787  * \param owner Asterisk channel associated with the call.
2788  * \param passthrough indicating if this message should be queued on the ast channel
2789  *
2790  * \note Assumes the pri->lock is already obtained.
2791  * \note Assumes the sig_pri private is locked
2792  * \note Assumes the owner channel lock is already obtained.
2793  *
2794  * \return Nothing
2795  */
2796 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
2797 {
2798         struct ast_aoc_decoded *decoded = NULL;
2799         struct ast_aoc_encoded *encoded = NULL;
2800         size_t encoded_size = 0;
2801         int idx;
2802
2803         if (!owner || !aoc_s) {
2804                 return;
2805         }
2806
2807         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
2808                 return;
2809         }
2810
2811         for (idx = 0; idx < aoc_s->num_items; ++idx) {
2812                 enum ast_aoc_s_charged_item charged_item;
2813
2814                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
2815                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
2816                         /* Delete the unknown charged item from the list. */
2817                         continue;
2818                 }
2819                 switch (aoc_s->item[idx].rate_type) {
2820                 case PRI_AOC_RATE_TYPE_DURATION:
2821                         ast_aoc_s_add_rate_duration(decoded,
2822                                 charged_item,
2823                                 aoc_s->item[idx].rate.duration.amount.cost,
2824                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
2825                                 aoc_s->item[idx].rate.duration.currency,
2826                                 aoc_s->item[idx].rate.duration.time.length,
2827                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
2828                                 aoc_s->item[idx].rate.duration.granularity.length,
2829                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
2830                                 aoc_s->item[idx].rate.duration.charging_type);
2831                         break;
2832                 case PRI_AOC_RATE_TYPE_FLAT:
2833                         ast_aoc_s_add_rate_flat(decoded,
2834                                 charged_item,
2835                                 aoc_s->item[idx].rate.flat.amount.cost,
2836                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
2837                                 aoc_s->item[idx].rate.flat.currency);
2838                         break;
2839                 case PRI_AOC_RATE_TYPE_VOLUME:
2840                         ast_aoc_s_add_rate_volume(decoded,
2841                                 charged_item,
2842                                 aoc_s->item[idx].rate.volume.unit,
2843                                 aoc_s->item[idx].rate.volume.amount.cost,
2844                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
2845                                 aoc_s->item[idx].rate.volume.currency);
2846                         break;
2847                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
2848                         ast_aoc_s_add_rate_special_charge_code(decoded,
2849                                 charged_item,
2850                                 aoc_s->item[idx].rate.special);
2851                         break;
2852                 case PRI_AOC_RATE_TYPE_FREE:
2853                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
2854                         break;
2855                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2856                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
2857                         break;
2858                 default:
2859                         ast_aoc_s_add_rate_na(decoded, charged_item);
2860                         break;
2861                 }
2862         }
2863
2864         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2865                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2866         }
2867
2868         ast_aoc_manager_event(decoded, owner);
2869
2870         ast_aoc_destroy_decoded(decoded);
2871         ast_aoc_destroy_encoded(encoded);
2872 }
2873 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2874
2875 #if defined(HAVE_PRI_AOC_EVENTS)
2876 /*!
2877  * \internal
2878  * \brief Generate AOC Request Response
2879  * \since 1.8
2880  *
2881  * \param aoc_request
2882  *
2883  * \note Assumes the pri->lock is already obtained.
2884  * \note Assumes the sig_pri private is locked
2885  * \note Assumes the owner channel lock is already obtained.
2886  *
2887  * \return Nothing
2888  */
2889 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
2890 {
2891         int request;
2892
2893         if (!aoc_request) {
2894                 return;
2895         }
2896
2897         request = aoc_request->charging_request;
2898
2899         if (request & PRI_AOC_REQUEST_S) {
2900                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
2901                         /* An AOC-S response must come from the other side, so save off this invoke_id
2902                          * and see if an AOC-S message comes in before the call is answered. */
2903                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
2904                         pvt->aoc_s_request_invoke_id_valid = 1;
2905
2906                 } else {
2907                         pri_aoc_s_request_response_send(pvt->pri->pri,
2908                                 call,
2909                                 aoc_request->invoke_id,
2910                                 NULL);
2911                 }
2912         }
2913
2914         if (request & PRI_AOC_REQUEST_D) {
2915                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
2916                         pri_aoc_de_request_response_send(pvt->pri->pri,
2917                                 call,
2918                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2919                                 aoc_request->invoke_id);
2920                 } else {
2921                         pri_aoc_de_request_response_send(pvt->pri->pri,
2922                                 call,
2923                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2924                                 aoc_request->invoke_id);
2925                 }
2926         }
2927
2928         if (request & PRI_AOC_REQUEST_E) {
2929                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
2930                         pri_aoc_de_request_response_send(pvt->pri->pri,
2931                                 call,
2932                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2933                                 aoc_request->invoke_id);
2934                 } else {
2935                         pri_aoc_de_request_response_send(pvt->pri->pri,
2936                                 call,
2937                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2938                                 aoc_request->invoke_id);
2939                 }
2940         }
2941 }
2942 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2943
2944 #if defined(HAVE_PRI_AOC_EVENTS)
2945 /*!
2946  * \internal
2947  * \brief Generate AOC-D AST_CONTROL_AOC frame
2948  * \since 1.8
2949  *
2950  * \param aoc_e AOC-D event parameters.
2951  * \param owner Asterisk channel associated with the call.
2952  * \param passthrough indicating if this message should be queued on the ast channel
2953  *
2954  * \note Assumes the pri->lock is already obtained.
2955  * \note Assumes the sig_pri private is locked
2956  * \note Assumes the owner channel lock is already obtained.
2957  *
2958  * \return Nothing
2959  */
2960 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
2961 {
2962         struct ast_aoc_decoded *decoded = NULL;
2963         struct ast_aoc_encoded *encoded = NULL;
2964         size_t encoded_size = 0;
2965         enum ast_aoc_charge_type type;
2966
2967         if (!owner || !aoc_d) {
2968                 return;
2969         }
2970
2971         switch (aoc_d->charge) {
2972         case PRI_AOC_DE_CHARGE_CURRENCY:
2973                 type = AST_AOC_CHARGE_CURRENCY;
2974                 break;
2975         case PRI_AOC_DE_CHARGE_UNITS:
2976                 type = AST_AOC_CHARGE_UNIT;
2977                 break;
2978         case PRI_AOC_DE_CHARGE_FREE:
2979                 type = AST_AOC_CHARGE_FREE;
2980                 break;
2981         default:
2982                 type = AST_AOC_CHARGE_NA;
2983                 break;
2984         }
2985
2986         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
2987                 return;
2988         }
2989
2990         switch (aoc_d->billing_accumulation) {
2991         default:
2992                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
2993                         aoc_d->billing_accumulation);
2994                 /* Fall through */
2995         case 0:/* subTotal */
2996                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
2997                 break;
2998         case 1:/* total */
2999                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
3000                 break;
3001         }
3002
3003         switch (aoc_d->billing_id) {
3004         case PRI_AOC_D_BILLING_ID_NORMAL:
3005                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3006                 break;
3007         case PRI_AOC_D_BILLING_ID_REVERSE:
3008                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3009                 break;
3010         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
3011                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3012                 break;
3013         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
3014         default:
3015                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3016                 break;
3017         }
3018
3019         switch (aoc_d->charge) {
3020         case PRI_AOC_DE_CHARGE_CURRENCY:
3021                 ast_aoc_set_currency_info(decoded,
3022                         aoc_d->recorded.money.amount.cost,
3023                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
3024                         aoc_d->recorded.money.currency);
3025                 break;
3026         case PRI_AOC_DE_CHARGE_UNITS:
3027                 {
3028                         int i;
3029                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
3030                                 /* if type or number are negative, then they are not present */
3031                                 ast_aoc_add_unit_entry(decoded,
3032                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
3033                                         aoc_d->recorded.unit.item[i].number,
3034                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
3035                                         aoc_d->recorded.unit.item[i].type);
3036                         }
3037                 }
3038                 break;
3039         }
3040
3041         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3042                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3043         }
3044
3045         ast_aoc_manager_event(decoded, owner);
3046
3047         ast_aoc_destroy_decoded(decoded);
3048         ast_aoc_destroy_encoded(encoded);
3049 }
3050 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3051
3052 #if defined(HAVE_PRI_AOC_EVENTS)
3053 /*!
3054  * \internal
3055  * \brief Generate AOC-E AST_CONTROL_AOC frame
3056  * \since 1.8
3057  *
3058  * \param aoc_e AOC-E event parameters.
3059  * \param owner Asterisk channel associated with the call.
3060  * \param passthrough indicating if this message should be queued on the ast channel
3061  *
3062  * \note Assumes the pri->lock is already obtained.
3063  * \note Assumes the sig_pri private is locked
3064  * \note Assumes the owner channel lock is already obtained.
3065  * \note owner channel may be NULL. In that case, generate event only
3066  *
3067  * \return Nothing
3068  */
3069 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
3070 {
3071         struct ast_aoc_decoded *decoded = NULL;
3072         struct ast_aoc_encoded *encoded = NULL;
3073         size_t encoded_size = 0;
3074         enum ast_aoc_charge_type type;
3075
3076         if (!aoc_e) {
3077                 return;
3078         }
3079
3080         switch (aoc_e->charge) {
3081         case PRI_AOC_DE_CHARGE_CURRENCY:
3082                 type = AST_AOC_CHARGE_CURRENCY;
3083                 break;
3084         case PRI_AOC_DE_CHARGE_UNITS:
3085                 type = AST_AOC_CHARGE_UNIT;
3086                 break;
3087         case PRI_AOC_DE_CHARGE_FREE:
3088                 type = AST_AOC_CHARGE_FREE;
3089                 break;
3090         default:
3091                 type = AST_AOC_CHARGE_NA;
3092                 break;
3093         }
3094
3095         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
3096                 return;
3097         }
3098
3099         switch (aoc_e->associated.charging_type) {
3100         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
3101                 if (!aoc_e->associated.charge.number.valid) {
3102                         break;
3103                 }
3104                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
3105                 break;
3106         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
3107                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
3108                 break;
3109         default:
3110                 break;
3111         }
3112
3113         switch (aoc_e->billing_id) {
3114         case PRI_AOC_E_BILLING_ID_NORMAL:
3115                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3116                 break;
3117         case PRI_AOC_E_BILLING_ID_REVERSE:
3118                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3119                 break;
3120         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
3121                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3122                 break;
3123         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
3124                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
3125                 break;
3126         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
3127                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
3128                 break;
3129         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
3130                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
3131                 break;
3132         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
3133                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
3134                 break;
3135         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
3136                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
3137                 break;
3138         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
3139         default:
3140                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3141                 break;
3142         }
3143
3144         switch (aoc_e->charge) {
3145         case PRI_AOC_DE_CHARGE_CURRENCY:
3146                 ast_aoc_set_currency_info(decoded,
3147                         aoc_e->recorded.money.amount.cost,
3148                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
3149                         aoc_e->recorded.money.currency);
3150                 break;
3151         case PRI_AOC_DE_CHARGE_UNITS:
3152                 {
3153                         int i;
3154                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
3155                                 /* if type or number are negative, then they are not present */
3156                                 ast_aoc_add_unit_entry(decoded,
3157                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
3158                                         aoc_e->recorded.unit.item[i].number,
3159                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
3160                                         aoc_e->recorded.unit.item[i].type);
3161                         }
3162                 }
3163         }
3164
3165         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3166                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3167         }
3168
3169         ast_aoc_manager_event(decoded, owner);
3170
3171         ast_aoc_destroy_decoded(decoded);
3172         ast_aoc_destroy_encoded(encoded);
3173 }
3174 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3175
3176 #if defined(HAVE_PRI_AOC_EVENTS)
3177 /*!
3178  * \internal
3179  * \brief send an AOC-S message on the current call
3180  *
3181  * \param pvt sig_pri private channel structure.
3182  * \param generic decoded ast AOC message
3183  *
3184  * \return Nothing
3185  *
3186  * \note Assumes that the PRI lock is already obtained.
3187  */
3188 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3189 {
3190         struct pri_subcmd_aoc_s aoc_s = { 0, };
3191         const struct ast_aoc_s_entry *entry;
3192         int idx;
3193
3194         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
3195                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
3196                         break;
3197                 }
3198
3199                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
3200
3201                 switch (entry->rate_type) {
3202                 case AST_AOC_RATE_TYPE_DURATION:
3203                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
3204                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
3205                         aoc_s.item[idx].rate.duration.amount.multiplier =
3206                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
3207                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
3208                         aoc_s.item[idx].rate.duration.time.scale =
3209                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
3210                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
3211                         aoc_s.item[idx].rate.duration.granularity.scale =
3212                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
3213                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
3214
3215                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
3216                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
3217                                         entry->rate.duration.currency_name,
3218                                         sizeof(aoc_s.item[idx].rate.duration.currency));
3219                         }
3220                         break;
3221                 case AST_AOC_RATE_TYPE_FLAT:
3222                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
3223                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
3224                         aoc_s.item[idx].rate.flat.amount.multiplier =
3225                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
3226
3227                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
3228                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
3229                                         entry->rate.flat.currency_name,
3230                                         sizeof(aoc_s.item[idx].rate.flat.currency));
3231                         }
3232                         break;
3233                 case AST_AOC_RATE_TYPE_VOLUME:
3234                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
3235                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
3236                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
3237                         aoc_s.item[idx].rate.volume.amount.multiplier =
3238                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
3239
3240                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
3241                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
3242                                         entry->rate.volume.currency_name,
3243                                         sizeof(aoc_s.item[idx].rate.volume.currency));
3244                         }
3245                         break;
3246                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
3247                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
3248                         aoc_s.item[idx].rate.special = entry->rate.special_code;
3249                         break;
3250                 case AST_AOC_RATE_TYPE_FREE:
3251                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
3252                         break;
3253                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3254                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
3255                         break;
3256                 default:
3257                 case AST_AOC_RATE_TYPE_NA:
3258                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
3259                         break;
3260                 }
3261         }
3262         aoc_s.num_items = idx;
3263
3264         /* if this rate should be sent as a response to an AOC-S request we will
3265          * have an aoc_s_request_invoke_id associated with this pvt */
3266         if (pvt->aoc_s_request_invoke_id_valid) {
3267                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
3268                 pvt->aoc_s_request_invoke_id_valid = 0;
3269         } else {
3270                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
3271         }
3272 }
3273 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3274
3275 #if defined(HAVE_PRI_AOC_EVENTS)
3276 /*!
3277  * \internal
3278  * \brief send an AOC-D message on the current call
3279  *
3280  * \param pvt sig_pri private channel structure.
3281  * \param generic decoded ast AOC message
3282  *
3283  * \return Nothing
3284  *
3285  * \note Assumes that the PRI lock is already obtained.
3286  */
3287 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3288 {
3289         struct pri_subcmd_aoc_d aoc_d = { 0, };
3290
3291         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
3292
3293         switch (ast_aoc_get_billing_id(decoded)) {
3294         case AST_AOC_BILLING_NORMAL:
3295                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
3296                 break;
3297         case AST_AOC_BILLING_REVERSE_CHARGE:
3298                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
3299                 break;
3300         case AST_AOC_BILLING_CREDIT_CARD:
3301                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
3302                 break;
3303         case AST_AOC_BILLING_NA:
3304         default:
3305                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
3306                 break;
3307         }
3308
3309         switch (ast_aoc_get_charge_type(decoded)) {
3310         case AST_AOC_CHARGE_FREE:
3311                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
3312                 break;
3313         case AST_AOC_CHARGE_CURRENCY:
3314                 {
3315                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3316                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
3317                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3318                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3319                         if (!ast_strlen_zero(currency_name)) {
3320                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
3321                         }
3322                 }
3323                 break;
3324         case AST_AOC_CHARGE_UNIT:
3325                 {
3326                         const struct ast_aoc_unit_entry *entry;
3327                         int i;
3328                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
3329                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3330                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
3331                                         if (entry->valid_amount) {
3332                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
3333                                         } else {
3334                                                 aoc_d.recorded.unit.item[i].number = -1;
3335                                         }
3336                                         if (entry->valid_type) {
3337                                                 aoc_d.recorded.unit.item[i].type = entry->type;
3338                                         } else {
3339                                                 aoc_d.recorded.unit.item[i].type = -1;
3340                                         }
3341                                         aoc_d.recorded.unit.num_items++;
3342                                 } else {
3343                                         break;
3344                                 }
3345                         }
3346                 }
3347                 break;
3348         case AST_AOC_CHARGE_NA:
3349         default:
3350                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3351                 break;
3352         }
3353
3354         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
3355 }
3356 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3357
3358 #if defined(HAVE_PRI_AOC_EVENTS)
3359 /*!
3360  * \internal
3361  * \brief send an AOC-E message on the current call
3362  *
3363  * \param pvt sig_pri private channel structure.
3364  * \param generic decoded ast AOC message
3365  *
3366  * \return Nothing
3367  *
3368  * \note Assumes that the PRI lock is already obtained.
3369  */
3370 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3371 {
3372         struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
3373         const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
3374
3375         memset(aoc_e, 0, sizeof(*aoc_e));
3376         pvt->holding_aoce = 1;
3377
3378         switch (ca->charging_type) {
3379         case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
3380                 aoc_e->associated.charge.number.valid = 1;
3381                 ast_copy_string(aoc_e->associated.charge.number.str,
3382                         ca->charge.number.number,
3383                         sizeof(aoc_e->associated.charge.number.str));
3384                 aoc_e->associated.charge.number.plan = ca->charge.number.plan;
3385                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
3386                 break;
3387         case AST_AOC_CHARGING_ASSOCIATION_ID:
3388                 aoc_e->associated.charge.id = ca->charge.id;
3389                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
3390                 break;
3391         case AST_AOC_CHARGING_ASSOCIATION_NA:
3392         default:
3393                 break;
3394         }
3395
3396         switch (ast_aoc_get_billing_id(decoded)) {
3397         case AST_AOC_BILLING_NORMAL:
3398                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
3399                 break;
3400         case AST_AOC_BILLING_REVERSE_CHARGE:
3401                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
3402                 break;
3403         case AST_AOC_BILLING_CREDIT_CARD:
3404                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
3405                 break;
3406         case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
3407                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
3408                 break;
3409         case AST_AOC_BILLING_CALL_FWD_BUSY:
3410                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
3411                 break;
3412         case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
3413                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
3414                 break;
3415         case AST_AOC_BILLING_CALL_DEFLECTION:
3416                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
3417                 break;
3418         case AST_AOC_BILLING_CALL_TRANSFER:
3419                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
3420                 break;
3421         case AST_AOC_BILLING_NA:
3422         default:
3423                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
3424                 break;
3425         }
3426
3427         switch (ast_aoc_get_charge_type(decoded)) {
3428         case AST_AOC_CHARGE_FREE:
3429                 aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
3430                 break;
3431         case AST_AOC_CHARGE_CURRENCY:
3432                 {
3433                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3434                         aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
3435                         aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3436                         aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3437                         if (!ast_strlen_zero(currency_name)) {
3438                                 ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
3439                         }
3440                 }
3441                 break;
3442         case AST_AOC_CHARGE_UNIT:
3443                 {
3444                         const struct ast_aoc_unit_entry *entry;
3445                         int i;
3446                         aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
3447                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3448                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
3449                                         if (entry->valid_amount) {
3450                                                 aoc_e->recorded.unit.item[i].number = entry->amount;
3451                                         } else {
3452                                                 aoc_e->recorded.unit.item[i].number = -1;
3453                                         }
3454                                         if (entry->valid_type) {
3455                                                 aoc_e->recorded.unit.item[i].type = entry->type;
3456                                         } else {
3457                                                 aoc_e->recorded.unit.item[i].type = -1;
3458                                         }
3459                                         aoc_e->recorded.unit.num_items++;
3460                                 }
3461                         }
3462                 }
3463                 break;
3464         case AST_AOC_CHARGE_NA:
3465         default:
3466                 aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3467                 break;
3468         }
3469 }
3470 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3471
3472 #if defined(HAVE_PRI_AOC_EVENTS)
3473 /*!
3474  * \internal
3475  * \brief send an AOC-E termination request on ast_channel and set
3476  * hangup delay.
3477  *
3478  * \param pri PRI span control structure.
3479  * \param chanpos Channel position in the span.
3480  * \param ms to delay hangup
3481  *
3482  * \note Assumes the pri->lock is already obtained.
3483  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
3484  *
3485  * \return Nothing
3486  */
3487 static void sig_pri_send_aoce_termination_request(struct sig_pri_span *pri, int chanpos, unsigned int ms)
3488 {
3489         struct sig_pri_chan *pvt;
3490         struct ast_aoc_decoded *decoded = NULL;
3491         struct ast_aoc_encoded *encoded = NULL;
3492         size_t encoded_size;
3493         struct timeval whentohangup = { 0, };
3494
3495         sig_pri_lock_owner(pri, chanpos);
3496         pvt = pri->pvts[chanpos];
3497         if (!pvt->owner) {
3498                 return;
3499         }
3500
3501         if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
3502                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3503                 goto cleanup_termination_request;
3504         }
3505
3506         ast_aoc_set_termination_request(decoded);
3507
3508         if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
3509                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3510                 goto cleanup_termination_request;
3511         }
3512
3513         /* convert ms to timeval */
3514         whentohangup.tv_usec = (ms % 1000) * 1000;
3515         whentohangup.tv_sec = ms / 1000;
3516
3517         if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
3518                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3519                 goto cleanup_termination_request;
3520         }
3521
3522         pvt->waiting_for_aoce = 1;
3523         ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
3524         ast_debug(1, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
3525
3526 cleanup_termination_request:
3527         ast_channel_unlock(pvt->owner);
3528         ast_aoc_destroy_decoded(decoded);
3529         ast_aoc_destroy_encoded(encoded);
3530 }
3531 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3532
3533 /*!
3534  * \internal
3535  * \brief TRUE if PRI event came in on a CIS call.
3536  * \since 1.8
3537  *
3538  * \param channel PRI encoded span/channel
3539  *
3540  * \retval non-zero if CIS call.
3541  */
3542 static int sig_pri_is_cis_call(int channel)
3543 {
3544         return channel != -1 && (channel & PRI_CIS_CALL);
3545 }
3546
3547 /*!
3548  * \internal
3549  * \brief Handle the CIS associated PRI subcommand events.
3550  * \since 1.8
3551  *
3552  * \param pri PRI span control structure.
3553  * \param event_id PRI event id
3554  * \param subcmds Subcommands to process if any. (Could be NULL).
3555  * \param call_rsp libpri opaque call structure to send any responses toward.
3556  * Could be NULL either because it is not available or the call is for the
3557  * dummy call reference.  However, this should not be NULL in the cases that
3558  * need to use the pointer to send a response message back.
3559  *
3560  * \note Assumes the pri->lock is already obtained.
3561  *
3562  * \return Nothing
3563  */
3564 static void sig_pri_handle_cis_subcmds(struct sig_pri_span *pri, int event_id,
3565         const struct pri_subcommands *subcmds, q931_call *call_rsp)
3566 {
3567         int index;
3568 #if defined(HAVE_PRI_CCSS)
3569         struct ast_cc_agent *agent;
3570         struct sig_pri_cc_agent_prv *agent_prv;
3571         struct sig_pri_cc_monitor_instance *monitor;
3572 #endif  /* defined(HAVE_PRI_CCSS) */
3573
3574         if (!subcmds) {
3575                 return;
3576         }
3577         for (index = 0; index < subcmds->counter_subcmd; ++index) {
3578                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
3579
3580                 switch (subcmd->cmd) {
3581 #if defined(STATUS_REQUEST_PLACE_HOLDER)
3582                 case PRI_SUBCMD_STATUS_REQ:
3583                 case PRI_SUBCMD_STATUS_REQ_RSP:
3584                         /* Ignore for now. */
3585                         break;
3586 #endif  /* defined(STATUS_REQUEST_PLACE_HOLDER) */
3587 #if defined(HAVE_PRI_CCSS)
3588                 case PRI_SUBCMD_CC_REQ:
3589                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
3590                         if (!agent) {
3591                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3592                                 break;
3593                         }
3594                         if (!ast_cc_request_is_within_limits()) {
3595                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3596                                         5/* queue_full */)) {
3597                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3598                                 }
3599                                 ast_cc_failed(agent->core_id, "%s agent system CC queue full",
3600                                         sig_pri_cc_type_name);
3601                                 ao2_ref(agent, -1);
3602                                 break;
3603                         }
3604                         agent_prv = agent->private_data;
3605                         agent_prv->cc_request_response_pending = 1;
3606                         if (ast_cc_agent_accept_request(agent->core_id,
3607                                 "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
3608                                 agent_prv->cc_request_response_pending = 0;
3609                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
3610                                         2/* short_term_denial */)) {
3611                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
3612                                 }
3613                                 ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
3614                                         sig_pri_cc_type_name);
3615                         }
3616                         ao2_ref(agent, -1);
3617                         break;
3618 #endif  /* defined(HAVE_PRI_CCSS) */
3619 #if defined(HAVE_PRI_CCSS)
3620                 case PRI_SUBCMD_CC_REQ_RSP:
3621                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3622                                 subcmd->u.cc_request_rsp.cc_id);
3623                         if (!monitor) {
3624                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
3625                                 break;
3626                         }
3627                         switch (subcmd->u.cc_request_rsp.status) {
3628                         case 0:/* success */
3629                                 ast_cc_monitor_request_acked(monitor->core_id,
3630                                         "%s far end accepted CC request", sig_pri_cc_type_name);
3631                                 break;
3632                         case 1:/* timeout */
3633                                 ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
3634                                         sig_pri_cc_type_name);
3635                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3636                                         "%s CC request timeout", sig_pri_cc_type_name);
3637                                 break;
3638                         case 2:/* error */
3639                                 ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
3640                                         sig_pri_cc_type_name,
3641                                         pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
3642                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3643                                         "%s CC request error", sig_pri_cc_type_name);
3644                                 break;
3645                         case 3:/* reject */
3646                                 ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
3647                                         sig_pri_cc_type_name,
3648                                         pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
3649                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3650                                         "%s CC request reject", sig_pri_cc_type_name);
3651                                 break;
3652                         default:
3653                                 ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
3654                                         monitor->core_id, sig_pri_cc_type_name,
3655                                         subcmd->u.cc_request_rsp.status);
3656                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3657                                         "%s CC request unknown status", sig_pri_cc_type_name);
3658                                 break;
3659                         }
3660                         ao2_ref(monitor, -1);
3661                         break;
3662 #endif  /* defined(HAVE_PRI_CCSS) */
3663 #if defined(HAVE_PRI_CCSS)
3664                 case PRI_SUBCMD_CC_REMOTE_USER_FREE:
3665                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3666                                 subcmd->u.cc_remote_user_free.cc_id);
3667                         if (!monitor) {
3668                                 pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
3669                                 break;
3670                         }
3671                         ast_cc_monitor_callee_available(monitor->core_id,
3672                                 "%s callee has become available", sig_pri_cc_type_name);
3673                         ao2_ref(monitor, -1);
3674                         break;
3675 #endif  /* defined(HAVE_PRI_CCSS) */
3676 #if defined(HAVE_PRI_CCSS)
3677                 case PRI_SUBCMD_CC_B_FREE:
3678                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3679                                 subcmd->u.cc_b_free.cc_id);
3680                         if (!monitor) {
3681                                 pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
3682                                 break;
3683                         }
3684                         ast_cc_monitor_party_b_free(monitor->core_id);
3685                         ao2_ref(monitor, -1);
3686                         break;
3687 #endif  /* defined(HAVE_PRI_CCSS) */
3688 #if defined(HAVE_PRI_CCSS)
3689                 case PRI_SUBCMD_CC_STATUS_REQ:
3690                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3691                                 subcmd->u.cc_status_req.cc_id);
3692                         if (!monitor) {
3693                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
3694                                 break;
3695                         }
3696                         ast_cc_monitor_status_request(monitor->core_id);
3697                         ao2_ref(monitor, -1);
3698                         break;
3699 #endif  /* defined(HAVE_PRI_CCSS) */
3700 #if defined(HAVE_PRI_CCSS)
3701                 case PRI_SUBCMD_CC_STATUS_REQ_RSP:
3702                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
3703                         if (!agent) {
3704                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
3705                                 break;
3706                         }
3707                         ast_cc_agent_status_response(agent->core_id,
3708                                 subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
3709                                 : AST_DEVICE_NOT_INUSE);
3710                         ao2_ref(agent, -1);
3711                         break;
3712 #endif  /* defined(HAVE_PRI_CCSS) */
3713 #if defined(HAVE_PRI_CCSS)
3714                 case PRI_SUBCMD_CC_STATUS:
3715                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
3716                         if (!agent) {
3717                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
3718                                 break;
3719                         }
3720                         if (subcmd->u.cc_status.status) {
3721                                 ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
3722                                         sig_pri_cc_type_name);
3723                         } else {
3724                                 ast_cc_agent_caller_available(agent->core_id,
3725                                         "%s agent caller is available", sig_pri_cc_type_name);
3726                         }
3727                         ao2_ref(agent, -1);
3728                         break;
3729 #endif  /* defined(HAVE_PRI_CCSS) */
3730 #if defined(HAVE_PRI_CCSS)
3731                 case PRI_SUBCMD_CC_CANCEL:
3732                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
3733                                 subcmd->u.cc_cancel.is_agent);
3734                         break;
3735 #endif  /* defined(HAVE_PRI_CCSS) */
3736 #if defined(HAVE_PRI_CCSS)
3737                 case PRI_SUBCMD_CC_STOP_ALERTING:
3738                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
3739                                 subcmd->u.cc_stop_alerting.cc_id);
3740                         if (!monitor) {
3741                                 pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
3742                                 break;
3743                         }
3744                         ast_cc_monitor_stop_ringing(monitor->core_id);
3745                         ao2_ref(monitor, -1);
3746                         break;
3747 #endif  /* defined(HAVE_PRI_CCSS) */
3748 #if defined(HAVE_PRI_AOC_EVENTS)
3749                 case PRI_SUBCMD_AOC_E:
3750                         /* Queue AST_CONTROL_AOC frame */
3751                         sig_pri_aoc_e_from_pri(&subcmd->u.aoc_e, NULL, 0);
3752                         break;
3753 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3754                 default:
3755                         ast_debug(2,
3756                                 "Unknown CIS subcommand(%d) in %s event on span %d.\n",
3757                                 subcmd->cmd, pri_event2str(event_id), pri->span);
3758                         break;
3759                 }
3760         }
3761 }
3762
3763 #if defined(HAVE_PRI_AOC_EVENTS)
3764 /*!
3765  * \internal
3766  * \brief detect if AOC-S subcmd is present.
3767  * \since 1.8
3768  *
3769  * \param subcmds Subcommands to process if any. (Could be NULL).
3770  *
3771  * \note Knowing whether or not an AOC-E subcmd is present on certain
3772  * PRI hangup events is necessary to determine what method to use to hangup
3773  * the ast_channel.  If an AOC-E subcmd just came in, then a new AOC-E was queued
3774  * on the ast_channel.  If a soft hangup is used, the AOC-E msg will never make it
3775  * across the bridge, but if a AST_CONTROL_HANGUP frame is queued behind it
3776  * we can ensure the AOC-E frame makes it to it's destination before the hangup
3777  * frame is read.
3778  *
3779  *
3780  * \retval 0 AOC-E is not present in subcmd list
3781  * \retval 1 AOC-E is present in subcmd list
3782  */
3783 static int detect_aoc_e_subcmd(const struct pri_subcommands *subcmds)
3784 {
3785         int i;
3786
3787         if (!subcmds) {
3788                 return 0;
3789         }
3790         for (i = 0; i < subcmds->counter_subcmd; ++i) {
3791                 const struct pri_subcommand *subcmd = &subcmds->subcmd[i];
3792                 if (subcmd->cmd == PRI_SUBCMD_AOC_E) {
3793                         return 1;
3794                 }
3795         }
3796         return 0;
3797 }
3798 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */