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