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