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