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