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