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