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