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