Add ability to ignore layer 1 alarms for BRI PTMP lines.
[asterisk/asterisk.git] / channels / sig_pri.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2009, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief PRI signaling module
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  */
25
26
27 #include "asterisk.h"
28
29 #ifdef HAVE_PRI
30
31 #include <errno.h>
32 #include <ctype.h>
33 #include <signal.h>
34
35 #include "asterisk/utils.h"
36 #include "asterisk/options.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/app.h"
39 #include "asterisk/file.h"
40 #include "asterisk/callerid.h"
41 #include "asterisk/say.h"
42 #include "asterisk/manager.h"
43 #include "asterisk/astdb.h"
44 #include "asterisk/causes.h"
45 #include "asterisk/musiconhold.h"
46 #include "asterisk/cli.h"
47 #include "asterisk/transcap.h"
48 #include "asterisk/features.h"
49 #include "asterisk/aoc.h"
50
51 #include "sig_pri.h"
52 #ifndef PRI_EVENT_FACILITY
53 #error please update libpri
54 #endif
55
56 /* define this to send PRI user-user information elements */
57 #undef SUPPORT_USERUSER
58
59 /*!
60  * Define to make always pick a channel if allowed.  Useful for
61  * testing channel shifting.
62  */
63 //#define ALWAYS_PICK_CHANNEL   1
64
65 /*!
66  * Define to force a RESTART on a channel that returns a cause
67  * code of PRI_CAUSE_REQUESTED_CHAN_UNAVAIL(44).  If the cause
68  * is because of a stuck channel on the peer and the channel is
69  * always the next channel we pick for an outgoing call then
70  * this can help.
71  */
72 #define FORCE_RESTART_UNAVAIL_CHANS             1
73
74 #if defined(HAVE_PRI_CCSS)
75 struct sig_pri_cc_agent_prv {
76         /*! Asterisk span D channel control structure. */
77         struct sig_pri_span *pri;
78         /*! CC id value to use with libpri. -1 if invalid. */
79         long cc_id;
80         /*! TRUE if CC has been requested and we are waiting for the response. */
81         unsigned char cc_request_response_pending;
82 };
83
84 struct sig_pri_cc_monitor_instance {
85         /*! \brief Asterisk span D channel control structure. */
86         struct sig_pri_span *pri;
87         /*! CC id value to use with libpri. (-1 if already canceled). */
88         long cc_id;
89         /*! CC core id value. */
90         int core_id;
91         /*! Device name(Channel name less sequence number) */
92         char name[1];
93 };
94
95 /*! Upper level agent/monitor type name. */
96 static const char *sig_pri_cc_type_name;
97 /*! Container of sig_pri monitor instances. */
98 static struct ao2_container *sig_pri_cc_monitors;
99 #endif  /* defined(HAVE_PRI_CCSS) */
100
101 static int pri_matchdigittimeout = 3000;
102
103 static int pri_gendigittimeout = 8000;
104
105 #define DCHAN_NOTINALARM  (1 << 0)
106 #define DCHAN_UP          (1 << 1)
107
108 /* Defines to help decode the encoded event channel id. */
109 #define PRI_CHANNEL(p)  ((p) & 0xff)
110 #define PRI_SPAN(p)             (((p) >> 8) & 0xff)
111 #define PRI_EXPLICIT    (1 << 16)
112 #define PRI_CIS_CALL    (1 << 17)       /* Call is using the D channel only. */
113 #define PRI_HELD_CALL   (1 << 18)
114
115
116 #define DCHAN_AVAILABLE (DCHAN_NOTINALARM | DCHAN_UP)
117
118 #define PRI_DEADLOCK_AVOIDANCE(p) \
119         do { \
120                 sig_pri_unlock_private(p); \
121                 usleep(1); \
122                 sig_pri_lock_private(p); \
123         } while (0)
124
125 static int pri_active_dchan_index(struct sig_pri_span *pri);
126
127 static const char *sig_pri_call_level2str(enum sig_pri_call_level level)
128 {
129         switch (level) {
130         case SIG_PRI_CALL_LEVEL_IDLE:
131                 return "Idle";
132         case SIG_PRI_CALL_LEVEL_SETUP:
133                 return "Setup";
134         case SIG_PRI_CALL_LEVEL_OVERLAP:
135                 return "Overlap";
136         case SIG_PRI_CALL_LEVEL_PROCEEDING:
137                 return "Proceeding";
138         case SIG_PRI_CALL_LEVEL_ALERTING:
139                 return "Alerting";
140         case SIG_PRI_CALL_LEVEL_DEFER_DIAL:
141                 return "DeferDial";
142         case SIG_PRI_CALL_LEVEL_CONNECT:
143                 return "Connect";
144         }
145         return "Unknown";
146 }
147
148 static inline void pri_rel(struct sig_pri_span *pri)
149 {
150         ast_mutex_unlock(&pri->lock);
151 }
152
153 static unsigned int PVT_TO_CHANNEL(struct sig_pri_chan *p)
154 {
155         int res = (((p)->prioffset) | ((p)->logicalspan << 8) | (p->mastertrunkgroup ? PRI_EXPLICIT : 0));
156         ast_debug(5, "prioffset: %d mastertrunkgroup: %d logicalspan: %d result: %d\n",
157                 p->prioffset, p->mastertrunkgroup, p->logicalspan, res);
158
159         return res;
160 }
161
162 static void sig_pri_handle_dchan_exception(struct sig_pri_span *pri, int index)
163 {
164         if (pri->calls->handle_dchan_exception)
165                 pri->calls->handle_dchan_exception(pri, index);
166 }
167
168 static void sig_pri_set_dialing(struct sig_pri_chan *p, int is_dialing)
169 {
170         if (p->calls->set_dialing) {
171                 p->calls->set_dialing(p->chan_pvt, is_dialing);
172         }
173 }
174
175 static void sig_pri_set_digital(struct sig_pri_chan *p, int is_digital)
176 {
177         p->digital = is_digital;
178         if (p->calls->set_digital) {
179                 p->calls->set_digital(p->chan_pvt, is_digital);
180         }
181 }
182
183 static void sig_pri_set_outgoing(struct sig_pri_chan *p, int is_outgoing)
184 {
185         p->outgoing = is_outgoing;
186         if (p->calls->set_outgoing) {
187                 p->calls->set_outgoing(p->chan_pvt, is_outgoing);
188         }
189 }
190
191 void sig_pri_set_alarm(struct sig_pri_chan *p, int in_alarm)
192 {
193         if (sig_pri_is_alarm_ignored(p->pri)) {
194                 /* Always set not in alarm */
195                 in_alarm = 0;
196         }
197
198         /*
199          * Clear the channel restart flag when the channel alarm changes
200          * to prevent the flag from getting stuck when the link goes
201          * down.
202          */
203         p->resetting = 0;
204
205         p->inalarm = in_alarm;
206         if (p->calls->set_alarm) {
207                 p->calls->set_alarm(p->chan_pvt, in_alarm);
208         }
209 }
210
211 static const char *sig_pri_get_orig_dialstring(struct sig_pri_chan *p)
212 {
213         if (p->calls->get_orig_dialstring) {
214                 return p->calls->get_orig_dialstring(p->chan_pvt);
215         }
216         ast_log(LOG_ERROR, "get_orig_dialstring callback not defined\n");
217         return "";
218 }
219
220 #if defined(HAVE_PRI_CCSS)
221 static void sig_pri_make_cc_dialstring(struct sig_pri_chan *p, char *buf, size_t buf_size)
222 {
223         if (p->calls->make_cc_dialstring) {
224                 p->calls->make_cc_dialstring(p->chan_pvt, buf, buf_size);
225         } else {
226                 ast_log(LOG_ERROR, "make_cc_dialstring callback not defined\n");
227                 buf[0] = '\0';
228         }
229 }
230 #endif  /* defined(HAVE_PRI_CCSS) */
231
232 static void sig_pri_dial_digits(struct sig_pri_chan *p, const char *dial_string)
233 {
234         if (p->calls->dial_digits) {
235                 p->calls->dial_digits(p->chan_pvt, dial_string);
236         }
237 }
238
239 /*!
240  * \internal
241  * \brief Reevaluate the PRI span device state.
242  * \since 1.8
243  *
244  * \param pri PRI span control structure.
245  *
246  * \return Nothing
247  *
248  * \note Assumes the pri->lock is already obtained.
249  */
250 static void sig_pri_span_devstate_changed(struct sig_pri_span *pri)
251 {
252         if (pri->calls->update_span_devstate) {
253                 pri->calls->update_span_devstate(pri);
254         }
255 }
256
257 /*!
258  * \internal
259  * \brief Set the caller id information in the parent module.
260  * \since 1.8
261  *
262  * \param p sig_pri channel structure.
263  *
264  * \return Nothing
265  */
266 static void sig_pri_set_caller_id(struct sig_pri_chan *p)
267 {
268         struct ast_party_caller caller;
269
270         if (p->calls->set_callerid) {
271                 ast_party_caller_init(&caller);
272
273                 caller.id.name.str = p->cid_name;
274                 caller.id.name.presentation = p->callingpres;
275                 caller.id.name.valid = 1;
276
277                 caller.id.number.str = p->cid_num;
278                 caller.id.number.plan = p->cid_ton;
279                 caller.id.number.presentation = p->callingpres;
280                 caller.id.number.valid = 1;
281
282                 if (!ast_strlen_zero(p->cid_subaddr)) {
283                         caller.id.subaddress.valid = 1;
284                         //caller.id.subaddress.type = 0;/* nsap */
285                         //caller.id.subaddress.odd_even_indicator = 0;
286                         caller.id.subaddress.str = p->cid_subaddr;
287                 }
288                 caller.id.tag = p->user_tag;
289
290                 caller.ani.number.str = p->cid_ani;
291                 //caller.ani.number.plan = p->xxx;
292                 //caller.ani.number.presentation = p->xxx;
293                 caller.ani.number.valid = 1;
294
295                 caller.ani2 = p->cid_ani2;
296                 p->calls->set_callerid(p->chan_pvt, &caller);
297         }
298 }
299
300 /*!
301  * \internal
302  * \brief Set the Dialed Number Identifier.
303  * \since 1.8
304  *
305  * \param p sig_pri channel structure.
306  * \param dnid Dialed Number Identifier string.
307  *
308  * \return Nothing
309  */
310 static void sig_pri_set_dnid(struct sig_pri_chan *p, const char *dnid)
311 {
312         if (p->calls->set_dnid) {
313                 p->calls->set_dnid(p->chan_pvt, dnid);
314         }
315 }
316
317 /*!
318  * \internal
319  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
320  * \since 1.8
321  *
322  * \param p sig_pri channel structure.
323  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
324  *
325  * \return Nothing
326  */
327 static void sig_pri_set_rdnis(struct sig_pri_chan *p, const char *rdnis)
328 {
329         if (p->calls->set_rdnis) {
330                 p->calls->set_rdnis(p->chan_pvt, rdnis);
331         }
332 }
333
334 static void sig_pri_unlock_private(struct sig_pri_chan *p)
335 {
336         if (p->calls->unlock_private)
337                 p->calls->unlock_private(p->chan_pvt);
338 }
339
340 static void sig_pri_lock_private(struct sig_pri_chan *p)
341 {
342         if (p->calls->lock_private)
343                 p->calls->lock_private(p->chan_pvt);
344 }
345
346 static void sig_pri_deadlock_avoidance_private(struct sig_pri_chan *p)
347 {
348         if (p->calls->deadlock_avoidance_private) {
349                 p->calls->deadlock_avoidance_private(p->chan_pvt);
350         } else {
351                 /* Fallback to the old way if callback not present. */
352                 PRI_DEADLOCK_AVOIDANCE(p);
353         }
354 }
355
356 static void pri_grab(struct sig_pri_chan *p, struct sig_pri_span *pri)
357 {
358         int res;
359
360         /* Grab the lock first */
361         do {
362                 res = ast_mutex_trylock(&pri->lock);
363                 if (res) {
364                         sig_pri_deadlock_avoidance_private(p);
365                 }
366         } while (res);
367         /* Then break the poll */
368         pthread_kill(pri->master, SIGURG);
369 }
370
371 /*!
372  * \internal
373  * \brief Convert PRI redirecting reason to asterisk version.
374  * \since 1.8
375  *
376  * \param pri_reason PRI redirecting reason.
377  *
378  * \return Equivalent asterisk redirecting reason value.
379  */
380 static enum AST_REDIRECTING_REASON pri_to_ast_reason(int pri_reason)
381 {
382         enum AST_REDIRECTING_REASON ast_reason;
383
384         switch (pri_reason) {
385         case PRI_REDIR_FORWARD_ON_BUSY:
386                 ast_reason = AST_REDIRECTING_REASON_USER_BUSY;
387                 break;
388         case PRI_REDIR_FORWARD_ON_NO_REPLY:
389                 ast_reason = AST_REDIRECTING_REASON_NO_ANSWER;
390                 break;
391         case PRI_REDIR_DEFLECTION:
392                 ast_reason = AST_REDIRECTING_REASON_DEFLECTION;
393                 break;
394         case PRI_REDIR_UNCONDITIONAL:
395                 ast_reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
396                 break;
397         case PRI_REDIR_UNKNOWN:
398         default:
399                 ast_reason = AST_REDIRECTING_REASON_UNKNOWN;
400                 break;
401         }
402
403         return ast_reason;
404 }
405
406 /*!
407  * \internal
408  * \brief Convert asterisk redirecting reason to PRI version.
409  * \since 1.8
410  *
411  * \param ast_reason Asterisk redirecting reason.
412  *
413  * \return Equivalent PRI redirecting reason value.
414  */
415 static int ast_to_pri_reason(enum AST_REDIRECTING_REASON ast_reason)
416 {
417         int pri_reason;
418
419         switch (ast_reason) {
420         case AST_REDIRECTING_REASON_USER_BUSY:
421                 pri_reason = PRI_REDIR_FORWARD_ON_BUSY;
422                 break;
423         case AST_REDIRECTING_REASON_NO_ANSWER:
424                 pri_reason = PRI_REDIR_FORWARD_ON_NO_REPLY;
425                 break;
426         case AST_REDIRECTING_REASON_UNCONDITIONAL:
427                 pri_reason = PRI_REDIR_UNCONDITIONAL;
428                 break;
429         case AST_REDIRECTING_REASON_DEFLECTION:
430                 pri_reason = PRI_REDIR_DEFLECTION;
431                 break;
432         case AST_REDIRECTING_REASON_UNKNOWN:
433         default:
434                 pri_reason = PRI_REDIR_UNKNOWN;
435                 break;
436         }
437
438         return pri_reason;
439 }
440
441 /*!
442  * \internal
443  * \brief Convert PRI number presentation to asterisk version.
444  * \since 1.8
445  *
446  * \param pri_presentation PRI number presentation.
447  *
448  * \return Equivalent asterisk number presentation value.
449  */
450 static int pri_to_ast_presentation(int pri_presentation)
451 {
452         int ast_presentation;
453
454         switch (pri_presentation) {
455         case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED:
456                 ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED;
457                 break;
458         case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
459                 ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
460                 break;
461         case PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
462                 ast_presentation = AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
463                 break;
464         case PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER:
465                 ast_presentation = AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER;
466                 break;
467
468         case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED:
469                 ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
470                 break;
471         case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
472                 ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN;
473                 break;
474         case PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
475                 ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN;
476                 break;
477         case PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER:
478                 ast_presentation = AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER;
479                 break;
480
481         case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_UNSCREENED:
482         case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_PASSED_SCREEN:
483         case PRI_PRES_UNAVAILABLE | PRI_PRES_USER_NUMBER_FAILED_SCREEN:
484         case PRI_PRES_UNAVAILABLE | PRI_PRES_NETWORK_NUMBER:
485                 ast_presentation = AST_PRES_NUMBER_NOT_AVAILABLE;
486                 break;
487
488         default:
489                 ast_presentation = AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED;
490                 break;
491         }
492
493         return ast_presentation;
494 }
495
496 /*!
497  * \internal
498  * \brief Convert asterisk number presentation to PRI version.
499  * \since 1.8
500  *
501  * \param ast_presentation Asterisk number presentation.
502  *
503  * \return Equivalent PRI number presentation value.
504  */
505 static int ast_to_pri_presentation(int ast_presentation)
506 {
507         int pri_presentation;
508
509         switch (ast_presentation) {
510         case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_UNSCREENED:
511                 pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_UNSCREENED;
512                 break;
513         case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
514                 pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
515                 break;
516         case AST_PRES_ALLOWED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
517                 pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
518                 break;
519         case AST_PRES_ALLOWED | AST_PRES_NETWORK_NUMBER:
520                 pri_presentation = PRI_PRES_ALLOWED | PRI_PRES_NETWORK_NUMBER;
521                 break;
522
523         case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_UNSCREENED:
524                 pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
525                 break;
526         case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_PASSED_SCREEN:
527                 pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_PASSED_SCREEN;
528                 break;
529         case AST_PRES_RESTRICTED | AST_PRES_USER_NUMBER_FAILED_SCREEN:
530                 pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_FAILED_SCREEN;
531                 break;
532         case AST_PRES_RESTRICTED | AST_PRES_NETWORK_NUMBER:
533                 pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_NETWORK_NUMBER;
534                 break;
535
536         case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_UNSCREENED:
537         case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_PASSED_SCREEN:
538         case AST_PRES_UNAVAILABLE | AST_PRES_USER_NUMBER_FAILED_SCREEN:
539         case AST_PRES_UNAVAILABLE | AST_PRES_NETWORK_NUMBER:
540                 pri_presentation = PRES_NUMBER_NOT_AVAILABLE;
541                 break;
542
543         default:
544                 pri_presentation = PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
545                 break;
546         }
547
548         return pri_presentation;
549 }
550
551 /*!
552  * \internal
553  * \brief Convert PRI name char_set to asterisk version.
554  * \since 1.8
555  *
556  * \param pri_char_set PRI name char_set.
557  *
558  * \return Equivalent asterisk name char_set value.
559  */
560 static enum AST_PARTY_CHAR_SET pri_to_ast_char_set(int pri_char_set)
561 {
562         enum AST_PARTY_CHAR_SET ast_char_set;
563
564         switch (pri_char_set) {
565         default:
566         case PRI_CHAR_SET_UNKNOWN:
567                 ast_char_set = AST_PARTY_CHAR_SET_UNKNOWN;
568                 break;
569         case PRI_CHAR_SET_ISO8859_1:
570                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_1;
571                 break;
572         case PRI_CHAR_SET_WITHDRAWN:
573                 ast_char_set = AST_PARTY_CHAR_SET_WITHDRAWN;
574                 break;
575         case PRI_CHAR_SET_ISO8859_2:
576                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_2;
577                 break;
578         case PRI_CHAR_SET_ISO8859_3:
579                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_3;
580                 break;
581         case PRI_CHAR_SET_ISO8859_4:
582                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_4;
583                 break;
584         case PRI_CHAR_SET_ISO8859_5:
585                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_5;
586                 break;
587         case PRI_CHAR_SET_ISO8859_7:
588                 ast_char_set = AST_PARTY_CHAR_SET_ISO8859_7;
589                 break;
590         case PRI_CHAR_SET_ISO10646_BMPSTRING:
591                 ast_char_set = AST_PARTY_CHAR_SET_ISO10646_BMPSTRING;
592                 break;
593         case PRI_CHAR_SET_ISO10646_UTF_8STRING:
594                 ast_char_set = AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING;
595                 break;
596         }
597
598         return ast_char_set;
599 }
600
601 /*!
602  * \internal
603  * \brief Convert asterisk name char_set to PRI version.
604  * \since 1.8
605  *
606  * \param ast_char_set Asterisk name char_set.
607  *
608  * \return Equivalent PRI name char_set value.
609  */
610 static int ast_to_pri_char_set(enum AST_PARTY_CHAR_SET ast_char_set)
611 {
612         int pri_char_set;
613
614         switch (ast_char_set) {
615         default:
616         case AST_PARTY_CHAR_SET_UNKNOWN:
617                 pri_char_set = PRI_CHAR_SET_UNKNOWN;
618                 break;
619         case AST_PARTY_CHAR_SET_ISO8859_1:
620                 pri_char_set = PRI_CHAR_SET_ISO8859_1;
621                 break;
622         case AST_PARTY_CHAR_SET_WITHDRAWN:
623                 pri_char_set = PRI_CHAR_SET_WITHDRAWN;
624                 break;
625         case AST_PARTY_CHAR_SET_ISO8859_2:
626                 pri_char_set = PRI_CHAR_SET_ISO8859_2;
627                 break;
628         case AST_PARTY_CHAR_SET_ISO8859_3:
629                 pri_char_set = PRI_CHAR_SET_ISO8859_3;
630                 break;
631         case AST_PARTY_CHAR_SET_ISO8859_4:
632                 pri_char_set = PRI_CHAR_SET_ISO8859_4;
633                 break;
634         case AST_PARTY_CHAR_SET_ISO8859_5:
635                 pri_char_set = PRI_CHAR_SET_ISO8859_5;
636                 break;
637         case AST_PARTY_CHAR_SET_ISO8859_7:
638                 pri_char_set = PRI_CHAR_SET_ISO8859_7;
639                 break;
640         case AST_PARTY_CHAR_SET_ISO10646_BMPSTRING:
641                 pri_char_set = PRI_CHAR_SET_ISO10646_BMPSTRING;
642                 break;
643         case AST_PARTY_CHAR_SET_ISO10646_UTF_8STRING:
644                 pri_char_set = PRI_CHAR_SET_ISO10646_UTF_8STRING;
645                 break;
646         }
647
648         return pri_char_set;
649 }
650
651 #if defined(HAVE_PRI_SUBADDR)
652 /*!
653  * \internal
654  * \brief Fill in the asterisk party subaddress from the given PRI party subaddress.
655  * \since 1.8
656  *
657  * \param ast_subaddress Asterisk party subaddress structure.
658  * \param pri_subaddress PRI party subaddress structure.
659  *
660  * \return Nothing
661  *
662  */
663 static void sig_pri_set_subaddress(struct ast_party_subaddress *ast_subaddress, const struct pri_party_subaddress *pri_subaddress)
664 {
665         char *cnum, *ptr;
666         int x, len;
667
668         if (ast_subaddress->str) {
669                 ast_free(ast_subaddress->str);
670         }
671         if (pri_subaddress->length <= 0) {
672                 ast_party_subaddress_init(ast_subaddress);
673                 return;
674         }
675
676         if (!pri_subaddress->type) {
677                 /* NSAP */
678                 ast_subaddress->str = ast_strdup((char *) pri_subaddress->data);
679         } else {
680                 /* User Specified */
681                 if (!(cnum = ast_malloc(2 * pri_subaddress->length + 1))) {
682                         ast_party_subaddress_init(ast_subaddress);
683                         return;
684                 }
685
686                 ptr = cnum;
687                 len = pri_subaddress->length - 1; /* -1 account for zero based indexing */
688                 for (x = 0; x < len; ++x) {
689                         ptr += sprintf(ptr, "%02x", pri_subaddress->data[x]);
690                 }
691
692                 if (pri_subaddress->odd_even_indicator) {
693                         /* ODD */
694                         sprintf(ptr, "%01x", (pri_subaddress->data[len]) >> 4);
695                 } else {
696                         /* EVEN */
697                         sprintf(ptr, "%02x", pri_subaddress->data[len]);
698                 }
699                 ast_subaddress->str = cnum;
700         }
701         ast_subaddress->type = pri_subaddress->type;
702         ast_subaddress->odd_even_indicator = pri_subaddress->odd_even_indicator;
703         ast_subaddress->valid = 1;
704 }
705 #endif  /* defined(HAVE_PRI_SUBADDR) */
706
707 #if defined(HAVE_PRI_SUBADDR)
708 static unsigned char ast_pri_pack_hex_char(char c)
709 {
710         unsigned char res;
711
712         if (c < '0') {
713                 res = 0;
714         } else if (c < ('9' + 1)) {
715                 res = c - '0';
716         } else if (c < 'A') {
717                 res = 0;
718         } else if (c < ('F' + 1)) {
719                 res = c - 'A' + 10;
720         } else if (c < 'a') {
721                 res = 0;
722         } else if (c < ('f' + 1)) {
723                 res = c - 'a' + 10;
724         } else {
725                 res = 0;
726         }
727         return res;
728 }
729 #endif  /* defined(HAVE_PRI_SUBADDR) */
730
731 #if defined(HAVE_PRI_SUBADDR)
732 /*!
733  * \internal
734  * \brief Convert a null terminated hexadecimal string to a packed hex byte array.
735  * \details left justified, with 0 padding if odd length.
736  * \since 1.8
737  *
738  * \param dst pointer to packed byte array.
739  * \param src pointer to null terminated hexadecimal string.
740  * \param maxlen destination array size.
741  *
742  * \return Length of byte array
743  *
744  * \note The dst is not an ASCIIz string.
745  * \note The src is an ASCIIz hex string.
746  */
747 static int ast_pri_pack_hex_string(unsigned char *dst, char *src, int maxlen)
748 {
749         int res = 0;
750         int len = strlen(src);
751
752         if (len > (2 * maxlen)) {
753                 len = 2 * maxlen;
754         }
755
756         res = len / 2 + len % 2;
757
758         while (len > 1) {
759                 *dst = ast_pri_pack_hex_char(*src) << 4;
760                 src++;
761                 *dst |= ast_pri_pack_hex_char(*src);
762                 dst++, src++;
763                 len -= 2;
764         }
765         if (len) { /* 1 left */
766                 *dst = ast_pri_pack_hex_char(*src) << 4;
767         }
768         return res;
769 }
770 #endif  /* defined(HAVE_PRI_SUBADDR) */
771
772 #if defined(HAVE_PRI_SUBADDR)
773 /*!
774  * \internal
775  * \brief Fill in the PRI party subaddress from the given asterisk party subaddress.
776  * \since 1.8
777  *
778  * \param pri_subaddress PRI party subaddress structure.
779  * \param ast_subaddress Asterisk party subaddress structure.
780  *
781  * \return Nothing
782  *
783  * \note Assumes that pri_subaddress has been previously memset to zero.
784  */
785 static void sig_pri_party_subaddress_from_ast(struct pri_party_subaddress *pri_subaddress, const struct ast_party_subaddress *ast_subaddress)
786 {
787         if (ast_subaddress->valid && !ast_strlen_zero(ast_subaddress->str)) {
788                 pri_subaddress->type = ast_subaddress->type;
789                 if (!ast_subaddress->type) {
790                         /* 0 = NSAP */
791                         ast_copy_string((char *) pri_subaddress->data, ast_subaddress->str,
792                                 sizeof(pri_subaddress->data));
793                         pri_subaddress->length = strlen((char *) pri_subaddress->data);
794                         pri_subaddress->odd_even_indicator = 0;
795                         pri_subaddress->valid = 1;
796                 } else {
797                         /* 2 = User Specified */
798                         /*
799                          * Copy HexString to packed HexData,
800                          * if odd length then right pad trailing byte with 0
801                          */
802                         int length = ast_pri_pack_hex_string(pri_subaddress->data,
803                                 ast_subaddress->str, sizeof(pri_subaddress->data));
804
805                         pri_subaddress->length = length; /* packed data length */
806
807                         length = strlen(ast_subaddress->str);
808                         if (length > 2 * sizeof(pri_subaddress->data)) {
809                                 pri_subaddress->odd_even_indicator = 0;
810                         } else {
811                                 pri_subaddress->odd_even_indicator = (length & 1);
812                         }
813                         pri_subaddress->valid = 1;
814                 }
815         }
816 }
817 #endif  /* defined(HAVE_PRI_SUBADDR) */
818
819 /*!
820  * \internal
821  * \brief Fill in the PRI party name from the given asterisk party name.
822  * \since 1.8
823  *
824  * \param pri_name PRI party name structure.
825  * \param ast_name Asterisk party name structure.
826  *
827  * \return Nothing
828  *
829  * \note Assumes that pri_name has been previously memset to zero.
830  */
831 static void sig_pri_party_name_from_ast(struct pri_party_name *pri_name, const struct ast_party_name *ast_name)
832 {
833         if (!ast_name->valid) {
834                 return;
835         }
836         pri_name->valid = 1;
837         pri_name->presentation = ast_to_pri_presentation(ast_name->presentation);
838         pri_name->char_set = ast_to_pri_char_set(ast_name->char_set);
839         if (!ast_strlen_zero(ast_name->str)) {
840                 ast_copy_string(pri_name->str, ast_name->str, sizeof(pri_name->str));
841         }
842 }
843
844 /*!
845  * \internal
846  * \brief Fill in the PRI party number from the given asterisk party number.
847  * \since 1.8
848  *
849  * \param pri_number PRI party number structure.
850  * \param ast_number Asterisk party number structure.
851  *
852  * \return Nothing
853  *
854  * \note Assumes that pri_number has been previously memset to zero.
855  */
856 static void sig_pri_party_number_from_ast(struct pri_party_number *pri_number, const struct ast_party_number *ast_number)
857 {
858         if (!ast_number->valid) {
859                 return;
860         }
861         pri_number->valid = 1;
862         pri_number->presentation = ast_to_pri_presentation(ast_number->presentation);
863         pri_number->plan = ast_number->plan;
864         if (!ast_strlen_zero(ast_number->str)) {
865                 ast_copy_string(pri_number->str, ast_number->str, sizeof(pri_number->str));
866         }
867 }
868
869 /*!
870  * \internal
871  * \brief Fill in the PRI party id from the given asterisk party id.
872  * \since 1.8
873  *
874  * \param pri_id PRI party id structure.
875  * \param ast_id Asterisk party id structure.
876  *
877  * \return Nothing
878  *
879  * \note Assumes that pri_id has been previously memset to zero.
880  */
881 static void sig_pri_party_id_from_ast(struct pri_party_id *pri_id, const struct ast_party_id *ast_id)
882 {
883         sig_pri_party_name_from_ast(&pri_id->name, &ast_id->name);
884         sig_pri_party_number_from_ast(&pri_id->number, &ast_id->number);
885 #if defined(HAVE_PRI_SUBADDR)
886         sig_pri_party_subaddress_from_ast(&pri_id->subaddress, &ast_id->subaddress);
887 #endif  /* defined(HAVE_PRI_SUBADDR) */
888 }
889
890 /*!
891  * \internal
892  * \brief Update the PRI redirecting information for the current call.
893  * \since 1.8
894  *
895  * \param pvt sig_pri private channel structure.
896  * \param ast Asterisk channel
897  *
898  * \return Nothing
899  *
900  * \note Assumes that the PRI lock is already obtained.
901  */
902 static void sig_pri_redirecting_update(struct sig_pri_chan *pvt, struct ast_channel *ast)
903 {
904         struct pri_party_redirecting pri_redirecting;
905
906 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
907
908         memset(&pri_redirecting, 0, sizeof(pri_redirecting));
909         sig_pri_party_id_from_ast(&pri_redirecting.from, &ast_channel_redirecting(ast)->from);
910         sig_pri_party_id_from_ast(&pri_redirecting.to, &ast_channel_redirecting(ast)->to);
911         pri_redirecting.count = ast_channel_redirecting(ast)->count;
912         pri_redirecting.reason = ast_to_pri_reason(ast_channel_redirecting(ast)->reason);
913
914         pri_redirecting_update(pvt->pri->pri, pvt->call, &pri_redirecting);
915 }
916
917 /*!
918  * \internal
919  * \brief Reset DTMF detector.
920  * \since 1.8
921  *
922  * \param p sig_pri channel structure.
923  *
924  * \return Nothing
925  */
926 static void sig_pri_dsp_reset_and_flush_digits(struct sig_pri_chan *p)
927 {
928         if (p->calls->dsp_reset_and_flush_digits) {
929                 p->calls->dsp_reset_and_flush_digits(p->chan_pvt);
930         }
931 }
932
933 static int sig_pri_set_echocanceller(struct sig_pri_chan *p, int enable)
934 {
935         if (p->calls->set_echocanceller)
936                 return p->calls->set_echocanceller(p->chan_pvt, enable);
937         else
938                 return -1;
939 }
940
941 static void sig_pri_fixup_chans(struct sig_pri_chan *old_chan, struct sig_pri_chan *new_chan)
942 {
943         if (old_chan->calls->fixup_chans)
944                 old_chan->calls->fixup_chans(old_chan->chan_pvt, new_chan->chan_pvt);
945 }
946
947 static int sig_pri_play_tone(struct sig_pri_chan *p, enum sig_pri_tone tone)
948 {
949         if (p->calls->play_tone)
950                 return p->calls->play_tone(p->chan_pvt, tone);
951         else
952                 return -1;
953 }
954
955 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)
956 {
957         struct ast_channel *c;
958
959         if (p->calls->new_ast_channel) {
960                 c = p->calls->new_ast_channel(p->chan_pvt, state, ulaw, exten, requestor);
961         } else {
962                 return NULL;
963         }
964         if (!c) {
965                 return NULL;
966         }
967
968         if (!p->owner)
969                 p->owner = c;
970         p->isidlecall = 0;
971         p->alreadyhungup = 0;
972         ast_channel_transfercapability_set(c, transfercapability);
973         pbx_builtin_setvar_helper(c, "TRANSFERCAPABILITY",
974                 ast_transfercapability2str(transfercapability));
975         if (transfercapability & AST_TRANS_CAP_DIGITAL) {
976                 sig_pri_set_digital(p, 1);
977         }
978         if (p->pri) {
979                 ast_mutex_lock(&p->pri->lock);
980                 sig_pri_span_devstate_changed(p->pri);
981                 ast_mutex_unlock(&p->pri->lock);
982         }
983
984         return c;
985 }
986
987 /*!
988  * \internal
989  * \brief Open the PRI channel media path.
990  * \since 1.8
991  *
992  * \param p Channel private control structure.
993  *
994  * \return Nothing
995  */
996 static void sig_pri_open_media(struct sig_pri_chan *p)
997 {
998         if (p->no_b_channel) {
999                 return;
1000         }
1001
1002         if (p->calls->open_media) {
1003                 p->calls->open_media(p->chan_pvt);
1004         }
1005 }
1006
1007 /*!
1008  * \internal
1009  * \brief Post an AMI B channel association event.
1010  * \since 1.8
1011  *
1012  * \param p Channel private control structure.
1013  *
1014  * \note Assumes the private and owner are locked.
1015  *
1016  * \return Nothing
1017  */
1018 static void sig_pri_ami_channel_event(struct sig_pri_chan *p)
1019 {
1020         if (p->calls->ami_channel_event) {
1021                 p->calls->ami_channel_event(p->chan_pvt, p->owner);
1022         }
1023 }
1024
1025 struct ast_channel *sig_pri_request(struct sig_pri_chan *p, enum sig_pri_law law, const struct ast_channel *requestor, int transfercapability)
1026 {
1027         struct ast_channel *ast;
1028
1029         ast_debug(1, "%s %d\n", __FUNCTION__, p->channel);
1030
1031         sig_pri_set_outgoing(p, 1);
1032         ast = sig_pri_new_ast_channel(p, AST_STATE_RESERVED, law, transfercapability, p->exten, requestor);
1033         if (!ast) {
1034                 sig_pri_set_outgoing(p, 0);
1035         }
1036         return ast;
1037 }
1038
1039 int pri_is_up(struct sig_pri_span *pri)
1040 {
1041         int x;
1042         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
1043                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
1044                         return 1;
1045         }
1046         return 0;
1047 }
1048
1049 static const char *pri_order(int level)
1050 {
1051         switch (level) {
1052         case 0:
1053                 return "Primary";
1054         case 1:
1055                 return "Secondary";
1056         case 2:
1057                 return "Tertiary";
1058         case 3:
1059                 return "Quaternary";
1060         default:
1061                 return "<Unknown>";
1062         }
1063 }
1064
1065 /* Returns index of the active dchan */
1066 static int pri_active_dchan_index(struct sig_pri_span *pri)
1067 {
1068         int x;
1069
1070         for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
1071                 if ((pri->dchans[x] == pri->pri))
1072                         return x;
1073         }
1074
1075         ast_log(LOG_WARNING, "No active dchan found!\n");
1076         return -1;
1077 }
1078
1079 static void pri_find_dchan(struct sig_pri_span *pri)
1080 {
1081         struct pri *old;
1082         int oldslot = -1;
1083         int newslot = -1;
1084         int idx;
1085
1086         old = pri->pri;
1087         for (idx = 0; idx < SIG_PRI_NUM_DCHANS; ++idx) {
1088                 if (!pri->dchans[idx]) {
1089                         /* No more D channels defined on the span. */
1090                         break;
1091                 }
1092                 if (pri->dchans[idx] == old) {
1093                         oldslot = idx;
1094                 }
1095                 if (newslot < 0 && pri->dchanavail[idx] == DCHAN_AVAILABLE) {
1096                         newslot = idx;
1097                 }
1098         }
1099         /* At this point, idx is a count of how many D-channels are defined on the span. */
1100
1101         if (1 < idx) {
1102                 /* We have several D-channels defined on the span.  (NFAS PRI setup) */
1103                 if (newslot < 0) {
1104                         /* No D-channels available.  Default to the primary D-channel. */
1105                         newslot = 0;
1106
1107                         if (!pri->no_d_channels) {
1108                                 pri->no_d_channels = 1;
1109                                 if (old && oldslot != newslot) {
1110                                         ast_log(LOG_WARNING,
1111                                                 "Span %d: No D-channels up!  Switching selected D-channel from %s to %s.\n",
1112                                                 pri->span, pri_order(oldslot), pri_order(newslot));
1113                                 } else {
1114                                         ast_log(LOG_WARNING, "Span %d: No D-channels up!\n", pri->span);
1115                                 }
1116                         }
1117                 } else {
1118                         pri->no_d_channels = 0;
1119                 }
1120                 if (old && oldslot != newslot) {
1121                         ast_log(LOG_NOTICE,
1122                                 "Switching selected D-channel from %s (fd %d) to %s (fd %d)!\n",
1123                                 pri_order(oldslot), pri->fds[oldslot],
1124                                 pri_order(newslot), pri->fds[newslot]);
1125                 }
1126         } else {
1127                 if (newslot < 0) {
1128                         /* The only D-channel is not up. */
1129                         newslot = 0;
1130
1131                         if (!pri->no_d_channels) {
1132                                 pri->no_d_channels = 1;
1133
1134                                 /*
1135                                  * This is annoying to see on non-persistent layer 2
1136                                  * connections.  Let's not complain in that case.
1137                                  */
1138                                 if (pri->sig != SIG_BRI_PTMP) {
1139                                         ast_log(LOG_WARNING, "Span %d: D-channel is down!\n", pri->span);
1140                                 }
1141                         }
1142                 } else {
1143                         pri->no_d_channels = 0;
1144                 }
1145         }
1146         pri->pri = pri->dchans[newslot];
1147 }
1148
1149 /*!
1150  * \internal
1151  * \brief Determine if a private channel structure is in use.
1152  * \since 1.8
1153  *
1154  * \param pvt Channel to determine if in use.
1155  *
1156  * \return TRUE if the channel is in use.
1157  */
1158 static int sig_pri_is_chan_in_use(struct sig_pri_chan *pvt)
1159 {
1160         return pvt->owner || pvt->call || pvt->allocated || pvt->resetting || pvt->inalarm;
1161 }
1162
1163 /*!
1164  * \brief Determine if a private channel structure is available.
1165  * \since 1.8
1166  *
1167  * \param pvt Channel to determine if available.
1168  *
1169  * \return TRUE if the channel is available.
1170  */
1171 int sig_pri_is_chan_available(struct sig_pri_chan *pvt)
1172 {
1173         return !sig_pri_is_chan_in_use(pvt)
1174 #if defined(HAVE_PRI_SERVICE_MESSAGES)
1175                 /* And not out-of-service */
1176                 && !pvt->service_status
1177 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
1178                 ;
1179 }
1180
1181 /*!
1182  * \internal
1183  * \brief Obtain the sig_pri owner channel lock if the owner exists.
1184  * \since 1.8
1185  *
1186  * \param pri PRI span control structure.
1187  * \param chanpos Channel position in the span.
1188  *
1189  * \note Assumes the pri->lock is already obtained.
1190  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1191  *
1192  * \return Nothing
1193  */
1194 static void sig_pri_lock_owner(struct sig_pri_span *pri, int chanpos)
1195 {
1196         for (;;) {
1197                 if (!pri->pvts[chanpos]->owner) {
1198                         /* There is no owner lock to get. */
1199                         break;
1200                 }
1201                 if (!ast_channel_trylock(pri->pvts[chanpos]->owner)) {
1202                         /* We got the lock */
1203                         break;
1204                 }
1205                 /* We must unlock the PRI to avoid the possibility of a deadlock */
1206                 ast_mutex_unlock(&pri->lock);
1207                 sig_pri_deadlock_avoidance_private(pri->pvts[chanpos]);
1208                 ast_mutex_lock(&pri->lock);
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 = 1;
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->from, &pri_redirecting->from, pri);
2119         sig_pri_party_id_convert(&ast_redirecting->to, &pri_redirecting->to, pri);
2120         ast_redirecting->count = pri_redirecting->count;
2121         ast_redirecting->reason = pri_to_ast_reason(pri_redirecting->reason);
2122 }
2123
2124 /*!
2125  * \internal
2126  * \brief Determine if the given extension matches one of the MSNs in the pattern list.
2127  * \since 1.8
2128  *
2129  * \param msn_patterns Comma separated list of MSN patterns to match.
2130  * \param exten Extension to match in the MSN list.
2131  *
2132  * \retval 1 if matches.
2133  * \retval 0 if no match.
2134  */
2135 static int sig_pri_msn_match(const char *msn_patterns, const char *exten)
2136 {
2137         char *pattern;
2138         char *msn_list;
2139         char *list_tail;
2140
2141         msn_list = ast_strdupa(msn_patterns);
2142
2143         list_tail = NULL;
2144         pattern = strtok_r(msn_list, ",", &list_tail);
2145         while (pattern) {
2146                 pattern = ast_strip(pattern);
2147                 if (!ast_strlen_zero(pattern) && ast_extension_match(pattern, exten)) {
2148                         /* Extension matched the pattern. */
2149                         return 1;
2150                 }
2151                 pattern = strtok_r(NULL, ",", &list_tail);
2152         }
2153         /* Did not match any pattern in the list. */
2154         return 0;
2155 }
2156
2157 #if defined(HAVE_PRI_MCID)
2158 /*!
2159  * \internal
2160  * \brief Append the given party id to the event string.
2161  * \since 1.8
2162  *
2163  * \param msg Event message string being built.
2164  * \param prefix Prefix to add to the party id lines.
2165  * \param party Party information to encode.
2166  *
2167  * \return Nothing
2168  */
2169 static void sig_pri_event_party_id(struct ast_str **msg, const char *prefix, struct ast_party_id *party)
2170 {
2171         int pres;
2172
2173         /* Combined party presentation */
2174         pres = ast_party_id_presentation(party);
2175         ast_str_append(msg, 0, "%sPres: %d (%s)\r\n", prefix, pres,
2176                 ast_describe_caller_presentation(pres));
2177
2178         /* Party number */
2179         ast_str_append(msg, 0, "%sNumValid: %d\r\n", prefix,
2180                 (unsigned) party->number.valid);
2181         ast_str_append(msg, 0, "%sNum: %s\r\n", prefix,
2182                 S_COR(party->number.valid, party->number.str, ""));
2183         ast_str_append(msg, 0, "%ston: %d\r\n", prefix, party->number.plan);
2184         if (party->number.valid) {
2185                 ast_str_append(msg, 0, "%sNumPlan: %d\r\n", prefix, party->number.plan);
2186                 ast_str_append(msg, 0, "%sNumPres: %d (%s)\r\n", prefix,
2187                         party->number.presentation,
2188                         ast_describe_caller_presentation(party->number.presentation));
2189         }
2190
2191         /* Party name */
2192         ast_str_append(msg, 0, "%sNameValid: %d\r\n", prefix,
2193                 (unsigned) party->name.valid);
2194         ast_str_append(msg, 0, "%sName: %s\r\n", prefix,
2195                 S_COR(party->name.valid, party->name.str, ""));
2196         if (party->name.valid) {
2197                 ast_str_append(msg, 0, "%sNameCharSet: %s\r\n", prefix,
2198                         ast_party_name_charset_describe(party->name.char_set));
2199                 ast_str_append(msg, 0, "%sNamePres: %d (%s)\r\n", prefix,
2200                         party->name.presentation,
2201                         ast_describe_caller_presentation(party->name.presentation));
2202         }
2203
2204 #if defined(HAVE_PRI_SUBADDR)
2205         /* Party subaddress */
2206         if (party->subaddress.valid) {
2207                 static const char subaddress[] = "Subaddr";
2208
2209                 ast_str_append(msg, 0, "%s%s: %s\r\n", prefix, subaddress,
2210                         S_OR(party->subaddress.str, ""));
2211                 ast_str_append(msg, 0, "%s%sType: %d\r\n", prefix, subaddress,
2212                         party->subaddress.type);
2213                 ast_str_append(msg, 0, "%s%sOdd: %d\r\n", prefix, subaddress,
2214                         party->subaddress.odd_even_indicator);
2215         }
2216 #endif  /* defined(HAVE_PRI_SUBADDR) */
2217 }
2218 #endif  /* defined(HAVE_PRI_MCID) */
2219
2220 #if defined(HAVE_PRI_MCID)
2221 /*!
2222  * \internal
2223  * \brief Handle the MCID event.
2224  * \since 1.8
2225  *
2226  * \param pri PRI span control structure.
2227  * \param mcid MCID event parameters.
2228  * \param owner Asterisk channel associated with the call.
2229  * NULL if Asterisk no longer has the ast_channel struct.
2230  *
2231  * \note Assumes the pri->lock is already obtained.
2232  * \note Assumes the owner channel lock is already obtained if still present.
2233  *
2234  * \return Nothing
2235  */
2236 static void sig_pri_mcid_event(struct sig_pri_span *pri, const struct pri_subcmd_mcid_req *mcid, struct ast_channel *owner)
2237 {
2238         struct ast_channel *chans[1];
2239         struct ast_str *msg;
2240         struct ast_party_id party;
2241
2242         msg = ast_str_create(4096);
2243         if (!msg) {
2244                 return;
2245         }
2246
2247         if (owner) {
2248                 /*
2249                  * The owner channel is present.
2250                  * Pass the event to the peer as well.
2251                  */
2252                 ast_queue_control(owner, AST_CONTROL_MCID);
2253
2254                 ast_str_append(&msg, 0, "Channel: %s\r\n", ast_channel_name(owner));
2255                 ast_str_append(&msg, 0, "UniqueID: %s\r\n", ast_channel_uniqueid(owner));
2256
2257                 sig_pri_event_party_id(&msg, "CallerID", &ast_channel_connected(owner)->id);
2258         } else {
2259                 /*
2260                  * Since we no longer have an owner channel,
2261                  * we have to use the caller information supplied by libpri.
2262                  */
2263                 ast_party_id_init(&party);
2264                 sig_pri_party_id_convert(&party, &mcid->originator, pri);
2265                 sig_pri_event_party_id(&msg, "CallerID", &party);
2266                 ast_party_id_free(&party);
2267         }
2268
2269         /* Always use libpri's called party information. */
2270         ast_party_id_init(&party);
2271         sig_pri_party_id_convert(&party, &mcid->answerer, pri);
2272         sig_pri_event_party_id(&msg, "ConnectedID", &party);
2273         ast_party_id_free(&party);
2274
2275         chans[0] = owner;
2276         ast_manager_event_multichan(EVENT_FLAG_CALL, "MCID", owner ? 1 : 0, chans, "%s",
2277                 ast_str_buffer(msg));
2278         ast_free(msg);
2279 }
2280 #endif  /* defined(HAVE_PRI_MCID) */
2281
2282 #if defined(HAVE_PRI_TRANSFER)
2283 struct xfer_rsp_data {
2284         struct sig_pri_span *pri;
2285         /*! Call to send transfer success/fail response over. */
2286         q931_call *call;
2287         /*! Invocation ID to use when sending a reply to the transfer request. */
2288         int invoke_id;
2289 };
2290 #endif  /* defined(HAVE_PRI_TRANSFER) */
2291
2292 #if defined(HAVE_PRI_TRANSFER)
2293 /*!
2294  * \internal
2295  * \brief Send the transfer success/fail response message.
2296  * \since 1.8
2297  *
2298  * \param data Callback user data pointer
2299  * \param is_successful TRUE if the transfer was successful.
2300  *
2301  * \return Nothing
2302  */
2303 static void sig_pri_transfer_rsp(void *data, int is_successful)
2304 {
2305         struct xfer_rsp_data *rsp = data;
2306
2307         pri_transfer_rsp(rsp->pri->pri, rsp->call, rsp->invoke_id, is_successful);
2308 }
2309 #endif  /* defined(HAVE_PRI_TRANSFER) */
2310
2311 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2312 /*!
2313  * \brief Protocol callback to indicate if transfer will happen.
2314  * \since 1.8
2315  *
2316  * \param data Callback user data pointer
2317  * \param is_successful TRUE if the transfer will happen.
2318  *
2319  * \return Nothing
2320  */
2321 typedef void (*xfer_rsp_callback)(void *data, int is_successful);
2322 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2323
2324 #if defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER)
2325 /*!
2326  * \internal
2327  * \brief Attempt to transfer the two calls to each other.
2328  * \since 1.8
2329  *
2330  * \param pri PRI span control structure.
2331  * \param call_1_pri First call involved in the transfer. (transferee; usually on hold)
2332  * \param call_1_held TRUE if call_1_pri is on hold.
2333  * \param call_2_pri Second call involved in the transfer. (target; usually active/ringing)
2334  * \param call_2_held TRUE if call_2_pri is on hold.
2335  * \param rsp_callback Protocol callback to indicate if transfer will happen. NULL if not used.
2336  * \param data Callback user data pointer
2337  *
2338  * \note Assumes the pri->lock is already obtained.
2339  *
2340  * \retval 0 on success.
2341  * \retval -1 on error.
2342  */
2343 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)
2344 {
2345         struct attempt_xfer_call {
2346                 q931_call *pri;
2347                 struct ast_channel *ast;
2348                 int held;
2349                 int chanpos;
2350         };
2351         int retval;
2352         struct ast_channel *transferee;
2353         struct attempt_xfer_call *call_1;
2354         struct attempt_xfer_call *call_2;
2355         struct attempt_xfer_call *swap_call;
2356         struct attempt_xfer_call c1;
2357         struct attempt_xfer_call c2;
2358
2359         c1.pri = call_1_pri;
2360         c1.held = call_1_held;
2361         call_1 = &c1;
2362
2363         c2.pri = call_2_pri;
2364         c2.held = call_2_held;
2365         call_2 = &c2;
2366
2367         call_1->chanpos = pri_find_principle_by_call(pri, call_1->pri);
2368         call_2->chanpos = pri_find_principle_by_call(pri, call_2->pri);
2369         if (call_1->chanpos < 0 || call_2->chanpos < 0) {
2370                 /* Calls not found in span control. */
2371                 if (rsp_callback) {
2372                         /* Transfer failed. */
2373                         rsp_callback(data, 0);
2374                 }
2375                 return -1;
2376         }
2377
2378         /* Attempt to make transferee and target consistent. */
2379         if (!call_1->held && call_2->held) {
2380                 /*
2381                  * Swap call_1 and call_2 to make call_1 the transferee(held call)
2382                  * and call_2 the target(active call).
2383                  */
2384                 swap_call = call_1;
2385                 call_1 = call_2;
2386                 call_2 = swap_call;
2387         }
2388
2389         /* Deadlock avoidance is attempted. */
2390         sig_pri_lock_private(pri->pvts[call_1->chanpos]);
2391         sig_pri_lock_owner(pri, call_1->chanpos);
2392         sig_pri_lock_private(pri->pvts[call_2->chanpos]);
2393         sig_pri_lock_owner(pri, call_2->chanpos);
2394
2395         call_1->ast = pri->pvts[call_1->chanpos]->owner;
2396         call_2->ast = pri->pvts[call_2->chanpos]->owner;
2397         if (!call_1->ast || !call_2->ast) {
2398                 /* At least one owner is not present. */
2399                 if (call_1->ast) {
2400                         ast_channel_unlock(call_1->ast);
2401                 }
2402                 if (call_2->ast) {
2403                         ast_channel_unlock(call_2->ast);
2404                 }
2405                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2406                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2407                 if (rsp_callback) {
2408                         /* Transfer failed. */
2409                         rsp_callback(data, 0);
2410                 }
2411                 return -1;
2412         }
2413
2414         for (;;) {
2415                 transferee = ast_bridged_channel(call_1->ast);
2416                 if (transferee) {
2417                         break;
2418                 }
2419
2420                 /* Try masquerading the other way. */
2421                 swap_call = call_1;
2422                 call_1 = call_2;
2423                 call_2 = swap_call;
2424
2425                 transferee = ast_bridged_channel(call_1->ast);
2426                 if (transferee) {
2427                         break;
2428                 }
2429
2430                 /* Could not transfer.  Neither call is bridged. */
2431                 ast_channel_unlock(call_1->ast);
2432                 ast_channel_unlock(call_2->ast);
2433                 sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2434                 sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2435
2436                 if (rsp_callback) {
2437                         /* Transfer failed. */
2438                         rsp_callback(data, 0);
2439                 }
2440                 return -1;
2441         }
2442
2443         ast_verb(3, "TRANSFERRING %s to %s\n", ast_channel_name(call_1->ast), ast_channel_name(call_2->ast));
2444
2445         /*
2446          * Setup transfer masquerade.
2447          *
2448          * Note:  There is an extremely nasty deadlock avoidance issue
2449          * with ast_channel_transfer_masquerade().  Deadlock may be possible if
2450          * the channels involved are proxies (chan_agent channels) and
2451          * it is called with locks.  Unfortunately, there is no simple
2452          * or even merely difficult way to guarantee deadlock avoidance
2453          * and still be able to send an ECT success response without the
2454          * possibility of the bridged channel hanging up on us.
2455          */
2456         ast_mutex_unlock(&pri->lock);
2457         retval = ast_channel_transfer_masquerade(
2458                 call_2->ast,
2459                 ast_channel_connected(call_2->ast),
2460                 call_2->held,
2461                 transferee,
2462                 ast_channel_connected(call_1->ast),
2463                 call_1->held);
2464
2465         /* Reacquire the pri->lock to hold off completion of the transfer masquerade. */
2466         ast_mutex_lock(&pri->lock);
2467
2468         ast_channel_unlock(call_1->ast);
2469         ast_channel_unlock(call_2->ast);
2470         sig_pri_unlock_private(pri->pvts[call_1->chanpos]);
2471         sig_pri_unlock_private(pri->pvts[call_2->chanpos]);
2472
2473         if (rsp_callback) {
2474                 /*
2475                  * Report transfer status.
2476                  *
2477                  * Must do the callback before the masquerade completes to ensure
2478                  * that the protocol message goes out before the call leg is
2479                  * disconnected.
2480                  */
2481                 rsp_callback(data, retval ? 0 : 1);
2482         }
2483         return retval;
2484 }
2485 #endif  /* defined(HAVE_PRI_CALL_HOLD) || defined(HAVE_PRI_TRANSFER) */
2486
2487 #if defined(HAVE_PRI_CCSS)
2488 /*!
2489  * \internal
2490  * \brief Compare the CC agent private data by libpri cc_id.
2491  * \since 1.8
2492  *
2493  * \param obj pointer to the (user-defined part) of an object.
2494  * \param arg callback argument from ao2_callback()
2495  * \param flags flags from ao2_callback()
2496  *
2497  * \return values are a combination of enum _cb_results.
2498  */
2499 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
2500 {
2501         struct ast_cc_agent *agent_1 = obj;
2502         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
2503         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
2504
2505         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
2506                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2507 }
2508 #endif  /* defined(HAVE_PRI_CCSS) */
2509
2510 #if defined(HAVE_PRI_CCSS)
2511 /*!
2512  * \internal
2513  * \brief Find the CC agent by libpri cc_id.
2514  * \since 1.8
2515  *
2516  * \param pri PRI span control structure.
2517  * \param cc_id CC record ID to find.
2518  *
2519  * \note
2520  * Since agents are refcounted, and this function returns
2521  * a reference to the agent, it is imperative that you decrement
2522  * the refcount of the agent once you have finished using it.
2523  *
2524  * \retval agent on success.
2525  * \retval NULL not found.
2526  */
2527 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_span *pri, long cc_id)
2528 {
2529         struct sig_pri_cc_agent_prv finder = {
2530                 .pri = pri,
2531                 .cc_id = cc_id,
2532         };
2533
2534         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
2535                 sig_pri_cc_type_name);
2536 }
2537 #endif  /* defined(HAVE_PRI_CCSS) */
2538
2539 #if defined(HAVE_PRI_CCSS)
2540 /*!
2541  * \internal
2542  * \brief Compare the CC monitor instance by libpri cc_id.
2543  * \since 1.8
2544  *
2545  * \param obj pointer to the (user-defined part) of an object.
2546  * \param arg callback argument from ao2_callback()
2547  * \param flags flags from ao2_callback()
2548  *
2549  * \return values are a combination of enum _cb_results.
2550  */
2551 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
2552 {
2553         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
2554         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
2555
2556         return (monitor_1->pri == monitor_2->pri
2557                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
2558 }
2559 #endif  /* defined(HAVE_PRI_CCSS) */
2560
2561 #if defined(HAVE_PRI_CCSS)
2562 /*!
2563  * \internal
2564  * \brief Find the CC monitor instance by libpri cc_id.
2565  * \since 1.8
2566  *
2567  * \param pri PRI span control structure.
2568  * \param cc_id CC record ID to find.
2569  *
2570  * \note
2571  * Since monitor_instances are refcounted, and this function returns
2572  * a reference to the instance, it is imperative that you decrement
2573  * the refcount of the instance once you have finished using it.
2574  *
2575  * \retval monitor_instance on success.
2576  * \retval NULL not found.
2577  */
2578 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_span *pri, long cc_id)
2579 {
2580         struct sig_pri_cc_monitor_instance finder = {
2581                 .pri = pri,
2582                 .cc_id = cc_id,
2583         };
2584
2585         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
2586 }
2587 #endif  /* defined(HAVE_PRI_CCSS) */
2588
2589 #if defined(HAVE_PRI_CCSS)
2590 /*!
2591  * \internal
2592  * \brief Destroy the given monitor instance.
2593  * \since 1.8
2594  *
2595  * \param data Monitor instance to destroy.
2596  *
2597  * \return Nothing
2598  */
2599 static void sig_pri_cc_monitor_instance_destroy(void *data)
2600 {
2601         struct sig_pri_cc_monitor_instance *monitor_instance = data;
2602
2603         if (monitor_instance->cc_id != -1) {
2604                 ast_mutex_lock(&monitor_instance->pri->lock);
2605                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
2606                 ast_mutex_unlock(&monitor_instance->pri->lock);
2607         }
2608         monitor_instance->pri->calls->module_unref();
2609 }
2610 #endif  /* defined(HAVE_PRI_CCSS) */
2611
2612 #if defined(HAVE_PRI_CCSS)
2613 /*!
2614  * \internal
2615  * \brief Construct a new monitor instance.
2616  * \since 1.8
2617  *
2618  * \param core_id CC core ID.
2619  * \param pri PRI span control structure.
2620  * \param cc_id CC record ID.
2621  * \param device_name Name of device (Asterisk channel name less sequence number).
2622  *
2623  * \note
2624  * Since monitor_instances are refcounted, and this function returns
2625  * a reference to the instance, it is imperative that you decrement
2626  * the refcount of the instance once you have finished using it.
2627  *
2628  * \retval monitor_instance on success.
2629  * \retval NULL on error.
2630  */
2631 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)
2632 {
2633         struct sig_pri_cc_monitor_instance *monitor_instance;
2634
2635         if (!pri->calls->module_ref || !pri->calls->module_unref) {
2636                 return NULL;
2637         }
2638
2639         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
2640                 sig_pri_cc_monitor_instance_destroy);
2641         if (!monitor_instance) {
2642                 return NULL;
2643         }
2644
2645         monitor_instance->cc_id = cc_id;
2646         monitor_instance->pri = pri;
2647         monitor_instance->core_id = core_id;
2648         strcpy(monitor_instance->name, device_name);
2649
2650         pri->calls->module_ref();
2651
2652         ao2_link(sig_pri_cc_monitors, monitor_instance);
2653         return monitor_instance;
2654 }
2655 #endif  /* defined(HAVE_PRI_CCSS) */
2656
2657 #if defined(HAVE_PRI_CCSS)
2658 /*!
2659  * \internal
2660  * \brief Announce to the CC core that protocol CC monitor is available for this call.
2661  * \since 1.8
2662  *
2663  * \param pri PRI span control structure.
2664  * \param chanpos Channel position in the span.
2665  * \param cc_id CC record ID.
2666  * \param service CCBS/CCNR indication.
2667  *
2668  * \note Assumes the pri->lock is already obtained.
2669  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2670  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
2671  *
2672  * \retval 0 on success.
2673  * \retval -1 on error.
2674  */
2675 static int sig_pri_cc_available(struct sig_pri_span *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
2676 {
2677         struct sig_pri_chan *pvt;
2678         struct ast_cc_config_params *cc_params;
2679         struct sig_pri_cc_monitor_instance *monitor;
2680         enum ast_cc_monitor_policies monitor_policy;
2681         int core_id;
2682         int res;
2683         char device_name[AST_CHANNEL_NAME];
2684         char dialstring[AST_CHANNEL_NAME];
2685
2686         pvt = pri->pvts[chanpos];
2687
2688         core_id = ast_cc_get_current_core_id(pvt->owner);
2689         if (core_id == -1) {
2690                 return -1;
2691         }
2692
2693         cc_params = ast_channel_get_cc_config_params(pvt->owner);
2694         if (!cc_params) {
2695                 return -1;
2696         }
2697
2698         res = -1;
2699         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2700         switch (monitor_policy) {
2701         case AST_CC_MONITOR_NEVER:
2702                 /* CCSS is not enabled. */
2703                 break;
2704         case AST_CC_MONITOR_NATIVE:
2705         case AST_CC_MONITOR_ALWAYS:
2706                 /*
2707                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
2708                  * later in the call to sig_pri_cc_generic_check().
2709                  */
2710                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2711                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
2712                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
2713                 if (!monitor) {
2714                         break;
2715                 }
2716                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
2717                         monitor);
2718                 if (res) {
2719                         monitor->cc_id = -1;
2720                         ao2_unlink(sig_pri_cc_monitors, monitor);
2721                         ao2_ref(monitor, -1);
2722                 }
2723                 break;
2724         case AST_CC_MONITOR_GENERIC:
2725                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
2726                         sig_pri_get_orig_dialstring(pvt), service, NULL);
2727                 /* Say it failed to force caller to cancel native CC. */
2728                 break;
2729         }
2730         return res;
2731 }
2732 #endif  /* defined(HAVE_PRI_CCSS) */
2733
2734 /*!
2735  * \internal
2736  * \brief Check if generic CC monitor is needed and request it.
2737  * \since 1.8
2738  *
2739  * \param pri PRI span control structure.
2740  * \param chanpos Channel position in the span.
2741  * \param service CCBS/CCNR indication.
2742  *
2743  * \note Assumes the pri->lock is already obtained.
2744  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2745  *
2746  * \return Nothing
2747  */
2748 static void sig_pri_cc_generic_check(struct sig_pri_span *pri, int chanpos, enum ast_cc_service_type service)
2749 {
2750         struct ast_channel *owner;
2751         struct ast_cc_config_params *cc_params;
2752 #if defined(HAVE_PRI_CCSS)
2753         struct ast_cc_monitor *monitor;
2754         char device_name[AST_CHANNEL_NAME];
2755 #endif  /* defined(HAVE_PRI_CCSS) */
2756         enum ast_cc_monitor_policies monitor_policy;
2757         int core_id;
2758
2759         if (!pri->pvts[chanpos]->outgoing) {
2760                 /* This is not an outgoing call so it cannot be CC monitor. */
2761                 return;
2762         }
2763
2764         sig_pri_lock_owner(pri, chanpos);
2765         owner = pri->pvts[chanpos]->owner;
2766         if (!owner) {
2767                 return;
2768         }
2769         core_id = ast_cc_get_current_core_id(owner);
2770         if (core_id == -1) {
2771                 /* No CC core setup */
2772                 goto done;
2773         }
2774
2775         cc_params = ast_channel_get_cc_config_params(owner);
2776         if (!cc_params) {
2777                 /* Could not get CC config parameters. */
2778                 goto done;
2779         }
2780
2781 #if defined(HAVE_PRI_CCSS)
2782         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
2783         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
2784         if (monitor) {
2785                 /* CC monitor is already present so no need for generic CC. */
2786                 ao2_ref(monitor, -1);
2787                 goto done;
2788         }
2789 #endif  /* defined(HAVE_PRI_CCSS) */
2790
2791         monitor_policy = ast_get_cc_monitor_policy(cc_params);
2792         switch (monitor_policy) {
2793         case AST_CC_MONITOR_NEVER:
2794                 /* CCSS is not enabled. */
2795                 break;
2796         case AST_CC_MONITOR_NATIVE:
2797                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2798                         /* Request generic CC monitor. */
2799                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2800                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2801                 }
2802                 break;
2803         case AST_CC_MONITOR_ALWAYS:
2804                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
2805                         /*
2806                          * Cannot monitor PTMP TE side since this is not defined.
2807                          * We are playing the roll of a phone in this case and
2808                          * a phone cannot monitor a party over the network without
2809                          * protocol help.
2810                          */
2811                         break;
2812                 }
2813                 /*
2814                  * We are either falling back or this is a PTMP NT span.
2815                  * Request generic CC monitor.
2816                  */
2817                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2818                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2819                 break;
2820         case AST_CC_MONITOR_GENERIC:
2821                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
2822                         /* Request generic CC monitor. */
2823                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
2824                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
2825                 }
2826                 break;
2827         }
2828
2829 done:
2830         ast_channel_unlock(owner);
2831 }
2832
2833 #if defined(HAVE_PRI_CCSS)
2834 /*!
2835  * \internal
2836  * \brief The CC link canceled the CC instance.
2837  * \since 1.8
2838  *
2839  * \param pri PRI span control structure.
2840  * \param cc_id CC record ID.
2841  * \param is_agent TRUE if the cc_id is for an agent.
2842  *
2843  * \return Nothing
2844  */
2845 static void sig_pri_cc_link_canceled(struct sig_pri_span *pri, long cc_id, int is_agent)
2846 {
2847         if (is_agent) {
2848                 struct ast_cc_agent *agent;
2849
2850                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
2851                 if (!agent) {
2852                         return;
2853                 }
2854                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
2855                         sig_pri_cc_type_name);
2856                 ao2_ref(agent, -1);
2857         } else {
2858                 struct sig_pri_cc_monitor_instance *monitor;
2859
2860                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
2861                 if (!monitor) {
2862                         return;
2863                 }
2864                 monitor->cc_id = -1;
2865                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2866                         "%s monitor got canceled by link", sig_pri_cc_type_name);
2867                 ao2_ref(monitor, -1);
2868         }
2869 }
2870 #endif  /* defined(HAVE_PRI_CCSS) */
2871
2872 #if defined(HAVE_PRI_AOC_EVENTS)
2873 /*!
2874  * \internal
2875  * \brief Convert ast_aoc_charged_item to PRI_AOC_CHARGED_ITEM .
2876  * \since 1.8
2877  *
2878  * \param value Value to convert to string.
2879  *
2880  * \return PRI_AOC_CHARGED_ITEM
2881  */
2882 static enum PRI_AOC_CHARGED_ITEM sig_pri_aoc_charged_item_to_pri(enum PRI_AOC_CHARGED_ITEM value)
2883 {
2884         switch (value) {
2885         case AST_AOC_CHARGED_ITEM_NA:
2886                 return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2887         case AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2888                 return PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2889         case AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2890                 return PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2891         case AST_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2892                 return PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2893         case AST_AOC_CHARGED_ITEM_CALL_SETUP:
2894                 return PRI_AOC_CHARGED_ITEM_CALL_SETUP;
2895         case AST_AOC_CHARGED_ITEM_USER_USER_INFO:
2896                 return PRI_AOC_CHARGED_ITEM_USER_USER_INFO;
2897         case AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2898                 return PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2899         }
2900         return PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE;
2901 }
2902 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2903
2904 #if defined(HAVE_PRI_AOC_EVENTS)
2905 /*!
2906  * \internal
2907  * \brief Convert PRI_AOC_CHARGED_ITEM to ast_aoc_charged_item.
2908  * \since 1.8
2909  *
2910  * \param value Value to convert to string.
2911  *
2912  * \return ast_aoc_charged_item
2913  */
2914 static enum ast_aoc_s_charged_item sig_pri_aoc_charged_item_to_ast(enum PRI_AOC_CHARGED_ITEM value)
2915 {
2916         switch (value) {
2917         case PRI_AOC_CHARGED_ITEM_NOT_AVAILABLE:
2918                 return AST_AOC_CHARGED_ITEM_NA;
2919         case PRI_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT:
2920                 return AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
2921         case PRI_AOC_CHARGED_ITEM_BASIC_COMMUNICATION:
2922                 return AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
2923         case PRI_AOC_CHARGED_ITEM_CALL_ATTEMPT:
2924                 return AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
2925         case PRI_AOC_CHARGED_ITEM_CALL_SETUP:
2926                 return AST_AOC_CHARGED_ITEM_CALL_SETUP;
2927         case PRI_AOC_CHARGED_ITEM_USER_USER_INFO:
2928                 return AST_AOC_CHARGED_ITEM_USER_USER_INFO;
2929         case PRI_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE:
2930                 return AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
2931         }
2932         return AST_AOC_CHARGED_ITEM_NA;
2933 }
2934 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2935
2936 #if defined(HAVE_PRI_AOC_EVENTS)
2937 /*!
2938  * \internal
2939  * \brief Convert AST_AOC_MULTIPLER to PRI_AOC_MULTIPLIER.
2940  * \since 1.8
2941  *
2942  * \return pri enum equivalent.
2943  */
2944 static int sig_pri_aoc_multiplier_from_ast(enum ast_aoc_currency_multiplier mult)
2945 {
2946         switch (mult) {
2947         case AST_AOC_MULT_ONETHOUSANDTH:
2948                 return PRI_AOC_MULTIPLIER_THOUSANDTH;
2949         case AST_AOC_MULT_ONEHUNDREDTH:
2950                 return PRI_AOC_MULTIPLIER_HUNDREDTH;
2951         case AST_AOC_MULT_ONETENTH:
2952                 return PRI_AOC_MULTIPLIER_TENTH;
2953         case AST_AOC_MULT_ONE:
2954                 return PRI_AOC_MULTIPLIER_ONE;
2955         case AST_AOC_MULT_TEN:
2956                 return PRI_AOC_MULTIPLIER_TEN;
2957         case AST_AOC_MULT_HUNDRED:
2958                 return PRI_AOC_MULTIPLIER_HUNDRED;
2959         case AST_AOC_MULT_THOUSAND:
2960                 return PRI_AOC_MULTIPLIER_THOUSAND;
2961         default:
2962                 return PRI_AOC_MULTIPLIER_ONE;
2963         }
2964 }
2965 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2966
2967 #if defined(HAVE_PRI_AOC_EVENTS)
2968 /*!
2969  * \internal
2970  * \brief Convert PRI_AOC_MULTIPLIER to AST_AOC_MULTIPLIER
2971  * \since 1.8
2972  *
2973  * \return ast enum equivalent.
2974  */
2975 static int sig_pri_aoc_multiplier_from_pri(const int mult)
2976 {
2977         switch (mult) {
2978         case PRI_AOC_MULTIPLIER_THOUSANDTH:
2979                 return AST_AOC_MULT_ONETHOUSANDTH;
2980         case PRI_AOC_MULTIPLIER_HUNDREDTH:
2981                 return AST_AOC_MULT_ONEHUNDREDTH;
2982         case PRI_AOC_MULTIPLIER_TENTH:
2983                 return AST_AOC_MULT_ONETENTH;
2984         case PRI_AOC_MULTIPLIER_ONE:
2985                 return AST_AOC_MULT_ONE;
2986         case PRI_AOC_MULTIPLIER_TEN:
2987                 return AST_AOC_MULT_TEN;
2988         case PRI_AOC_MULTIPLIER_HUNDRED:
2989                 return AST_AOC_MULT_HUNDRED;
2990         case PRI_AOC_MULTIPLIER_THOUSAND:
2991                 return AST_AOC_MULT_THOUSAND;
2992         default:
2993                 return AST_AOC_MULT_ONE;
2994         }
2995 }
2996 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
2997
2998 #if defined(HAVE_PRI_AOC_EVENTS)
2999 /*!
3000  * \internal
3001  * \brief Convert ast_aoc_time_scale representation to PRI_AOC_TIME_SCALE
3002  * \since 1.8
3003  *
3004  * \param value Value to convert to ast representation
3005  *
3006  * \return PRI_AOC_TIME_SCALE
3007  */
3008 static enum PRI_AOC_TIME_SCALE sig_pri_aoc_scale_to_pri(enum ast_aoc_time_scale value)
3009 {
3010         switch (value) {
3011         default:
3012         case AST_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3013                 return PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3014         case AST_AOC_TIME_SCALE_TENTH_SECOND:
3015                 return PRI_AOC_TIME_SCALE_TENTH_SECOND;
3016         case AST_AOC_TIME_SCALE_SECOND:
3017                 return PRI_AOC_TIME_SCALE_SECOND;
3018         case AST_AOC_TIME_SCALE_TEN_SECOND:
3019                 return PRI_AOC_TIME_SCALE_TEN_SECOND;
3020         case AST_AOC_TIME_SCALE_MINUTE:
3021                 return PRI_AOC_TIME_SCALE_MINUTE;
3022         case AST_AOC_TIME_SCALE_HOUR:
3023                 return PRI_AOC_TIME_SCALE_HOUR;
3024         case AST_AOC_TIME_SCALE_DAY:
3025                 return PRI_AOC_TIME_SCALE_DAY;
3026         }
3027 }
3028 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3029
3030 #if defined(HAVE_PRI_AOC_EVENTS)
3031 /*!
3032  * \internal
3033  * \brief Convert PRI_AOC_TIME_SCALE to ast aoc representation
3034  * \since 1.8
3035  *
3036  * \param value Value to convert to ast representation
3037  *
3038  * \return ast aoc time scale
3039  */
3040 static enum ast_aoc_time_scale sig_pri_aoc_scale_to_ast(enum PRI_AOC_TIME_SCALE value)
3041 {
3042         switch (value) {
3043         default:
3044         case PRI_AOC_TIME_SCALE_HUNDREDTH_SECOND:
3045                 return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3046         case PRI_AOC_TIME_SCALE_TENTH_SECOND:
3047                 return AST_AOC_TIME_SCALE_TENTH_SECOND;
3048         case PRI_AOC_TIME_SCALE_SECOND:
3049                 return AST_AOC_TIME_SCALE_SECOND;
3050         case PRI_AOC_TIME_SCALE_TEN_SECOND:
3051                 return AST_AOC_TIME_SCALE_TEN_SECOND;
3052         case PRI_AOC_TIME_SCALE_MINUTE:
3053                 return AST_AOC_TIME_SCALE_MINUTE;
3054         case PRI_AOC_TIME_SCALE_HOUR:
3055                 return AST_AOC_TIME_SCALE_HOUR;
3056         case PRI_AOC_TIME_SCALE_DAY:
3057                 return AST_AOC_TIME_SCALE_DAY;
3058         }
3059         return AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
3060 }
3061 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3062
3063 #if defined(HAVE_PRI_AOC_EVENTS)
3064 /*!
3065  * \internal
3066  * \brief Handle AOC-S control frame
3067  * \since 1.8
3068  *
3069  * \param aoc_s AOC-S event parameters.
3070  * \param owner Asterisk channel associated with the call.
3071  * \param passthrough indicating if this message should be queued on the ast channel
3072  *
3073  * \note Assumes the pri->lock is already obtained.
3074  * \note Assumes the sig_pri private is locked
3075  * \note Assumes the owner channel lock is already obtained.
3076  *
3077  * \return Nothing
3078  */
3079 static void sig_pri_aoc_s_from_pri(const struct pri_subcmd_aoc_s *aoc_s, struct ast_channel *owner, int passthrough)
3080 {
3081         struct ast_aoc_decoded *decoded = NULL;
3082         struct ast_aoc_encoded *encoded = NULL;
3083         size_t encoded_size = 0;
3084         int idx;
3085
3086         if (!owner || !aoc_s) {
3087                 return;
3088         }
3089
3090         if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
3091                 return;
3092         }
3093
3094         for (idx = 0; idx < aoc_s->num_items; ++idx) {
3095                 enum ast_aoc_s_charged_item charged_item;
3096
3097                 charged_item = sig_pri_aoc_charged_item_to_ast(aoc_s->item[idx].chargeable);
3098                 if (charged_item == AST_AOC_CHARGED_ITEM_NA) {
3099                         /* Delete the unknown charged item from the list. */
3100                         continue;
3101                 }
3102                 switch (aoc_s->item[idx].rate_type) {
3103                 case PRI_AOC_RATE_TYPE_DURATION:
3104                         ast_aoc_s_add_rate_duration(decoded,
3105                                 charged_item,
3106                                 aoc_s->item[idx].rate.duration.amount.cost,
3107                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.duration.amount.multiplier),
3108                                 aoc_s->item[idx].rate.duration.currency,
3109                                 aoc_s->item[idx].rate.duration.time.length,
3110                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.time.scale),
3111                                 aoc_s->item[idx].rate.duration.granularity.length,
3112                                 sig_pri_aoc_scale_to_ast(aoc_s->item[idx].rate.duration.granularity.scale),
3113                                 aoc_s->item[idx].rate.duration.charging_type);
3114                         break;
3115                 case PRI_AOC_RATE_TYPE_FLAT:
3116                         ast_aoc_s_add_rate_flat(decoded,
3117                                 charged_item,
3118                                 aoc_s->item[idx].rate.flat.amount.cost,
3119                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.flat.amount.multiplier),
3120                                 aoc_s->item[idx].rate.flat.currency);
3121                         break;
3122                 case PRI_AOC_RATE_TYPE_VOLUME:
3123                         ast_aoc_s_add_rate_volume(decoded,
3124                                 charged_item,
3125                                 aoc_s->item[idx].rate.volume.unit,
3126                                 aoc_s->item[idx].rate.volume.amount.cost,
3127                                 sig_pri_aoc_multiplier_from_pri(aoc_s->item[idx].rate.volume.amount.multiplier),
3128                                 aoc_s->item[idx].rate.volume.currency);
3129                         break;
3130                 case PRI_AOC_RATE_TYPE_SPECIAL_CODE:
3131                         ast_aoc_s_add_rate_special_charge_code(decoded,
3132                                 charged_item,
3133                                 aoc_s->item[idx].rate.special);
3134                         break;
3135                 case PRI_AOC_RATE_TYPE_FREE:
3136                         ast_aoc_s_add_rate_free(decoded, charged_item, 0);
3137                         break;
3138                 case PRI_AOC_RATE_TYPE_FREE_FROM_BEGINNING:
3139                         ast_aoc_s_add_rate_free(decoded, charged_item, 1);
3140                         break;
3141                 default:
3142                         ast_aoc_s_add_rate_na(decoded, charged_item);
3143                         break;
3144                 }
3145         }
3146
3147         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3148                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3149         }
3150
3151         ast_aoc_manager_event(decoded, owner);
3152
3153         ast_aoc_destroy_decoded(decoded);
3154         ast_aoc_destroy_encoded(encoded);
3155 }
3156 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3157
3158 #if defined(HAVE_PRI_AOC_EVENTS)
3159 /*!
3160  * \internal
3161  * \brief Generate AOC Request Response
3162  * \since 1.8
3163  *
3164  * \param aoc_request
3165  *
3166  * \note Assumes the pri->lock is already obtained.
3167  * \note Assumes the sig_pri private is locked
3168  * \note Assumes the owner channel lock is already obtained.
3169  *
3170  * \return Nothing
3171  */
3172 static void sig_pri_aoc_request_from_pri(const struct pri_subcmd_aoc_request *aoc_request, struct sig_pri_chan *pvt, q931_call *call)
3173 {
3174         int request;
3175
3176         if (!aoc_request) {
3177                 return;
3178         }
3179
3180         request = aoc_request->charging_request;
3181
3182         if (request & PRI_AOC_REQUEST_S) {
3183                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_S) {
3184                         /* An AOC-S response must come from the other side, so save off this invoke_id
3185                          * and see if an AOC-S message comes in before the call is answered. */
3186                         pvt->aoc_s_request_invoke_id = aoc_request->invoke_id;
3187                         pvt->aoc_s_request_invoke_id_valid = 1;
3188
3189                 } else {
3190                         pri_aoc_s_request_response_send(pvt->pri->pri,
3191                                 call,
3192                                 aoc_request->invoke_id,
3193                                 NULL);
3194                 }
3195         }
3196
3197         if (request & PRI_AOC_REQUEST_D) {
3198                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_D) {
3199                         pri_aoc_de_request_response_send(pvt->pri->pri,
3200                                 call,
3201                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3202                                 aoc_request->invoke_id);
3203                 } else {
3204                         pri_aoc_de_request_response_send(pvt->pri->pri,
3205                                 call,
3206                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3207                                 aoc_request->invoke_id);
3208                 }
3209         }
3210
3211         if (request & PRI_AOC_REQUEST_E) {
3212                 if (pvt->pri->aoc_passthrough_flag & SIG_PRI_AOC_GRANT_E) {
3213                         pri_aoc_de_request_response_send(pvt->pri->pri,
3214                                 call,
3215                                 PRI_AOC_REQ_RSP_CHARGING_INFO_FOLLOWS,
3216                                 aoc_request->invoke_id);
3217                 } else {
3218                         pri_aoc_de_request_response_send(pvt->pri->pri,
3219                                 call,
3220                                 PRI_AOC_REQ_RSP_ERROR_NOT_AVAILABLE,
3221                                 aoc_request->invoke_id);
3222                 }
3223         }
3224 }
3225 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3226
3227 #if defined(HAVE_PRI_AOC_EVENTS)
3228 /*!
3229  * \internal
3230  * \brief Generate AOC-D AST_CONTROL_AOC frame
3231  * \since 1.8
3232  *
3233  * \param aoc_e AOC-D event parameters.
3234  * \param owner Asterisk channel associated with the call.
3235  * \param passthrough indicating if this message should be queued on the ast channel
3236  *
3237  * \note Assumes the pri->lock is already obtained.
3238  * \note Assumes the sig_pri private is locked
3239  * \note Assumes the owner channel lock is already obtained.
3240  *
3241  * \return Nothing
3242  */
3243 static void sig_pri_aoc_d_from_pri(const struct pri_subcmd_aoc_d *aoc_d, struct ast_channel *owner, int passthrough)
3244 {
3245         struct ast_aoc_decoded *decoded = NULL;
3246         struct ast_aoc_encoded *encoded = NULL;
3247         size_t encoded_size = 0;
3248         enum ast_aoc_charge_type type;
3249
3250         if (!owner || !aoc_d) {
3251                 return;
3252         }
3253
3254         switch (aoc_d->charge) {
3255         case PRI_AOC_DE_CHARGE_CURRENCY:
3256                 type = AST_AOC_CHARGE_CURRENCY;
3257                 break;
3258         case PRI_AOC_DE_CHARGE_UNITS:
3259                 type = AST_AOC_CHARGE_UNIT;
3260                 break;
3261         case PRI_AOC_DE_CHARGE_FREE:
3262                 type = AST_AOC_CHARGE_FREE;
3263                 break;
3264         default:
3265                 type = AST_AOC_CHARGE_NA;
3266                 break;
3267         }
3268
3269         if (!(decoded = ast_aoc_create(AST_AOC_D, type, 0))) {
3270                 return;
3271         }
3272
3273         switch (aoc_d->billing_accumulation) {
3274         default:
3275                 ast_debug(1, "AOC-D billing accumulation has unknown value: %d\n",
3276                         aoc_d->billing_accumulation);
3277                 /* Fall through */
3278         case 0:/* subTotal */
3279                 ast_aoc_set_total_type(decoded, AST_AOC_SUBTOTAL);
3280                 break;
3281         case 1:/* total */
3282                 ast_aoc_set_total_type(decoded, AST_AOC_TOTAL);
3283                 break;
3284         }
3285
3286         switch (aoc_d->billing_id) {
3287         case PRI_AOC_D_BILLING_ID_NORMAL:
3288                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NORMAL);
3289                 break;
3290         case PRI_AOC_D_BILLING_ID_REVERSE:
3291                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_REVERSE_CHARGE);
3292                 break;
3293         case PRI_AOC_D_BILLING_ID_CREDIT_CARD:
3294                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_CREDIT_CARD);
3295                 break;
3296         case PRI_AOC_D_BILLING_ID_NOT_AVAILABLE:
3297         default:
3298                 ast_aoc_set_billing_id(decoded, AST_AOC_BILLING_NA);
3299                 break;
3300         }
3301
3302         switch (aoc_d->charge) {
3303         case PRI_AOC_DE_CHARGE_CURRENCY:
3304                 ast_aoc_set_currency_info(decoded,
3305                         aoc_d->recorded.money.amount.cost,
3306                         sig_pri_aoc_multiplier_from_pri(aoc_d->recorded.money.amount.multiplier),
3307                         aoc_d->recorded.money.currency);
3308                 break;
3309         case PRI_AOC_DE_CHARGE_UNITS:
3310                 {
3311                         int i;
3312                         for (i = 0; i < aoc_d->recorded.unit.num_items; ++i) {
3313                                 /* if type or number are negative, then they are not present */
3314                                 ast_aoc_add_unit_entry(decoded,
3315                                         (aoc_d->recorded.unit.item[i].number >= 0 ? 1 : 0),
3316                                         aoc_d->recorded.unit.item[i].number,
3317                                         (aoc_d->recorded.unit.item[i].type >= 0 ? 1 : 0),
3318                                         aoc_d->recorded.unit.item[i].type);
3319                         }
3320                 }
3321                 break;
3322         }
3323
3324         if (passthrough && (encoded = ast_aoc_encode(decoded, &encoded_size, owner))) {
3325                 ast_queue_control_data(owner, AST_CONTROL_AOC, encoded, encoded_size);
3326         }
3327
3328         ast_aoc_manager_event(decoded, owner);
3329
3330         ast_aoc_destroy_decoded(decoded);
3331         ast_aoc_destroy_encoded(encoded);
3332 }
3333 #endif  /* defined(HAVE_PRI_AOC_EVENTS) */
3334
3335 #if defined(HAVE_PRI_AOC_EVENTS)
3336 /*!
3337  * \internal
3338  * \brief Generate AOC-E AST_CONTROL_AOC frame
3339  * \since 1.8
3340  *
3341  * \param aoc_e AOC-E event parameters.
3342  * \param owner Asterisk channel associated with the call.
3343  * \param passthrough indicating if this message should be queued on the ast channel
3344  *
3345  * \note Assumes the pri->lock is already obtained.
3346  * \note Assumes the sig_pri private is locked
3347  * \note Assumes the owner channel lock is already obtained.
3348  * \note owner channel may be NULL. In that case, generate event only
3349  *
3350  * \return Nothing
3351  */
3352 static void sig_pri_aoc_e_from_pri(const struct pri_subcmd_aoc_e *aoc_e, struct ast_channel *owner, int passthrough)
3353 {
3354         struct ast_aoc_decoded *decoded = NULL;
3355         struct ast_aoc_encoded *encoded = NULL;
3356         size_t encoded_size = 0;
3357         enum ast_aoc_charge_type type;
3358
3359         if (!aoc_e) {
3360                 return;
3361         }
3362
3363         switch (aoc_e->charge) {
3364         case PRI_AOC_DE_CHARGE_CURRENCY:
3365                 type = AST_AOC_CHARGE_CURRENCY;
3366                 break;
3367         case PRI_AOC_DE_CHARGE_UNITS:
3368                 type = AST_AOC_CHARGE_UNIT;
3369                 break;
3370         case PRI_AOC_DE_CHARGE_FREE:
3371                 type = AST_AOC_CHARGE_FREE;