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