7c7c9dfa44b4e8054d3825b3e11699f8ac8061f3
[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_log(LOG_WARNING, "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_CCSS)
1573 /*!
1574  * \internal
1575  * \brief Compare the CC agent private data by libpri cc_id.
1576  * \since 1.8
1577  *
1578  * \param obj pointer to the (user-defined part) of an object.
1579  * \param arg callback argument from ao2_callback()
1580  * \param flags flags from ao2_callback()
1581  *
1582  * \return values are a combination of enum _cb_results.
1583  */
1584 static int sig_pri_cc_agent_cmp_cc_id(void *obj, void *arg, int flags)
1585 {
1586         struct ast_cc_agent *agent_1 = obj;
1587         struct sig_pri_cc_agent_prv *agent_prv_1 = agent_1->private_data;
1588         struct sig_pri_cc_agent_prv *agent_prv_2 = arg;
1589
1590         return (agent_prv_1 && agent_prv_1->pri == agent_prv_2->pri
1591                 && agent_prv_1->cc_id == agent_prv_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1592 }
1593 #endif  /* defined(HAVE_PRI_CCSS) */
1594
1595 #if defined(HAVE_PRI_CCSS)
1596 /*!
1597  * \internal
1598  * \brief Find the CC agent by libpri cc_id.
1599  * \since 1.8
1600  *
1601  * \param pri sig_pri PRI control structure.
1602  * \param cc_id CC record ID to find.
1603  *
1604  * \note
1605  * Since agents are refcounted, and this function returns
1606  * a reference to the agent, it is imperative that you decrement
1607  * the refcount of the agent once you have finished using it.
1608  *
1609  * \retval agent on success.
1610  * \retval NULL not found.
1611  */
1612 static struct ast_cc_agent *sig_pri_find_cc_agent_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1613 {
1614         struct sig_pri_cc_agent_prv finder = {
1615                 .pri = pri,
1616                 .cc_id = cc_id,
1617         };
1618
1619         return ast_cc_agent_callback(0, sig_pri_cc_agent_cmp_cc_id, &finder,
1620                 sig_pri_cc_type_name);
1621 }
1622 #endif  /* defined(HAVE_PRI_CCSS) */
1623
1624 #if defined(HAVE_PRI_CCSS)
1625 /*!
1626  * \internal
1627  * \brief Compare the CC monitor instance by libpri cc_id.
1628  * \since 1.8
1629  *
1630  * \param obj pointer to the (user-defined part) of an object.
1631  * \param arg callback argument from ao2_callback()
1632  * \param flags flags from ao2_callback()
1633  *
1634  * \return values are a combination of enum _cb_results.
1635  */
1636 static int sig_pri_cc_monitor_cmp_cc_id(void *obj, void *arg, int flags)
1637 {
1638         struct sig_pri_cc_monitor_instance *monitor_1 = obj;
1639         struct sig_pri_cc_monitor_instance *monitor_2 = arg;
1640
1641         return (monitor_1->pri == monitor_2->pri
1642                 && monitor_1->cc_id == monitor_2->cc_id) ? CMP_MATCH | CMP_STOP : 0;
1643 }
1644 #endif  /* defined(HAVE_PRI_CCSS) */
1645
1646 #if defined(HAVE_PRI_CCSS)
1647 /*!
1648  * \internal
1649  * \brief Find the CC monitor instance by libpri cc_id.
1650  * \since 1.8
1651  *
1652  * \param pri sig_pri PRI control structure.
1653  * \param cc_id CC record ID to find.
1654  *
1655  * \note
1656  * Since monitor_instances are refcounted, and this function returns
1657  * a reference to the instance, it is imperative that you decrement
1658  * the refcount of the instance once you have finished using it.
1659  *
1660  * \retval monitor_instance on success.
1661  * \retval NULL not found.
1662  */
1663 static struct sig_pri_cc_monitor_instance *sig_pri_find_cc_monitor_by_cc_id(struct sig_pri_pri *pri, long cc_id)
1664 {
1665         struct sig_pri_cc_monitor_instance finder = {
1666                 .pri = pri,
1667                 .cc_id = cc_id,
1668         };
1669
1670         return ao2_callback(sig_pri_cc_monitors, 0, sig_pri_cc_monitor_cmp_cc_id, &finder);
1671 }
1672 #endif  /* defined(HAVE_PRI_CCSS) */
1673
1674 #if defined(HAVE_PRI_CCSS)
1675 /*!
1676  * \internal
1677  * \brief Destroy the given monitor instance.
1678  * \since 1.8
1679  *
1680  * \param data Monitor instance to destroy.
1681  *
1682  * \return Nothing
1683  */
1684 static void sig_pri_cc_monitor_instance_destroy(void *data)
1685 {
1686         struct sig_pri_cc_monitor_instance *monitor_instance = data;
1687
1688         if (monitor_instance->cc_id != -1) {
1689                 ast_mutex_lock(&monitor_instance->pri->lock);
1690                 pri_cc_cancel(monitor_instance->pri->pri, monitor_instance->cc_id);
1691                 ast_mutex_unlock(&monitor_instance->pri->lock);
1692         }
1693         monitor_instance->pri->calls->module_unref();
1694 }
1695 #endif  /* defined(HAVE_PRI_CCSS) */
1696
1697 #if defined(HAVE_PRI_CCSS)
1698 /*!
1699  * \internal
1700  * \brief Construct a new monitor instance.
1701  * \since 1.8
1702  *
1703  * \param core_id CC core ID.
1704  * \param pri sig_pri PRI control structure.
1705  * \param cc_id CC record ID.
1706  * \param device_name Name of device (Asterisk channel name less sequence number).
1707  *
1708  * \note
1709  * Since monitor_instances are refcounted, and this function returns
1710  * a reference to the instance, it is imperative that you decrement
1711  * the refcount of the instance once you have finished using it.
1712  *
1713  * \retval monitor_instance on success.
1714  * \retval NULL on error.
1715  */
1716 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)
1717 {
1718         struct sig_pri_cc_monitor_instance *monitor_instance;
1719
1720         if (!pri->calls->module_ref || !pri->calls->module_unref) {
1721                 return NULL;
1722         }
1723
1724         monitor_instance = ao2_alloc(sizeof(*monitor_instance) + strlen(device_name),
1725                 sig_pri_cc_monitor_instance_destroy);
1726         if (!monitor_instance) {
1727                 return NULL;
1728         }
1729
1730         monitor_instance->cc_id = cc_id;
1731         monitor_instance->pri = pri;
1732         monitor_instance->core_id = core_id;
1733         strcpy(monitor_instance->name, device_name);
1734
1735         pri->calls->module_ref();
1736
1737         ao2_link(sig_pri_cc_monitors, monitor_instance);
1738         return monitor_instance;
1739 }
1740 #endif  /* defined(HAVE_PRI_CCSS) */
1741
1742 #if defined(HAVE_PRI_CCSS)
1743 /*!
1744  * \internal
1745  * \brief Announce to the CC core that protocol CC monitor is available for this call.
1746  * \since 1.8
1747  *
1748  * \param pri sig_pri PRI control structure.
1749  * \param chanpos Channel position in the span.
1750  * \param cc_id CC record ID.
1751  * \param service CCBS/CCNR indication.
1752  *
1753  * \note Assumes the pri->lock is already obtained.
1754  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1755  * \note Assumes the sig_pri_lock_owner(pri, chanpos) is already obtained.
1756  *
1757  * \retval 0 on success.
1758  * \retval -1 on error.
1759  */
1760 static int sig_pri_cc_available(struct sig_pri_pri *pri, int chanpos, long cc_id, enum ast_cc_service_type service)
1761 {
1762         struct sig_pri_chan *pvt;
1763         struct ast_cc_config_params *cc_params;
1764         struct sig_pri_cc_monitor_instance *monitor;
1765         enum ast_cc_monitor_policies monitor_policy;
1766         int core_id;
1767         int res;
1768         char device_name[AST_CHANNEL_NAME];
1769         char dialstring[AST_CHANNEL_NAME];
1770
1771         pvt = pri->pvts[chanpos];
1772
1773         core_id = ast_cc_get_current_core_id(pvt->owner);
1774         if (core_id == -1) {
1775                 return -1;
1776         }
1777
1778         cc_params = ast_channel_get_cc_config_params(pvt->owner);
1779         if (!cc_params) {
1780                 return -1;
1781         }
1782
1783         res = -1;
1784         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1785         switch (monitor_policy) {
1786         case AST_CC_MONITOR_NEVER:
1787                 /* CCSS is not enabled. */
1788                 break;
1789         case AST_CC_MONITOR_NATIVE:
1790         case AST_CC_MONITOR_ALWAYS:
1791                 /*
1792                  * If it is AST_CC_MONITOR_ALWAYS and native fails we will attempt the fallback
1793                  * later in the call to sig_pri_cc_generic_check().
1794                  */
1795                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
1796                 sig_pri_make_cc_dialstring(pvt, dialstring, sizeof(dialstring));
1797                 monitor = sig_pri_cc_monitor_instance_init(core_id, pri, cc_id, device_name);
1798                 if (!monitor) {
1799                         break;
1800                 }
1801                 res = ast_queue_cc_frame(pvt->owner, sig_pri_cc_type_name, dialstring, service,
1802                         monitor);
1803                 if (res) {
1804                         monitor->cc_id = -1;
1805                         ao2_unlink(sig_pri_cc_monitors, monitor);
1806                         ao2_ref(monitor, -1);
1807                 }
1808                 break;
1809         case AST_CC_MONITOR_GENERIC:
1810                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE,
1811                         sig_pri_get_orig_dialstring(pvt), service, NULL);
1812                 /* Say it failed to force caller to cancel native CC. */
1813                 break;
1814         }
1815         return res;
1816 }
1817 #endif  /* defined(HAVE_PRI_CCSS) */
1818
1819 /*!
1820  * \internal
1821  * \brief Check if generic CC monitor is needed and request it.
1822  * \since 1.8
1823  *
1824  * \param pri sig_pri PRI control structure.
1825  * \param chanpos Channel position in the span.
1826  * \param service CCBS/CCNR indication.
1827  *
1828  * \note Assumes the pri->lock is already obtained.
1829  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
1830  *
1831  * \return Nothing
1832  */
1833 static void sig_pri_cc_generic_check(struct sig_pri_pri *pri, int chanpos, enum ast_cc_service_type service)
1834 {
1835         struct ast_channel *owner;
1836         struct ast_cc_config_params *cc_params;
1837 #if defined(HAVE_PRI_CCSS)
1838         struct ast_cc_monitor *monitor;
1839         char device_name[AST_CHANNEL_NAME];
1840 #endif  /* defined(HAVE_PRI_CCSS) */
1841         enum ast_cc_monitor_policies monitor_policy;
1842         int core_id;
1843
1844         if (!pri->pvts[chanpos]->outgoing) {
1845                 /* This is not an outgoing call so it cannot be CC monitor. */
1846                 return;
1847         }
1848
1849         sig_pri_lock_owner(pri, chanpos);
1850         owner = pri->pvts[chanpos]->owner;
1851         if (!owner) {
1852                 return;
1853         }
1854         core_id = ast_cc_get_current_core_id(owner);
1855         if (core_id == -1) {
1856                 /* No CC core setup */
1857                 goto done;
1858         }
1859
1860         cc_params = ast_channel_get_cc_config_params(owner);
1861         if (!cc_params) {
1862                 /* Could not get CC config parameters. */
1863                 goto done;
1864         }
1865
1866 #if defined(HAVE_PRI_CCSS)
1867         ast_channel_get_device_name(owner, device_name, sizeof(device_name));
1868         monitor = ast_cc_get_monitor_by_recall_core_id(core_id, device_name);
1869         if (monitor) {
1870                 /* CC monitor is already present so no need for generic CC. */
1871                 ao2_ref(monitor, -1);
1872                 goto done;
1873         }
1874 #endif  /* defined(HAVE_PRI_CCSS) */
1875
1876         monitor_policy = ast_get_cc_monitor_policy(cc_params);
1877         switch (monitor_policy) {
1878         case AST_CC_MONITOR_NEVER:
1879                 /* CCSS is not enabled. */
1880                 break;
1881         case AST_CC_MONITOR_NATIVE:
1882                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
1883                         /* Request generic CC monitor. */
1884                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1885                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1886                 }
1887                 break;
1888         case AST_CC_MONITOR_ALWAYS:
1889                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype != PRI_NETWORK) {
1890                         /*
1891                          * Cannot monitor PTMP TE side since this is not defined.
1892                          * We are playing the roll of a phone in this case and
1893                          * a phone cannot monitor a party over the network without
1894                          * protocol help.
1895                          */
1896                         break;
1897                 }
1898                 /*
1899                  * We are either falling back or this is a PTMP NT span.
1900                  * Request generic CC monitor.
1901                  */
1902                 ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1903                         sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1904                 break;
1905         case AST_CC_MONITOR_GENERIC:
1906                 if (pri->sig == SIG_BRI_PTMP && pri->nodetype == PRI_NETWORK) {
1907                         /* Request generic CC monitor. */
1908                         ast_queue_cc_frame(owner, AST_CC_GENERIC_MONITOR_TYPE,
1909                                 sig_pri_get_orig_dialstring(pri->pvts[chanpos]), service, NULL);
1910                 }
1911                 break;
1912         }
1913
1914 done:
1915         ast_channel_unlock(owner);
1916 }
1917
1918 #if defined(HAVE_PRI_CCSS)
1919 /*!
1920  * \internal
1921  * \brief The CC link canceled the CC instance.
1922  * \since 1.8
1923  *
1924  * \param pri sig_pri PRI control structure.
1925  * \param cc_id CC record ID.
1926  * \param is_agent TRUE if the cc_id is for an agent.
1927  *
1928  * \return Nothing
1929  */
1930 static void sig_pri_cc_link_canceled(struct sig_pri_pri *pri, long cc_id, int is_agent)
1931 {
1932         if (is_agent) {
1933                 struct ast_cc_agent *agent;
1934
1935                 agent = sig_pri_find_cc_agent_by_cc_id(pri, cc_id);
1936                 if (!agent) {
1937                         return;
1938                 }
1939                 ast_cc_failed(agent->core_id, "%s agent got canceled by link",
1940                         sig_pri_cc_type_name);
1941                 ao2_ref(agent, -1);
1942         } else {
1943                 struct sig_pri_cc_monitor_instance *monitor;
1944
1945                 monitor = sig_pri_find_cc_monitor_by_cc_id(pri, cc_id);
1946                 if (!monitor) {
1947                         return;
1948                 }
1949                 monitor->cc_id = -1;
1950                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
1951                         "%s monitor got canceled by link", sig_pri_cc_type_name);
1952                 ao2_ref(monitor, -1);
1953         }
1954 }
1955 #endif  /* defined(HAVE_PRI_CCSS) */
1956
1957 /*!
1958  * \internal
1959  * \brief TRUE if PRI event came in on a CIS call.
1960  * \since 1.8
1961  *
1962  * \param channel PRI encoded span/channel
1963  *
1964  * \retval non-zero if CIS call.
1965  */
1966 static int sig_pri_is_cis_call(int channel)
1967 {
1968         return channel != -1 && (channel & PRI_CIS_CALL);
1969 }
1970
1971 /*!
1972  * \internal
1973  * \brief Handle the CIS associated PRI subcommand events.
1974  * \since 1.8
1975  *
1976  * \param pri sig_pri PRI control structure.
1977  * \param event_id PRI event id
1978  * \param subcmds Subcommands to process if any. (Could be NULL).
1979  * \param call_rsp libpri opaque call structure to send any responses toward.
1980  * Could be NULL either because it is not available or the call is for the
1981  * dummy call reference.  However, this should not be NULL in the cases that
1982  * need to use the pointer to send a response message back.
1983  *
1984  * \note Assumes the pri->lock is already obtained.
1985  *
1986  * \return Nothing
1987  */
1988 static void sig_pri_handle_cis_subcmds(struct sig_pri_pri *pri, int event_id,
1989         const struct pri_subcommands *subcmds, q931_call *call_rsp)
1990 {
1991         int index;
1992 #if defined(HAVE_PRI_CCSS)
1993         struct ast_cc_agent *agent;
1994         struct sig_pri_cc_agent_prv *agent_prv;
1995         struct sig_pri_cc_monitor_instance *monitor;
1996 #endif  /* defined(HAVE_PRI_CCSS) */
1997
1998         if (!subcmds) {
1999                 return;
2000         }
2001         for (index = 0; index < subcmds->counter_subcmd; ++index) {
2002                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
2003
2004                 switch (subcmd->cmd) {
2005 #if defined(STATUS_REQUEST_PLACE_HOLDER)
2006                 case PRI_SUBCMD_STATUS_REQ:
2007                 case PRI_SUBCMD_STATUS_REQ_RSP:
2008                         /* Ignore for now. */
2009                         break;
2010 #endif  /* defined(STATUS_REQUEST_PLACE_HOLDER) */
2011 #if defined(HAVE_PRI_CCSS)
2012                 case PRI_SUBCMD_CC_REQ:
2013                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_request.cc_id);
2014                         if (!agent) {
2015                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
2016                                 break;
2017                         }
2018                         if (!ast_cc_request_is_within_limits()) {
2019                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
2020                                         5/* queue_full */)) {
2021                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
2022                                 }
2023                                 ast_cc_failed(agent->core_id, "%s agent system CC queue full",
2024                                         sig_pri_cc_type_name);
2025                                 ao2_ref(agent, -1);
2026                                 break;
2027                         }
2028                         agent_prv = agent->private_data;
2029                         agent_prv->cc_request_response_pending = 1;
2030                         if (ast_cc_agent_accept_request(agent->core_id,
2031                                 "%s caller accepted CC offer.", sig_pri_cc_type_name)) {
2032                                 agent_prv->cc_request_response_pending = 0;
2033                                 if (pri_cc_req_rsp(pri->pri, subcmd->u.cc_request.cc_id,
2034                                         2/* short_term_denial */)) {
2035                                         pri_cc_cancel(pri->pri, subcmd->u.cc_request.cc_id);
2036                                 }
2037                                 ast_cc_failed(agent->core_id, "%s agent CC core request accept failed",
2038                                         sig_pri_cc_type_name);
2039                         }
2040                         ao2_ref(agent, -1);
2041                         break;
2042 #endif  /* defined(HAVE_PRI_CCSS) */
2043 #if defined(HAVE_PRI_CCSS)
2044                 case PRI_SUBCMD_CC_REQ_RSP:
2045                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2046                                 subcmd->u.cc_request_rsp.cc_id);
2047                         if (!monitor) {
2048                                 pri_cc_cancel(pri->pri, subcmd->u.cc_request_rsp.cc_id);
2049                                 break;
2050                         }
2051                         switch (subcmd->u.cc_request_rsp.status) {
2052                         case 0:/* success */
2053                                 ast_cc_monitor_request_acked(monitor->core_id,
2054                                         "%s far end accepted CC request", sig_pri_cc_type_name);
2055                                 break;
2056                         case 1:/* timeout */
2057                                 ast_verb(2, "core_id:%d %s CC request timeout\n", monitor->core_id,
2058                                         sig_pri_cc_type_name);
2059                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2060                                         "%s CC request timeout", sig_pri_cc_type_name);
2061                                 break;
2062                         case 2:/* error */
2063                                 ast_verb(2, "core_id:%d %s CC request error: %s\n", monitor->core_id,
2064                                         sig_pri_cc_type_name,
2065                                         pri_facility_error2str(subcmd->u.cc_request_rsp.fail_code));
2066                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2067                                         "%s CC request error", sig_pri_cc_type_name);
2068                                 break;
2069                         case 3:/* reject */
2070                                 ast_verb(2, "core_id:%d %s CC request reject: %s\n", monitor->core_id,
2071                                         sig_pri_cc_type_name,
2072                                         pri_facility_reject2str(subcmd->u.cc_request_rsp.fail_code));
2073                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2074                                         "%s CC request reject", sig_pri_cc_type_name);
2075                                 break;
2076                         default:
2077                                 ast_verb(2, "core_id:%d %s CC request unknown status %d\n",
2078                                         monitor->core_id, sig_pri_cc_type_name,
2079                                         subcmd->u.cc_request_rsp.status);
2080                                 ast_cc_monitor_failed(monitor->core_id, monitor->name,
2081                                         "%s CC request unknown status", sig_pri_cc_type_name);
2082                                 break;
2083                         }
2084                         ao2_ref(monitor, -1);
2085                         break;
2086 #endif  /* defined(HAVE_PRI_CCSS) */
2087 #if defined(HAVE_PRI_CCSS)
2088                 case PRI_SUBCMD_CC_REMOTE_USER_FREE:
2089                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2090                                 subcmd->u.cc_remote_user_free.cc_id);
2091                         if (!monitor) {
2092                                 pri_cc_cancel(pri->pri, subcmd->u.cc_remote_user_free.cc_id);
2093                                 break;
2094                         }
2095                         ast_cc_monitor_callee_available(monitor->core_id,
2096                                 "%s callee has become available", sig_pri_cc_type_name);
2097                         ao2_ref(monitor, -1);
2098                         break;
2099 #endif  /* defined(HAVE_PRI_CCSS) */
2100 #if defined(HAVE_PRI_CCSS)
2101                 case PRI_SUBCMD_CC_B_FREE:
2102                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2103                                 subcmd->u.cc_b_free.cc_id);
2104                         if (!monitor) {
2105                                 pri_cc_cancel(pri->pri, subcmd->u.cc_b_free.cc_id);
2106                                 break;
2107                         }
2108                         ast_cc_monitor_party_b_free(monitor->core_id);
2109                         ao2_ref(monitor, -1);
2110                         break;
2111 #endif  /* defined(HAVE_PRI_CCSS) */
2112 #if defined(HAVE_PRI_CCSS)
2113                 case PRI_SUBCMD_CC_STATUS_REQ:
2114                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2115                                 subcmd->u.cc_status_req.cc_id);
2116                         if (!monitor) {
2117                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req.cc_id);
2118                                 break;
2119                         }
2120                         ast_cc_monitor_status_request(monitor->core_id);
2121                         ao2_ref(monitor, -1);
2122                         break;
2123 #endif  /* defined(HAVE_PRI_CCSS) */
2124 #if defined(HAVE_PRI_CCSS)
2125                 case PRI_SUBCMD_CC_STATUS_REQ_RSP:
2126                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status_req_rsp.cc_id);
2127                         if (!agent) {
2128                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status_req_rsp.cc_id);
2129                                 break;
2130                         }
2131                         ast_cc_agent_status_response(agent->core_id,
2132                                 subcmd->u.cc_status_req_rsp.status ? AST_DEVICE_INUSE
2133                                 : AST_DEVICE_NOT_INUSE);
2134                         ao2_ref(agent, -1);
2135                         break;
2136 #endif  /* defined(HAVE_PRI_CCSS) */
2137 #if defined(HAVE_PRI_CCSS)
2138                 case PRI_SUBCMD_CC_STATUS:
2139                         agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_status.cc_id);
2140                         if (!agent) {
2141                                 pri_cc_cancel(pri->pri, subcmd->u.cc_status.cc_id);
2142                                 break;
2143                         }
2144                         if (subcmd->u.cc_status.status) {
2145                                 ast_cc_agent_caller_busy(agent->core_id, "%s agent caller is busy",
2146                                         sig_pri_cc_type_name);
2147                         } else {
2148                                 ast_cc_agent_caller_available(agent->core_id,
2149                                         "%s agent caller is available", sig_pri_cc_type_name);
2150                         }
2151                         ao2_ref(agent, -1);
2152                         break;
2153 #endif  /* defined(HAVE_PRI_CCSS) */
2154 #if defined(HAVE_PRI_CCSS)
2155                 case PRI_SUBCMD_CC_CANCEL:
2156                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
2157                                 subcmd->u.cc_cancel.is_agent);
2158                         break;
2159 #endif  /* defined(HAVE_PRI_CCSS) */
2160 #if defined(HAVE_PRI_CCSS)
2161                 case PRI_SUBCMD_CC_STOP_ALERTING:
2162                         monitor = sig_pri_find_cc_monitor_by_cc_id(pri,
2163                                 subcmd->u.cc_stop_alerting.cc_id);
2164                         if (!monitor) {
2165                                 pri_cc_cancel(pri->pri, subcmd->u.cc_stop_alerting.cc_id);
2166                                 break;
2167                         }
2168                         ast_cc_monitor_stop_ringing(monitor->core_id);
2169                         ao2_ref(monitor, -1);
2170                         break;
2171 #endif  /* defined(HAVE_PRI_CCSS) */
2172                 default:
2173                         ast_debug(2,
2174                                 "Unknown CIS subcommand(%d) in %s event on span %d.\n",
2175                                 subcmd->cmd, pri_event2str(event_id), pri->span);
2176                         break;
2177                 }
2178         }
2179 }
2180
2181 /*!
2182  * \internal
2183  * \brief Handle the call associated PRI subcommand events.
2184  * \since 1.8
2185  *
2186  * \param pri sig_pri PRI control structure.
2187  * \param chanpos Channel position in the span.
2188  * \param event_id PRI event id
2189  * \param channel PRI encoded span/channel
2190  * \param subcmds Subcommands to process if any. (Could be NULL).
2191  * \param call_rsp libpri opaque call structure to send any responses toward.
2192  * Could be NULL either because it is not available or the call is for the
2193  * dummy call reference.  However, this should not be NULL in the cases that
2194  * need to use the pointer to send a response message back.
2195  *
2196  * \note Assumes the pri->lock is already obtained.
2197  * \note Assumes the sig_pri_lock_private(pri->pvts[chanpos]) is already obtained.
2198  *
2199  * \return Nothing
2200  */
2201 static void sig_pri_handle_subcmds(struct sig_pri_pri *pri, int chanpos, int event_id,
2202         int channel, const struct pri_subcommands *subcmds, q931_call *call_rsp)
2203 {
2204         int index;
2205         struct ast_channel *owner;
2206         struct ast_party_redirecting ast_redirecting;
2207
2208         if (!subcmds) {
2209                 return;
2210         }
2211         for (index = 0; index < subcmds->counter_subcmd; ++index) {
2212                 const struct pri_subcommand *subcmd = &subcmds->subcmd[index];
2213
2214                 switch (subcmd->cmd) {
2215                 case PRI_SUBCMD_CONNECTED_LINE:
2216                         sig_pri_lock_owner(pri, chanpos);
2217                         owner = pri->pvts[chanpos]->owner;
2218                         if (owner) {
2219                                 struct ast_party_connected_line ast_connected;
2220                                 int caller_id_update;
2221
2222                                 /* Extract the connected line information */
2223                                 ast_party_connected_line_init(&ast_connected);
2224                                 sig_pri_party_id_convert(&ast_connected.id, &subcmd->u.connected_line.id,
2225                                         pri);
2226
2227                                 caller_id_update = 0;
2228                                 if (ast_connected.id.name) {
2229                                         /* Save name for Caller-ID update */
2230                                         ast_copy_string(pri->pvts[chanpos]->cid_name,
2231                                                 ast_connected.id.name, sizeof(pri->pvts[chanpos]->cid_name));
2232                                         caller_id_update = 1;
2233                                 }
2234                                 if (ast_connected.id.number) {
2235                                         /* Save number for Caller-ID update */
2236                                         ast_copy_string(pri->pvts[chanpos]->cid_num, ast_connected.id.number,
2237                                                 sizeof(pri->pvts[chanpos]->cid_num));
2238                                         pri->pvts[chanpos]->cid_ton = ast_connected.id.number_type;
2239                                         caller_id_update = 1;
2240                                 } else {
2241                                         ast_connected.id.number = ast_strdup("");
2242                                 }
2243                                 ast_connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2244
2245                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
2246 #if defined(HAVE_PRI_SUBADDR)
2247                                 if (ast_connected.id.subaddress.valid) {
2248                                         ast_party_subaddress_set(&owner->cid.subaddress,
2249                                                 &ast_connected.id.subaddress);
2250                                         if (ast_connected.id.subaddress.str) {
2251                                                 ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
2252                                                         ast_connected.id.subaddress.str,
2253                                                         sizeof(pri->pvts[chanpos]->cid_subaddr));
2254                                         }
2255                                 }
2256 #endif  /* defined(HAVE_PRI_SUBADDR) */
2257                                 if (caller_id_update) {
2258                                         pri->pvts[chanpos]->callingpres =
2259                                                 ast_connected.id.number_presentation;
2260                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
2261                                         ast_set_callerid(owner, S_OR(ast_connected.id.number, NULL),
2262                                                 S_OR(ast_connected.id.name, NULL),
2263                                                 S_OR(ast_connected.id.number, NULL));
2264                                 }
2265
2266                                 /* Update the connected line information on the other channel */
2267                                 if (event_id != PRI_EVENT_RING) {
2268                                         /* This connected_line update was not from a SETUP message. */
2269                                         ast_channel_queue_connected_line_update(owner, &ast_connected);
2270                                 }
2271
2272                                 ast_party_connected_line_free(&ast_connected);
2273                                 ast_channel_unlock(owner);
2274                         }
2275                         break;
2276                 case PRI_SUBCMD_REDIRECTING:
2277                         sig_pri_lock_owner(pri, chanpos);
2278                         owner = pri->pvts[chanpos]->owner;
2279                         if (owner) {
2280                                 sig_pri_redirecting_convert(&ast_redirecting, &subcmd->u.redirecting,
2281                                         &owner->redirecting, pri);
2282
2283 /*! \todo XXX Original called data can be put in a channel data store that is inherited. */
2284
2285                                 ast_channel_set_redirecting(owner, &ast_redirecting);
2286                                 if (event_id != PRI_EVENT_RING) {
2287                                         /* This redirection was not from a SETUP message. */
2288                                         ast_channel_queue_redirecting_update(owner, &ast_redirecting);
2289                                 }
2290                                 ast_party_redirecting_free(&ast_redirecting);
2291
2292                                 ast_channel_unlock(owner);
2293                         }
2294                         break;
2295 #if defined(HAVE_PRI_CALL_REROUTING)
2296                 case PRI_SUBCMD_REROUTING:
2297                         sig_pri_lock_owner(pri, chanpos);
2298                         owner = pri->pvts[chanpos]->owner;
2299                         if (owner) {
2300                                 struct pri_party_redirecting pri_deflection;
2301
2302                                 if (!call_rsp) {
2303                                         ast_channel_unlock(owner);
2304                                         ast_log(LOG_WARNING,
2305                                                 "CallRerouting/CallDeflection to '%s' without call!\n",
2306                                                 subcmd->u.rerouting.deflection.to.number.str);
2307                                         break;
2308                                 }
2309
2310                                 pri_deflection = subcmd->u.rerouting.deflection;
2311
2312                                 ast_string_field_set(owner, call_forward, pri_deflection.to.number.str);
2313
2314                                 /* Adjust the deflecting to number based upon the subscription option. */
2315                                 switch (subcmd->u.rerouting.subscription_option) {
2316                                 case 0: /* noNotification */
2317                                 case 1: /* notificationWithoutDivertedToNr */
2318                                         /* Delete the number because the far end is not supposed to see it. */
2319                                         pri_deflection.to.number.presentation =
2320                                                 PRI_PRES_RESTRICTED | PRI_PRES_USER_NUMBER_UNSCREENED;
2321                                         pri_deflection.to.number.plan =
2322                                                 (PRI_TON_UNKNOWN << 4) | PRI_NPI_E163_E164;
2323                                         pri_deflection.to.number.str[0] = '\0';
2324                                         break;
2325                                 case 2: /* notificationWithDivertedToNr */
2326                                         break;
2327                                 case 3: /* notApplicable */
2328                                 default:
2329                                         break;
2330                                 }
2331                                 sig_pri_redirecting_convert(&ast_redirecting, &pri_deflection,
2332                                         &owner->redirecting, pri);
2333                                 ast_channel_set_redirecting(owner, &ast_redirecting);
2334                                 ast_party_redirecting_free(&ast_redirecting);
2335
2336                                 /*
2337                                  * Send back positive ACK to CallRerouting/CallDeflection.
2338                                  *
2339                                  * Note:  This call will be hungup by the dial application when
2340                                  * it processes the call_forward string set above.
2341                                  */
2342                                 pri_rerouting_rsp(pri->pri, call_rsp, subcmd->u.rerouting.invoke_id,
2343                                         PRI_REROUTING_RSP_OK_CLEAR);
2344
2345                                 /* This line is BUSY to further attempts by this dialing attempt. */
2346                                 ast_queue_control(owner, AST_CONTROL_BUSY);
2347
2348                                 ast_channel_unlock(owner);
2349                         }
2350                         break;
2351 #endif  /* defined(HAVE_PRI_CALL_REROUTING) */
2352 #if defined(HAVE_PRI_CCSS)
2353                 case PRI_SUBCMD_CC_AVAILABLE:
2354                         sig_pri_lock_owner(pri, chanpos);
2355                         owner = pri->pvts[chanpos]->owner;
2356                         if (owner) {
2357                                 enum ast_cc_service_type service;
2358
2359                                 switch (event_id) {
2360                                 case PRI_EVENT_RINGING:
2361                                         service = AST_CC_CCNR;
2362                                         break;
2363                                 case PRI_EVENT_HANGUP_REQ:
2364                                         /* We will assume that the cause was busy/congestion. */
2365                                         service = AST_CC_CCBS;
2366                                         break;
2367                                 default:
2368                                         service = AST_CC_NONE;
2369                                         break;
2370                                 }
2371                                 if (service == AST_CC_NONE
2372                                         || sig_pri_cc_available(pri, chanpos, subcmd->u.cc_available.cc_id,
2373                                         service)) {
2374                                         pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
2375                                 }
2376                                 ast_channel_unlock(owner);
2377                         } else {
2378                                 /* No asterisk channel. */
2379                                 pri_cc_cancel(pri->pri, subcmd->u.cc_available.cc_id);
2380                         }
2381                         break;
2382 #endif  /* defined(HAVE_PRI_CCSS) */
2383 #if defined(HAVE_PRI_CCSS)
2384                 case PRI_SUBCMD_CC_CALL:
2385                         sig_pri_lock_owner(pri, chanpos);
2386                         owner = pri->pvts[chanpos]->owner;
2387                         if (owner) {
2388                                 struct ast_cc_agent *agent;
2389
2390                                 agent = sig_pri_find_cc_agent_by_cc_id(pri, subcmd->u.cc_call.cc_id);
2391                                 if (agent) {
2392                                         ast_setup_cc_recall_datastore(owner, agent->core_id);
2393                                         ast_cc_agent_set_interfaces_chanvar(owner);
2394                                         ast_cc_agent_recalling(agent->core_id,
2395                                                 "%s caller is attempting recall", sig_pri_cc_type_name);
2396                                         ao2_ref(agent, -1);
2397                                 }
2398
2399                                 ast_channel_unlock(owner);
2400                         }
2401                         break;
2402 #endif  /* defined(HAVE_PRI_CCSS) */
2403 #if defined(HAVE_PRI_CCSS)
2404                 case PRI_SUBCMD_CC_CANCEL:
2405                         sig_pri_cc_link_canceled(pri, subcmd->u.cc_cancel.cc_id,
2406                                 subcmd->u.cc_cancel.is_agent);
2407                         break;
2408 #endif  /* defined(HAVE_PRI_CCSS) */
2409                 default:
2410                         ast_debug(2,
2411                                 "Unknown call subcommand(%d) in %s event on channel %d/%d on span %d.\n",
2412                                 subcmd->cmd, pri_event2str(event_id), PRI_SPAN(channel),
2413                                 PRI_CHANNEL(channel), pri->span);
2414                         break;
2415                 }
2416         }
2417 }
2418
2419 #if defined(HAVE_PRI_CALL_HOLD)
2420 /*!
2421  * \internal
2422  * \brief Attempt to transfer the active call to the held call.
2423  * \since 1.8
2424  *
2425  * \param pri sig_pri PRI control structure.
2426  * \param active_call Active call to transfer.
2427  * \param held_call Held call to transfer.
2428  *
2429  * \note Assumes the pri->lock is already obtained.
2430  *
2431  * \retval 0 on success.
2432  * \retval -1 on error.
2433  */
2434 static int sig_pri_attempt_transfer(struct sig_pri_pri *pri, q931_call *active_call, q931_call *held_call)
2435 {
2436         int retval;
2437         int active_chanpos;
2438         int held_chanpos;
2439         struct ast_channel *active_ast;
2440         struct ast_channel *held_ast;
2441         struct ast_channel *bridged;
2442
2443         active_chanpos = pri_find_pri_call(pri, active_call);
2444         held_chanpos = pri_find_pri_call(pri, held_call);
2445         if (active_chanpos < 0 || held_chanpos < 0) {
2446                 return -1;
2447         }
2448
2449         sig_pri_lock_private(pri->pvts[active_chanpos]);
2450         sig_pri_lock_private(pri->pvts[held_chanpos]);
2451         sig_pri_lock_owner(pri, active_chanpos);
2452         sig_pri_lock_owner(pri, held_chanpos);
2453
2454         active_ast = pri->pvts[active_chanpos]->owner;
2455         held_ast = pri->pvts[held_chanpos]->owner;
2456         if (!active_ast || !held_ast) {
2457                 if (active_ast) {
2458                         ast_channel_unlock(active_ast);
2459                 }
2460                 if (held_ast) {
2461                         ast_channel_unlock(held_ast);
2462                 }
2463                 sig_pri_unlock_private(pri->pvts[active_chanpos]);
2464                 sig_pri_unlock_private(pri->pvts[held_chanpos]);
2465                 return -1;
2466         }
2467
2468         bridged = ast_bridged_channel(held_ast);
2469         if (bridged) {
2470                 ast_queue_control(held_ast, AST_CONTROL_UNHOLD);
2471
2472                 ast_verb(3, "TRANSFERRING %s to %s\n", held_ast->name, active_ast->name);
2473                 retval = ast_channel_masquerade(active_ast, bridged);
2474         } else {
2475                 /*
2476                  * Could not transfer.  Held channel is not bridged anymore.
2477                  * Held party probably got tired of waiting and hung up.
2478                  */
2479                 retval = -1;
2480         }
2481
2482         ast_channel_unlock(active_ast);
2483         ast_channel_unlock(held_ast);
2484         sig_pri_unlock_private(pri->pvts[active_chanpos]);
2485         sig_pri_unlock_private(pri->pvts[held_chanpos]);
2486
2487         return retval;
2488 }
2489 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2490
2491 #if defined(HAVE_PRI_CALL_HOLD)
2492 /*!
2493  * \internal
2494  * \brief Handle the hold event from libpri.
2495  * \since 1.8
2496  *
2497  * \param pri sig_pri PRI control structure.
2498  * \param ev Hold event received.
2499  *
2500  * \note Assumes the pri->lock is already obtained.
2501  *
2502  * \retval 0 on success.
2503  * \retval -1 on error.
2504  */
2505 static int sig_pri_handle_hold(struct sig_pri_pri *pri, pri_event *ev)
2506 {
2507         int retval;
2508         int chanpos_old;
2509         int chanpos_new;
2510         struct ast_channel *bridged;
2511         struct ast_channel *owner;
2512
2513         chanpos_old = pri_find_principle(pri, ev->hold.channel, ev->hold.call);
2514         if (chanpos_old < 0) {
2515                 ast_log(LOG_WARNING,
2516                         "Received HOLD on unconfigured channel %d/%d span %d\n",
2517                         PRI_SPAN(ev->hold.channel), PRI_CHANNEL(ev->hold.channel), pri->span);
2518                 return -1;
2519         }
2520         if (pri->pvts[chanpos_old]->no_b_channel) {
2521                 /* Call is already on hold or is call waiting call. */
2522                 return -1;
2523         }
2524
2525         sig_pri_lock_private(pri->pvts[chanpos_old]);
2526         sig_pri_lock_owner(pri, chanpos_old);
2527         owner = pri->pvts[chanpos_old]->owner;
2528         if (!owner) {
2529                 retval = -1;
2530                 goto done_with_private;
2531         }
2532         bridged = ast_bridged_channel(owner);
2533         if (!bridged) {
2534                 /* Cannot hold a call that is not bridged. */
2535                 retval = -1;
2536                 goto done_with_owner;
2537         }
2538         chanpos_new = pri_find_empty_nobch(pri);
2539         if (chanpos_new < 0) {
2540                 /* No hold channel available. */
2541                 retval = -1;
2542                 goto done_with_owner;
2543         }
2544         sig_pri_handle_subcmds(pri, chanpos_old, ev->e, ev->hold.channel, ev->hold.subcmds,
2545                 ev->hold.call);
2546         chanpos_new = pri_fixup_principle(pri, chanpos_new, ev->hold.call);
2547         if (chanpos_new < 0) {
2548                 /* Should never happen. */
2549                 retval = -1;
2550         } else {
2551                 struct ast_frame f = { AST_FRAME_CONTROL, };
2552
2553                 /*
2554                  * Things are in an odd state here so we cannot use pri_queue_control().
2555                  * However, we already have the owner lock so we can simply queue the frame.
2556                  */
2557                 f.subclass.integer = AST_CONTROL_HOLD;
2558                 ast_queue_frame(owner, &f);
2559
2560                 sig_pri_span_devstate_changed(pri);
2561                 retval = 0;
2562         }
2563
2564 done_with_owner:;
2565         ast_channel_unlock(owner);
2566 done_with_private:;
2567         sig_pri_unlock_private(pri->pvts[chanpos_old]);
2568
2569         return retval;
2570 }
2571 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2572
2573 #if defined(HAVE_PRI_CALL_HOLD)
2574 /*!
2575  * \internal
2576  * \brief Handle the retrieve event from libpri.
2577  * \since 1.8
2578  *
2579  * \param pri sig_pri PRI control structure.
2580  * \param ev Retrieve event received.
2581  *
2582  * \note Assumes the pri->lock is already obtained.
2583  *
2584  * \return Nothing
2585  */
2586 static void sig_pri_handle_retrieve(struct sig_pri_pri *pri, pri_event *ev)
2587 {
2588         int chanpos;
2589
2590         if (!(ev->retrieve.channel & PRI_HELD_CALL)
2591                 || pri_find_principle(pri, ev->retrieve.channel, ev->retrieve.call) < 0) {
2592                 /* The call is not currently held. */
2593                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2594                         PRI_CAUSE_RESOURCE_UNAVAIL_UNSPECIFIED);
2595                 return;
2596         }
2597         if (PRI_CHANNEL(ev->retrieve.channel) == 0xFF) {
2598                 chanpos = pri_find_empty_chan(pri, 1);
2599         } else {
2600                 chanpos = pri_find_principle(pri,
2601                         ev->retrieve.channel & ~PRI_HELD_CALL, ev->retrieve.call);
2602                 if (ev->retrieve.flexible
2603                         && (chanpos < 0 || pri->pvts[chanpos]->owner)) {
2604                         /*
2605                          * Channel selection is flexible and the requested channel
2606                          * is bad or already in use.  Pick another channel.
2607                          */
2608                         chanpos = pri_find_empty_chan(pri, 1);
2609                 }
2610         }
2611         if (chanpos < 0) {
2612                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2613                         ev->retrieve.flexible ? PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION
2614                         : PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
2615                 return;
2616         }
2617         chanpos = pri_fixup_principle(pri, chanpos, ev->retrieve.call);
2618         if (chanpos < 0) {
2619                 /* Channel is already in use. */
2620                 pri_retrieve_rej(pri->pri, ev->retrieve.call,
2621                         PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
2622                 return;
2623         }
2624         sig_pri_lock_private(pri->pvts[chanpos]);
2625         sig_pri_handle_subcmds(pri, chanpos, ev->e, ev->retrieve.channel,
2626                 ev->retrieve.subcmds, ev->retrieve.call);
2627         pri_queue_control(pri, chanpos, AST_CONTROL_UNHOLD);
2628         sig_pri_unlock_private(pri->pvts[chanpos]);
2629         sig_pri_span_devstate_changed(pri);
2630         pri_retrieve_ack(pri->pri, ev->retrieve.call,
2631                 PVT_TO_CHANNEL(pri->pvts[chanpos]));
2632 }
2633 #endif  /* defined(HAVE_PRI_CALL_HOLD) */
2634
2635 static void *pri_dchannel(void *vpri)
2636 {
2637         struct sig_pri_pri *pri = vpri;
2638         pri_event *e;
2639         struct pollfd fds[SIG_PRI_NUM_DCHANS];
2640         int res;
2641         int chanpos = 0;
2642         int x;
2643         struct ast_channel *c;
2644         struct timeval tv, lowest, *next;
2645         int doidling=0;
2646         char *cc;
2647         time_t t;
2648         int i, which=-1;
2649         int numdchans;
2650         pthread_t threadid;
2651         char ani2str[6];
2652         char plancallingnum[AST_MAX_EXTENSION];
2653         char plancallingani[AST_MAX_EXTENSION];
2654         char calledtonstr[10];
2655         struct timeval lastidle = { 0, 0 };
2656         pthread_t p;
2657         struct ast_channel *idle;
2658         char idlen[80];
2659         int nextidle = -1;
2660         int haveidles;
2661         int activeidles;
2662
2663         gettimeofday(&lastidle, NULL);
2664         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2665
2666         if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
2667                 /* Need to do idle dialing, check to be sure though */
2668                 cc = strchr(pri->idleext, '@');
2669                 if (cc) {
2670                         *cc = '\0';
2671                         cc++;
2672                         ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
2673 #if 0
2674                         /* Extensions may not be loaded yet */
2675                         if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
2676                                 ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
2677                         else
2678 #endif
2679                                 doidling = 1;
2680                 } else
2681                         ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
2682         }
2683         for (;;) {
2684                 for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
2685                         if (!pri->dchans[i])
2686                                 break;
2687                         fds[i].fd = pri->fds[i];
2688                         fds[i].events = POLLIN | POLLPRI;
2689                         fds[i].revents = 0;
2690                 }
2691                 numdchans = i;
2692                 time(&t);
2693                 ast_mutex_lock(&pri->lock);
2694                 if (pri->switchtype != PRI_SWITCH_GR303_TMC && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
2695                         if (pri->resetting && pri_is_up(pri)) {
2696                                 if (pri->resetpos < 0)
2697                                         pri_check_restart(pri);
2698                         } else {
2699                                 if (!pri->resetting     && (t - pri->lastreset) >= pri->resetinterval) {
2700                                         pri->resetting = 1;
2701                                         pri->resetpos = -1;
2702                                 }
2703                         }
2704                 }
2705                 /* Look for any idle channels if appropriate */
2706                 if (doidling && pri_is_up(pri)) {
2707                         nextidle = -1;
2708                         haveidles = 0;
2709                         activeidles = 0;
2710                         for (x = pri->numchans; x >= 0; x--) {
2711                                 if (pri->pvts[x]
2712                                         && !pri->pvts[x]->owner
2713                                         && !pri->pvts[x]->call
2714                                         && !pri->pvts[x]->no_b_channel) {
2715                                         if (haveidles < pri->minunused) {
2716                                                 haveidles++;
2717                                         } else if (!pri->pvts[x]->resetting) {
2718                                                 nextidle = x;
2719                                                 break;
2720                                         }
2721                                 } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
2722                                         activeidles++;
2723                         }
2724                         if (nextidle > -1) {
2725                                 if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
2726                                         /* Don't create a new idle call more than once per second */
2727                                         snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
2728                                         idle = sig_pri_request(pri->pvts[nextidle], AST_FORMAT_ULAW, NULL, 0);
2729                                         if (idle) {
2730                                                 pri->pvts[nextidle]->isidlecall = 1;
2731                                                 if (ast_pthread_create_background(&p, NULL, do_idle_thread, pri->pvts[nextidle])) {
2732                                                         ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
2733                                                         ast_hangup(idle);
2734                                                 }
2735                                         } else
2736                                                 ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
2737                                         gettimeofday(&lastidle, NULL);
2738                                 }
2739                         } else if ((haveidles < pri->minunused) &&
2740                                 (activeidles > pri->minidle)) {
2741                                 /* Mark something for hangup if there is something
2742                                    that can be hungup */
2743                                 for (x = pri->numchans; x >= 0; x--) {
2744                                         /* find a candidate channel */
2745                                         if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
2746                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2747                                                 haveidles++;
2748                                                 /* Stop if we have enough idle channels or
2749                                                   can't spare any more active idle ones */
2750                                                 if ((haveidles >= pri->minunused) ||
2751                                                         (activeidles <= pri->minidle))
2752                                                         break;
2753                                         }
2754                                 }
2755                         }
2756                 }
2757                 /* Start with reasonable max */
2758                 lowest = ast_tv(60, 0);
2759                 for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
2760                         /* Find lowest available d-channel */
2761                         if (!pri->dchans[i])
2762                                 break;
2763                         if ((next = pri_schedule_next(pri->dchans[i]))) {
2764                                 /* We need relative time here */
2765                                 tv = ast_tvsub(*next, ast_tvnow());
2766                                 if (tv.tv_sec < 0) {
2767                                         tv = ast_tv(0,0);
2768                                 }
2769                                 if (doidling || pri->resetting) {
2770                                         if (tv.tv_sec > 1) {
2771                                                 tv = ast_tv(1, 0);
2772                                         }
2773                                 } else {
2774                                         if (tv.tv_sec > 60) {
2775                                                 tv = ast_tv(60, 0);
2776                                         }
2777                                 }
2778                         } else if (doidling || pri->resetting) {
2779                                 /* Make sure we stop at least once per second if we're
2780                                    monitoring idle channels */
2781                                 tv = ast_tv(1,0);
2782                         } else {
2783                                 /* Don't poll for more than 60 seconds */
2784                                 tv = ast_tv(60, 0);
2785                         }
2786                         if (!i || ast_tvcmp(tv, lowest) < 0) {
2787                                 lowest = tv;
2788                         }
2789                 }
2790                 ast_mutex_unlock(&pri->lock);
2791
2792                 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
2793                 pthread_testcancel();
2794                 e = NULL;
2795                 res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
2796                 pthread_testcancel();
2797                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
2798
2799                 ast_mutex_lock(&pri->lock);
2800                 if (!res) {
2801                         for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
2802                                 if (!pri->dchans[which])
2803                                         break;
2804                                 /* Just a timeout, run the scheduler */
2805                                 e = pri_schedule_run(pri->dchans[which]);
2806                                 if (e)
2807                                         break;
2808                         }
2809                 } else if (res > -1) {
2810                         for (which = 0; which < SIG_PRI_NUM_DCHANS; which++) {
2811                                 if (!pri->dchans[which])
2812                                         break;
2813                                 if (fds[which].revents & POLLPRI) {
2814                                         sig_pri_handle_dchan_exception(pri, which);
2815                                 } else if (fds[which].revents & POLLIN) {
2816                                         e = pri_check_event(pri->dchans[which]);
2817                                 }
2818                                 if (e)
2819                                         break;
2820                         }
2821                 } else if (errno != EINTR)
2822                         ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
2823
2824                 if (e) {
2825                         if (pri->debug)
2826                                 pri_dump_event(pri->dchans[which], e);
2827
2828                         if (e->e != PRI_EVENT_DCHAN_DOWN) {
2829                                 if (!(pri->dchanavail[which] & DCHAN_UP)) {
2830                                         ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
2831                                 }
2832                                 pri->dchanavail[which] |= DCHAN_UP;
2833                         } else {
2834                                 if (pri->dchanavail[which] & DCHAN_UP) {
2835                                         ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
2836                                 }
2837                                 pri->dchanavail[which] &= ~DCHAN_UP;
2838                         }
2839
2840                         if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
2841                                 /* Must be an NFAS group that has the secondary dchan active */
2842                                 pri->pri = pri->dchans[which];
2843
2844                         switch (e->e) {
2845                         case PRI_EVENT_DCHAN_UP:
2846                                 if (!pri->pri) pri_find_dchan(pri);
2847
2848                                 /* Note presense of D-channel */
2849                                 time(&pri->lastreset);
2850
2851                                 /* Restart in 5 seconds */
2852                                 if (pri->resetinterval > -1) {
2853                                         pri->lastreset -= pri->resetinterval;
2854                                         pri->lastreset += 5;
2855                                 }
2856                                 pri->resetting = 0;
2857                                 /* Take the channels from inalarm condition */
2858                                 for (i = 0; i < pri->numchans; i++) {
2859                                         if (pri->pvts[i]) {
2860                                                 sig_pri_set_alarm(pri->pvts[i], 0);
2861                                         }
2862                                 }
2863                                 sig_pri_span_devstate_changed(pri);
2864                                 break;
2865                         case PRI_EVENT_DCHAN_DOWN:
2866                                 pri_find_dchan(pri);
2867                                 if (!pri_is_up(pri)) {
2868                                         pri->resetting = 0;
2869                                         if (pri->sig == SIG_BRI_PTMP) {
2870                                                 /* For PTMP connections with non persistent layer 2 we want
2871                                                  * to *not* declare inalarm unless there actually is an alarm */
2872                                                 break;
2873                                         }
2874                                         /* Hangup active channels and put them in alarm mode */
2875                                         for (i = 0; i < pri->numchans; i++) {
2876                                                 struct sig_pri_chan *p = pri->pvts[i];
2877                                                 if (p) {
2878                                                         if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
2879                                                                 /* T309 is not enabled : hangup calls when alarm occurs */
2880                                                                 if (p->call) {
2881                                                                         if (p->pri && p->pri->pri) {
2882                                                                                 pri_hangup(p->pri->pri, p->call, -1);
2883                                                                                 pri_destroycall(p->pri->pri, p->call);
2884                                                                                 p->call = NULL;
2885                                                                         } else
2886                                                                                 ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2887                                                                 }
2888                                                                 if (p->owner)
2889                                                                         p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2890                                                         }
2891                                                         sig_pri_set_alarm(p, 1);
2892                                                 }
2893                                         }
2894                                         sig_pri_span_devstate_changed(pri);
2895                                 }
2896                                 break;
2897                         case PRI_EVENT_RESTART:
2898                                 if (e->restart.channel > -1) {
2899                                         chanpos = pri_find_principle(pri, e->restart.channel, NULL);
2900                                         if (chanpos < 0)
2901                                                 ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
2902                                                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2903                                         else {
2904                                                 int skipit = 0;
2905 #if defined(HAVE_PRI_SERVICE_MESSAGES)
2906                                                 unsigned why;
2907
2908                                                 why = pri->pvts[chanpos]->service_status;
2909                                                 if (why) {
2910                                                         ast_log(LOG_NOTICE,
2911                                                                 "span '%d' channel '%d' out-of-service (reason: %s), ignoring RESTART\n",
2912                                                                 pri->span, PRI_CHANNEL(e->restart.channel),
2913                                                                 (why & SRVST_FAREND) ? (why & SRVST_NEAREND) ? "both ends" : "far end" : "near end");
2914                                                         skipit = 1;
2915                                                 }
2916 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
2917                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2918                                                 if (!skipit) {
2919                                                         ast_verb(3, "B-channel %d/%d restarted on span %d\n",
2920                                                                 PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
2921                                                         if (pri->pvts[chanpos]->call) {
2922                                                                 pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
2923                                                                 pri->pvts[chanpos]->call = NULL;
2924                                                         }
2925                                                 }
2926                                                 /* Force soft hangup if appropriate */
2927                                                 if (pri->pvts[chanpos]->owner)
2928                                                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2929                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2930                                         }
2931                                 } else {
2932                                         ast_verb(3, "Restart requested on entire span %d\n", pri->span);
2933                                         for (x = 0; x < pri->numchans; x++)
2934                                                 if (pri->pvts[x]) {
2935                                                         sig_pri_lock_private(pri->pvts[x]);
2936                                                         if (pri->pvts[x]->call) {
2937                                                                 pri_destroycall(pri->pri, pri->pvts[x]->call);
2938                                                                 pri->pvts[x]->call = NULL;
2939                                                         }
2940                                                         if (pri->pvts[x]->owner)
2941                                                                 pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2942                                                         sig_pri_unlock_private(pri->pvts[x]);
2943                                                 }
2944                                 }
2945                                 break;
2946                         case PRI_EVENT_KEYPAD_DIGIT:
2947                                 if (sig_pri_is_cis_call(e->digit.channel)) {
2948                                         sig_pri_handle_cis_subcmds(pri, e->e, e->digit.subcmds,
2949                                                 e->digit.call);
2950                                         break;
2951                                 }
2952                                 chanpos = pri_find_principle(pri, e->digit.channel, e->digit.call);
2953                                 if (chanpos < 0) {
2954                                         ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
2955                                                 PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
2956                                 } else {
2957                                         chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
2958                                         if (chanpos > -1) {
2959                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2960                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->digit.channel,
2961                                                         e->digit.subcmds, e->digit.call);
2962                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
2963                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2964                                                         && pri->pvts[chanpos]->call == e->digit.call
2965                                                         && pri->pvts[chanpos]->owner) {
2966                                                         /* how to do that */
2967                                                         int digitlen = strlen(e->digit.digits);
2968                                                         int i;
2969
2970                                                         for (i = 0; i < digitlen; i++) {
2971                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->digit.digits[i], };
2972
2973                                                                 pri_queue_frame(pri, chanpos, &f);
2974                                                         }
2975                                                 }
2976                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
2977                                         }
2978                                 }
2979                                 break;
2980
2981                         case PRI_EVENT_INFO_RECEIVED:
2982                                 if (sig_pri_is_cis_call(e->ring.channel)) {
2983                                         sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
2984                                                 e->ring.call);
2985                                         break;
2986                                 }
2987                                 chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
2988                                 if (chanpos < 0) {
2989                                         ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
2990                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
2991                                 } else {
2992                                         chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
2993                                         if (chanpos > -1) {
2994                                                 sig_pri_lock_private(pri->pvts[chanpos]);
2995                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
2996                                                         e->ring.subcmds, e->ring.call);
2997                                                 /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
2998                                                 if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
2999                                                         && pri->pvts[chanpos]->call == e->ring.call
3000                                                         && pri->pvts[chanpos]->owner) {
3001                                                         /* how to do that */
3002                                                         int digitlen = strlen(e->ring.callednum);
3003                                                         int i;
3004
3005                                                         for (i = 0; i < digitlen; i++) {
3006                                                                 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = e->ring.callednum[i], };
3007
3008                                                                 pri_queue_frame(pri, chanpos, &f);
3009                                                         }
3010                                                 }
3011                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
3012                                         }
3013                                 }
3014                                 break;
3015 #if defined(HAVE_PRI_SERVICE_MESSAGES)
3016                         case PRI_EVENT_SERVICE:
3017                                 chanpos = pri_find_principle(pri, e->service.channel, NULL);
3018                                 if (chanpos < 0) {
3019                                         ast_log(LOG_WARNING, "Received service change status %d on unconfigured channel %d/%d span %d\n",
3020                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
3021                                 } else {
3022                                         char db_chan_name[20];
3023                                         char db_answer[5];
3024                                         int ch;
3025                                         unsigned *why;
3026
3027                                         ch = pri->pvts[chanpos]->channel;
3028                                         snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, pri->span, ch);
3029                                         why = &pri->pvts[chanpos]->service_status;
3030                                         switch (e->service.changestatus) {
3031                                         case 0: /* in-service */
3032                                                 /* Far end wants to be in service now. */
3033                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
3034                                                 *why &= ~SRVST_FAREND;
3035                                                 if (*why) {
3036                                                         snprintf(db_answer, sizeof(db_answer), "%s:%u",
3037                                                                 SRVST_TYPE_OOS, *why);
3038                                                         ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
3039                                                 } else {
3040                                                         sig_pri_span_devstate_changed(pri);
3041                                                 }
3042                                                 break;
3043                                         case 2: /* out-of-service */
3044                                                 /* Far end wants to be out-of-service now. */
3045                                                 ast_db_del(db_chan_name, SRVST_DBKEY);
3046                                                 *why |= SRVST_FAREND;
3047                                                 snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS,
3048                                                         *why);
3049                                                 ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
3050                                                 sig_pri_span_devstate_changed(pri);
3051                                                 break;
3052                                         default:
3053                                                 ast_log(LOG_ERROR, "Huh?  changestatus is: %d\n", e->service.changestatus);
3054                                                 break;
3055                                         }
3056                                         ast_log(LOG_NOTICE, "Channel %d/%d span %d (logical: %d) received a change of service message, status '%d'\n",
3057                                                 PRI_SPAN(e->service.channel), PRI_CHANNEL(e->service.channel), pri->span, ch, e->service.changestatus);
3058                                 }
3059                                 break;
3060                         case PRI_EVENT_SERVICE_ACK:
3061                                 chanpos = pri_find_principle(pri, e->service_ack.channel, NULL);
3062                                 if (chanpos < 0) {
3063                                         ast_log(LOG_WARNING, "Received service acknowledge change status '%d' on unconfigured channel %d/%d span %d\n",
3064                                                 e->service_ack.changestatus, PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span);
3065                                 } else {
3066                                         ast_debug(2, "Channel %d/%d span %d received a change os service acknowledgement message, status '%d'\n",
3067                                                 PRI_SPAN(e->service_ack.channel), PRI_CHANNEL(e->service_ack.channel), pri->span, e->service_ack.changestatus);
3068                                 }
3069                                 break;
3070 #endif  /* defined(HAVE_PRI_SERVICE_MESSAGES) */
3071                         case PRI_EVENT_RING:
3072                                 if (!ast_strlen_zero(pri->msn_list)
3073                                         && !sig_pri_msn_match(pri->msn_list, e->ring.callednum)) {
3074                                         /* The call is not for us so ignore it. */
3075                                         ast_verb(3,
3076                                                 "Ignoring call to '%s' on span %d.  Its not in the MSN list: %s\n",
3077                                                 e->ring.callednum, pri->span, pri->msn_list);
3078                                         pri_destroycall(pri->pri, e->ring.call);
3079                                         break;
3080                                 }
3081                                 if (sig_pri_is_cis_call(e->ring.channel)) {
3082                                         sig_pri_handle_cis_subcmds(pri, e->e, e->ring.subcmds,
3083                                                 e->ring.call);
3084                                         break;
3085                                 }
3086                                 if (e->ring.channel == -1 || PRI_CHANNEL(e->ring.channel) == 0xFF)
3087                                         chanpos = pri_find_empty_chan(pri, 1);
3088                                 else
3089                                         chanpos = pri_find_principle(pri, e->ring.channel, e->ring.call);
3090                                 /* if no channel specified find one empty */
3091                                 if (chanpos < 0) {
3092                                         ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
3093                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
3094                                 } else {
3095                                         sig_pri_lock_private(pri->pvts[chanpos]);
3096                                         if (pri->pvts[chanpos]->owner) {
3097                                                 if (pri->pvts[chanpos]->call == e->ring.call) {
3098                                                         ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
3099                                                                 PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
3100                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
3101                                                         break;
3102                                                 } else {
3103                                                         /* This is where we handle initial glare */
3104                                                         ast_debug(1, "Ring requested on channel %d/%d already in use or previously requested on span %d.  Attempting to renegotiating channel.\n",
3105                                                         PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
3106                                                         sig_pri_unlock_private(pri->pvts[chanpos]);
3107                                                         chanpos = -1;
3108                                                 }
3109                                         }
3110                                         if (chanpos > -1)
3111                                                 sig_pri_unlock_private(pri->pvts[chanpos]);
3112                                 }
3113                                 if ((chanpos < 0) && (e->ring.flexible))
3114                                         chanpos = pri_find_empty_chan(pri, 1);
3115                                 if (chanpos > -1) {
3116                                         sig_pri_lock_private(pri->pvts[chanpos]);
3117                                         pri->pvts[chanpos]->call = e->ring.call;
3118
3119                                         /* Use plancallingnum as a scratch buffer since it is initialized next. */
3120                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri,
3121                                                 e->ring.redirectingnum, e->ring.callingplanrdnis);
3122                                         sig_pri_set_rdnis(pri->pvts[chanpos], plancallingnum);
3123
3124                                         /* Setup caller-id info */
3125                                         apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
3126                                         pri->pvts[chanpos]->cid_ani2 = 0;
3127                                         if (pri->pvts[chanpos]->use_callerid) {
3128                                                 ast_shrink_phone_number(plancallingnum);
3129                                                 ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
3130 #ifdef PRI_ANI
3131                                                 if (!ast_strlen_zero(e->ring.callingani)) {
3132                                                         apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
3133                                                         ast_shrink_phone_number(plancallingani);
3134                                                         ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
3135                                                 } else {
3136                                                         pri->pvts[chanpos]->cid_ani[0] = '\0';
3137                                                 }
3138 #endif
3139                                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
3140 #if defined(HAVE_PRI_SUBADDR)
3141                                                 if (e->ring.calling.subaddress.valid) {
3142                                                         struct ast_party_subaddress calling_subaddress;
3143
3144                                                         ast_party_subaddress_init(&calling_subaddress);
3145                                                         sig_pri_set_subaddress(&calling_subaddress,
3146                                                                 &e->ring.calling.subaddress);
3147                                                         if (calling_subaddress.str) {
3148                                                                 ast_copy_string(pri->pvts[chanpos]->cid_subaddr,
3149                                                                         calling_subaddress.str,
3150                                                                         sizeof(pri->pvts[chanpos]->cid_subaddr));
3151                                                         }
3152                                                         ast_party_subaddress_free(&calling_subaddress);
3153                                                 }
3154 #endif /* defined(HAVE_PRI_SUBADDR) */
3155                                                 ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
3156                                                 pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
3157                                                 pri->pvts[chanpos]->callingpres = e->ring.callingpres;
3158                                                 if (e->ring.ani2 >= 0) {
3159                                                         pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
3160                                                 }
3161                                         } else {
3162                                                 pri->pvts[chanpos]->cid_num[0] = '\0';
3163                                                 pri->pvts[chanpos]->cid_subaddr[0] = '\0';
3164                                                 pri->pvts[chanpos]->cid_ani[0] = '\0';
3165                                                 pri->pvts[chanpos]->cid_name[0] = '\0';
3166                                                 pri->pvts[chanpos]->cid_ton = 0;
3167                                                 pri->pvts[chanpos]->callingpres = 0;
3168                                         }
3169                                         sig_pri_set_caller_id(pri->pvts[chanpos]);
3170
3171                                         /* Set DNID on all incoming calls -- even immediate */
3172                                         sig_pri_set_dnid(pri->pvts[chanpos], e->ring.callednum);
3173
3174                                         /* If immediate=yes go to s|1 */
3175                                         if (pri->pvts[chanpos]->immediate) {
3176                                                 ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
3177                                                 pri->pvts[chanpos]->exten[0] = 's';
3178                                                 pri->pvts[chanpos]->exten[1] = '\0';
3179                                         }
3180                                         /* Get called number */
3181                                         else if (!ast_strlen_zero(e->ring.callednum)) {
3182                                                 ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
3183                                         } else if (pri->overlapdial)
3184                                                 pri->pvts[chanpos]->exten[0] = '\0';
3185                                         else {
3186                                                 /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
3187                                                 pri->pvts[chanpos]->exten[0] = 's';
3188                                                 pri->pvts[chanpos]->exten[1] = '\0';
3189                                         }
3190                                         /* No number yet, but received "sending complete"? */
3191                                         if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
3192                                                 ast_verb(3, "Going to extension s|1 because of Complete received\n");
3193                                                 pri->pvts[chanpos]->exten[0] = 's';
3194                                                 pri->pvts[chanpos]->exten[1] = '\0';
3195                                         }
3196
3197                                         /* Make sure extension exists (or in overlap dial mode, can exist) */
3198                                         if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
3199                                                 ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
3200                                                 /* Setup law */
3201                                                 if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
3202                                                         /* Just announce proceeding */
3203                                                         pri->pvts[chanpos]->proceeding = 1;
3204                                                         pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
3205                                                 } else {
3206                                                         if (pri->switchtype != PRI_SWITCH_GR303_TMC)
3207                                                                 pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
3208                                                         else
3209                                                                 pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
3210                                                 }
3211
3212                                                 /* Start PBX */
3213                                                 if (!e->ring.complete
3214                                                         && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
3215                                                         && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
3216                                                         /*
3217                                                          * Release the PRI lock while we create the channel
3218                                                          * so other threads can send D channel messages.
3219                                                          */
3220                                                         ast_mutex_unlock(&pri->lock);
3221                                                         c = sig_pri_new_ast_channel(pri->pvts[chanpos],
3222                                                                 AST_STATE_RESERVED, 0,
3223                                                                 (e->ring.layer1 == PRI_LAYER_1_ALAW)
3224                                                                         ? SIG_PRI_ALAW : SIG_PRI_ULAW,
3225                                                                 e->ring.ctype, pri->pvts[chanpos]->exten, NULL);
3226                                                         ast_mutex_lock(&pri->lock);
3227                                                         if (c) {
3228 #if defined(HAVE_PRI_SUBADDR)
3229                                                                 if (e->ring.calling.subaddress.valid) {
3230                                                                         /* Set Calling Subaddress */
3231                                                                         sig_pri_lock_owner(pri, chanpos);
3232                                                                         sig_pri_set_subaddress(
3233                                                                                 &pri->pvts[chanpos]->owner->cid.subaddress,
3234                                                                                 &e->ring.calling.subaddress);
3235                                                                         if (!e->ring.calling.subaddress.type
3236                                                                                 && !ast_strlen_zero(
3237                                                                                         (char *) e->ring.calling.subaddress.data)) {
3238                                                                                 /* NSAP */
3239                                                                                 pbx_builtin_setvar_helper(c, "CALLINGSUBADDR",
3240                                                                                         (char *) e->ring.calling.subaddress.data);
3241                                                                         }
3242                                                                         ast_channel_unlock(c);
3243                                                                 }
3244                                                                 if (e->ring.called_subaddress.valid) {
3245                                                                         /* Set Called Subaddress */
3246                                                                         sig_pri_lock_owner(pri, chanpos);
3247                                                                         sig_pri_set_subaddress(
3248                                                                                 &pri->pvts[chanpos]->owner->cid.dialed_subaddress,
3249                                                                                 &e->ring.called_subaddress);
3250                                                                         if (!e->ring.called_subaddress.type
3251                                                                                 && !ast_strlen_zero(
3252                                                                                         (char *) e->ring.called_subaddress.data)) {
3253                                                                                 /* NSAP */
3254                                                                                 pbx_builtin_setvar_helper(c, "CALLEDSUBADDR",
3255                                                                                         (char *) e->ring.called_subaddress.data);
3256                                                                         }
3257                                                                         ast_channel_unlock(c);
3258                                                                 }
3259 #else
3260                                                                 if (!ast_strlen_zero(e->ring.callingsubaddr)) {
3261                                                                         pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
3262                                                                 }
3263 #endif /* !defined(HAVE_PRI_SUBADDR) */
3264                                                                 if (e->ring.ani2 >= 0) {
3265                                                                         snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
3266                                                                         pbx_builtin_setvar_helper(c, "ANI2", ani2str);
3267                                                                 }
3268
3269 #ifdef SUPPORT_USERUSER
3270                                                                 if (!ast_strlen_zero(e->ring.useruserinfo)) {
3271                                                                         pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
3272                                                                 }
3273 #endif
3274
3275                                                                 snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
3276                                                                 pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
3277                                                                 if (e->ring.redirectingreason >= 0) {
3278                                                                         /* This is now just a status variable.  Use REDIRECTING() dialplan function. */
3279                                                                         pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
3280                                                                 }
3281 #if defined(HAVE_PRI_REVERSE_CHARGE)
3282                                                                 pri->pvts[chanpos]->reverse_charging_indication = e->ring.reversecharge;
3283 #endif
3284 #if defined(HAVE_PRI_SETUP_KEYPAD)
3285                                                                 ast_copy_string(pri->pvts[chanpos]->keypad_digits,
3286                                                                         e->ring.keypad_digits,
3287                                                                         sizeof(pri->pvts[chanpos]->keypad_digits));
3288 #endif  /* defined(HAVE_PRI_SETUP_KEYPAD) */
3289
3290                                                                 sig_pri_handle_subcmds(pri, chanpos, e->e, e->ring.channel,
3291                                                                         e->ring.subcmds, e->ring.call);
3292
3293                                                         }
3294                                                         if (c && !ast_pthread_create_detached(&threadid, NULL, pri_ss_thread, pri->pvts[chanpos])) {
3295                                                                 ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
3296                                                                         plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
3297