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