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