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