Merge "pjproject: Configurable setting for cnonce to include hyphens or not"
[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  * \return Nothing
1391  */
1392 static void sig_pri_queue_hangup(struct sig_pri_span *pri, int chanpos)
1393 {
1394         if (sig_pri_callbacks.queue_control) {
1395                 sig_pri_callbacks.queue_control(pri->pvts[chanpos]->chan_pvt, AST_CONTROL_HANGUP);
1396         }
1397
1398         sig_pri_lock_owner(pri, chanpos);
1399         if (pri->pvts[chanpos]->owner) {
1400                 ast_queue_hangup(pri->pvts[chanpos]->owner);
1401                 ast_channel_unlock(pri->pvts[chanpos]->owner);
1402         }
1403 }
1404
1405 /*!
1406  * \internal
1407  * \brief Queue a PVT_CAUSE_CODE frame onto the owner channel.
1408  * \since 11
1409  *
1410  * \param pri PRI span control structure.
1411  * \param chanpos Channel position in the span.
1412  * \param cause String describing the cause to be placed into the frame.
1413  *
1414  * \note Assumes the pri->lock is already obtained.
1415  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1416  *
1417  * \return Nothing
1418  */
1419 static void pri_queue_pvt_cause_data(struct sig_pri_span *pri, int chanpos, const char *cause, int ast_cause)
1420 {
1421         struct ast_channel *chan;
1422         struct ast_control_pvt_cause_code *cause_code;
1423
1424         sig_pri_lock_owner(pri, chanpos);
1425         chan = pri->pvts[chanpos]->owner;
1426         if (chan) {
1427                 int datalen = sizeof(*cause_code) + strlen(cause);
1428                 cause_code = ast_alloca(datalen);
1429                 memset(cause_code, 0, datalen);
1430                 cause_code->ast_cause = ast_cause;
1431                 ast_copy_string(cause_code->chan_name, ast_channel_name(chan), AST_CHANNEL_NAME);
1432                 ast_copy_string(cause_code->code, cause, datalen + 1 - sizeof(*cause_code));
1433                 ast_queue_control_data(chan, AST_CONTROL_PVT_CAUSE_CODE, cause_code, datalen);
1434                 ast_channel_hangupcause_hash_set(chan, cause_code, datalen);
1435                 ast_channel_unlock(chan);
1436         }
1437 }
1438
1439 /*!
1440  * \internal
1441  * \brief Find the channel associated with the libpri call.
1442  * \since 10.0
1443  *
1444  * \param pri PRI span control structure.
1445  * \param call LibPRI opaque call pointer to find.
1446  *
1447  * \note Assumes the pri->lock is already obtained.
1448  *
1449  * \retval array-index into private pointer array on success.
1450  * \retval -1 on error.
1451  */
1452 static int pri_find_principle_by_call(struct sig_pri_span *pri, q931_call *call)
1453 {
1454         int idx;
1455
1456         if (!call) {
1457                 /* Cannot find a call without a call. */
1458                 return -1;
1459         }
1460         for (idx = 0; idx < pri->numchans; ++idx) {
1461                 if (pri->pvts[idx] && pri->pvts[idx]->call == call) {
1462                         /* Found the principle */
1463                         return idx;
1464                 }
1465         }
1466         return -1;
1467 }
1468
1469 /*!
1470  * \internal
1471  * \brief Queue the span for destruction
1472  * \since 13.0
1473  *
1474  * \param pri PRI span control structure.
1475  *
1476  * Asks the channel driver to queue the span for destruction at a
1477  * possibly later time, if (e.g.) locking considerations don't allow
1478  * destroying it right now.
1479  *
1480  * \return Nothing
1481  */
1482 static void pri_destroy_later(struct sig_pri_span *pri)
1483 {
1484         if (!sig_pri_callbacks.destroy_later) {
1485                 return;
1486         }
1487         sig_pri_callbacks.destroy_later(pri);
1488 }
1489
1490 /*!
1491  * \internal
1492  * \brief Kill the call.
1493  * \since 10.0
1494  *
1495  * \param pri PRI span control structure.
1496  * \param call LibPRI opaque call pointer to find.
1497  * \param cause Reason call was killed.
1498  *
1499  * \note Assumes the pvt->pri->lock is already obtained.
1500  *
1501  * \return Nothing
1502  */
1503 static void sig_pri_kill_call(struct sig_pri_span *pri, q931_call *call, int cause)
1504 {
1505         int chanpos;
1506
1507         chanpos = pri_find_principle_by_call(pri, call);
1508         if (chanpos < 0) {
1509                 pri_hangup(pri->pri, call, cause);
1510                 return;
1511         }
1512         sig_pri_lock_private(pri->pvts[chanpos]);
1513         if (!pri->pvts[chanpos]->owner) {
1514                 pri_hangup(pri->pri, call, cause);
1515                 pri->pvts[chanpos]->call = NULL;
1516                 sig_pri_unlock_private(pri->pvts[chanpos]);
1517                 sig_pri_span_devstate_changed(pri);
1518                 return;
1519         }
1520         ast_channel_hangupcause_set(pri->pvts[chanpos]->owner, cause);
1521         pri_queue_control(pri, chanpos, AST_CONTROL_HANGUP);
1522         sig_pri_unlock_private(pri->pvts[chanpos]);
1523 }
1524
1525 /*!
1526  * \internal
1527  * \brief Find the private structure for the libpri call.
1528  *
1529  * \param pri PRI span control structure.
1530  * \param channel LibPRI encoded channel ID.
1531  * \param call LibPRI opaque call pointer.
1532  *
1533  * \note Assumes the pri->lock is already obtained.
1534  *
1535  * \retval array-index into private pointer array on success.
1536  * \retval -1 on error.
1537  */
1538 static int pri_find_principle(struct sig_pri_span *pri, int channel, q931_call *call)
1539 {
1540         int x;
1541         int span;
1542         int principle;
1543         int prioffset;
1544
1545         if (channel < 0) {
1546                 /* Channel is not picked yet. */
1547                 return -1;
1548         }
1549
1550         prioffset = PRI_CHANNEL(channel);
1551         if (!prioffset || (channel & PRI_HELD_CALL)) {
1552                 /* Find the call waiting call or held call. */
1553                 return pri_find_principle_by_call(pri, call);
1554         }
1555
1556         span = PRI_SPAN(channel);
1557         if (!(channel & PRI_EXPLICIT)) {
1558                 int index;
1559
1560                 index = pri_active_dchan_index(pri);
1561                 if (index == -1) {
1562                         return -1;
1563                 }
1564                 span = pri->dchan_logical_span[index];
1565         }
1566
1567         principle = -1;
1568         for (x = 0; x < pri->numchans; x++) {
1569                 if (pri->pvts[x]
1570                         && pri->pvts[x]->prioffset == prioffset
1571                         && pri->pvts[x]->logicalspan == span
1572                         && !pri->pvts[x]->no_b_channel) {
1573                         principle = x;
1574                         break;
1575                 }
1576         }
1577
1578         return principle;
1579 }
1580
1581 /*!
1582  * \internal
1583  * \brief Fixup the private structure associated with the libpri call.
1584  *
1585  * \param pri PRI span control structure.
1586  * \param principle Array-index into private array to move call to if not already there.
1587  * \param call LibPRI opaque call pointer to find if need to move call.
1588  *
1589  * \note Assumes the pri->lock is already obtained.
1590  *
1591  * \retval principle on success.
1592  * \retval -1 on error.
1593  */
1594 static int pri_fixup_principle(struct sig_pri_span *pri, int principle, q931_call *call)
1595 {
1596         int x;
1597
1598         if (principle < 0 || pri->numchans <= principle) {
1599                 /* Out of rannge */
1600                 return -1;
1601         }
1602         if (!call) {
1603                 /* No call */
1604                 return principle;
1605         }
1606         if (pri->pvts[principle] && pri->pvts[principle]->call == call) {
1607                 /* Call is already on the specified principle. */
1608                 return principle;
1609         }
1610
1611         /* Find the old principle location. */
1612         for (x = 0; x < pri->numchans; x++) {
1613                 struct sig_pri_chan *new_chan;
1614                 struct sig_pri_chan *old_chan;
1615
1616                 if (!pri->pvts[x] || pri->pvts[x]->call != call) {
1617                         continue;
1618                 }
1619
1620                 /* Found our call */
1621                 new_chan = pri->pvts[principle];
1622                 old_chan = pri->pvts[x];
1623
1624                 /* Get locks to safely move to the new private structure. */
1625                 sig_pri_lock_private(old_chan);
1626                 sig_pri_lock_owner(pri, x);
1627                 sig_pri_lock_private(new_chan);
1628
1629                 ast_verb(3, "Moving call (%s) from channel %d to %d.\n",
1630                         old_chan->owner ? ast_channel_name(old_chan->owner) : "",
1631                         old_chan->channel, new_chan->channel);
1632                 if (!sig_pri_is_chan_available(new_chan)) {
1633                         ast_log(LOG_WARNING,
1634                                 "Can't move call (%s) from channel %d to %d.  It is already in use.\n",
1635                                 old_chan->owner ? ast_channel_name(old_chan->owner) : "",
1636                                 old_chan->channel, new_chan->channel);
1637                         sig_pri_unlock_private(new_chan);
1638                         if (old_chan->owner) {
1639                                 ast_channel_unlock(old_chan->owner);
1640                         }
1641                         sig_pri_unlock_private(old_chan);
1642                         return -1;
1643                 }
1644
1645                 sig_pri_fixup_chans(old_chan, new_chan);
1646
1647                 /* Fix it all up now */
1648                 new_chan->owner = old_chan->owner;
1649                 old_chan->owner = NULL;
1650
1651                 new_chan->call = old_chan->call;
1652                 old_chan->call = NULL;
1653
1654                 /* Transfer flags from the old channel. */
1655 #if defined(HAVE_PRI_AOC_EVENTS)
1656                 new_chan->aoc_s_request_invoke_id_valid = old_chan->aoc_s_request_invoke_id_valid;
1657                 new_chan->waiting_for_aoce = old_chan->waiting_for_aoce;
1658                 new_chan->holding_aoce = old_chan->holding_aoce;
1659 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1660                 new_chan->alreadyhungup = old_chan->alreadyhungup;
1661                 new_chan->isidlecall = old_chan->isidlecall;
1662                 new_chan->progress = old_chan->progress;
1663                 new_chan->allocated = old_chan->allocated;
1664                 new_chan->outgoing = old_chan->outgoing;
1665                 new_chan->digital = old_chan->digital;
1666 #if defined(HAVE_PRI_CALL_WAITING)
1667                 new_chan->is_call_waiting = old_chan->is_call_waiting;
1668 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1669 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
1670                 new_chan->no_dialed_digits = old_chan->no_dialed_digits;
1671 #endif  /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
1672
1673 #if defined(HAVE_PRI_AOC_EVENTS)
1674                 old_chan->aoc_s_request_invoke_id_valid = 0;
1675                 old_chan->waiting_for_aoce = 0;
1676                 old_chan->holding_aoce = 0;
1677 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1678                 old_chan->alreadyhungup = 0;
1679                 old_chan->isidlecall = 0;
1680                 old_chan->progress = 0;
1681                 old_chan->allocated = 0;
1682                 old_chan->outgoing = 0;
1683                 old_chan->digital = 0;
1684 #if defined(HAVE_PRI_CALL_WAITING)
1685                 old_chan->is_call_waiting = 0;
1686 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1687 #if defined(HAVE_PRI_SETUP_ACK_INBAND)
1688                 old_chan->no_dialed_digits = 0;
1689 #endif  /* defined(HAVE_PRI_SETUP_ACK_INBAND) */
1690
1691                 /* More stuff to transfer to the new channel. */
1692                 new_chan->call_level = old_chan->call_level;
1693                 old_chan->call_level = SIG_PRI_CALL_LEVEL_IDLE;
1694 #if defined(HAVE_PRI_REVERSE_CHARGE)
1695                 new_chan->reverse_charging_indication = old_chan->reverse_charging_indication;
1696 #endif  /* defined(HAVE_PRI_REVERSE_CHARGE) */
1697 #if defined(HAVE_PRI_SETUP_KEYPAD)
1698                 strcpy(new_chan->keypad_digits, old_chan->keypad_digits);
1699 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
1700                 strcpy(new_chan->deferred_digits, old_chan->deferred_digits);
1701                 strcpy(new_chan->moh_suggested, old_chan->moh_suggested);
1702                 new_chan->moh_state = old_chan->moh_state;
1703                 old_chan->moh_state = SIG_PRI_MOH_STATE_IDLE;
1704 #if defined(HAVE_PRI_TRANSFER)
1705                 new_chan->xfer_data = old_chan->xfer_data;
1706                 old_chan->xfer_data = NULL;
1707 #endif  /* defined(HAVE_PRI_TRANSFER) */
1708
1709 #if defined(HAVE_PRI_AOC_EVENTS)
1710                 new_chan->aoc_s_request_invoke_id = old_chan->aoc_s_request_invoke_id;
1711                 new_chan->aoc_e = old_chan->aoc_e;
1712 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
1713                 strcpy(new_chan->user_tag, old_chan->user_tag);
1714
1715                 if (new_chan->no_b_channel) {
1716                         /* Copy the real channel configuration to the no B channel interface. */
1717                         new_chan->hidecallerid = old_chan->hidecallerid;
1718                         new_chan->hidecalleridname = old_chan->hidecalleridname;
1719                         new_chan->immediate = old_chan->immediate;
1720                         new_chan->priexclusive = old_chan->priexclusive;
1721                         new_chan->priindication_oob = old_chan->priindication_oob;
1722                         new_chan->use_callerid = old_chan->use_callerid;
1723                         new_chan->use_callingpres = old_chan->use_callingpres;
1724                         new_chan->stripmsd = old_chan->stripmsd;
1725                         strcpy(new_chan->context, old_chan->context);
1726                         strcpy(new_chan->mohinterpret, old_chan->mohinterpret);
1727
1728                         /* Become a member of the old channel span/trunk-group. */
1729                         new_chan->logicalspan = old_chan->logicalspan;
1730                         new_chan->mastertrunkgroup = old_chan->mastertrunkgroup;
1731                 } else if (old_chan->no_b_channel) {
1732                         /*
1733                          * We are transitioning from a held/call-waiting channel to a
1734                          * real channel so we need to make sure that the media path is
1735                          * open.  (Needed especially if the channel is natively
1736                          * bridged.)
1737                          */
1738                         sig_pri_open_media(new_chan);
1739                 }
1740
1741                 if (new_chan->owner) {
1742                         sig_pri_ami_channel_event(new_chan);
1743                 }
1744
1745                 sig_pri_unlock_private(old_chan);
1746                 if (new_chan->owner) {
1747                         ast_channel_unlock(new_chan->owner);
1748                 }
1749                 sig_pri_unlock_private(new_chan);
1750
1751                 return principle;
1752         }
1753         ast_verb(3, "Call specified, but not found.\n");
1754         return -1;
1755 }
1756
1757 /*!
1758  * \internal
1759  * \brief Find and fixup the private structure associated with the libpri call.
1760  *
1761  * \param pri PRI span control structure.
1762  * \param channel LibPRI encoded channel ID.
1763  * \param call LibPRI opaque call pointer.
1764  *
1765  * \details
1766  * This is a combination of pri_find_principle() and pri_fixup_principle()
1767  * to reduce code redundancy and to make handling several PRI_EVENT_xxx's
1768  * consistent for the current architecture.
1769  *
1770  * \note Assumes the pri->lock is already obtained.
1771  *
1772  * \retval array-index into private pointer array on success.
1773  * \retval -1 on error.
1774  */
1775 static int pri_find_fixup_principle(struct sig_pri_span *pri, int channel, q931_call *call)
1776 {
1777         int chanpos;
1778
1779         chanpos = pri_find_principle(pri, channel, call);
1780         if (chanpos < 0) {
1781                 ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is unconfigured.\n",
1782                         pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
1783                 sig_pri_kill_call(pri, call, PRI_CAUSE_IDENTIFIED_CHANNEL_NOTEXIST);
1784                 return -1;
1785         }
1786         chanpos = pri_fixup_principle(pri, chanpos, call);
1787         if (chanpos < 0) {
1788                 ast_log(LOG_WARNING, "Span %d: PRI requested channel %d/%d is not available.\n",
1789                         pri->span, PRI_SPAN(channel), PRI_CHANNEL(channel));
1790                 /*
1791                  * Using Q.931 section 5.2.3.1 b) as the reason for picking
1792                  * PRI_CAUSE_CHANNEL_UNACCEPTABLE.  Receiving a
1793                  * PRI_CAUSE_REQUESTED_CHAN_UNAVAIL would cause us to restart
1794                  * that channel (which is not specified by Q.931) and kill some
1795                  * other call which would be bad.
1796                  */
1797                 sig_pri_kill_call(pri, call, PRI_CAUSE_CHANNEL_UNACCEPTABLE);
1798                 return -1;
1799         }
1800         return chanpos;
1801 }
1802
1803 static char * redirectingreason2str(int redirectingreason)
1804 {
1805         switch (redirectingreason) {
1806         case 0:
1807                 return "UNKNOWN";
1808         case 1:
1809                 return "BUSY";
1810         case 2:
1811                 return "NO_REPLY";
1812         case 0xF:
1813                 return "UNCONDITIONAL";
1814         default:
1815                 return "NOREDIRECT";
1816         }
1817 }
1818
1819 static char *dialplan2str(int dialplan)
1820 {
1821         if (dialplan == -1) {
1822                 return("Dynamically set dialplan in ISDN");
1823         }
1824         return (pri_plan2str(dialplan));
1825 }
1826
1827 /*!
1828  * \internal
1829  * \brief Apply numbering plan prefix to the given number.
1830  *
1831  * \param buf Buffer to put number into.
1832  * \param size Size of given buffer.
1833  * \param pri PRI span control structure.
1834  * \param number Number to apply numbering plan.
1835  * \param plan Numbering plan to apply.
1836  *
1837  * \return Nothing
1838  */
1839 static void apply_plan_to_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
1840 {
1841         switch (plan) {
1842         case PRI_INTERNATIONAL_ISDN:            /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
1843                 snprintf(buf, size, "%s%s", pri->internationalprefix, number);
1844                 break;
1845         case PRI_NATIONAL_ISDN:                 /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
1846                 snprintf(buf, size, "%s%s", pri->nationalprefix, number);
1847                 break;
1848         case PRI_LOCAL_ISDN:                    /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
1849                 snprintf(buf, size, "%s%s", pri->localprefix, number);
1850                 break;
1851         case PRI_PRIVATE:                       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
1852                 snprintf(buf, size, "%s%s", pri->privateprefix, number);
1853                 break;
1854         case PRI_UNKNOWN:                       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
1855                 snprintf(buf, size, "%s%s", pri->unknownprefix, number);
1856                 break;
1857         default:                                /* other Q.931 dialplan => don't twiddle with callingnum */
1858                 snprintf(buf, size, "%s", number);
1859                 break;
1860         }
1861 }
1862
1863 /*!
1864  * \internal
1865  * \brief Apply numbering plan prefix to the given number if the number exists.
1866  *
1867  * \param buf Buffer to put number into.
1868  * \param size Size of given buffer.
1869  * \param pri PRI span control structure.
1870  * \param number Number to apply numbering plan.
1871  * \param plan Numbering plan to apply.
1872  *
1873  * \return Nothing
1874  */
1875 static void apply_plan_to_existing_number(char *buf, size_t size, const struct sig_pri_span *pri, const char *number, int plan)
1876 {
1877         /* Make sure a number exists so the prefix isn't placed on an empty string. */
1878         if (ast_strlen_zero(number)) {
1879                 if (size) {
1880                         *buf = '\0';
1881                 }
1882                 return;
1883         }
1884         apply_plan_to_number(buf, size, pri, number, plan);
1885 }
1886
1887 /*!
1888  * \internal
1889  * \brief Restart the next channel we think is idle on the span.
1890  *
1891  * \param pri PRI span control structure.
1892  *
1893  * \note Assumes the pri->lock is already obtained.
1894  *
1895  * \return Nothing
1896  */
1897 static void pri_check_restart(struct sig_pri_span *pri)
1898 {
1899 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1900         unsigned why;
1901 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1902
1903         for (++pri->resetpos; pri->resetpos < pri->numchans; ++pri->resetpos) {
1904                 if (!pri->pvts[pri->resetpos]
1905                         || pri->pvts[pri->resetpos]->no_b_channel
1906                         || sig_pri_is_chan_in_use(pri->pvts[pri->resetpos])) {
1907                         continue;
1908                 }
1909 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1910                 why = pri->pvts[pri->resetpos]->service_status;
1911                 if (why) {
1912                         ast_log(LOG_NOTICE,
1913                                 "Span %d: channel %d out-of-service (reason: %s), not sending RESTART\n",
1914                                 pri->span, pri->pvts[pri->resetpos]->channel,
1915                                 (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
1916                         continue;
1917                 }
1918 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1919                 break;
1920         }
1921         if (pri->resetpos < pri->numchans) {
1922                 /* Mark the channel as resetting and restart it */
1923                 pri->pvts[pri->resetpos]->resetting = SIG_PRI_RESET_ACTIVE;
1924                 pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
1925         } else {
1926                 pri->resetting = 0;
1927                 time(&pri->lastreset);
1928                 sig_pri_span_devstate_changed(pri);
1929         }
1930 }
1931
1932 #if defined(HAVE_PRI_CALL_WAITING)
1933 /*!
1934  * \internal
1935  * \brief Init the private channel configuration using the span controller.
1936  * \since 1.8
1937  *
1938  * \param pvt Channel to init the configuration.
1939  * \param pri PRI span control structure.
1940  *
1941  * \note Assumes the pri->lock is already obtained.
1942  *
1943  * \return Nothing
1944  */
1945 static void sig_pri_init_config(struct sig_pri_chan *pvt, struct sig_pri_span *pri)
1946 {
1947         pvt->stripmsd = pri->ch_cfg.stripmsd;
1948         pvt->hidecallerid = pri->ch_cfg.hidecallerid;
1949         pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
1950         pvt->immediate = pri->ch_cfg.immediate;
1951         pvt->priexclusive = pri->ch_cfg.priexclusive;
1952         pvt->priindication_oob = pri->ch_cfg.priindication_oob;
1953         pvt->use_callerid = pri->ch_cfg.use_callerid;
1954         pvt->use_callingpres = pri->ch_cfg.use_callingpres;
1955         ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
1956         ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
1957
1958         if (sig_pri_callbacks.init_config) {
1959                 sig_pri_callbacks.init_config(pvt->chan_pvt, pri);
1960         }
1961 }
1962 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
1963
1964 /*!
1965  * \internal
1966  * \brief Find an empty B-channel interface to use.
1967  *
1968  * \param pri PRI span control structure.
1969  * \param backwards TRUE if the search starts from higher channels.
1970  *
1971  * \note Assumes the pri->lock is already obtained.
1972  *
1973  * \retval array-index into private pointer array on success.
1974  * \retval -1 on error.
1975  */
1976 static int pri_find_empty_chan(struct sig_pri_span *pri, int backwards)
1977 {
1978         int x;
1979         if (backwards)
1980                 x = pri->numchans;
1981         else
1982                 x = 0;
1983         for (;;) {
1984                 if (backwards && (x < 0))
1985                         break;
1986                 if (!backwards && (x >= pri->numchans))
1987                         break;
1988                 if (pri->pvts[x]
1989                         && !pri->pvts[x]->no_b_channel
1990                         && sig_pri_is_chan_available(pri->pvts[x])) {
1991                         ast_debug(1, "Found empty available channel %d/%d\n",
1992                                 pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
1993                         return x;
1994                 }
1995                 if (backwards)
1996                         x--;
1997                 else
1998                         x++;
1999         }
2000         return -1;
2001 }
2002
2003 #if defined(HAVE_PRI_CALL_HOLD)
2004 /*!
2005  * \internal
2006  * \brief Find or create an empty no-B-channel interface to use.
2007  * \since 1.8
2008  *
2009  * \param pri PRI span control structure.
2010  *
2011  * \note Assumes the pri->lock is already obtained.
2012  *
2013  * \retval array-index into private pointer array on success.
2014  * \retval -1 on error.
2015  */
2016 static int pri_find_empty_nobch(struct sig_pri_span *pri)
2017 {
2018         int idx;
2019
2020         for (idx = 0; idx < pri->numchans; ++idx) {
2021                 if (pri->pvts[idx]
2022                         && pri->pvts[idx]->no_b_channel
2023                         && sig_pri_is_chan_available(pri->pvts[idx])) {
2024                         ast_debug(1, "Found empty available no B channel interface\n");
2025                         return idx;
2026                 }
2027         }
2028
2029         /* Need to create a new interface. */
2030         if (sig_pri_callbacks.new_nobch_intf) {
2031                 idx = sig_pri_callbacks.new_nobch_intf(pri);
2032         } else {
2033                 idx = -1;
2034         }
2035         return idx;
2036 }
2037 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2038
2039 static void *do_idle_thread(void *v_pvt)
2040 {
2041         struct sig_pri_chan *pvt = v_pvt;
2042         struct ast_channel *chan = pvt->owner;
2043         struct ast_frame *f;
2044         char ex[128];
2045         /* Wait up to 30 seconds for an answer */
2046         int timeout_ms = 30000;
2047         int ms;
2048         struct timeval start;
2049         ast_callid callid;
2050
2051         if ((callid = ast_channel_callid(chan))) {
2052                 ast_callid_threadassoc_add(callid);
2053         }
2054
2055         ast_verb(3, "Initiating idle call on channel %s\n", ast_channel_name(chan));
2056         snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
2057         if (ast_call(chan, ex, 0)) {
2058                 ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", ast_channel_name(chan), ex);
2059                 ast_hangup(chan);
2060                 return NULL;
2061         }
2062         start = ast_tvnow();
2063         while ((ms = ast_remaining_ms(start, timeout_ms))) {
2064                 if (ast_waitfor(chan, ms) <= 0) {
2065                         break;
2066                 }
2067
2068                 f = ast_read(chan);
2069                 if (!f) {
2070                         /* Got hangup */
2071                         break;
2072                 }
2073                 if (f->frametype == AST_FRAME_CONTROL) {
2074                         switch (f->subclass.integer) {
2075                         case AST_CONTROL_ANSWER:
2076                                 /* Launch the PBX */
2077                                 ast_channel_exten_set(chan, pvt->pri->idleext);
2078                                 ast_channel_context_set(chan, pvt->pri->idlecontext);
2079                                 ast_channel_priority_set(chan, 1);
2080                                 ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", ast_channel_name(chan), ast_channel_exten(chan), ast_channel_context(chan));
2081                                 ast_pbx_run(chan);
2082                                 /* It's already hungup, return immediately */
2083                                 return NULL;
2084                         case AST_CONTROL_BUSY:
2085                                 ast_verb(4, "Idle channel '%s' busy, waiting...\n", ast_channel_name(chan));
2086                                 break;
2087                         case AST_CONTROL_CONGESTION:
2088                                 ast_verb(4, "Idle channel '%s' congested, waiting...\n", ast_channel_name(chan));
2089                                 break;
2090                         };
2091                 }
2092                 ast_frfree(f);
2093         }
2094         /* Hangup the channel since nothing happend */
2095         ast_hangup(chan);
2096         return NULL;
2097 }
2098
2099 static void *pri_ss_thread(void *data)
2100 {
2101         struct sig_pri_chan *p = data;
2102         struct ast_channel *chan = p->owner;
2103         char exten[AST_MAX_EXTENSION];
2104         int res;
2105         int len;
2106         int timeout;
2107         ast_callid callid;
2108
2109         if (!chan) {
2110                 /* We lost the owner before we could get started. */
2111                 return NULL;
2112         }
2113
2114         if ((callid = ast_channel_callid(chan))) {
2115                 ast_callid_threadassoc_add(callid);
2116         }
2117
2118         /*
2119          * In the bizarre case where the channel has become a zombie before we
2120          * even get started here, abort safely.
2121          */
2122         if (!ast_channel_tech_pvt(chan)) {
2123                 ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", ast_channel_name(chan));
2124                 ast_hangup(chan);
2125                 return NULL;
2126         }
2127
2128         ast_verb(3, "Starting simple switch on '%s'\n", ast_channel_name(chan));
2129
2130         sig_pri_dsp_reset_and_flush_digits(p);
2131
2132         /* Now loop looking for an extension */
2133         ast_copy_string(exten, p->exten, sizeof(exten));
2134         len = strlen(exten);
2135         res = 0;
2136         while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num)) {
2137                 if (len && !ast_ignore_pattern(ast_channel_context(chan), exten))
2138                         sig_pri_play_tone(p, -1);
2139                 else
2140                         sig_pri_play_tone(p, SIG_PRI_TONE_DIALTONE);
2141                 if (ast_exists_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num))
2142                         timeout = pri_matchdigittimeout;
2143                 else
2144                         timeout = pri_gendigittimeout;
2145                 res = ast_waitfordigit(chan, timeout);
2146                 if (res < 0) {
2147                         ast_debug(1, "waitfordigit returned < 0...\n");
2148                         ast_hangup(chan);
2149                         return NULL;
2150                 } else if (res) {
2151                         exten[len++] = res;
2152                         exten[len] = '\0';
2153                 } else
2154                         break;
2155         }
2156         /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
2157         if (ast_strlen_zero(exten)) {
2158                 ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
2159                 exten[0] = 's';
2160                 exten[1] = '\0';
2161         } else {
2162                 ast_free(ast_channel_dialed(chan)->number.str);
2163                 ast_channel_dialed(chan)->number.str = ast_strdup(exten);
2164
2165                 if (p->pri->append_msn_to_user_tag && p->pri->nodetype != PRI_NETWORK) {
2166                         /*
2167                          * Update the user tag for party id's from this device for this call
2168                          * now that we have a complete MSN from the network.
2169                          */
2170                         snprintf(p->user_tag, sizeof(p->user_tag), "%s_%s", p->pri->initial_user_tag,
2171                                 exten);
2172                         ast_free(ast_channel_caller(chan)->id.tag);
2173                         ast_channel_caller(chan)->id.tag = ast_strdup(p->user_tag);
2174                 }
2175         }
2176         sig_pri_play_tone(p, -1);
2177         if (ast_exists_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num)) {
2178                 /* Start the real PBX */
2179                 ast_channel_exten_set(chan, exten);
2180                 sig_pri_dsp_reset_and_flush_digits(p);
2181 #if defined(JIRA_ASTERISK_15594)
2182                 /*
2183                  * Conditionaled out this code to effectively revert the JIRA
2184                  * ASTERISK-15594 change.  It breaks overlap dialing through
2185                  * Asterisk.  There is not enough information available at this
2186                  * point to know if dialing is complete.  The
2187                  * ast_exists_extension(), ast_matchmore_extension(), and
2188                  * ast_canmatch_extension() calls are not adequate to detect a
2189                  * dial through extension pattern of "_9!".
2190                  *
2191                  * Workaround is to use the dialplan Proceeding() application
2192                  * early on non-dial through extensions.
2193                  */
2194                 if ((p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2195                         && !ast_matchmore_extension(chan, ast_channel_context(chan), exten, 1, p->cid_num)) {
2196                         sig_pri_lock_private(p);
2197                         if (p->pri->pri) {
2198                                 pri_grab(p, p->pri);
2199                                 if (p->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING) {
2200                                         p->call_level = SIG_PRI_CALL_LEVEL_PROCEEDING;
2201                                 }
2202                                 pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
2203                                 pri_rel(p->pri);
2204                         }
2205                         sig_pri_unlock_private(p);
2206                 }
2207 #endif  /* defined(JIRA_ASTERISK_15594) */
2208
2209                 sig_pri_set_echocanceller(p, 1);
2210                 ast_channel_lock(chan);
2211                 ast_setstate(chan, AST_STATE_RING);
2212                 ast_channel_unlock(chan);
2213                 res = ast_pbx_run(chan);
2214                 if (res) {
2215                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
2216                 }
2217         } else {
2218                 ast_debug(1, "No such possible extension '%s' in context '%s'\n", exten, ast_channel_context(chan));
2219                 ast_channel_hangupcause_set(chan, AST_CAUSE_UNALLOCATED);
2220                 ast_hangup(chan);
2221                 p->exten[0] = '\0';
2222                 /* Since we send release complete here, we won't get one */
2223                 p->call = NULL;
2224                 ast_mutex_lock(&p->pri->lock);
2225                 sig_pri_span_devstate_changed(p->pri);
2226                 ast_mutex_unlock(&p->pri->lock);
2227         }
2228         return NULL;
2229 }
2230
2231 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
2232 {
2233         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
2234         if (!before_start_pri) {
2235                 pri_find_dchan(pri);
2236         }
2237 }
2238
2239 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
2240 {
2241         pri->dchanavail[index] |= DCHAN_NOTINALARM;
2242         if (!before_start_pri)
2243                 pri_restart(pri->dchans[index]);
2244 }
2245
2246 /*!
2247  * \internal
2248  * \brief Convert libpri party name into asterisk party name.
2249  * \since 1.8
2250  *
2251  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
2252  * \param pri_name libpri party name structure containing source information.
2253  *
2254  * \note The filled in ast_name structure needs to be destroyed by
2255  * ast_party_name_free() when it is no longer needed.
2256  *
2257  * \return Nothing
2258  */
2259 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
2260 {
2261         ast_name->str = ast_strdup(pri_name->str);
2262         ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
2263         ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
2264         ast_name->valid = 1;
2265 }
2266
2267 /*!
2268  * \internal
2269  * \brief Convert libpri party number into asterisk party number.
2270  * \since 1.8
2271  *
2272  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
2273  * \param pri_number libpri party number structure containing source information.
2274  * \param pri PRI span control structure.
2275  *
2276  * \note The filled in ast_number structure needs to be destroyed by
2277  * ast_party_number_free() when it is no longer needed.
2278  *
2279  * \return Nothing
2280  */
2281 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)
2282 {
2283         char number[AST_MAX_EXTENSION * 2];
2284
2285         apply_plan_to_existing_number(number, sizeof(number), pri, pri_number->str,
2286                 pri_number->plan);
2287         ast_number->str = ast_strdup(number);
2288         ast_number->plan = pri_number->plan;
2289         ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
2290         ast_number->valid = 1;
2291 }
2292
2293 /*!
2294  * \internal
2295  * \brief Convert libpri party id into asterisk party id.
2296  * \since 1.8
2297  *
2298  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
2299  * \param pri_id libpri party id structure containing source information.
2300  * \param pri PRI span control structure.
2301  *
2302  * \note The filled in ast_id structure needs to be destroyed by
2303  * ast_party_id_free() when it is no longer needed.
2304  *
2305  * \return Nothing
2306  */
2307 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)
2308 {
2309         if (pri_id->name.valid) {
2310                 sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
2311         }
2312         if (pri_id->number.valid) {
2313                 sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
2314         }
2315 #if defined(HAVE_PRI_SUBADDR)
2316         if (pri_id->subaddress.valid) {
2317                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
2318         }
2319 #endif  /* defined(HAVE_PRI_SUBADDR) */
2320 }
2321
2322 /*!
2323  * \internal
2324  * \brief Convert libpri redirecting information into asterisk redirecting information.
2325  * \since 1.8
2326  *
2327  * \param ast_redirecting Asterisk redirecting structure to fill.
2328  * \param pri_redirecting libpri redirecting structure containing source information.
2329  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
2330  * \param pri PRI span control structure.
2331  *
2332  * \note The filled in ast_redirecting structure needs to be destroyed by
2333  * ast_party_redirecting_free() when it is no longer needed.
2334  *
2335  * \return Nothing
2336  */
2337 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
2338         const struct pri_party_redirecting *pri_redirecting,
2339         const struct ast_party_redirecting *ast_guide,
2340         struct sig_pri_span *pri)
2341 {
2342         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
2343
2344         sig_pri_party_id_convert(&ast_redirecting->orig, &pri_redirecting->orig_called, pri);
2345         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
2346         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
2347         ast_redirecting->count = pri_redirecting->count;
2348         ast_redirecting->reason.code = pri_to_ast_reason(pri_redirecting->reason);
2349         ast_redirecting->orig_reason.code = pri_to_ast_reason(pri_redirecting->orig_reason);
2350 }
2351
2352 /*!
2353  * \internal
2354  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
2355  * \since 1.8
2356  *
2357  * \param msn_patterns Comma separated list of MSN patterns to match.
2358  * \param exten Extension to match in the MSN list.
2359  *
2360  * \retval 1 if matches.
2361  * \retval 0 if no match.
2362  */
2363 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
2364 {
2365         char *pattern;
2366         char *msn_list;
2367         char *list_tail;
2368
2369         msn_list = ast_strdupa(msn_patterns);
2370
2371         list_tail = NULL;
2372         pattern = strtok_r(msn_list, ",", &list_tail);
2373         while (pattern) {
2374                 pattern = ast_strip(pattern);
2375                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
2376                         /* Extension matched the pattern. */
2377                         return 1;
2378                 }
2379                 pattern = strtok_r(NULL, ",", &list_tail);
2380         }
2381         /* Did not match any pattern in the list. */
2382         return 0;
2383 }
2384
2385 #if defined(HAVE_PRI_MCID)
2386 static void party_number_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *number)
2387 {
2388         const char *num_txt, *pres_txt;
2389         int plan, pres;
2390         if (!number) {
2391                 ast_str_append(msg, 0,
2392                         "%sNumValid: 0\r\n"
2393                         "%sNum: \r\n"
2394                         "%ston: 0\r\n",
2395                         prefix, prefix, prefix);
2396                 return;
2397         }
2398
2399         num_txt = ast_json_string_get(ast_json_object_get(number, "number"));
2400         plan = ast_json_integer_get(ast_json_object_get(number, "plan"));
2401         pres = ast_json_integer_get(ast_json_object_get(number, "presentation"));
2402         pres_txt = ast_json_string_get(ast_json_object_get(number, "presentation_txt"));
2403
2404         ast_str_append(msg, 0, "%sNumValid: 1\r\n", prefix);
2405         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix, num_txt);
2406         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, plan);
2407         ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, plan);
2408         ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix, pres, pres_txt);
2409 }
2410
2411 static void party_name_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *name)
2412 {
2413         const char *name_txt, *pres_txt, *charset;
2414         int pres;
2415         if (!name) {
2416                 ast_str_append(msg, 0,
2417                         "%sNameValid: 0\r\n"
2418                         "%sName: \r\n",
2419                         prefix, prefix);
2420                 return;
2421         }
2422
2423         name_txt = ast_json_string_get(ast_json_object_get(name, "name"));
2424         charset = ast_json_string_get(ast_json_object_get(name, "character_set"));
2425         pres = ast_json_integer_get(ast_json_object_get(name, "presentation"));
2426         pres_txt = ast_json_string_get(ast_json_object_get(name, "presentation_txt"));
2427
2428         ast_str_append(msg, 0, "%sNameValid: 1\r\n", prefix);
2429         ast_str_append(msg, 0, "%sName: %s\r\n", prefix, name_txt);
2430         ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix, charset);
2431         ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix, pres, pres_txt);
2432 }
2433
2434 static void party_subaddress_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *subaddress)
2435 {
2436         const char *subaddress_txt, *type_txt;
2437         int odd;
2438         if (!subaddress) {
2439                 return;
2440         }
2441
2442         subaddress_txt = ast_json_string_get(ast_json_object_get(subaddress, "subaddress"));
2443         type_txt = ast_json_string_get(ast_json_object_get(subaddress, "type"));
2444         odd = ast_json_is_true(ast_json_object_get(subaddress, "odd")) ? 1 : 0;
2445
2446         ast_str_append(msg, 0, "%sSubaddr: %s\r\n", prefix, subaddress_txt);
2447         ast_str_append(msg, 0, "%sSubaddrType: %s\r\n", prefix, type_txt);
2448         ast_str_append(msg, 0, "%sSubaddrOdd: %d\r\n", prefix, odd);
2449 }
2450
2451 /*!
2452  * \internal
2453  * \brief Append the given JSON party id to the event string.
2454  * \since 1.8
2455  *
2456  * \param msg Event message string being built.
2457  * \param prefix Prefix to add to the party id lines.
2458  * \param party Party information to encode.
2459  *
2460  * \return Nothing
2461  */
2462 static void party_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *party)
2463 {
2464         struct ast_json *presentation = ast_json_object_get(party, "presentation");
2465         struct ast_json *presentation_txt = ast_json_object_get(party, "presentation_txt");
2466         struct ast_json *name = ast_json_object_get(party, "name");
2467         struct ast_json *number = ast_json_object_get(party, "number");
2468         struct ast_json *subaddress = ast_json_object_get(party, "subaddress");
2469
2470         /* Combined party presentation */
2471         ast_str_append(msg, 0, "%sPres: %jd (%s)\r\n", prefix,
2472                 ast_json_integer_get(presentation),
2473                 ast_json_string_get(presentation_txt));
2474
2475         /* Party number */
2476         party_number_json_to_ami(msg, prefix, number);
2477
2478         /* Party name */
2479         party_name_json_to_ami(msg, prefix, name);
2480
2481         /* Party subaddress */
2482         party_subaddress_json_to_ami(msg, prefix, subaddress);
2483 }
2484
2485 static struct ast_manager_event_blob *mcid_to_ami(struct stasis_message *msg)
2486 {
2487         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
2488         RAII_VAR(struct ast_str *, party_string, ast_str_create(256), ast_free);
2489         struct ast_channel_blob *obj = stasis_message_data(msg);
2490
2491         if (obj->snapshot) {
2492                 channel_string = ast_manager_build_channel_state_string(obj->snapshot);
2493                 if (!channel_string) {
2494                         return NULL;
2495                 }
2496         }
2497
2498         party_json_to_ami(&party_string, "MCallerID", ast_json_object_get(obj->blob, "caller"));
2499         party_json_to_ami(&party_string, "MConnectedID", ast_json_object_get(obj->blob, "connected"));
2500
2501         return ast_manager_event_blob_create(EVENT_FLAG_CALL, "MCID",
2502                 "%s"
2503                 "%s",
2504                 S_COR(obj->snapshot, ast_str_buffer(channel_string), ""), ast_str_buffer(party_string));
2505 }
2506
2507 STASIS_MESSAGE_TYPE_DEFN_LOCAL(mcid_type,
2508         .to_ami = mcid_to_ami,
2509         );
2510
2511 static void send_mcid(struct ast_channel *chan, struct ast_party_id *caller, struct ast_party_id *connected)
2512 {
2513         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2514
2515         ast_assert(caller != NULL);
2516         ast_assert(connected != NULL);
2517
2518         blob = ast_json_pack("{s: o, s: o}",
2519                 "caller", ast_json_party_id(caller),
2520                 "connected", ast_json_party_id(connected));
2521         if (!blob) {
2522                 return;
2523         }
2524
2525         ast_channel_publish_blob(chan, mcid_type(), blob);
2526 }
2527
2528 /*!
2529  * \internal
2530  * \brief Handle the MCID event.
2531  * \since 1.8
2532  *
2533  * \param pri PRI span control structure.
2534  * \param mcid MCID event parameters.
2535  * \param owner Asterisk channel associated with the call.
2536  * NULL if Asterisk no longer has the ast_channel struct.
2537  *
2538  * \note Assumes the pri->lock is already obtained.
2539  * \note Assumes the owner channel lock is already obtained if still present.
2540  *
2541  * \return Nothing
2542  */
2543 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
2544 {
2545         struct ast_party_id caller_party;
2546         struct ast_party_id connected_party;
2547
2548         /* Always use libpri's called party information. */
2549         ast_party_id_init(&connected_party);
2550         sig_pri_party_id_convert(&connected_party, &mcid->answerer, pri);
2551         if (owner) {
2552                 /*
2553                  * The owner channel is present.
2554                  * Pass the event to the peer as well.
2555                  */
2556                 ast_queue_control(owner, AST_CONTROL_MCID);
2557
2558                 send_mcid(owner, &ast_channel_connected(owner)->id, &connected_party);
2559         } else {
2560                 /*
2561                  * Since we no longer have an owner channel,
2562                  * we have to use the caller information supplied by libpri.
2563                  */
2564                 ast_party_id_init(&caller_party);
2565                 sig_pri_party_id_convert(&caller_party, &mcid->originator, pri);
2566                 send_mcid(owner, &caller_party, &connected_party);
2567                 ast_party_id_free(&caller_party);
2568         }
2569         ast_party_id_free(&connected_party);
2570 }
2571 #endif  /* defined(HAVE_PRI_MCID) */
2572
2573 #if defined(HAVE_PRI_TRANSFER)
2574 struct xfer_rsp_data {
2575         struct sig_pri_span *pri;
2576         /*! Call to send transfer success/fail response over. */
2577         q931_call *call;
2578         /*! Invocation ID to use when sending a reply to the transfer request. */
2579         int invoke_id;
2580         /*! TRUE if the transfer response has been made. */
2581         int responded;
2582 };
2583 #endif  /* defined(HAVE_PRI_TRANSFER) */
2584
2585 #if defined(HAVE_PRI_TRANSFER)
2586 /*!
2587  * \internal
2588  * \brief Send the transfer success/fail response message.
2589  * \since 1.8
2590  *
2591  * \param rsp Transfer response data.
2592  * \param is_successful TRUE if the transfer was successful.
2593  *
2594  * \note Assumes the rsp->pri->lock is already obtained.
2595  *
2596  * \return Nothing
2597  */
2598 static void sig_pri_transfer_rsp(struct xfer_rsp_data *rsp, int is_successful)
2599 {
2600         if (rsp->responded) {
2601                 return;
2602         }
2603         rsp->responded = 1;
2604
2605         pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
2606 }
2607 #endif  /* defined(HAVE_PRI_TRANSFER) */
2608
2609 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2610 /*!
2611  * \internal
2612  * \brief Attempt to transfer the two calls to each other.
2613  * \since 1.8
2614  *
2615  * \param pri PRI span control structure.
2616  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
2617  * \param call_1_held TRUE if call_1_pri is on hold.
2618  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
2619  * \param call_2_held TRUE if call_2_pri is on hold.
2620  * \param xfer_data Transfer response data if non-NULL.
2621  *
2622  * \note Assumes the pri->lock is already obtained.
2623  *
2624  * \retval 0 on success.
2625  * \retval -1 on error.
2626  */
2627 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)
2628 {
2629         struct attempt_xfer_call {
2630                 q931_call *pri;
2631                 struct ast_channel *ast;
2632                 int held;
2633                 int chanpos;
2634         };
2635         int retval;
2636         enum ast_transfer_result xfer_res;
2637         struct attempt_xfer_call *call_1;
2638         struct attempt_xfer_call *call_2;
2639         struct attempt_xfer_call c1;
2640         struct attempt_xfer_call c2;
2641
2642         c1.pri = call_1_pri;
2643         c1.held = call_1_held;
2644         call_1 = &c1;
2645
2646         c2.pri = call_2_pri;
2647         c2.held = call_2_held;
2648         call_2 = &c2;
2649
2650         call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
2651         call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
2652         if (call_1->chanpos < 0 || call_2->chanpos < 0) {
2653                 /* Calls not found in span control. */
2654 #if defined(HAVE_PRI_TRANSFER)
2655                 if (xfer_data) {
2656                         /* Transfer failed. */
2657                         sig_pri_transfer_rsp(xfer_data, 0);
2658                 }
2659 #endif  /* defined(HAVE_PRI_TRANSFER) */
2660                 return -1;
2661         }
2662
2663         /* Get call_1 owner. */
2664         sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2665         sig_pri_lock_owner(pri, call_1->chanpos);
2666         call_1->ast = pri->pvts[call_1->chanpos]->owner;
2667         if (call_1->ast) {
2668                 ast_channel_ref(call_1->ast);
2669                 ast_channel_unlock(call_1->ast);
2670         }
2671         sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2672
2673         /* Get call_2 owner. */
2674         sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2675         sig_pri_lock_owner(pri, call_2->chanpos);
2676         call_2->ast = pri->pvts[call_2->chanpos]->owner;
2677         if (call_2->ast) {
2678                 ast_channel_ref(call_2->ast);
2679                 ast_channel_unlock(call_2->ast);
2680         }
2681         sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2682
2683         if (!call_1->ast || !call_2->ast) {
2684                 /* At least one owner is not present. */
2685                 if (call_1->ast) {
2686                         ast_channel_unref(call_1->ast);
2687                 }
2688                 if (call_2->ast) {
2689                         ast_channel_unref(call_2->ast);
2690                 }
2691 #if defined(HAVE_PRI_TRANSFER)
2692                 if (xfer_data) {
2693                         /* Transfer failed. */
2694                         sig_pri_transfer_rsp(xfer_data, 0);
2695                 }
2696 #endif  /* defined(HAVE_PRI_TRANSFER) */
2697                 return -1;
2698         }
2699
2700         ast_verb(3, "TRANSFERRING %s to %s\n",
2701                 ast_channel_name(call_1->ast), ast_channel_name(call_2->ast));
2702
2703 #if defined(HAVE_PRI_TRANSFER)
2704         if (xfer_data) {
2705                 /*
2706                  * Add traps on the transferer channels in case threading causes
2707                  * them to hangup before ast_bridge_transfer_attended() returns
2708                  * and we can get the pri->lock back.
2709                  */
2710                 sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2711                 pri->pvts[call_1->chanpos]->xfer_data = xfer_data;
2712                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2713                 sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2714                 pri->pvts[call_2->chanpos]->xfer_data = xfer_data;
2715                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2716         }
2717 #endif  /* defined(HAVE_PRI_TRANSFER) */
2718
2719         ast_mutex_unlock(&pri->lock);
2720         xfer_res = ast_bridge_transfer_attended(call_1->ast, call_2->ast);
2721         ast_mutex_lock(&pri->lock);
2722         retval = (xfer_res != AST_BRIDGE_TRANSFER_SUCCESS) ? -1 : 0;
2723
2724 #if defined(HAVE_PRI_TRANSFER)
2725         if (xfer_data) {
2726                 int rsp_chanpos;
2727
2728                 /*
2729                  * Remove the transferrer channel traps.
2730                  *
2731                  * We must refind chanpos because we released pri->lock.
2732                  */
2733                 rsp_chanpos = pri_find_principle_by_call(pri, call_1->pri);
2734                 if (0 <= rsp_chanpos) {
2735                         sig_pri_lock_private(pri->pvts[rsp_chanpos]);
2736                         pri->pvts[rsp_chanpos]->xfer_data = NULL;
2737                         sig_pri_unlock_private(pri->pvts[rsp_chanpos]);
2738                 }
2739                 rsp_chanpos = pri_find_principle_by_call(pri, call_2->pri);
2740                 if (0 <= rsp_chanpos) {
2741                         sig_pri_lock_private(pri->pvts[rsp_chanpos]);
2742                         pri->pvts[rsp_chanpos]->xfer_data = NULL;
2743                         sig_pri_unlock_private(pri->pvts[rsp_chanpos]);
2744                 }
2745
2746                 /* Report transfer status. */
2747                 sig_pri_transfer_rsp(xfer_data, retval ? 0 : 1);
2748         }
2749 #endif  /* defined(HAVE_PRI_TRANSFER) */
2750         ast_channel_unref(call_1->ast);
2751         ast_channel_unref(call_2->ast);
2752         return retval;
2753 }
2754 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2755
2756 #if defined(HAVE_PRI_CCSS)
2757 /*!
2758  * \internal
2759  * \brief Compare the CC agent private data by libpri cc_id.
2760  * \since 1.8
2761  *
2762  * \param obj pointer to the (user-defined part) of an object.
2763  * \param arg callback argument from ao2_callback()
2764  * \param flags flags from ao2_callback()
2765  *
2766  * \return values are a combination of enum _cb_results.
2767  */
2768 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
2769 {
2770         struct ast_cc_agent *agent_1 = obj;
2771         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2772         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2773
2774         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2775                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2776 }
2777 #endif  /* defined(HAVE_PRI_CCSS) */
2778
2779 #if defined(HAVE_PRI_CCSS)
2780 /*!
2781  * \internal
2782  * \brief Find the CC agent by libpri cc_id.
2783  * \since 1.8
2784  *
2785  * \param pri PRI span control structure.
2786  * \param cc_id CC record ID to find.
2787  *
2788  * \note
2789  * Since agents are refcounted, and this function returns
2790  * a reference to the agent, it is imperative that you decrement
2791  * the refcount of the agent once you have finished using it.
2792  *
2793  * \retval agent on success.
2794  * \retval NULL not found.
2795  */
2796 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2797 {
2798         struct sig_pri_cc_agent_prv finder = {
2799                 .pri = pri,
2800                 .cc_id = cc_id,
2801         };
2802
2803         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2804                 sig_pri_cc_type_name);
2805 }
2806 #endif  /* defined(HAVE_PRI_CCSS) */
2807
2808 #if defined(HAVE_PRI_CCSS)
2809 /*!
2810  * \internal
2811  * \brief Compare the CC monitor instance by libpri cc_id.
2812  * \since 1.8
2813  *
2814  * \param obj pointer to the (user-defined part) of an object.
2815  * \param arg callback argument from ao2_callback()
2816  * \param flags flags from ao2_callback()
2817  *
2818  * \return values are a combination of enum _cb_results.
2819  */
2820 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2821 {
2822         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2823         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2824
2825         return (monitor_1->pri == monitor_2->pri
2826                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2827 }
2828 #endif  /* defined(HAVE_PRI_CCSS) */
2829
2830 #if defined(HAVE_PRI_CCSS)
2831 /*!
2832  * \internal
2833  * \brief Find the CC monitor instance by libpri cc_id.
2834  * \since 1.8
2835  *
2836  * \param pri PRI span control structure.
2837  * \param cc_id CC record ID to find.
2838  *
2839  * \note
2840  * Since monitor_instances are refcounted, and this function returns
2841  * a reference to the instance, it is imperative that you decrement
2842  * the refcount of the instance once you have finished using it.
2843  *
2844  * \retval monitor_instance on success.
2845  * \retval NULL not found.
2846  */
2847 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2848 {
2849         struct sig_pri_cc_monitor_instance finder = {
2850                 .pri = pri,
2851                 .cc_id = cc_id,
2852         };
2853
2854         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2855 }
2856 #endif  /* defined(HAVE_PRI_CCSS) */
2857
2858 #if defined(HAVE_PRI_CCSS)
2859 /*!
2860  * \internal
2861  * \brief Destroy the given monitor instance.
2862  * \since 1.8
2863  *
2864  * \param data Monitor instance to destroy.
2865  *
2866  * \return Nothing
2867  */
2868 static void sig_pri_cc_monitor_instance_destroy(void *data)
2869 {
2870         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2871
2872         if (monitor_instance->cc_id != -1) {
2873                 ast_mutex_lock(&monitor_instance->pri->lock);
2874                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2875                 ast_mutex_unlock(&monitor_instance->pri->lock);
2876         }
2877         sig_pri_callbacks.module_unref();
2878 }
2879 #endif  /* defined(HAVE_PRI_CCSS) */
2880
2881 #if defined(HAVE_PRI_CCSS)
2882 /*!
2883  * \internal
2884  * \brief Construct a new monitor instance.
2885  * \since 1.8
2886  *
2887  * \param core_id CC core ID.
2888  * \param pri PRI span control structure.
2889  * \param cc_id CC record ID.
2890  * \param device_name Name of device (Asterisk channel name less sequence number).
2891  *
2892  * \note
2893  * Since monitor_instances are refcounted, and this function returns
2894  * a reference to the instance, it is imperative that you decrement
2895  * the refcount of the instance once you have finished using it.
2896  *
2897  * \retval monitor_instance on success.
2898  * \retval NULL on error.
2899  */
2900 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)
2901 {
2902         struct sig_pri_cc_monitor_instance *monitor_instance;
2903
2904         if (!sig_pri_callbacks.module_ref || !sig_pri_callbacks.module_unref) {
2905                 return NULL;
2906         }
2907
2908         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2909                 sig_pri_cc_monitor_instance_destroy);
2910         if (!monitor_instance) {
2911                 return NULL;
2912         }
2913
2914         monitor_instance->cc_id = cc_id;
2915         monitor_instance->pri = pri;
2916         monitor_instance->core_id = core_id;
2917         strcpy(monitor_instance->name, device_name);
2918
2919         sig_pri_callbacks.module_ref();
2920
2921         ao2_link(sig_pri_cc_monitors, monitor_instance);
2922         return monitor_instance;
2923 }
2924 #endif  /* defined(HAVE_PRI_CCSS) */
2925
2926 #if defined(HAVE_PRI_CCSS)
2927 /*!
2928  * \internal
2929  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2930  * \since 1.8
2931  *
2932  * \param pri PRI span control structure.
2933  * \param chanpos Channel position in the span.
2934  * \param cc_id CC record ID.
2935  * \param service CCBS/CCNR indication.
2936  *
2937  * \note Assumes the pri->lock is already obtained.
2938  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2939  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2940  *
2941  * \retval 0 on success.
2942  * \retval -1 on error.
2943  */
2944 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2945 {
2946         struct sig_pri_chan *pvt;
2947         struct ast_cc_config_params *cc_params;
2948         struct sig_pri_cc_monitor_instance *monitor;
2949         enum ast_cc_monitor_policies monitor_policy;
2950         int core_id;
2951         int res;
2952         char device_name[AST_CHANNEL_NAME];
2953         char dialstring[AST_CHANNEL_NAME];
2954
2955         pvt = pri->pvts[chanpos];
2956
2957         core_id = ast_cc_get_current_core_id(pvt->owner);
2958         if (core_id == -1) {
2959                 return -1;
2960         }
2961
2962         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2963         if (!cc_params) {
2964                 return -1;
2965         }
2966
2967         res = -1;
2968         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2969         switch (monitor_policy) {
2970         case AST_CC_MONITOR_NEVER:
2971                 /* CCSS is not enabled. */
2972                 break;
2973         case AST_CC_MONITOR_NATIVE:
2974         case AST_CC_MONITOR_ALWAYS:
2975                 /*
2976                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2977                  * later in the call to sig_pri_cc_generic_check().
2978                  */
2979                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2980                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2981                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2982                 if (!monitor) {
2983                         break;
2984                 }
2985                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2986                         monitor);
2987                 if (res) {
2988                         monitor->cc_id = -1;
2989                         ao2_unlink(sig_pri_cc_monitors, monitor);
2990                         ao2_ref(monitor, -1);
2991                 }
2992                 break;
2993         case AST_CC_MONITOR_GENERIC:
2994                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2995                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2996                 /* Say it failed to force caller to cancel native CC. */
2997                 break;
2998         }
2999         return res;
3000 }
3001 #endif  /* defined(HAVE_PRI_CCSS) */
3002
3003 /*!
3004  * \internal
3005  * \brief Check if generic CC monitor is needed and request it.
3006  * \since 1.8
3007  *
3008  * \param pri PRI span control structure.
3009  * \param chanpos Channel position in the span.
3010  * \param service CCBS/CCNR indication.
3011  *
3012  * \note Assumes the pri->lock is already obtained.
3013  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
3014  *
3015  * \return Nothing
3016  */
3017 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
3018 {
3019         struct ast_channel *owner;
3020         struct ast_cc_config_params *cc_params;
3021 #if defined(HAVE_PRI_CCSS)
3022         struct ast_cc_monitor *monitor;
3023         char device_name[AST_CHANNEL_NAME];
3024 #endif  /* defined(HAVE_PRI_CCSS) */
3025         enum ast_cc_monitor_policies monitor_policy;
3026         int core_id;
3027
3028         if (!pri->pvts[chanpos]->outgoing) {
3029                 /* This is not an outgoing call so it cannot be CC monitor. */
3030                 return;
3031         }
3032
3033         sig_pri_lock_owner(pri, chanpos);
3034         owner = pri->pvts[chanpos]->owner;
3035         if (!owner) {
3036                 return;
3037         }
3038         core_id = ast_cc_get_current_core_id(owner);
3039         if (core_id == -1) {
3040                 /* No CC core setup */
3041                 goto done;
3042         }
3043
3044         cc_params = ast_channel_get_cc_config_params(owner);
3045         if (!cc_params) {
3046                 /* Could not get CC config parameters. */
3047                 goto done;
3048         }
3049
3050 #if defined(HAVE_PRI_CCSS)
3051         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
3052         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
3053         if (monitor) {
3054                 /* CC monitor is already present so no need for generic CC. */
3055                 ao2_ref(monitor, -1);
3056                 goto done;
3057         }
3058 #endif  /* defined(HAVE_PRI_CCSS) */
3059
3060         monitor_policy = ast_get_cc_monitor_policy(cc_params);
3061         switch (monitor_policy) {
3062         case AST_CC_MONITOR_NEVER:
3063                 /* CCSS is not enabled. */
3064                 break;
3065         case AST_CC_MONITOR_NATIVE:
3066                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
3067                         /* Request generic CC monitor. */
3068                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3069                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3070                 }
3071                 break;
3072         case AST_CC_MONITOR_ALWAYS:
3073                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
3074                         /*
3075                          * Cannot monitor PTMP TE side since this is not defined.
3076                          * We are playing the roll of a phone in this case and
3077                          * a phone cannot monitor a party over the network without
3078                          * protocol help.
3079                          */
3080                         break;
3081                 }
3082                 /*
3083                  * We are either falling back or this is a PTMP NT span.
3084                  * Request generic CC monitor.
3085                  */
3086                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3087                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3088                 break;
3089         case AST_CC_MONITOR_GENERIC:
3090                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
3091                         /* Request generic CC monitor. */
3092                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3093                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3094                 }
3095                 break;
3096         }
3097
3098 done:
3099         ast_channel_unlock(owner);
3100 }
3101
3102 #if defined(HAVE_PRI_CCSS)
3103 /*!
3104  * \internal
3105  * \brief The CC link canceled the CC instance.
3106  * \since 1.8
3107  *
3108  * \param pri PRI span control structure.
3109  * \param cc_id CC record ID.
3110  * \param is_agent TRUE if the cc_id is for an agent.
3111  *
3112  * \return Nothing
3113  */
3114 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
3115 {
3116         if (is_agent) {
3117                 struct ast_cc_agent *agent;
3118
3119                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
3120                 if (!agent) {
3121                         return;
3122                 }
3123                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
3124                         sig_pri_cc_type_name);
3125                 ao2_ref(agent, -1);
3126         } else {
3127                 struct sig_pri_cc_monitor_instance *monitor;
3128
3129                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
3130                 if (!monitor) {
3131                         return;
3132                 }
3133                 monitor->cc_id = -1;
3134                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3135                         "%s monitor got canceled by link", sig_pri_cc_type_name);
3136                 ao2_ref(monitor, -1);
3137         }
3138 }
3139 #endif  /* defined(HAVE_PRI_CCSS) */
3140
3141 #if defined(HAVE_PRI_AOC_EVENTS)
3142 /*!
3143  * \internal
3144  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
3145  * \since 1.8
3146  *
3147  * \param value Value to convert to string.
3148  *
3149  * \return PRI_AOC_CHARGED_ITEM
3150  */
3151 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
3152 {
3153         switch (value) {
3154         case AST_AOC_CHARGED_ITEM_NA:
3155                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
3156         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
3157                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
3158         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
3159                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
3160         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
3161                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
3162         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
3163                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
3164         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
3165                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
3166         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
3167                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
3168         }
3169         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
3170 }
3171 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3172
3173 #if defined(HAVE_PRI_AOC_EVENTS)
3174 /*!
3175  * \internal
3176  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
3177  * \since 1.8
3178  *
3179  * \param value Value to convert to string.
3180  *
3181  * \return ast_aoc_charged_item
3182  */
3183 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
3184 {
3185         switch (value) {
3186         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
3187                 return AST_AOC_CHARGED_ITEM_NA;
3188         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
3189                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
3190         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
3191                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
3192         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
3193                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
3194         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
3195                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
3196         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
3197                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
3198         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
3199                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
3200         }
3201         return AST_AOC_CHARGED_ITEM_NA;
3202 }
3203 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3204
3205 #if defined(HAVE_PRI_AOC_EVENTS)
3206 /*!
3207  * \internal
3208  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
3209  * \since 1.8
3210  *
3211  * \return pri enum equivalent.
3212  */
3213 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
3214 {
3215         switch (mult) {
3216         case AST_AOC_MULT_ONETHOUSANDTH:
3217                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
3218         case AST_AOC_MULT_ONEHUNDREDTH:
3219                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
3220         case AST_AOC_MULT_ONETENTH:
3221                 return PRI_AOC_MULTIPLIER_TENTH;
3222         case AST_AOC_MULT_ONE:
3223                 return PRI_AOC_MULTIPLIER_ONE;
3224         case AST_AOC_MULT_TEN:
3225                 return PRI_AOC_MULTIPLIER_TEN;
3226         case AST_AOC_MULT_HUNDRED:
3227                 return PRI_AOC_MULTIPLIER_HUNDRED;
3228         case AST_AOC_MULT_THOUSAND:
3229                 return PRI_AOC_MULTIPLIER_THOUSAND;
3230         default:
3231                 return PRI_AOC_MULTIPLIER_ONE;
3232         }
3233 }
3234 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3235
3236 #if defined(HAVE_PRI_AOC_EVENTS)
3237 /*!
3238  * \internal
3239  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
3240  * \since 1.8
3241  *
3242  * \return ast enum equivalent.
3243  */
3244 static int sig_pri_aoc_multiplier_from_pri(const int mult)
3245 {
3246         switch (mult) {
3247         case PRI_AOC_MULTIPLIER_THOUSANDTH:
3248                 return AST_AOC_MULT_ONETHOUSANDTH;
3249         case PRI_AOC_MULTIPLIER_HUNDREDTH:
3250                 return AST_AOC_MULT_ONEHUNDREDTH;
3251         case PRI_AOC_MULTIPLIER_TENTH:
3252                 return AST_AOC_MULT_ONETENTH;
3253         case PRI_AOC_MULTIPLIER_ONE:
3254                 return AST_AOC_MULT_ONE;
3255         case PRI_AOC_MULTIPLIER_TEN:
3256                 return AST_AOC_MULT_TEN;
3257         case PRI_AOC_MULTIPLIER_HUNDRED:
3258                 return AST_AOC_MULT_HUNDRED;
3259         case PRI_AOC_MULTIPLIER_THOUSAND:
3260                 return AST_AOC_MULT_THOUSAND;
3261         default:
3262                 return AST_AOC_MULT_ONE;
3263         }
3264 }
3265 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3266
3267 #if defined(HAVE_PRI_AOC_EVENTS)
3268 /*!
3269  * \internal
3270  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
3271  * \since 1.8
3272  *
3273  * \param value Value to convert to ast representation
3274  *
3275  * \return PRI_AOC_TIME_SCALE
3276  */
3277 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
3278 {
3279         switch (value) {
3280         default:
3281         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3282                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3283         case AST_AOC_TIME_SCALE_TENTH_SECOND:
3284                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
3285         case AST_AOC_TIME_SCALE_SECOND:
3286                 return PRI_AOC_TIME_SCALE_SECOND;
3287         case AST_AOC_TIME_SCALE_TEN_SECOND:
3288                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
3289         case AST_AOC_TIME_SCALE_MINUTE:
3290                 return PRI_AOC_TIME_SCALE_MINUTE;
3291         case AST_AOC_TIME_SCALE_HOUR:
3292                 return PRI_AOC_TIME_SCALE_HOUR;
3293         case AST_AOC_TIME_SCALE_DAY:
3294                 return PRI_AOC_TIME_SCALE_DAY;
3295         }
3296 }
3297 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3298
3299 #if defined(HAVE_PRI_AOC_EVENTS)
3300 /*!
3301  * \internal
3302  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
3303  * \since 1.8
3304  *
3305  * \param value Value to convert to ast representation
3306  *
3307  * \return ast aoc time scale
3308  */
3309 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
3310 {
3311         switch (value) {
3312         default:
3313         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3314                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3315         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
3316                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
3317         case PRI_AOC_TIME_SCALE_SECOND:
3318                 return AST_AOC_TIME_SCALE_SECOND;
3319         case PRI_AOC_TIME_SCALE_TEN_SECOND:
3320                 return AST_AOC_TIME_SCALE_TEN_SECOND;
3321         case PRI_AOC_TIME_SCALE_MINUTE:
3322                 return AST_AOC_TIME_SCALE_MINUTE;
3323         case PRI_AOC_TIME_SCALE_HOUR:
3324                 return AST_AOC_TIME_SCALE_HOUR;
3325         case PRI_AOC_TIME_SCALE_DAY:
3326                 return AST_AOC_TIME_SCALE_DAY;
3327         }
3328         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3329 }
3330 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3331
3332 #if defined(HAVE_PRI_AOC_EVENTS)
3333 /*!
3334  * \internal
3335  * \brief Handle AOC-S control frame
3336  * \since 1.8
3337  *
3338  * \param aoc_s AOC-S event parameters.
3339  * \param owner Asterisk channel associated with the call.
3340  * \param passthrough indicating if this message should be queued on the ast channel
3341  *
3342  * \note Assumes the pri->lock is already obtained.
3343  * \note Assumes the sig_pri private is locked
3344  * \note Assumes the owner channel lock is already obtained.
3345  *
3346  * \return Nothing
3347  */
3348 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
3349 {
3350         struct ast_aoc_decoded *decoded = NULL;
3351         struct ast_aoc_encoded *encoded = NULL;
3352         size_t encoded_size = 0;
3353         int idx;
3354
3355         if (!owner || !aoc_s) {
3356                 return;
3357         }
3358
3359         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
3360                 return;
3361         }
3362
3363         for (idx = 0; idx < aoc_s->num_items; ++idx) {
3364                 enum ast_aoc_s_charged_item charged_item;
3365
3366                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
3367                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
3368                         /* Delete the unknown charged item from the list. */
3369                         continue;
3370                 }
3371                 switch (aoc_s->item[idx].rate_type) {
3372                 case PRI_AOC_RATE_TYPE_DURATION:
3373                         ast_aoc_s_add_rate_duration(decoded,
3374                                 charged_item,
3375                                 aoc_s->item[idx].rate.duration.amount.cost,
3376                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
3377                                 aoc_s->item[idx].rate.duration.currency,
3378                                 aoc_s->item[idx].rate.duration.time.length,
3379                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
3380                                 aoc_s->item[idx].rate.duration.granularity.length,
3381                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
3382                                 aoc_s->item[idx].rate.duration.charging_type);
3383                         break;
3384                 case PRI_AOC_RATE_TYPE_FLAT:
3385                         ast_aoc_s_add_rate_flat(decoded,
3386                                 charged_item,
3387                                 aoc_s->item[idx].rate.flat.amount.cost,
3388                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
3389                                 aoc_s->item[idx].rate.flat.currency);
3390                         break;
3391                 case PRI_AOC_RATE_TYPE_VOLUME:
3392                         ast_aoc_s_add_rate_volume(decoded,
3393                                 charged_item,
3394                                 aoc_s->item[idx].rate.volume.unit,
3395                                 aoc_s->item[idx].rate.volume.amount.cost,
3396                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
3397                                 aoc_s->item[idx].rate.volume.currency);
3398                         break;
3399                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
3400                         ast_aoc_s_add_rate_special_charge_code(decoded,
3401                                 charged_item,
3402                                 aoc_s->item[idx].rate.special);
3403                         break;
3404                 case PRI_AOC_RATE_TYPE_FREE:
3405                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
3406                         break;
3407                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3408                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
3409                         break;
3410                 default:
3411                         ast_aoc_s_add_rate_na(decoded, charged_item);
3412                         break;
3413                 }
3414         }
3415
3416         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3417                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3418         }
3419
3420         ast_aoc_manager_event(decoded, owner);
3421
3422         ast_aoc_destroy_decoded(decoded);
3423         ast_aoc_destroy_encoded(encoded);
3424 }
3425 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3426
3427 #if defined(HAVE_PRI_AOC_EVENTS)
3428 /*!
3429  * \internal
3430  * \brief Generate AOC Request Response
3431  * \since 1.8
3432  *
3433  * \param aoc_request
3434  *
3435  * \note Assumes the pri->lock is already obtained.
3436  * \note Assumes the sig_pri private is locked
3437  * \note Assumes the owner channel lock is already obtained.
3438  *
3439  * \return Nothing
3440  */
3441 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
3442 {
3443         int request;
3444
3445         if (!aoc_request) {
3446                 return;
3447         }
3448
3449         request = aoc_request->charging_request;
3450
3451         if (request & PRI_AOC_REQUEST_S) {
3452                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
3453                         /* An AOC-S response must come from the other side, so save off this invoke_id
3454                          * and see if an AOC-S message comes in before the call is answered. */
3455                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
3456                         pvt->aoc_s_request_invoke_id_valid = 1;
3457
3458                 } else {
3459                         pri_aoc_s_request_response_send(pvt->pri->pri,
3460                                 call,
3461                                 aoc_request->invoke_id,
3462                                 NULL);
3463                 }
3464         }
3465
3466         if (request & PRI_AOC_REQUEST_D) {
3467                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
3468                         pri_aoc_de_request_response_send(pvt->pri->pri,
3469                                 call,
3470                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3471                                 aoc_request->invoke_id);
3472                 } else {
3473                         pri_aoc_de_request_response_send(pvt->pri->pri,
3474                                 call,
3475                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3476                                 aoc_request->invoke_id);
3477                 }
3478         }
3479
3480         if (request & PRI_AOC_REQUEST_E) {
3481                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
3482                         pri_aoc_de_request_response_send(pvt->pri->pri,
3483                                 call,
3484                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3485                                 aoc_request->invoke_id);
3486                 } else {
3487                         pri_aoc_de_request_response_send(pvt->pri->pri,
3488                                 call,
3489                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3490                                 aoc_request->invoke_id);
3491                 }
3492         }
3493 }
3494 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3495
3496 #if defined(HAVE_PRI_AOC_EVENTS)
3497 /*!
3498  * \internal
3499  * \brief Generate AOC-D AST_CONTROL_AOC frame
3500  * \since 1.8
3501  *
3502  * \param aoc_e AOC-D event parameters.
3503  * \param owner Asterisk channel associated with the call.
3504  * \param passthrough indicating if this message should be queued on the ast channel
3505  *
3506  * \note Assumes the pri->lock is already obtained.
3507  * \note Assumes the sig_pri private is locked
3508  * \note Assumes the owner channel lock is already obtained.
3509  *
3510  * \return Nothing
3511  */
3512 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
3513 {
3514         struct ast_aoc_decoded *decoded = NULL;
3515         struct ast_aoc_encoded *encoded = NULL;
3516         size_t encoded_size = 0;
3517         enum ast_aoc_charge_type type;
3518
3519         if (!owner || !aoc_d) {
3520                 return;
3521         }
3522
3523         switch (aoc_d->charge) {
3524         case PRI_AOC_DE_CHARGE_CURRENCY:
3525                 type = AST_AOC_CHARGE_CURRENCY;
3526                 break;
3527         case PRI_AOC_DE_CHARGE_UNITS:
3528                 type = AST_AOC_CHARGE_UNIT;
3529                 break;
3530         case PRI_AOC_DE_CHARGE_FREE:
3531                 type = AST_AOC_CHARGE_FREE;
3532                 break;
3533         default:
3534                 type = AST_AOC_CHARGE_NA;
3535                 break;
3536         }
3537
3538         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
3539                 return;
3540         }
3541
3542         switch (aoc_d->billing_accumulation) {
3543         default:
3544                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
3545                         aoc_d->billing_accumulation);
3546                 /* Fall through */
3547         case 0:/* subTotal */
3548                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
3549                 break;
3550         case 1:/* total */
3551                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
3552                 break;
3553         }
3554
3555         switch (aoc_d->billing_id) {
3556         case PRI_AOC_D_BILLING_ID_NORMAL:
3557                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3558                 break;
3559         case PRI_AOC_D_BILLING_ID_REVERSE:
3560                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3561                 break;
3562         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
3563                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3564                 break;
3565         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
3566         default:
3567                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3568                 break;
3569         }
3570
3571         switch (aoc_d->charge) {
3572         case PRI_AOC_DE_CHARGE_CURRENCY:
3573                 ast_aoc_set_currency_info(decoded,
3574                         aoc_d->recorded.money.amount.cost,
3575                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
3576                         aoc_d->recorded.money.currency);
3577                 break;
3578         case PRI_AOC_DE_CHARGE_UNITS:
3579                 {
3580                         int i;
3581                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
3582                                 /* if type or number are negative, then they are not present */
3583                                 ast_aoc_add_unit_entry(decoded,
3584                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
3585                                         aoc_d->recorded.unit.item[i].number,
3586                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
3587                                         aoc_d->recorded.unit.item[i].type);
3588                         }
3589                 }
3590                 break;
3591         }
3592
3593         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3594                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3595         }
3596
3597         ast_aoc_manager_event(decoded, owner);
3598
3599         ast_aoc_destroy_decoded(decoded);
3600         ast_aoc_destroy_encoded(encoded);
3601 }
3602 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3603
3604 #if defined(HAVE_PRI_AOC_EVENTS)
3605 /*!
3606  * \internal
3607  * \brief Generate AOC-E AST_CONTROL_AOC frame
3608  * \since 1.8
3609  *
3610  * \param aoc_e AOC-E event parameters.
3611  * \param owner Asterisk channel associated with the call.
3612  * \param passthrough indicating if this message should be queued on the ast channel
3613  *
3614  * \note Assumes the pri->lock is already obtained.
3615  * \note Assumes the sig_pri private is locked
3616  * \note Assumes the owner channel lock is already obtained.
3617  * \note owner channel may be NULL. In that case, generate event only
3618  *
3619  * \return Nothing
3620  */
3621 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
3622 {
3623         struct ast_aoc_decoded *decoded = NULL;
3624         struct ast_aoc_encoded *encoded = NULL;
3625         size_t encoded_size = 0;
3626         enum ast_aoc_charge_type type;
3627
3628         if (!aoc_e) {
3629                 return;
3630         }
3631
3632         switch (aoc_e->charge) {
3633         case PRI_AOC_DE_CHARGE_CURRENCY:
3634                 type = AST_AOC_CHARGE_CURRENCY;
3635                 break;
3636         case PRI_AOC_DE_CHARGE_UNITS:
3637                 type = AST_AOC_CHARGE_UNIT;
3638                 break;
3639         case PRI_AOC_DE_CHARGE_FREE:
3640                 type = AST_AOC_CHARGE_FREE;
3641                 break;
3642         default:
3643                 type = AST_AOC_CHARGE_NA;
3644                 break;
3645         }
3646
3647         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
3648                 return;
3649         }
3650
3651         switch (aoc_e->associated.charging_type) {
3652         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
3653                 if (!aoc_e->associated.charge.number.valid) {
3654                         break;
3655                 }
3656                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
3657                 break;
3658         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
3659                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
3660                 break;
3661         default:
3662                 break;
3663         }
3664
3665         switch (aoc_e->billing_id) {
3666         case PRI_AOC_E_BILLING_ID_NORMAL:
3667                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3668                 break;
3669         case PRI_AOC_E_BILLING_ID_REVERSE:
3670                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3671                 break;
3672         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
3673                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3674                 break;
3675         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
3676                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
3677                 break;
3678         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
3679                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
3680                 break;
3681         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
3682                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
3683                 break;
3684         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
3685                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
3686                 break;
3687         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
3688                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
3689                 break;
3690         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
3691         default:
3692                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3693                 break;
3694         }
3695
3696         switch (aoc_e->charge) {
3697         case PRI_AOC_DE_CHARGE_CURRENCY:
3698                 ast_aoc_set_currency_info(decoded,
3699                         aoc_e->recorded.money.amount.cost,
3700                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
3701                         aoc_e->recorded.money.currency);
3702                 break;
3703         case PRI_AOC_DE_CHARGE_UNITS:
3704                 {
3705                         int i;
3706                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
3707                                 /* if type or number are negative, then they are not present */
3708                                 ast_aoc_add_unit_entry(decoded,
3709                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
3710                                         aoc_e->recorded.unit.item[i].number,
3711                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
3712                                         aoc_e->recorded.unit.item[i].type);
3713                         }
3714                 }
3715         }
3716
3717         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3718                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3719         }
3720
3721         ast_aoc_manager_event(decoded, owner);
3722
3723         ast_aoc_destroy_decoded(decoded);
3724         ast_aoc_destroy_encoded(encoded);
3725 }
3726 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3727
3728 #if defined(HAVE_PRI_AOC_EVENTS)
3729 /*!
3730  * \internal
3731  * \brief send an AOC-S message on the current call
3732  *
3733  * \param pvt sig_pri private channel structure.
3734  * \param generic decoded ast AOC message
3735  *
3736  * \return Nothing
3737  *
3738  * \note Assumes that the PRI lock is already obtained.
3739  */
3740 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3741 {
3742         struct pri_subcmd_aoc_s aoc_s = { 0, };
3743         const struct ast_aoc_s_entry *entry;
3744         int idx;
3745
3746         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
3747                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
3748                         break;
3749                 }
3750
3751                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
3752
3753                 switch (entry->rate_type) {
3754                 case AST_AOC_RATE_TYPE_DURATION:
3755                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
3756                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
3757                         aoc_s.item[idx].rate.duration.amount.multiplier =
3758                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
3759                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
3760                         aoc_s.item[idx].rate.duration.time.scale =
3761                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
3762                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
3763                         aoc_s.item[idx].rate.duration.granularity.scale =
3764                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
3765                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
3766
3767                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
3768                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
3769                                         entry->rate.duration.currency_name,
3770                                         sizeof(aoc_s.item[idx].rate.duration.currency));
3771                         }
3772                         break;
3773                 case AST_AOC_RATE_TYPE_FLAT:
3774                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
3775                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
3776                         aoc_s.item[idx].rate.flat.amount.multiplier =
3777                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
3778
3779                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
3780                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
3781