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