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