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