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