Merged revisions 290674 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_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
1886 /*!
1887  * \internal
1888  * \brief Attempt to transfer the two calls to each other.
1889  * \since 1.8
1890  *
1891  * \param pri sig_pri PRI control structure.
1892  * \param call_1 First call involved in the transfer.
1893  * \param call_1_held TRUE if call_1 is on hold.
1894  * \param call_2 Second call involved in the transfer.
1895  * \param call_2_held TRUE if call_2 is on hold.
1896  *
1897  * \note Assumes the pri->lock is already obtained.
1898  *
1899  * \retval 0 on success.
1900  * \retval -1 on error.
1901  */
1902 static int sig_pri_attempt_transfer(struct sig_pri_span *pri, q931_call *call_1, int call_1_held, q931_call *call_2, int call_2_held)
1903 {
1904         int retval;
1905         int call_1_chanpos;
1906         int call_2_chanpos;
1907         struct ast_channel *call_1_ast;
1908         struct ast_channel *call_2_ast;
1909         struct ast_channel *bridged;
1910
1911         call_1_chanpos = pri_find_pri_call(pri, call_1);
1912         call_2_chanpos = pri_find_pri_call(pri, call_2);
1913         if (call_1_chanpos < 0 || call_2_chanpos < 0) {
1914                 return -1;
1915         }
1916
1917         /* Deadlock avoidance is attempted. */
1918         sig_pri_lock_private(pri->pvts[call_1_chanpos]);
1919         sig_pri_lock_owner(pri, call_1_chanpos);
1920         sig_pri_lock_private(pri->pvts[call_2_chanpos]);
1921         sig_pri_lock_owner(pri, call_2_chanpos);
1922
1923         call_1_ast = pri->pvts[call_1_chanpos]->owner;
1924         call_2_ast = pri->pvts[call_2_chanpos]->owner;
1925         if (!call_1_ast || !call_2_ast) {
1926                 if (call_1_ast) {
1927                         ast_channel_unlock(call_1_ast);
1928                 }
1929                 if (call_2_ast) {
1930                         ast_channel_unlock(call_2_ast);
1931                 }
1932                 sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1933                 sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1934                 return -1;
1935         }
1936
1937         bridged = ast_bridged_channel(call_2_ast);
1938         if (bridged) {
1939                 if (call_1_held) {
1940                         ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1941                 }
1942                 if (call_2_held) {
1943                         ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1944                 }
1945
1946                 ast_verb(3, "TRANSFERRING %s to %s\n", call_2_ast->name, call_1_ast->name);
1947                 retval = ast_channel_masquerade(call_1_ast, bridged);
1948         } else {
1949                 /* Try masquerading the other way. */
1950                 bridged = ast_bridged_channel(call_1_ast);
1951                 if (bridged) {
1952                         if (call_1_held) {
1953                                 ast_queue_control(call_1_ast, AST_CONTROL_UNHOLD);
1954                         }
1955                         if (call_2_held) {
1956                                 ast_queue_control(call_2_ast, AST_CONTROL_UNHOLD);
1957                         }
1958
1959                         ast_verb(3, "TRANSFERRING %s to %s\n", call_1_ast->name, call_2_ast->name);
1960                         retval = ast_channel_masquerade(call_2_ast, bridged);
1961                 } else {
1962                         /* Could not transfer. */
1963                         retval = -1;
1964                 }
1965         }
1966         if (bridged && retval) {
1967                 /* Restore HOLD on held calls because masquerade failed. */
1968                 if (call_1_held) {
1969                         ast_queue_control(call_1_ast, AST_CONTROL_HOLD);
1970                 }
1971                 if (call_2_held) {
1972                         ast_queue_control(call_2_ast, AST_CONTROL_HOLD);
1973                 }
1974         }
1975
1976         ast_channel_unlock(call_1_ast);
1977         ast_channel_unlock(call_2_ast);
1978         sig_pri_unlock_private(pri->pvts[call_1_chanpos]);
1979         sig_pri_unlock_private(pri->pvts[call_2_chanpos]);
1980
1981         return retval;
1982 }
1983 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
1984
1985 #if defined(HAVE_PRI_CCSS)
1986 /*!
1987  * \internal
1988  * \brief Compare the CC agent private data by libpri cc_id.
1989  * \since 1.8
1990  *
1991  * \param obj pointer to the (user-defined part) of an object.
1992  * \param arg callback argument from ao2_callback()
1993  * \param flags flags from ao2_callback()
1994  *
1995  * \return values are a combination of enum _cb_results.
1996  */
1997 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
1998 {
1999         struct ast_cc_agent *agent_1 = obj;
2000         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2001         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2002
2003         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2004                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2005 }
2006 #endif  /* defined(HAVE_PRI_CCSS) */
2007
2008 #if defined(HAVE_PRI_CCSS)
2009 /*!
2010  * \internal
2011  * \brief Find the CC agent by libpri cc_id.
2012  * \since 1.8
2013  *
2014  * \param pri sig_pri PRI control structure.
2015  * \param cc_id CC record ID to find.
2016  *
2017  * \note
2018  * Since agents are refcounted, and this function returns
2019  * a reference to the agent, it is imperative that you decrement
2020  * the refcount of the agent once you have finished using it.
2021  *
2022  * \retval agent on success.
2023  * \retval NULL not found.
2024  */
2025 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2026 {
2027         struct sig_pri_cc_agent_prv finder = {
2028                 .pri = pri,
2029                 .cc_id = cc_id,
2030         };
2031
2032         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2033                 sig_pri_cc_type_name);
2034 }
2035 #endif  /* defined(HAVE_PRI_CCSS) */
2036
2037 #if defined(HAVE_PRI_CCSS)
2038 /*!
2039  * \internal
2040  * \brief Compare the CC monitor instance by libpri cc_id.
2041  * \since 1.8
2042  *
2043  * \param obj pointer to the (user-defined part) of an object.
2044  * \param arg callback argument from ao2_callback()
2045  * \param flags flags from ao2_callback()
2046  *
2047  * \return values are a combination of enum _cb_results.
2048  */
2049 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2050 {
2051         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2052         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2053
2054         return (monitor_1->pri == monitor_2->pri
2055                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2056 }
2057 #endif  /* defined(HAVE_PRI_CCSS) */
2058
2059 #if defined(HAVE_PRI_CCSS)
2060 /*!
2061  * \internal
2062  * \brief Find the CC monitor instance by libpri cc_id.
2063  * \since 1.8
2064  *
2065  * \param pri sig_pri PRI control structure.
2066  * \param cc_id CC record ID to find.
2067  *
2068  * \note
2069  * Since monitor_instances are refcounted, and this function returns
2070  * a reference to the instance, it is imperative that you decrement
2071  * the refcount of the instance once you have finished using it.
2072  *
2073  * \retval monitor_instance on success.
2074  * \retval NULL not found.
2075  */
2076 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2077 {
2078         struct sig_pri_cc_monitor_instance finder = {
2079                 .pri = pri,
2080                 .cc_id = cc_id,
2081         };
2082
2083         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2084 }
2085 #endif  /* defined(HAVE_PRI_CCSS) */
2086
2087 #if defined(HAVE_PRI_CCSS)
2088 /*!
2089  * \internal
2090  * \brief Destroy the given monitor instance.
2091  * \since 1.8
2092  *
2093  * \param data Monitor instance to destroy.
2094  *
2095  * \return Nothing
2096  */
2097 static void sig_pri_cc_monitor_instance_destroy(void *data)
2098 {
2099         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2100
2101         if (monitor_instance->cc_id != -1) {
2102                 ast_mutex_lock(&monitor_instance->pri->lock);
2103                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2104                 ast_mutex_unlock(&monitor_instance->pri->lock);
2105         }
2106         monitor_instance->pri->calls->module_unref();
2107 }
2108 #endif  /* defined(HAVE_PRI_CCSS) */
2109
2110 #if defined(HAVE_PRI_CCSS)
2111 /*!
2112  * \internal
2113  * \brief Construct a new monitor instance.
2114  * \since 1.8
2115  *
2116  * \param core_id CC core ID.
2117  * \param pri sig_pri PRI control structure.
2118  * \param cc_id CC record ID.
2119  * \param device_name Name of device (Asterisk channel name less sequence number).
2120  *
2121  * \note
2122  * Since monitor_instances are refcounted, and this function returns
2123  * a reference to the instance, it is imperative that you decrement
2124  * the refcount of the instance once you have finished using it.
2125  *
2126  * \retval monitor_instance on success.
2127  * \retval NULL on error.
2128  */
2129 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)
2130 {
2131         struct sig_pri_cc_monitor_instance *monitor_instance;
2132
2133         if (!pri->calls->module_ref || !pri->calls->module_unref) {
2134                 return NULL;
2135         }
2136
2137         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2138                 sig_pri_cc_monitor_instance_destroy);
2139         if (!monitor_instance) {
2140                 return NULL;
2141         }
2142
2143         monitor_instance->cc_id = cc_id;
2144         monitor_instance->pri = pri;
2145         monitor_instance->core_id = core_id;
2146         strcpy(monitor_instance->name, device_name);
2147
2148         pri->calls->module_ref();
2149
2150         ao2_link(sig_pri_cc_monitors, monitor_instance);
2151         return monitor_instance;
2152 }
2153 #endif  /* defined(HAVE_PRI_CCSS) */
2154
2155 #if defined(HAVE_PRI_CCSS)
2156 /*!
2157  * \internal
2158  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2159  * \since 1.8
2160  *
2161  * \param pri sig_pri PRI control structure.
2162  * \param chanpos Channel position in the span.
2163  * \param cc_id CC record ID.
2164  * \param service CCBS/CCNR indication.
2165  *
2166  * \note Assumes the pri->lock is already obtained.
2167  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2168  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2169  *
2170  * \retval 0 on success.
2171  * \retval -1 on error.
2172  */
2173 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2174 {
2175         struct sig_pri_chan *pvt;
2176         struct ast_cc_config_params *cc_params;
2177         struct sig_pri_cc_monitor_instance *monitor;
2178         enum ast_cc_monitor_policies monitor_policy;
2179         int core_id;
2180         int res;
2181         char device_name[AST_CHANNEL_NAME];
2182         char dialstring[AST_CHANNEL_NAME];
2183
2184         pvt = pri->pvts[chanpos];
2185
2186         core_id = ast_cc_get_current_core_id(pvt->owner);
2187         if (core_id == -1) {
2188                 return -1;
2189         }
2190
2191         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2192         if (!cc_params) {
2193                 return -1;
2194         }
2195
2196         res = -1;
2197         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2198         switch (monitor_policy) {
2199         case AST_CC_MONITOR_NEVER:
2200                 /* CCSS is not enabled. */
2201                 break;
2202         case AST_CC_MONITOR_NATIVE:
2203         case AST_CC_MONITOR_ALWAYS:
2204                 /*
2205                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2206                  * later in the call to sig_pri_cc_generic_check().
2207                  */
2208                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2209                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2210                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2211                 if (!monitor) {
2212                         break;
2213                 }
2214                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2215                         monitor);
2216                 if (res) {
2217                         monitor->cc_id = -1;
2218                         ao2_unlink(sig_pri_cc_monitors, monitor);
2219                         ao2_ref(monitor, -1);
2220                 }
2221                 break;
2222         case AST_CC_MONITOR_GENERIC:
2223                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2224                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2225                 /* Say it failed to force caller to cancel native CC. */
2226                 break;
2227         }
2228         return res;
2229 }
2230 #endif  /* defined(HAVE_PRI_CCSS) */
2231
2232 /*!
2233  * \internal
2234  * \brief Check if generic CC monitor is needed and request it.
2235  * \since 1.8
2236  *
2237  * \param pri sig_pri PRI control structure.
2238  * \param chanpos Channel position in the span.
2239  * \param service CCBS/CCNR indication.
2240  *
2241  * \note Assumes the pri->lock is already obtained.
2242  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2243  *
2244  * \return Nothing
2245  */
2246 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
2247 {
2248         struct ast_channel *owner;
2249         struct ast_cc_config_params *cc_params;
2250 #if defined(HAVE_PRI_CCSS)
2251         struct ast_cc_monitor *monitor;
2252         char device_name[AST_CHANNEL_NAME];
2253 #endif  /* defined(HAVE_PRI_CCSS) */
2254         enum ast_cc_monitor_policies monitor_policy;
2255         int core_id;
2256
2257         if (!pri->pvts[chanpos]->outgoing) {
2258                 /* This is not an outgoing call so it cannot be CC monitor. */
2259                 return;
2260         }
2261
2262         sig_pri_lock_owner(pri, chanpos);
2263         owner = pri->pvts[chanpos]->owner;
2264         if (!owner) {
2265                 return;
2266         }
2267         core_id = ast_cc_get_current_core_id(owner);
2268         if (core_id == -1) {
2269                 /* No CC core setup */
2270                 goto done;
2271         }
2272
2273         cc_params = ast_channel_get_cc_config_params(owner);
2274         if (!cc_params) {
2275                 /* Could not get CC config parameters. */
2276                 goto done;
2277         }
2278
2279 #if defined(HAVE_PRI_CCSS)
2280         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
2281         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
2282         if (monitor) {
2283                 /* CC monitor is already present so no need for generic CC. */
2284                 ao2_ref(monitor, -1);
2285                 goto done;
2286         }
2287 #endif  /* defined(HAVE_PRI_CCSS) */
2288
2289         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2290         switch (monitor_policy) {
2291         case AST_CC_MONITOR_NEVER:
2292                 /* CCSS is not enabled. */
2293                 break;
2294         case AST_CC_MONITOR_NATIVE:
2295                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2296                         /* Request generic CC monitor. */
2297                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2298                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2299                 }
2300                 break;
2301         case AST_CC_MONITOR_ALWAYS:
2302                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2303                         /*
2304                          * Cannot monitor PTMP TE side since this is not defined.
2305                          * We are playing the roll of a phone in this case and
2306                          * a phone cannot monitor a party over the network without
2307                          * protocol help.
2308                          */
2309                         break;
2310                 }
2311                 /*
2312                  * We are either falling back or this is a PTMP NT span.
2313                  * Request generic CC monitor.
2314                  */
2315                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2316                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2317                 break;
2318         case AST_CC_MONITOR_GENERIC:
2319                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2320                         /* Request generic CC monitor. */
2321                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2322                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2323                 }
2324                 break;
2325         }
2326
2327 done:
2328         ast_channel_unlock(owner);
2329 }
2330
2331 #if defined(HAVE_PRI_CCSS)
2332 /*!
2333  * \internal
2334  * \brief The CC link canceled the CC instance.
2335  * \since 1.8
2336  *
2337  * \param pri sig_pri PRI control structure.
2338  * \param cc_id CC record ID.
2339  * \param is_agent TRUE if the cc_id is for an agent.
2340  *
2341  * \return Nothing
2342  */
2343 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
2344 {
2345         if (is_agent) {
2346                 struct ast_cc_agent *agent;
2347
2348                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2349                 if (!agent) {
2350                         return;
2351                 }
2352                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2353                         sig_pri_cc_type_name);
2354                 ao2_ref(agent, -1);
2355         } else {
2356                 struct sig_pri_cc_monitor_instance *monitor;
2357
2358                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2359                 if (!monitor) {
2360                         return;
2361                 }
2362                 monitor->cc_id = -1;
2363                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2364                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2365                 ao2_ref(monitor, -1);
2366         }
2367 }
2368 #endif  /* defined(HAVE_PRI_CCSS) */
2369
2370 #if defined(HAVE_PRI_AOC_EVENTS)
2371 /*!
2372  * \internal
2373  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2374  * \since 1.8
2375  *
2376  * \param value Value to convert to string.
2377  *
2378  * \return PRI_AOC_CHARGED_ITEM
2379  */
2380 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2381 {
2382         switch (value) {
2383         case AST_AOC_CHARGED_ITEM_NA:
2384                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2385         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2386                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2387         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2388                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2389         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2390                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2391         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2392                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2393         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2394                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2395         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2396                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2397         }
2398         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2399 }
2400 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2401
2402 #if defined(HAVE_PRI_AOC_EVENTS)
2403 /*!
2404  * \internal
2405  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2406  * \since 1.8
2407  *
2408  * \param value Value to convert to string.
2409  *
2410  * \return ast_aoc_charged_item
2411  */
2412 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2413 {
2414         switch (value) {
2415         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2416                 return AST_AOC_CHARGED_ITEM_NA;
2417         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2418                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2419         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2420                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2421         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2422                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2423         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2424                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2425         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2426                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2427         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2428                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2429         }
2430         return AST_AOC_CHARGED_ITEM_NA;
2431 }
2432 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2433
2434 #if defined(HAVE_PRI_AOC_EVENTS)
2435 /*!
2436  * \internal
2437  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2438  * \since 1.8
2439  *
2440  * \return pri enum equivalent.
2441  */
2442 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2443 {
2444         switch (mult) {
2445         case AST_AOC_MULT_ONETHOUSANDTH:
2446                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2447         case AST_AOC_MULT_ONEHUNDREDTH:
2448                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2449         case AST_AOC_MULT_ONETENTH:
2450                 return PRI_AOC_MULTIPLIER_TENTH;
2451         case AST_AOC_MULT_ONE:
2452                 return PRI_AOC_MULTIPLIER_ONE;
2453         case AST_AOC_MULT_TEN:
2454                 return PRI_AOC_MULTIPLIER_TEN;
2455         case AST_AOC_MULT_HUNDRED:
2456                 return PRI_AOC_MULTIPLIER_HUNDRED;
2457         case AST_AOC_MULT_THOUSAND:
2458                 return PRI_AOC_MULTIPLIER_THOUSAND;
2459         default:
2460                 return PRI_AOC_MULTIPLIER_ONE;
2461         }
2462 }
2463 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2464
2465 #if defined(HAVE_PRI_AOC_EVENTS)
2466 /*!
2467  * \internal
2468  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2469  * \since 1.8
2470  *
2471  * \return ast enum equivalent.
2472  */
2473 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2474 {
2475         switch (mult) {
2476         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2477                 return AST_AOC_MULT_ONETHOUSANDTH;
2478         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2479                 return AST_AOC_MULT_ONEHUNDREDTH;
2480         case PRI_AOC_MULTIPLIER_TENTH:
2481                 return AST_AOC_MULT_ONETENTH;
2482         case PRI_AOC_MULTIPLIER_ONE:
2483                 return AST_AOC_MULT_ONE;
2484         case PRI_AOC_MULTIPLIER_TEN:
2485                 return AST_AOC_MULT_TEN;
2486         case PRI_AOC_MULTIPLIER_HUNDRED:
2487                 return AST_AOC_MULT_HUNDRED;
2488         case PRI_AOC_MULTIPLIER_THOUSAND:
2489                 return AST_AOC_MULT_THOUSAND;
2490         default:
2491                 return AST_AOC_MULT_ONE;
2492         }
2493 }
2494 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2495
2496 #if defined(HAVE_PRI_AOC_EVENTS)
2497 /*!
2498  * \internal
2499  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
2500  * \since 1.8
2501  *
2502  * \param value Value to convert to ast representation
2503  *
2504  * \return PRI_AOC_TIME_SCALE
2505  */
2506 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
2507 {
2508         switch (value) {
2509         default:
2510         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2511                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2512         case AST_AOC_TIME_SCALE_TENTH_SECOND:
2513                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
2514         case AST_AOC_TIME_SCALE_SECOND:
2515                 return PRI_AOC_TIME_SCALE_SECOND;
2516         case AST_AOC_TIME_SCALE_TEN_SECOND:
2517                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
2518         case AST_AOC_TIME_SCALE_MINUTE:
2519                 return PRI_AOC_TIME_SCALE_MINUTE;
2520         case AST_AOC_TIME_SCALE_HOUR:
2521                 return PRI_AOC_TIME_SCALE_HOUR;
2522         case AST_AOC_TIME_SCALE_DAY:
2523                 return PRI_AOC_TIME_SCALE_DAY;
2524         }
2525 }
2526 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2527
2528 #if defined(HAVE_PRI_AOC_EVENTS)
2529 /*!
2530  * \internal
2531  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
2532  * \since 1.8
2533  *
2534  * \param value Value to convert to ast representation
2535  *
2536  * \return ast aoc time scale
2537  */
2538 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
2539 {
2540         switch (value) {
2541         default:
2542         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
2543                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2544         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
2545                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
2546         case PRI_AOC_TIME_SCALE_SECOND:
2547                 return AST_AOC_TIME_SCALE_SECOND;
2548         case PRI_AOC_TIME_SCALE_TEN_SECOND:
2549                 return AST_AOC_TIME_SCALE_TEN_SECOND;
2550         case PRI_AOC_TIME_SCALE_MINUTE:
2551                 return AST_AOC_TIME_SCALE_MINUTE;
2552         case PRI_AOC_TIME_SCALE_HOUR:
2553                 return AST_AOC_TIME_SCALE_HOUR;
2554         case PRI_AOC_TIME_SCALE_DAY:
2555                 return AST_AOC_TIME_SCALE_DAY;
2556         }
2557         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
2558 }
2559 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2560
2561 #if defined(HAVE_PRI_AOC_EVENTS)
2562 /*!
2563  * \internal
2564  * \brief Handle AOC-S control frame
2565  * \since 1.8
2566  *
2567  * \param aoc_s AOC-S event parameters.
2568  * \param owner Asterisk channel associated with the call.
2569  * \param passthrough indicating if this message should be queued on the ast channel
2570  *
2571  * \note Assumes the pri->lock is already obtained.
2572  * \note Assumes the sig_pri private is locked
2573  * \note Assumes the owner channel lock is already obtained.
2574  *
2575  * \return Nothing
2576  */
2577 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
2578 {
2579         struct ast_aoc_decoded *decoded = NULL;
2580         struct ast_aoc_encoded *encoded = NULL;
2581         size_t encoded_size = 0;
2582         int idx;
2583
2584         if (!owner || !aoc_s) {
2585                 return;
2586         }
2587
2588         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
2589                 return;
2590         }
2591
2592         for (idx = 0; idx < aoc_s->num_items; ++idx) {
2593                 enum ast_aoc_s_charged_item charged_item;
2594
2595                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
2596                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
2597                         /* Delete the unknown charged item from the list. */
2598                         continue;
2599                 }
2600                 switch (aoc_s->item[idx].rate_type) {
2601                 case PRI_AOC_RATE_TYPE_DURATION:
2602                         ast_aoc_s_add_rate_duration(decoded,
2603                                 charged_item,
2604                                 aoc_s->item[idx].rate.duration.amount.cost,
2605                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
2606                                 aoc_s->item[idx].rate.duration.currency,
2607                                 aoc_s->item[idx].rate.duration.time.length,
2608                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
2609                                 aoc_s->item[idx].rate.duration.granularity.length,
2610                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
2611                                 aoc_s->item[idx].rate.duration.charging_type);
2612                         break;
2613                 case PRI_AOC_RATE_TYPE_FLAT:
2614                         ast_aoc_s_add_rate_flat(decoded,
2615                                 charged_item,
2616                                 aoc_s->item[idx].rate.flat.amount.cost,
2617                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
2618                                 aoc_s->item[idx].rate.flat.currency);
2619                         break;
2620                 case PRI_AOC_RATE_TYPE_VOLUME:
2621                         ast_aoc_s_add_rate_volume(decoded,
2622                                 charged_item,
2623                                 aoc_s->item[idx].rate.volume.unit,
2624                                 aoc_s->item[idx].rate.volume.amount.cost,
2625                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
2626                                 aoc_s->item[idx].rate.volume.currency);
2627                         break;
2628                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
2629                         ast_aoc_s_add_rate_special_charge_code(decoded,
2630                                 charged_item,
2631                                 aoc_s->item[idx].rate.special);
2632                         break;
2633                 case PRI_AOC_RATE_TYPE_FREE:
2634                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
2635                         break;
2636                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
2637                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
2638                         break;
2639                 default:
2640                         ast_aoc_s_add_rate_na(decoded, charged_item);
2641                         break;
2642                 }
2643         }
2644
2645         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2646                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2647         }
2648
2649         ast_aoc_manager_event(decoded, owner);
2650
2651         ast_aoc_destroy_decoded(decoded);
2652         ast_aoc_destroy_encoded(encoded);
2653 }
2654 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2655
2656 #if defined(HAVE_PRI_AOC_EVENTS)
2657 /*!
2658  * \internal
2659  * \brief Generate AOC Request Response
2660  * \since 1.8
2661  *
2662  * \param aoc_request
2663  *
2664  * \note Assumes the pri->lock is already obtained.
2665  * \note Assumes the sig_pri private is locked
2666  * \note Assumes the owner channel lock is already obtained.
2667  *
2668  * \return Nothing
2669  */
2670 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
2671 {
2672         int request;
2673
2674         if (!aoc_request) {
2675                 return;
2676         }
2677
2678         request = aoc_request->charging_request;
2679
2680         if (request & PRI_AOC_REQUEST_S) {
2681                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
2682                         /* An AOC-S response must come from the other side, so save off this invoke_id
2683                          * and see if an AOC-S message comes in before the call is answered. */
2684                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
2685                         pvt->aoc_s_request_invoke_id_valid = 1;
2686
2687                 } else {
2688                         pri_aoc_s_request_response_send(pvt->pri->pri,
2689                                 call,
2690                                 aoc_request->invoke_id,
2691                                 NULL);
2692                 }
2693         }
2694
2695         if (request & PRI_AOC_REQUEST_D) {
2696                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
2697                         pri_aoc_de_request_response_send(pvt->pri->pri,
2698                                 call,
2699                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2700                                 aoc_request->invoke_id);
2701                 } else {
2702                         pri_aoc_de_request_response_send(pvt->pri->pri,
2703                                 call,
2704                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2705                                 aoc_request->invoke_id);
2706                 }
2707         }
2708
2709         if (request & PRI_AOC_REQUEST_E) {
2710                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
2711                         pri_aoc_de_request_response_send(pvt->pri->pri,
2712                                 call,
2713                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
2714                                 aoc_request->invoke_id);
2715                 } else {
2716                         pri_aoc_de_request_response_send(pvt->pri->pri,
2717                                 call,
2718                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
2719                                 aoc_request->invoke_id);
2720                 }
2721         }
2722 }
2723 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2724
2725 #if defined(HAVE_PRI_AOC_EVENTS)
2726 /*!
2727  * \internal
2728  * \brief Generate AOC-D AST_CONTROL_AOC frame
2729  * \since 1.8
2730  *
2731  * \param aoc_e AOC-D event parameters.
2732  * \param owner Asterisk channel associated with the call.
2733  * \param passthrough indicating if this message should be queued on the ast channel
2734  *
2735  * \note Assumes the pri->lock is already obtained.
2736  * \note Assumes the sig_pri private is locked
2737  * \note Assumes the owner channel lock is already obtained.
2738  *
2739  * \return Nothing
2740  */
2741 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
2742 {
2743         struct ast_aoc_decoded *decoded = NULL;
2744         struct ast_aoc_encoded *encoded = NULL;
2745         size_t encoded_size = 0;
2746         enum ast_aoc_charge_type type;
2747
2748         if (!owner || !aoc_d) {
2749                 return;
2750         }
2751
2752         switch (aoc_d->charge) {
2753         case PRI_AOC_DE_CHARGE_CURRENCY:
2754                 type = AST_AOC_CHARGE_CURRENCY;
2755                 break;
2756         case PRI_AOC_DE_CHARGE_UNITS:
2757                 type = AST_AOC_CHARGE_UNIT;
2758                 break;
2759         case PRI_AOC_DE_CHARGE_FREE:
2760                 type = AST_AOC_CHARGE_FREE;
2761                 break;
2762         default:
2763                 type = AST_AOC_CHARGE_NA;
2764                 break;
2765         }
2766
2767         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
2768                 return;
2769         }
2770
2771         switch (aoc_d->billing_accumulation) {
2772         default:
2773                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
2774                         aoc_d->billing_accumulation);
2775                 /* Fall through */
2776         case 0:/* subTotal */
2777                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
2778                 break;
2779         case 1:/* total */
2780                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
2781                 break;
2782         }
2783
2784         switch (aoc_d->billing_id) {
2785         case PRI_AOC_D_BILLING_ID_NORMAL:
2786                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2787                 break;
2788         case PRI_AOC_D_BILLING_ID_REVERSE:
2789                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2790                 break;
2791         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
2792                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2793                 break;
2794         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
2795         default:
2796                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2797                 break;
2798         }
2799
2800         switch (aoc_d->charge) {
2801         case PRI_AOC_DE_CHARGE_CURRENCY:
2802                 ast_aoc_set_currency_info(decoded,
2803                         aoc_d->recorded.money.amount.cost,
2804                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
2805                         aoc_d->recorded.money.currency);
2806                 break;
2807         case PRI_AOC_DE_CHARGE_UNITS:
2808                 {
2809                         int i;
2810                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
2811                                 /* if type or number are negative, then they are not present */
2812                                 ast_aoc_add_unit_entry(decoded,
2813                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
2814                                         aoc_d->recorded.unit.item[i].number,
2815                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
2816                                         aoc_d->recorded.unit.item[i].type);
2817                         }
2818                 }
2819                 break;
2820         }
2821
2822         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2823                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2824         }
2825
2826         ast_aoc_manager_event(decoded, owner);
2827
2828         ast_aoc_destroy_decoded(decoded);
2829         ast_aoc_destroy_encoded(encoded);
2830 }
2831 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2832
2833 #if defined(HAVE_PRI_AOC_EVENTS)
2834 /*!
2835  * \internal
2836  * \brief Generate AOC-E AST_CONTROL_AOC frame
2837  * \since 1.8
2838  *
2839  * \param aoc_e AOC-E event parameters.
2840  * \param owner Asterisk channel associated with the call.
2841  * \param passthrough indicating if this message should be queued on the ast channel
2842  *
2843  * \note Assumes the pri->lock is already obtained.
2844  * \note Assumes the sig_pri private is locked
2845  * \note Assumes the owner channel lock is already obtained.
2846  * \note owner channel may be NULL. In that case, generate event only
2847  *
2848  * \return Nothing
2849  */
2850 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
2851 {
2852         struct ast_aoc_decoded *decoded = NULL;
2853         struct ast_aoc_encoded *encoded = NULL;
2854         size_t encoded_size = 0;
2855         enum ast_aoc_charge_type type;
2856
2857         if (!aoc_e) {
2858                 return;
2859         }
2860
2861         switch (aoc_e->charge) {
2862         case PRI_AOC_DE_CHARGE_CURRENCY:
2863                 type = AST_AOC_CHARGE_CURRENCY;
2864                 break;
2865         case PRI_AOC_DE_CHARGE_UNITS:
2866                 type = AST_AOC_CHARGE_UNIT;
2867                 break;
2868         case PRI_AOC_DE_CHARGE_FREE:
2869                 type = AST_AOC_CHARGE_FREE;
2870                 break;
2871         default:
2872                 type = AST_AOC_CHARGE_NA;
2873                 break;
2874         }
2875
2876         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
2877                 return;
2878         }
2879
2880         switch (aoc_e->associated.charging_type) {
2881         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
2882                 if (!aoc_e->associated.charge.number.valid) {
2883                         break;
2884                 }
2885                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
2886                 break;
2887         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
2888                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
2889                 break;
2890         default:
2891                 break;
2892         }
2893
2894         switch (aoc_e->billing_id) {
2895         case PRI_AOC_E_BILLING_ID_NORMAL:
2896                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
2897                 break;
2898         case PRI_AOC_E_BILLING_ID_REVERSE:
2899                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
2900                 break;
2901         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
2902                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
2903                 break;
2904         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
2905                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
2906                 break;
2907         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
2908                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
2909                 break;
2910         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
2911                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
2912                 break;
2913         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
2914                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
2915                 break;
2916         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
2917                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
2918                 break;
2919         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
2920         default:
2921                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
2922                 break;
2923         }
2924
2925         switch (aoc_e->charge) {
2926         case PRI_AOC_DE_CHARGE_CURRENCY:
2927                 ast_aoc_set_currency_info(decoded,
2928                         aoc_e->recorded.money.amount.cost,
2929                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
2930                         aoc_e->recorded.money.currency);
2931                 break;
2932         case PRI_AOC_DE_CHARGE_UNITS:
2933                 {
2934                         int i;
2935                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
2936                                 /* if type or number are negative, then they are not present */
2937                                 ast_aoc_add_unit_entry(decoded,
2938                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
2939                                         aoc_e->recorded.unit.item[i].number,
2940                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
2941                                         aoc_e->recorded.unit.item[i].type);
2942                         }
2943                 }
2944         }
2945
2946         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
2947                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
2948         }
2949
2950         ast_aoc_manager_event(decoded, owner);
2951
2952         ast_aoc_destroy_decoded(decoded);
2953         ast_aoc_destroy_encoded(encoded);
2954 }
2955 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2956
2957 #if defined(HAVE_PRI_AOC_EVENTS)
2958 /*!
2959  * \internal
2960  * \brief send an AOC-S message on the current call
2961  *
2962  * \param pvt sig_pri private channel structure.
2963  * \param generic decoded ast AOC message
2964  *
2965  * \return Nothing
2966  *
2967  * \note Assumes that the PRI lock is already obtained.
2968  */
2969 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
2970 {
2971         struct pri_subcmd_aoc_s aoc_s = { 0, };
2972         const struct ast_aoc_s_entry *entry;
2973         int idx;
2974
2975         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
2976                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
2977                         break;
2978                 }
2979
2980                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
2981
2982                 switch (entry->rate_type) {
2983                 case AST_AOC_RATE_TYPE_DURATION:
2984                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
2985                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
2986                         aoc_s.item[idx].rate.duration.amount.multiplier =
2987                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
2988                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
2989                         aoc_s.item[idx].rate.duration.time.scale =
2990                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
2991                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
2992                         aoc_s.item[idx].rate.duration.granularity.scale =
2993                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
2994                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
2995
2996                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
2997                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
2998                                         entry->rate.duration.currency_name,
2999                                         sizeof(aoc_s.item[idx].rate.duration.currency));
3000                         }
3001                         break;
3002                 case AST_AOC_RATE_TYPE_FLAT:
3003                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
3004                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
3005                         aoc_s.item[idx].rate.flat.amount.multiplier =
3006                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
3007
3008                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
3009                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
3010                                         entry->rate.flat.currency_name,
3011                                         sizeof(aoc_s.item[idx].rate.flat.currency));
3012                         }
3013                         break;
3014                 case AST_AOC_RATE_TYPE_VOLUME:
3015                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
3016                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
3017                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
3018                         aoc_s.item[idx].rate.volume.amount.multiplier =
3019                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
3020
3021                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
3022                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
3023                                         entry->rate.volume.currency_name,
3024                                         sizeof(aoc_s.item[idx].rate.volume.currency));
3025                         }
3026                         break;
3027                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
3028                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
3029                         aoc_s.item[idx].rate.special = entry->rate.special_code;
3030                         break;
3031                 case AST_AOC_RATE_TYPE_FREE:
3032                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
3033                         break;
3034                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3035                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
3036                         break;
3037                 default:
3038                 case AST_AOC_RATE_TYPE_NA:
3039                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
3040                         break;
3041                 }
3042         }
3043         aoc_s.num_items = idx;
3044
3045         /* if this rate should be sent as a response to an AOC-S request we will
3046          * have an aoc_s_request_invoke_id associated with this pvt */
3047         if (pvt->aoc_s_request_invoke_id_valid) {
3048                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
3049                 pvt->aoc_s_request_invoke_id_valid = 0;
3050         } else {
3051                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
3052         }
3053 }
3054 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3055
3056 #if defined(HAVE_PRI_AOC_EVENTS)
3057 /*!
3058  * \internal
3059  * \brief send an AOC-D message on the current call
3060  *
3061  * \param pvt sig_pri private channel structure.
3062  * \param generic decoded ast AOC message
3063  *
3064  * \return Nothing
3065  *
3066  * \note Assumes that the PRI lock is already obtained.
3067  */
3068 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3069 {
3070         struct pri_subcmd_aoc_d aoc_d = { 0, };
3071
3072         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
3073
3074         switch (ast_aoc_get_billing_id(decoded)) {
3075         case AST_AOC_BILLING_NORMAL:
3076                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
3077                 break;
3078         case AST_AOC_BILLING_REVERSE_CHARGE:
3079                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
3080                 break;
3081         case AST_AOC_BILLING_CREDIT_CARD:
3082                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
3083                 break;
3084         case AST_AOC_BILLING_NA:
3085         default:
3086                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
3087                 break;
3088         }
3089
3090         switch (ast_aoc_get_charge_type(decoded)) {
3091         case AST_AOC_CHARGE_FREE:
3092                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
3093                 break;
3094         case AST_AOC_CHARGE_CURRENCY:
3095                 {
3096                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3097                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
3098                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3099                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3100                         if (!ast_strlen_zero(currency_name)) {
3101                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
3102                         }
3103                 }
3104                 break;
3105         case AST_AOC_CHARGE_UNIT:
3106                 {
3107                         const struct ast_aoc_unit_entry *entry;
3108                         int i;
3109                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
3110                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3111                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
3112                                         if (entry->valid_amount) {
3113                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
3114                                         } else {
3115                                                 aoc_d.recorded.unit.item[i].number = -1;
3116                                         }
3117                                         if (entry->valid_type) {
3118                                                 aoc_d.recorded.unit.item[i].type = entry->type;
3119                                         } else {
3120                                                 aoc_d.recorded.unit.item[i].type = -1;
3121                                         }
3122                                         aoc_d.recorded.unit.num_items++;
3123                                 } else {
3124                                         break;
3125                                 }
3126                         }
3127                 }
3128                 break;
3129         case AST_AOC_CHARGE_NA:
3130         default:
3131                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3132                 break;
3133         }
3134
3135         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
3136 }
3137 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3138
3139 #if defined(HAVE_PRI_AOC_EVENTS)
3140 /*!
3141  * \internal
3142  * \brief send an AOC-E message on the current call
3143  *
3144  * \param pvt sig_pri private channel structure.
3145  * \param generic decoded ast AOC message
3146  *
3147  * \return Nothing
3148  *
3149  * \note Assumes that the PRI lock is already obtained.
3150  */
3151 static void sig_pri_aoc_e_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3152 {
3153         struct pri_subcmd_aoc_e *aoc_e = &pvt->aoc_e;
3154         const struct ast_aoc_charging_association *ca = ast_aoc_get_association_info(decoded);
3155
3156         memset(aoc_e, 0, sizeof(*aoc_e));
3157         pvt->holding_aoce = 1;
3158
3159         switch (ca->charging_type) {
3160         case AST_AOC_CHARGING_ASSOCIATION_NUMBER:
3161                 aoc_e->associated.charge.number.valid = 1;
3162                 ast_copy_string(aoc_e->associated.charge.number.str,
3163                         ca->charge.number.number,
3164                         sizeof(aoc_e->associated.charge.number.str));
3165                 aoc_e->associated.charge.number.plan = ca->charge.number.plan;
3166                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER;
3167                 break;
3168         case AST_AOC_CHARGING_ASSOCIATION_ID:
3169                 aoc_e->associated.charge.id = ca->charge.id;
3170                 aoc_e->associated.charging_type = PRI_AOC_E_CHARGING_ASSOCIATION_ID;
3171                 break;
3172         case AST_AOC_CHARGING_ASSOCIATION_NA:
3173         default:
3174                 break;
3175         }
3176
3177         switch (ast_aoc_get_billing_id(decoded)) {
3178         case AST_AOC_BILLING_NORMAL:
3179                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NORMAL;
3180                 break;
3181         case AST_AOC_BILLING_REVERSE_CHARGE:
3182                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_REVERSE;
3183                 break;
3184         case AST_AOC_BILLING_CREDIT_CARD:
3185                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CREDIT_CARD;
3186                 break;
3187         case AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL:
3188                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL;
3189                 break;
3190         case AST_AOC_BILLING_CALL_FWD_BUSY:
3191                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY;
3192                 break;
3193         case AST_AOC_BILLING_CALL_FWD_NO_REPLY:
3194                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY;
3195                 break;
3196         case AST_AOC_BILLING_CALL_DEFLECTION:
3197                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_DEFLECTION;
3198                 break;
3199         case AST_AOC_BILLING_CALL_TRANSFER:
3200                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_CALL_TRANSFER;
3201                 break;
3202         case AST_AOC_BILLING_NA:
3203         default:
3204                 aoc_e->billing_id = PRI_AOC_E_BILLING_ID_NOT_AVAILABLE;
3205                 break;
3206         }
3207
3208         switch (ast_aoc_get_charge_type(decoded)) {
3209         case AST_AOC_CHARGE_FREE:
3210                 aoc_e->charge = PRI_AOC_DE_CHARGE_FREE;
3211                 break;
3212         case AST_AOC_CHARGE_CURRENCY:
3213                 {
3214                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3215                         aoc_e->charge = PRI_AOC_DE_CHARGE_CURRENCY;
3216                         aoc_e->recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3217                         aoc_e->recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3218                         if (!ast_strlen_zero(currency_name)) {
3219                                 ast_copy_string(aoc_e->recorded.money.currency, currency_name, sizeof(aoc_e->recorded.money.currency));
3220                         }
3221                 }
3222                 break;
3223         case AST_AOC_CHARGE_UNIT:
3224                 {
3225                         const struct ast_aoc_unit_entry *entry;
3226                         int i;
3227                         aoc_e->charge = PRI_AOC_DE_CHARGE_UNITS;
3228                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3229                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_e->recorded.unit.item)) {
3230                                         if (entry->valid_amount) {
3231                                                 aoc_e->recorded.unit.item[i].number = entry->amount;
3232                                         } else {
3233                                                 aoc_e->recorded.unit.item[i].number = -1;
3234                                         }
3235                                         if (entry->valid_type) {
3236                                                 aoc_e->recorded.unit.item[i].type = entry->type;
3237                                         } else {
3238                                                 aoc_e->recorded.unit.item[i].type = -1;
3239                                         }
3240                                         aoc_e->recorded.unit.num_items++;
3241                                 }
3242                         }
3243                 }
3244                 break;
3245         case AST_AOC_CHARGE_NA:
3246         default:
3247                 aoc_e->charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3248                 break;
3249         }
3250 }
3251 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3252
3253 #if defined(HAVE_PRI_AOC_EVENTS)
3254 /*!
3255  * \internal
3256  * \brief send an AOC-E termination request on ast_channel and set
3257  * hangup delay.
3258  *
3259  * \param pri sig_pri PRI control structure.
3260  * \param chanpos Channel position in the span.
3261  * \param ms to delay hangup
3262  *
3263  * \note Assumes the pri->lock is already obtained.
3264  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
3265  *
3266  * \return Nothing
3267  */
3268 static void sig_pri_send_aoce_termination_request(struct sig_pri_span *pri, int chanpos, unsigned int ms)
3269 {
3270         struct sig_pri_chan *pvt;
3271         struct ast_aoc_decoded *decoded = NULL;
3272         struct ast_aoc_encoded *encoded = NULL;
3273         size_t encoded_size;
3274         struct timeval whentohangup = { 0, };
3275
3276         sig_pri_lock_owner(pri, chanpos);
3277         pvt = pri->pvts[chanpos];
3278         if (!pvt->owner) {
3279                 return;
3280         }
3281
3282         if (!(decoded = ast_aoc_create(AST_AOC_REQUEST, 0, AST_AOC_REQUEST_E))) {
3283                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3284                 goto cleanup_termination_request;
3285         }
3286
3287         ast_aoc_set_termination_request(decoded);
3288
3289         if (!(encoded = ast_aoc_encode(decoded, &encoded_size, pvt->owner))) {
3290                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3291                 goto cleanup_termination_request;
3292         }
3293
3294         /* convert ms to timeval */
3295         whentohangup.tv_usec = (ms % 1000) * 1000;
3296         whentohangup.tv_sec = ms / 1000;
3297
3298         if (ast_queue_control_data(pvt->owner, AST_CONTROL_AOC, encoded, encoded_size)) {
3299                 ast_softhangup_nolock(pvt->owner, AST_SOFTHANGUP_DEV);
3300                 goto cleanup_termination_request;
3301         }
3302
3303         pvt->waiting_for_aoce = 1;
3304         ast_channel_setwhentohangup_tv(pvt->owner, whentohangup);
3305         ast_log(LOG_DEBUG, "Delaying hangup on %s for aoc-e msg\n", pvt->owner->name);
3306
3307 cleanup_termination_request:
3308         ast_channel_unlock(pvt->owner);
3309         ast_aoc_destroy_decoded(decoded);
3310         ast_aoc_destroy_encoded(encoded);
3311 }
3312 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3313
3314 /*!
3315  * \internal
3316  * \brief TRUE if PRI event came in on a CIS call.
3317  * \since 1.8
3318  *
3319  * \param channel PRI encoded span/channel
3320  *
3321  * \retval non-zero if CIS call.
3322  */
3323 static int sig_pri_is_cis_call(int channel)
3324 {
3325         return channel != -1 && (channel & PRI_CIS_CALL);
3326 }
3327
3328 /*!