48c8c33d74f2f723ba2a591cd78bc05873f2b80b
[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_channel_lock(chan);
2164                 ast_setstate(chan, AST_STATE_RING);
2165                 ast_channel_unlock(chan);
2166                 res = ast_pbx_run(chan);
2167                 if (res) {
2168                         ast_log(LOG_WARNING, "PBX exited non-zero!\n");
2169                 }
2170         } else {
2171                 ast_debug(1, "No such possible extension '%s' in context '%s'\n", exten, ast_channel_context(chan));
2172                 ast_channel_hangupcause_set(chan, AST_CAUSE_UNALLOCATED);
2173                 ast_hangup(chan);
2174                 p->exten[0] = '\0';
2175                 /* Since we send release complete here, we won't get one */
2176                 p->call = NULL;
2177                 ast_mutex_lock(&p->pri->lock);
2178                 sig_pri_span_devstate_changed(p->pri);
2179                 ast_mutex_unlock(&p->pri->lock);
2180         }
2181         return NULL;
2182 }
2183
2184 void pri_event_alarm(struct sig_pri_span *pri, int index, int before_start_pri)
2185 {
2186         pri->dchanavail[index] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
2187         if (!before_start_pri) {
2188                 pri_find_dchan(pri);
2189         }
2190 }
2191
2192 void pri_event_noalarm(struct sig_pri_span *pri, int index, int before_start_pri)
2193 {
2194         pri->dchanavail[index] |= DCHAN_NOTINALARM;
2195         if (!before_start_pri)
2196                 pri_restart(pri->dchans[index]);
2197 }
2198
2199 /*!
2200  * \internal
2201  * \brief Convert libpri party name into asterisk party name.
2202  * \since 1.8
2203  *
2204  * \param ast_name Asterisk party name structure to fill.  Must already be set initialized.
2205  * \param pri_name libpri party name structure containing source information.
2206  *
2207  * \note The filled in ast_name structure needs to be destroyed by
2208  * ast_party_name_free() when it is no longer needed.
2209  *
2210  * \return Nothing
2211  */
2212 static void sig_pri_party_name_convert(struct ast_party_name *ast_name, const struct pri_party_name *pri_name)
2213 {
2214         ast_name->str = ast_strdup(pri_name->str);
2215         ast_name->char_set = pri_to_ast_char_set(pri_name->char_set);
2216         ast_name->presentation = pri_to_ast_presentation(pri_name->presentation);
2217         ast_name->valid = 1;
2218 }
2219
2220 /*!
2221  * \internal
2222  * \brief Convert libpri party number into asterisk party number.
2223  * \since 1.8
2224  *
2225  * \param ast_number Asterisk party number structure to fill.  Must already be set initialized.
2226  * \param pri_number libpri party number structure containing source information.
2227  * \param pri PRI span control structure.
2228  *
2229  * \note The filled in ast_number structure needs to be destroyed by
2230  * ast_party_number_free() when it is no longer needed.
2231  *
2232  * \return Nothing
2233  */
2234 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)
2235 {
2236         char number[AST_MAX_EXTENSION];
2237
2238         apply_plan_to_existing_number(number, sizeof(number), pri, pri_number->str,
2239                 pri_number->plan);
2240         ast_number->str = ast_strdup(number);
2241         ast_number->plan = pri_number->plan;
2242         ast_number->presentation = pri_to_ast_presentation(pri_number->presentation);
2243         ast_number->valid = 1;
2244 }
2245
2246 /*!
2247  * \internal
2248  * \brief Convert libpri party id into asterisk party id.
2249  * \since 1.8
2250  *
2251  * \param ast_id Asterisk party id structure to fill.  Must already be set initialized.
2252  * \param pri_id libpri party id structure containing source information.
2253  * \param pri PRI span control structure.
2254  *
2255  * \note The filled in ast_id structure needs to be destroyed by
2256  * ast_party_id_free() when it is no longer needed.
2257  *
2258  * \return Nothing
2259  */
2260 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)
2261 {
2262         if (pri_id->name.valid) {
2263                 sig_pri_party_name_convert(&ast_id->name, &pri_id->name);
2264         }
2265         if (pri_id->number.valid) {
2266                 sig_pri_party_number_convert(&ast_id->number, &pri_id->number, pri);
2267         }
2268 #if defined(HAVE_PRI_SUBADDR)
2269         if (pri_id->subaddress.valid) {
2270                 sig_pri_set_subaddress(&ast_id->subaddress, &pri_id->subaddress);
2271         }
2272 #endif  /* defined(HAVE_PRI_SUBADDR) */
2273 }
2274
2275 /*!
2276  * \internal
2277  * \brief Convert libpri redirecting information into asterisk redirecting information.
2278  * \since 1.8
2279  *
2280  * \param ast_redirecting Asterisk redirecting structure to fill.
2281  * \param pri_redirecting libpri redirecting structure containing source information.
2282  * \param ast_guide Asterisk redirecting structure to use as an initialization guide.
2283  * \param pri PRI span control structure.
2284  *
2285  * \note The filled in ast_redirecting structure needs to be destroyed by
2286  * ast_party_redirecting_free() when it is no longer needed.
2287  *
2288  * \return Nothing
2289  */
2290 static void sig_pri_redirecting_convert(struct ast_party_redirecting *ast_redirecting,
2291         const struct pri_party_redirecting *pri_redirecting,
2292         const struct ast_party_redirecting *ast_guide,
2293         struct sig_pri_span *pri)
2294 {
2295         ast_party_redirecting_set_init(ast_redirecting, ast_guide);
2296
2297         sig_pri_party_id_convert(&ast_redirecting->orig, &pri_redirecting->orig_called, pri);
2298         sig_pri_party_id_convert(&ast_redirecting->from, &pri_redirecting->from, pri);
2299         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
2300         ast_redirecting->count = pri_redirecting->count;
2301         ast_redirecting->reason.code = pri_to_ast_reason(pri_redirecting->reason);
2302         ast_redirecting->orig_reason.code = pri_to_ast_reason(pri_redirecting->orig_reason);
2303 }
2304
2305 /*!
2306  * \internal
2307  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
2308  * \since 1.8
2309  *
2310  * \param msn_patterns Comma separated list of MSN patterns to match.
2311  * \param exten Extension to match in the MSN list.
2312  *
2313  * \retval 1 if matches.
2314  * \retval 0 if no match.
2315  */
2316 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
2317 {
2318         char *pattern;
2319         char *msn_list;
2320         char *list_tail;
2321
2322         msn_list = ast_strdupa(msn_patterns);
2323
2324         list_tail = NULL;
2325         pattern = strtok_r(msn_list, ",", &list_tail);
2326         while (pattern) {
2327                 pattern = ast_strip(pattern);
2328                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
2329                         /* Extension matched the pattern. */
2330                         return 1;
2331                 }
2332                 pattern = strtok_r(NULL, ",", &list_tail);
2333         }
2334         /* Did not match any pattern in the list. */
2335         return 0;
2336 }
2337
2338 #if defined(HAVE_PRI_MCID)
2339 static void party_number_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *number)
2340 {
2341         const char *num_txt, *pres_txt;
2342         int plan, pres;
2343         if (!number) {
2344                 ast_str_append(msg, 0,
2345                         "%sNumValid: 0\r\n"
2346                         "%sNum: \r\n"
2347                         "%ston: 0\r\n",
2348                         prefix, prefix, prefix);
2349                 return;
2350         }
2351
2352         num_txt = ast_json_string_get(ast_json_object_get(number, "number"));
2353         plan = ast_json_integer_get(ast_json_object_get(number, "plan"));
2354         pres = ast_json_integer_get(ast_json_object_get(number, "presentation"));
2355         pres_txt = ast_json_string_get(ast_json_object_get(number, "presentation_txt"));
2356
2357         ast_str_append(msg, 0, "%sNumValid: 1\r\n", prefix);
2358         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix, num_txt);
2359         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, plan);
2360         ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, plan);
2361         ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix, pres, pres_txt);
2362 }
2363
2364 static void party_name_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *name)
2365 {
2366         const char *name_txt, *pres_txt, *charset;
2367         int pres;
2368         if (!name) {
2369                 ast_str_append(msg, 0,
2370                         "%sNameValid: 0\r\n"
2371                         "%sName: \r\n",
2372                         prefix, prefix);
2373                 return;
2374         }
2375
2376         name_txt = ast_json_string_get(ast_json_object_get(name, "name"));
2377         charset = ast_json_string_get(ast_json_object_get(name, "character_set"));
2378         pres = ast_json_integer_get(ast_json_object_get(name, "presentation"));
2379         pres_txt = ast_json_string_get(ast_json_object_get(name, "presentation_txt"));
2380
2381         ast_str_append(msg, 0, "%sNameValid: 1\r\n", prefix);
2382         ast_str_append(msg, 0, "%sName: %s\r\n", prefix, name_txt);
2383         ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix, charset);
2384         ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix, pres, pres_txt);
2385 }
2386
2387 static void party_subaddress_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *subaddress)
2388 {
2389         const char *subaddress_txt, *type_txt;
2390         int odd;
2391         if (!subaddress) {
2392                 return;
2393         }
2394
2395         subaddress_txt = ast_json_string_get(ast_json_object_get(subaddress, "subaddress"));
2396         type_txt = ast_json_string_get(ast_json_object_get(subaddress, "type"));
2397         odd = ast_json_is_true(ast_json_object_get(subaddress, "odd")) ? 1 : 0;
2398
2399         ast_str_append(msg, 0, "%sSubaddr: %s\r\n", prefix, subaddress_txt);
2400         ast_str_append(msg, 0, "%sSubaddrType: %s\r\n", prefix, type_txt);
2401         ast_str_append(msg, 0, "%sSubaddrOdd: %d\r\n", prefix, odd);
2402 }
2403
2404 /*!
2405  * \internal
2406  * \brief Append the given JSON party id to the event string.
2407  * \since 1.8
2408  *
2409  * \param msg Event message string being built.
2410  * \param prefix Prefix to add to the party id lines.
2411  * \param party Party information to encode.
2412  *
2413  * \return Nothing
2414  */
2415 static void party_json_to_ami(struct ast_str **msg, const char *prefix, struct ast_json *party)
2416 {
2417         struct ast_json *presentation = ast_json_object_get(party, "presentation");
2418         struct ast_json *presentation_txt = ast_json_object_get(party, "presentation_txt");
2419         struct ast_json *name = ast_json_object_get(party, "name");
2420         struct ast_json *number = ast_json_object_get(party, "number");
2421         struct ast_json *subaddress = ast_json_object_get(party, "subaddress");
2422
2423         /* Combined party presentation */
2424         ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix,
2425                 (uint32_t)ast_json_integer_get(presentation),
2426                 ast_json_string_get(presentation_txt));
2427
2428         /* Party number */
2429         party_number_json_to_ami(msg, prefix, number);
2430
2431         /* Party name */
2432         party_name_json_to_ami(msg, prefix, name);
2433
2434         /* Party subaddress */
2435         party_subaddress_json_to_ami(msg, prefix, subaddress);
2436 }
2437
2438 static struct ast_manager_event_blob *mcid_to_ami(struct stasis_message *msg)
2439 {
2440         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
2441         RAII_VAR(struct ast_str *, party_string, ast_str_create(256), ast_free);
2442         struct ast_channel_blob *obj = stasis_message_data(msg);
2443
2444         if (obj->snapshot) {
2445                 channel_string = ast_manager_build_channel_state_string(obj->snapshot);
2446                 if (!channel_string) {
2447                         return NULL;
2448                 }
2449         }
2450
2451         party_json_to_ami(&party_string, "MCallerID", ast_json_object_get(obj->blob, "caller"));
2452         party_json_to_ami(&party_string, "MConnectedID", ast_json_object_get(obj->blob, "connected"));
2453
2454         return ast_manager_event_blob_create(EVENT_FLAG_CALL, "MCID",
2455                 "%s"
2456                 "%s",
2457                 S_COR(obj->snapshot, ast_str_buffer(channel_string), ""), ast_str_buffer(party_string));
2458 }
2459
2460 STASIS_MESSAGE_TYPE_DEFN_LOCAL(mcid_type,
2461         .to_ami = mcid_to_ami,
2462         );
2463
2464 static void send_mcid(struct ast_channel *chan, struct ast_party_id *caller, struct ast_party_id *connected)
2465 {
2466         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
2467
2468         ast_assert(caller != NULL);
2469         ast_assert(connected != NULL);
2470
2471         blob = ast_json_pack("{s: o, s: o}",
2472                 "caller", ast_json_party_id(caller),
2473                 "connected", ast_json_party_id(connected));
2474         if (!blob) {
2475                 return;
2476         }
2477
2478         ast_channel_publish_blob(chan, mcid_type(), blob);
2479 }
2480
2481 /*!
2482  * \internal
2483  * \brief Handle the MCID event.
2484  * \since 1.8
2485  *
2486  * \param pri PRI span control structure.
2487  * \param mcid MCID event parameters.
2488  * \param owner Asterisk channel associated with the call.
2489  * NULL if Asterisk no longer has the ast_channel struct.
2490  *
2491  * \note Assumes the pri->lock is already obtained.
2492  * \note Assumes the owner channel lock is already obtained if still present.
2493  *
2494  * \return Nothing
2495  */
2496 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
2497 {
2498         struct ast_party_id caller_party;
2499         struct ast_party_id connected_party;
2500
2501         /* Always use libpri's called party information. */
2502         ast_party_id_init(&connected_party);
2503         sig_pri_party_id_convert(&connected_party, &mcid->answerer, pri);
2504         if (owner) {
2505                 /*
2506                  * The owner channel is present.
2507                  * Pass the event to the peer as well.
2508                  */
2509                 ast_queue_control(owner, AST_CONTROL_MCID);
2510
2511                 send_mcid(owner, &ast_channel_connected(owner)->id, &connected_party);
2512         } else {
2513                 /*
2514                  * Since we no longer have an owner channel,
2515                  * we have to use the caller information supplied by libpri.
2516                  */
2517                 ast_party_id_init(&caller_party);
2518                 sig_pri_party_id_convert(&caller_party, &mcid->originator, pri);
2519                 send_mcid(owner, &caller_party, &connected_party);
2520                 ast_party_id_free(&caller_party);
2521         }
2522         ast_party_id_free(&connected_party);
2523 }
2524 #endif  /* defined(HAVE_PRI_MCID) */
2525
2526 #if defined(HAVE_PRI_TRANSFER)
2527 struct xfer_rsp_data {
2528         struct sig_pri_span *pri;
2529         /*! Call to send transfer success/fail response over. */
2530         q931_call *call;
2531         /*! Invocation ID to use when sending a reply to the transfer request. */
2532         int invoke_id;
2533         /*! TRUE if the transfer response has been made. */
2534         int responded;
2535 };
2536 #endif  /* defined(HAVE_PRI_TRANSFER) */
2537
2538 #if defined(HAVE_PRI_TRANSFER)
2539 /*!
2540  * \internal
2541  * \brief Send the transfer success/fail response message.
2542  * \since 1.8
2543  *
2544  * \param rsp Transfer response data.
2545  * \param is_successful TRUE if the transfer was successful.
2546  *
2547  * \note Assumes the rsp->pri->lock is already obtained.
2548  *
2549  * \return Nothing
2550  */
2551 static void sig_pri_transfer_rsp(struct xfer_rsp_data *rsp, int is_successful)
2552 {
2553         if (rsp->responded) {
2554                 return;
2555         }
2556         rsp->responded = 1;
2557
2558         pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
2559 }
2560 #endif  /* defined(HAVE_PRI_TRANSFER) */
2561
2562 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2563 /*!
2564  * \internal
2565  * \brief Attempt to transfer the two calls to each other.
2566  * \since 1.8
2567  *
2568  * \param pri PRI span control structure.
2569  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
2570  * \param call_1_held TRUE if call_1_pri is on hold.
2571  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
2572  * \param call_2_held TRUE if call_2_pri is on hold.
2573  * \param xfer_data Transfer response data if non-NULL.
2574  *
2575  * \note Assumes the pri->lock is already obtained.
2576  *
2577  * \retval 0 on success.
2578  * \retval -1 on error.
2579  */
2580 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)
2581 {
2582         struct attempt_xfer_call {
2583                 q931_call *pri;
2584                 struct ast_channel *ast;
2585                 int held;
2586                 int chanpos;
2587         };
2588         int retval;
2589         enum ast_transfer_result xfer_res;
2590         struct attempt_xfer_call *call_1;
2591         struct attempt_xfer_call *call_2;
2592         struct attempt_xfer_call c1;
2593         struct attempt_xfer_call c2;
2594
2595         c1.pri = call_1_pri;
2596         c1.held = call_1_held;
2597         call_1 = &c1;
2598
2599         c2.pri = call_2_pri;
2600         c2.held = call_2_held;
2601         call_2 = &c2;
2602
2603         call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
2604         call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
2605         if (call_1->chanpos < 0 || call_2->chanpos < 0) {
2606                 /* Calls not found in span control. */
2607 #if defined(HAVE_PRI_TRANSFER)
2608                 if (xfer_data) {
2609                         /* Transfer failed. */
2610                         sig_pri_transfer_rsp(xfer_data, 0);
2611                 }
2612 #endif  /* defined(HAVE_PRI_TRANSFER) */
2613                 return -1;
2614         }
2615
2616         /* Get call_1 owner. */
2617         sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2618         sig_pri_lock_owner(pri, call_1->chanpos);
2619         call_1->ast = pri->pvts[call_1->chanpos]->owner;
2620         if (call_1->ast) {
2621                 ast_channel_ref(call_1->ast);
2622                 ast_channel_unlock(call_1->ast);
2623         }
2624         sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2625
2626         /* Get call_2 owner. */
2627         sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2628         sig_pri_lock_owner(pri, call_2->chanpos);
2629         call_2->ast = pri->pvts[call_2->chanpos]->owner;
2630         if (call_2->ast) {
2631                 ast_channel_ref(call_2->ast);
2632                 ast_channel_unlock(call_2->ast);
2633         }
2634         sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2635
2636         if (!call_1->ast || !call_2->ast) {
2637                 /* At least one owner is not present. */
2638                 if (call_1->ast) {
2639                         ast_channel_unref(call_1->ast);
2640                 }
2641                 if (call_2->ast) {
2642                         ast_channel_unref(call_2->ast);
2643                 }
2644 #if defined(HAVE_PRI_TRANSFER)
2645                 if (xfer_data) {
2646                         /* Transfer failed. */
2647                         sig_pri_transfer_rsp(xfer_data, 0);
2648                 }
2649 #endif  /* defined(HAVE_PRI_TRANSFER) */
2650                 return -1;
2651         }
2652
2653         ast_verb(3, "TRANSFERRING %s to %s\n",
2654                 ast_channel_name(call_1->ast), ast_channel_name(call_2->ast));
2655
2656 #if defined(HAVE_PRI_TRANSFER)
2657         if (xfer_data) {
2658                 /*
2659                  * Add traps on the transferer channels in case threading causes
2660                  * them to hangup before ast_bridge_transfer_attended() returns
2661                  * and we can get the pri->lock back.
2662                  */
2663                 sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2664                 pri->pvts[call_1->chanpos]->xfer_data = xfer_data;
2665                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2666                 sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2667                 pri->pvts[call_2->chanpos]->xfer_data = xfer_data;
2668                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2669         }
2670 #endif  /* defined(HAVE_PRI_TRANSFER) */
2671
2672         ast_mutex_unlock(&pri->lock);
2673         xfer_res = ast_bridge_transfer_attended(call_1->ast, call_2->ast);
2674         ast_mutex_lock(&pri->lock);
2675         retval = (xfer_res != AST_BRIDGE_TRANSFER_SUCCESS) ? -1 : 0;
2676
2677 #if defined(HAVE_PRI_TRANSFER)
2678         if (xfer_data) {
2679                 int rsp_chanpos;
2680
2681                 /*
2682                  * Remove the transferrer channel traps.
2683                  *
2684                  * We must refind chanpos because we released pri->lock.
2685                  */
2686                 rsp_chanpos = pri_find_principle_by_call(pri, call_1->pri);
2687                 if (0 <= rsp_chanpos) {
2688                         sig_pri_lock_private(pri->pvts[rsp_chanpos]);
2689                         pri->pvts[rsp_chanpos]->xfer_data = NULL;
2690                         sig_pri_unlock_private(pri->pvts[rsp_chanpos]);
2691                 }
2692                 rsp_chanpos = pri_find_principle_by_call(pri, call_2->pri);
2693                 if (0 <= rsp_chanpos) {
2694                         sig_pri_lock_private(pri->pvts[rsp_chanpos]);
2695                         pri->pvts[rsp_chanpos]->xfer_data = NULL;
2696                         sig_pri_unlock_private(pri->pvts[rsp_chanpos]);
2697                 }
2698
2699                 /* Report transfer status. */
2700                 sig_pri_transfer_rsp(xfer_data, retval ? 0 : 1);
2701         }
2702 #endif  /* defined(HAVE_PRI_TRANSFER) */
2703         ast_channel_unref(call_1->ast);
2704         ast_channel_unref(call_2->ast);
2705         return retval;
2706 }
2707 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2708
2709 #if defined(HAVE_PRI_CCSS)
2710 /*!
2711  * \internal
2712  * \brief Compare the CC agent private data by libpri cc_id.
2713  * \since 1.8
2714  *
2715  * \param obj pointer to the (user-defined part) of an object.
2716  * \param arg callback argument from ao2_callback()
2717  * \param flags flags from ao2_callback()
2718  *
2719  * \return values are a combination of enum _cb_results.
2720  */
2721 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
2722 {
2723         struct ast_cc_agent *agent_1 = obj;
2724         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2725         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2726
2727         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2728                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2729 }
2730 #endif  /* defined(HAVE_PRI_CCSS) */
2731
2732 #if defined(HAVE_PRI_CCSS)
2733 /*!
2734  * \internal
2735  * \brief Find the CC agent by libpri cc_id.
2736  * \since 1.8
2737  *
2738  * \param pri PRI span control structure.
2739  * \param cc_id CC record ID to find.
2740  *
2741  * \note
2742  * Since agents are refcounted, and this function returns
2743  * a reference to the agent, it is imperative that you decrement
2744  * the refcount of the agent once you have finished using it.
2745  *
2746  * \retval agent on success.
2747  * \retval NULL not found.
2748  */
2749 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2750 {
2751         struct sig_pri_cc_agent_prv finder = {
2752                 .pri = pri,
2753                 .cc_id = cc_id,
2754         };
2755
2756         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2757                 sig_pri_cc_type_name);
2758 }
2759 #endif  /* defined(HAVE_PRI_CCSS) */
2760
2761 #if defined(HAVE_PRI_CCSS)
2762 /*!
2763  * \internal
2764  * \brief Compare the CC monitor instance by libpri cc_id.
2765  * \since 1.8
2766  *
2767  * \param obj pointer to the (user-defined part) of an object.
2768  * \param arg callback argument from ao2_callback()
2769  * \param flags flags from ao2_callback()
2770  *
2771  * \return values are a combination of enum _cb_results.
2772  */
2773 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2774 {
2775         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2776         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2777
2778         return (monitor_1->pri == monitor_2->pri
2779                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2780 }
2781 #endif  /* defined(HAVE_PRI_CCSS) */
2782
2783 #if defined(HAVE_PRI_CCSS)
2784 /*!
2785  * \internal
2786  * \brief Find the CC monitor instance by libpri cc_id.
2787  * \since 1.8
2788  *
2789  * \param pri PRI span control structure.
2790  * \param cc_id CC record ID to find.
2791  *
2792  * \note
2793  * Since monitor_instances are refcounted, and this function returns
2794  * a reference to the instance, it is imperative that you decrement
2795  * the refcount of the instance once you have finished using it.
2796  *
2797  * \retval monitor_instance on success.
2798  * \retval NULL not found.
2799  */
2800 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2801 {
2802         struct sig_pri_cc_monitor_instance finder = {
2803                 .pri = pri,
2804                 .cc_id = cc_id,
2805         };
2806
2807         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2808 }
2809 #endif  /* defined(HAVE_PRI_CCSS) */
2810
2811 #if defined(HAVE_PRI_CCSS)
2812 /*!
2813  * \internal
2814  * \brief Destroy the given monitor instance.
2815  * \since 1.8
2816  *
2817  * \param data Monitor instance to destroy.
2818  *
2819  * \return Nothing
2820  */
2821 static void sig_pri_cc_monitor_instance_destroy(void *data)
2822 {
2823         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2824
2825         if (monitor_instance->cc_id != -1) {
2826                 ast_mutex_lock(&monitor_instance->pri->lock);
2827                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2828                 ast_mutex_unlock(&monitor_instance->pri->lock);
2829         }
2830         sig_pri_callbacks.module_unref();
2831 }
2832 #endif  /* defined(HAVE_PRI_CCSS) */
2833
2834 #if defined(HAVE_PRI_CCSS)
2835 /*!
2836  * \internal
2837  * \brief Construct a new monitor instance.
2838  * \since 1.8
2839  *
2840  * \param core_id CC core ID.
2841  * \param pri PRI span control structure.
2842  * \param cc_id CC record ID.
2843  * \param device_name Name of device (Asterisk channel name less sequence number).
2844  *
2845  * \note
2846  * Since monitor_instances are refcounted, and this function returns
2847  * a reference to the instance, it is imperative that you decrement
2848  * the refcount of the instance once you have finished using it.
2849  *
2850  * \retval monitor_instance on success.
2851  * \retval NULL on error.
2852  */
2853 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)
2854 {
2855         struct sig_pri_cc_monitor_instance *monitor_instance;
2856
2857         if (!sig_pri_callbacks.module_ref || !sig_pri_callbacks.module_unref) {
2858                 return NULL;
2859         }
2860
2861         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2862                 sig_pri_cc_monitor_instance_destroy);
2863         if (!monitor_instance) {
2864                 return NULL;
2865         }
2866
2867         monitor_instance->cc_id = cc_id;
2868         monitor_instance->pri = pri;
2869         monitor_instance->core_id = core_id;
2870         strcpy(monitor_instance->name, device_name);
2871
2872         sig_pri_callbacks.module_ref();
2873
2874         ao2_link(sig_pri_cc_monitors, monitor_instance);
2875         return monitor_instance;
2876 }
2877 #endif  /* defined(HAVE_PRI_CCSS) */
2878
2879 #if defined(HAVE_PRI_CCSS)
2880 /*!
2881  * \internal
2882  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2883  * \since 1.8
2884  *
2885  * \param pri PRI span control structure.
2886  * \param chanpos Channel position in the span.
2887  * \param cc_id CC record ID.
2888  * \param service CCBS/CCNR indication.
2889  *
2890  * \note Assumes the pri->lock is already obtained.
2891  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2892  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2893  *
2894  * \retval 0 on success.
2895  * \retval -1 on error.
2896  */
2897 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2898 {
2899         struct sig_pri_chan *pvt;
2900         struct ast_cc_config_params *cc_params;
2901         struct sig_pri_cc_monitor_instance *monitor;
2902         enum ast_cc_monitor_policies monitor_policy;
2903         int core_id;
2904         int res;
2905         char device_name[AST_CHANNEL_NAME];
2906         char dialstring[AST_CHANNEL_NAME];
2907
2908         pvt = pri->pvts[chanpos];
2909
2910         core_id = ast_cc_get_current_core_id(pvt->owner);
2911         if (core_id == -1) {
2912                 return -1;
2913         }
2914
2915         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2916         if (!cc_params) {
2917                 return -1;
2918         }
2919
2920         res = -1;
2921         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2922         switch (monitor_policy) {
2923         case AST_CC_MONITOR_NEVER:
2924                 /* CCSS is not enabled. */
2925                 break;
2926         case AST_CC_MONITOR_NATIVE:
2927         case AST_CC_MONITOR_ALWAYS:
2928                 /*
2929                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2930                  * later in the call to sig_pri_cc_generic_check().
2931                  */
2932                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2933                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2934                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2935                 if (!monitor) {
2936                         break;
2937                 }
2938                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2939                         monitor);
2940                 if (res) {
2941                         monitor->cc_id = -1;
2942                         ao2_unlink(sig_pri_cc_monitors, monitor);
2943                         ao2_ref(monitor, -1);
2944                 }
2945                 break;
2946         case AST_CC_MONITOR_GENERIC:
2947                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2948                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2949                 /* Say it failed to force caller to cancel native CC. */
2950                 break;
2951         }
2952         return res;
2953 }
2954 #endif  /* defined(HAVE_PRI_CCSS) */
2955
2956 /*!
2957  * \internal
2958  * \brief Check if generic CC monitor is needed and request it.
2959  * \since 1.8
2960  *
2961  * \param pri PRI span control structure.
2962  * \param chanpos Channel position in the span.
2963  * \param service CCBS/CCNR indication.
2964  *
2965  * \note Assumes the pri->lock is already obtained.
2966  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2967  *
2968  * \return Nothing
2969  */
2970 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
2971 {
2972         struct ast_channel *owner;
2973         struct ast_cc_config_params *cc_params;
2974 #if defined(HAVE_PRI_CCSS)
2975         struct ast_cc_monitor *monitor;
2976         char device_name[AST_CHANNEL_NAME];
2977 #endif  /* defined(HAVE_PRI_CCSS) */
2978         enum ast_cc_monitor_policies monitor_policy;
2979         int core_id;
2980
2981         if (!pri->pvts[chanpos]->outgoing) {
2982                 /* This is not an outgoing call so it cannot be CC monitor. */
2983                 return;
2984         }
2985
2986         sig_pri_lock_owner(pri, chanpos);
2987         owner = pri->pvts[chanpos]->owner;
2988         if (!owner) {
2989                 return;
2990         }
2991         core_id = ast_cc_get_current_core_id(owner);
2992         if (core_id == -1) {
2993                 /* No CC core setup */
2994                 goto done;
2995         }
2996
2997         cc_params = ast_channel_get_cc_config_params(owner);
2998         if (!cc_params) {
2999                 /* Could not get CC config parameters. */
3000                 goto done;
3001         }
3002
3003 #if defined(HAVE_PRI_CCSS)
3004         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
3005         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
3006         if (monitor) {
3007                 /* CC monitor is already present so no need for generic CC. */
3008                 ao2_ref(monitor, -1);
3009                 goto done;
3010         }
3011 #endif  /* defined(HAVE_PRI_CCSS) */
3012
3013         monitor_policy = ast_get_cc_monitor_policy(cc_params);
3014         switch (monitor_policy) {
3015         case AST_CC_MONITOR_NEVER:
3016                 /* CCSS is not enabled. */
3017                 break;
3018         case AST_CC_MONITOR_NATIVE:
3019                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
3020                         /* Request generic CC monitor. */
3021                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3022                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3023                 }
3024                 break;
3025         case AST_CC_MONITOR_ALWAYS:
3026                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
3027                         /*
3028                          * Cannot monitor PTMP TE side since this is not defined.
3029                          * We are playing the roll of a phone in this case and
3030                          * a phone cannot monitor a party over the network without
3031                          * protocol help.
3032                          */
3033                         break;
3034                 }
3035                 /*
3036                  * We are either falling back or this is a PTMP NT span.
3037                  * Request generic CC monitor.
3038                  */
3039                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3040                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3041                 break;
3042         case AST_CC_MONITOR_GENERIC:
3043                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
3044                         /* Request generic CC monitor. */
3045                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
3046                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
3047                 }
3048                 break;
3049         }
3050
3051 done:
3052         ast_channel_unlock(owner);
3053 }
3054
3055 #if defined(HAVE_PRI_CCSS)
3056 /*!
3057  * \internal
3058  * \brief The CC link canceled the CC instance.
3059  * \since 1.8
3060  *
3061  * \param pri PRI span control structure.
3062  * \param cc_id CC record ID.
3063  * \param is_agent TRUE if the cc_id is for an agent.
3064  *
3065  * \return Nothing
3066  */
3067 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
3068 {
3069         if (is_agent) {
3070                 struct ast_cc_agent *agent;
3071
3072                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
3073                 if (!agent) {
3074                         return;
3075                 }
3076                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
3077                         sig_pri_cc_type_name);
3078                 ao2_ref(agent, -1);
3079         } else {
3080                 struct sig_pri_cc_monitor_instance *monitor;
3081
3082                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
3083                 if (!monitor) {
3084                         return;
3085                 }
3086                 monitor->cc_id = -1;
3087                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
3088                         "%s monitor got canceled by link", sig_pri_cc_type_name);
3089                 ao2_ref(monitor, -1);
3090         }
3091 }
3092 #endif  /* defined(HAVE_PRI_CCSS) */
3093
3094 #if defined(HAVE_PRI_AOC_EVENTS)
3095 /*!
3096  * \internal
3097  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
3098  * \since 1.8
3099  *
3100  * \param value Value to convert to string.
3101  *
3102  * \return PRI_AOC_CHARGED_ITEM
3103  */
3104 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
3105 {
3106         switch (value) {
3107         case AST_AOC_CHARGED_ITEM_NA:
3108                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
3109         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
3110                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
3111         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
3112                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
3113         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
3114                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
3115         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
3116                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
3117         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
3118                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
3119         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
3120                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
3121         }
3122         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
3123 }
3124 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3125
3126 #if defined(HAVE_PRI_AOC_EVENTS)
3127 /*!
3128  * \internal
3129  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
3130  * \since 1.8
3131  *
3132  * \param value Value to convert to string.
3133  *
3134  * \return ast_aoc_charged_item
3135  */
3136 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
3137 {
3138         switch (value) {
3139         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
3140                 return AST_AOC_CHARGED_ITEM_NA;
3141         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
3142                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
3143         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
3144                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
3145         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
3146                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
3147         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
3148                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
3149         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
3150                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
3151         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
3152                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
3153         }
3154         return AST_AOC_CHARGED_ITEM_NA;
3155 }
3156 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3157
3158 #if defined(HAVE_PRI_AOC_EVENTS)
3159 /*!
3160  * \internal
3161  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
3162  * \since 1.8
3163  *
3164  * \return pri enum equivalent.
3165  */
3166 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
3167 {
3168         switch (mult) {
3169         case AST_AOC_MULT_ONETHOUSANDTH:
3170                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
3171         case AST_AOC_MULT_ONEHUNDREDTH:
3172                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
3173         case AST_AOC_MULT_ONETENTH:
3174                 return PRI_AOC_MULTIPLIER_TENTH;
3175         case AST_AOC_MULT_ONE:
3176                 return PRI_AOC_MULTIPLIER_ONE;
3177         case AST_AOC_MULT_TEN:
3178                 return PRI_AOC_MULTIPLIER_TEN;
3179         case AST_AOC_MULT_HUNDRED:
3180                 return PRI_AOC_MULTIPLIER_HUNDRED;
3181         case AST_AOC_MULT_THOUSAND:
3182                 return PRI_AOC_MULTIPLIER_THOUSAND;
3183         default:
3184                 return PRI_AOC_MULTIPLIER_ONE;
3185         }
3186 }
3187 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3188
3189 #if defined(HAVE_PRI_AOC_EVENTS)
3190 /*!
3191  * \internal
3192  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
3193  * \since 1.8
3194  *
3195  * \return ast enum equivalent.
3196  */
3197 static int sig_pri_aoc_multiplier_from_pri(const int mult)
3198 {
3199         switch (mult) {
3200         case PRI_AOC_MULTIPLIER_THOUSANDTH:
3201                 return AST_AOC_MULT_ONETHOUSANDTH;
3202         case PRI_AOC_MULTIPLIER_HUNDREDTH:
3203                 return AST_AOC_MULT_ONEHUNDREDTH;
3204         case PRI_AOC_MULTIPLIER_TENTH:
3205                 return AST_AOC_MULT_ONETENTH;
3206         case PRI_AOC_MULTIPLIER_ONE:
3207                 return AST_AOC_MULT_ONE;
3208         case PRI_AOC_MULTIPLIER_TEN:
3209                 return AST_AOC_MULT_TEN;
3210         case PRI_AOC_MULTIPLIER_HUNDRED:
3211                 return AST_AOC_MULT_HUNDRED;
3212         case PRI_AOC_MULTIPLIER_THOUSAND:
3213                 return AST_AOC_MULT_THOUSAND;
3214         default:
3215                 return AST_AOC_MULT_ONE;
3216         }
3217 }
3218 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3219
3220 #if defined(HAVE_PRI_AOC_EVENTS)
3221 /*!
3222  * \internal
3223  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
3224  * \since 1.8
3225  *
3226  * \param value Value to convert to ast representation
3227  *
3228  * \return PRI_AOC_TIME_SCALE
3229  */
3230 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
3231 {
3232         switch (value) {
3233         default:
3234         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3235                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3236         case AST_AOC_TIME_SCALE_TENTH_SECOND:
3237                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
3238         case AST_AOC_TIME_SCALE_SECOND:
3239                 return PRI_AOC_TIME_SCALE_SECOND;
3240         case AST_AOC_TIME_SCALE_TEN_SECOND:
3241                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
3242         case AST_AOC_TIME_SCALE_MINUTE:
3243                 return PRI_AOC_TIME_SCALE_MINUTE;
3244         case AST_AOC_TIME_SCALE_HOUR:
3245                 return PRI_AOC_TIME_SCALE_HOUR;
3246         case AST_AOC_TIME_SCALE_DAY:
3247                 return PRI_AOC_TIME_SCALE_DAY;
3248         }
3249 }
3250 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3251
3252 #if defined(HAVE_PRI_AOC_EVENTS)
3253 /*!
3254  * \internal
3255  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
3256  * \since 1.8
3257  *
3258  * \param value Value to convert to ast representation
3259  *
3260  * \return ast aoc time scale
3261  */
3262 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
3263 {
3264         switch (value) {
3265         default:
3266         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3267                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3268         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
3269                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
3270         case PRI_AOC_TIME_SCALE_SECOND:
3271                 return AST_AOC_TIME_SCALE_SECOND;
3272         case PRI_AOC_TIME_SCALE_TEN_SECOND:
3273                 return AST_AOC_TIME_SCALE_TEN_SECOND;
3274         case PRI_AOC_TIME_SCALE_MINUTE:
3275                 return AST_AOC_TIME_SCALE_MINUTE;
3276         case PRI_AOC_TIME_SCALE_HOUR:
3277                 return AST_AOC_TIME_SCALE_HOUR;
3278         case PRI_AOC_TIME_SCALE_DAY:
3279                 return AST_AOC_TIME_SCALE_DAY;
3280         }
3281         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3282 }
3283 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3284
3285 #if defined(HAVE_PRI_AOC_EVENTS)
3286 /*!
3287  * \internal
3288  * \brief Handle AOC-S control frame
3289  * \since 1.8
3290  *
3291  * \param aoc_s AOC-S event parameters.
3292  * \param owner Asterisk channel associated with the call.
3293  * \param passthrough indicating if this message should be queued on the ast channel
3294  *
3295  * \note Assumes the pri->lock is already obtained.
3296  * \note Assumes the sig_pri private is locked
3297  * \note Assumes the owner channel lock is already obtained.
3298  *
3299  * \return Nothing
3300  */
3301 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
3302 {
3303         struct ast_aoc_decoded *decoded = NULL;
3304         struct ast_aoc_encoded *encoded = NULL;
3305         size_t encoded_size = 0;
3306         int idx;
3307
3308         if (!owner || !aoc_s) {
3309                 return;
3310         }
3311
3312         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
3313                 return;
3314         }
3315
3316         for (idx = 0; idx < aoc_s->num_items; ++idx) {
3317                 enum ast_aoc_s_charged_item charged_item;
3318
3319                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
3320                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
3321                         /* Delete the unknown charged item from the list. */
3322                         continue;
3323                 }
3324                 switch (aoc_s->item[idx].rate_type) {
3325                 case PRI_AOC_RATE_TYPE_DURATION:
3326                         ast_aoc_s_add_rate_duration(decoded,
3327                                 charged_item,
3328                                 aoc_s->item[idx].rate.duration.amount.cost,
3329                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
3330                                 aoc_s->item[idx].rate.duration.currency,
3331                                 aoc_s->item[idx].rate.duration.time.length,
3332                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
3333                                 aoc_s->item[idx].rate.duration.granularity.length,
3334                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
3335                                 aoc_s->item[idx].rate.duration.charging_type);
3336                         break;
3337                 case PRI_AOC_RATE_TYPE_FLAT:
3338                         ast_aoc_s_add_rate_flat(decoded,
3339                                 charged_item,
3340                                 aoc_s->item[idx].rate.flat.amount.cost,
3341                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
3342                                 aoc_s->item[idx].rate.flat.currency);
3343                         break;
3344                 case PRI_AOC_RATE_TYPE_VOLUME:
3345                         ast_aoc_s_add_rate_volume(decoded,
3346                                 charged_item,
3347                                 aoc_s->item[idx].rate.volume.unit,
3348                                 aoc_s->item[idx].rate.volume.amount.cost,
3349                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
3350                                 aoc_s->item[idx].rate.volume.currency);
3351                         break;
3352                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
3353                         ast_aoc_s_add_rate_special_charge_code(decoded,
3354                                 charged_item,
3355                                 aoc_s->item[idx].rate.special);
3356                         break;
3357                 case PRI_AOC_RATE_TYPE_FREE:
3358                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
3359                         break;
3360                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3361                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
3362                         break;
3363                 default:
3364                         ast_aoc_s_add_rate_na(decoded, charged_item);
3365                         break;
3366                 }
3367         }
3368
3369         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3370                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3371         }
3372
3373         ast_aoc_manager_event(decoded, owner);
3374
3375         ast_aoc_destroy_decoded(decoded);
3376         ast_aoc_destroy_encoded(encoded);
3377 }
3378 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3379
3380 #if defined(HAVE_PRI_AOC_EVENTS)
3381 /*!
3382  * \internal
3383  * \brief Generate AOC Request Response
3384  * \since 1.8
3385  *
3386  * \param aoc_request
3387  *
3388  * \note Assumes the pri->lock is already obtained.
3389  * \note Assumes the sig_pri private is locked
3390  * \note Assumes the owner channel lock is already obtained.
3391  *
3392  * \return Nothing
3393  */
3394 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
3395 {
3396         int request;
3397
3398         if (!aoc_request) {
3399                 return;
3400         }
3401
3402         request = aoc_request->charging_request;
3403
3404         if (request & PRI_AOC_REQUEST_S) {
3405                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
3406                         /* An AOC-S response must come from the other side, so save off this invoke_id
3407                          * and see if an AOC-S message comes in before the call is answered. */
3408                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
3409                         pvt->aoc_s_request_invoke_id_valid = 1;
3410
3411                 } else {
3412                         pri_aoc_s_request_response_send(pvt->pri->pri,
3413                                 call,
3414                                 aoc_request->invoke_id,
3415                                 NULL);
3416                 }
3417         }
3418
3419         if (request & PRI_AOC_REQUEST_D) {
3420                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
3421                         pri_aoc_de_request_response_send(pvt->pri->pri,
3422                                 call,
3423                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3424                                 aoc_request->invoke_id);
3425                 } else {
3426                         pri_aoc_de_request_response_send(pvt->pri->pri,
3427                                 call,
3428                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3429                                 aoc_request->invoke_id);
3430                 }
3431         }
3432
3433         if (request & PRI_AOC_REQUEST_E) {
3434                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
3435                         pri_aoc_de_request_response_send(pvt->pri->pri,
3436                                 call,
3437                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3438                                 aoc_request->invoke_id);
3439                 } else {
3440                         pri_aoc_de_request_response_send(pvt->pri->pri,
3441                                 call,
3442                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3443                                 aoc_request->invoke_id);
3444                 }
3445         }
3446 }
3447 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3448
3449 #if defined(HAVE_PRI_AOC_EVENTS)
3450 /*!
3451  * \internal
3452  * \brief Generate AOC-D AST_CONTROL_AOC frame
3453  * \since 1.8
3454  *
3455  * \param aoc_e AOC-D event parameters.
3456  * \param owner Asterisk channel associated with the call.
3457  * \param passthrough indicating if this message should be queued on the ast channel
3458  *
3459  * \note Assumes the pri->lock is already obtained.
3460  * \note Assumes the sig_pri private is locked
3461  * \note Assumes the owner channel lock is already obtained.
3462  *
3463  * \return Nothing
3464  */
3465 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
3466 {
3467         struct ast_aoc_decoded *decoded = NULL;
3468         struct ast_aoc_encoded *encoded = NULL;
3469         size_t encoded_size = 0;
3470         enum ast_aoc_charge_type type;
3471
3472         if (!owner || !aoc_d) {
3473                 return;
3474         }
3475
3476         switch (aoc_d->charge) {
3477         case PRI_AOC_DE_CHARGE_CURRENCY:
3478                 type = AST_AOC_CHARGE_CURRENCY;
3479                 break;
3480         case PRI_AOC_DE_CHARGE_UNITS:
3481                 type = AST_AOC_CHARGE_UNIT;
3482                 break;
3483         case PRI_AOC_DE_CHARGE_FREE:
3484                 type = AST_AOC_CHARGE_FREE;
3485                 break;
3486         default:
3487                 type = AST_AOC_CHARGE_NA;
3488                 break;
3489         }
3490
3491         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
3492                 return;
3493         }
3494
3495         switch (aoc_d->billing_accumulation) {
3496         default:
3497                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
3498                         aoc_d->billing_accumulation);
3499                 /* Fall through */
3500         case 0:/* subTotal */
3501                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
3502                 break;
3503         case 1:/* total */
3504                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
3505                 break;
3506         }
3507
3508         switch (aoc_d->billing_id) {
3509         case PRI_AOC_D_BILLING_ID_NORMAL:
3510                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3511                 break;
3512         case PRI_AOC_D_BILLING_ID_REVERSE:
3513                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3514                 break;
3515         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
3516                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3517                 break;
3518         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
3519         default:
3520                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3521                 break;
3522         }
3523
3524         switch (aoc_d->charge) {
3525         case PRI_AOC_DE_CHARGE_CURRENCY:
3526                 ast_aoc_set_currency_info(decoded,
3527                         aoc_d->recorded.money.amount.cost,
3528                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
3529                         aoc_d->recorded.money.currency);
3530                 break;
3531         case PRI_AOC_DE_CHARGE_UNITS:
3532                 {
3533                         int i;
3534                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
3535                                 /* if type or number are negative, then they are not present */
3536                                 ast_aoc_add_unit_entry(decoded,
3537                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
3538                                         aoc_d->recorded.unit.item[i].number,
3539                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
3540                                         aoc_d->recorded.unit.item[i].type);
3541                         }
3542                 }
3543                 break;
3544         }
3545
3546         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3547                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3548         }
3549
3550         ast_aoc_manager_event(decoded, owner);
3551
3552         ast_aoc_destroy_decoded(decoded);
3553         ast_aoc_destroy_encoded(encoded);
3554 }
3555 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3556
3557 #if defined(HAVE_PRI_AOC_EVENTS)
3558 /*!
3559  * \internal
3560  * \brief Generate AOC-E AST_CONTROL_AOC frame
3561  * \since 1.8
3562  *
3563  * \param aoc_e AOC-E event parameters.
3564  * \param owner Asterisk channel associated with the call.
3565  * \param passthrough indicating if this message should be queued on the ast channel
3566  *
3567  * \note Assumes the pri->lock is already obtained.
3568  * \note Assumes the sig_pri private is locked
3569  * \note Assumes the owner channel lock is already obtained.
3570  * \note owner channel may be NULL. In that case, generate event only
3571  *
3572  * \return Nothing
3573  */
3574 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
3575 {
3576         struct ast_aoc_decoded *decoded = NULL;
3577         struct ast_aoc_encoded *encoded = NULL;
3578         size_t encoded_size = 0;
3579         enum ast_aoc_charge_type type;
3580
3581         if (!aoc_e) {
3582                 return;
3583         }
3584
3585         switch (aoc_e->charge) {
3586         case PRI_AOC_DE_CHARGE_CURRENCY:
3587                 type = AST_AOC_CHARGE_CURRENCY;
3588                 break;
3589         case PRI_AOC_DE_CHARGE_UNITS:
3590                 type = AST_AOC_CHARGE_UNIT;
3591                 break;
3592         case PRI_AOC_DE_CHARGE_FREE:
3593                 type = AST_AOC_CHARGE_FREE;
3594                 break;
3595         default:
3596                 type = AST_AOC_CHARGE_NA;
3597                 break;
3598         }
3599
3600         if (!(decoded = ast_aoc_create(AST_AOC_E, type, 0))) {
3601                 return;
3602         }
3603
3604         switch (aoc_e->associated.charging_type) {
3605         case PRI_AOC_E_CHARGING_ASSOCIATION_NUMBER:
3606                 if (!aoc_e->associated.charge.number.valid) {
3607                         break;
3608                 }
3609                 ast_aoc_set_association_number(decoded, aoc_e->associated.charge.number.str, aoc_e->associated.charge.number.plan);
3610                 break;
3611         case PRI_AOC_E_CHARGING_ASSOCIATION_ID:
3612                 ast_aoc_set_association_id(decoded, aoc_e->associated.charge.id);
3613                 break;
3614         default:
3615                 break;
3616         }
3617
3618         switch (aoc_e->billing_id) {
3619         case PRI_AOC_E_BILLING_ID_NORMAL:
3620                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3621                 break;
3622         case PRI_AOC_E_BILLING_ID_REVERSE:
3623                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3624                 break;
3625         case PRI_AOC_E_BILLING_ID_CREDIT_CARD:
3626                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3627                 break;
3628         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_UNCONDITIONAL:
3629                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL);
3630                 break;
3631         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_BUSY:
3632                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_BUSY);
3633                 break;
3634         case PRI_AOC_E_BILLING_ID_CALL_FORWARDING_NO_REPLY:
3635                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_FWD_NO_REPLY);
3636                 break;
3637         case PRI_AOC_E_BILLING_ID_CALL_DEFLECTION:
3638                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_DEFLECTION);
3639                 break;
3640         case PRI_AOC_E_BILLING_ID_CALL_TRANSFER:
3641                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CALL_TRANSFER);
3642                 break;
3643         case PRI_AOC_E_BILLING_ID_NOT_AVAILABLE:
3644         default:
3645                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3646                 break;
3647         }
3648
3649         switch (aoc_e->charge) {
3650         case PRI_AOC_DE_CHARGE_CURRENCY:
3651                 ast_aoc_set_currency_info(decoded,
3652                         aoc_e->recorded.money.amount.cost,
3653                         sig_pri_aoc_multiplier_from_pri(aoc_e->recorded.money.amount.multiplier),
3654                         aoc_e->recorded.money.currency);
3655                 break;
3656         case PRI_AOC_DE_CHARGE_UNITS:
3657                 {
3658                         int i;
3659                         for (i = 0; i < aoc_e->recorded.unit.num_items; ++i) {
3660                                 /* if type or number are negative, then they are not present */
3661                                 ast_aoc_add_unit_entry(decoded,
3662                                         (aoc_e->recorded.unit.item[i].number >= 0 ? 1 : 0),
3663                                         aoc_e->recorded.unit.item[i].number,
3664                                         (aoc_e->recorded.unit.item[i].type >= 0 ? 1 : 0),
3665                                         aoc_e->recorded.unit.item[i].type);
3666                         }
3667                 }
3668         }
3669
3670         if (passthrough && owner && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3671                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3672         }
3673
3674         ast_aoc_manager_event(decoded, owner);
3675
3676         ast_aoc_destroy_decoded(decoded);
3677         ast_aoc_destroy_encoded(encoded);
3678 }
3679 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3680
3681 #if defined(HAVE_PRI_AOC_EVENTS)
3682 /*!
3683  * \internal
3684  * \brief send an AOC-S message on the current call
3685  *
3686  * \param pvt sig_pri private channel structure.
3687  * \param generic decoded ast AOC message
3688  *
3689  * \return Nothing
3690  *
3691  * \note Assumes that the PRI lock is already obtained.
3692  */
3693 static void sig_pri_aoc_s_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3694 {
3695         struct pri_subcmd_aoc_s aoc_s = { 0, };
3696         const struct ast_aoc_s_entry *entry;
3697         int idx;
3698
3699         for (idx = 0; idx < ast_aoc_s_get_count(decoded); idx++) {
3700                 if (!(entry = ast_aoc_s_get_rate_info(decoded, idx))) {
3701                         break;
3702                 }
3703
3704                 aoc_s.item[idx].chargeable = sig_pri_aoc_charged_item_to_pri(entry->charged_item);
3705
3706                 switch (entry->rate_type) {
3707                 case AST_AOC_RATE_TYPE_DURATION:
3708                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_DURATION;
3709                         aoc_s.item[idx].rate.duration.amount.cost = entry->rate.duration.amount;
3710                         aoc_s.item[idx].rate.duration.amount.multiplier =
3711                                 sig_pri_aoc_multiplier_from_ast(entry->rate.duration.multiplier);
3712                         aoc_s.item[idx].rate.duration.time.length = entry->rate.duration.time;
3713                         aoc_s.item[idx].rate.duration.time.scale =
3714                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.time_scale);
3715                         aoc_s.item[idx].rate.duration.granularity.length = entry->rate.duration.granularity_time;
3716                         aoc_s.item[idx].rate.duration.granularity.scale =
3717                                 sig_pri_aoc_scale_to_pri(entry->rate.duration.granularity_time_scale);
3718                         aoc_s.item[idx].rate.duration.charging_type = entry->rate.duration.charging_type;
3719
3720                         if (!ast_strlen_zero(entry->rate.duration.currency_name)) {
3721                                 ast_copy_string(aoc_s.item[idx].rate.duration.currency,
3722                                         entry->rate.duration.currency_name,
3723                                         sizeof(aoc_s.item[idx].rate.duration.currency));
3724                         }
3725                         break;
3726                 case AST_AOC_RATE_TYPE_FLAT:
3727                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FLAT;
3728                         aoc_s.item[idx].rate.flat.amount.cost = entry->rate.flat.amount;
3729                         aoc_s.item[idx].rate.flat.amount.multiplier =
3730                                 sig_pri_aoc_multiplier_from_ast(entry->rate.flat.multiplier);
3731
3732                         if (!ast_strlen_zero(entry->rate.flat.currency_name)) {
3733                                 ast_copy_string(aoc_s.item[idx].rate.flat.currency,
3734                                         entry->rate.flat.currency_name,
3735                                         sizeof(aoc_s.item[idx].rate.flat.currency));
3736                         }
3737                         break;
3738                 case AST_AOC_RATE_TYPE_VOLUME:
3739                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_VOLUME;
3740                         aoc_s.item[idx].rate.volume.unit = entry->rate.volume.volume_unit;
3741                         aoc_s.item[idx].rate.volume.amount.cost = entry->rate.volume.amount;
3742                         aoc_s.item[idx].rate.volume.amount.multiplier =
3743                                 sig_pri_aoc_multiplier_from_ast(entry->rate.volume.multiplier);
3744
3745                         if (!ast_strlen_zero(entry->rate.volume.currency_name)) {
3746                                 ast_copy_string(aoc_s.item[idx].rate.volume.currency,
3747                                         entry->rate.volume.currency_name,
3748                                         sizeof(aoc_s.item[idx].rate.volume.currency));
3749                         }
3750                         break;
3751                 case AST_AOC_RATE_TYPE_SPECIAL_CODE:
3752                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_SPECIAL_CODE;
3753                         aoc_s.item[idx].rate.special = entry->rate.special_code;
3754                         break;
3755                 case AST_AOC_RATE_TYPE_FREE:
3756                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE;
3757                         break;
3758                 case AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3759                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
3760                         break;
3761                 default:
3762                 case AST_AOC_RATE_TYPE_NA:
3763                         aoc_s.item[idx].rate_type = PRI_AOC_RATE_TYPE_NOT_AVAILABLE;
3764                         break;
3765                 }
3766         }
3767         aoc_s.num_items = idx;
3768
3769         /* if this rate should be sent as a response to an AOC-S request we will
3770          * have an aoc_s_request_invoke_id associated with this pvt */
3771         if (pvt->aoc_s_request_invoke_id_valid) {
3772                 pri_aoc_s_request_response_send(pvt->pri->pri, pvt->call, pvt->aoc_s_request_invoke_id, &aoc_s);
3773                 pvt->aoc_s_request_invoke_id_valid = 0;
3774         } else {
3775                 pri_aoc_s_send(pvt->pri->pri, pvt->call, &aoc_s);
3776         }
3777 }
3778 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3779
3780 #if defined(HAVE_PRI_AOC_EVENTS)
3781 /*!
3782  * \internal
3783  * \brief send an AOC-D message on the current call
3784  *
3785  * \param pvt sig_pri private channel structure.
3786  * \param generic decoded ast AOC message
3787  *
3788  * \return Nothing
3789  *
3790  * \note Assumes that the PRI lock is already obtained.
3791  */
3792 static void sig_pri_aoc_d_from_ast(struct sig_pri_chan *pvt, struct ast_aoc_decoded *decoded)
3793 {
3794         struct pri_subcmd_aoc_d aoc_d = { 0, };
3795
3796         aoc_d.billing_accumulation = (ast_aoc_get_total_type(decoded) == AST_AOC_TOTAL) ? 1 : 0;
3797
3798         switch (ast_aoc_get_billing_id(decoded)) {
3799         case AST_AOC_BILLING_NORMAL:
3800                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NORMAL;
3801                 break;
3802         case AST_AOC_BILLING_REVERSE_CHARGE:
3803                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_REVERSE;
3804                 break;
3805         case AST_AOC_BILLING_CREDIT_CARD:
3806                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_CREDIT_CARD;
3807                 break;
3808         case AST_AOC_BILLING_NA:
3809         default:
3810                 aoc_d.billing_id = PRI_AOC_D_BILLING_ID_NOT_AVAILABLE;
3811                 break;
3812         }
3813
3814         switch (ast_aoc_get_charge_type(decoded)) {
3815         case AST_AOC_CHARGE_FREE:
3816                 aoc_d.charge = PRI_AOC_DE_CHARGE_FREE;
3817                 break;
3818         case AST_AOC_CHARGE_CURRENCY:
3819                 {
3820                         const char *currency_name = ast_aoc_get_currency_name(decoded);
3821                         aoc_d.charge = PRI_AOC_DE_CHARGE_CURRENCY;
3822                         aoc_d.recorded.money.amount.cost = ast_aoc_get_currency_amount(decoded);
3823                         aoc_d.recorded.money.amount.multiplier = sig_pri_aoc_multiplier_from_ast(ast_aoc_get_currency_multiplier(decoded));
3824                         if (!ast_strlen_zero(currency_name)) {
3825                                 ast_copy_string(aoc_d.recorded.money.currency, currency_name, sizeof(aoc_d.recorded.money.currency));
3826                         }
3827                 }
3828                 break;
3829         case AST_AOC_CHARGE_UNIT:
3830                 {
3831                         const struct ast_aoc_unit_entry *entry;
3832                         int i;
3833                         aoc_d.charge = PRI_AOC_DE_CHARGE_UNITS;
3834                         for (i = 0; i < ast_aoc_get_unit_count(decoded); i++) {
3835                                 if ((entry = ast_aoc_get_unit_info(decoded, i)) && i < ARRAY_LEN(aoc_d.recorded.unit.item)) {
3836                                         if (entry->valid_amount) {
3837                                                 aoc_d.recorded.unit.item[i].number = entry->amount;
3838                                         } else {
3839                                                 aoc_d.recorded.unit.item[i].number = -1;
3840                                         }
3841                                         if (entry->valid_type) {
3842                                                 aoc_d.recorded.unit.item[i].type = entry->type;
3843                                         } else {
3844                                                 aoc_d.recorded.unit.item[i].type = -1;
3845                                         }
3846                                         aoc_d.recorded.unit.num_items++;
3847                                 } else {
3848                                         break;
3849                                 }
3850                         }
3851                 }
3852                 break;
3853         case AST_AOC_CHARGE_NA:
3854         default:
3855                 aoc_d.charge = PRI_AOC_DE_CHARGE_NOT_AVAILABLE;
3856                 break;
3857         }
3858
3859         pri_aoc_d_send(pvt->pri->pri, pvt->call, &aoc_d);
3860 }
3861 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3862
3863 #if defined(HAVE_PRI_AOC_EVENTS)
3864 /*!
3865  * \internal
3866  * \brief send an AOC-E message on the current call
3867  *
3868  * \param pvt sig_pri private channel structure.
3869  * \param generic decoded ast AOC message