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