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