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