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