Merged revisions 294823 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 static int pri_find_principle(struct sig_pri_span *pri, int channel, q931_call *call)
1082 {
1083         int x;
1084         int span;
1085         int principle;
1086         int prioffset;
1087
1088         if (channel < 0) {
1089                 /* Channel is not picked yet. */
1090                 return -1;
1091         }
1092
1093         prioffset = PRI_CHANNEL(channel);
1094         if (!prioffset || (channel & PRI_HELD_CALL)) {
1095                 if (!call) {
1096                         /* Cannot find a call waiting call or held call without a call. */
1097                         return -1;
1098                 }
1099                 principle = -1;
1100                 for (x = 0; x < pri->numchans; ++x) {
1101                         if (pri->pvts[x]
1102                                 && pri->pvts[x]->call == call) {
1103                                 principle = x;
1104                                 break;
1105                         }
1106                 }
1107                 return principle;
1108         }
1109
1110         span = PRI_SPAN(channel);
1111         if (!(channel & PRI_EXPLICIT)) {
1112                 int index;
1113
1114                 index = pri_active_dchan_index(pri);
1115                 if (index == -1) {
1116                         return -1;
1117                 }
1118                 span = pri->dchan_logical_span[index];
1119         }
1120
1121         principle = -1;
1122         for (x = 0; x < pri->numchans; x++) {
1123                 if (pri->pvts[x]
1124                         && pri->pvts[x]->prioffset == prioffset
1125                         && pri->pvts[x]->logicalspan == span
1126                         && !pri->pvts[x]->no_b_channel) {
1127                         principle = x;
1128                         break;
1129                 }
1130         }
1131
1132         return principle;
1133 }
1134
1135 static int pri_fixup_principle(struct sig_pri_span *pri, int principle, q931_call *call)
1136 {
1137         int x;
1138
1139         if (principle < 0 || pri->numchans <= principle) {
1140                 /* Out of rannge */
1141                 return -1;
1142         }
1143         if (!call) {
1144                 /* No call */
1145                 return principle;
1146         }
1147         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
1148                 /* Call is already on the specified principle. */
1149                 return principle;
1150         }
1151
1152         /* Find the old principle location. */
1153         for (x = 0; x < pri->numchans; x++) {
1154                 struct sig_pri_chan *new_chan;
1155                 struct sig_pri_chan *old_chan;
1156
1157                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
1158                         continue;
1159                 }
1160
1161                 /* Found our call */
1162                 new_chan = pri->pvts[principle];
1163                 old_chan = pri->pvts[x];
1164
1165                 ast_verb(3, "Moving call from channel %d to channel %d\n",
1166                         old_chan->channel, new_chan->channel);
1167                 if (new_chan->owner) {
1168                         ast_log(LOG_WARNING,
1169                                 "Can't fix up channel from %d to %d because %d is already in use\n",
1170                                 old_chan->channel, new_chan->channel, new_chan->channel);
1171                         return -1;
1172                 }
1173
1174                 sig_pri_fixup_chans(old_chan, new_chan);
1175
1176                 /* Fix it all up now */
1177                 new_chan->owner = old_chan->owner;
1178                 old_chan->owner = NULL;
1179
1180                 new_chan->call = old_chan->call;
1181                 old_chan->call = NULL;
1182
1183                 /* Transfer flags from the old channel. */
1184 #if defined(HAVE_PRI_AOC_EVENTS)
1185                 new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
1186                 new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
1187                 new_chan->holding_aoce = old_chan->holding_aoce;
1188 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1189                 new_chan->alerting = old_chan->alerting;
1190                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1191                 new_chan->isidlecall = old_chan->isidlecall;
1192                 new_chan->proceeding = old_chan->proceeding;
1193                 new_chan->progress = old_chan->progress;
1194                 new_chan->setup_ack = old_chan->setup_ack;
1195                 new_chan->outgoing = old_chan->outgoing;
1196                 new_chan->digital = old_chan->digital;
1197 #if defined(HAVE_PRI_CALL_WAITING)
1198                 new_chan->is_call_waiting = old_chan->is_call_waiting;
1199 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1200
1201 #if defined(HAVE_PRI_AOC_EVENTS)
1202                 old_chan->aoc_s_request_invoke_id_valid = 0;
1203                 old_chan->waiting_for_aoce = 0;
1204                 old_chan->holding_aoce = 0;
1205 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1206                 old_chan->alerting = 0;
1207                 old_chan->alreadyhungup = 0;
1208                 old_chan->isidlecall = 0;
1209                 old_chan->proceeding = 0;
1210                 old_chan->progress = 0;
1211                 old_chan->setup_ack = 0;
1212                 old_chan->outgoing = 0;
1213                 old_chan->digital = 0;
1214 #if defined(HAVE_PRI_CALL_WAITING)
1215                 old_chan->is_call_waiting = 0;
1216 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1217
1218                 /* More stuff to transfer to the new channel. */
1219 #if defined(HAVE_PRI_REVERSE_CHARGE)
1220                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1221 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1222 #if defined(HAVE_PRI_SETUP_KEYPAD)
1223                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1224 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1225 #if defined(HAVE_PRI_AOC_EVENTS)
1226                 new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
1227                 new_chan->aoc_e = old_chan->aoc_e;
1228 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1229                 strcpy(new_chan->user_tag, old_chan->user_tag);
1230
1231                 if (new_chan->no_b_channel) {
1232                         /* Copy the real channel configuration to the no B channel interface. */
1233                         new_chan->hidecallerid = old_chan->hidecallerid;
1234                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1235                         new_chan->immediate = old_chan->immediate;
1236                         new_chan->priexclusive = old_chan->priexclusive;
1237                         new_chan->priindication_oob = old_chan->priindication_oob;
1238                         new_chan->use_callerid = old_chan->use_callerid;
1239                         new_chan->use_callingpres = old_chan->use_callingpres;
1240                         new_chan->stripmsd = old_chan->stripmsd;
1241                         strcpy(new_chan->context, old_chan->context);
1242                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1243
1244                         /* Become a member of the old channel span/trunk-group. */
1245                         new_chan->logicalspan = old_chan->logicalspan;
1246                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1247                 }
1248
1249                 return principle;
1250         }
1251         ast_verb(3, "Call specified, but not found.\n");
1252         return -1;
1253 }
1254
1255 static char * redirectingreason2str(int redirectingreason)
1256 {
1257         switch (redirectingreason) {
1258         case 0:
1259                 return "UNKNOWN";
1260         case 1:
1261                 return "BUSY";
1262         case 2:
1263                 return "NO_REPLY";
1264         case 0xF:
1265                 return "UNCONDITIONAL";
1266         default:
1267                 return "NOREDIRECT";
1268         }
1269 }
1270
1271 static char *dialplan2str(int dialplan)
1272 {
1273         if (dialplan == -1) {
1274                 return("Dynamically set dialplan in ISDN");
1275         }
1276         return (pri_plan2str(dialplan));
1277 }
1278
1279 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, const int plan)
1280 {
1281         switch (plan) {
1282         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1283                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1284                 break;
1285         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1286                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1287                 break;
1288         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1289                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1290                 break;
1291         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1292                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1293                 break;
1294         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1295                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1296                 break;
1297         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1298                 snprintf(buf, size, "%s", number);
1299                 break;
1300         }
1301 }
1302
1303 /*! \note Assumes the pri->lock is already obtained. */
1304 static int pri_check_restart(struct sig_pri_span *pri)
1305 {
1306 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1307 tryanotherpos:
1308 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1309         do {
1310                 pri->resetpos++;
1311         } while (pri->resetpos < pri->numchans
1312                 && (!pri->pvts[pri->resetpos]
1313                         || pri->pvts[pri->resetpos]->no_b_channel
1314                         || pri->pvts[pri->resetpos]->call
1315                         || pri->pvts[pri->resetpos]->resetting));
1316         if (pri->resetpos < pri->numchans) {
1317 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1318                 unsigned why;
1319
1320                 why = pri->pvts[pri->resetpos]->service_status;
1321                 if (why) {
1322                         ast_log(LOG_NOTICE, "span '%d' channel '%d' out-of-service (reason: %s), not sending RESTART\n", pri->span,
1323                                 pri->pvts[pri->resetpos]->channel, (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1324                         goto tryanotherpos;
1325                 }
1326 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1327
1328                 /* Mark the channel as resetting and restart it */
1329                 pri->pvts[pri->resetpos]->resetting = 1;
1330                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1331         } else {
1332                 pri->resetting = 0;
1333                 time(&pri->lastreset);
1334         }
1335         return 0;
1336 }
1337
1338 #if defined(HAVE_PRI_CALL_WAITING)
1339 /*!
1340  * \internal
1341  * \brief Init the private channel configuration using the span controller.
1342  * \since 1.8
1343  *
1344  * \param pvt Channel to init the configuration.
1345  * \param pri sig_pri PRI control structure.
1346  *
1347  * \note Assumes the pri->lock is already obtained.
1348  *
1349  * \return Nothing
1350  */
1351 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_span *pri)
1352 {
1353         pvt->stripmsd = pri->ch_cfg.stripmsd;
1354         pvt->hidecallerid = pri->ch_cfg.hidecallerid;
1355         pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
1356         pvt->immediate = pri->ch_cfg.immediate;
1357         pvt->priexclusive = pri->ch_cfg.priexclusive;
1358         pvt->priindication_oob = pri->ch_cfg.priindication_oob;
1359         pvt->use_callerid = pri->ch_cfg.use_callerid;
1360         pvt->use_callingpres = pri->ch_cfg.use_callingpres;
1361         ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
1362         ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
1363
1364         if (pri->calls->init_config) {
1365                 pri->calls->init_config(pvt->chan_pvt, pri);
1366         }
1367 }
1368 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1369
1370 static int pri_find_empty_chan(struct sig_pri_span *pri, int backwards)
1371 {
1372         int x;
1373         if (backwards)
1374                 x = pri->numchans;
1375         else
1376                 x = 0;
1377         for (;;) {
1378                 if (backwards && (x < 0))
1379                         break;
1380                 if (!backwards && (x >= pri->numchans))
1381                         break;
1382                 if (pri->pvts[x]
1383                         && !pri->pvts[x]->no_b_channel
1384                         && !pri->pvts[x]->inalarm
1385                         && !pri->pvts[x]->owner) {
1386                         ast_debug(1, "Found empty available channel %d/%d\n",
1387                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1388                         return x;
1389                 }
1390                 if (backwards)
1391                         x--;
1392                 else
1393                         x++;
1394         }
1395         return -1;
1396 }
1397
1398 #if defined(HAVE_PRI_CALL_HOLD)
1399 /*!
1400  * \internal
1401  * \brief Find or create an empty no-B-channel interface to use.
1402  * \since 1.8
1403  *
1404  * \param pri sig_pri span controller to find interface.
1405  *
1406  * \note Assumes the pri->lock is already obtained.
1407  *
1408  * \retval array-index into private pointer array on success.
1409  * \retval -1 on error.
1410  */
1411 static int pri_find_empty_nobch(struct sig_pri_span *pri)
1412 {
1413         int idx;
1414
1415         for (idx = 0; idx < pri->numchans; ++idx) {
1416                 if (pri->pvts[idx]
1417                         && pri->pvts[idx]->no_b_channel
1418                         && !pri->pvts[idx]->inalarm
1419                         && !pri->pvts[idx]->owner) {
1420                         ast_debug(1, "Found empty available no B channel interface\n");
1421                         return idx;
1422                 }
1423         }
1424
1425         /* Need to create a new interface. */
1426         if (pri->calls->new_nobch_intf) {
1427                 idx = pri->calls->new_nobch_intf(pri);
1428         } else {
1429                 idx = -1;
1430         }
1431         return idx;
1432 }
1433 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1434
1435 #if defined(HAVE_PRI_CALL_HOLD)
1436 /*!
1437  * \internal
1438  * \brief Find the channel associated with the libpri call.
1439  * \since 1.8
1440  *
1441  * \param pri sig_pri span controller to find interface.
1442  * \param call LibPRI opaque call pointer to find.
1443  *
1444  * \note Assumes the pri->lock is already obtained.
1445  *
1446  * \retval array-index into private pointer array on success.
1447  * \retval -1 on error.
1448  */
1449 static int pri_find_pri_call(struct sig_pri_span *pri, q931_call *call)
1450 {
1451         int idx;
1452
1453         for (idx = 0; idx < pri->numchans; ++idx) {
1454                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1455                         /* Found the channel */
1456                         return idx;
1457                 }
1458         }
1459         return -1;
1460 }
1461 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
1462
1463 static void *do_idle_thread(void *v_pvt)
1464 {
1465         struct sig_pri_chan *pvt = v_pvt;
1466         struct ast_channel *chan = pvt->owner;
1467         struct ast_frame *f;
1468         char ex[80];
1469         /* Wait up to 30 seconds for an answer */
1470         int newms, ms = 30000;
1471
1472         ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
1473         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
1474         if (ast_call(chan, ex, 0)) {
1475                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
1476                 ast_hangup(chan);
1477                 return NULL;
1478         }
1479         while ((newms = ast_waitfor(chan, ms)) > 0) {
1480                 f = ast_read(chan);
1481                 if (!f) {
1482                         /* Got hangup */
1483                         break;
1484                 }
1485                 if (f->frametype == AST_FRAME_CONTROL) {
1486                         switch (f->subclass.integer) {
1487                         case AST_CONTROL_ANSWER:
1488                                 /* Launch the PBX */
1489                                 ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
1490                                 ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
1491                                 chan->priority = 1;
1492                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
1493                                 ast_pbx_run(chan);
1494                                 /* It's already hungup, return immediately */
1495                                 return NULL;
1496                         case AST_CONTROL_BUSY:
1497                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
1498                                 break;
1499                         case AST_CONTROL_CONGESTION:
1500                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
1501                                 break;
1502                         };
1503                 }
1504                 ast_frfree(f);
1505                 ms = newms;
1506         }
1507         /* Hangup the channel since nothing happend */
1508         ast_hangup(chan);
1509         return NULL;
1510 }
1511
1512 static void *pri_ss_thread(void *data)
1513 {
1514         struct sig_pri_chan *p = data;
1515         struct ast_channel *chan = p->owner;
1516         char exten[AST_MAX_EXTENSION];
1517         int res;
1518         int len;
1519         int timeout;
1520
1521         if (!chan) {
1522                 /* We lost the owner before we could get started. */
1523                 return NULL;
1524         }
1525
1526         /*
1527          * In the bizarre case where the channel has become a zombie before we
1528          * even get started here, abort safely.
1529          */
1530         if (!chan->tech_pvt) {
1531                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
1532                 ast_hangup(chan);
1533                 return NULL;
1534         }
1535
1536         ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
1537
1538         sig_pri_dsp_reset_and_flush_digits(p);
1539
1540         /* Now loop looking for an extension */
1541         ast_copy_string(exten, p->exten, sizeof(exten));
1542         len = strlen(exten);
1543         res = 0;
1544         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
1545                 if (len && !ast_ignore_pattern(chan->context, exten))
1546                         sig_pri_play_tone(p, -1);
1547                 else
1548                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
1549                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
1550                         timeout = pri_matchdigittimeout;
1551                 else
1552                         timeout = pri_gendigittimeout;
1553                 res = ast_waitfordigit(chan, timeout);
1554                 if (res < 0) {
1555                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
1556                         ast_hangup(chan);
1557                         return NULL;
1558                 } else if (res) {
1559                         exten[len++] = res;
1560                         exten[len] = '\0';
1561                 } else
1562                         break;
1563         }
1564         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
1565         if (ast_strlen_zero(exten)) {
1566                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
1567                 exten[0] = 's';
1568                 exten[1] = '\0';
1569         } else {
1570                 ast_free(chan->dialed.number.str);
1571                 chan->dialed.number.str = ast_strdup(exten);
1572
1573                 if (p->pri->append_msn_to_user_tag && p->pri->nodetype != PRI_NETWORK) {
1574                         /*
1575                          * Update the user tag for party id's from this device for this call
1576                          * now that we have a complete MSN from the network.
1577                          */
1578                         snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
1579                                 exten);
1580                         ast_free(chan->caller.id.tag);
1581                         chan->caller.id.tag = ast_strdup(p->user_tag);
1582                 }
1583         }
1584         sig_pri_play_tone(p, -1);
1585         if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
1586                 /* Start the real PBX */
1587                 ast_copy_string(chan->exten, exten, sizeof(chan->exten));
1588                 sig_pri_dsp_reset_and_flush_digits(p);
1589                 if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
1590                         sig_pri_lock_private(p);
1591                         if (p->pri->pri) {              
1592                                 if (!pri_grab(p, p->pri)) {
1593                                         pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
1594                                         p->proceeding = 1;
1595                                         pri_rel(p->pri);
1596                                 } else {
1597                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->pri->span);
1598                                 }
1599                         }
1600                         sig_pri_unlock_private(p);
1601                 }
1602
1603                 sig_pri_set_echocanceller(p, 1);
1604                 ast_setstate(chan, AST_STATE_RING);
1605                 res = ast_pbx_run(chan);
1606                 if (res) {
1607                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
1608                 }
1609         } else {
1610                 ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
1611                 chan->hangupcause = AST_CAUSE_UNALLOCATED;
1612                 ast_hangup(chan);
1613                 p->exten[0] = '\0';
1614                 /* Since we send release complete here, we won't get one */
1615                 p->call = NULL;
1616         }
1617         return NULL;
1618 }
1619
1620 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
1621 {
1622         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
1623         if (!before_start_pri)
1624                 pri_find_dchan(pri);
1625 }
1626
1627 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
1628 {
1629         pri->dchanavail[index] |= DCHAN_NOTINALARM;
1630         if (!before_start_pri)
1631                 pri_restart(pri->dchans[index]);
1632 }
1633
1634 /*!
1635  * \internal
1636  * \brief Convert libpri party name into asterisk party name.
1637  * \since 1.8
1638  *
1639  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
1640  * \param pri_name libpri party name structure containing source information.
1641  *
1642  * \note The filled in ast_name structure needs to be destroyed by
1643  * ast_party_name_free() when it is no longer needed.
1644  *
1645  * \return Nothing
1646  */
1647 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
1648 {
1649         ast_name->str = ast_strdup(pri_name->str);
1650         ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
1651         ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
1652         ast_name->valid = 1;
1653 }
1654
1655 /*!
1656  * \internal
1657  * \brief Convert libpri party number into asterisk party number.
1658  * \since 1.8
1659  *
1660  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
1661  * \param pri_number libpri party number structure containing source information.
1662  * \param pri Span controlling structure.
1663  *
1664  * \note The filled in ast_number structure needs to be destroyed by
1665  * ast_party_number_free() when it is no longer needed.
1666  *
1667  * \return Nothing
1668  */
1669 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)
1670 {
1671         char number[AST_MAX_EXTENSION];
1672
1673         apply_plan_to_number(number, sizeof(number), pri, pri_number->str, pri_number->plan);
1674         ast_number->str = ast_strdup(number);
1675         ast_number->plan = pri_number->plan;
1676         ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
1677         ast_number->valid = 1;
1678 }
1679
1680 /*!
1681  * \internal
1682  * \brief Convert libpri party id into asterisk party id.
1683  * \since 1.8
1684  *
1685  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
1686  * \param pri_id libpri party id structure containing source information.
1687  * \param pri Span controlling structure.
1688  *
1689  * \note The filled in ast_id structure needs to be destroyed by
1690  * ast_party_id_free() when it is no longer needed.
1691  *
1692  * \return Nothing
1693  */
1694 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)
1695 {
1696         if (pri_id->name.valid) {
1697                 sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
1698         }
1699         if (pri_id->number.valid) {
1700                 sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
1701         }
1702 #if defined(HAVE_PRI_SUBADDR)
1703         if (pri_id->subaddress.valid) {
1704                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
1705         }
1706 #endif  /* defined(HAVE_PRI_SUBADDR) */
1707 }
1708
1709 /*!
1710  * \internal
1711  * \brief Convert libpri redirecting information into asterisk redirecting information.
1712  * \since 1.8
1713  *
1714  * \param ast_redirecting Asterisk redirecting structure to fill.
1715  * \param pri_redirecting libpri redirecting structure containing source information.
1716  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
1717  * \param pri Span controlling structure.
1718  *
1719  * \note The filled in ast_redirecting structure needs to be destroyed by
1720  * ast_party_redirecting_free() when it is no longer needed.
1721  *
1722  * \return Nothing
1723  */
1724 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
1725         const struct pri_party_redirecting *pri_redirecting,
1726         const struct ast_party_redirecting *ast_guide,
1727         struct sig_pri_span *pri)
1728 {
1729         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
1730
1731         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
1732         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
1733         ast_redirecting->count = pri_redirecting->count;
1734         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
1735 }
1736
1737 /*!
1738  * \internal
1739  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
1740  * \since 1.8
1741  *
1742  * \param msn_patterns Comma separated list of MSN patterns to match.
1743  * \param exten Extension to match in the MSN list.
1744  *
1745  * \retval 1 if matches.
1746  * \retval 0 if no match.
1747  */
1748 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
1749 {
1750         char *pattern;
1751         char *msn_list;
1752         char *list_tail;
1753
1754         msn_list = ast_strdupa(msn_patterns);
1755
1756         list_tail = NULL;
1757         pattern = strtok_r(msn_list, ",", &list_tail);
1758         while (pattern) {
1759                 pattern = ast_strip(pattern);
1760                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
1761                         /* Extension matched the pattern. */
1762                         return 1;
1763                 }
1764                 pattern = strtok_r(NULL, ",", &list_tail);
1765         }
1766         /* Did not match any pattern in the list. */
1767         return 0;
1768 }
1769
1770 #if defined(HAVE_PRI_MCID)
1771 /*!
1772  * \internal
1773  * \brief Append the given party id to the event string.
1774  * \since 1.8
1775  *
1776  * \param msg Event message string being built.
1777  * \param prefix Prefix to add to the party id lines.
1778  * \param party Party information to encode.
1779  *
1780  * \return Nothing
1781  */
1782 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
1783 {
1784         int pres;
1785
1786         /* Combined party presentation */
1787         pres = ast_party_id_presentation(party);
1788         ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix, pres,
1789                 ast_describe_caller_presentation(pres));
1790
1791         /* Party number */
1792         ast_str_append(msg, 0, "%sNumValid: %d\r\n", prefix,
1793                 (unsigned) party->number.valid);
1794         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix,
1795                 S_COR(party->number.valid, party->number.str, ""));
1796         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number.plan);
1797         if (party->number.valid) {
1798                 ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, party->number.plan);
1799                 ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix,
1800                         party->number.presentation,
1801                         ast_describe_caller_presentation(party->number.presentation));
1802         }
1803
1804         /* Party name */
1805         ast_str_append(msg, 0, "%sNameValid: %d\r\n", prefix,
1806                 (unsigned) party->name.valid);
1807         ast_str_append(msg, 0, "%sName: %s\r\n", prefix,
1808                 S_COR(party->name.valid, party->name.str, ""));
1809         if (party->name.valid) {
1810                 ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix,
1811                         ast_party_name_charset_describe(party->name.char_set));
1812                 ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix,
1813                         party->name.presentation,
1814                         ast_describe_caller_presentation(party->name.presentation));
1815         }
1816
1817 #if defined(HAVE_PRI_SUBADDR)
1818         /* Party subaddress */
1819         if (party->subaddress.valid) {
1820                 static const char subaddress[] = "Subaddr";
1821
1822                 ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
1823                         S_OR(party->subaddress.str, ""));
1824                 ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
1825                         party->subaddress.type);
1826                 ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
1827                         party->subaddress.odd_even_indicator);
1828         }
1829 #endif  /* defined(HAVE_PRI_SUBADDR) */
1830 }
1831 #endif  /* defined(HAVE_PRI_MCID) */
1832
1833 #if defined(HAVE_PRI_MCID)
1834 /*!
1835  * \internal
1836  * \brief Handle the MCID event.
1837  * \since 1.8
1838  *
1839  * \param pri sig_pri PRI control structure.
1840  * \param mcid MCID event parameters.
1841  * \param owner Asterisk channel associated with the call.
1842  * NULL if Asterisk no longer has the ast_channel struct.
1843  *
1844  * \note Assumes the pri->lock is already obtained.
1845  * \note Assumes the owner channel lock is already obtained if still present.
1846  *
1847  * \return Nothing
1848  */
1849 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
1850 {
1851         struct ast_channel *chans[1];
1852         struct ast_str *msg;
1853         struct ast_party_id party;
1854
1855         msg = ast_str_create(4096);
1856         if (!msg) {
1857                 return;
1858         }
1859
1860         if (owner) {
1861                 /* The owner channel is present. */
1862                 ast_str_append(&msg, 0, "Channel: %s\r\n", owner->name);
1863                 ast_str_append(&msg, 0, "UniqueID: %s\r\n", owner->uniqueid);
1864
1865                 sig_pri_event_party_id(&msg, "CallerID", &owner->connected.id);
1866         } else {
1867                 /*
1868                  * Since we no longer have an owner channel,
1869                  * we have to use the caller information supplied by libpri.
1870                  */
1871                 ast_party_id_init(&party);
1872                 sig_pri_party_id_convert(&party, &mcid->originator, pri);
1873                 sig_pri_event_party_id(&msg, "CallerID", &party);
1874                 ast_party_id_free(&party);
1875         }
1876
1877         /* Always use libpri's called party information. */
1878         ast_party_id_init(&party);
1879         sig_pri_party_id_convert(&party, &mcid->answerer, pri);
1880         sig_pri_event_party_id(&msg, "ConnectedID", &party);
1881         ast_party_id_free(&party);
1882
1883         chans[0] = owner;
1884         ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
1885                 ast_str_buffer(msg));
1886         ast_free(msg);
1887 }
1888 #endif  /* defined(HAVE_PRI_MCID) */
1889
1890 #if defined(HAVE_PRI_TRANSFER)
1891 struct xfer_rsp_data {
1892         struct sig_pri_span *pri;
1893         /*! Call to send transfer success/fail response over. */
1894         q931_call *call;
1895         /*! Invocation ID to use when sending a reply to the transfer request. */
1896         int invoke_id;
1897 };
1898 #endif  /* defined(HAVE_PRI_TRANSFER) */
1899
1900 #if defined(HAVE_PRI_TRANSFER)
1901 /*!
1902  * \internal
1903  * \brief Send the transfer success/fail response message.
1904  * \since 1.8
1905  *
1906  * \param data Callback user data pointer
1907  * \param is_successful TRUE if the transfer was successful.
1908  *
1909  * \return Nothing
1910  */
1911 static void sig_pri_transfer_rsp(void *data, int is_successful)
1912 {
1913         struct xfer_rsp_data *rsp = data;
1914
1915         pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
1916 }
1917 #endif  /* defined(HAVE_PRI_TRANSFER) */
1918
1919 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
1920 /*!
1921  * \brief Protocol callback to indicate if transfer will happen.
1922  * \since 1.8
1923  *
1924  * \param data Callback user data pointer
1925  * \param is_successful TRUE if the transfer will happen.
1926  *
1927  * \return Nothing
1928  */
1929 typedef void (*xfer_rsp_callback)(void *data, int is_successful);
1930 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
1931
1932 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
1933 /*!
1934  * \internal
1935  * \brief Attempt to transfer the two calls to each other.
1936  * \since 1.8
1937  *
1938  * \param pri sig_pri PRI control structure.
1939  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
1940  * \param call_1_held TRUE if call_1_pri is on hold.
1941  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
1942  * \param call_2_held TRUE if call_2_pri is on hold.
1943  * \param rsp_callback Protocol callback to indicate if transfer will happen. NULL if not used.
1944  * \param data Callback user data pointer
1945  *
1946  * \note Assumes the pri->lock is already obtained.
1947  *
1948  * \retval 0 on success.
1949  * \retval -1 on error.
1950  */
1951 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)
1952 {
1953         struct attempt_xfer_call {
1954                 q931_call *pri;
1955                 struct ast_channel *ast;
1956                 int held;
1957                 int chanpos;
1958         };
1959         int retval;
1960         struct ast_channel *transferee;
1961         struct attempt_xfer_call *call_1;
1962         struct attempt_xfer_call *call_2;
1963         struct attempt_xfer_call *swap_call;
1964         struct attempt_xfer_call c1;
1965         struct attempt_xfer_call c2;
1966
1967         c1.pri = call_1_pri;
1968         c1.held = call_1_held;
1969         call_1 = &c1;
1970
1971         c2.pri = call_2_pri;
1972         c2.held = call_2_held;
1973         call_2 = &c2;
1974
1975         call_1->chanpos = pri_find_pri_call(pri, call_1->pri);
1976         call_2->chanpos = pri_find_pri_call(pri, call_2->pri);
1977         if (call_1->chanpos < 0 || call_2->chanpos < 0) {
1978                 /* Calls not found in span control. */
1979                 if (rsp_callback) {
1980                         /* Transfer failed. */
1981                         rsp_callback(data, 0);
1982                 }
1983                 return -1;
1984         }
1985
1986         /* Attempt to make transferee and target consistent. */
1987         if (!call_1->held && call_2->held) {
1988                 /*
1989                  * Swap call_1 and call_2 to make call_1 the transferee(held call)
1990                  * and call_2 the target(active call).
1991                  */
1992                 swap_call = call_1;
1993                 call_1 = call_2;
1994                 call_2 = swap_call;
1995         }
1996
1997         /* Deadlock avoidance is attempted. */
1998         sig_pri_lock_private(pri->pvts[call_1->chanpos]);
1999         sig_pri_lock_owner(pri, call_1->chanpos);
2000         sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2001         sig_pri_lock_owner(pri, call_2->chanpos);
2002
2003         call_1->ast = pri->pvts[call_1->chanpos]->owner;
2004         call_2->ast = pri->pvts[call_2->chanpos]->owner;
2005         if (!call_1->ast || !call_2->ast) {
2006                 /* At least one owner is not present. */
2007                 if (call_1->ast) {
2008                         ast_channel_unlock(call_1->ast);
2009                 }
2010                 if (call_2->ast) {
2011                         ast_channel_unlock(call_2->ast);
2012                 }
2013                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2014                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2015                 if (rsp_callback) {
2016                         /* Transfer failed. */
2017                         rsp_callback(data, 0);
2018                 }
2019                 return -1;
2020         }
2021
2022         for (;;) {
2023                 transferee = ast_bridged_channel(call_1->ast);
2024                 if (transferee) {
2025                         break;
2026                 }
2027
2028                 /* Try masquerading the other way. */
2029                 swap_call = call_1;
2030                 call_1 = call_2;
2031                 call_2 = swap_call;
2032
2033                 transferee = ast_bridged_channel(call_1->ast);
2034                 if (transferee) {
2035                         break;
2036                 }
2037
2038                 /* Could not transfer.  Neither call is bridged. */
2039                 ast_channel_unlock(call_1->ast);
2040                 ast_channel_unlock(call_2->ast);
2041                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2042                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2043
2044                 if (rsp_callback) {
2045                         /* Transfer failed. */
2046                         rsp_callback(data, 0);
2047                 }
2048                 return -1;
2049         }
2050
2051         ast_verb(3, "TRANSFERRING %s to %s\n", call_1->ast->name, call_2->ast->name);
2052
2053         /*
2054          * Setup transfer masquerade.
2055          *
2056          * Note:  There is an extremely nasty deadlock avoidance issue
2057          * with ast_channel_transfer_masquerade().  Deadlock may be possible if
2058          * the channels involved are proxies (chan_agent channels) and
2059          * it is called with locks.  Unfortunately, there is no simple
2060          * or even merely difficult way to guarantee deadlock avoidance
2061          * and still be able to send an ECT success response without the
2062          * possibility of the bridged channel hanging up on us.
2063          */
2064         ast_mutex_unlock(&pri->lock);
2065         retval = ast_channel_transfer_masquerade(
2066                 call_2->ast,
2067                 &call_2->ast->connected,
2068                 call_2->held,
2069                 transferee,
2070                 &call_1->ast->connected,
2071                 call_1->held);
2072
2073         /* Reacquire the pri->lock to hold off completion of the transfer masquerade. */
2074         ast_mutex_lock(&pri->lock);
2075
2076         ast_channel_unlock(call_1->ast);
2077         ast_channel_unlock(call_2->ast);
2078         sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2079         sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2080
2081         if (rsp_callback) {
2082                 /*
2083                  * Report transfer status.
2084                  *
2085                  * Must do the callback before the masquerade completes to ensure
2086                  * that the protocol message goes out before the call leg is
2087                  * disconnected.
2088                  */
2089                 rsp_callback(data, retval ? 0 : 1);
2090         }
2091         return retval;
2092 }
2093 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2094
2095 #if defined(HAVE_PRI_CCSS)
2096 /*!
2097  * \internal
2098  * \brief Compare the CC agent private data by libpri cc_id.
2099  * \since 1.8
2100  *
2101  * \param obj pointer to the (user-defined part) of an object.
2102  * \param arg callback argument from ao2_callback()
2103  * \param flags flags from ao2_callback()
2104  *
2105  * \return values are a combination of enum _cb_results.
2106  */
2107 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
2108 {
2109         struct ast_cc_agent *agent_1 = obj;
2110         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2111         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2112
2113         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2114                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2115 }
2116 #endif  /* defined(HAVE_PRI_CCSS) */
2117
2118 #if defined(HAVE_PRI_CCSS)
2119 /*!
2120  * \internal
2121  * \brief Find the CC agent by libpri cc_id.
2122  * \since 1.8
2123  *
2124  * \param pri sig_pri PRI control structure.
2125  * \param cc_id CC record ID to find.
2126  *
2127  * \note
2128  * Since agents are refcounted, and this function returns
2129  * a reference to the agent, it is imperative that you decrement
2130  * the refcount of the agent once you have finished using it.
2131  *
2132  * \retval agent on success.
2133  * \retval NULL not found.
2134  */
2135 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2136 {
2137         struct sig_pri_cc_agent_prv finder = {
2138                 .pri = pri,
2139                 .cc_id = cc_id,
2140         };
2141
2142         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2143                 sig_pri_cc_type_name);
2144 }
2145 #endif  /* defined(HAVE_PRI_CCSS) */
2146
2147 #if defined(HAVE_PRI_CCSS)
2148 /*!
2149  * \internal
2150  * \brief Compare the CC monitor instance by libpri cc_id.
2151  * \since 1.8
2152  *
2153  * \param obj pointer to the (user-defined part) of an object.
2154  * \param arg callback argument from ao2_callback()
2155  * \param flags flags from ao2_callback()
2156  *
2157  * \return values are a combination of enum _cb_results.
2158  */
2159 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2160 {
2161         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2162         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2163
2164         return (monitor_1->pri == monitor_2->pri
2165                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2166 }
2167 #endif  /* defined(HAVE_PRI_CCSS) */
2168
2169 #if defined(HAVE_PRI_CCSS)
2170 /*!
2171  * \internal
2172  * \brief Find the CC monitor instance by libpri cc_id.
2173  * \since 1.8
2174  *
2175  * \param pri sig_pri PRI control structure.
2176  * \param cc_id CC record ID to find.
2177  *
2178  * \note
2179  * Since monitor_instances are refcounted, and this function returns
2180  * a reference to the instance, it is imperative that you decrement
2181  * the refcount of the instance once you have finished using it.
2182  *
2183  * \retval monitor_instance on success.
2184  * \retval NULL not found.
2185  */
2186 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2187 {
2188         struct sig_pri_cc_monitor_instance finder = {
2189                 .pri = pri,
2190                 .cc_id = cc_id,
2191         };
2192
2193         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2194 }
2195 #endif  /* defined(HAVE_PRI_CCSS) */
2196
2197 #if defined(HAVE_PRI_CCSS)
2198 /*!
2199  * \internal
2200  * \brief Destroy the given monitor instance.
2201  * \since 1.8
2202  *
2203  * \param data Monitor instance to destroy.
2204  *
2205  * \return Nothing
2206  */
2207 static void sig_pri_cc_monitor_instance_destroy(void *data)
2208 {
2209         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2210
2211         if (monitor_instance->cc_id != -1) {
2212                 ast_mutex_lock(&monitor_instance->pri->lock);
2213                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2214                 ast_mutex_unlock(&monitor_instance->pri->lock);
2215         }
2216         monitor_instance->pri->calls->module_unref();
2217 }
2218 #endif  /* defined(HAVE_PRI_CCSS) */
2219
2220 #if defined(HAVE_PRI_CCSS)
2221 /*!
2222  * \internal
2223  * \brief Construct a new monitor instance.
2224  * \since 1.8
2225  *
2226  * \param core_id CC core ID.
2227  * \param pri sig_pri PRI control structure.
2228  * \param cc_id CC record ID.
2229  * \param device_name Name of device (Asterisk channel name less sequence number).
2230  *
2231  * \note
2232  * Since monitor_instances are refcounted, and this function returns
2233  * a reference to the instance, it is imperative that you decrement
2234  * the refcount of the instance once you have finished using it.
2235  *
2236  * \retval monitor_instance on success.
2237  * \retval NULL on error.
2238  */
2239 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)
2240 {
2241         struct sig_pri_cc_monitor_instance *monitor_instance;
2242
2243         if (!pri->calls->module_ref || !pri->calls->module_unref) {
2244                 return NULL;
2245         }
2246
2247         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2248                 sig_pri_cc_monitor_instance_destroy);
2249         if (!monitor_instance) {
2250                 return NULL;
2251         }
2252
2253         monitor_instance->cc_id = cc_id;
2254         monitor_instance->pri = pri;
2255         monitor_instance->core_id = core_id;
2256         strcpy(monitor_instance->name, device_name);
2257
2258         pri->calls->module_ref();
2259
2260         ao2_link(sig_pri_cc_monitors, monitor_instance);
2261         return monitor_instance;
2262 }
2263 #endif  /* defined(HAVE_PRI_CCSS) */
2264
2265 #if defined(HAVE_PRI_CCSS)
2266 /*!
2267  * \internal
2268  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2269  * \since 1.8
2270  *
2271  * \param pri sig_pri PRI control structure.
2272  * \param chanpos Channel position in the span.
2273  * \param cc_id CC record ID.
2274  * \param service CCBS/CCNR indication.
2275  *
2276  * \note Assumes the pri->lock is already obtained.
2277  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2278  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2279  *
2280  * \retval 0 on success.
2281  * \retval -1 on error.
2282  */
2283 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2284 {
2285         struct sig_pri_chan *pvt;
2286         struct ast_cc_config_params *cc_params;
2287         struct sig_pri_cc_monitor_instance *monitor;
2288         enum ast_cc_monitor_policies monitor_policy;
2289         int core_id;
2290         int res;
2291         char device_name[AST_CHANNEL_NAME];
2292         char dialstring[AST_CHANNEL_NAME];
2293
2294         pvt = pri->pvts[chanpos];
2295
2296         core_id = ast_cc_get_current_core_id(pvt->owner);
2297         if (core_id == -1) {
2298                 return -1;
2299         }
2300
2301         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2302         if (!cc_params) {
2303                 return -1;
2304         }
2305
2306         res = -1;
2307         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2308         switch (monitor_policy) {
2309         case AST_CC_MONITOR_NEVER:
2310                 /* CCSS is not enabled. */
2311                 break;
2312         case AST_CC_MONITOR_NATIVE:
2313         case AST_CC_MONITOR_ALWAYS:
2314                 /*
2315                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2316                  * later in the call to sig_pri_cc_generic_check().
2317                  */
2318                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2319                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2320                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2321                 if (!monitor) {
2322                         break;
2323                 }
2324                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2325                         monitor);
2326                 if (res) {
2327                         monitor->cc_id = -1;
2328                         ao2_unlink(sig_pri_cc_monitors, monitor);
2329                         ao2_ref(monitor, -1);
2330                 }
2331                 break;
2332         case AST_CC_MONITOR_GENERIC:
2333                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2334                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2335                 /* Say it failed to force caller to cancel native CC. */
2336                 break;
2337         }
2338         return res;
2339 }
2340 #endif  /* defined(HAVE_PRI_CCSS) */
2341
2342 /*!
2343  * \internal
2344  * \brief Check if generic CC monitor is needed and request it.
2345  * \since 1.8
2346  *
2347  * \param pri sig_pri PRI control structure.
2348  * \param chanpos Channel position in the span.
2349  * \param service CCBS/CCNR indication.
2350  *
2351  * \note Assumes the pri->lock is already obtained.
2352  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2353  *
2354  * \return Nothing
2355  */
2356 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
2357 {
2358         struct ast_channel *owner;
2359         struct ast_cc_config_params *cc_params;
2360 #if defined(HAVE_PRI_CCSS)
2361         struct ast_cc_monitor *monitor;
2362         char device_name[AST_CHANNEL_NAME];
2363 #endif  /* defined(HAVE_PRI_CCSS) */
2364         enum ast_cc_monitor_policies monitor_policy;
2365         int core_id;
2366
2367         if (!pri->pvts[chanpos]->outgoing) {
2368                 /* This is not an outgoing call so it cannot be CC monitor. */
2369                 return;
2370         }
2371
2372         sig_pri_lock_owner(pri, chanpos);
2373         owner = pri->pvts[chanpos]->owner;
2374         if (!owner) {
2375                 return;
2376         }
2377         core_id = ast_cc_get_current_core_id(owner);
2378         if (core_id == -1) {
2379                 /* No CC core setup */
2380                 goto done;
2381         }
2382
2383         cc_params = ast_channel_get_cc_config_params(owner);
2384         if (!cc_params) {
2385                 /* Could not get CC config parameters. */
2386                 goto done;
2387         }
2388
2389 #if defined(HAVE_PRI_CCSS)
2390         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
2391         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
2392         if (monitor) {
2393                 /* CC monitor is already present so no need for generic CC. */
2394                 ao2_ref(monitor, -1);
2395                 goto done;
2396         }
2397 #endif  /* defined(HAVE_PRI_CCSS) */
2398
2399         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2400         switch (monitor_policy) {
2401         case AST_CC_MONITOR_NEVER:
2402                 /* CCSS is not enabled. */
2403                 break;
2404         case AST_CC_MONITOR_NATIVE:
2405                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2406                         /* Request generic CC monitor. */
2407                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2408                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2409                 }
2410                 break;
2411         case AST_CC_MONITOR_ALWAYS:
2412                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2413                         /*
2414                          * Cannot monitor PTMP TE side since this is not defined.
2415                          * We are playing the roll of a phone in this case and
2416                          * a phone cannot monitor a party over the network without
2417                          * protocol help.
2418                          */
2419                         break;
2420                 }
2421                 /*
2422                  * We are either falling back or this is a PTMP NT span.
2423                  * Request generic CC monitor.
2424                  */
2425                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2426                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2427                 break;
2428         case AST_CC_MONITOR_GENERIC:
2429                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2430                         /* Request generic CC monitor. */
2431                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2432                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2433                 }
2434                 break;
2435         }
2436
2437 done:
2438         ast_channel_unlock(owner);
2439 }
2440
2441 #if defined(HAVE_PRI_CCSS)
2442 /*!
2443  * \internal
2444  * \brief The CC link canceled the CC instance.
2445  * \since 1.8
2446  *
2447  * \param pri sig_pri PRI control structure.
2448  * \param cc_id CC record ID.
2449  * \param is_agent TRUE if the cc_id is for an agent.
2450  *
2451  * \return Nothing
2452  */
2453 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
2454 {
2455         if (is_agent) {
2456                 struct ast_cc_agent *agent;
2457
2458                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2459                 if (!agent) {
2460                         return;
2461                 }
2462                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2463                         sig_pri_cc_type_name);
2464                 ao2_ref(agent, -1);
2465         } else {
2466                 struct sig_pri_cc_monitor_instance *monitor;
2467
2468                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2469                 if (!monitor) {
2470                         return;
2471                 }
2472                 monitor->cc_id = -1;
2473                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2474                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2475                 ao2_ref(monitor, -1);
2476         }
2477 }
2478 #endif  /* defined(HAVE_PRI_CCSS) */
2479
2480 #if defined(HAVE_PRI_AOC_EVENTS)
2481 /*!
2482  * \internal
2483  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2484  * \since 1.8
2485  *
2486  * \param value Value to convert to string.
2487  *
2488  * \return PRI_AOC_CHARGED_ITEM
2489  */
2490 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2491 {
2492         switch (value) {
2493         case AST_AOC_CHARGED_ITEM_NA:
2494                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2495         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2496                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2497         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2498                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2499         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2500                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2501         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2502                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2503         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2504                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2505         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2506                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2507         }
2508         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2509 }
2510 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2511
2512 #if defined(HAVE_PRI_AOC_EVENTS)
2513 /*!
2514  * \internal
2515  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2516  * \since 1.8
2517  *
2518  * \param value Value to convert to string.
2519  *
2520  * \return ast_aoc_charged_item
2521  */
2522 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2523 {
2524         switch (value) {
2525         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2526                 return AST_AOC_CHARGED_ITEM_NA;
2527         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2528                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2529         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2530                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2531         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2532                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2533         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2534                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2535         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2536                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2537         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2538                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2539         }
2540         return AST_AOC_CHARGED_ITEM_NA;
2541 }
2542 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2543
2544 #if defined(HAVE_PRI_AOC_EVENTS)
2545 /*!
2546  * \internal
2547  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2548  * \since 1.8
2549  *
2550  * \return pri enum equivalent.
2551  */
2552 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2553 {
2554         switch (mult) {
2555         case AST_AOC_MULT_ONETHOUSANDTH:
2556                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2557         case AST_AOC_MULT_ONEHUNDREDTH:
2558                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2559         case AST_AOC_MULT_ONETENTH:
2560                 return PRI_AOC_MULTIPLIER_TENTH;
2561         case AST_AOC_MULT_ONE:
2562                 return PRI_AOC_MULTIPLIER_ONE;
2563         case AST_AOC_MULT_TEN:
2564                 return PRI_AOC_MULTIPLIER_TEN;
2565         case AST_AOC_MULT_HUNDRED:
2566                 return PRI_AOC_MULTIPLIER_HUNDRED;
2567         case AST_AOC_MULT_THOUSAND:
2568                 return PRI_AOC_MULTIPLIER_THOUSAND;
2569         default:
2570                 return PRI_AOC_MULTIPLIER_ONE;
2571         }
2572 }
2573 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2574
2575 #if defined(HAVE_PRI_AOC_EVENTS)
2576 /*!
2577  * \internal
2578  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2579  * \since 1.8
2580  *
2581  * \return ast enum equivalent.
2582  */
2583 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2584 {
2585         switch (mult) {
2586         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2587                 return AST_AOC_MULT_ONETHOUSANDTH;
2588         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2589                 return AST_AOC_MULT_ONEHUNDREDTH;
2590         case PRI_AOC_MULTIPLIER_TENTH:
2591                 return AST_AOC_MULT_ONETENTH;
2592         case PRI_AOC_MULTIPLIER_ONE:
2593                 return AST_AOC_MULT_ONE;
2594         case PRI_AOC_MULTIPLIER_TEN:
2595                 return AST_AOC_MULT_TEN;
2596         case PRI_AOC_MULTIPLIER_HUNDRED:
2597                 return AST_AOC_MULT_HUNDRED;
2598         case PRI_AOC_MULTIPLIER_THOUSAND:
2599                 return AST_AOC_MULT_THOUSAND;
2600         default:
2601                 return AST_AOC_MULT_ONE;
2602         }
2603 }
2604 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2605
2606 #if defined(HAVE_PRI_AOC_EVENTS)
2607 /*!
2608  * \internal
2609  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
2610  * \since 1.8
2611  *
2612  * \param value Value to convert to ast representation
2613  *
2614  * \return PRI_AOC_TIME_SCALE
2615  */
2616 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
2617 {
2618         switch (value) {
2619         default:
2620         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2621                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2622         case AST_AOC_TIME_SCALE_TENTH_SECOND:
2623                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
2624         case AST_AOC_TIME_SCALE_SECOND:
2625                 return PRI_AOC_TIME_SCALE_SECOND;
2626         case AST_AOC_TIME_SCALE_TEN_SECOND:
2627                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
2628         case AST_AOC_TIME_SCALE_MINUTE:
2629                 return PRI_AOC_TIME_SCALE_MINUTE;
2630         case AST_AOC_TIME_SCALE_HOUR:
2631                 return PRI_AOC_TIME_SCALE_HOUR;
2632         case AST_AOC_TIME_SCALE_DAY:
2633                 return PRI_AOC_TIME_SCALE_DAY;
2634         }
2635 }
2636 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2637
2638 #if defined(HAVE_PRI_AOC_EVENTS)
2639 /*!
2640  * \internal
2641  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
2642  * \since 1.8
2643  *
2644  * \param value Value to convert to ast representation
2645  *
2646  * \return ast aoc time scale
2647  */
2648 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
2649 {
2650         switch (value) {
2651         default:
2652         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2653                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2654         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
2655                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
2656         case PRI_AOC_TIME_SCALE_SECOND:
2657                 return AST_AOC_TIME_SCALE_SECOND;
2658         case PRI_AOC_TIME_SCALE_TEN_SECOND:
2659                 return AST_AOC_TIME_SCALE_TEN_SECOND;
2660         case PRI_AOC_TIME_SCALE_MINUTE:
2661                 return AST_AOC_TIME_SCALE_MINUTE;
2662         case PRI_AOC_TIME_SCALE_HOUR:
2663                 return AST_AOC_TIME_SCALE_HOUR;
2664         case PRI_AOC_TIME_SCALE_DAY:
2665                 return AST_AOC_TIME_SCALE_DAY;
2666         }
2667         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2668 }
2669 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2670
2671 #if defined(HAVE_PRI_AOC_EVENTS)
2672 /*!
2673  * \internal
2674  * \brief Handle AOC-S control frame
2675  * \since 1.8
2676  *
2677  * \param aoc_s AOC-S event parameters.
2678  * \param owner Asterisk channel associated with the call.
2679  * \param passthrough indicating if this message should be queued on the ast channel
2680  *
2681  * \note Assumes the pri->lock is already obtained.
2682  * \note Assumes the sig_pri private is locked
2683  * \note Assumes the owner channel lock is already obtained.
2684  *
2685  * \return Nothing
2686  */
2687 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
2688 {
2689         struct ast_aoc_decoded *decoded = NULL;
2690         struct ast_aoc_encoded *encoded = NULL;
2691         size_t encoded_size = 0;
2692         int idx;
2693
2694         if (!owner || !aoc_s) {
2695                 return;
2696         }
2697
2698         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
2699                 return;
2700         }
2701
2702         for (idx = 0; idx < aoc_s->num_items; ++idx) {
2703                 enum ast_aoc_s_charged_item charged_item;
2704
2705                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
2706                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
2707                         /* Delete the unknown charged item from the list. */
2708                         continue;
2709                 }
2710                 switch (aoc_s->item[idx].rate_type) {
2711                 case PRI_AOC_RATE_TYPE_DURATION:
2712                         ast_aoc_s_add_rate_duration(decoded,
2713                                 charged_item,
2714                                 aoc_s->item[idx].rate.duration.amount.cost,
2715                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
2716                                 aoc_s->item[idx].rate.duration.currency,
2717                                 aoc_s->item[idx].rate.duration.time.length,
2718                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
2719                                 aoc_s->item[idx].rate.duration.granularity.length,
2720                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
2721                                 aoc_s->item[idx].rate.duration.charging_type);
2722                         break;
2723                 case PRI_AOC_RATE_TYPE_FLAT:
2724                         ast_aoc_s_add_rate_flat(decoded,
2725                                 charged_item,
2726                                 aoc_s->item[idx].rate.flat.amount.cost,
2727                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
2728                                 aoc_s->item[idx].rate.flat.currency);
2729                         break;
2730                 case PRI_AOC_RATE_TYPE_VOLUME:
2731                         ast_aoc_s_add_rate_volume(decoded,
2732                                 charged_item,
2733                                 aoc_s->item[idx].rate.volume.unit,
2734                                 aoc_s->item[idx].rate.volume.amount.cost,
2735                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
2736                                 aoc_s->item[idx].rate.volume.currency);
2737                         break;
2738                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
2739                         ast_aoc_s_add_rate_special_charge_code(decoded,
2740                                 charged_item,
2741                                 aoc_s->item[idx].rate.special);
2742                         break;
2743                 case PRI_AOC_RATE_TYPE_FREE:
2744                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
2745                         break;
2746                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2747                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
2748                         break;
2749                 default:
2750                         ast_aoc_s_add_rate_na(decoded, charged_item);
2751                         break;
2752                 }
2753         }
2754
2755         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2756                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2757         }
2758
2759         ast_aoc_manager_event(decoded, owner);
2760
2761         ast_aoc_destroy_decoded(decoded);
2762         ast_aoc_destroy_encoded(encoded);
2763 }
2764 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2765
2766 #if defined(HAVE_PRI_AOC_EVENTS)
2767 /*!
2768  * \internal
2769  * \brief Generate AOC Request Response
2770  * \since 1.8
2771  *
2772  * \param aoc_request
2773  *
2774  * \note Assumes the pri->lock is already obtained.
2775  * \note Assumes the sig_pri private is locked
2776  * \note Assumes the owner channel lock is already obtained.
2777  *
2778  * \return Nothing
2779  */
2780 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
2781 {
2782         int request;
2783
2784         if (!aoc_request) {
2785                 return;
2786         }
2787
2788         request = aoc_request->charging_request;
2789
2790         if (request & PRI_AOC_REQUEST_S) {
2791                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
2792                         /* An AOC-S response must come from the other side, so save off this invoke_id
2793                          * and see if an AOC-S message comes in before the call is answered. */
2794                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
2795                         pvt->aoc_s_request_invoke_id_valid = 1;
2796
2797                 } else {
2798                         pri_aoc_s_request_response_send(pvt->pri->pri,
2799                                 call,
2800                                 aoc_request->invoke_id,
2801                                 NULL);
2802                 }
2803         }
2804
2805         if (request & PRI_AOC_REQUEST_D) {
2806                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
2807                         pri_aoc_de_request_response_send(pvt->pri->pri,
2808                                 call,
2809                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2810                                 aoc_request->invoke_id);
2811                 } else {
2812                         pri_aoc_de_request_response_send(pvt->pri->pri,
2813                                 call,
2814                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2815                                 aoc_request->invoke_id);
2816                 }
2817         }
2818
2819         if (request & PRI_AOC_REQUEST_E) {
2820                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
2821                         pri_aoc_de_request_response_send(pvt->pri->pri,
2822                                 call,
2823                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2824                                 aoc_request->invoke_id);
2825                 } else {
2826                         pri_aoc_de_request_response_send(pvt->pri->pri,
2827                                 call,
2828                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2829                                 aoc_request->invoke_id);
2830                 }
2831         }
2832 }
2833 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2834
2835 #if defined(HAVE_PRI_AOC_EVENTS)
2836 /*!
2837  * \internal
2838  * \brief Generate AOC-D AST_CONTROL_AOC frame
2839  * \since 1.8
2840  *
2841  * \param aoc_e AOC-D event parameters.
2842  * \param owner Asterisk channel associated with the call.
2843  * \param passthrough indicating if this message should be queued on the ast channel
2844  *
2845  * \note Assumes the pri->lock is already obtained.
2846  * \note Assumes the sig_pri private is locked
2847  * \note Assumes the owner channel lock is already obtained.
2848  *
2849  * \return Nothing
2850  */
2851 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
2852 {
2853         struct ast_aoc_decoded *decoded = NULL;
2854         struct ast_aoc_encoded *encoded = NULL;
2855         size_t encoded_size = 0;
2856         enum ast_aoc_charge_type type;
2857
2858         if (!owner || !aoc_d) {
2859                 return;
2860         }
2861
2862         switch (aoc_d->charge) {
2863         case PRI_AOC_DE_CHARGE_CURRENCY:
2864                 type = AST_AOC_CHARGE_CURRENCY;
2865                 break;
2866         case PRI_AOC_DE_CHARGE_UNITS:
2867                 type = AST_AOC_CHARGE_UNIT;
2868                 break;
2869         case PRI_AOC_DE_CHARGE_FREE:
2870                 type = AST_AOC_CHARGE_FREE;
2871                 break;
2872         default:
2873                 type = AST_AOC_CHARGE_NA;
2874                 break;
2875         }
2876
2877         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
2878                 return;
2879         }
2880
2881         switch (aoc_d->billing_accumulation) {
2882         default:
2883                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
2884                         aoc_d->billing_accumulation);
2885                 /* Fall through */
2886         case 0:/* subTotal */
2887                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
2888                 break;
2889         case 1:/* total */
2890                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
2891                 break;
2892         }
2893
2894         switch (aoc_d->billing_id) {
2895         case PRI_AOC_D_BILLING_ID_NORMAL:
2896                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2897                 break;
2898         case PRI_AOC_D_BILLING_ID_REVERSE:
2899                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2900                 break;
2901         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
2902                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2903                 break;
2904         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
2905         default:
2906                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2907                 break;
2908         }
2909
2910         switch (aoc_d->charge) {
2911         case PRI_AOC_DE_CHARGE_CURRENCY:
2912                 ast_aoc_set_currency_info(decoded,
2913                         aoc_d->recorded.money.amount.cost,
2914                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
2915                         aoc_d->recorded.money.currency);
2916                 break;
2917         case PRI_AOC_DE_CHARGE_UNITS:
2918                 {
2919                         int i;
2920                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
2921                                 /* if type or number are negative, then they are not present */
2922                                 ast_aoc_add_unit_entry(decoded,
2923                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
2924                                         aoc_d->recorded.unit.item[i].number,
2925                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
2926                                         aoc_d->recorded.unit.item[i].type);
2927                         }
2928                 }
2929                 break;
2930         }
2931
2932         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2933                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2934         }
2935
2936         ast_aoc_manager_event(decoded, owner);
2937
2938         ast_aoc_destroy_decoded(decoded);
2939         ast_aoc_destroy_encoded(encoded);
2940 }
2941 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2942
2943 #if defined(HAVE_PRI_AOC_EVENTS)
2944 /*!
2945  * \internal
2946  * \brief Generate AOC-E AST_CONTROL_AOC frame
2947  * \since 1.8
2948  *
2949  * \param aoc_e AOC-E event parameters.
2950  * \param owner Asterisk channel associated with the call.
2951  * \param passthrough indicating if this message should be queued on the ast channel
2952  *
2953  * \note Assumes the pri->lock is already obtained.
2954  * \note Assumes the sig_pri private is locked
2955  * \note Assumes the owner channel lock is already obtained.
2956  * \note owner channel may be NULL. In that case, generate event only
2957  *
2958  * \return Nothing
2959  */
2960 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
2961 {
2962         struct ast_aoc_decoded *decoded = NULL;
2963         struct ast_aoc_encoded *encoded = NULL;
2964         size_t encoded_size = 0;
2965         enum ast_aoc_charge_type type;
2966
2967         if (!aoc_e) {
2968                 return;
2969         }
2970
2971         switch (aoc_e->charge) {
2972         case PRI_AOC_DE_CHARGE_CURRENCY:
2973                 type = AST_AOC_CHARGE_CURRENCY;
2974                 break;
2975         case PRI_AOC_DE_CHARGE_UNITS:
2976                 type = AST_AOC_CHARGE_UNIT;
2977                 break;
2978         case PRI_AOC_DE_CHARGE_FREE:
2979                 type = AST_AOC_CHARGE_FREE;
2980                 break;
2981         default:
2982                 type = AST_AOC_CHARGE_NA;
2983                 break;
2984         }
2985
2986         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
2987                 return;
2988         }
2989
2990         switch (aoc_e->associated.charging_type) {
2991         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
2992                 if (!aoc_e->associated.charge.number.valid) {
2993                         break;
2994                 }
2995                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
2996                 break;
2997         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
2998                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
2999                 break;
3000         default:
3001                 break;
3002         }
3003
3004         switch (aoc_e->billing_id) {
3005         case PRI_AOC_E_BILLING_ID_NORMAL:
3006                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3007                 break;
3008         case PRI_AOC_E_BILLING_ID_REVERSE:
3009                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3010                 break;
3011         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
3012                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3013                 break;
3014         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
3015                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
3016                 break;
3017         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
3018                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
3019                 break;
3020         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
3021                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
3022                 break;
3023         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
3024                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
3025                 break;
3026         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
3027                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
3028                 break;
3029         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
3030         default:
3031                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3032                 break;
3033         }
3034
3035         switch (aoc_e->charge) {
3036         case PRI_AOC_DE_CHARGE_CURRENCY:
3037                 ast_aoc_set_currency_info(decoded,
3038                         aoc_e->recorded.money.amount.cost,
3039                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
3040                         aoc_e->recorded.money.currency);
3041                 break;
3042         case PRI_AOC_DE_CHARGE_UNITS:
3043                 {
3044                         int i;
3045                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
3046                                 /* if type or number are negative, then they are not present */
3047                                 ast_aoc_add_unit_entry(decoded,
3048                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
3049                                         aoc_e->recorded.unit.item[i].number,
3050                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
3051                                         aoc_e->recorded.unit.item[i].type);
3052                         }
3053                 }
3054         }
3055
3056         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3057                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3058         }
3059
3060         ast_aoc_manager_event(decoded, owner);
3061
3062         ast_aoc_destroy_decoded(decoded);
3063         ast_aoc_destroy_encoded(encoded);
3064 }
3065 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3066
3067 #if defined(HAVE_PRI_AOC_EVENTS)
3068 /*!
3069  * \internal
3070  * \brief send an AOC-S message on the current call
3071  *
3072  * \param pvt sig_pri private channel structure.
3073  * \param generic decoded ast AOC message
3074  *
3075  * \return Nothing
3076  *
3077  * \note Assumes that the PRI lock is already obtained.
3078  */
3079 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3080 {
3081         struct pri_subcmd_aoc_s aoc_s = { 0, };
3082         const struct ast_aoc_s_entry *entry;
3083         int idx;
3084
3085         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
3086                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
3087                         break;
3088                 }
3089
3090                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
3091
3092                 switch (entry->rate_type) {
3093                 case AST_AOC_RATE_TYPE_DURATION:
3094                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
3095                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
3096                         aoc_s.item[idx].rate.duration.amount.multiplier =
3097                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
3098                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
3099                         aoc_s.item[idx].rate.duration.time.scale =
3100                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
3101                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
3102                         aoc_s.item[idx].rate.duration.granularity.scale =
3103                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
3104                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
3105
3106                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
3107                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
3108                                         entry->rate.duration.currency_name,
3109                                         sizeof(aoc_s.item[idx].rate.duration.currency));
3110                         }
3111                         break;
3112                 case AST_AOC_RATE_TYPE_FLAT:
3113                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
3114                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
3115                         aoc_s.item[idx].rate.flat.amount.multiplier =
3116                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
3117
3118                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
3119                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
3120                                         entry->rate.flat.currency_name,
3121                                         sizeof(aoc_s.item[idx].rate.flat.currency));
3122                         }
3123                         break;
3124                 case AST_AOC_RATE_TYPE_VOLUME:
3125                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
3126                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
3127                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
3128                         aoc_s.item[idx].rate.volume.amount.multiplier =
3129                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
3130
3131                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
3132                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
3133                                         entry->rate.volume.currency_name,
3134                                         sizeof(aoc_s.item[idx].rate.volume.currency));
3135                         }
3136                         break;
3137                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
3138                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
3139                         aoc_s.item[idx].rate.special = entry->rate.special_code;
3140                         break;
3141                 case AST_AOC_RATE_TYPE_FREE:
3142                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
3143                         break;
3144                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3145                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
3146                         break;
3147                 default:
3148                 case AST_AOC_RATE_TYPE_NA:
3149                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
3150                         break;
3151                 }
3152         }
3153         aoc_s.num_items = idx;
3154
3155         /* if this rate should be sent as a response to an AOC-S request we will
3156          * have an aoc_s_request_invoke_id associated with this pvt */
3157         if (pvt->aoc_s_request_invoke_id_valid) {
3158                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
3159                 pvt->aoc_s_request_invoke_id_valid = 0;
3160         } else {
3161                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
3162         }
3163 }
3164 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3165
3166 #if defined(HAVE_PRI_AOC_EVENTS)
3167 /*!
3168  * \internal
3169  * \brief send an AOC-D message on the current call
3170  *
3171  * \param pvt sig_pri private channel structure.
3172  * \param generic decoded ast AOC message
3173  *
3174  * \return Nothing
3175  *
3176  * \note Assumes that the PRI lock is already obtained.
3177  */
3178 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3179 {
3180         struct pri_subcmd_aoc_d aoc_d = { 0, };
3181
3182         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
3183
3184         switch (ast_aoc_get_billing_id(decoded)) {
3185         case AST_AOC_BILLING_NORMAL:
3186                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
3187                 break;
3188         case AST_AOC_BILLING_REVERSE_CHARGE:
3189                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
3190                 break;
3191         case AST_AOC_BILLING_CREDIT_CARD:
3192                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
3193                 break;
3194         case AST_AOC_BILLING_NA:
3195         default:
3196                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
3197                 break;
3198         }
3199
3200         switch (ast_aoc_get_charge_type(decoded)) {
3201         case AST_AOC_CHARGE_FREE:
3202                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
3203                 break;
3204         case AST_AOC_CHARGE_CURRENCY:
3205                 {
3206                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3207                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
3208                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3209                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3210                         if (!ast_strlen_zero(currency_name)) {
3211                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
3212                         }
3213                 }
3214                 break;
3215         case AST_AOC_CHARGE_UNIT:
3216                 {
3217                         const struct ast_aoc_unit_entry *entry;
3218                         int i;
3219                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
3220                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3221                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
3222                                         if (entry->valid_amount) {
3223                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
3224                                         } else {
3225                                                 aoc_d.recorded.unit.item[i].number = -1;
3226                                         }
3227                                         if (entry->valid_type) {
3228                                                 aoc_d.recorded.unit.item[i].type = entry->type;
3229                                         } else {
3230                                                 aoc_d.recorded.unit.item[i].type = -1;
3231                                         }
3232                                         aoc_d.recorded.unit.num_items++;
3233                                 } else {
3234                                         break;
3235                                 }
3236                         }
3237                 }
3238                 break;
3239         case AST_AOC_CHARGE_NA:
3240         default:
3241                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3242                 break;
3243         }
3244
3245         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
3246 }
3247 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3248
3249 #if defined(HAVE_PRI_AOC_EVENTS)
3250 /*!
3251  * \internal
3252  * \brief send an AOC-E message on the current call
3253  *
3254  * \param pvt sig_pri private channel structure.
3255  * \param generic decoded ast AOC message
3256  *
3257  * \return Nothing
3258  *
3259  * \note Assumes that the PRI lock is already obtained.
3260  */
3261 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3262 {
3263         struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
3264         const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
3265
3266         memset(aoc_e, 0, sizeof(*aoc_e));
3267         pvt->holding_aoce = 1;
3268
3269         switch (ca->charging_type) {
3270         case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
3271                 aoc_e->associated.charge.number.valid = 1;
3272                 ast_copy_string(aoc_e->associated.charge.number.str,
3273                         ca->charge.number.number,
3274                         sizeof(aoc_e->associated.charge.number.str));
3275                 aoc_e->associated.charge.number.plan = ca->charge.number.plan;
3276                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
3277                 break;
3278         case AST_AOC_CHARGING_ASSOCIATION_ID:
3279                 aoc_e->associated.charge.id = ca->charge.id;
3280                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
3281                 break;
3282         case AST_AOC_CHARGING_ASSOCIATION_NA:
3283         default:
3284                 break;
3285         }
3286
3287         switch (ast_aoc_get_billing_id(decoded)) {
3288         case AST_AOC_BILLING_NORMAL:
3289                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
3290                 break;
3291         case AST_AOC_BILLING_REVERSE_CHARGE:
3292                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
3293                 break;
3294         case AST_AOC_BILLING_CREDIT_CARD:
3295                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
3296                 break;
3297         case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
3298                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
3299                 break;
3300         case AST_AOC_BILLING_CALL_FWD_BUSY:
3301                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
3302                 break;
3303         case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
3304                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
3305                 break;
3306         case AST_AOC_BILLING_CALL_DEFLECTION:
3307                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
3308                 break;
3309         case AST_AOC_BILLING_CALL_TRANSFER:
3310                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
3311                 break;
3312         case AST_AOC_BILLING_NA:
3313         default:
3314                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
3315                 break;
3316         }
3317
3318         switch (ast_aoc_get_charge_type(decoded)) {
3319         case AST_AOC_CHARGE_FREE:
3320                 aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
3321                 break;
3322         case AST_AOC_CHARGE_CURRENCY:
3323                 {
3324                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3325                         aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
3326                         aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3327                         aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3328                         if (!ast_strlen_zero(currency_name)) {
3329                                 ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
3330                         }
3331                 }
3332                 break;
3333      &nb