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