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